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