]> git.plutz.net Git - tabnote/blob - tabnote
79295deab0a21e60c75a149ed5274ef3b2f6bfbd
[tabnote] / tabnote
1 #!/usr/bin/python
2 #encoding: utf-8
3
4 # TabNote - Note Taking Application
5 # Copyright 2011 Paul Hänsch
6 # Contact: haensch.paul@gmail.com
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 from Tkinter import *
22 from pysqlite2 import dbapi2
23 import os
24 import Pmw
25
26 class Persistence():
27   """
28   Database storage layer
29   """
30   def __init__(self):
31     """
32     Constructor
33     Open a database, create and initialize the database if needed
34     """
35     self.dbcon = dbapi2.connect(os.getenv('HOME') + os.sep + '.tabnote.sqlite')
36     self.dbcur = self.dbcon.cursor()
37     self.initDB()
38
39   def initDB(self):
40     initnote = ('Welcome to TabNote!\n\n' +
41                 'Click the "+"-Tab to open a new note.\n' +
42                 'Double Click on the selected tab to relabel or delete it.\n' +
43                 'Notes are stored when you exit the program.\n\n' +
44                 'Shortcuts:\n' +
45                 'Ctrl Left   - switch to previous tab\n' +
46                 'Ctrl Right  - switch to next tab\n' +
47                 'Ctrl Return - bring up relabel/delete dialog\n' +
48                 'Ctrl t      - create new tab\n' +
49                 'Ctrl q      - save and quit')
50     initnote = self.escape(initnote)
51
52     try:
53       self.dbcur.execute('CREATE TABLE settings (key TEXT, value TEXT, UNIQUE (key));')
54       self.dbcur.execute('INSERT INTO settings (key, value) VALUES ("version", "1.6");')
55       self.dbcur.execute('INSERT INTO settings (key, value) VALUES ("geometry", "420x300");')
56       self.dbcur.execute('CREATE TABLE notes (uuid TEXT, seq INTEGER PRIMARY KEY, label TEXT, ' +
57                    'content TEXT, revision DATETIME, lastsync DATETIME, UNIQUE (uuid));')
58       self.dbcur.execute('INSERT INTO notes (uuid, label, content, revision, lastsync) VALUES ' +
59                    '(lower(hex(randomblob(16))), "Intro", "' + initnote +
60                    '", datetime(\'now\'), datetime(\'1970-01-01\'));')
61     except: pass
62
63   def getSetting(self, key):
64     self.dbcur.execute('SELECT value FROM settings WHERE key = "' + self.escape(key) + '";')
65     try: return self.dbcur.fetchall()[0][0]
66     except: return ''
67
68   def setSetting(self, key, value):
69     try:
70       self.dbcur.execute('INSERT INTO settings (key, value) VALUES ("' + self.escape(key) +
71                          '", "' + self.escape(value) + '");')
72     except:
73       self.dbcur.execute('UPDATE settings SET value = "' + self.escape(value) +
74                          '" WHERE key = "' + self.escape(key) + '";')
75
76   def escape(self, string):
77     """
78     Return sanitized string for use in SQL-Statements
79     """
80     ret = ''
81     for c in string:
82       if c == '"': ret += '""'
83       else: ret += c
84     return ret
85
86   def allRecords(self):
87     """
88     Return list of all recorded notes
89     Each item is an array of the format [id, label, textcontent]
90     """
91     self.dbcur.execute('SELECT uuid, label, content FROM notes ORDER BY seq;')
92     return self.dbcur.fetchall()
93
94   def setRecord(self, uuid = None, label = None, content = None):
95     """
96     Create or alter a record
97     """
98     if not uuid:
99       if label: label = self.escape(label)
100       else: label = ''
101       if content: content = self.escape(content)
102       else: content = ''
103       self.dbcur.execute('INSERT INTO notes (uuid, label, content, revision, lastsync) VALUES ' +
104                          '(lower(hex(randomblob(16))), "' + label + '", "' + content +
105                          '", datetime(\'now\'), datetime(\'1970-01-01\'));')
106     else:    
107       if content:
108         self.dbcur.execute('UPDATE notes SET content = "' + self.escape(content) +
109                            '", revision = datetime(\'now\') WHERE uuid = "' + str(uuid) +
110                            '" AND NOT content = "' + self.escape(content) + '";')
111       if label:
112         self.dbcur.execute('UPDATE notes SET label = "' + self.escape(label) +
113                            '", revision = datetime(\'now\') WHERE uuid = "' + str(uuid) + '";')
114     return self.dbcur.lastrowid
115
116   def delRecord(self, uuid):
117     """
118     Delete record by ID
119     """
120     self.dbcur.execute('DELETE FROM notes WHERE uuid = "' + str(uuid) + '";')
121
122   def close(self):
123     """
124     Flush and close databese
125     """
126     self.dbcur.close()
127     self.dbcon.commit()
128     self.dbcon.close()
129
130 class Main(Tk):
131   """
132   Main application class
133   """
134   def __init__(self):
135     """
136     Open Database, create Main application window, and retrieve stored data
137     """
138     Tk.__init__(self)
139     self.storage = Persistence()
140     self.protocol('WM_DELETE_WINDOW', self.quit)
141     self.title('TabNote')
142
143     self.relabelWin = False
144     self.contents = []
145
146     self.tablist = Pmw.NoteBook(self, raisecommand = self.tabselect, lowercommand = self.tabunselect)
147     self.tablist.add('')
148     self.tablist.pack(expand = True, fill = BOTH)
149     for tab in self.storage.allRecords():
150       self.addTab(tab[0], tab[1], tab[2])
151     self.tablist.delete(Pmw.END)
152     self.tablist.add('+')
153
154     self.bind_all('<Control-Left>', self.previouspage)
155     self.bind_all('<Control-Right>', self.nextpage)
156     self.bind_all('<Control-t>', self.newTab)
157     self.bind_all('<Control-q>', self.quit)
158     self.bind_all('<Control-Return>', self.tabedit)
159
160     try:
161       self.geometry(self.storage.getSetting('geometry'))
162       self.tablist.selectpage(self.storage.getSetting('activeTab'))
163     except: pass
164
165   def newTab(self, junk):
166     """
167     Event wrapper for new tab
168     """
169     self.tablist.selectpage('+')
170
171   def previouspage(self, junk):
172     """
173     Event wrapper for tab switching
174     """
175     if self.tablist.getcurselection() == self.tablist.pagenames()[0]:
176       self.tablist.selectpage(self.tablist.pagenames()[-2])
177     else:
178       self.tablist.previouspage()
179
180   def nextpage(self, junk):
181     """
182     Event wrapper for tab switching
183     """
184     if self.tablist.getcurselection() == self.tablist.pagenames()[-2]:
185       self.tablist.selectpage(0)
186     else:
187       self.tablist.nextpage()
188
189   def closeRelabel(self, junk = None):
190     """
191     Close relabeling dialog window
192     """
193     self.relabelWin.destroy()
194     self.relabelWin = False
195
196   def delTab(self, junk = None):
197     """
198     Delete a tab (and its record)
199     Called by relabeling dialog
200     """
201     for tab in self.contents:
202       if tab[1] == self.tablist.page(self.relabel):
203         self.storage.delRecord(tab[0])
204         self.contents.remove(tab)
205         self.tablist.previouspage()
206         self.tablist.delete(self.relabel)
207         break
208     self.closeRelabel()
209
210   def relabelTab(self, junk = None):
211     """
212     Change the name of a tab
213     Called by relabeling dialog
214     """
215     for tab in self.contents:
216       if tab[1] == self.tablist.page(self.relabel) and self.relabel != self.relabelText.get():
217         label = self.newName(self.relabelText.get())
218         content = tab[2].getvalue()[:-1]
219  
220         tab[1] = self.tablist.insert(label, before = self.tablist.index(self.relabel))
221         self.tablist.tab(label).bind(sequence = '<Double-Button-1>', func = self.tabedit)
222         tab[2] = Pmw.ScrolledText(tab[1])
223         tab[2].setvalue(content)
224         tab[2].pack(expand = True, fill = BOTH)
225  
226         self.tablist.previouspage()
227         self.tablist.delete(self.relabel)
228         self.storage.setRecord(tab[0], label = label)
229         break
230     self.closeRelabel()
231
232   def tabedit(self, junk):
233     """
234     Bring up relabeling dialog
235     """
236     if not self.relabelWin:
237       self.relabel = self.tablist.getcurselection()
238       self.relabelWin = Tk()
239       self.relabelWin.bind('<Escape>', self.closeRelabel)
240       self.relabelWin.protocol('WM_DELETE_WINDOW', self.closeRelabel)
241       self.relabelText = Entry(self.relabelWin)
242       self.relabelText.insert(0, self.relabel)
243       self.relabelText.focus()
244       self.relabelText.bind('<Return>', self.relabelTab)
245       self.relabelText.pack(side = TOP, fill = X, expand = True)
246       relabelButton = Button(self.relabelWin, text='Relabel', command=self.relabelTab)
247       relabelButton.bind('<Return>', self.relabelTab)
248       relabelButton.pack(side = LEFT, fill = BOTH, expand = True)
249       deleteButton = Button(self.relabelWin, text='Delete', command=self.delTab)
250       deleteButton.bind('<Return>', self.delTab)
251       deleteButton.pack(side = LEFT, fill = BOTH, expand = True)
252
253   def newName(self, basename = 'New'):
254     """
255     Return a unique name for a tab by appending a number to the given basename
256     """
257     if not basename in self.tablist.pagenames(): return basename
258     incrementor = 1
259     while (basename + str(incrementor)) in self.tablist.pagenames(): incrementor += 1
260     return (basename + str(incrementor))
261
262   def tabunselect(self, name):
263     """
264     Called when a tab becomes unselected, write the DB record for this tab
265     """
266     for tab in self.contents:
267       if tab[1] == self.tablist.page(name):
268         self.storage.setRecord(tab[0], content = tab[2].getvalue()[:-1])
269
270   def addTab(self, rid, label = 'New', content = ""):
271     """
272     Create a new tab
273     """
274     label = self.newName(label)
275     self.contents.append([rid, self.tablist.insert(label, before = self.tablist.index(Pmw.END)), None])
276     self.tablist.tab(label).bind(sequence = '<Double-Button-1>', func = self.tabedit)
277     self.contents[-1][2] = Pmw.ScrolledText(self.contents[-1][1])
278     self.contents[-1][2].setvalue(content)
279     self.contents[-1][2].pack(expand = True, fill = BOTH)
280
281   def tabselect(self, name):
282     """
283     Called when a tab is selected
284     Normally sets focus to the text editor widget
285     If the + tab is selected, this function creates a new record and tab
286     """
287     if name == '+':
288       self.addTab(self.storage.setRecord(None, 'New', ''), 'New', '');
289       self.tablist.previouspage();
290     else:
291       for tab in self.contents:
292         if tab[1] == self.tablist.page(name):
293           tab[2].component('text').focus()
294
295   def quit(self, junk = None):
296     """
297     Store all data and terminate program
298     """
299     self.storage.setSetting('activeTab', self.tablist.getcurselection())
300     self.storage.setSetting('geometry', str(self.geometry()))
301     self.tabunselect(self.tablist.getcurselection())
302     self.storage.close()
303     self.destroy()
304
305 win = Main()
306 win.mainloop()