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