02cc124d0826428195122f855b532efc43671f16
[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 PROFILE_STARTUP = False
55
56
57 class QuicknoteProgram(hildonize.get_app_class()):
58
59         _user_data = os.path.join(os.path.expanduser("~"), ".%s" % constants.__app_name__)
60         _user_settings = "%s/settings.ini" % _user_data
61
62         def __init__(self):
63                 super(QuicknoteProgram, self).__init__()
64                 self._clipboard = gtk.clipboard_get()
65
66                 dblog = os.path.join(self._user_data, "quicknote.log")
67
68                 _moduleLogger.info('Starting quicknote')
69                 self._wordWrapEnabled = False
70
71                 self._window_in_fullscreen = False #The window isn't in full screen mode initially.
72
73                 self._db = speichern.Speichern()
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._window.connect("delete-event", self._on_delete_event)
216                 self._window.connect("destroy", self._on_destroy)
217                 self._window.connect("key-press-event", self._on_key_press)
218                 self._window.connect("window-state-event", self._on_window_state_change)
219
220                 self._window.show_all()
221                 self._search.hide()
222                 self._load_settings()
223
224         def _save_settings(self):
225                 config = ConfigParser.SafeConfigParser()
226                 self.save_settings(config)
227                 with open(self._user_settings, "wb") as configFile:
228                         config.write(configFile)
229
230         def save_settings(self, config):
231                 config.add_section(constants.__pretty_app_name__)
232                 config.set(constants.__pretty_app_name__, "wordwrap", str(self._wordWrapEnabled))
233                 config.set(constants.__pretty_app_name__, "fullscreen", str(self._window_in_fullscreen))
234
235         def _load_settings(self):
236                 config = ConfigParser.SafeConfigParser()
237                 config.read(self._user_settings)
238                 self.load_settings(config)
239
240         def load_settings(self, config):
241                 try:
242                         self._wordWrapEnabled = config.getboolean(constants.__pretty_app_name__, "wordwrap")
243                         self._window_in_fullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
244                 except ConfigParser.NoSectionError, e:
245                         warnings.warn(
246                                 "Settings file %s is missing section %s" % (
247                                         self._user_settings,
248                                         e.section,
249                                 ),
250                                 stacklevel=2
251                         )
252
253                 self._notizen.set_wordwrap(self._wordWrapEnabled)
254
255                 if self._window_in_fullscreen:
256                         self._window.fullscreen()
257                 else:
258                         self._window.unfullscreen()
259
260         def set_db_file(self, widget = None, data = None):
261                 dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
262
263                 if self._db.ladeDirekt('datenbank'):
264                         dlg.set_filename(self._db.ladeDirekt('datenbank'))
265
266                 dlg.set_title(_("Choose database file"))
267                 if dlg.run() == gtk.RESPONSE_OK:
268                         fileName = dlg.get_filename()
269                         self._db.speichereDirekt('datenbank', fileName)
270
271                         self._db.openDB()
272                         self._category.load_categories()
273                         self._notizen.load_notes()
274                 dlg.destroy()
275
276         def _toggle_search(self):
277                 if self._search.get_property("visible"):
278                         self._search.hide()
279                 else:
280                         self._search.show()
281
282         @gtk_toolbox.log_exception(_moduleLogger)
283         def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
284                 """
285                 For system_inactivity, we have no background tasks to pause
286
287                 @note Hildon specific
288                 """
289                 if memory_low:
290                         gc.collect()
291
292                 if save_unsaved_data or shutdown:
293                         self._save_settings()
294
295         @gtk_toolbox.log_exception(_moduleLogger)
296         def _on_window_state_change(self, widget, event, *args):
297                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
298                         self._window_in_fullscreen = True
299                 else:
300                         self._window_in_fullscreen = False
301
302         @gtk_toolbox.log_exception(_moduleLogger)
303         def _on_key_press(self, widget, event, *args):
304                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
305                 isCtrl = bool(event.get_state() & gtk.gdk.CONTROL_MASK)
306                 if (
307                         event.keyval == gtk.keysyms.F6 or
308                         event.keyval in RETURN_TYPES and isCtrl
309                 ):
310                         # The "Full screen" hardware key has been pressed 
311                         if self._window_in_fullscreen:
312                                 self._window.unfullscreen ()
313                         else:
314                                 self._window.fullscreen ()
315                         return True
316                 elif event.keyval == gtk.keysyms.f and isCtrl:
317                         self._toggle_search()
318                         return True
319                 elif (
320                         event.keyval in (gtk.keysyms.w, gtk.keysyms.q) and
321                         event.get_state() & gtk.gdk.CONTROL_MASK
322                 ):
323                         self._window.destroy()
324                 elif event.keyval == gtk.keysyms.l and event.get_state() & gtk.gdk.CONTROL_MASK:
325                         with open(constants._user_logpath_, "r") as f:
326                                 logLines = f.xreadlines()
327                                 log = "".join(logLines)
328                                 self._clipboard.set_text(str(log))
329                         return True
330
331         def _on_toggle_search(self, *args):
332                 self._toggle_search()
333
334         @gtk_toolbox.log_exception(_moduleLogger)
335         def _on_show_history(self, *args):
336                 self._notizen.show_history()
337
338         @gtk_toolbox.log_exception(_moduleLogger)
339         def _on_view_sql_history(self, widget = None, data = None, data2 = None):
340                 import sqldialog
341                 sqldiag = sqldialog.SqlDialog(self._db)
342                 res = sqldiag.run()
343                 sqldiag.hide()
344                 if res == sqldiag.EXPORT_RESPONSE:
345                         _moduleLogger.info("exporting sql")
346
347                         dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
348
349                         dlg.set_title(_("Select SQL export file"))
350                         if dlg.run() == gtk.RESPONSE_OK:
351                                 fileName = dlg.get_filename()
352                                 sqldiag.exportSQL(fileName)
353                         dlg.destroy()
354
355                 sqldiag.destroy()
356
357         @gtk_toolbox.log_exception(_moduleLogger)
358         def _on_move_category(self, *args):
359                 if self._notizen.noteId == -1:
360                         mbox = gtk.MessageDialog(self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("No note selected."))
361                         try:
362                                 response = mbox.run()
363                         finally:
364                                 mbox.hide()
365                                 mbox.destroy()
366                         return
367
368                 sql = "SELECT id, liste FROM categories WHERE id = 0 ORDER BY liste"
369                 rows = self._db.ladeSQL(sql)
370
371                 selectableCategories = list(self._category.get_categories())
372                 selectableCategories.remove(self._category.ALL_CATEGORIES)
373                 currentCategory = self._category.get_category_name()
374                 if currentCategory == self._category.ALL_CATEGORIES:
375                         currentCategory = selectableCategories[0]
376
377                 newCategory = hildonize.touch_selector_entry(
378                         self._window, "Move to", selectableCategories, currentCategory
379                 )
380
381                 self._category.add_category(newCategory)
382                 noteid, pcdatum, category, note = self._db.loadNote(self._notizen.noteId)
383                 self._db.saveNote(noteid, note, newCategory, pcdatum = None)
384                 self._category.set_category() # HACK force it to update
385
386         @gtk_toolbox.log_exception(_moduleLogger)
387         def _on_delete_category(self, *args):
388                 if (
389                         self._category.get_category_name() in (
390                                 self._category.ALL_CATEGORIES, self._category.UNDEFINED_CATEGORY
391                         )
392                 ):
393                         mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("This category can not be deleted"))
394                         try:
395                                 response = mbox.run()
396                         finally:
397                                 mbox.hide()
398                                 mbox.destroy()
399                         return
400
401                 mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, _("Are you sure to delete the current category?"))
402                 try:
403                         response = mbox.run()
404                 finally:
405                         mbox.hide()
406                         mbox.destroy()
407                 if response == gtk.RESPONSE_YES:
408                         self._category.delete_this_category()
409
410         @gtk_toolbox.log_exception(_moduleLogger)
411         def _on_sync_finished(self, data = None, data2 = None):
412                 self._category.load_categories()
413                 self._notizen.load_notes()
414
415         @gtk_toolbox.log_exception(_moduleLogger)
416         def _on_sync_notes(self, widget = None, data = None):
417                 syncer = sync.Sync(self._db, self._window, 50504)
418                 syncer.connect("syncFinished", self._on_sync_finished)
419
420                 syncDialog = gtk.Dialog(_("Sync"), None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
421
422                 syncDialog.set_position(gtk.WIN_POS_CENTER)
423                 syncDialog.vbox.pack_start(syncer, True, True, 0)
424                 syncDialog.set_size_request(500, 350)
425                 syncDialog.vbox.show_all()
426                 syncDialog.run()
427                 syncDialog.hide()
428
429         @gtk_toolbox.log_exception(_moduleLogger)
430         def _on_toggle_word_wrap(self, *args):
431                 self._wordWrapEnabled = not self._wordWrapEnabled
432                 self._notizen.set_wordwrap(self._wordWrapEnabled)
433
434         @gtk_toolbox.log_exception(_moduleLogger)
435         def _on_delete_event(self, widget, event, data = None):
436                 return False
437
438         @gtk_toolbox.log_exception(_moduleLogger)
439         def _on_destroy(self, widget = None, data = None):
440                 try:
441                         self._db.close()
442                         self._save_settings()
443
444                         try:
445                                 self._deviceState.close()
446                         except AttributeError:
447                                 pass # Either None or close was removed (in Fremantle)
448                         try:
449                                 self._osso_c.close()
450                         except AttributeError:
451                                 pass # Either None or close was removed (in Fremantle)
452                 finally:
453                         gtk.main_quit()
454
455         @gtk_toolbox.log_exception(_moduleLogger)
456         def _on_show_about(self, widget = None, data = None):
457                 dialog = gtk.AboutDialog()
458                 dialog.set_position(gtk.WIN_POS_CENTER)
459                 dialog.set_name(constants.__pretty_app_name__)
460                 dialog.set_version(constants.__version__)
461                 dialog.set_copyright("")
462                 dialog.set_website("http://axique.de/index.php?f=Quicknote")
463                 comments = _("%s is a note taking program; it is optimised for quick save and search of notes") % constants.__pretty_app_name__
464                 dialog.set_comments(comments)
465                 dialog.set_authors(["Christoph Wurstle <n800@axique.net>", "Ed Page <eopage@byu.net> (Blame him for the most recent bugs)"])
466                 dialog.run()
467                 dialog.destroy()
468
469
470 def run_quicknote():
471         if hildonize.IS_HILDON_SUPPORTED:
472                 gtk.set_application_name(constants.__pretty_app_name__)
473         app = QuicknoteProgram()
474         if not PROFILE_STARTUP:
475                 gtk.main()
476
477
478 if __name__ == "__main__":
479         logging.basicConfig(level=logging.DEBUG)
480         run_quicknote()