-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
epy.py
executable file
·2279 lines (2052 loc) · 79 KB
/
epy.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""\
Usages:
epy read last epub
epy EPUBFILE read EPUBFILE
epy STRINGS read matched STRINGS from history
epy NUMBER read file from history
with associated NUMBER
Options:
-r print reading history
-d dump epub
-h, --help print short, long help
"""
__version__ = "2021.7.8"
__license__ = "GPL-3.0"
__author__ = "Benawi Adha"
__email__ = "benawiadha@gmail.com"
__url__ = "https://github.com/wustho/epy"
import base64
import curses
import zipfile
import sys
import re
import os
import textwrap
import json
import tempfile
import shutil
import subprocess
import multiprocessing
import xml.etree.ElementTree as ET
from urllib.parse import unquote
from html import unescape
from html.parser import HTMLParser
from difflib import SequenceMatcher as SM
from functools import wraps
try:
import mobi
MOBISUPPORT = True
except ModuleNotFoundError:
MOBISUPPORT = False
if shutil.which("pico2wave") is None\
or shutil.which("play") is None:
TTSSUPPORT = False
else:
TTSSUPPORT = True
SPEAKING = False
# -1 is default terminal fg/bg colors
CFG = {
"DefaultViewer": "auto",
"DictionaryClient": "auto",
"ShowProgressIndicator": True,
"PageScrollAnimation": True,
"MouseSupport": False,
"StartWithDoubleSpread": False,
"TTSSpeed": 1,
"DarkColorFG": 252,
"DarkColorBG": 235,
"LightColorFG": 238,
"LightColorBG": 253,
"Keys": {
"ScrollUp": "k",
"ScrollDown": "j",
"PageUp": "h",
"PageDown": "l",
"HalfScreenUp": "^u",
"HalfScreenDown": "C-d",
"NextChapter": "n",
"PrevChapter": "p",
"BeginningOfCh": "g",
"EndOfCh": "G",
"Shrink": "-",
"Enlarge": "+",
"SetWidth": "=",
"Metadata": "M",
"DefineWord": "d",
"TableOfContents": "t",
"Follow": "f",
"OpenImage": "o",
"RegexSearch": "/",
"ShowHideProgress": "s",
"MarkPosition": "m",
"JumpToPosition": "`",
"AddBookmark": "b",
"ShowBookmarks": "B",
"Quit": "q",
"Help": "?",
"SwitchColor": "c",
"TTSToggle": "!",
"DoubleSpreadToggle": "D"
}
}
STATE = {
"LastRead": "",
"States": {}
}
# default keys
K = {
"ScrollUp": {curses.KEY_UP},
"ScrollDown": {curses.KEY_DOWN},
"PageUp": {curses.KEY_PPAGE, curses.KEY_LEFT},
"PageDown": {curses.KEY_NPAGE, ord(" "), curses.KEY_RIGHT},
"BeginningOfCh": {curses.KEY_HOME},
"EndOfCh": {curses.KEY_END},
"TableOfContents": {9, ord("\t")},
"Follow": {10},
"Quit": {3, 27, 304}
}
WINKEYS = set()
CFGFILE = ""
STATEFILE = ""
COLORSUPPORT = False
SEARCHPATTERN = None
VWR = None
DICT = None
SCREEN = None
JUMPLIST = {}
SHOWPROGRESS = CFG["ShowProgressIndicator"]
MULTIPROC = False if multiprocessing.cpu_count() == 1 else True
ALLPREVLETTERS = []
SUMALLLETTERS = 0
PROC_COUNTLETTERS = None
ANIMATE = None
SPREAD = 1
class Epub:
NS = {
"DAISY": "http://www.daisy.org/z3986/2005/ncx/",
"OPF": "http://www.idpf.org/2007/opf",
"CONT": "urn:oasis:names:tc:opendocument:xmlns:container",
"XHTML": "http://www.w3.org/1999/xhtml",
"EPUB": "http://www.idpf.org/2007/ops"
}
def __init__(self, fileepub):
self.path = os.path.abspath(fileepub)
self.file = zipfile.ZipFile(fileepub, "r")
def get_meta(self):
meta = []
# why self.file.read(self.rootfile) problematic
cont = ET.fromstring(self.file.open(self.rootfile).read())
for i in cont.findall("OPF:metadata/*", self.NS):
if i.text is not None:
meta.append([re.sub("{.*?}", "", i.tag), i.text])
return meta
def initialize(self):
cont = ET.parse(self.file.open("META-INF/container.xml"))
self.rootfile = cont.find(
"CONT:rootfiles/CONT:rootfile",
self.NS
).attrib["full-path"]
self.rootdir = os.path.dirname(self.rootfile)\
+ "/" if os.path.dirname(self.rootfile) != "" else ""
cont = ET.parse(self.file.open(self.rootfile))
# EPUB3
self.version = cont.getroot().get("version")
if self.version == "2.0":
# "OPF:manifest/*[@id='ncx']"
self.toc = self.rootdir\
+ cont.find(
"OPF:manifest/*[@media-type='application/x-dtbncx+xml']",
self.NS
).get("href")
elif self.version == "3.0":
self.toc = self.rootdir\
+ cont.find(
"OPF:manifest/*[@properties='nav']",
self.NS
).get("href")
self.contents = []
self.toc_entries = [[], [], []]
# cont = ET.parse(self.file.open(self.rootfile)).getroot()
manifest = []
for i in cont.findall("OPF:manifest/*", self.NS):
# EPUB3
# if i.get("id") != "ncx" and i.get("properties") != "nav":
if i.get("media-type") != "application/x-dtbncx+xml"\
and i.get("properties") != "nav":
manifest.append([
i.get("id"),
i.get("href")
])
spine, contents = [], []
for i in cont.findall("OPF:spine/*", self.NS):
spine.append(i.get("idref"))
for i in spine:
for j in manifest:
if i == j[0]:
self.contents.append(self.rootdir+unquote(j[1]))
contents.append(unquote(j[1]))
manifest.remove(j)
# TODO: test is break necessary
break
try:
toc = ET.parse(self.file.open(self.toc)).getroot()
# EPUB3
if self.version == "2.0":
navPoints = toc.findall("DAISY:navMap//DAISY:navPoint", self.NS)
elif self.version == "3.0":
navPoints = toc.findall(
"XHTML:body//XHTML:nav[@EPUB:type='toc']//XHTML:a",
self.NS
)
for i in navPoints:
if self.version == "2.0":
src = i.find("DAISY:content", self.NS).get("src")
name = i.find("DAISY:navLabel/DAISY:text", self.NS).text
elif self.version == "3.0":
src = i.get("href")
name = "".join(list(i.itertext()))
src = src.split("#")
try:
idx = contents.index(unquote(src[0]))
except ValueError:
continue
self.toc_entries[0].append(name)
self.toc_entries[1].append(idx)
if len(src) == 2:
self.toc_entries[2].append(src[1])
elif len(src) == 1:
self.toc_entries[2].append("")
except AttributeError:
pass
def get_raw_text(self, chpath):
# using try-except block to catch
# zlib.error: Error -3 while decompressing data: invalid distance too far back
# caused by forking PROC_COUNTLETTERS
while True:
try:
content = self.file.open(chpath).read()
break
except:
continue
return content.decode("utf-8")
def get_img_bytestr(self, impath):
return impath, self.file.read(impath)
def cleanup(self):
return
class Mobi(Epub):
def __init__(self, filemobi):
self.path = os.path.abspath(filemobi)
self.file, _ = mobi.extract(filemobi)
def get_meta(self):
meta = []
# why self.file.read(self.rootfile) problematic
with open(os.path.join(self.rootdir, "content.opf")) as f:
cont = ET.parse(f).getroot()
for i in cont.findall("OPF:metadata/*", self.NS):
if i.text is not None:
meta.append([re.sub("{.*?}", "", i.tag), i.text])
return meta
def initialize(self):
self.rootdir = os.path.join(self.file, "mobi7")
self.toc = os.path.join(self.rootdir, "toc.ncx")
self.version = "2.0"
self.contents = []
self.toc_entries = [[], [], []]
with open(os.path.join(self.rootdir, "content.opf")) as f:
cont = ET.parse(f).getroot()
manifest = []
for i in cont.findall("OPF:manifest/*", self.NS):
# EPUB3
# if i.get("id") != "ncx" and i.get("properties") != "nav":
if i.get("media-type") != "application/x-dtbncx+xml"\
and i.get("properties") != "nav":
manifest.append([
i.get("id"),
i.get("href")
])
spine, contents = [], []
for i in cont.findall("OPF:spine/*", self.NS):
spine.append(i.get("idref"))
for i in spine:
for j in manifest:
if i == j[0]:
self.contents.append(os.path.join(self.rootdir, unquote(j[1])))
contents.append(unquote(j[1]))
manifest.remove(j)
# TODO: test is break necessary
break
with open(self.toc) as f:
toc = ET.parse(f).getroot()
# EPUB3
if self.version == "2.0":
navPoints = toc.findall("DAISY:navMap//DAISY:navPoint", self.NS)
elif self.version == "3.0":
navPoints = toc.findall(
"XHTML:body//XHTML:nav[@EPUB:type='toc']//XHTML:a",
self.NS
)
for i in navPoints:
if self.version == "2.0":
src = i.find("DAISY:content", self.NS).get("src")
name = i.find("DAISY:navLabel/DAISY:text", self.NS).text
elif self.version == "3.0":
src = i.get("href")
name = "".join(list(i.itertext()))
src = src.split("#")
try:
idx = contents.index(unquote(src[0]))
except ValueError:
continue
self.toc_entries[0].append(name)
self.toc_entries[1].append(idx)
if len(src) == 2:
self.toc_entries[2].append(src[1])
elif len(src) == 1:
self.toc_entries[2].append("")
def get_raw_text(self, chpath):
# using try-except block to catch
# zlib.error: Error -3 while decompressing data: invalid distance too far back
# caused by forking PROC_COUNTLETTERS
while True:
try:
with open(chpath) as f:
content = f.read()
break
except:
continue
# return content.decode("utf-8")
return content
def get_img_bytestr(self, impath):
# TODO: test on windows
# if impath "Images/asdf.png" is problematic
with open(os.path.join(self.rootdir, impath), "rb") as f:
src = f.read()
return impath, src
def cleanup(self):
shutil.rmtree(self.file)
return
class Azw3(Epub):
def __init__(self, fileepub):
self.path = os.path.abspath(fileepub)
self.tmpdir, self.tmpepub = mobi.extract(fileepub)
self.file = zipfile.ZipFile(self.tmpepub, "r")
def cleanup(self):
shutil.rmtree(self.tmpdir)
return
class FictionBook:
NS = {
"FB2": "http://www.gribuser.ru/xml/fictionbook/2.0"
}
def __init__(self, filefb):
self.path = os.path.abspath(filefb)
self.file = filefb
def get_meta(self):
desc = self.root.find("FB2:description", self.NS)
alltags = desc.findall("*/*")
return [[re.sub("{.*?}", "", i.tag), " ".join(i.itertext())] for i in alltags]
def initialize(self):
cont = ET.parse(self.file)
self.root = cont.getroot()
self.contents = []
self.toc_entries = [[], [], []]
self.contents = self.root.findall("FB2:body/*", self.NS)
# TODO
for n, i in enumerate(self.contents):
title = i.find("FB2:title", self.NS)
if title is not None:
self.toc_entries[0].append("".join(title.itertext()))
self.toc_entries[1].append(n)
self.toc_entries[2].append("")
def get_raw_text(self, node):
ET.register_namespace("", "http://www.gribuser.ru/xml/fictionbook/2.0")
# sys.exit(ET.tostring(node, encoding="utf8", method="html").decode("utf-8").replace("ns1:",""))
return ET.tostring(node, encoding="utf8", method="html").decode("utf-8").replace("ns1:","")
def get_img_bytestr(self, imgid):
imgid = imgid.replace("#", "")
img = self.root.find("*[@id='{}']".format(imgid))
imgtype = img.get("content-type").split("/")[1]
return imgid+"."+imgtype, base64.b64decode(img.text)
def cleanup(self):
return
class HTMLtoLines(HTMLParser):
para = {"p", "div"}
inde = {"q", "dt", "dd", "blockquote"}
pref = {"pre"}
bull = {"li"}
hide = {"script", "style", "head"}
ital = {"i", "em"}
bold = {"b"}
# hide = {"script", "style", "head", ", "sub}
def __init__(self, sects={""}):
HTMLParser.__init__(self)
self.text = [""]
self.imgs = []
self.ishead = False
self.isinde = False
self.isbull = False
self.ispref = False
self.ishidden = False
self.idhead = set()
self.idinde = set()
self.idbull = set()
self.idpref = set()
self.sects = sects
self.sectsindex = {}
self.initital = []
self.initbold = []
def handle_starttag(self, tag, attrs):
if re.match("h[1-6]", tag) is not None:
self.ishead = True
elif tag in self.inde:
self.isinde = True
elif tag in self.pref:
self.ispref = True
elif tag in self.bull:
self.isbull = True
elif tag in self.hide:
self.ishidden = True
elif tag == "sup":
self.text[-1] += "^{"
elif tag == "sub":
self.text[-1] += "_{"
# NOTE: "img" and "image"
# In HTML, both are startendtag (no need endtag)
# but in XHTML both need endtag
elif tag in {"img", "image"}:
for i in attrs:
if (tag == "img" and i[0] == "src")\
or (tag == "image" and i[0].endswith("href")):
self.text.append("[IMG:{}]".format(len(self.imgs)))
self.imgs.append(unquote(i[1]))
# formatting
elif tag in self.ital:
if len(self.initital) == 0 or len(self.initital[-1]) == 4:
self.initital.append([len(self.text)-1, len(self.text[-1])])
elif tag in self.bold:
if len(self.initbold) == 0 or len(self.initbold[-1]) == 4:
self.initbold.append([len(self.text)-1, len(self.text[-1])])
if self.sects != {""}:
for i in attrs:
if i[0] == "id" and i[1] in self.sects:
# self.text[-1] += " (#" + i[1] + ") "
# self.sectsindex.append([len(self.text), i[1]])
self.sectsindex[len(self.text)-1] = i[1]
def handle_startendtag(self, tag, attrs):
if tag == "br":
self.text += [""]
elif tag in {"img", "image"}:
for i in attrs:
# if (tag == "img" and i[0] == "src")\
# or (tag == "image" and i[0] == "xlink:href"):
if (tag == "img" and i[0] == "src")\
or (tag == "image" and i[0].endswith("href")):
self.text.append("[IMG:{}]".format(len(self.imgs)))
self.imgs.append(unquote(i[1]))
self.text.append("")
# sometimes attribute "id" is inside "startendtag"
# especially html from mobi module (kindleunpack fork)
if self.sects != {""}:
for i in attrs:
if i[0] == "id" and i[1] in self.sects:
# self.text[-1] += " (#" + i[1] + ") "
self.sectsindex[len(self.text)-1] = i[1]
def handle_endtag(self, tag):
if re.match("h[1-6]", tag) is not None:
self.text.append("")
self.text.append("")
self.ishead = False
elif tag in self.para:
self.text.append("")
elif tag in self.hide:
self.ishidden = False
elif tag in self.inde:
if self.text[-1] != "":
self.text.append("")
self.isinde = False
elif tag in self.pref:
if self.text[-1] != "":
self.text.append("")
self.ispref = False
elif tag in self.bull:
if self.text[-1] != "":
self.text.append("")
self.isbull = False
elif tag in {"sub", "sup"}:
self.text[-1] += "}"
elif tag in {"img", "image"}:
self.text.append("")
# formatting
elif tag in self.ital:
if len(self.initital[-1]) == 2:
self.initital[-1] += [len(self.text)-1, len(self.text[-1])]
elif len(self.initital[-1]) == 4:
self.initital[-1][2:4] = [len(self.text)-1, len(self.text[-1])]
elif tag in self.bold:
if len(self.initbold[-1]) == 2:
self.initbold[-1] += [len(self.text)-1, len(self.text[-1])]
elif len(self.initbold[-1]) == 4:
self.initbold[-1][2:4] = [len(self.text)-1, len(self.text[-1])]
def handle_data(self, raw):
if raw and not self.ishidden:
if self.text[-1] == "":
tmp = raw.lstrip()
else:
tmp = raw
if self.ispref:
line = unescape(tmp)
else:
line = unescape(re.sub(r"\s+", " ", tmp))
self.text[-1] += line
if self.ishead:
self.idhead.add(len(self.text)-1)
elif self.isbull:
self.idbull.add(len(self.text)-1)
elif self.isinde:
self.idinde.add(len(self.text)-1)
elif self.ispref:
self.idpref.add(len(self.text)-1)
def get_lines(self, width=0):
text, sect = [], {}
formatting = {
"italic": [],
"bold": []
}
tmpital = []
for i in self.initital:
# handle uneven markup
# like <i> but no </i>
if len(i) == 4:
if i[0] == i[2]:
tmpital.append([i[0], i[1], i[3]-i[1]])
elif i[0] == i[2]-1:
tmpital.append([i[0], i[1], len(self.text[i[0]])-i[1]])
tmpital.append([i[2], 0, i[3]])
elif i[2]-i[0] > 1:
tmpital.append([i[0], i[1], len(self.text[i[0]])-i[1]])
for j in range(i[0]+1, i[2]):
tmpital.append([j, 0, len(self.text[j])])
tmpital.append([i[2], 0, i[3]])
tmpbold = []
for i in self.initbold:
if len(i) == 4:
if i[0] == i[2]:
tmpbold.append([i[0], i[1], i[3]-i[1]])
elif i[0] == i[2]-1:
tmpbold.append([i[0], i[1], len(self.text[i[0]])-i[1]])
tmpbold.append([i[2], 0, i[3]])
elif i[2]-i[0] > 1:
tmpbold.append([i[0], i[1], len(self.text[i[0]])-i[1]])
for j in range(i[0]+1, i[2]):
tmpbold.append([j, 0, len(self.text[j])])
tmpbold.append([i[2], 0, i[3]])
if width == 0:
return self.text
for n, i in enumerate(self.text):
startline = len(text)
# findsect = re.search(r"(?<= \(#).*?(?=\) )", i)
# if findsect is not None and findsect.group() in self.sects:
# i = i.replace(" (#" + findsect.group() + ") ", "")
# # i = i.replace(" (#" + findsect.group() + ") ", " "*(5+len(findsect.group())))
# sect[findsect.group()] = len(text)
if n in self.sectsindex.keys():
sect[self.sectsindex[n]] = len(text)
if n in self.idhead:
text += [i.rjust(width//2 + len(i)//2)] + [""]
formatting["bold"] += [[j, 0, len(text[j])] for j in range(startline, len(text))]
elif n in self.idinde:
text += [
" "+j for j in textwrap.wrap(i, width - 3)
] + [""]
elif n in self.idbull:
tmp = textwrap.wrap(i, width - 3)
text += [
" - "+j if j == tmp[0] else " "+j for j in tmp
] + [""]
elif n in self.idpref:
tmp = i.splitlines()
wraptmp = []
for line in tmp:
wraptmp += [j for j in textwrap.wrap(line, width - 6)]
text += [" "+j for j in wraptmp] + [""]
else:
text += textwrap.wrap(i, width) + [""]
# TODO: inline formats for indents
endline = len(text) # -1
tmp_filtered = [j for j in tmpital if j[0] == n]
for j in tmp_filtered:
tmp_count = 0
# for k in text[startline:endline]:
for k in range(startline, endline):
if n in self.idbull|self.idinde:
if tmp_count <= j[1]:
tmp_start = [k, j[1]-tmp_count+3]
if tmp_count <= j[1]+j[2]:
tmp_end = [k, j[1]+j[2]-tmp_count+3]
tmp_count += len(text[k]) - 2
else:
if tmp_count <= j[1]:
tmp_start = [k, j[1]-tmp_count]
if tmp_count <= j[1]+j[2]:
tmp_end = [k, j[1]+j[2]-tmp_count]
tmp_count += len(text[k]) + 1
if tmp_start[0] == tmp_end[0]:
formatting["italic"].append(tmp_start + [tmp_end[1]-tmp_start[1]])
elif tmp_start[0] == tmp_end[0]-1:
formatting["italic"].append(tmp_start + [len(text[tmp_start[0]])-tmp_start[1]+1])
formatting["italic"].append([tmp_end[0], 0, tmp_end[1]])
# elif tmp_start[0]-tmp_end[1] > 1:
else:
formatting["italic"].append(tmp_start + [len(text[tmp_start[0]])-tmp_start[1]+1])
for l in range(tmp_start[0]+1, tmp_end[0]):
formatting["italic"].append([l, 0, len(text[l])])
formatting["italic"].append([tmp_end[0], 0, tmp_end[1]])
tmp_filtered = [j for j in tmpbold if j[0] == n]
for j in tmp_filtered:
tmp_count = 0
# for k in text[startline:endline]:
for k in range(startline, endline):
if n in self.idbull|self.idinde:
if tmp_count <= j[1]:
tmp_start = [k, j[1]-tmp_count+3]
if tmp_count <= j[1]+j[2]:
tmp_end = [k, j[1]+j[2]-tmp_count+3]
tmp_count += len(text[k]) - 2
else:
if tmp_count <= j[1]:
tmp_start = [k, j[1]-tmp_count]
if tmp_count <= j[1]+j[2]:
tmp_end = [k, j[1]+j[2]-tmp_count]
tmp_count += len(text[k]) + 1
if tmp_start[0] == tmp_end[0]:
formatting["bold"].append(tmp_start + [tmp_end[1]-tmp_start[1]])
elif tmp_start[0] == tmp_end[0]-1:
formatting["bold"].append(tmp_start + [len(text[tmp_start[0]])-tmp_start[1]+1])
formatting["bold"].append([tmp_end[0], 0, tmp_end[1]])
# elif tmp_start[0]-tmp_end[1] > 1:
else:
formatting["bold"].append(tmp_start + [len(text[tmp_start[0]])-tmp_start[1]+1])
for l in range(tmp_start[0]+1, tmp_end[0]):
formatting["bold"].append([l, 0, len(text[l])])
formatting["bold"].append([tmp_end[0], 0, tmp_end[1]])
return text, self.imgs, sect, formatting
class Board:
MAXCHUNKS = 32000-2 # lines
def __init__(self, totlines, width):
self.chunks = [self.MAXCHUNKS*(i+1)-1 for i in range(totlines // self.MAXCHUNKS)]
self.chunks += [] if totlines % self.MAXCHUNKS == 0 else [totlines % self.MAXCHUNKS + (0 if self.chunks == [] else self.chunks[-1])] # -1
self.pad = curses.newpad(min([self.MAXCHUNKS+2, totlines]), width)
self.pad.keypad(True)
# self.current_chunk = 0
self.y = 0
self.width = width
def feed(self, textlist):
self.text = textlist
def feed_format(self, formatting):
self.formatting = formatting
def format(self):
chunkidx = self.find_chunkidx(self.y)
start_chunk = 0 if chunkidx == 0 else self.chunks[chunkidx-1]+1
end_chunk = self.chunks[chunkidx]
# if y in range(start_chunk, end_chunk+1):
for i in [j for j in self.formatting["italic"] if start_chunk <= j[0] and j[0] <= end_chunk]:
try:
self.pad.chgat(i[0] % self.MAXCHUNKS, i[1], i[2], SCREEN.getbkgd()|curses.A_ITALIC)
except:
pass
for i in [j for j in self.formatting["bold"] if start_chunk <= j[0] and j[0] <= end_chunk]:
try:
self.pad.chgat(i[0] % self.MAXCHUNKS, i[1], i[2], SCREEN.getbkgd()|curses.A_BOLD)
except:
pass
def getch(self):
return self.pad.getch()
def bkgd(self, bg):
self.pad.bkgd(SCREEN.getbkgd())
def find_chunkidx(self, y):
for n, i in enumerate(self.chunks):
if y <= i:
return n
def paint_text(self, chunkidx=0):
self.pad.clear()
start_chunk = 0 if chunkidx == 0 else self.chunks[chunkidx-1]+1
end_chunk = self.chunks[chunkidx]
for n, i in enumerate(self.text[start_chunk:end_chunk+1]):
if re.search("\\[IMG:[0-9]+\\]", i):
self.pad.addstr(n, self.width//2 - len(i)//2 + 1, i, curses.A_REVERSE)
else:
self.pad.addstr(n, 0, i)
# chapter suffix
ch_suffix = "***" # "\u3064\u3065\u304f" つづく
try:
self.pad.addstr(n+1, (self.width - len(ch_suffix))//2 + 1, ch_suffix)
except curses.error:
pass
# if chunkidx < len(self.chunks)-1:
# try:
# self.pad.addstr(self.MAXCHUNKS+1, (self.width - len(ch_suffix))//2 + 1, ch_suffix)
# except curses.error:
# pass
def chgat(self, y, x, n, attr):
chunkidx = self.find_chunkidx(y)
start_chunk = 0 if chunkidx == 0 else self.chunks[chunkidx-1]+1
end_chunk = self.chunks[chunkidx]
if y in range(start_chunk, end_chunk+1):
self.pad.chgat(y % self.MAXCHUNKS, x, n, attr)
def getbkgd(self):
return self.pad.getbkgd()
def refresh(self, y, b, c, d, e, f):
chunkidx = self.find_chunkidx(y)
if chunkidx != self.find_chunkidx(self.y):
self.paint_text(chunkidx)
self.y = y
self.format()
# TODO: not modulo by self.MAXCHUNKS but self.pad.height
self.pad.refresh(y % self.MAXCHUNKS, b, c, d, e, f)
self.y = y
def text_win(textfunc):
@wraps(textfunc)
def wrapper(*args, **kwargs):
rows, cols = SCREEN.getmaxyx()
hi, wi = rows - 4, cols - 4
Y, X = 2, 2
textw = curses.newwin(hi, wi, Y, X)
if COLORSUPPORT:
textw.bkgd(SCREEN.getbkgd())
title, raw_texts, key = textfunc(*args, **kwargs)
if len(title) > cols-8:
title = title[:cols-8]
texts = []
for i in raw_texts.splitlines():
texts += textwrap.wrap(i, wi - 6, drop_whitespace=False)
textw.box()
textw.keypad(True)
textw.addstr(1, 2, title)
textw.addstr(2, 2, "-"*len(title))
key_textw = 0
totlines = len(texts)
pad = curses.newpad(totlines, wi - 2)
if COLORSUPPORT:
pad.bkgd(SCREEN.getbkgd())
pad.keypad(True)
for n, i in enumerate(texts):
pad.addstr(n, 0, i)
y = 0
textw.refresh()
pad.refresh(y, 0, Y+4, X+4, rows - 5, cols - 6)
padhi = rows - 8 - Y
while key_textw not in K["Quit"]|key:
if key_textw in K["ScrollUp"] and y > 0:
y -= 1
elif key_textw in K["ScrollDown"] and y < totlines - hi + 6:
y += 1
elif key_textw in K["PageUp"]:
y = pgup(y, padhi)
elif key_textw in K["PageDown"]:
y = pgdn(y, totlines, padhi)
elif key_textw in K["BeginningOfCh"]:
y = 0
elif key_textw in K["EndOfCh"]:
y = pgend(totlines, padhi)
elif key_textw in WINKEYS - key:
textw.clear()
textw.refresh()
return key_textw
pad.refresh(y, 0, 6, 5, rows - 5, cols - 5)
key_textw = textw.getch()
textw.clear()
textw.refresh()
return
return wrapper
def choice_win(allowdel=False):
def inner_f(listgen):
@wraps(listgen)
def wrapper(*args, **kwargs):
rows, cols = SCREEN.getmaxyx()
hi, wi = rows - 4, cols - 4
Y, X = 2, 2
chwin = curses.newwin(hi, wi, Y, X)
if COLORSUPPORT:
chwin.bkgd(SCREEN.getbkgd())
title, ch_list, index, key = listgen(*args, **kwargs)
if len(title) > cols-8:
title = title[:cols-8]
chwin.box()
chwin.keypad(True)
chwin.addstr(1, 2, title)
chwin.addstr(2, 2, "-"*len(title))
if allowdel:
chwin.addstr(3, 2, "HINT: Press 'd' to delete.")
key_chwin = 0
totlines = len(ch_list)
chwin.refresh()
pad = curses.newpad(totlines, wi - 2)
if COLORSUPPORT:
pad.bkgd(SCREEN.getbkgd())
pad.keypad(True)
padhi = rows - 5 - Y - 4 + 1 - (1 if allowdel else 0)
# padhi = rows - 5 - Y - 4 + 1 - 1
y = 0
if index in range(padhi//2, totlines - padhi//2):
y = index - padhi//2 + 1
span = []
for n, i in enumerate(ch_list):
# strs = " " + str(n+1).rjust(d) + " " + i[0]
strs = " " + i
strs = strs[0:wi-3]
pad.addstr(n, 0, strs)
span.append(len(strs))
countstring = ""
while key_chwin not in K["Quit"]|key:
if countstring == "":
count = 1
else:
count = int(countstring)
if key_chwin in range(48, 58): # i.e., k is a numeral
countstring = countstring + chr(key_chwin)
else:
if key_chwin in K["ScrollUp"] or key_chwin in K["PageUp"]:
index -= count
if index < 0:
index = 0
elif key_chwin in K["ScrollDown"] or key_chwin in K["PageDown"]:
index += count
if index + 1 >= totlines:
index = totlines - 1
elif key_chwin in K["Follow"]:
chwin.clear()
chwin.refresh()
return None, index, None
# elif key_chwin in K["PageUp"]:
# index -= 3
# if index < 0:
# index = 0
# elif key_chwin in K["PageDown"]:
# index += 3
# if index >= totlines:
# index = totlines - 1
elif key_chwin in K["BeginningOfCh"]:
index = 0
elif key_chwin in K["EndOfCh"]:
index = totlines - 1
elif key_chwin == ord("D") and allowdel:
return None, (0 if index == 0 else index-1), index
# chwin.redrawwin()
# chwin.refresh()
elif key_chwin == ord("d") and allowdel:
resk, resp, _ = choice_win()(
lambda: ("Delete '{}'?".format(
ch_list[index]
), ["(Y)es", "(N)o"], 0, {ord("n")})
)()
if resk is not None:
key_chwin = resk
continue
elif resp == 0:
return None, (0 if index == 0 else index-1), index
chwin.redrawwin()
chwin.refresh()
elif key_chwin in {ord(i) for i in ["Y", "y", "N", "n"]}\
and ch_list == ["(Y)es", "(N)o"]:
if key_chwin in {ord("Y"), ord("y")}:
return None, 0, None
else:
return None, 1, None
elif key_chwin in WINKEYS - key:
chwin.clear()
chwin.refresh()
return key_chwin, index, None
countstring = ""
while index not in range(y, y+padhi):
if index < y:
y -= 1
else:
y += 1
for n in range(totlines):
att = curses.A_REVERSE if index == n else curses.A_NORMAL
pre = ">>" if index == n else " "
pad.addstr(n, 0, pre)
pad.chgat(n, 0, span[n], pad.getbkgd() | att)
pad.refresh(y, 0, Y+4+(1 if allowdel else 0), X+4, rows - 5, cols - 6)
# pad.refresh(y, 0, Y+5, X+4, rows - 5, cols - 6)
key_chwin = chwin.getch()
if key_chwin == curses.KEY_MOUSE:
mouse_event = curses.getmouse()
if mouse_event[4] == curses.BUTTON4_PRESSED:
key_chwin = list(K["ScrollUp"])[0]
elif mouse_event[4] == 2097152:
key_chwin = list(K["ScrollDown"])[0]
elif mouse_event[4] == curses.BUTTON1_DOUBLE_CLICKED:
if mouse_event[2] >= 6 and mouse_event[2] < rows-4\
and mouse_event[2] < 6+totlines:
index = mouse_event[2]-6+y
key_chwin = list(K["Follow"])[0]
elif mouse_event[4] == curses.BUTTON1_CLICKED\
and mouse_event[2] >= 6 and mouse_event[2] < rows-4\
and mouse_event[2] < 6+totlines:
if index == mouse_event[2]-6+y:
key_chwin = list(K["Follow"])[0]
continue
index = mouse_event[2]-6+y
elif mouse_event[4] == curses.BUTTON3_CLICKED:
key_chwin = list(K["Quit"])[0]
chwin.clear()
chwin.refresh()
return None, None, None
return wrapper
return inner_f
def show_loader(scr):
scr.clear()
rows, cols = scr.getmaxyx()
scr.addstr((rows-1)//2, (cols-1)//2, "\u231B")
# scr.addstr(((rows-2)//2)+1, (cols-len(msg))//2, msg)
scr.refresh()