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