viewing and deleting trash works
[public/library.git] / browser.py
1 import sys
2 import curses
3 import dbLayer as db
4 from form import bookForm,categoryForm
5
6 class browserWindow:
7     hl=0
8     topline = 0
9     entries = []
10     selected = []
11     commands = [(' /', 'search'), (' n', 'find next'), (' N', 'find previous'), (' q', 'quit')]
12     cs = []
13     # column definitions are in (label, weight, specified width) triples
14     columnDefs = [('something',1,None)]
15     mx = my = 0
16     cx = cy = 0
17     # for searches
18     last_search = ""
19     found_index = 0
20
21     def __init__(self,window,helpbar):
22         self.w = window
23         self.hb = helpbar
24         self.updateGeometry()
25         self.commands = self.cs+self.commands
26
27     def sortByColumn(self, col):
28         self.entries.sort(key=lambda k: k.get(col)) # key=dict.get(col))
29         self.selected = map(lambda x: False, self.selected)
30
31     def updateGeometry(self):
32         (self.my,self.mx)=self.w.getmaxyx()
33         (y,x) = self.w.getbegyx()
34         self.cx = x + self.mx/2
35         self.cy = y + self.my/2
36         self.pageSize = self.my-3
37         self.calcColWidths()
38
39     def calcColWidths(self):
40         total_weights = 0
41         available_space = self.mx - len(self.columnDefs)
42         cols = []
43         for label,weight,value in self.columnDefs:
44             if value!=None:
45                 available_space -= value
46             else:
47                 total_weights+=weight
48
49         for label,weight,value in self.columnDefs:
50             if value!=None:
51                 cols.append((label,value))
52             else:
53                 cols.append((label,available_space*weight/total_weights))
54         self.columns=cols
55
56     def refresh(self):
57         self.hb.commands = self.commands
58         self.hb.refresh()
59         self.displayHeader()
60         for r in range(0,self.pageSize):
61             self.displayRow(r)
62         self.w.refresh()
63         self.highlight()
64
65     def clear(self):
66         self.w.erase()
67         self.w.refresh()
68
69     def centreChild(self,child):
70         (y,x)=child.getmaxyx()
71         child.mvwin(self.cy-y/2,self.cx-x/2)
72
73
74     def displayHeader(self):
75         cursor = 1
76         for header,width in self.columns:
77             self.w.addnstr(0,cursor,header+" "*width,width)
78             self.w.addstr(1,cursor,"-"*width)
79             cursor += width+1
80
81     def displayRow(self,row):
82         if self.topline+row < len(self.entries):
83             entry = self.entries[self.topline+row]
84             cursor = 1
85             if self.selected[self.topline+row]:
86                 self.w.addstr(row+2, 0, "*")
87             else:
88                 self.w.addstr(row+2, 0, " ")
89             for k,width in self.columns:
90                 if k.lower() in entry:
91                     self.w.addnstr(row+2,cursor,str(entry[k.lower()])+" "*width,width)
92                 cursor += width+1
93         else:
94             self.w.addstr(row+2,0," "*self.mx)
95
96     def highlight(self):
97         row = self.hl-self.topline+2
98         if row > 1 and row < self.my:
99             self.w.chgat(row,0,self.mx,curses.A_REVERSE)
100
101     def unHighlight(self):
102         row = self.hl-self.topline+2
103         if row > 1 and row < self.my:
104             self.w.chgat(row,0,self.mx,curses.A_NORMAL)
105
106     def mvHighlight(self,delta):
107         new = self.hl+delta
108         new = max(new,0)
109         new = min(new,len(self.entries)-1)
110         self.unHighlight()
111         self.hl = new
112         self.highlight()
113     
114     def scroll(self,delta):
115         self.unHighlight()
116         self.topline += delta
117         self.topline = max(self.topline,0)
118         self.topline = min(self.topline,len(self.entries)-1)
119         self.refresh()
120
121     def search(self, string):
122         i = 0
123         found = False
124         for e in self.entries:
125             for k,v in e.items():
126                 if str(v).find(string) != -1:
127                     found = True
128             if found:
129                 break
130             i += 1;
131         if found:
132             self.last_search = string
133             self.search_index = i
134             return i
135         else:
136             self.search_index = -1
137             return -1
138
139     def findNext(self):
140         if self.last_search == "" or self.search_index == -1:
141             return -1
142         found = False
143         for i in range(self.hl+1,len(self.entries)-1):
144             for k,v in self.entries[i].items():
145                 if str(v).find(self.last_search) != -1:
146                     found = True
147             if found:
148                 break
149         if found:
150             self.search_index = i
151             return i
152         else:
153             return -1
154
155     def findPrevious(self):
156         if self.last_search == "" or self.search_index == -1:
157             return -1
158         found = False
159         for i in range(self.hl-1, 0, -1):
160             for k,v in self.entries[i].items():
161                 if str(v).find(self.last_search) != -1:
162                     found = True
163             if found:
164                 break
165         if found:
166             self.search_index = i
167             return i
168         else:
169             return -1
170
171
172     def eventLoop(self):
173         self.w.keypad(1)
174         self.refresh()
175
176         ch = self.w.getch()
177         while ch != 27 and ch != 113:
178             ch = self.handleInput(ch)
179             if ch==113:
180                 return {}
181             self.w.refresh()
182             ch = self.w.getch()
183             self.hb.refresh()
184
185     def handleInput(self,ch):
186         if ch == curses.KEY_UP or ch == 107 or ch == 16:
187             if self.hl == self.topline:
188                 self.scroll(-self.pageSize/2-1)
189             self.mvHighlight(-1)
190         elif ch == curses.KEY_DOWN or ch == 106 or ch == 14:
191             if self.hl == self.topline+self.pageSize-1:
192                 self.scroll(+self.pageSize/2+1)
193             self.mvHighlight(+1)
194         elif ch == curses.KEY_PPAGE:
195             self.scroll(-self.pageSize)
196             self.mvHighlight(-self.pageSize)
197         elif ch == curses.KEY_NPAGE:
198             self.scroll(+self.pageSize)
199             self.mvHighlight(+self.pageSize)
200         elif ch == 47: # forward slash
201             string = self.hb.getSearch()
202             hl = self.search(string)
203             if hl != -1:
204                 delta = hl - self.hl
205                 self.scroll(delta)
206                 self.mvHighlight(delta)
207             else:
208                 self.hb.display(string+' not found')
209         elif ch == 110: # n
210             hl = self.findNext()
211             if hl != -1:
212                 delta = hl - self.hl
213                 self.scroll(delta)
214                 self.mvHighlight(delta)
215             else:
216                 self.hb.display(self.last_search+' not found')
217         elif ch == 78: # N
218             hl = self.findPrevious()
219             if hl != -1:
220                 delta = hl - self.hl
221                 self.scroll(delta)
222                 self.mvHighlight(delta)
223             else:
224                 self.hb.display(self.last_search+' not found')
225         elif ch == 32:
226             self.selected[self.hl] = not self.selected[self.hl]
227             self.displayRow(self.hl-self.topline)
228             self.highlight()
229
230
231
232 class trashBrowser(browserWindow):
233     columnDefs = [('ID',0,3),
234                   ('ISBN',0,13),
235                   ('Authors',30,None),
236                   ('Title',60,None)]
237     
238     cs = [(' r', 'restore selected'), (' d', 'delete selected')]
239     
240     # redefinable functions
241     def viewSelection(self,book):
242         bookid = book['id']
243         w=curses.newwin(1,1,20,20)
244         bf = bookForm(w,self.hb,book)
245         self.centreChild(w)
246         bf.caption='Viewing Book '+str(bookid)
247         bf.blabel='done'
248         bf.eventLoop()
249         bf.clear()
250
251     def delSelected(self):
252         books = []
253         for sel,book in zip(self.selected, self.entries):
254             if sel:
255                 books.append(book)
256         db.deleteBooks(books)
257
258     def refreshBooks(self):
259         self.entries = db.getRemovedBooks()
260         self.selected = map(lambda x:False, self.entries)
261
262     def handleInput(self,ch):
263         browserWindow.handleInput(self,ch)
264         if ch == 10:
265             book = self.entries[self.hl]
266             self.viewSelection(book)
267             self.refresh()
268         if ch==100:
269             count=0
270             for s in self.selected[0:self.hl-1]:
271                 if s:
272                     count+=1
273             self.delSelected()
274             self.refreshBooks()
275             self.refresh()
276             self.scroll(-count)
277             self.mvHighlight(-count)
278         return ch
279
280 class bookBrowser(browserWindow):
281     columnDefs = [('ID',0,3),
282                   ('ISBN',0,13),
283                   ('Authors',30,None),
284                   ('Title',60,None)]
285     
286     cs = [(' u', 'update'), (' d', 'delete selected')]
287     
288     # redefinable functions
289     def updateSelection(self,book):
290         bookid = book['id']
291         
292         w=curses.newwin(1,1)
293         bf=bookForm(w,self.hb,book)
294         self.centreChild(w)
295         bf.caption='Update Book '+str(bookid)
296         bf.blabel='update'
297         newbook = bf.eventLoop()
298         if len(newbook)!=0:
299             db.updateBook(newbook,bookid)
300         bf.clear()
301
302     def viewSelection(self,book):
303         bookid = book['id']
304         w=curses.newwin(1,1,20,20)
305         bf = bookForm(w,self.hb,book)
306         self.centreChild(w)
307         bf.caption='Viewing Book '+str(bookid)
308         bf.blabel='done'
309         bf.eventLoop()
310         bf.clear()
311
312     def categorizeSelection(self,book):
313         w = curses.newwin(40,20,20,20)
314         cs = categorySelector(w,self.hb)
315         self.centreChild(w)
316         cs.book = book
317         cs.refreshCategories()
318         cs.eventLoop()
319         cs.clear()
320     
321     def delSelected(self):
322         books = []
323         for sel,book in zip(self.selected, self.entries):
324             if sel:
325                 books.append(book)
326         db.removeBooks(books)
327
328     def refreshBooks(self):
329         self.entries = db.getBooks()
330         self.selected = map(lambda x:False, self.entries)
331
332     def handleInput(self,ch):
333         browserWindow.handleInput(self,ch)
334         if ch == 117: #update on 'u'
335             book = self.entries[self.hl]
336             self.updateSelection(book)
337             self.entries[self.hl]=db.getBookByID(book['id'])
338             self.refresh()
339         elif ch == 10:
340             book = self.entries[self.hl]
341             self.viewSelection(book)
342             self.refresh()
343         elif ch == 99:
344             book = self.entries[self.hl]
345             self.categorizeSelection(book)
346             self.refresh()
347         if ch==100:
348             count=0
349             for s in self.selected[0:self.hl-1]:
350                 if s:
351                     count+=1
352             self.delSelected()
353             self.refreshBooks()
354             self.refresh()
355             self.scroll(-count)
356             self.mvHighlight(-count)
357         return ch
358
359 class categoryBrowser(browserWindow):
360     columnDefs = [('Category',100,None)]
361     cs = [(' a', 'add category'), (' d', 'delete selected')]
362
363
364     def refreshCategories(self):
365         self.entries = db.getCategories()
366         self.sortByColumn('category')
367         self.selected = map(lambda x:False, self.entries)
368
369     def addCategory(self):
370         w = curses.newwin(1,1,10,10)
371         cf = categoryForm(w,self.hb)
372         self.centreChild(w)
373         cats = cf.eventLoop()
374         for c in cats:
375             db.addCategory(c)
376         cf.clear()
377
378     def delSelected(self):
379         categories = []
380         for sel,cat in zip(self.selected, self.entries):
381             if sel:
382                 categories.append(cat)
383         db.deleteCategories(categories)
384
385     def handleInput(self,ch):
386         browserWindow.handleInput(self,ch)
387         if ch==97:
388             self.addCategory()
389             self.refreshCategories()
390             self.refresh()
391         if ch==100:
392             count=0
393             for s in self.selected[0:self.hl-1]:
394                 if s:
395                     count+=1
396             self.delSelected()
397             self.refreshCategories()
398             self.refresh()
399             self.scroll(-count)
400             self.mvHighlight(-count)
401         return ch
402
403 class categorySelector(browserWindow):
404     columnDefs = [('Category',100,None)]
405     cs = [(' a', 'add category'), (' c', 'commit')]
406     book = {'id':''}
407     original=[]
408
409
410     def refreshCategories(self):
411         self.entries = db.getCategories()
412         self.sortByColumn('category')
413         self.refreshSelected()
414
415     def refreshSelected(self):
416         self.original = map(lambda x:False, self.entries)
417         cats = db.getBookCategories(self.book)
418         cats.sort()
419         cats.sort(key=lambda k: k.get('category')) # key=dict.get(col))
420         i = 0
421         j = 0
422         for cat in self.entries:
423             if i == len(cats):
424                 break
425             if cat['id']==cats[i]['cat_id']:
426                 self.original[j] = True;
427                 i+=1
428             j+=1
429         self.selected = self.original[:]
430
431
432     def addCategory(self):
433         w = curses.newwin(1,1,10,10)
434         cf = categoryForm(w,self.hb)
435         self.centreChild(w)
436         cats = cf.eventLoop()
437         for c in cats:
438             db.addCategory(c)
439         cf.clear()
440
441     def updateCategories(self):
442         # first removed the deselected ones
443         uncats = []
444         cats = []
445         for old, new, category in zip(self.original, self.selected, self.entries):
446             if old and (not new):
447                 uncats.append(category)
448             if (not old) and new:
449                 cats.append(category)
450         db.uncategorizeBook(self.book, uncats)
451         # add the newly selected categories
452         db.categorizeBook(self.book, cats)
453
454
455     def handleInput(self,ch):
456         browserWindow.handleInput(self,ch)
457         if ch==97:
458             self.addCategory()
459             self.refreshCategories()
460             self.refresh()
461         if ch==99:
462             self.updateCategories()
463             return 113
464