]> git.plutz.net Git - tabnote/blob - tabnote
initial code commit
[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     initnote = ('Welcome to TabNote!\n\n' +
38                 'Click the "+"-Tab to open a new note.\n' +
39                 'Double Click on the selected tab to relabel or delete it.\n' +
40                 'Notes are stored when you exit the program.\n\n' +
41                 'Shortcuts:\n' +
42                 'Ctrl Left   - switch to previous tab\n' +
43                 'Ctrl Right  - switch to next tab\n' +
44                 'Ctrl Return - bring up relabel/delete dialog\n' +
45                 'Ctrl t      - create new tab\n' +
46                 'Ctrl q      - save and quit')
47     try:
48       self.dbcur.execute('CREATE TABLE settings (key TEXT, value TEXT, UNIQUE (key))')
49       self.dbcur.execute('INSERT INTO settings (key, value) VALUES ("version", "1.0");')
50       self.dbcur.execute('INSERT INTO settings (key, value) VALUES ("geometry", "420x300");')
51       self.dbcur.execute('CREATE TABLE notes (id INTEGER PRIMARY KEY, label TEXT, content TEXT);')
52       self.dbcur.execute('INSERT INTO notes (label, content) VALUES ("Introduction", "' +
53                          self.escape(initnote) + '");')
54     except: pass
55
56   def getSetting(self, key):
57     self.dbcur.execute('SELECT value FROM settings WHERE key = "' + self.escape(key) + '";')
58     try: return self.dbcur.fetchall()[0][0]
59     except: return ''
60
61   def setSetting(self, key, value):
62     try:
63       self.dbcur.execute('INSERT INTO settings (key, value) VALUES ("' + self.escape(key) +
64                          '", "' + self.escape(value) + '");')
65     except:
66       self.dbcur.execute('UPDATE settings SET value = "' + self.escape(value) +
67                          '" WHERE key = "' + self.escape(key) + '";')
68
69   def escape(self, string):
70     """
71     Return sanitized string for use in SQL-Statements
72     """
73     ret = ''
74     for c in string:
75       if c == '"': ret += '""'
76       else: ret += c
77     return ret
78
79   def allRecords(self):
80     """
81     Return list of all recorded notes
82     Each item is an array of the format [id, label, textcontent]
83     """
84     self.dbcur.execute('SELECT id, label, content FROM notes ORDER BY id;')
85     return self.dbcur.fetchall()
86
87   def setRecord(self, rid, content = None, label = None):
88     """
89     Alter an existing record
90     """
91     if content:
92       self.dbcur.execute('UPDATE notes SET content = "' + self.escape(content) +
93                          '" WHERE id = ' + str(rid) + ';')
94     if label:
95       self.dbcur.execute('UPDATE notes SET label = "' + self.escape(label) +
96                          '" WHERE id = ' + str(rid) + ';')
97
98   def addRecord(self, label = '', content = ''):
99     """
100     Create a new record, return the new record id
101     """
102     self.dbcur.execute('INSERT INTO notes (label, content) VALUES ("' + self.escape(label) +
103                        '", "' + self.escape(content) + '");')
104     return self.dbcur.lastrowid
105
106   def delRecord(self, rid):
107     """
108     Delete record by ID
109     """
110     self.dbcur.execute('DELETE FROM notes WHERE id = ' + str(rid) + ';')
111
112   def close(self):
113     """
114     Flush and close databese
115     """
116     self.dbcur.close()
117     self.dbcon.commit()
118     self.dbcon.close()
119
120 class Main(Tk):
121   """
122   Main application class
123   """
124   def __init__(self):
125     """
126     Open Database, create Main application window, and retrieve stored data
127     """
128     Tk.__init__(self)
129     self.storage = Persistence()
130     self.protocol('WM_DELETE_WINDOW', self.quit)
131     self.title('TabNote')
132
133     self.relabelWin = False
134     self.contents = []
135
136     self.tablist = Pmw.NoteBook(self, raisecommand = self.tabselect, lowercommand = self.tabunselect)
137     self.tablist.add('')
138     self.tablist.pack(expand = True, fill = BOTH)
139     for tab in self.storage.allRecords():
140       self.addTab(tab[0], tab[1], tab[2])
141     self.tablist.delete(Pmw.END)
142     self.tablist.add('+')
143
144     self.bind_all('<Control-Left>', self.previouspage)
145     self.bind_all('<Control-Right>', self.nextpage)
146     self.bind_all('<Control-t>', self.newTab)
147     self.bind_all('<Control-q>', self.quit)
148     self.bind_all('<Control-Return>', self.tabedit)
149
150     try:
151       self.geometry(self.storage.getSetting('geometry'))
152       self.tablist.selectpage(self.storage.getSetting('activeTab'))
153     except: pass
154
155   def newTab(self, junk):
156     """
157     Event wrapper for new tab
158     """
159     self.tablist.selectpage('+')
160
161   def previouspage(self, junk):
162     """
163     Event wrapper for tab switching
164     """
165     if self.tablist.getcurselection() == self.tablist.pagenames()[0]:
166       self.tablist.selectpage(self.tablist.pagenames()[-2])
167     else:
168       self.tablist.previouspage()
169
170   def nextpage(self, junk):
171     """
172     Event wrapper for tab switching
173     """
174     if self.tablist.getcurselection() == self.tablist.pagenames()[-2]:
175       self.tablist.selectpage(0)
176     else:
177       self.tablist.nextpage()
178
179   def closeRelabel(self, junk = None):
180     """
181     Close relabeling dialog window
182     """
183     self.relabelWin.destroy()
184     self.relabelWin = False
185
186   def delTab(self, junk = None):
187     """
188     Delete a tab (and its record)
189     Called by relabeling dialog
190     """
191     for tab in self.contents:
192       if tab[1] == self.tablist.page(self.relabel):
193         self.storage.delRecord(tab[0])
194         self.contents.remove(tab)
195         self.tablist.previouspage()
196         self.tablist.delete(self.relabel)
197         break
198     self.closeRelabel()
199
200   def relabelTab(self, junk = None):
201     """
202     Change the name of a tab
203     Called by relabeling dialog
204     """
205     for tab in self.contents:
206       if tab[1] == self.tablist.page(self.relabel) and self.relabel != self.relabelText.get():
207         label = self.newName(self.relabelText.get())
208         content = tab[2].getvalue()[:-1]
209  
210         tab[1] = self.tablist.insert(label, before = self.tablist.index(self.relabel))
211         self.tablist.tab(label).bind(sequence = '<Double-Button-1>', func = self.tabedit)
212         tab[2] = Pmw.ScrolledText(tab[1])
213         tab[2].setvalue(content)
214         tab[2].pack(expand = True, fill = BOTH)
215  
216         self.tablist.previouspage()
217         self.tablist.delete(self.relabel)
218         self.storage.setRecord(tab[0], label = label)
219         break
220     self.closeRelabel()
221
222   def tabedit(self, junk):
223     """
224     Bring up relabeling dialog
225     """
226     if not self.relabelWin:
227       self.relabel = self.tablist.getcurselection()
228       self.relabelWin = Tk()
229       self.relabelWin.bind('<Escape>', self.closeRelabel)
230       self.relabelWin.protocol('WM_DELETE_WINDOW', self.closeRelabel)
231       self.relabelText = Entry(self.relabelWin)
232       self.relabelText.insert(0, self.relabel)
233       self.relabelText.focus()
234       self.relabelText.bind('<Return>', self.relabelTab)
235       self.relabelText.pack(side = TOP, fill = X, expand = True)
236       relabelButton = Button(self.relabelWin, text='Relabel', command=self.relabelTab)
237       relabelButton.bind('<Return>', self.relabelTab)
238       relabelButton.pack(side = LEFT, fill = BOTH, expand = True)
239       deleteButton = Button(self.relabelWin, text='Delete', command=self.delTab)
240       deleteButton.bind('<Return>', self.delTab)
241       deleteButton.pack(side = LEFT, fill = BOTH, expand = True)
242
243   def newName(self, basename = 'New'):
244     """
245     Return a unique name for a tab by appending a number to the given basename
246     """
247     if not basename in self.tablist.pagenames(): return basename
248     incrementor = 1
249     while (basename + str(incrementor)) in self.tablist.pagenames(): incrementor += 1
250     return (basename + str(incrementor))
251
252   def tabunselect(self, name):
253     """
254     Called when a tab becomes unselected, write the DB record for this tab
255     """
256     for tab in self.contents:
257       if tab[1] == self.tablist.page(name):
258         self.storage.setRecord(tab[0], content=tab[2].getvalue()[:-1])
259
260   def addTab(self, rid, label = 'New', content = ""):
261     """
262     Create a new tab
263     """
264     label = self.newName(label)
265     self.contents.append([rid, self.tablist.insert(label, before = self.tablist.index(Pmw.END)), None])
266     self.tablist.tab(label).bind(sequence = '<Double-Button-1>', func = self.tabedit)
267     self.contents[-1][2] = Pmw.ScrolledText(self.contents[-1][1])
268     self.contents[-1][2].setvalue(content)
269     self.contents[-1][2].pack(expand = True, fill = BOTH)
270
271   def tabselect(self, name):
272     """
273     Called when a tab is selected
274     Normally sets focus to the text editor widget
275     If the + tab is selected, this function creates a new record and tab
276     """
277     if name == '+':
278       self.addTab(self.storage.addRecord('New', ''), 'New', '');
279       self.tablist.previouspage();
280     else:
281       for tab in self.contents:
282         if tab[1] == self.tablist.page(name):
283           tab[2].component('text').focus()
284
285   def quit(self, junk = None):
286     """
287     Store all data and terminate program
288     """
289     self.storage.setSetting('activeTab', self.tablist.getcurselection())
290     self.storage.setSetting('geometry', str(self.geometry()))
291     self.tabunselect(self.tablist.getcurselection())
292     self.storage.close()
293     self.destroy()
294
295 win = Main()
296 win.mainloop()