f1e86994539680b288526273c5ae18b1a8d97ff0
[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 sync
44
45
46 try:
47         _
48 except NameError:
49         _ = lambda x: x
50
51
52 _moduleLogger = logging.getLogger("quicknote_gtk")
53
54
55 class QuicknoteProgram(hildonize.get_app_class()):
56
57         _user_data = os.path.join(os.path.expanduser("~"), ".%s" % constants.__app_name__)
58         _user_settings = "%s/settings.ini" % _user_data
59
60         def __init__(self):
61                 super(QuicknoteProgram, self).__init__()
62                 self._clipboard = gtk.clipboard_get()
63
64                 dblog = os.path.join(self._user_data, "quicknote.log")
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                 self._isZoomEnabled = False
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(_("Delete"))
105                         categorymenu.append(menu_items)
106                         menu_items.connect("activate", self._on_delete_category, None)
107
108                         menu_items = gtk.MenuItem(_("Move To Category"))
109                         categorymenu.append(menu_items)
110                         menu_items.connect("activate", self._on_move_category, None)
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(_("Word Wrap"))
119                         viewmenu.append(menu_items)
120                         menu_items.connect("activate", self._on_toggle_word_wrap, None)
121
122                         view_menu = gtk.MenuItem(_("View"))
123                         view_menu.show()
124                         view_menu.set_submenu(viewmenu)
125
126                         helpmenu = gtk.Menu()
127
128                         menu_items = gtk.MenuItem(_("About"))
129                         helpmenu.append(menu_items)
130                         menu_items.connect("activate", self._on_show_about, None)
131
132                         help_menu = gtk.MenuItem(_("Help"))
133                         help_menu.show()
134                         help_menu.set_submenu(helpmenu)
135
136                         menuBar = gtk.MenuBar()
137                         menuBar.show()
138                         menuBar.append (file_menu)
139                         menuBar.append (category_menu)
140                         menuBar.append (view_menu)
141                         menuBar.append (help_menu)
142
143                         vbox.pack_start(menuBar, False, False, 0)
144                 else:
145                         menuBar = gtk.MenuBar()
146                         menuBar.show()
147                         vbox.pack_start(menuBar, False, False, 0)
148
149                 #Create GUI elements
150                 self._topBox = kopfzeile.Kopfzeile(self._db)
151                 vbox.pack_start(self._topBox, False, False, 0)
152
153                 self._notizen = notizen.Notizen(self._db, self._topBox)
154                 vbox.pack_start(self._notizen, True, True, 0)
155
156                 #Get the Main Window, and connect the "destroy" event
157                 self._window = gtk.Window()
158                 self._window.add(vbox)
159
160                 self._on_toggle_word_wrap()
161                 self.enable_zoom(True)
162
163                 try:
164                         os.makedirs(self._user_data)
165                 except OSError, e:
166                         if e.errno != 17:
167                                 raise
168
169                 self._window = hildonize.hildonize_window(self, self._window)
170                 hildonize.set_application_title(self._window, "%s" % constants.__pretty_app_name__)
171                 menuBar = hildonize.hildonize_menu(
172                         self._window,
173                         menuBar,
174                 )
175                 if hildonize.IS_FREMANTLE_SUPPORTED:
176                         moveToCategoryButton = gtk.Button(_("Move To Category"))
177                         moveToCategoryButton.connect("clicked", self._on_move_category, None)
178                         menuBar.append(moveToCategoryButton)
179
180                         deleteCategoryButton = gtk.Button(_("Delete Category"))
181                         deleteCategoryButton.connect("clicked", self._on_delete_category, None)
182                         menuBar.append(deleteCategoryButton)
183
184                         menuBar.show_all()
185
186                 if not hildonize.IS_HILDON_SUPPORTED:
187                         _moduleLogger.info("No hildonization support")
188
189                 if osso is not None:
190                         self._osso_c = osso.Context(constants.__app_name__, constants.__version__, False)
191                         self._deviceState = osso.DeviceState(self._osso_c)
192                         self._deviceState.set_device_state_callback(self._on_device_state_change, 0)
193                 else:
194                         _moduleLogger.info("No osso support")
195                         self._osso_c = None
196                         self._deviceState = None
197
198                 self._prepare_sync_dialog()
199
200                 self._window.connect("delete-event", self._on_delete_event)
201                 self._window.connect("destroy", self._on_destroy)
202                 self._window.connect("key-press-event", self._on_key_press)
203                 self._window.connect("window-state-event", self._on_window_state_change)
204
205                 self._window.show_all()
206                 self._load_settings()
207
208         def main(self):
209                 gtk.main()
210
211         def _save_settings(self):
212                 config = ConfigParser.SafeConfigParser()
213                 self.save_settings(config)
214                 with open(self._user_settings, "wb") as configFile:
215                         config.write(configFile)
216
217         def save_settings(self, config):
218                 config.add_section(constants.__pretty_app_name__)
219                 config.set(constants.__pretty_app_name__, "wordwrap", str(self._wordWrapEnabled))
220                 config.set(constants.__pretty_app_name__, "zoom", str(self._isZoomEnabled))
221                 config.set(constants.__pretty_app_name__, "fullscreen", str(self._window_in_fullscreen))
222
223         def _load_settings(self):
224                 config = ConfigParser.SafeConfigParser()
225                 config.read(self._user_settings)
226                 self.load_settings(config)
227
228         def load_settings(self, config):
229                 try:
230                         self._wordWrapEnabled = config.getboolean(constants.__pretty_app_name__, "wordwrap")
231                         self._isZoomEnabled = config.getboolean(constants.__pretty_app_name__, "zoom")
232                         self._window_in_fullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
233                 except ConfigParser.NoSectionError, e:
234                         warnings.warn(
235                                 "Settings file %s is missing section %s" % (
236                                         self._user_settings,
237                                         e.section,
238                                 ),
239                                 stacklevel=2
240                         )
241
242                 self._notizen.set_wordwrap(self._wordWrapEnabled)
243
244                 self.enable_zoom(self._isZoomEnabled)
245
246                 if self._window_in_fullscreen:
247                         self._window.fullscreen()
248                 else:
249                         self._window.unfullscreen()
250
251         def set_db_file(self, widget = None, data = None):
252                 dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
253
254                 if self._db.ladeDirekt('datenbank'):
255                         dlg.set_filename(self._db.ladeDirekt('datenbank'))
256
257                 dlg.set_title(_("Choose database file"))
258                 if dlg.run() == gtk.RESPONSE_OK:
259                         fileName = dlg.get_filename()
260                         self._db.speichereDirekt('datenbank', fileName)
261
262                         self._db.openDB()
263                         self._topBox.load_categories()
264                         self._notizen.load_notes()
265                 dlg.destroy()
266
267         def _prepare_sync_dialog(self):
268                 self._syncDialog = gtk.Dialog(_("Sync"), None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
269
270                 self._syncDialog.set_position(gtk.WIN_POS_CENTER)
271                 syncer = sync.Sync(self._db, self._window, 50504)
272                 self._syncDialog.vbox.pack_start(syncer, True, True, 0)
273                 self._syncDialog.set_size_request(500, 350)
274                 self._syncDialog.vbox.show_all()
275                 syncer.connect("syncFinished", self._on_sync_finished)
276
277         def enable_zoom(self, zoomEnabled):
278                 self._isZoomEnabled = zoomEnabled
279                 if zoomEnabled:
280                         self._topBox.hide()
281                         self._notizen.show_history_area(False)
282                 else:
283                         self._topBox.show()
284                         self._notizen.show_history_area(True)
285
286         @gtk_toolbox.log_exception(_moduleLogger)
287         def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
288                 """
289                 For system_inactivity, we have no background tasks to pause
290
291                 @note Hildon specific
292                 """
293                 if memory_low:
294                         gc.collect()
295
296                 if save_unsaved_data or shutdown:
297                         self._save_settings()
298
299         @gtk_toolbox.log_exception(_moduleLogger)
300         def _on_window_state_change(self, widget, event, *args):
301                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
302                         self._window_in_fullscreen = True
303                 else:
304                         self._window_in_fullscreen = False
305
306         @gtk_toolbox.log_exception(_moduleLogger)
307         def _on_key_press(self, widget, event, *args):
308                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
309                 isCtrl = bool(event.get_state() & gtk.gdk.CONTROL_MASK)
310                 if (
311                         event.keyval == gtk.keysyms.F6 or
312                         event.keyval in RETURN_TYPES and isCtrl
313                 ):
314                         # The "Full screen" hardware key has been pressed 
315                         if self._window_in_fullscreen:
316                                 self._window.unfullscreen ()
317                         else:
318                                 self._window.fullscreen ()
319                         return True
320                 elif (
321                         event.keyval == gtk.keysyms.F7 or
322                         event.keyval == gtk.keysyms.i and isCtrl
323                 ):
324                         # Zoom In
325                         self.enable_zoom(True)
326                         return True
327                 elif (
328                         event.keyval == gtk.keysyms.F8 or
329                         event.keyval == gtk.keysyms.o and isCtrl
330                 ):
331                         # Zoom Out
332                         self.enable_zoom(False)
333                         return True
334                 elif (
335                         event.keyval in (gtk.keysyms.w, gtk.keysyms.q) and
336                         event.get_state() & gtk.gdk.CONTROL_MASK
337                 ):
338                         self._window.destroy()
339                 elif event.keyval == gtk.keysyms.l and event.get_state() & gtk.gdk.CONTROL_MASK:
340                         with open(constants._user_logpath_, "r") as f:
341                                 logLines = f.xreadlines()
342                                 log = "".join(logLines)
343                                 self._clipboard.set_text(str(log))
344                         return True
345
346         @gtk_toolbox.log_exception(_moduleLogger)
347         def _on_view_sql_history(self, widget = None, data = None, data2 = None):
348                 import sqldialog
349                 sqldiag = sqldialog.SqlDialog(self._db)
350                 res = sqldiag.run()
351                 sqldiag.hide()
352                 if res == sqldiag.EXPORT_RESPONSE:
353                         _moduleLogger.info("exporting sql")
354
355                         dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
356
357                         dlg.set_title(_("Select SQL export file"))
358                         if dlg.run() == gtk.RESPONSE_OK:
359                                 fileName = dlg.get_filename()
360                                 sqldiag.exportSQL(fileName)
361                         dlg.destroy()
362
363                 sqldiag.destroy()
364
365         @gtk_toolbox.log_exception(_moduleLogger)
366         def _on_move_category(self, *args):
367                 comboCategory = gtk.combo_box_new_text()
368                 comboCategory.append_text('undefined')
369                 sql = "SELECT id, liste FROM categories WHERE id = 0 ORDER BY liste"
370                 rows = self._db.ladeSQL(sql)
371                 for row in rows:
372                         comboCategory.append_text(row[1])
373
374                 dialog = gtk.Dialog(_("Choose category"), self._window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
375                 try:
376                         dialog.set_position(gtk.WIN_POS_CENTER)
377
378                         dialog.vbox.pack_start(comboCategory, True, True, 0)
379                         dialog.vbox.show_all()
380
381                         userResponse = dialog.run()
382                 finally:
383                         dialog.destroy()
384
385                 if userResponse != gtk.RESPONSE_ACCEPT:
386                         return
387
388                 n = comboCategory.get_active()
389                 if -1 < n and self._notizen.noteId != -1:
390                         model = comboCategory.get_model()
391                         active = comboCategory.get_active()
392                         if active < 0:
393                                 return None
394                         cat_id = model[active][0]
395
396                         noteid, pcdatum, category, note = self._db.loadNote(self._notizen.noteId)
397                         self._db.saveNote(noteid, note, cat_id, pcdatum = None)
398                         self._topBox.category_combo_changed()
399                 else:
400                         mbox = gtk.MessageDialog(self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("No note selected."))
401                         response = mbox.run()
402                         mbox.hide()
403                         mbox.destroy()
404
405         @gtk_toolbox.log_exception(_moduleLogger)
406         def _on_delete_category(self, *args):
407                 if self._topBox.get_category() == "%" or self._topBox.get_category() == "undefined":
408                         mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("This category can not be deleted"))
409                         response = mbox.run()
410                         mbox.hide()
411                         mbox.destroy()
412                         return
413
414                 mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, _("Are you sure to delete the current category?"))
415                 response = mbox.run()
416                 mbox.hide()
417                 mbox.destroy()
418                 if response == gtk.RESPONSE_YES:
419                         sql = "UPDATE notes SET category = ? WHERE category = ?"
420                         self._db.speichereSQL(sql, ("undefined", self._topBox.get_category()))
421                         sql = "DELETE FROM categories WHERE liste = ?"
422                         self._db.speichereSQL(sql, (self._topBox.get_category(), ))
423                         model = self._topBox.categoryCombo.get_model()
424                         pos = self._topBox.categoryCombo.get_active()
425                         if (pos>1):
426                                 self._topBox.categoryCombo.remove_text(pos)
427                                 self._topBox.categoryCombo.set_active(0)
428
429         @gtk_toolbox.log_exception(_moduleLogger)
430         def _on_sync_finished(self, data = None, data2 = None):
431                 self._topBox.load_categories()
432                 self._notizen.load_notes()
433
434         @gtk_toolbox.log_exception(_moduleLogger)
435         def _on_sync_notes(self, widget = None, data = None):
436                 self._syncDialog.run()
437                 self._syncDialog.hide()
438
439         @gtk_toolbox.log_exception(_moduleLogger)
440         def _on_toggle_word_wrap(self, *args):
441                 self._wordWrapEnabled = not self._wordWrapEnabled
442                 self._notizen.set_wordwrap(self._wordWrapEnabled)
443
444         @gtk_toolbox.log_exception(_moduleLogger)
445         def _on_delete_event(self, widget, event, data = None):
446                 return False
447
448         @gtk_toolbox.log_exception(_moduleLogger)
449         def _on_destroy(self, widget = None, data = None):
450                 try:
451                         self._db.close()
452                         self._save_settings()
453
454                         try:
455                                 self._deviceState.close()
456                         except AttributeError:
457                                 pass # Either None or close was removed (in Fremantle)
458                         try:
459                                 self._osso_c.close()
460                         except AttributeError:
461                                 pass # Either None or close was removed (in Fremantle)
462                 finally:
463                         gtk.main_quit()
464
465         @gtk_toolbox.log_exception(_moduleLogger)
466         def _on_show_about(self, widget = None, data = None):
467                 dialog = gtk.AboutDialog()
468                 dialog.set_position(gtk.WIN_POS_CENTER)
469                 dialog.set_name(constants.__pretty_app_name__)
470                 dialog.set_version(constants.__version__)
471                 dialog.set_copyright("")
472                 dialog.set_website("http://axique.de/index.php?f=Quicknote")
473                 comments = _("%s is a note taking program; it is optimised for quick save and search of notes") % constants.__pretty_app_name__
474                 dialog.set_comments(comments)
475                 dialog.set_authors(["Christoph Wurstle <n800@axique.net>", "Ed Page <eopage@byu.net> (Blame him for the most recent bugs)"])
476                 dialog.run()
477                 dialog.destroy()
478
479
480 def run_quicknote():
481         if hildonize.IS_HILDON_SUPPORTED:
482                 gtk.set_application_name(constants.__pretty_app_name__)
483         app = QuicknoteProgram()
484         app.main()
485
486
487 if __name__ == "__main__":
488         logging.basicConfig(level=logging.DEBUG)
489         run_quicknote()