Make {,back}space pan between the edges of a zoomed page.
[automanga.git] / manga / reader.py
CommitLineData
04f773e3 1import threading, gtk, gobject
43423668 2import lib, profile
03feea07
FT
3
4class notdone(Exception): pass
5
6class future(threading.Thread):
7 prog = None
8
9 def __init__(self):
10 super(future, self).__init__()
11 self._val = None
12 self._exc = None
c9e2eced
FT
13 self._notlist = []
14 self._started = False
95213fa6 15 self.setDaemon(True)
c9e2eced
FT
16
17 def start(self):
18 if not self._started:
19 super(future, self).start()
20 self._started = True
03feea07
FT
21
22 def run(self):
23 try:
24 val = self.value()
25 except Exception as e:
c84f095d
FT
26 self._exc = e
27 gobject.idle_add(self._callcbs, True)
03feea07 28 else:
c84f095d
FT
29 self._val = [val]
30 gobject.idle_add(self._callcbs, True)
31
32 def _callcbs(self, final):
33 nls = []
34 for cb in self._notlist:
35 if cb():
36 nls.append(cb)
37 self._notlist = [] if final else nls
c9e2eced
FT
38
39 # Caller must hold GDK lock
40 def notify(self, cb):
41 self.start()
42 if not self.done:
43 self._notlist.append(cb)
44 else:
45 cb()
46
47 def progcb(self):
c84f095d 48 gobject.idle_add(self._callcbs, False)
03feea07
FT
49
50 @property
51 def val(self):
c9e2eced 52 self.start()
03feea07
FT
53 if self._exc is not None:
54 raise self._exc
55 if self._val is None:
56 raise notdone()
57 return self._val[0]
58
59 @property
60 def done(self):
c9e2eced 61 self.start()
03feea07
FT
62 return self._exc != None or self._val != None
63
c9e2eced
FT
64 def wait(self):
65 self.start()
66 while self.is_alive():
67 self.join()
68 return self.val
69
03feea07
FT
70class imgload(future):
71 def __init__(self, page):
c9e2eced 72 super(imgload, self).__init__()
03feea07
FT
73 self.page = page
74 self.st = None
c9e2eced 75 self.start()
03feea07
FT
76
77 def value(self):
04f773e3 78 buf = gtk.gdk.PixbufLoader()
1aa34ec9
FT
79 try:
80 with self.page.open() as st:
81 self.p = 0
82 self.st = st
83 while True:
84 read = st.read(1024)
85 if read == "":
86 break
87 self.p += len(read)
88 buf.write(read)
89 self.progcb()
90 self.st = None
91 finally:
92 buf.close()
04f773e3 93 return buf.get_pixbuf()
03feea07
FT
94
95 @property
96 def prog(self):
97 if self.st is None or self.st.clen is None:
98 return None
99 return float(self.p) / float(self.st.clen)
100
c9e2eced
FT
101class pagecache(object):
102 def __init__(self, sz=50):
103 self.sz = sz
104 self.bk = []
105
106 def __getitem__(self, page):
107 idl = page.idlist()
108 for ol, f in self.bk:
109 if ol == idl:
110 return f
111 f = imgload(page)
112 self.bk.append((idl, f))
113 if len(self.bk) > self.sz:
d9163efe 114 self.bk = self.bk[-self.sz:]
c9e2eced
FT
115 return f
116
a133683d
FT
117 def __delitem__(self, page):
118 idl = page.idlist()
119 for i, (ol, f) in enumerate(self.bk):
120 if ol == idl:
121 del self.bk[i]
122 return
123 raise KeyError(idl)
124
c9e2eced
FT
125class relpageget(future):
126 def __init__(self, cur, prev, cache=None):
127 super(relpageget, self).__init__()
128 self.cur = lib.cursor(cur)
129 self.prev = prev
130 self.cache = cache
131 self.start()
132
133 def value(self):
134 try:
135 if self.prev:
136 page = self.cur.prev()
137 else:
138 page = self.cur.next()
139 except StopIteration:
140 page = None
141 else:
142 if self.cache:
143 self.cache[page]
144 return page
145
012c4cae
FT
146class idpageget(future):
147 def __init__(self, base, idlist):
148 super(idpageget, self).__init__()
149 self.bnode = base
150 self.idlist = idlist
151
152 def value(self):
153 return lib.cursor(self.bnode.byidlist(self.idlist)).cur
154
c9e2eced
FT
155class pageget(future):
156 def __init__(self, fnode):
157 super(pageget, self).__init__()
158 self.fnode = fnode
159 self.start()
160
161 def value(self):
162 return lib.cursor(self.fnode).cur
163
164class ccursor(object):
165 def __init__(self, ob, cache=None):
166 self.cur = lib.cursor(ob)
167 self.prev = relpageget(self.cur, True, cache)
168 self.next = relpageget(self.cur, False, cache)
169
03feea07
FT
170class pageview(gtk.Widget):
171 def __init__(self, pixbuf):
172 super(pageview, self).__init__()
173 self.pixbuf = pixbuf
174 self.zoomed = None, None
175 self.fit = True
176 self.zoom = 1.0
177 self.interp = gtk.gdk.INTERP_HYPER
178 self.off = 0, 0
179
180 def get_osize(self):
181 return self.pixbuf.get_width(), self.pixbuf.get_height()
182
183 def get_asize(self):
184 return self.allocation.width, self.allocation.height
185
186 def do_realize(self):
187 self.set_flags(self.flags() | gtk.REALIZED)
188 alloc = self.allocation
189 self.window = gtk.gdk.Window(self.get_parent_window(),
190 width=alloc.width, height=alloc.height,
191 window_type = gtk.gdk.WINDOW_CHILD,
192 wclass = gtk.gdk.INPUT_OUTPUT,
193 event_mask = self.get_events() | gtk.gdk.EXPOSURE_MASK
194 )
195 self.window.set_user_data(self)
196 self.style.attach(self.window)
197 self.style.set_background(self.window, gtk.STATE_NORMAL)
198 self.window.move_resize(*alloc)
199
200 def do_unrealize(self):
201 self.window.set_user_data(None)
202
203 def do_size_request(self, req):
d9163efe
FT
204 w, h = self.get_osize()
205 req.width, req.height = max(min(w, 4096), 0), max(min(h, 4096), 0)
03feea07
FT
206
207 def fitzoom(self):
208 w, h = self.get_osize()
209 alloc = self.allocation
210 return min(float(alloc.width) / float(w), float(alloc.height) / float(h))
211
212 def do_size_allocate(self, alloc):
213 self.allocation = alloc
214 if self.fit:
215 self.zoom = self.fitzoom()
216 if self.flags() & gtk.REALIZED:
217 self.window.move_resize(*alloc)
218
219 def get_zoomed(self):
220 zoom = self.zoom
221 pz, zbuf = self.zoomed
222 if pz != zoom:
223 w, h = self.get_osize()
224 zbuf = self.pixbuf.scale_simple(int(w * zoom), int(h * zoom), self.interp)
225 self.zoomed = zoom, zbuf
226 return zbuf
227
228 def get_zsize(self):
229 zbuf = self.get_zoomed()
230 return zbuf.get_width(), zbuf.get_height()
231
232 def do_expose_event(self, event):
233 aw, ah = self.get_asize()
234 dw, dh = aw, ah
235 zbuf = self.get_zoomed()
236 zw, zh = self.get_zsize()
237 ox, oy = self.off
238 dx, dy = 0, 0
239 if zw < aw:
240 dx = (aw - zw) / 2
241 dw = zw
242 if zh < ah:
243 dy = (ah - zh) / 2
244 dh = zh
245 gc = self.style.fg_gc[gtk.STATE_NORMAL]
246 self.window.draw_pixbuf(gc, zbuf, ox, oy, dx, dy, dw, dh)
247
248 def set_off(self, off):
249 aw, ah = self.get_asize()
250 zw, zh = self.get_zsize()
251 ox, oy = off
252 ox, oy = int(ox), int(oy)
253 if ox > zw - aw: ox = zw - aw
254 if oy > zh - ah: oy = zh - ah
255 if ox < 0: ox = 0
256 if oy < 0: oy = 0
257 self.off = ox, oy
258 self.queue_draw()
259
260 def set_zoom(self, zoom):
261 if zoom is not None: zoom = float(zoom)
262 aw, ah = self.get_asize()
263 zw, zh = self.get_zsize()
264 dw, dh = zw - aw, zh - ah
265 ox, oy = self.off
266 xa = float(ox) / float(dw) if dw > 0 else 0.5
267 ya = float(oy) / float(dh) if dh > 0 else 0.5
268
269 if zoom is None:
270 self.fit = True
271 self.zoom = self.fitzoom()
272 else:
273 self.fit = False
274 self.zoom = zoom
275
276 zw, zh = self.get_zsize()
277 dw, dh = zw - aw, zh - ah
278 ox = int(xa * dw) if dw > 0 else 0
279 oy = int(ya * dh) if dh > 0 else 0
280 self.set_off((ox, oy))
281gobject.type_register(pageview)
282
304250ff 283class msgproc(object):
c9e2eced
FT
284 def attach(self, reader):
285 self.rd = reader
286 self.msg = gtk.Alignment(0, 0.5, 0, 0)
287 self.hlay = gtk.HBox()
304250ff 288 self.lbl = gtk.Label("")
c9e2eced
FT
289 self.hlay.pack_start(self.lbl)
290 self.lbl.show()
291 self.msg.add(self.hlay)
292 self.hlay.show()
293 self.rd.sbar.pack_start(self.msg)
294 self.msg.show()
304250ff
FT
295 self._prog = None
296
297 def prog(self, p):
03fdcb32
FT
298 if p is not None:
299 if self._prog is None:
300 self._prog = gtk.ProgressBar()
301 self.hlay.pack_start(self._prog, padding=5)
302 self._prog.show()
304250ff 303 self._prog.set_fraction(p)
304250ff
FT
304 elif p is None and self._prog is not None:
305 self.hlay.remove(self._prog)
306 self._prog = None
307
308 def abort(self):
309 self.rd.sbar.remove(self.msg)
310
311class pagefetch(msgproc):
312 def __init__(self, fpage, setcb=None):
313 self.pg = fpage
314 self.setcb = setcb
c9e2eced 315
304250ff
FT
316 def attach(self, reader):
317 super(pagefetch, self).attach(reader)
318 self.lbl.set_text("Fetching page...")
c9e2eced
FT
319 self.pg.notify(self.haspage)
320
321 def haspage(self):
322 if self.rd.pagefetch.cur != self: return False
323 if not self.pg.done:
324 return True
325 if self.pg.val is not None:
326 self.rd.setpage(self.pg.val)
95213fa6
FT
327 if self.setcb is not None:
328 self.setcb(self.pg.val)
c9e2eced
FT
329 self.rd.pagefetch.set(None)
330
304250ff 331class imgfetch(msgproc):
c9e2eced
FT
332 def __init__(self, fimage):
333 self.img = fimage
334 self.upd = False
335 self.error = None
336
337 def attach(self, reader):
304250ff
FT
338 super(imgfetch, self).attach(reader)
339 self.lbl.set_text("Fetching image...")
c9e2eced
FT
340 self.img.notify(self.imgprog)
341
342 def imgprog(self):
343 if self.rd.imgfetch.cur != self: return False
344 if self.img.done:
345 try:
346 img = self.img.val
347 except Exception as e:
348 self.error = str(e)
349 else:
350 self.rd.setimg(img)
351 self.upd = True
352 self.rd.imgfetch.set(None)
353 else:
304250ff 354 self.prog(self.img.prog)
c9e2eced
FT
355 return True
356
357 def abort(self):
358 self.rd.sbar.remove(self.msg)
359 if not self.upd:
360 self.rd.setimg(None)
361 if self.error is not None:
362 self.rd.pagelbl.set_text("Error fetching image: " + self.error)
363
304250ff 364class preload(msgproc):
95213fa6
FT
365 def __init__(self, fpage):
366 self.pg = fpage
367
368 def attach(self, reader):
304250ff
FT
369 super(preload, self).attach(reader)
370 self.lbl.set_text("Fetching next page...")
95213fa6
FT
371 self.pg.notify(self.haspage)
372
373 def haspage(self):
374 if self.rd.preload.cur != self: return False
375 if not self.pg.done: return True
376 if self.pg.val is not None:
377 self.img = self.rd.cache[self.pg.val]
95213fa6
FT
378 self.lbl.set_text("Loading next page...")
379 self.img.notify(self.imgprog)
380 else:
381 self.rd.preload.set(None)
382
383 def imgprog(self):
384 if self.rd.preload.cur != self: return False
385 if self.img.done:
386 self.rd.preload.set(None)
387 else:
304250ff 388 self.prog(self.img.prog)
95213fa6
FT
389 return True
390
391 def abort(self):
392 self.rd.sbar.remove(self.msg)
393
c9e2eced
FT
394class procslot(object):
395 __slots__ = ["cur", "p"]
396 def __init__(self, p):
397 self.cur = None
398 self.p = p
399
400 def set(self, proc):
401 if self.cur is not None:
402 self.cur.abort()
403 self.cur = None
404 if proc is not None:
405 self.cur = proc
406 try:
407 proc.attach(self.p)
408 except:
409 self.cur = None
410 raise
411
32b804f2
FT
412class plistget(future):
413 def __init__(self, node):
414 super(plistget, self).__init__()
415 self.node = node
416
417 def value(self):
418 return list(self.node)
419
420class loadplist(object):
421 def __init__(self, pnode):
422 self.pnode = pnode
423 self.flist = plistget(self.pnode)
424
425 def attach(self, sbox):
426 self.sbox = sbox
427 self.flist.notify(self.haslist)
428
429 def haslist(self):
430 if self.sbox.loadlist.cur != self: return False
431 if not self.flist.done: return True
432 self.sbox.setlist(self.flist.val)
433
434class sbox(gtk.ComboBox):
435 def __init__(self, reader, ptnode):
436 super(sbox, self).__init__()
437 self.rd = reader
438 self.node = ptnode
439 self.pnode, self.pidx = self.node.stack[-1]
440
441 self.bk = gtk.ListStore(str)
442 self.set_model(self.bk)
443 cell = gtk.CellRendererText()
444 self.pack_start(cell, True)
445 self.add_attribute(cell, "text", 0)
446 self.set_active(0)
447
448 self.set_sensitive(False)
d9163efe 449 self.set_focus_on_click(False)
32b804f2
FT
450 self.bk.append([ptnode.name])
451 self.loadlist = procslot(self)
452 self.loadlist.set(loadplist(self.pnode))
453
454 def setlist(self, ls):
455 self.bk.clear()
456 for i, ch in enumerate(ls):
d9163efe 457 self.bk.append(["%i/%i: %s" % (i + 1, len(ls), ch.name)])
32b804f2
FT
458 self.set_active(self.pidx)
459 self.set_sensitive(True)
460 self.connect("changed", self.changed_cb)
461
462 def changed_cb(self, wdg, data=None):
463 self.rd.fetchpage(pageget(self.pnode[self.get_active()]))
464
0b60fcf8
FT
465class profprop(object):
466 def __init__(self, key, default=None):
467 self.key = key
468 self.default = default
469
470 def __get__(self, ins, cls):
471 return ins.profile.props.get(self.key, self.default)
472
473 def __set__(self, ins, val):
474 ins.profile.props[self.key] = val
475 ins.profile.save()
476
477 def __delete__(self, ins):
478 del ins.profile.props[self.key]
479 ins.profile.save()
480
43a12498 481class reader(gtk.Window):
43423668 482 def __init__(self, manga, prof=None):
43a12498
FT
483 super(reader, self).__init__(gtk.WINDOW_TOPLEVEL)
484 self.connect("delete_event", lambda wdg, ev, data=None: False)
485 self.connect("destroy", lambda wdg, data=None: self.quit())
486 self.connect("key_press_event", self.key)
c9e2eced
FT
487 self.cache = pagecache()
488 self.pagefetch = procslot(self)
489 self.imgfetch = procslot(self)
95213fa6 490 self.preload = procslot(self)
43423668 491 self.profile = prof if prof else profile.memmanga(None, None, manga.id)
c9e2eced 492
32b804f2
FT
493 self.manga = manga
494 self.page = None
495 self.sboxes = []
496 self.point = None
497
c9e2eced 498 vlay = gtk.VBox()
43a12498
FT
499 self.pfr = gtk.Frame(None)
500 self.pfr.set_shadow_type(gtk.SHADOW_NONE)
c9e2eced 501 vlay.pack_start(self.pfr)
43a12498 502 self.pfr.show()
32b804f2
FT
503 self.sboxbar = gtk.HBox()
504 algn = gtk.Alignment(0, 0.5, 0, 0)
505 sboxlbl = gtk.Label(self.manga.name + u": ")
506 algn.add(sboxlbl)
507 sboxlbl.show()
508 self.sboxbar.pack_start(algn, False)
509 algn.show()
510 vlay.pack_start(self.sboxbar, False)
511 self.sboxbar.show()
c9e2eced
FT
512 self.sbar = gtk.HBox()
513 self.pagelbl = gtk.Label("")
514 algn = gtk.Alignment(0, 0.5, 0, 0)
515 algn.add(self.pagelbl)
516 self.pagelbl.show()
517 self.sbar.pack_start(algn)
518 algn.show()
519 vlay.pack_end(self.sbar, False)
520 self.sbar.show()
521 self.add(vlay)
522 vlay.show()
43a12498 523
0b60fcf8
FT
524 if self.curpage is not None:
525 self.fetchpage(idpageget(self.manga, self.curpage))
012c4cae
FT
526 else:
527 self.fetchpage(pageget(self.manga))
43a12498
FT
528 self.updtitle()
529
0b60fcf8
FT
530 zmode = profprop("zmode", "fit")
531 curpage = profprop("curpage")
532
c9e2eced
FT
533 def updpagelbl(self):
534 if self.page is None:
535 self.pagelbl.set_text("")
536 else:
537 w, h = self.page.get_osize()
538 self.pagelbl.set_text(u"%s\u00d7%s (%d%%)" % (w, h, int(self.page.zoom * 100)))
539
32b804f2
FT
540 def updsboxes(self, page):
541 nodes = [node for node, idx in page.stack[1:]] + [page]
542 l = min(len(self.sboxes), len(nodes))
543 for i, (pbox, node) in enumerate(zip(self.sboxes, nodes)):
544 if pbox.node != node:
545 l = i
546 break
547 for i in xrange(l, len(self.sboxes)):
548 self.sboxbar.remove(self.sboxes[i])
549 self.sboxes = self.sboxes[:l]
550 for i in xrange(l, len(nodes)):
551 new = sbox(self, nodes[i])
552 self.sboxbar.pack_start(new, False, padding=5)
553 self.sboxes.append(new)
554 new.show()
555
c9e2eced 556 def setimg(self, img):
43a12498
FT
557 if self.page is not None:
558 self.pfr.remove(self.page)
559 self.page = None
c9e2eced
FT
560 if img is not None:
561 self.page = pageview(img)
0b60fcf8
FT
562 if self.zmode == "1":
563 self.page.set_zoom(1)
564 self.page.set_off((0, 0))
43a12498
FT
565 self.pfr.add(self.page)
566 self.page.show()
c9e2eced
FT
567 self.updpagelbl()
568
569 def setpage(self, page):
570 if self.point is not None:
571 self.point = None
572 if page is not None:
0b60fcf8 573 self.curpage = page.idlist()
c9e2eced
FT
574 self.point = ccursor(page, self.cache)
575 self.imgfetch.set(imgfetch(self.cache[page]))
576 else:
577 self.setimg(None)
32b804f2 578 self.updsboxes(page)
c9e2eced 579
95213fa6 580 def fetchpage(self, fpage, setcb=None):
c9e2eced 581 self.imgfetch.set(None)
95213fa6
FT
582 proc = pagefetch(fpage, setcb)
583 self.pagefetch.set(proc)
584 return proc
43a12498
FT
585
586 def updtitle(self):
587 self.set_title(u"Automanga \u2013 " + self.manga.name)
03feea07
FT
588
589 @property
590 def zoom(self):
591 return self.page.zoom
592 @zoom.setter
593 def zoom(self, zoom):
594 self.page.set_zoom(zoom)
c9e2eced 595 self.updpagelbl()
03feea07
FT
596
597 def pan(self, off):
598 ox, oy = self.page.off
599 px, py = off
600 self.page.set_off((ox + px, oy + py))
601
03feea07 602 def key(self, wdg, ev, data=None):
c9e2eced 603 if ev.keyval in [ord('Q'), ord('q')]:
03feea07 604 self.quit()
c9e2eced
FT
605 elif ev.keyval in [65307]:
606 if self.page is not None:
607 self.pagefetch.set(None)
608 self.imgfetch.set(None)
609 if self.page is not None:
610 if ev.keyval in [ord('O'), ord('o')]:
611 self.zoom = 1.0
0b60fcf8 612 self.zmode = "1"
c9e2eced
FT
613 elif ev.keyval in [ord('P'), ord('p')]:
614 self.zoom = None
0b60fcf8 615 self.zmode = "fit"
c9e2eced
FT
616 elif ev.keyval in [ord('[')]:
617 self.zoom = min(self.zoom * 1.25, 3)
618 elif ev.keyval in [ord(']')]:
619 self.zoom /= 1.25
620 elif ev.keyval in [ord('h')]:
621 self.pan((-100, 0))
622 elif ev.keyval in [ord('j')]:
623 self.pan((0, 100))
624 elif ev.keyval in [ord('k')]:
625 self.pan((0, -100))
626 elif ev.keyval in [ord('l')]:
627 self.pan((100, 0))
628 elif ev.keyval in [ord('H')]:
629 self.page.set_off((0, self.page.off[1]))
630 elif ev.keyval in [ord('J')]:
631 self.page.set_off((self.page.off[0], self.page.get_asize()[1]))
632 elif ev.keyval in [ord('K')]:
633 self.page.set_off((self.page.off[1], 0))
634 elif ev.keyval in [ord('L')]:
635 self.page.set_off((self.page.get_asize()[0], self.page.off[1]))
636 if self.point is not None:
637 if ev.keyval in [ord(' ')]:
dcaf33f5
FT
638 if self.page and self.page.off[1] + self.page.get_asize()[1] < self.page.get_zsize()[1]:
639 self.pan((0, self.page.get_asize()[1] - 50))
640 else:
641 self.fetchpage(self.point.next, lambda page: self.preload.set(preload(relpageget(page, False, self.cache))))
c9e2eced 642 elif ev.keyval in [65288]:
dcaf33f5
FT
643 if self.page and self.page.off[1] > 0:
644 self.pan((0, -(self.page.get_asize()[1] - 50)))
645 else:
646 self.fetchpage(self.point.prev, lambda page: self.preload.set(preload(relpageget(page, True, self.cache))))
a133683d
FT
647 elif ev.keyval in [ord('R'), ord('r')]:
648 page = self.point.cur.cur
649 del self.cache[page]
650 self.imgfetch.set(imgfetch(self.cache[page]))
03feea07
FT
651
652 def quit(self):
653 self.hide()
d9bf4bdb 654 gtk.main_quit()
43a12498 655gobject.type_register(reader)