-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
view.pyj
1181 lines (1066 loc) · 53.2 KB
/
view.pyj
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
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from __python__ import bound_methods, hash_literals
from elementmaker import E
from gettext import gettext as _
import read_book.iframe # noqa
from ajax import ajax_send
from book_list.globals import get_session_data
from book_list.theme import cached_color_to_rgba, get_color
from dom import add_extra_css, build_rule, clear, set_css, svgicon, unique_id
from iframe_comm import IframeWrapper
from modals import error_dialog, warning_dialog
from read_book.content_popup import ContentPopupOverlay
from read_book.create_annotation import AnnotationsManager, CreateAnnotation, ViewAnnotation
from read_book.globals import (
current_book, runtime, set_current_spine_item, ui_operations
)
from read_book.goto import get_next_section
from read_book.open_book import add_book_to_recently_viewed
from read_book.overlay import Overlay
from read_book.prefs.colors import resolve_color_scheme
from read_book.prefs.font_size import change_font_size_by
from read_book.prefs.head_foot import render_head_foot
from read_book.prefs.scrolling import (
MIN_SCROLL_SPEED_AUTO as SCROLL_SPEED_STEP, change_scroll_speed
)
from read_book.resources import load_resources
from read_book.scrollbar import BookScrollbar
from read_book.search import SearchOverlay, find_in_spine
from read_book.shortcuts import create_shortcut_map
from read_book.timers import Timers
from read_book.toc import get_current_toc_nodes, update_visible_toc_nodes
from read_book.touch import set_left_margin_handler, set_right_margin_handler
from session import get_device_uuid, get_interface_data
from utils import (
html_escape, is_ios, parse_url_params, safe_set_inner_html, username_key
)
from viewer.constants import READER_BACKGROUND_URL
add_extra_css(def():
sel = '.book-side-margin'
ans = build_rule(sel, cursor='pointer', text_align='center', height='100vh', user_select='none', display='flex', align_items='center', justify_content='space-between', flex_direction='column')
ans += build_rule(sel + ' > .arrow', display='none')
ans += build_rule(sel + ' > *', max_width='100%', overflow='hidden')
ans += build_rule(sel + ':hover > .not-arrow', display='none')
ans += build_rule(sel + ':active > .not-arrow', display='none')
ans += build_rule(sel + ':hover > .arrow', display='block')
ans += build_rule(sel + ':active > .arrow', color=get_color('window-hover-foreground'), display='block', transform='scale(2)')
return ans
)
# Simple Overlays {{{
def show_controls_help():
container = document.getElementById('controls-help-overlay')
container.style.display = 'block'
container.style.backgroundColor = get_color('window-background')
if not show_controls_help.listener_added:
show_controls_help.listener_added = True
container.addEventListener('click', def():
document.getElementById('controls-help-overlay').style.display = 'none'
ui_operations.focus_iframe()
)
container.addEventListener('contextmenu', def(evt):
evt.preventDefault(), evt.stopPropagation()
document.getElementById('controls-help-overlay').style.display = 'none'
ui_operations.focus_iframe()
, {'passive': False})
container.addEventListener('keydown', def(event):
event.preventDefault(), event.stopPropagation()
document.getElementById('controls-help-overlay').style.display = 'none'
ui_operations.focus_iframe()
, {'passive': False})
def focus():
if container.style.display is 'block':
container.querySelector('input').focus()
window.setTimeout(focus, 10)
if runtime.is_standalone_viewer:
container.appendChild(E.div(
style='margin: 1rem',
E.div(style='margin-top: 1rem'),
E.div(style='margin-top: 1rem'),
E.div(style='margin-top: 1rem'),
E.div(style='margin-top: 1rem'),
E.input(style='background: transparent; border-width: 0; outline: none', readonly='readonly'),
))
div = container.lastChild.firstChild
safe_set_inner_html(div, _('Welcome to the <b>calibre viewer</b>!'))
div = div.nextSibling
safe_set_inner_html(div, _('Use the <b>PageUp/PageDn</b> or <b>Arrow keys</b> to turn pages'))
div = div.nextSibling
safe_set_inner_html(div, _('Press the <b>Esc</b> key or <b>{}</b> or <b>tap on the top third</b> of the text area to show the viewer controls').format(
_('control+click') if 'macos' in window.navigator.userAgent else _('right click')
))
div = div.nextSibling
safe_set_inner_html(div, _('Press any key to continue…'))
focus()
return
def msg(txt):
return set_css(E.div(txt), padding='1ex 1em', text_align='center', margin='auto')
container.appendChild(E.div(
style=f'overflow: hidden; width: 100vw; height: 100vh; text-align: center; font-size: 1.3rem; font-weight: bold; background: {get_color("window-background")};' +
'display:flex; flex-direction: column; align-items: stretch',
E.div(
msg(_('Tap (or right click) for controls')),
style='height: 25vh; display:flex; align-items: center; border-bottom: solid 2px currentColor',
),
E.div(
style="display: flex; align-items: stretch; flex-grow: 10",
E.div(
msg(_('Tap to turn back')),
style='width: 25vw; display:flex; align-items: center; border-right: solid 2px currentColor',
),
E.div(
msg(_('Tap to turn page')),
style='width: 75vw; display:flex; align-items: center',
)
)
))
# }}}
def maximum_font_size():
ans = maximum_font_size.ans
if not ans:
q = window.getComputedStyle(document.body).fontSize
if q and q.endsWith('px'):
q = parseInt(q)
if q and not isNaN(q):
ans = maximum_font_size.ans = q
return ans
ans = maximum_font_size.ans = 12
return ans
def margin_elem(sd, which, id, onclick, oncontextmenu):
sz = sd.get(which, 20)
fsz = min(max(0, sz - 6), maximum_font_size())
s = '; text-overflow: ellipsis; white-space: nowrap; overflow: hidden'
ans = E.div(
style=f'height:{sz}px; overflow: hidden; font-size:{fsz}px; width:100%; padding: 0; display: flex; justify-content: space-between; align-items: center',
id=id,
E.div(style='margin-right: 1.5em' + s), E.div(style=s), E.div(style='margin-left: 1.5em' + s)
)
if onclick:
ans.addEventListener('click', onclick)
if oncontextmenu:
ans.addEventListener('contextmenu', oncontextmenu)
if is_ios and which is 'margin_bottom' and not window.navigator.standalone and not /CriOS\//.test(window.navigator.userAgent):
# On iOS Safari 100vh includes the size of the navbar and there is no way to
# go fullscreen, so to make the bottom bar visible we add a margin to
# the bottom bar. CriOS is for Chrome on iOS. And in standalone
# (web-app mode) there is no nav bar.
ans.style.marginBottom = '25px'
return ans
def side_margin_elem(self, sd, which):
ans = E.div(
E.div(class_='arrow', style='order: 3', svgicon(f'caret-{which}', '100%', '100%')),
E.div(style='order:1'), E.div(style='order:2', class_='not-arrow'), E.div(style='order:4'),
style='width:{}px;'.format(sd.get(f'margin_{which}', 20)),
class_='book-side-margin', id=f'book-{which}-margin',
onclick=self.side_margin_clicked.bind(None, which),
oncontextmenu=self.margin_context_menu.bind(None, which),
onwheel=self.on_margin_wheel.bind(None, which)
)
return ans
class View:
def __init__(self, container):
self.timers = Timers()
self.reference_mode_enabled = False
self.loaded_resources = {}
self.current_progress_frac = self.current_file_progress_frac = 0
self.current_toc_node = self.current_toc_toplevel_node = None
self.report_cfi_callbacks = {}
self.get_cfi_counter = 0
self.show_loading_callback_timer = None
self.timer_ids = {'clock': 0}
self.book_scrollbar = BookScrollbar(self)
sd = get_session_data()
self.keyboard_shortcut_map = create_shortcut_map(sd.get('keyboard_shortcuts'))
if ui_operations.export_shortcut_map:
ui_operations.export_shortcut_map(self.keyboard_shortcut_map)
left_margin = side_margin_elem(self, sd, 'left')
set_left_margin_handler(left_margin)
right_margin = side_margin_elem(self, sd, 'right')
set_right_margin_handler(right_margin)
iframe_id = unique_id('read-book-iframe')
sandbox = 'allow-popups allow-scripts allow-popups-to-escape-sandbox'
if runtime.is_standalone_viewer:
sandbox += ' allow-same-origin'
container.appendChild(
E.div(style='max-height: 100vh; width: 100vw; height: 100vh; overflow: hidden; display: flex; align-items: stretch', # container for horizontally aligned panels
oncontextmenu=def (ev):
ev.preventDefault()
,
E.div(style='max-height: 100vh; display: flex; flex-direction: column; align-items: stretch; flex-grow:2', # container for iframe and any other panels in the same column
E.div(style='max-height: 100vh; flex-grow: 2; display:flex; align-items: stretch', # container for iframe and its overlay
left_margin,
E.div(style='flex-grow:2; display:flex; align-items:stretch; flex-direction: column', # container for top and bottom margins
margin_elem(sd, 'margin_top', 'book-top-margin', self.top_margin_clicked, self.margin_context_menu.bind(None, 'top')),
E.iframe(id=iframe_id, seamless=True, sandbox=sandbox, style='flex-grow: 2', allowfullscreen='true'),
margin_elem(sd, 'margin_bottom', 'book-bottom-margin', self.bottom_margin_clicked, self.margin_context_menu.bind(None, 'bottom')),
),
right_margin,
self.book_scrollbar.create(),
E.div(style='position: absolute; top:0; left:0; width: 100%; pointer-events:none; display:none', id='book-search-overlay'), # search overlay
E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none', id='book-content-popup-overlay'), # content popup overlay
E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; overflow: auto; display:none', id='book-overlay'), # main overlay
E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none', id='controls-help-overlay'), # controls help overlay
E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; display:none; overflow: hidden', id=CreateAnnotation.container_id, tabindex='0'), # create annotation overlay
E.div(style='position: absolute; top:0; left:0; width: 100%; height: 100%; pointer-events:none; display:none; z-index: 4000', id=ViewAnnotation.container_id), # view annotation overlay
)
),
E.div(
style=f'color: {get_color("window-foreground")}; background: {get_color("window-background")};' +
'position: absolute; display: none; left: 0; top: 0; padding: 0.5ex; border: solid 2px; z-index: 3000',
id='reference-mode-overlay'
),
),
)
handlers = {
'autoscroll_state_changed': def(data):
self.autoscroll_active = v'!!data.running'
if ui_operations.autoscroll_state_changed:
ui_operations.autoscroll_state_changed(self.autoscroll_active)
,
'bump_font_size': self.bump_font_size,
'content_loaded': self.on_content_loaded,
'error': self.on_iframe_error,
'find_in_spine': self.on_find_in_spine,
'goto_doc_boundary': def(data): self.goto_doc_boundary(data.start);,
'handle_keypress': self.on_handle_keypress,
'handle_shortcut': self.on_handle_shortcut,
'human_scroll': self.on_human_scroll,
'lookup_word': self.on_lookup_word,
'next_section': self.on_next_section,
'next_spine_item': self.on_next_spine_item,
'print': self.on_print,
'ready': self.on_iframe_ready,
'reference_item_changed': self.on_reference_item_changed,
'report_cfi': self.on_report_cfi,
'request_size': self.on_request_size,
'scroll_to_anchor': self.on_scroll_to_anchor,
'selectionchange': self.on_selection_change,
'columns_per_screen_changed': self.on_columns_per_screen_changed,
'show_chrome': self.show_chrome,
'show_footnote': self.on_show_footnote,
'update_cfi': self.on_update_cfi,
'update_progress_frac': self.on_update_progress_frac,
'update_toc_position': self.on_update_toc_position,
'search_result_not_found': def (data):
if ui_operations.search_result_not_found:
ui_operations.search_result_not_found(data.search_result)
,
'annotations': self.on_annotations_message,
'copy_text_to_clipboard': def(data):
if ui_operations.copy_selection:
ui_operations.copy_selection(data.text)
,
'view_image': def(data):
if ui_operations.view_image:
ui_operations.view_image(data.calibre_src)
,
}
entry_point = None if runtime.is_standalone_viewer else 'read_book.iframe'
if runtime.is_standalone_viewer:
document.documentElement.addEventListener('keydown', self.handle_keypress, {'passive': False})
self.current_color_scheme = resolve_color_scheme()
self.iframe_wrapper = IframeWrapper(
handlers, document.getElementById(iframe_id), entry_point, _('Bootstrapping book reader...'),
f'{runtime.FAKE_PROTOCOL}://{runtime.SANDBOX_HOST}/book/__index__')
self.search_overlay = SearchOverlay(self)
self.content_popup_overlay = ContentPopupOverlay(self)
self.overlay = Overlay(self)
self.processing_spine_item_display = False
self.pending_load = None
self.currently_showing = {}
self.book_scrollbar.apply_visibility()
self.annotations_manager = AnnotationsManager(self)
self.create_annotation = CreateAnnotation(self)
self.view_annotation = ViewAnnotation(self)
@property
def iframe(self):
return self.iframe_wrapper.iframe
@property
def reference_mode_overlay(self):
return document.getElementById('reference-mode-overlay')
def set_scrollbar_visibility(self, visible):
sd = get_session_data()
sd.set('book_scrollbar', bool(visible))
self.book_scrollbar.apply_visibility()
def toggle_scrollbar(self):
sd = get_session_data()
self.set_scrollbar_visibility(not sd.get('book_scrollbar'))
def on_lookup_word(self, data):
if runtime.is_standalone_viewer:
ui_operations.selection_changed(data.word)
return
self.overlay.show_word_actions(data.word)
def on_annotations_message(self, data):
self.create_annotation.handle_message(data)
def left_margin_clicked(self, event):
if event.button is 0:
event.preventDefault(), event.stopPropagation()
sd = get_session_data()
self.iframe_wrapper.send_message('next_screen', backwards=True, all_pages_on_screen=sd.get('paged_margin_clicks_scroll_by_screen'))
elif event.button is 2:
event.preventDefault(), event.stopPropagation()
window.setTimeout(self.show_chrome, 0)
self.focus_iframe()
def right_margin_clicked(self, event):
if event.button is 0:
event.preventDefault(), event.stopPropagation()
sd = get_session_data()
self.iframe_wrapper.send_message('next_screen', backwards=False, all_pages_on_screen=sd.get('paged_margin_clicks_scroll_by_screen'))
elif event.button is 2:
event.preventDefault(), event.stopPropagation()
window.setTimeout(self.show_chrome, 0)
self.focus_iframe()
def side_margin_clicked(self, which, event):
self.left_margin_clicked(event) if which is 'left' else self.right_margin_clicked(event)
def top_margin_clicked(self, event):
if event.button is 0 or event.button is 2:
event.preventDefault(), event.stopPropagation()
self.show_chrome()
else:
self.focus_iframe()
def bottom_margin_clicked(self, event):
if event.button is 2:
event.preventDefault(), event.stopPropagation()
window.setTimeout(self.show_chrome, 0)
self.focus_iframe()
def margin_context_menu(self, which, event):
event.preventDefault(), event.stopPropagation()
self.show_chrome()
def on_margin_wheel(self, which, event):
event.preventDefault()
evt = {}
for attr in ('deltaX', 'deltaY', 'deltaMode', 'altKey', 'ctrlKey', 'shiftKey', 'metaKey'):
evt[attr] = event[attr]
self.iframe_wrapper.send_message('wheel_from_margin', evt=evt)
def forward_gesture(self, gesture):
self.iframe_wrapper.send_message('gesture_from_margin', gesture=gesture)
def iframe_size(self):
iframe = self.iframe
l, r = document.getElementById('book-left-margin'), document.getElementById('book-right-margin')
w = r.offsetLeft - l.offsetLeft - iframe.offsetLeft
t, b = document.getElementById('book-top-margin'), document.getElementById('book-bottom-margin')
h = b.offsetTop - t.offsetTop - iframe.offsetTop
return w, h
def on_request_size(self, data):
# On iOS/Safari window.innerWidth/Height are incorrect inside an iframe
window.scrollTo(0, 0) # ensure the window is at 0 because otherwise it sometimes moves down a bit on mobile thanks to the disappearing nav bar
w, h = self.iframe_size()
self.iframe_wrapper.send_message('window_size', width=w, height=h)
def on_print(self, data):
print(data.string)
def on_human_scroll(self, data):
if data.scrolled_by_frac is None:
self.timers.reset_read_timer()
else:
name = self.currently_showing.name
length = self.book.manifest.files[name]?.length
if length:
amt_scrolled = data.scrolled_by_frac * length
self.timers.on_human_scroll(amt_scrolled)
def on_handle_keypress(self, data):
self.handle_keypress(data.evt)
def handle_keypress(self, evt):
if self.overlay.is_visible and evt.key is 'Escape':
if self.overlay.handle_escape():
if evt.preventDefault:
evt.preventDefault(), evt.stopPropagation()
def overlay_visibility_changed(self, visible):
if self.iframe_wrapper.send_message:
self.iframe_wrapper.send_message('overlay_visibility_changed', visible=visible)
if ui_operations.overlay_visibility_changed:
ui_operations.overlay_visibility_changed(visible)
def on_handle_shortcut(self, data):
if data.name is 'back':
window.history.back()
elif data.name is 'forward':
window.history.forward()
elif data.name is 'show_chrome':
self.show_chrome()
elif data.name is 'show_chrome_force':
self.show_chrome_force()
elif data.name is 'toggle_toc':
ui_operations.toggle_toc()
elif data.name is 'toggle_bookmarks':
ui_operations.toggle_bookmarks()
elif data.name is 'new_bookmark':
ui_operations.new_bookmark()
elif data.name is 'toggle_inspector':
ui_operations.toggle_inspector()
elif data.name is 'toggle_lookup':
ui_operations.toggle_lookup()
elif data.name is 'toggle_full_screen':
ui_operations.toggle_full_screen()
elif data.name is 'toggle_paged_mode':
self.toggle_paged_mode()
elif data.name is 'toggle_toolbar':
self.toggle_toolbar()
elif data.name is 'toggle_scrollbar':
self.toggle_scrollbar()
elif data.name is 'quit':
ui_operations.quit()
elif data.name is 'start_search':
self.show_search()
elif data.name is 'next_match':
self.search_overlay.find_next()
elif data.name is 'previous_match':
self.search_overlay.find_previous()
elif data.name is 'increase_font_size':
self.bump_font_size({'increase': True})
elif data.name is 'decrease_font_size':
self.bump_font_size({'increase': False})
elif data.name is 'toggle_full_screen':
ui_operations.toggle_full_screen()
elif data.name is 'toggle_reference_mode':
self.toggle_reference_mode()
elif data.name is 'reload_book':
ui_operations.reload_book()
elif data.name is 'search_for_selection':
if self.currently_showing.selected_text:
self.search_overlay.set_text(self.currently_showing.selected_text)
self.search_overlay.find_next()
elif data.name is 'next_section':
self.on_next_section({'forward': True})
elif data.name is 'previous_section':
self.on_next_section({'forward': False})
elif data.name is 'open_book':
self.overlay.open_book()
elif data.name is 'next':
self.iframe_wrapper.send_message(
'next_screen', backwards=False, all_pages_on_screen=get_session_data().get('paged_margin_clicks_scroll_by_screen'))
elif data.name is 'previous':
self.iframe_wrapper.send_message(
'next_screen', backwards=True, all_pages_on_screen=get_session_data().get('paged_margin_clicks_scroll_by_screen'))
elif data.name is 'print':
ui_operations.print_book()
elif data.name is 'preferences':
self.show_chrome({'initial_panel': 'show_prefs'})
elif data.name is 'metadata':
self.overlay.show_metadata()
elif data.name is 'goto_location':
self.overlay.show_ask_for_location()
elif data.name is 'shrink_selection_by_word':
self.iframe_wrapper.send_message('modify_selection', direction='backward', granularity='word')
elif data.name is 'extend_selection_by_word':
self.iframe_wrapper.send_message('modify_selection', direction='forward', granularity='word')
elif data.name is 'scrollspeed_increase':
self.update_scroll_speed(SCROLL_SPEED_STEP)
elif data.name is 'scrollspeed_decrease':
self.update_scroll_speed(-SCROLL_SPEED_STEP)
elif data.name is 'toggle_autoscroll':
self.toggle_autoscroll()
elif data.name.startsWith('switch_color_scheme:'):
self.switch_color_scheme(data.name.partition(':')[-1])
elif data.name is 'increase_number_of_columns':
self.iframe_wrapper.send_message('change_number_of_columns', delta=1)
elif data.name is 'decrease_number_of_columns':
self.iframe_wrapper.send_message('change_number_of_columns', delta=-1)
elif data.name is 'reset_number_of_columns':
self.iframe_wrapper.send_message('change_number_of_columns', delta=0)
else:
self.iframe_wrapper.send_message('handle_navigation_shortcut', name=data.name)
def on_selection_change(self, data):
self.currently_showing.selected_text = data.text
if ui_operations.selection_changed:
ui_operations.selection_changed(data.text)
def on_columns_per_screen_changed(self, data):
sd = get_session_data()
cps = sd.get('columns_per_screen') or {}
cps[data.which] = int(data.cps)
sd.set('columns_per_screen', cps)
def switch_color_scheme(self, name):
get_session_data().set('current_color_scheme', name)
ui_operations.redisplay_book()
def toggle_paged_mode(self):
sd = get_session_data()
mode = sd.get('read_mode')
new_mode = 'flow' if mode is 'paged' else 'paged'
sd.set('read_mode', new_mode)
ui_operations.redisplay_book()
def toggle_autoscroll(self):
self.iframe_wrapper.send_message('toggle_autoscroll')
def toggle_toolbar(self):
sd = get_session_data()
misc = sd.get('standalone_misc_settings')
misc.show_actions_toolbar = v'!misc.show_actions_toolbar'
sd.set('standalone_misc_settings', misc)
def find(self, text, backwards):
self.iframe_wrapper.send_message('find', text=text, backwards=backwards, searched_in_spine=False)
def on_find_in_spine(self, data):
if data.searched_in_spine:
warning_dialog(
_('Not found'), _('The text: <i>{}</i> was not found in this book').format(html_escape(data.text)),
on_close=def():
self.search_overlay.show()
)
return
spine = self.book.manifest.spine
idx = spine.indexOf(self.currently_showing.name)
if idx < 0:
error_dialog(_('Missing file'), _(
'Could not search as the spine item {} is missing from the book').format(self.currently_showing.name),
on_close=def():
self.search_overlay.show()
)
return
names = v'[]'
item_groups = [range(idx-1, -1, -1), range(spine.length-1, idx, -1)] if data.backwards else [range(idx + 1, spine.length), range(idx)]
for items in item_groups:
for i in items:
names.push(spine[i])
find_in_spine(names, self.book, data.text, def(found_in):
if found_in:
self.show_name(found_in, initial_position={'type':'search', 'search_data':data, 'replace_history':True})
else:
self.iframe_wrapper.send_message('find', text=data.text, backwards=data.backwards, searched_in_spine=True)
)
def bump_font_size(self, data):
delta = 2 if data.increase else -2
change_font_size_by(delta)
def on_show_footnote(self, data):
self.show_content_popup()
self.content_popup_overlay.show_footnote(data)
def hide_overlays(self):
self.overlay.hide()
self.search_overlay.hide()
self.content_popup_overlay.hide()
self.reference_mode_overlay.style.display = 'none'
self.create_annotation.hide()
self.view_annotation.hide()
self.focus_iframe()
def focus_iframe(self):
self.iframe.contentWindow.focus()
def show_chrome(self, data):
elements = {}
if data and data.elements:
elements = data.elements
initial_panel = data?.initial_panel or None
self.get_current_cfi('show-chrome', self.do_show_chrome.bind(None, elements, initial_panel))
def show_chrome_force(self):
self.hide_overlays()
self.show_chrome()
def do_show_chrome(self, elements, initial_panel, request_id, cfi_data):
self.hide_overlays()
self.update_cfi_data(cfi_data)
if initial_panel:
getattr(self.overlay, initial_panel)()
else:
self.overlay.show(elements)
def prepare_for_close(self):
def close_prepared(request_id, cfi_data):
ui_operations.close_prep_finished(cfi_data.cfi)
self.get_current_cfi('prepare-close', close_prepared)
def show_search(self):
self.hide_overlays()
if runtime.is_standalone_viewer:
ui_operations.show_search()
else:
self.search_overlay.show()
def show_content_popup(self):
self.hide_overlays()
self.content_popup_overlay.show()
def set_margins(self):
no_margins = self.currently_showing.name is self.book.manifest.title_page_name
sd = get_session_data()
margin_left = 0 if no_margins else sd.get('margin_left')
margin_right = 0 if no_margins else sd.get('margin_right')
margin_top = 0 if no_margins else sd.get('margin_top')
margin_bottom = 0 if no_margins else sd.get('margin_bottom')
max_text_height = sd.get('max_text_height')
th = window.innerHeight - margin_top - margin_bottom
if not no_margins and max_text_height > 100 and th > max_text_height:
extra = (th - max_text_height) // 2
margin_top += extra
margin_bottom += extra
max_text_width = sd.get('max_text_width')
tw = window.innerWidth - margin_left - margin_right
if not no_margins and max_text_width > 100 and tw > max_text_width:
extra = (tw - max_text_width) // 2
margin_left += extra
margin_right += extra
set_css(document.getElementById('book-top-margin'), height=margin_top + 'px')
set_css(document.getElementById('book-bottom-margin'), height=margin_bottom + 'px')
def side_margin(which, val):
m = document.getElementById('book-{}-margin'.format(which))
if which is 'left':
# Explicitly set the width of the central panel. This is needed
# on small screens with chrome, without it sometimes the right
# margin/scrollbar goes off the screen.
m.nextSibling.style.maxWidth = 'calc(100vw - {}px)'.format(
margin_left + margin_right + self.book_scrollbar.effective_width)
set_css(m, width=val + 'px')
val = min(val, 25)
s = m.querySelector('.arrow').style
s.width = val + 'px'
s.height = val + 'px'
side_margin('left', margin_left), side_margin('right', margin_right)
def on_iframe_ready(self, data):
data.width, data.height = self.iframe_size()
return self.do_pending_load
def do_pending_load(self):
if self.pending_load:
data = self.pending_load
self.pending_load = None
self.show_spine_item_stage2(data)
def on_iframe_error(self, data):
title = data.title or _('There was an error processing the book')
if data.is_non_critical:
warning_dialog(title, data.msg, data.details, on_close=ui_operations.focus_iframe)
return
ui_operations.show_error(title, data.msg, data.details)
def apply_color_scheme(self):
ans = resolve_color_scheme()
self.current_color_scheme = ans
for which in 'left top right bottom'.split(' '):
m = document.getElementById('book-{}-margin'.format(which))
s = m.style
mc = ans[f'margin_{which}']
if mc:
s.backgroundColor, s.color = mc.split(':')
else:
s.color = ans.foreground
s.backgroundColor = ans.background
sd = get_session_data()
iframe = self.iframe
iframe.style.backgroundColor = ans.background or 'white'
bg_image = sd.get('background_image')
if bg_image:
iframe.style.backgroundImage = f'url({READER_BACKGROUND_URL}?{Date().getTime()})' if runtime.is_standalone_viewer else f'url({bg_image})'
else:
iframe.style.backgroundImage = 'none'
if sd.get('background_image_style') is 'scaled':
iframe.style.backgroundSize = '100% 100%'
iframe.style.backgroundRepeat = 'no-repeat'
iframe.style.backgroundAttachment = 'scroll'
iframe.style.backgroundPosition = 'center'
else:
iframe.style.backgroundSize = 'auto'
iframe.style.backgroundRepeat = 'repeat'
iframe.style.backgroundAttachment = 'scroll'
iframe.style.backgroundPosition = '0 0'
self.content_popup_overlay.apply_color_scheme(ans.background, ans.foreground)
self.book_scrollbar.apply_color_scheme(ans)
# this is needed on iOS where the bottom margin has its own margin,
# so we dont want the body background color to bleed through
iframe.parentNode.style.backgroundColor = ans.background
iframe.parentNode.parentNode.style.backgroundColor = ans.background
return ans
def on_resize(self):
if self.book and self.currently_showing.name:
sd = get_session_data()
if sd.get('max_text_width') or sd.get('max_text_height'):
self.set_margins()
def show_loading_message(self, msg):
self.overlay.show_loading_message(msg)
def show_loading(self):
msg = _('Loading next section from <i>{title}</i>, please wait…').format(title=self.book.metadata.title or _('Unknown'))
if self.show_loading_callback_timer is not None:
clearTimeout(self.show_loading_callback_timer)
self.show_loading_callback_timer = setTimeout(self.show_loading_message.bind(None, msg), 200)
def hide_loading(self):
if self.show_loading_callback_timer is not None:
clearTimeout(self.show_loading_callback_timer)
self.show_loading_callback_timer = None
self.iframe.style.visibility = 'visible'
self.overlay.hide_loading_message()
self.focus_iframe()
def parse_cfi(self, encoded_cfi, book):
name = cfi = None
if encoded_cfi and encoded_cfi.startswith('epubcfi(/'):
cfi = encoded_cfi[len('epubcfi(/'):-1]
snum, rest = cfi.partition('/')[::2]
try:
snum = int(snum)
except Exception:
print('Invalid spine number in CFI:', snum)
if jstype(snum) is 'number':
name = book.manifest.spine[(int(snum) // 2) - 1] or name
cfi = '/' + rest
return name, cfi
def display_book(self, book, initial_position):
self.hide_overlays()
self.iframe.focus()
is_current_book = self.book and self.book.key == book.key
self.book_load_started = True
if not is_current_book:
self.iframe_wrapper.reset()
self.content_popup_overlay.iframe_wrapper.reset()
self.loaded_resources = {}
self.content_popup_overlay.loaded_resources = {}
self.timers.start_book(book)
self.book = current_book.book = book
self.annotations_manager.set_highlights(book.highlights or v'[]')
if runtime.is_standalone_viewer:
add_book_to_recently_viewed(book)
if ui_operations.update_last_read_time:
ui_operations.update_last_read_time(book)
pos = {'replace_history':True}
unkey = username_key(get_interface_data().username)
name = book.manifest.spine[0]
cfi = None
if initial_position and initial_position.type is 'cfi' and initial_position.data.startswith('epubcfi(/'):
cfi = initial_position.data
else:
q = parse_url_params()
if q.bookpos and q.bookpos.startswith('epubcfi(/'):
cfi = q.bookpos
elif book.last_read_position and book.last_read_position[unkey]:
cfi = book.last_read_position[unkey]
cfiname, internal_cfi = self.parse_cfi(cfi, book)
if cfiname and internal_cfi:
name = cfiname
pos.type, pos.cfi = 'cfi', internal_cfi
navigated = False
if initial_position:
if initial_position.type is 'toc':
navigated = self.goto_toc_node(initial_position.data)
elif initial_position.type is 'bookpos':
navigated = True
self.goto_book_position(initial_position.data)
elif initial_position.type is 'ref':
navigated = self.goto_reference(initial_position.data)
if navigated:
self.hide_loading()
else:
self.show_name(name, initial_position=pos)
sd = get_session_data()
c = sd.get('controls_help_shown_count', 0)
if c < 2:
show_controls_help()
sd.set('controls_help_shown_count', c + 1)
def preferences_changed(self):
ui_operations.update_url_state(True)
ui_operations.redisplay_book()
def redisplay_book(self):
# redisplay_book() is called when settings are changed
sd = get_session_data()
self.keyboard_shortcut_map = create_shortcut_map(sd.get('keyboard_shortcuts'))
if ui_operations.export_shortcut_map:
ui_operations.export_shortcut_map(self.keyboard_shortcut_map)
self.book_scrollbar.apply_visibility()
self.display_book(self.book)
def iframe_settings(self, name):
sd = get_session_data()
bg_image_fade = 'transparent'
cs = self.apply_color_scheme()
fade = int(sd.get('background_image_fade'))
rgba = cached_color_to_rgba(cs.background)
is_dark_theme = max(rgba[0], rgba[1], rgba[2]) < 115
if self.iframe.style.backgroundImage is not 'none' and fade > 0:
bg_image_fade = f'rgba({rgba[0]}, {rgba[1]}, {rgba[2]}, {fade/100})'
return {
'margin_left': 0 if name is self.book.manifest.title_page_name else sd.get('margin_left'),
'margin_right': 0 if name is self.book.manifest.title_page_name else sd.get('margin_right'),
'read_mode': sd.get('read_mode'),
'columns_per_screen': sd.get('columns_per_screen'),
'color_scheme': cs,
'override_book_colors': sd.get('override_book_colors'),
'is_dark_theme': is_dark_theme,
'bg_image_fade': bg_image_fade,
'base_font_size': sd.get('base_font_size'),
'user_stylesheet': sd.get('user_stylesheet'),
'keyboard_shortcuts': sd.get('keyboard_shortcuts'),
'hide_tooltips': sd.get('hide_tooltips'),
'cover_preserve_aspect_ratio': sd.get('cover_preserve_aspect_ratio'),
'paged_wheel_scrolls_by_screen': sd.get('paged_wheel_scrolls_by_screen'),
'paged_taps_scroll_by_screen': sd.get('paged_taps_scroll_by_screen'),
'lines_per_sec_auto': sd.get('lines_per_sec_auto'),
'lines_per_sec_smooth': sd.get('lines_per_sec_smooth'),
'scroll_auto_boundary_delay': sd.get('scroll_auto_boundary_delay'),
'scroll_stop_boundaries': sd.get('scroll_stop_boundaries'),
}
def show_name(self, name, initial_position=None):
if self.currently_showing.loading:
return
self.processing_spine_item_display = False
initial_position = initial_position or {'replace_history':False}
spine = self.book.manifest.spine
idx = spine.indexOf(name)
self.currently_showing = {
'name':name, 'settings':self.iframe_settings(name), 'initial_position':initial_position,
'loading':True, 'spine_index': idx
}
self.show_loading()
set_current_spine_item(name)
if idx > -1:
self.currently_showing.bookpos = 'epubcfi(/{})'.format(2 * (idx +1))
self.set_margins()
self.load_doc(name, self.show_spine_item)
def load_doc(self, name, done_callback):
def cb(resource_data):
self.loaded_resources = resource_data
done_callback(resource_data)
load_resources(self.book, name, self.loaded_resources, cb)
def goto_doc_boundary(self, start):
name = self.book.manifest.spine[0 if start else self.book.manifest.spine.length - 1]
self.show_name(name, initial_position={'type':'frac', 'frac':0 if start else 1, 'replace_history':False})
def goto_frac(self, frac):
if not self.book or not self.book.manifest:
return
chapter_start_page = 0
total_length = self.book.manifest.spine_length
page = total_length * frac
chapter_frac = 0
chapter_name = None
for name in self.book.manifest.spine:
chapter_length = self.book.manifest.files[name]?.length or 0
chapter_end_page = chapter_start_page + chapter_length
if chapter_start_page <= page <= chapter_end_page:
num_pages = chapter_end_page - chapter_start_page - 1
if num_pages > 0:
chapter_frac = (page - chapter_start_page) / num_pages
else:
chapter_frac = 0
chapter_name = name
break
chapter_start_page = chapter_end_page
if not chapter_name:
chapter_name = self.book.manifest.spine[-1]
chapter_frac = max(0, min(chapter_frac, 1))
if self.currently_showing.name is chapter_name:
self.iframe_wrapper.send_message('scroll_to_frac', frac=chapter_frac)
else:
self.show_name(chapter_name, initial_position={'type':'frac', 'frac':chapter_frac, 'replace_history':True})
def goto_book_position(self, bpos):
val = max(0, min(1000 * float(bpos) / self.current_position_data.book_length, 1))
return self.goto_frac(val)
def on_scroll_to_anchor(self, data):
self.show_name(data.name, initial_position={'type':'anchor', 'anchor':data.frag, 'replace_history':False})
def goto_cfi(self, bookpos):
cfiname, internal_cfi = self.parse_cfi(bookpos, self.book)
if cfiname and internal_cfi:
# replace_history has to be true here otherwise forward does not
# work after back, as back uses goto_cfi
pos = {'replace_history': True}
name = cfiname
pos.type, pos.cfi = 'cfi', internal_cfi
self.show_name(name, initial_position=pos)
return True
return False
def goto_reference(self, reference):
if not self.book or not self.book.manifest:
return
index, refnum = reference.split('.')
index, refnum = int(index), int(refnum)
chapter_name = self.book.manifest.spine[index]
if not chapter_name:
return False
if self.currently_showing.name is chapter_name:
self.iframe_wrapper.send_message('scroll_to_ref', refnum=refnum)
else:
self.show_name(chapter_name, initial_position={'type':'ref', 'refnum':refnum, 'replace_history':True})
return True
def goto_named_destination(self, name, frag):
if self.currently_showing.name is name:
self.iframe_wrapper.send_message('scroll_to_anchor', frag=frag)
else:
spine = self.book.manifest.spine
idx = spine.indexOf(name)
if idx is -1:
error_dialog(_('Destination does not exist'), _(
'The file {} does not exist in this book').format(name), on_close=def():
ui_operations.focus_iframe()
)
return False
self.show_name(name, initial_position={'type':'anchor', 'anchor':frag, 'replace_history':False})
return True
def goto_toc_node(self, node_id):
toc = self.book.manifest.toc
found = False
def process_node(x):
nonlocal found
if x.id is node_id:
self.goto_named_destination(x.dest or '', x.frag or '')
found = True
return
for c in x.children:
process_node(c)
if toc:
process_node(toc)
return found
def on_next_spine_item(self, data):
spine = self.book.manifest.spine
idx = spine.indexOf(self.currently_showing.name)
if data.previous:
if idx is 0:
return
idx = min(spine.length - 1, max(idx - 1, 0))
self.show_name(spine[idx], initial_position={'type':'frac', 'frac':1, 'replace_history':True})
else:
if idx is spine.length - 1:
return
idx = max(0, min(spine.length - 1, idx + 1))
self.show_name(spine[idx], initial_position={'type':'frac', 'frac':0, 'replace_history':True})
def on_next_section(self, data):
toc_node = get_next_section(data.forward)
if toc_node:
self.goto_named_destination(toc_node.dest, toc_node.frag)
def get_current_cfi(self, request_id, callback):
self.get_cfi_counter += 1
request_id += ':' + self.get_cfi_counter
self.report_cfi_callbacks[request_id] = callback
self.iframe_wrapper.send_message('get_current_cfi', request_id=request_id)
def update_cfi_data(self, data):
self.currently_showing.bookpos = data.cfi
self.currently_showing.selected_text = data.selected_text
username = get_interface_data().username