Version bump
[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 an edit menu with select all, cut, copy, and paste
12 @todo Add undo directly into the UI
13 @todo Add Note Export (txt File) and Export All (json dump?)
14 @todo Save word wrap and zoom setting 
15 """
16
17
18 import os
19 import gc
20 import logging
21
22 import gtk
23
24 try:
25         import hildon
26         IS_HILDON = True
27 except ImportError:
28         import fakehildon as hildon
29         IS_HILDON = False
30
31 try:
32         import osso
33 except ImportError:
34         osso = None
35
36 import libspeichern
37 import libkopfzeile
38 import libnotizen
39 import libsync
40
41
42 try:
43         _
44 except NameError:
45         _ = lambda x: x
46
47
48 class quicknoteclass(hildon.Program):
49
50         __pretty_app_name__ = "quicknote"
51         __app_name__ = "quicknote"
52         __version__ = "0.7.7"
53
54         def __init__(self):
55                 super(quicknoteclass, self).__init__()
56
57                 home_dir = os.path.expanduser('~')
58                 dblog = os.path.join(home_dir, "quicknote.log")
59
60                 # define a Handler which writes INFO messages or higher to the sys.stderr
61                 console = logging.StreamHandler()
62                 console.setLevel(logging.DEBUG)
63                 # set a format which is simpler for console use
64                 formatter = logging.Formatter('%(asctime)s  %(levelname)-8s %(message)s')
65                 # tell the handler to use this format
66                 console.setFormatter(formatter)
67                 # add the handler to the root logger
68                 logging.getLogger('').addHandler(console)
69
70                 logging.info('Starting quicknote')
71
72                 if osso is not None:
73                         self._osso_c = osso.Context(self.__app_name__, self.__version__, False)
74                         self.device = osso.DeviceState(self._osso_c)
75                         self.device.set_device_state_callback(self._on_device_state_change, 0)
76                 else:
77                         self._osso_c = None
78
79                 #Get the Main Window, and connect the "destroy" event
80                 self.window = hildon.Window()
81                 self.add_window(self.window)
82
83                 self.window.set_title(self.__pretty_app_name__)
84                 self.window.connect("delete_event", self.delete_event)
85                 self.window.connect("destroy", self.destroy)
86                 self.window.connect("key-press-event", self.on_key_press)
87                 self.window.connect("window-state-event", self.on_window_state_change)
88                 self.window_in_fullscreen = False #The window isn't in full screen mode initially.
89
90                 self.db = libspeichern.Speichern()
91                 self.prepare_sync_dialog()
92
93                 #Create GUI main vbox
94                 vbox = gtk.VBox(homogeneous = False, spacing = 0)
95
96                 #Create Menu and apply it for hildon
97                 filemenu = gtk.Menu()
98
99                 menu_items = gtk.MenuItem(_("Set DB file"))
100                 filemenu.append(menu_items)
101                 menu_items.connect("activate", self.set_db_file, None)
102
103                 menu_items = gtk.MenuItem(_("SQL History"))
104                 filemenu.append(menu_items)
105                 menu_items.connect("activate", self.view_sql_history, None)
106
107                 menu_items = gtk.MenuItem(_("Sync notes"))
108                 filemenu.append(menu_items)
109                 menu_items.connect("activate", self.sync_notes, None)
110
111                 menu_items = gtk.MenuItem(_("Quit"))
112                 filemenu.append(menu_items)
113                 menu_items.connect("activate", self.destroy, None)
114
115                 file_menu = gtk.MenuItem(_("File"))
116                 file_menu.show()
117                 file_menu.set_submenu(filemenu)
118
119                 categorymenu = gtk.Menu()
120
121                 menu_items = gtk.MenuItem(_("delete"))
122                 categorymenu.append(menu_items)
123                 menu_items.connect("activate", self.delete_Category, None)
124
125                 menu_items = gtk.MenuItem(_("move to category"))
126                 categorymenu.append(menu_items)
127                 menu_items.connect("activate", self.move_Category, None)
128
129                 category_menu = gtk.MenuItem(_("Category"))
130                 category_menu.show()
131                 category_menu.set_submenu(categorymenu)
132
133                 viewmenu = gtk.Menu()
134
135                 menu_items = gtk.MenuItem(_("Word Wrap"))
136                 viewmenu.append(menu_items)
137                 menu_items.connect("activate", self.toggle_word_wrap, None)
138                 self._wordWrapEnabled = False
139
140                 view_menu = gtk.MenuItem(_("View"))
141                 view_menu.show()
142                 view_menu.set_submenu(viewmenu)
143
144                 helpmenu = gtk.Menu()
145
146                 menu_items = gtk.MenuItem(_("About"))
147                 helpmenu.append(menu_items)
148                 menu_items.connect("activate", self.show_about, None)
149
150                 help_menu = gtk.MenuItem(_("Help"))
151                 help_menu.show()
152                 help_menu.set_submenu(helpmenu)
153
154                 menu_bar = gtk.MenuBar()
155                 menu_bar.show()
156                 menu_bar.append (file_menu)
157                 menu_bar.append (category_menu)
158                 menu_bar.append (view_menu)
159                 menu_bar.append (help_menu)
160
161                 menu_bar.show()
162                 if IS_HILDON:
163                         menu = gtk.Menu()
164                         for child in menu_bar.get_children():
165                                 child.reparent(menu)
166                         self.window.set_menu(menu)
167                         menu_bar.destroy()
168                 else:
169                         vbox.pack_start(menu_bar, False, False, 0)
170
171                 #Create GUI elements
172                 self.topBox = libkopfzeile.Kopfzeile(self.db)
173                 vbox.pack_start(self.topBox, False, False, 0)
174
175                 self.notizen = libnotizen.Notizen(self.db, self.topBox)
176                 vbox.pack_start(self.notizen, True, True, 0)
177
178                 self.window.add(vbox)
179                 self.window.show_all()
180                 self.toggle_word_wrap()
181
182         def set_db_file(self, widget = None, data = None):
183                 dlg = hildon.FileChooserDialog(parent=self.window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
184
185                 if self.db.ladeDirekt('datenbank'):
186                         dlg.set_filename(self.db.ladeDirekt('datenbank'))
187
188                 dlg.set_title(_("Choose database file"))
189                 if dlg.run() == gtk.RESPONSE_OK:
190                         fileName = dlg.get_filename()
191                         self.db.speichereDirekt('datenbank', fileName)
192
193                         self.db.openDB()
194                         self.topBox.loadCategories()
195                         self.notizen.loadNotes()
196                         dlg.destroy()
197
198         def show_about(self, widget = None, data = None):
199                 dialog = gtk.AboutDialog()
200                 dialog.set_position(gtk.WIN_POS_CENTER)
201                 dialog.set_name(self.__pretty_app_name__)
202                 dialog.set_version(self.__version__)
203                 dialog.set_copyright("")
204                 dialog.set_website("http://axique.de/index.php?f=Quicknote")
205                 comments = _("%s is a note taking program; it is optimised for quick save and search of notes") % self.__pretty_app_name__
206                 dialog.set_comments(comments)
207                 dialog.run()
208                 dialog.destroy()
209
210         def view_sql_history(self, widget = None, data = None, data2 = None):
211                 import libsqldialog
212                 sqldiag = libsqldialog.sqlDialog(self.db)
213                 res = sqldiag.run()
214                 sqldiag.hide()
215                 if res == 444:
216                         logging.info("exporting sql")
217
218                         dlg = hildon.FileChooserDialog(parent=self.window, action=gtk.FILE_CHOOSER_ACTION_SAVE)
219
220                         dlg.set_title(_("Select SQL export file"))
221                         if dlg.run() == gtk.RESPONSE_OK:
222                                 fileName = dlg.get_filename()
223                                 dlg.destroy()
224                                 sqldiag.exportSQL(fileName)
225                         else:
226                                 dlg.destroy()
227
228                 sqldiag.destroy()
229
230         def delete_Category(self, widget = None, data = None):
231                 if (self.topBox.getCategory() == "%") or (self.topBox.getCategory() == "undefined"):
232                         mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("This category can not be deleted"))
233                         response = mbox.run()
234                         mbox.hide()
235                         mbox.destroy()
236                         return
237
238                 mbox = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, _("Are you sure to delete the current category?"))
239                 response = mbox.run()
240                 mbox.hide()
241                 mbox.destroy()
242                 if response == gtk.RESPONSE_YES:
243                         sql = "UPDATE notes SET category = ? WHERE category = ?"
244                         self.db.speichereSQL(sql, ("undefined", self.topBox.getCategory()))
245                         sql = "DELETE FROM categories WHERE liste = ?"
246                         self.db.speichereSQL(sql, (self.topBox.getCategory(), ))
247                         model = self.topBox.comboCategory.get_model()
248                         pos = self.topBox.comboCategory.get_active()
249                         if (pos>1):
250                                 self.topBox.comboCategory.remove_text(pos)
251                                 self.topBox.comboCategory.set_active(0)
252
253         def move_Category(self, widget = None, data = None):
254                 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))
255
256                 dialog.set_position(gtk.WIN_POS_CENTER)
257                 comboCategory = gtk.combo_box_new_text()
258
259                 comboCategory.append_text('undefined')
260                 sql = "SELECT id, liste FROM categories WHERE id = 0 ORDER BY liste"
261                 rows = self.db.ladeSQL(sql)
262                 for row in rows:
263                         comboCategory.append_text(row[1])
264
265                 dialog.vbox.pack_start(comboCategory, True, True, 0)
266
267                 dialog.vbox.show_all()
268                 #dialog.set_size_request(400, 300)
269
270                 if dialog.run() == gtk.RESPONSE_ACCEPT:
271                         n = comboCategory.get_active()
272                         if (n>-1) and (self.notizen.noteid!= -1):
273                                 model = comboCategory.get_model()
274                                 active = comboCategory.get_active()
275                                 if active < 0:
276                                         return None
277                                 cat_id = model[active][0]
278
279                                 noteid, category, note = self.db.loadNote(self.notizen.noteid)
280                                 #print noteid, category, cat_id
281                                 self.db.saveNote(noteid, note, cat_id, pcdatum = None)
282                                 self.topBox.comboCategoryChanged()
283                         else:
284                                 mbox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("No note selected."))
285                                 response = mbox.run()
286                                 mbox.hide()
287                                 mbox.destroy()
288
289                 dialog.destroy()
290
291         def sync_finished(self, data = None, data2 = None):
292                 self.topBox.loadCategories()
293                 self.notizen.loadNotes()
294
295         def prepare_sync_dialog(self):
296                 self.sync_dialog = gtk.Dialog(_("Sync"), None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
297
298                 self.sync_dialog.set_position(gtk.WIN_POS_CENTER)
299                 sync = libsync.Sync(self.db, self.window, 50504)
300                 self.sync_dialog.vbox.pack_start(sync, True, True, 0)
301                 self.sync_dialog.set_size_request(500, 350)
302                 self.sync_dialog.vbox.show_all()
303                 sync.connect("syncFinished", self.sync_finished)
304
305         def sync_notes(self, widget = None, data = None):
306                 self.sync_dialog.run()
307                 self.sync_dialog.hide()
308
309         def toggle_word_wrap(self, *args):
310                 self._wordWrapEnabled = not self._wordWrapEnabled
311                 self.notizen.set_wordwrap(self._wordWrapEnabled)
312
313         def delete_event(self, widget, event, data = None):
314                 return False
315
316         def destroy(self, widget = None, data = None):
317                 self.db.close()
318                 if self._osso_c:
319                         self._osso_c.close()
320                 gtk.main_quit()
321
322         def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
323                 """
324                 For system_inactivity, we have no background tasks to pause
325
326                 @note Hildon specific
327                 """
328                 if memory_low:
329                         gc.collect()
330
331                 if save_unsaved_data or shutdown:
332                         pass
333
334         def on_window_state_change(self, widget, event, *args):
335                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
336                         self.window_in_fullscreen = True
337                 else:
338                         self.window_in_fullscreen = False
339
340         def on_key_press(self, widget, event, *args):
341                 if event.keyval == gtk.keysyms.F6:
342                         # The "Full screen" hardware key has been pressed 
343                         if self.window_in_fullscreen:
344                                 self.window.unfullscreen ()
345                         else:
346                                 self.window.fullscreen ()
347                 elif event.keyval == gtk.keysyms.F7:
348                         # Zoom In
349                         self.topBox.hide()
350                 elif event.keyval == gtk.keysyms.F8:
351                         # Zoom Out
352                         self.topBox.show()
353
354         def main(self):
355                 gtk.main()