Trying to fix the application title
[quicknote] / src / libquicknote.py
1 #/usr/bin/env python2.5
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         IS_HILDON = True
29 except ImportError:
30         import fakehildon as hildon
31         IS_HILDON = False
32
33 try:
34         import osso
35 except ImportError:
36         osso = None
37
38 import constants
39
40 import libspeichern
41 import libkopfzeile
42 import libnotizen
43 import libsync
44
45
46 try:
47         _
48 except NameError:
49         _ = lambda x: x
50
51
52 class QuicknoteProgram(hildon.Program):
53
54         _user_data = os.path.join(os.path.expanduser("~"), ".%s" % constants.__app_name__)
55         _user_settings = "%s/settings.ini" % _user_data
56
57         def __init__(self):
58                 super(QuicknoteProgram, self).__init__()
59                 if IS_HILDON:
60                         gtk.set_application_name(constants.__pretty_app_name__)
61
62                 dblog = os.path.join(self._user_data, "quicknote.log")
63
64                 # define a Handler which writes INFO messages or higher to the sys.stderr
65                 console = logging.StreamHandler()
66                 console.setLevel(logging.DEBUG)
67                 # set a format which is simpler for console use
68                 formatter = logging.Formatter('%(asctime)s  %(levelname)-8s %(message)s')
69                 # tell the handler to use this format
70                 console.setFormatter(formatter)
71                 # add the handler to the root logger
72                 logging.getLogger('').addHandler(console)
73
74                 logging.info('Starting quicknote')
75
76                 if osso is not None:
77                         self._osso_c = osso.Context(constants.__app_name__, constants.__version__, False)
78                         self._deviceState = osso.DeviceState(self._osso_c)
79                         self._deviceState.set_device_state_callback(self._on_device_state_change, 0)
80                 else:
81                         self._osso_c = None
82                         self._deviceState = None
83
84                 #Get the Main Window, and connect the "destroy" event
85                 self._window = hildon.Window()
86                 self.add_window(self._window)
87
88                 if not IS_HILDON:
89                         self._window.set_title(constants.__pretty_app_name__)
90                 self._window.connect("delete_event", self._on_delete_event)
91                 self._window.connect("destroy", self._on_destroy)
92                 self._window.connect("key-press-event", self._on_key_press)
93                 self._window.connect("window-state-event", self._on_window_state_change)
94                 self._window_in_fullscreen = False #The window isn't in full screen mode initially.
95                 self._isZoomEnabled = False
96
97                 self._db = libspeichern.Speichern()
98                 self._syncDialog = None
99                 self._prepare_sync_dialog()
100
101                 #Create GUI main vbox
102                 vbox = gtk.VBox(homogeneous = False, spacing = 0)
103
104                 #Create Menu and apply it for hildon
105                 filemenu = gtk.Menu()
106
107                 menu_items = gtk.MenuItem(_("Set DB file"))
108                 filemenu.append(menu_items)
109                 menu_items.connect("activate", self.set_db_file, None)
110
111                 menu_items = gtk.MenuItem(_("SQL History"))
112                 filemenu.append(menu_items)
113                 menu_items.connect("activate", self._on_view_sql_history, None)
114
115                 menu_items = gtk.MenuItem(_("Sync notes"))
116                 filemenu.append(menu_items)
117                 menu_items.connect("activate", self._on_sync_notes, None)
118
119                 menu_items = gtk.MenuItem(_("Quit"))
120                 filemenu.append(menu_items)
121                 menu_items.connect("activate", self._on_destroy, None)
122
123                 file_menu = gtk.MenuItem(_("File"))
124                 file_menu.show()
125                 file_menu.set_submenu(filemenu)
126
127                 categorymenu = gtk.Menu()
128
129                 menu_items = gtk.MenuItem(_("Delete"))
130                 categorymenu.append(menu_items)
131                 menu_items.connect("activate", self._on_delete_category, None)
132
133                 menu_items = gtk.MenuItem(_("Move To Category"))
134                 categorymenu.append(menu_items)
135                 menu_items.connect("activate", self._on_move_category, None)
136
137                 category_menu = gtk.MenuItem(_("Category"))
138                 category_menu.show()
139                 category_menu.set_submenu(categorymenu)
140
141                 viewmenu = gtk.Menu()
142
143                 menu_items = gtk.MenuItem(_("Word Wrap"))
144                 viewmenu.append(menu_items)
145                 menu_items.connect("activate", self._on_toggle_word_wrap, None)
146                 self._wordWrapEnabled = False
147
148                 view_menu = gtk.MenuItem(_("View"))
149                 view_menu.show()
150                 view_menu.set_submenu(viewmenu)
151
152                 helpmenu = gtk.Menu()
153
154                 menu_items = gtk.MenuItem(_("About"))
155                 helpmenu.append(menu_items)
156                 menu_items.connect("activate", self._on_show_about, None)
157
158                 help_menu = gtk.MenuItem(_("Help"))
159                 help_menu.show()
160                 help_menu.set_submenu(helpmenu)
161
162                 menu_bar = gtk.MenuBar()
163                 menu_bar.show()
164                 menu_bar.append (file_menu)
165                 menu_bar.append (category_menu)
166                 menu_bar.append (view_menu)
167                 menu_bar.append (help_menu)
168
169                 menu_bar.show()
170                 if IS_HILDON:
171                         menu = gtk.Menu()
172                         for child in menu_bar.get_children():
173                                 child.reparent(menu)
174                         self._window.set_menu(menu)
175                         menu_bar.destroy()
176                 else:
177                         vbox.pack_start(menu_bar, False, False, 0)
178
179                 #Create GUI elements
180                 self._topBox = libkopfzeile.Kopfzeile(self._db)
181                 vbox.pack_start(self._topBox, False, False, 0)
182
183                 self._notizen = libnotizen.Notizen(self._db, self._topBox)
184                 vbox.pack_start(self._notizen, True, True, 0)
185                 self._window.add(vbox)
186
187                 self._on_toggle_word_wrap()
188
189                 try:
190                         os.makedirs(self._user_data)
191                 except OSError, e:
192                         if e.errno != 17:
193                                 raise
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                 sync = libsync.Sync(self._db, self._window, 50504)
261                 self._syncDialog.vbox.pack_start(sync, True, True, 0)
262                 self._syncDialog.set_size_request(500, 350)
263                 self._syncDialog.vbox.show_all()
264                 sync.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         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         def _on_window_state_change(self, widget, event, *args):
288                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
289                         self._window_in_fullscreen = True
290                 else:
291                         self._window_in_fullscreen = False
292
293         def _on_key_press(self, widget, event, *args):
294                 if event.keyval == gtk.keysyms.F6:
295                         # The "Full screen" hardware key has been pressed 
296                         if self._window_in_fullscreen:
297                                 self._window.unfullscreen ()
298                         else:
299                                 self._window.fullscreen ()
300                 elif event.keyval == gtk.keysyms.F7:
301                         # Zoom In
302                         self.enable_zoom(True)
303                 elif event.keyval == gtk.keysyms.F8:
304                         # Zoom Out
305                         self.enable_zoom(False)
306
307         def _on_view_sql_history(self, widget = None, data = None, data2 = None):
308                 import libsqldialog
309                 sqldiag = libsqldialog.SqlDialog(self._db)
310                 res = sqldiag.run()
311                 sqldiag.hide()
312                 if res == sqldiag.EXPORT_RESPONSE:
313                         logging.info("exporting sql")
314
315                         dlg = hildon.FileChooserDialog(parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
316
317                         dlg.set_title(_("Select SQL export file"))
318                         if dlg.run() == gtk.RESPONSE_OK:
319                                 fileName = dlg.get_filename()
320                                 sqldiag.exportSQL(fileName)
321                         dlg.destroy()
322
323                 sqldiag.destroy()
324
325         def _on_move_category(self, widget = None, data = None):
326                 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))
327
328                 dialog.set_position(gtk.WIN_POS_CENTER)
329                 comboCategory = gtk.combo_box_new_text()
330
331                 comboCategory.append_text('undefined')
332                 sql = "SELECT id, liste FROM categories WHERE id = 0 ORDER BY liste"
333                 rows = self._db.ladeSQL(sql)
334                 for row in rows:
335                         comboCategory.append_text(row[1])
336
337                 dialog.vbox.pack_start(comboCategory, True, True, 0)
338
339                 dialog.vbox.show_all()
340                 #dialog.set_size_request(400, 300)
341
342                 if dialog.run() == gtk.RESPONSE_ACCEPT:
343                         n = comboCategory.get_active()
344                         if -1 < n and self._notizen.noteId != -1:
345                                 model = comboCategory.get_model()
346                                 active = comboCategory.get_active()
347                                 if active < 0:
348                                         return None
349                                 cat_id = model[active][0]
350
351                                 noteid, category, note = self._db.loadNote(self._notizen.noteId)
352                                 #print noteid, category, cat_id
353                                 self._db.saveNote(noteid, note, cat_id, pcdatum = None)
354                                 self._topBox.category_combo_changed()
355                         else:
356                                 mbox = gtk.MessageDialog(self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("No note selected."))
357                                 response = mbox.run()
358                                 mbox.hide()
359                                 mbox.destroy()
360
361                 dialog.destroy()
362
363         def _on_delete_category(self, widget = None, data = None):
364                 if self._topBox.get_category() == "%" or self._topBox.get_category() == "undefined":
365                         mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("This category can not be deleted"))
366                         response = mbox.run()
367                         mbox.hide()
368                         mbox.destroy()
369                         return
370
371                 mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, _("Are you sure to delete the current category?"))
372                 response = mbox.run()
373                 mbox.hide()
374                 mbox.destroy()
375                 if response == gtk.RESPONSE_YES:
376                         sql = "UPDATE notes SET category = ? WHERE category = ?"
377                         self._db.speichereSQL(sql, ("undefined", self._topBox.get_category()))
378                         sql = "DELETE FROM categories WHERE liste = ?"
379                         self._db.speichereSQL(sql, (self._topBox.get_category(), ))
380                         model = self._topBox.categoryCombo.get_model()
381                         pos = self._topBox.categoryCombo.get_active()
382                         if (pos>1):
383                                 self._topBox.categoryCombo.remove_text(pos)
384                                 self._topBox.categoryCombo.set_active(0)
385
386         def _on_sync_finished(self, data = None, data2 = None):
387                 self._topBox.load_categories()
388                 self._notizen.load_notes()
389
390         def _on_sync_notes(self, widget = None, data = None):
391                 self._syncDialog.run()
392                 self._syncDialog.hide()
393
394         def _on_toggle_word_wrap(self, *args):
395                 self._wordWrapEnabled = not self._wordWrapEnabled
396                 self._notizen.set_wordwrap(self._wordWrapEnabled)
397
398         def _on_delete_event(self, widget, event, data = None):
399                 return False
400
401         def _on_destroy(self, widget = None, data = None):
402                 try:
403                         self._save_settings()
404                         self._db.close()
405                         if self._osso_c:
406                                 self._osso_c.close()
407                 finally:
408                         gtk.main_quit()
409
410         def _on_show_about(self, widget = None, data = None):
411                 dialog = gtk.AboutDialog()
412                 dialog.set_position(gtk.WIN_POS_CENTER)
413                 dialog.set_name(constants.__pretty_app_name__)
414                 dialog.set_version(constants.__version__)
415                 dialog.set_copyright("")
416                 dialog.set_website("http://axique.de/index.php?f=Quicknote")
417                 comments = _("%s is a note taking program; it is optimised for quick save and search of notes") % constants.__pretty_app_name__
418                 dialog.set_comments(comments)
419                 dialog.set_authors(["Christoph Wurstle <n800@axique.net>", "Ed Page <edpage@byu.net> (Blame him for the most recent bugs)"])
420                 dialog.run()
421                 dialog.destroy()