50ed6012ff93a5d481f16450ae1453f40bdcbd11
[quicknote] / src / quicknote_gtk.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5  Copyright (C) 2007 Christoph W├╝rstle
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 @todo Add Note Export (txt File) and Export All (json dump?)
12 @todo Remove confirmation on deleting empty notes
13 @todo Try to switch to more passive notifications (rather than message boxes)
14 """
15
16 from __future__ import with_statement
17
18 import os
19 import gc
20 import logging
21 import warnings
22 import ConfigParser
23
24 import gtk
25
26 try:
27         import hildon
28 except ImportError:
29         import fakehildon as hildon
30
31 try:
32         import osso
33 except ImportError:
34         osso = None
35
36 import constants
37 import hildonize
38 import gtk_toolbox
39
40 import speichern
41 import kopfzeile
42 import notizen
43 import search
44 import sync
45
46
47 try:
48         _
49 except NameError:
50         _ = lambda x: x
51
52
53 _moduleLogger = logging.getLogger("quicknote_gtk")
54
55
56 class QuicknoteProgram(hildonize.get_app_class()):
57
58         _user_data = os.path.join(os.path.expanduser("~"), ".%s" % constants.__app_name__)
59         _user_settings = "%s/settings.ini" % _user_data
60
61         def __init__(self):
62                 super(QuicknoteProgram, self).__init__()
63                 self._clipboard = gtk.clipboard_get()
64
65                 dblog = os.path.join(self._user_data, "quicknote.log")
66
67                 _moduleLogger.info('Starting quicknote')
68                 self._wordWrapEnabled = False
69
70                 self._window_in_fullscreen = False #The window isn't in full screen mode initially.
71
72                 self._db = speichern.Speichern()
73                 self._syncDialog = None
74
75                 #Create GUI main vbox
76                 vbox = gtk.VBox(homogeneous = False, spacing = 0)
77
78                 if hildonize.GTK_MENU_USED:
79                         #Create Menu and apply it for hildon
80                         filemenu = gtk.Menu()
81
82                         menu_items = gtk.MenuItem(_("Set DB file"))
83                         filemenu.append(menu_items)
84                         menu_items.connect("activate", self.set_db_file, None)
85
86                         menu_items = gtk.MenuItem(_("SQL History"))
87                         filemenu.append(menu_items)
88                         menu_items.connect("activate", self._on_view_sql_history, None)
89
90                         menu_items = gtk.MenuItem(_("Sync notes"))
91                         filemenu.append(menu_items)
92                         menu_items.connect("activate", self._on_sync_notes, None)
93
94                         menu_items = gtk.MenuItem(_("Quit"))
95                         filemenu.append(menu_items)
96                         menu_items.connect("activate", self._on_destroy, None)
97
98                         file_menu = gtk.MenuItem(_("File"))
99                         file_menu.show()
100                         file_menu.set_submenu(filemenu)
101
102                         categorymenu = gtk.Menu()
103
104                         menu_items = gtk.MenuItem(_("Search"))
105                         categorymenu.append(menu_items)
106                         menu_items.connect("activate", self._on_toggle_search)
107
108                         menu_items = gtk.MenuItem(_("Delete"))
109                         categorymenu.append(menu_items)
110                         menu_items.connect("activate", self._on_delete_category)
111
112                         category_menu = gtk.MenuItem(_("Category"))
113                         category_menu.show()
114                         category_menu.set_submenu(categorymenu)
115
116                         viewmenu = gtk.Menu()
117
118                         menu_items = gtk.MenuItem(_("Move To Category"))
119                         viewmenu.append(menu_items)
120                         menu_items.connect("activate", self._on_move_category)
121
122                         menu_items = gtk.MenuItem(_("History"))
123                         viewmenu.append(menu_items)
124                         menu_items.connect("activate", self._on_show_history)
125
126                         menu_items = gtk.MenuItem(_("Word Wrap"))
127                         viewmenu.append(menu_items)
128                         menu_items.connect("activate", self._on_toggle_word_wrap)
129
130                         view_menu = gtk.MenuItem(_("Note"))
131                         view_menu.show()
132                         view_menu.set_submenu(viewmenu)
133
134                         helpmenu = gtk.Menu()
135
136                         menu_items = gtk.MenuItem(_("About"))
137                         helpmenu.append(menu_items)
138                         menu_items.connect("activate", self._on_show_about, None)
139
140                         help_menu = gtk.MenuItem(_("Help"))
141                         help_menu.show()
142                         help_menu.set_submenu(helpmenu)
143
144                         menuBar = gtk.MenuBar()
145                         menuBar.show()
146                         menuBar.append (file_menu)
147                         menuBar.append (category_menu)
148                         menuBar.append (view_menu)
149                         menuBar.append (help_menu)
150
151                         vbox.pack_start(menuBar, False, False, 0)
152                 else:
153                         menuBar = gtk.MenuBar()
154                         menuBar.show()
155                         vbox.pack_start(menuBar, False, False, 0)
156
157                 #Create GUI elements
158                 self._category = kopfzeile.Kopfzeile(self._db)
159                 self._search = search.Search()
160                 self._notizen = notizen.Notizen(self._db, self._category, self._search)
161
162                 # notizen packs in the category
163                 vbox.pack_start(self._notizen, expand = True, fill = True)
164                 vbox.pack_start(self._search, expand = False, fill = True)
165
166                 #Get the Main Window, and connect the "destroy" event
167                 self._window = gtk.Window()
168                 self._window.add(vbox)
169
170                 self._on_toggle_word_wrap()
171
172                 try:
173                         os.makedirs(self._user_data)
174                 except OSError, e:
175                         if e.errno != 17:
176                                 raise
177
178                 self._window = hildonize.hildonize_window(self, self._window)
179                 hildonize.set_application_title(self._window, "%s" % constants.__pretty_app_name__)
180                 menuBar = hildonize.hildonize_menu(
181                         self._window,
182                         menuBar,
183                 )
184                 if hildonize.IS_FREMANTLE_SUPPORTED:
185                         moveToCategoryButton = gtk.Button(_("Move Note"))
186                         moveToCategoryButton.connect("clicked", self._on_move_category)
187                         menuBar.append(moveToCategoryButton)
188
189                         historyButton= gtk.Button(_("Note History"))
190                         historyButton.connect("clicked", self._on_show_history)
191                         menuBar.append(historyButton)
192
193                         searchButton= gtk.Button(_("Search Category"))
194                         searchButton.connect("clicked", self._on_toggle_search)
195                         menuBar.append(searchButton)
196
197                         deleteCategoryButton = gtk.Button(_("Delete Category"))
198                         deleteCategoryButton.connect("clicked", self._on_delete_category)
199                         menuBar.append(deleteCategoryButton)
200
201                         menuBar.show_all()
202
203                 if not hildonize.IS_HILDON_SUPPORTED:
204                         _moduleLogger.info("No hildonization support")
205
206                 if osso is not None:
207                         self._osso_c = osso.Context(constants.__app_name__, constants.__version__, False)
208                         self._deviceState = osso.DeviceState(self._osso_c)
209                         self._deviceState.set_device_state_callback(self._on_device_state_change, 0)
210                 else:
211                         _moduleLogger.info("No osso support")
212                         self._osso_c = None
213                         self._deviceState = None
214
215                 self._prepare_sync_dialog()
216
217                 self._window.connect("delete-event", self._on_delete_event)
218                 self._window.connect("destroy", self._on_destroy)
219                 self._window.connect("key-press-event", self._on_key_press)
220                 self._window.connect("window-state-event", self._on_window_state_change)
221
222                 self._window.show_all()
223                 self._search.hide()
224                 self._load_settings()
225
226         def _save_settings(self):
227                 config = ConfigParser.SafeConfigParser()
228                 self.save_settings(config)
229                 with open(self._user_settings, "wb") as configFile:
230                         config.write(configFile)
231
232         def save_settings(self, config):
233                 config.add_section(constants.__pretty_app_name__)
234                 config.set(constants.__pretty_app_name__, "wordwrap", str(self._wordWrapEnabled))
235                 config.set(constants.__pretty_app_name__, "fullscreen", str(self._window_in_fullscreen))
236
237         def _load_settings(self):
238                 config = ConfigParser.SafeConfigParser()
239                 config.read(self._user_settings)
240                 self.load_settings(config)
241
242         def load_settings(self, config):
243                 try:
244                         self._wordWrapEnabled = config.getboolean(constants.__pretty_app_name__, "wordwrap")
245                         self._window_in_fullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
246                 except ConfigParser.NoSectionError, e:
247                         warnings.warn(
248                                 "Settings file %s is missing section %s" % (
249                                         self._user_settings,
250                                         e.section,
251                                 ),
252                                 stacklevel=2
253                         )
254
255                 self._notizen.set_wordwrap(self._wordWrapEnabled)
256
257                 if self._window_in_fullscreen:
258                         self._window.fullscreen()
259                 else:
260                         self._window.unfullscreen()
261
262         def set_db_file(self, widget = None, data = None):
263                 dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
264
265                 if self._db.ladeDirekt('datenbank'):
266                         dlg.set_filename(self._db.ladeDirekt('datenbank'))
267
268                 dlg.set_title(_("Choose database file"))
269                 if dlg.run() == gtk.RESPONSE_OK:
270                         fileName = dlg.get_filename()
271                         self._db.speichereDirekt('datenbank', fileName)
272
273                         self._db.openDB()
274                         self._category.load_categories()
275                         self._notizen.load_notes()
276                 dlg.destroy()
277
278         def _prepare_sync_dialog(self):
279                 self._syncDialog = gtk.Dialog(_("Sync"), None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
280
281                 self._syncDialog.set_position(gtk.WIN_POS_CENTER)
282                 syncer = sync.Sync(self._db, self._window, 50504)
283                 self._syncDialog.vbox.pack_start(syncer, True, True, 0)
284                 self._syncDialog.set_size_request(500, 350)
285                 self._syncDialog.vbox.show_all()
286                 syncer.connect("syncFinished", self._on_sync_finished)
287
288         def _toggle_search(self):
289                 if self._search.get_property("visible"):
290                         self._search.hide()
291                 else:
292                         self._search.show()
293
294         @gtk_toolbox.log_exception(_moduleLogger)
295         def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
296                 """
297                 For system_inactivity, we have no background tasks to pause
298
299                 @note Hildon specific
300                 """
301                 if memory_low:
302                         gc.collect()
303
304                 if save_unsaved_data or shutdown:
305                         self._save_settings()
306
307         @gtk_toolbox.log_exception(_moduleLogger)
308         def _on_window_state_change(self, widget, event, *args):
309                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
310                         self._window_in_fullscreen = True
311                 else:
312                         self._window_in_fullscreen = False
313
314         @gtk_toolbox.log_exception(_moduleLogger)
315         def _on_key_press(self, widget, event, *args):
316                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
317                 isCtrl = bool(event.get_state() & gtk.gdk.CONTROL_MASK)
318                 if (
319                         event.keyval == gtk.keysyms.F6 or
320                         event.keyval in RETURN_TYPES and isCtrl
321                 ):
322                         # The "Full screen" hardware key has been pressed 
323                         if self._window_in_fullscreen:
324                                 self._window.unfullscreen ()
325                         else:
326                                 self._window.fullscreen ()
327                         return True
328                 elif event.keyval == gtk.keysyms.f and isCtrl:
329                         self._toggle_search()
330                         return True
331                 elif (
332                         event.keyval in (gtk.keysyms.w, gtk.keysyms.q) and
333                         event.get_state() & gtk.gdk.CONTROL_MASK
334                 ):
335                         self._window.destroy()
336                 elif event.keyval == gtk.keysyms.l and event.get_state() & gtk.gdk.CONTROL_MASK:
337                         with open(constants._user_logpath_, "r") as f:
338                                 logLines = f.xreadlines()
339                                 log = "".join(logLines)
340                                 self._clipboard.set_text(str(log))
341                         return True
342
343         def _on_toggle_search(self, *args):
344                 self._toggle_search()
345
346         @gtk_toolbox.log_exception(_moduleLogger)
347         def _on_show_history(self, *args):
348                 self._notizen.show_history()
349
350         @gtk_toolbox.log_exception(_moduleLogger)
351         def _on_view_sql_history(self, widget = None, data = None, data2 = None):
352                 import sqldialog
353                 sqldiag = sqldialog.SqlDialog(self._db)
354                 res = sqldiag.run()
355                 sqldiag.hide()
356                 if res == sqldiag.EXPORT_RESPONSE:
357                         _moduleLogger.info("exporting sql")
358
359                         dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
360
361                         dlg.set_title(_("Select SQL export file"))
362                         if dlg.run() == gtk.RESPONSE_OK:
363                                 fileName = dlg.get_filename()
364                                 sqldiag.exportSQL(fileName)
365                         dlg.destroy()
366
367                 sqldiag.destroy()
368
369         @gtk_toolbox.log_exception(_moduleLogger)
370         def _on_move_category(self, *args):
371                 if self._notizen.noteId == -1:
372                         mbox = gtk.MessageDialog(self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("No note selected."))
373                         try:
374                                 response = mbox.run()
375                         finally:
376                                 mbox.hide()
377                                 mbox.destroy()
378                         return
379
380                 sql = "SELECT id, liste FROM categories WHERE id = 0 ORDER BY liste"
381                 rows = self._db.ladeSQL(sql)
382
383                 selectableCategories = [row[1] for row in rows]
384                 selectableCategories[0:0] = [self._category.UNDEFINED_CATEGORY]
385
386                 newIndex = hildonize.touch_selector(self._window, "Move to", selectableCategories, 0)
387                 cat_id = selectableCategories[newIndex]
388
389                 noteid, pcdatum, category, note = self._db.loadNote(self._notizen.noteId)
390                 self._db.saveNote(noteid, note, cat_id, pcdatum = None)
391                 self._category.set_category() # force it to update
392
393         @gtk_toolbox.log_exception(_moduleLogger)
394         def _on_delete_category(self, *args):
395                 if self._category.get_category() == "%" or self._category.get_category() == "undefined":
396                         mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("This category can not be deleted"))
397                         try:
398                                 response = mbox.run()
399                         finally:
400                                 mbox.hide()
401                                 mbox.destroy()
402                         return
403
404                 mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, _("Are you sure to delete the current category?"))
405                 try:
406                         response = mbox.run()
407                 finally:
408                         mbox.hide()
409                         mbox.destroy()
410                 if response == gtk.RESPONSE_YES:
411                         self._category.delete_this_category()
412
413         @gtk_toolbox.log_exception(_moduleLogger)
414         def _on_sync_finished(self, data = None, data2 = None):
415                 self._category.load_categories()
416                 self._notizen.load_notes()
417
418         @gtk_toolbox.log_exception(_moduleLogger)
419         def _on_sync_notes(self, widget = None, data = None):
420                 self._syncDialog.run()
421                 self._syncDialog.hide()
422
423         @gtk_toolbox.log_exception(_moduleLogger)
424         def _on_toggle_word_wrap(self, *args):
425                 self._wordWrapEnabled = not self._wordWrapEnabled
426                 self._notizen.set_wordwrap(self._wordWrapEnabled)
427
428         @gtk_toolbox.log_exception(_moduleLogger)
429         def _on_delete_event(self, widget, event, data = None):
430                 return False
431
432         @gtk_toolbox.log_exception(_moduleLogger)
433         def _on_destroy(self, widget = None, data = None):
434                 try:
435                         self._db.close()
436                         self._save_settings()
437
438                         try:
439                                 self._deviceState.close()
440                         except AttributeError:
441                                 pass # Either None or close was removed (in Fremantle)
442                         try:
443                                 self._osso_c.close()
444                         except AttributeError:
445                                 pass # Either None or close was removed (in Fremantle)
446                 finally:
447                         gtk.main_quit()
448
449         @gtk_toolbox.log_exception(_moduleLogger)
450         def _on_show_about(self, widget = None, data = None):
451                 dialog = gtk.AboutDialog()
452                 dialog.set_position(gtk.WIN_POS_CENTER)
453                 dialog.set_name(constants.__pretty_app_name__)
454                 dialog.set_version(constants.__version__)
455                 dialog.set_copyright("")
456                 dialog.set_website("http://axique.de/index.php?f=Quicknote")
457                 comments = _("%s is a note taking program; it is optimised for quick save and search of notes") % constants.__pretty_app_name__
458                 dialog.set_comments(comments)
459                 dialog.set_authors(["Christoph Wurstle <n800@axique.net>", "Ed Page <eopage@byu.net> (Blame him for the most recent bugs)"])
460                 dialog.run()
461                 dialog.destroy()
462
463
464 def run_quicknote():
465         if hildonize.IS_HILDON_SUPPORTED:
466                 gtk.set_application_name(constants.__pretty_app_name__)
467         app = QuicknoteProgram()
468         gtk.main()
469
470
471 if __name__ == "__main__":
472         logging.basicConfig(level=logging.DEBUG)
473         run_quicknote()