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