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