forked from M4rtinK/mieru
/
manga.py
560 lines (471 loc) · 17.3 KB
/
manga.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# -*- coding: utf-8 -*-
"""a Mieru class representing a single manga / comic book file/folder
- this is driven by the storage format - it can really be a single chapter,
or a whole volume if all page images are in a single file or folder
"""
import os
import time
import re
#import manga as mangaModule
import container as containerModule
import page_cache
def name2PrettyName(name, path=None):
"""convert a manga name, eq. taken from its filename
to a nicer looking string
* replace _ with whitespace
* remove file extensions"""
# TODO: if path is provided check it the target is file or folder
# and use this information accordingly
name, extension = os.path.splitext(name)
# remove text in square braces
p = re.compile('(\s)*\[(\w)*\]', re.DOTALL)
name = p.sub('', name)
# replace _ with whitespace
name = re.sub('_', ' ', name)
# assure there is a space before numbers
name = re.sub(r"([a-zA-Z])([0-9])", r"\1 \2", name)
return name
def path2prettyName(path):
(path,name) = os.path.split(path)
return name2PrettyName(name)
class Manga:
def __init__(self, mieru, path=None, startOnPage=0, load=True, loadNotify=True, pageShownNotify=False):
self.mieru = mieru
self.fitMode = self.mieru.get('fitMode', 'original')
self.mieru.watch('fitMode', self.onFitModeChanged)
self.path = path
self.name = ""
self.pages = []
self.container = None
self.activePageId = None
self.nextArmed = False
self.previousArmed = False
self.previewBox = None
self.previewBoxStartingPoint = (0,0)
self.loadNotify = loadNotify
self.scale = 1.0
self.shiftX = 0.0
self.shiftY = 0.0
"""in case we get a manga instance just to grag some pages,
we don't want it to connect the page shown notify callback"""
if pageShownNotify:
# connect the page turn complete callback
self.mieru.gui.pageShownNotify(self._pageShownCB)
# get page cache object
self.cache = page_cache.PageCache(3)
self.cacheUpdate = None
if path and load:
self.name = self._nameFromPath(path)
"""
NOTE: for some reason, when not using this variable but just
if self.load(path,startOnPage):
the following code gets executed 2-4 times
"""
if self.load(path,startOnPage):
if loadNotify:
self.mieru.notify('<b>%s</b> loaded on page <b>%d</b>' % (self.getPrettyName(), self.ID2PageNumber(startOnPage)))
#print '<b>%s</b> loaded on page <b>%d</b>' % (self.name, self.ID2PageNumber(startOnPage))
else:
if loadNotify:
self.mieru.gui.newMangaLoaded(self) # notify the GUI
self.mieru.notify('<b>%s</b> loading failed' % self.getPrettyName())
def getName(self):
return self.name
def setName(self, name):
self.name = name
def getPath(self):
return self.path
def getScale(self):
return self.scale
def getShiftX(self):
return self.shiftX
def getShiftY(self):
return self.shiftY
def getState(self):
"""save current state to a dictionary"""
state = {}
state['path'] = self.path
state['pageNumber'] = self.activePageId
state['pageCount'] = len(self.pages) # for displaying in the history list
scale = self.mieru.gui.getScale()
if scale != None:
state['scale'] = scale
upperLeftShift = self.mieru.gui.getUpperLeftShift()
if upperLeftShift != None:
state['upperLeftShift'] = upperLeftShift
return state
def setState(self, state):
"""restore from the state dictionary"""
pageNumber = state.get('pageNumber',0)
if pageNumber == None:
pageNumber = 0
self.scale = state.get('scale',1.0)
(self.shiftX, self.shiftY) = state.get('upperLeftShift',(0.0,0.0))
path = state.get('path',None)
if path:
self.name = self._nameFromPath(path)
if self.load(path, pageNumber):
self.mieru.notify('<b>%s</b> restored to page <b>%d</b>' % (self.getPrettyName(), self.ID2PageNumber(self.activePageId)))
else:
self.mieru.notify('<b>%s</b> restore failed' % self.getPrettyName())
def load(self, path, pageNumber=0):
"""try to load manga from the given path"""
print "manga: loading from path: %s" % path
self.path = path
start = time.clock()
container = containerModule.from_path(path)
duration = (1000 * (time.clock() - start))
if container: # was a container created successfully ?
print("container created in %1.2f ms" % duration)
self.container = container
self.pages = self.container.getImageFileList()
if pageNumber == None: # None means we don't show a page yet
return True # nothing to go wrong here :)
else:
status = self.gotoPageId(pageNumber) # return if the first-selected page loaded successfully
return status
else:
print "manga: container initialization failed"
return False
def close(self):
# flush cache
self.cache.flush()
# remove any possible pending previews
self.mieru.gui.hidePreview()
def getContainer(self):
return self.container
def ID2PageNumber(self, id):
"""guess page number from id"""
if id == None:
return -1
if id >= 0:
return id + 1
else: # negative addressing
return (len(self.pages) + id + 1)
def PageNumber2ID(self, pageNumber):
"""convert page number to id"""
if pageNumber <= 0 or pageNumber > self.getMaxPageNumber():
return None
else:
return pageNumber-1
def idExistst(self, id):
if self.pages:
if id < 0 or id > (len(self.pages)-1) or id == None: # None indicates initial active id state
print "page id out of range:", id
return False
else:
return True
def getPageById(self, id, fitOnStart=True):
"""return a Page instance together with its id in a tuple"""
t1 = time.clock()
result = self.container.getImageFileById(id)
t2 = time.clock()
if result:
# correct id is returned for negative addressing (id=-1, etc.)
(file,id) = result
page = self.mieru.gui.getPage(file, self.mieru, fitOnStart=fitOnStart)
t3 = time.clock()
# TODO: reimplement this
if self.mieru.get('debugPageLoading', False):
(w,h) = page.getSize()
now = time.clock()
print("Page completely loaded in %1.2f ms" % (1000 * (now - t1)))
print("* loading from container: %1.2f ms" % (1000 * (t2 - t1)))
print("* loading to pixbuf & to page & cleanup: %1.2f ms" % (1000 * (t3 - t2)))
# print("* initializing page object with pixbuf: %1.2f ms" % (1000 * (t4 - t3)))
# print("* closing file and deleting pixbuf: %1.2f ms" % (1000 * (t5 - t4)))
print("- image resolution: %d x %d" % (w, h))
print("- image filename: %s" % self.container.getImageFilenameById(id))
return (page, id)
else:
print "manga: page not found, id: ", id
return None
def getActivePageId(self):
return self.activePageId
def setActivePageId(self, id):
"""set active page id to a given value"""
#TODO: support negative indexing
if id >= 0 and id <= self.getMaxId():
self.activePageId = id
def getActivePageNumber(self):
"""get the id of the currently active page"""
return self.ID2PageNumber(self.getActivePageId())
def getMaxId(self):
if self.pages:
return (len(self.pages)-1)
else:
return None
def getMaxPageNumber(self):
maxId = self.getMaxId()
if maxId == None:
return 0
else:
return self.ID2PageNumber(maxId)
def gotoPageId(self, id, direction=1):
"""go to the the page with the given id"""
if id < 0: # -1 = last page, etc.
currentId = ( self.getMaxId() - id - 1 )
else:
currentId = id
print("###################")
print("switching to page id: %d rel id: %d" % (currentId, id))
print("###################")
self.activePageId = currentId
# get page for the given id
newPage = None
cacheThisPage = False
# check if the page is already cached
page = self.cache.get(currentId, None) # try to load from cache
if page: # page was in cache
newPage = page
print "# page from cache"
else: # not in cache, load from storage
newPageQuery = self.getPageById(currentId)
print "# page from storage"
if newPageQuery:
(newPage,newPageId) = newPageQuery
cacheThisPage = True
if newPage:
# cache next/previous pages + this page (if needed)
if cacheThisPage:
self.cacheUpdate = (id, newPage, direction)
else:
self.cacheUpdate = (id, None, direction)
# show the page
newPage.activate()
newPage.show()
self.mieru.gui.showPage(newPage, self, currentId)
# increment page count
self.mieru.stats.incrementPageCount()
# success
return True
else:
print "switching to page failed, id: ", currentId
# enable to skip invalid pages that have valid id
return False
def next(self):
"""go one page forward"""
self._disarm("previous")
if self.nextArmed: # should we load next manga in folder after this press ?
(isTrue, path) = self.nextArmed # get the path
self._hidePreview()
self.mieru.openManga(path, 0) # open it on first page
return(False, "loadingNext") # done
currentId = self.activePageId
if currentId == None:
return(False,"Error")
nextId = currentId + 1
# sanity check the id
if nextId < len(self.pages):
self.gotoPageId(nextId, +1)
return(True, nextId)
else:
print("manga: end reached")
if self.mieru.continuousReading:
nextMangaPath = self.getNextMangaPath()
if nextMangaPath:
(folder, tail) = os.path.split(nextMangaPath)
name = name2PrettyName(tail)
self.mieru.notify('this is the <b>last</b> page,\n<u>press again</u> to load:\n<b>%s</b>' % name)
self.nextArmed = (True, nextMangaPath)
#self._showPreview(nextMangaPath, "next")
return(False, "press4Next")
else:
self.mieru.notify('this is the <b>last</b> page,\n there is no <i>previous</i> to load')
return(False, "noNext")
else:
self.mieru.notify('this is the <b>last</b> page')
return(False, "thisIsLastPage")
def previous(self):
"""go one page back"""
self._disarm("next")
if self.previousArmed: # should we load next manga in folder after this press ?
(isTrue, path) = self.previousArmed # get the path
self._hidePreview()
self.mieru.openManga(path, -1) # open it on last page
return(False, "loadingPrev") # done
currentId = self.activePageId
if currentId == None:
return(False,"Error")
prevId = currentId - 1
# sanity check the id
if prevId >= 0:
self.gotoPageId(prevId, -1)
return(True,prevId)
else:
print("manga: start reached") # TODO: display a notification & go to next archive/folder (?)
if self.mieru.continuousReading:
previousMangaPath = self.getPrevMangaPath()
if previousMangaPath:
# get a preview
(folder, tail) = os.path.split(previousMangaPath)
name = name2PrettyName(tail)
self.mieru.notify('this is the <b>first</b> page,\n <u>press again</u> to load:\n<b>%s</b>' % name)
self.previousArmed = (True, previousMangaPath)
#self._showPreview(previousMangaPath, "previous")
return(False, "press4Prev")
else:
self.mieru.notify('this is the <b>first</b> page,\n there is no <i>previous</i> to load')
return(False, "noPrev")
else:
self.mieru.notify('this is the <b>first</b> page')
return(False, "thisIsFirstPage")
def getPrettyName(self):
"""get a pretty name of this manga instance"""
return name2PrettyName(self.name)
def onFitModeChanged(self, key, value, oldValue):
# notify all pages that the fit mode has changed
page = self.mieru.gui.getCurrentPage()
if page:
page.setFitMode(value)
def getNeighborPaths(self):
prevPath = None
nextPath = None
path = self.path
if path:
(folderPath, tail) = os.path.split(path)
folderContent = os.listdir(folderPath)
folderContent.sort()
maxId = len(folderContent)-1
if tail in folderContent: # just to be sure
id = folderContent.index(tail)
prevId = id-1
nextId = id+1
if prevId >= 0:
prevPath = os.path.join(folderPath,folderContent[prevId])
if nextId <= maxId:
nextPath = os.path.join(folderPath,folderContent[nextId])
return (prevPath, nextPath)
def getPrevMangaPath(self):
(prevPath,nextPath) = self.getNeighborPaths()
if prevPath:
containerModule.testPath(prevPath)
return prevPath
else:
print "manga: previous path uses unsupported format:\n%s" % prevPath
return False
return prevPath
def getNextMangaPath(self):
(prevPath,nextPath) = self.getNeighborPaths()
if nextPath:
containerModule.testPath(nextPath)
return nextPath
else:
print "manga: next path uses unsupported format:\n%s" % nextPath
return False
return nextPath
def getPrevisousMangaStartID(self):
return -1
def getNextMangaStartID(self):
return 0
def _nameFromPath(self,path):
(tail,name) = os.path.split(path)
return name
def _getTitleText(self):
"""return a string suitable for window header"""
name = self.getName()
pageNumber = self.getActivePageNumber()
maxPages = self.getMaxPageNumber()
return "%d/%d %s" % (pageNumber, maxPages, name)
def _pageShownCB(self):
self._updateTitleText()
if self.cacheUpdate:
(id, page, direction) = self.cacheUpdate
self.mieru.gui.idleAdd(self._cacheAround, id, page, direction)
self.cacheUpdate = None
# self.mieru.gui.statusReport()
def _updateTitleText(self):
"""update the title text on the mieru window (and possibly elswhere)"""
title = self._getTitleText()
self.mieru.gui.setWindowTitle(title)
def _showPreview(self, path, type):
pass
# def _showPreview(self, path, type):
# # decide page number and direction
# if type == "previous":
# pageId = -1
# direction = type
# onPressAction = self.previous
# else: # type == "next"
# pageId = 0
# direction = type
# onPressAction = self.next
#
# # get the page
# manga = mangaModule.Manga(self.mieru, path, load=True, loadNotify=False, startOnPage=None, pageShownNotify=False)
# if manga: # only continue if the next manga was successfully loaded
# query = manga.getPageById(pageId, fitOnStart=False)
# if query:
# (page, id) = query
# self.mieru.gui.showPreview(page, direction, onPressAction)
def _hidePreview(self):
self.mieru.gui.hidePreview()
def _disarm(self,type):
"""a next/previous button is armed when it loads next/previous manga after pressing
calling this method disarms the button"""
# hide any previews
self._hidePreview()
if type == "previous":
self.previousArmed = False
elif type == "next":
self.nextArmed = False
def _cacheAround(self, id, page, direction):
"""cache pages around the current one"""
if id < 0: # -1 = last page, etc.
id = (self.getMaxId() - id + 1)
# get possible previous and nex page ids
pId = id - 1
nId = id + 1
# cache previous (if available)
if pId >= 0:
self._cachePageById(pId, direction)
# cache current (if needed)
if page:
self._cachePage(page, id, direction)
# cache next (if available)
if nId <= self.getMaxId():
self._cachePageById(nId, direction)
self.cache.statusReport()
def _cachePageById(self, id, direction):
"""check if the page already contains page with similar id,
if it doesnt add the page to cache"""
if not self.cache.has(id):
query = self.getPageById(id, fitOnStart=False)
if query:
(page, id) = query
self._cachePage(page, id, direction)
def _cachePage(self, page, id, direction):
"""add a page to cache under an id"""
self.cache.add(page, id, direction)
# def _transition(self, direction):
# """replace the currently open manga with the previewed one"""
#
# alpha = clutter.LINEAR
# transition = clutter.Score()
# minimizeTl = clutter.Timeline(duration=300)
# maximizeTl = clutter.Timeline(duration=300)
# bgInTl = clutter.Timeline(duration=300)
# bgOutTl = clutter.Timeline(duration=300)
#
# # transform currently visible page to a preview
# self.activePage.deactivate()
#
# (pBoxY,pBoxX,pBoxShownX,pBoxSide,pBoxInSide,border) = self._getPBoxCoords(type)
#
# (tw,th) = self.activePage.get_size()
# wf = float(pBoxInSide)/tw
# hf = float(pBoxInSide)/th
# if tw >= th:
# self.activePage.animate_with_timeline(minimizeTl, alpha, "width", tw*wf, "height", th*wf)
# else:
# self.activePage.animate_with_timeline(minimizeTl, alpha, "width", tw*hf, "height", th*hf)
# self.activePage.animate_with_timeline(minimizeTl, alpha, "x", ,"y", )
# (tw,th) = thumbnail.get_size()
# print (tw,th)
# thumbnail.move_by(border+(pBoxInSide-tw)/2.0,border+(pBoxInSide-th)/2.0)
# possible eye candy manga to manga transition
# show a yellow background behind it
# hide both the preview and background
# hide the background of the new page preview
# maximize the new page
# replace this manga instance by the new one