forked from dsanson/termpdf.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtermpdf.py
executable file
·1860 lines (1590 loc) · 57.3 KB
/
termpdf.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
# vim:fileencoding=utf-8
"""\
Usage:
termpdf.py [options] example.pdf
Options:
-p n, --page-number n : open to page n
-f n, --first-page n : set logical page number for page 1 to n
--citekey key : associate file with bibtex citekey
-o, --open citekey : open file associated with bibtex entry with citekey
--nvim-listen-address path : path to nvim msgpack server
--ignore-cache : ignore saved settings for files
-v, --version
-h, --help
"""
__version__ = "0.1.1"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2019"
__author__ = "David Sanson"
__url__ = "https://github.com/dsanson/termpdf.py"
__viewer_shortcuts__ = """\
Keys:
j, down, space: forward [count] pages
k, up: back [count] pages
l, right: forward [count] sections
h, left: back [count] sections
gg: go to beginning of document
G: go to end of document
[count]G: go to page [count]
b: cycle through open documents
s: visual mode
t: table of contents
M: show metadata
f: show links on page
r: rotate [count] quarter turns clockwise
R: rotate [count] quarter turns counterclockwise
c: toggle autocropping of margins
a: toggle alpha transparency
i: invert colors
d: darken using TINT_COLOR
[count]P: Set logical page number of current page to count
-: zoom out (reflowable only)
+: zoom in (reflowable only)
ctrl-r: refresh
q: quit
"""
import re
import array
import curses
import fcntl
import fitz
import os
import sys
import logging
import termios
import threading
import subprocess
import zlib
import shutil
import select
import hashlib
import string
import json
import roman
import pyperclip
from time import sleep, monotonic
from base64 import standard_b64encode
from operator import attrgetter
from collections import namedtuple
from math import ceil
from tempfile import NamedTemporaryFile
# Class Definitions
class Config:
def __init__(self):
self.BIBTEX = ''
#self.KITTYCMD = 'kitty --single-instance --instance-group=1' # open notes in a new OS window
self.KITTYCMD = 'kitty @ new-window' # open notes in split kitty window
self.TINT_COLOR = 'antiquewhite2'
self.URL_BROWSER_LIST = [
'gnome-open',
'gvfs-open',
'xdg-open',
'kde-open',
'firefox',
'w3m',
'elinks',
'lynx'
]
self.URL_BROWSER = None
self.GUI_VIEWER = 'preview'
self.NOTE_PATH = os.path.join(os.getenv("HOME"), 'inbox.org')
def browser_detect(self):
if sys.platform == 'darwin':
self.URL_BROWSER = 'open'
else:
for i in self.URL_BROWSER_LIST:
if shutil.which(i) is not None:
self.URL_BROWSER = i
break
def load_config_file(self):
config_file = os.path.expanduser(os.path.join(os.getenv("XDG_CONFIG_HOME", "~/.config"), 'termpdf.py', 'config'))
if os.path.exists(config_file):
with open(config_file, 'r') as f:
prefs = json.load(f)
for key in prefs:
setattr(self, key, prefs[key])
class Buffers:
def __init__(self):
self.docs = []
self.current = 0
def goto_buffer(self,n):
l = len(self.docs) - 1
if n > l:
n = l
elif n < 0:
n = 0
self.current = n
def cycle(self, count):
self.current = (self.current + count) % len(self.docs)
def close_buffer(self,n):
del self.docs[n]
if self.current == n:
self.current = max(0,n-1)
if len(self.docs) == 0:
clean_exit()
class Screen:
def __init__(self):
self.rows = 0
self.cols = 0
self.width = 0
self.height = 0
self.cell_width = 0
self.cell_height = 0
self.stdscr = None
def get_size(self):
fd = sys.stdout
buf = array.array('H', [0, 0, 0, 0])
fcntl.ioctl(fd, termios.TIOCGWINSZ, buf)
r,c,w,h = tuple(buf)
cw = w // (c or 1)
ch = h // (r or 1)
self.rows = r
self.cols = c
self.width = w
self.height = h
self.cell_width = cw
self.cell_height = ch
def init_curses(self):
os.environ.setdefault('ESCDELAY', '25')
self.stdscr = curses.initscr()
self.stdscr.clear()
curses.noecho()
curses.curs_set(0)
curses.mousemask(curses.REPORT_MOUSE_POSITION
| curses.BUTTON1_PRESSED | curses.BUTTON1_RELEASED
| curses.BUTTON2_PRESSED | curses.BUTTON2_RELEASED
| curses.BUTTON3_PRESSED | curses.BUTTON3_RELEASED
| curses.BUTTON4_PRESSED | curses.BUTTON4_RELEASED
| curses.BUTTON1_CLICKED | curses.BUTTON3_CLICKED
| curses.BUTTON1_DOUBLE_CLICKED
| curses.BUTTON1_TRIPLE_CLICKED
| curses.BUTTON2_DOUBLE_CLICKED
| curses.BUTTON2_TRIPLE_CLICKED
| curses.BUTTON3_DOUBLE_CLICKED
| curses.BUTTON3_TRIPLE_CLICKED
| curses.BUTTON4_DOUBLE_CLICKED
| curses.BUTTON4_TRIPLE_CLICKED
| curses.BUTTON_SHIFT | curses.BUTTON_ALT
| curses.BUTTON_CTRL)
self.stdscr.keypad(True) # Handle our own escape codes for now
# The first call to getch seems to clobber the statusbar.
# So we make a dummy first call.
self.stdscr.nodelay(True)
self.stdscr.getch()
self.stdscr.nodelay(False)
def create_text_win(self, length, header):
# calculate dimensions
w = max(self.cols - 4, 60)
h = self.rows - 2
x = int(self.cols / 2 - w / 2)
y = 1
win = curses.newwin(h,w,y,x)
win.box()
win.addstr(1,2, '{:^{l}}'.format(header, l=(w-3)))
self.stdscr.clear()
self.stdscr.refresh()
win.refresh()
pad = curses.newpad(length,1000)
pad.keypad(True)
return win, pad
def swallow_keys(self):
self.stdscr.nodelay(True)
k = self.stdscr.getch()
end = monotonic() + 0.1
while monotonic() < end:
self.stdscr.getch()
self.stdscr.nodelay(False)
def clear(self):
sys.stdout.buffer.write('\033[2J'.encode('ascii'))
def set_cursor(self,c,r):
if c > self.cols:
c = self.cols
elif c < 0:
c = 0
if r > self.rows:
r = self.rows
elif r < 0:
r = 0
sys.stdout.buffer.write('\033[{};{}f'.format(r, c).encode('ascii'))
def place_string(self,c,r,string):
self.set_cursor(c,r)
sys.stdout.write(string)
sys.stdout.flush()
def get_filehash(path):
blocksize = 65536
hasher = hashlib.md5()
with open(path, 'rb') as afile:
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest()
def get_cachefile(path):
filehash = get_filehash(path)
cachedir = os.path.expanduser(os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), 'termpdf.py'))
os.makedirs(cachedir, exist_ok=True)
cachefile = os.path.join(cachedir, filehash)
return cachefile
class Document(fitz.Document):
"""
An extension of the fitz.Document class, with extra attributes
"""
def __init__(self, filename=None, filetype=None, rect=None, width=0, height=0, fontsize=12):
fitz.Document.__init__(self, filename, None, filetype, rect, width, height, fontsize)
self.filename = filename
self.citekey = None
self.papersize = 3
self.layout(rect=fitz.paper_rect('A6'),fontsize=fontsize)
self.page = 0
self.logicalpage = 1
self.prevpage = 0
self.pages = self.page_count - 1
self.first_page_offset = 1
self.logical_pages = list(range(0 + self.first_page_offset, self.pages + self.first_page_offset))
self.chapter = 0
self.rotation = 0
self.fontsize = fontsize
self.width = width
self.height = height
self.autocrop = False
self.manualcrop = False
self.manualcroprect = [None,None]
self.alpha = False
self.invert = False
self.tint = False
self.tint_color = config.TINT_COLOR
self.nvim = None
self.nvim_listen_address = '/tmp/termpdf_nvim_bridge'
self.page_states = [ Page_State(i) for i in range(0,self.pages + 1) ]
def write_state(self):
cachefile = get_cachefile(self.filename)
state = {'citekey': self.citekey,
'papersize': self.papersize,
'page': self.page,
'logicalpage': self.logicalpage,
'first_page_offset': self.first_page_offset,
'chapter': self.chapter,
'rotation': self.rotation,
'autocrop': self.autocrop,
'manualcrop': self.manualcrop,
'manualcroprect': self.manualcroprect,
'alpha': self.alpha,
'invert': self.invert,
'tint': self.tint}
with open(cachefile, 'w') as f:
json.dump(state, f)
def goto_page(self, p):
# store prevpage
self.prevpage = self.page
# delete prevpage
# self.clear_page(self.prevpage)
# set new page
if p > self.pages:
self.page = self.pages
elif p < 0:
self.page = 0
else:
self.page = p
self.logicalpage = self.page_to_logical(self.page)
def goto_logical_page(self, p):
p = self.logical_to_page(p)
self.goto_page(p)
def next_page(self, count=1):
self.goto_page(self.page + count)
def prev_page(self, count=1):
self.goto_page(self.page - count)
def goto_chap(self, n):
toc = self.get_toc()
if n > len(toc):
n = len(toc)
elif n < 0:
n = 0
self.chapter = n
try:
self.goto_page(toc[n][2] - 1)
except:
self.goto_page(0)
def current_chap(self):
toc = self.get_toc()
p = self.page
for i,ch in enumerate(toc):
cp = ch[2] - 1
if cp > p:
return i - 1
return len(toc)
def next_chap(self, count=1):
self.goto_chap(self.chapter + count)
def prev_chap(self, count=1):
self.goto_chap(self.chapter - count)
def parse_pagelabels(self):
if self.is_pdf:
from pdfrw import PdfReader
from pagelabels import PageLabels, PageLabelScheme
try:
reader = PdfReader(self.filename)
labels = PageLabels.from_pdf(reader)
labels = sorted(labels, key=attrgetter('startpage'))
except:
labels = []
else:
labels = []
return labels
def set_pagelabel(self,count,style="arabic"):
if self.is_pdf:
from pdfrw import PdfReader, PdfWriter
from pagelabels import PageLabels, PageLabelScheme
reader = PdfReader(self.filename)
labels = PageLabels.from_pdf(reader)
newlabels = PageLabels()
for label in labels:
if label.startpage != self.page:
newlabels.append(label)
newlabel = PageLabelScheme(startpage=self.page,
style=style,
prefix="",
firstpagenum=count)
newlabels.append(newlabel)
newlabels.write(reader)
writer = PdfWriter()
writer.trailer = reader
logging.debug("writing new pagelabels...")
writer.write(self.filename)
# unused; using pdfrw instead
def parse_pagelabels_pure(self):
cat = self._getPDFroot()
cat_str = self._getXrefString(cat)
lines = cat_str.split('\n')
labels = []
for line in lines:
match = re.search('/PageLabels',line)
if re.match(r'.*/PageLabels.*', line):
labels += [line]
logging.debug(labels)
raise SystemExit
def pages_to_logical_pages(self):
labels = self.parse_pagelabels()
self.logical_pages = list(range(0,self.pages + 1))
def divmod_alphabetic(n):
a, b = divmod(n, 26)
if b == 0:
return a - 1, b + 26
return a, b
def to_alphabetic(n):
chars = []
while n > 0:
n, d = divmod_alphabetic(n)
chars.append(string.ascii_uppercase[d - 1])
return ''.join(reversed(chars))
if labels == []:
for p in range(0,self.pages + 1):
self.logical_pages[p] = str(p + self.first_page_offset)
else:
for p in range(0,self.pages + 1):
for label in labels:
if p >= label.startpage:
lp = (p - label.startpage) + label.firstpagenum
style = label.style
prefix = label.prefix
if style == 'roman uppercase':
lp = prefix + roman.toRoman(lp)
lp = lp.upper()
elif style == 'roman lowercase':
lp = prefix + roman.toRoman(lp)
lp = lp.lower()
elif style == 'alphabetic uppercase':
lp = prefix + to_alphabetic(lp)
elif style == 'alphabetic lowercase':
lp = prefix + to_alphabetic(lp)
lp = lp.lower()
else:
lp = prefix + str(lp)
self.logical_pages[p] = lp
def page_to_logical(self, p=None):
if not p:
p = self.page
return self.logical_pages[p]
def logical_to_page(self, lp=None):
if not lp:
lp = self.logicalpage
try:
p = self.logical_pages.index(str(lp))
except:
# no such logical page in document
p = 0
return p
def make_link(self):
p = self.page_to_logical(self.page)
if self.citekey:
return '[@{}, {}]'.format(self.citekey, p)
else:
return '({}, {}, {})'.format(self.metadata['author'],self.metadata['title'], p)
def find_target(self, target, target_text):
# since our pct calculation is at best an estimate
# of the correct target page, we search for the first
# few words of the original page on the surrounding pages
# until we find a match
for i in [0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6]:
f = target + i
match_text = self[f].get_text().split()
match_text = ' '.join(match_text)
if target_text in match_text:
return f
return target
def set_layout(self,papersize, adjustpage=True):
# save a snippet of text from current page
target_text = self[self.page].get_text().split()
if len(target_text) > 6:
target_text = ' '.join(target_text[:6])
elif len(target_text) > 0:
target_text = ' '.join(target_text)
else:
target_text = ''
pct = (self.page + 1) / (self.pages + 1)
sizes = ['a7','c7','b7','a6','c6','b6','a5','c5','b5','a4']
if papersize > len(sizes) - 1:
papersize = len(sizes) - 1
elif papersize < 0:
papersize = 0
p = sizes[papersize]
self.layout(fitz.paper_rect(p))
self.pages = self.page_count - 1
if adjustpage:
target = int((self.pages + 1) * pct) - 1
target = self.find_target(target, target_text)
self.goto_page(target)
self.papersize = papersize
self.pages_to_logical_pages()
def mark_all_pages_stale(self):
self.page_states = [ Page_State(i) for i in range(0,self.pages + 1) ]
def clear_page(self, p):
cmd = {'a': 'd', 'd': 'a', 'i': p + 1}
write_gr_cmd(cmd)
def cells_to_pixels(self, *coords):
factor = self.page_states[self.page].factor
l,t,_,_ = self.page_states[self.page].place
pix_coords = []
for coord in coords:
col = coord[0]
row = coord[1]
x = (col - l) * scr.cell_width / factor
y = (row - t) * scr.cell_height / factor
pix_coords.append((x,y))
return pix_coords
def pixels_to_cells(self, *coords):
factor = self.page_states[self.page].factor
l,t,_,_ = self.page_states[self.page].place
cell_coords = []
for coord in coords:
x = coord[0]
y = coord[1]
col = (x * factor + l * scr.cell_width) / scr.cell_width
row = (y * factor + t * scr.cell_height) / scr.cell_height
col = int(col)
row = int(row)
cell_coords.append((col,row))
return cell_coords
# get text that is inside a Rect
def get_text_in_Rect(self, rect):
from operator import itemgetter
from itertools import groupby
page = self.load_page(self.page)
words = page.get_text_words()
mywords = [w for w in words if fitz.Rect(w[:4]) in rect]
mywords.sort(key=itemgetter(3, 0)) # sort by y1, x0 of the word rect
group = groupby(mywords, key=itemgetter(3))
text = []
for y1, gwords in group:
text = text + [" ".join(w[4] for w in gwords)]
return text
# get text that intersects a Rect
def get_text_intersecting_Rect(self, rect):
from operator import itemgetter
from itertools import groupby
page = self.load_page(self.page)
words = page.get_text_words()
mywords = [w for w in words if fitz.Rect(w[:4]).intersects(rect)]
mywords.sort(key=itemgetter(3, 0)) # sort by y1, x0 of the word rect
group = groupby(mywords, key=itemgetter(3))
text = []
for y1, gwords in group:
text = text + [" ".join(w[4] for w in gwords)]
return text
def search_text(self,string):
for p in range(self.page,self.pages):
page_text = self.get_page_text(p, 'text')
if re.search(string,page_text):
self.goto_page(p)
return "match on page"
return "no matches"
def auto_crop(self,page):
blocks = page.get_text_blocks()
if len(blocks) > 0:
crop = fitz.Rect(blocks[0][:4])
else:
# don't try to crop empty pages
crop = fitz.Rect(0,0,0,0)
for block in blocks:
b = fitz.Rect(block[:4])
crop = crop | b
return crop
def display_page(self, bar, p, display=True):
page = self.load_page(p)
page_state = self.page_states[p]
if self.manualcrop and self.manualcroprect != [None,None] and self.is_pdf:
page.set_cropbox(fitz.Rect(self.manualcroprect[0],self.manualcroprect[1]))
elif self.autocrop and self.is_pdf:
page.set_cropbox(page.mediabox)
crop = self.auto_crop(page)
page.set_cropbox(crop)
elif self.is_pdf:
page.set_cropbox(page.mediabox)
dw = scr.width
dh = scr.height - scr.cell_height
if self.rotation in [0,180]:
pw = page.bound().width
ph = page.bound().height
else:
pw = page.bound().height
ph = page.bound().width
# calculate zoom factor
fx = dw / pw
fy = dh / ph
factor = min(fx,fy)
self.page_states[p].factor = factor
# calculate zoomed dimensions
zw = factor * pw
zh = factor * ph
# calculate place in pixels, convert to cells
pix_x = (dw / 2) - (zw / 2)
pix_y = (dh / 2) - (zh / 2)
l_col = int(pix_x / scr.cell_width) + 1
t_row = int(pix_y / scr.cell_height)
r_col = l_col + int(zw / scr.cell_width)
b_row = t_row + int(zh / scr.cell_height)
place = (l_col, t_row, r_col, b_row)
self.page_states[p].place = place
# move cursor to place
scr.set_cursor(l_col,t_row)
# clear previous page
# display image
cmd = {'a': 'p', 'i': p + 1, 'z': -1}
if page_state.stale: #or (display and not write_gr_cmd_with_response(cmd)):
# get zoomed and rotated pixmap
mat = fitz.Matrix(factor, factor)
mat = mat.prerotate(self.rotation)
pix = page.get_pixmap(matrix = mat, alpha=self.alpha)
if self.invert:
pix.invert_irect()
if self.tint:
tint = fitz.utils.getColor(self.tint_color)
red = int(tint[0] * 256)
blue = int(tint[1] * 256)
green = int(tint[2] * 256)
# pix.tint_with(red, blue, green)
# tinting disabled due to unresolved bug
# build cmd to send to kitty
cmd = {'i': p + 1, 't': 'd', 's': pix.width, 'v': pix.height}
if self.alpha:
cmd['f'] = 32
else:
cmd['f'] = 24
# transfer the image
write_chunked(cmd, pix.samples)
if display:
# clear prevpage
self.clear_page(self.prevpage)
# display the image
cmd = {'a': 'p', 'i': p + 1, 'z': -1}
success = write_gr_cmd_with_response(cmd)
if not success:
self.page_states[p].stale = True
bar.message = 'failed to load page ' + str(p+1)
bar.update(self)
self.page_states[p].stale = False
scr.swallow_keys()
def show_toc(self, bar):
toc = self.get_toc()
if not toc:
bar.message = "No ToC available"
return
self.page_states[self.page ].stale = True
self.clear_page(self.page)
scr.clear()
def init_pad(toc):
win, pad = scr.create_text_win(len(toc), 'Table of Contents')
y,x = win.getbegyx()
h,w = win.getmaxyx()
span = []
for i, ch in enumerate(toc):
text = '{}{}'.format(' ' * (ch[0] - 1), ch[1])
pad.addstr(i,0,text)
span.append(len(text))
return win,pad,y,x,h,w,span
win,pad,y,x,h,w,span = init_pad(toc)
keys = shortcuts()
index = self.current_chap()
j = 0
while True:
for i, ch in enumerate(toc):
attr = curses.A_REVERSE if index == i else curses.A_NORMAL
pad.chgat(i, 0, span[i], attr)
pad.refresh(j, 0, y + 3, x + 2, y + h - 2, x + w - 3)
key = scr.stdscr.getch()
if key in keys.REFRESH:
scr.clear()
scr.get_size()
scr.init_curses()
self.set_layout(self.papersize)
self.mark_all_pages_stale()
init_pad(toc)
elif key in keys.QUIT:
clean_exit()
elif key == 27 or key in keys.SHOW_TOC:
scr.clear()
return
elif key in keys.NEXT_PAGE:
index = min(len(toc) - 1, index + 1)
elif key in keys.PREV_PAGE:
index = max(0, index - 1)
elif key in keys.OPEN:
scr.clear()
self.goto_page(toc[index][2] - 1)
return
if index > j + (h - 5):
j += 1
if index < j:
j -= 1
def update_metadata_from_bibtex(self):
if not self.citekey:
return
bib = bib_from_key([self.citekey])
bib_entry = bib.entries[self.citekey]
metadata = self.metadata
title = bib_entry.fields['title']
title = title.replace('{','')
title = title.replace('}','')
metadata['title'] = title
authors = [author for author in bib_entry.persons['author']]
if len(authors) == 0:
authors = [author for author in bib_entry.persons['editor']]
authorNames = ''
for author in authors:
if authorNames != '':
authorNames += ' & '
if author.first_names:
authorNames += ' '.join(author.first_names) + ' '
if author.last_names:
authorNames += ' '.join(author.last_names)
metadata['author'] = authorNames
if 'Keywords' in bib_entry.fields:
metadata['keywords'] = bib_entry.fields['Keywords']
self.set_metadata(metadata)
try:
self.saveIncr()
except:
pass
def show_meta(self, bar):
meta = self.metadata
if not meta:
bar.message = "No metadata available"
return
self.page_states[self.page].stale = True
self.clear_page(self.page)
scr.clear()
def init_pad(metadata):
win, pad = scr.create_text_win(len(meta), 'Metadata')
y,x = win.getbegyx()
h,w = win.getmaxyx()
span = []
for i, mkey in enumerate(meta):
text = '{}: {}'.format(mkey,meta[mkey])
pad.addstr(i,0,text)
span.append(len(text))
return win,pad,y,x,h,w,span
win,pad,y,x,h,w,span = init_pad(meta)
keys = shortcuts()
index = 0
j = 0
while True:
for i, mkey in enumerate(meta):
attr = curses.A_REVERSE if index == i else curses.A_NORMAL
pad.chgat(i, 0, span[i], attr)
pad.refresh(j, 0, y + 3, x + 2, y + h - 2, x + w - 3)
key = scr.stdscr.getch()
if key in keys.REFRESH:
scr.clear()
scr.get_size()
scr.init_curses()
self.set_layout(self.papersize)
self.mark_all_pages_stale()
init_pad(meta)
elif key in keys.QUIT:
clean_exit()
elif key == 27 or key in keys.SHOW_META:
scr.clear()
return
elif key in keys.NEXT_PAGE:
index = min(len(meta) - 1, index + 1)
elif key in keys.PREV_PAGE:
index = max(0, index - 1)
elif key in keys.UPDATE_FROM_BIB:
self.update_metadata_from_bibtex()
meta = self.metadata
win,pad,y,x,h,w,span = init_pad(meta)
elif key in keys.OPEN:
# TODO edit metadata
pass
if index > j + (h - 5):
j += 1
if index < j:
j -= 1
def goto_link(self,link):
kind = link['kind']
# 0 == no destination
# 1 == internal link
# 2 == uri
# 3 == launch link
# 5 == external pdf link
if kind == 0:
pass
elif kind == 1:
self.goto_page(link['page'])
elif kind == 2:
subprocess.run([config.URL_BROWSER, link['uri']], check=True)
elif kind == 3:
# not sure what these are
pass
elif kind == 5:
path = link['fileSpec']
opts = {'page': link['page']}
#load_doc(path,opts)
pass
def show_links(self, bar):
links = self[self.page].get_links()
urls = [link for link in links if 0 < link['kind'] < 3]
if not urls:
bar.message = "No links on page"
return
self.page_states[self.page].stale = True
self.clear_page(self.page)
scr.clear()
def init_pad(urls):
win, pad = scr.create_text_win(len(urls), 'URLs')
y,x = win.getbegyx()
h,w = win.getmaxyx()
span = []
for i, url in enumerate(urls):
anchor_text = self.get_text_intersecting_Rect(url['from'])
if len(anchor_text) > 0:
anchor_text = anchor_text[0]
else:
anchor_text = ''
if url['kind'] == 2:
link_text = url['uri']
else:
link_text = url['page']
text = '{}: {}'.format(anchor_text, link_text)
pad.addstr(i,0,text)
span.append(len(text))
return win,pad,y,x,h,w,span
win,pad,y,x,h,w,span = init_pad(urls)
keys = shortcuts()
index = 0
j = 0
while True:
for i, url in enumerate(urls):
attr = curses.A_REVERSE if index == i else curses.A_NORMAL
pad.chgat(i, 0, span[i], attr)
pad.refresh(j, 0, y + 3, x + 2, y + h - 2, x + w - 3)
key = scr.stdscr.getch()
if key in keys.REFRESH:
scr.clear()
scr.get_size()
scr.init_curses()
self.set_layout(self.papersize)
self.mark_all_pages_stale()
init_pad(urls)
elif key in keys.QUIT:
clean_exit()
elif key == 27 or key in keys.SHOW_LINKS:
scr.clear()
return
elif key in keys.NEXT_PAGE:
index = min(len(urls) - 1, index + 1)
elif key in keys.PREV_PAGE:
index = max(0, index - 1)
elif key in keys.OPEN:
self.goto_link(urls[index])
scr.clear()
return
if index > j + (h - 5):
j += 1
if index < j:
j -= 1
def view_text(self):
pass
def init_neovim_bridge(self):
try:
from pynvim import attach
except:
raise SystemExit('pynvim unavailable')
try:
self.nvim = attach('socket', path=self.nvim_listen_address)
except:
ncmd = 'env NVIM_LISTEN_ADDRESS={} nvim {}'.format(self.nvim_listen_address, config.NOTE_PATH)
try:
os.system('{} {}'.format(config.KITTYCMD,ncmd))
except:
raise SystemExit('unable to open new kitty window')
end = monotonic() + 5 # 5 second time out
while monotonic() < end:
try:
self.nvim = attach('socket', path=self.nvim_listen_address)
break
except:
# keep trying every tenth of a second
sleep(0.1)
def send_to_neovim(self,text,append=False):
try:
self.nvim.api.strwidth('testing')
except:
self.init_neovim_bridge()
if not self.nvim:
return
if append:
line = self.nvim.funcs.line('$')
self.nvim.funcs.append(line, text)
self.nvim.funcs.cursor(self.nvim.funcs.line('$'),0)
else:
line = self.nvim.funcs.line('.')
self.nvim.funcs.append(line, text)
self.nvim.funcs.cursor(line + len(text), 0)
class Page_State:
def __init__(self, p):
self.number = p
self.stale = True
self.factor = (1,1)