-
Notifications
You must be signed in to change notification settings - Fork 25
/
eaf_pdf_widget.py
1842 lines (1522 loc) · 73.8 KB
/
eaf_pdf_widget.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
# -*- coding: utf-8 -*-
# Copyright (C) 2018 Andy Stewart
#
# Author: Andy Stewart <lazycat.manatee@gmail.com>
# Maintainer: Andy Stewart <lazycat.manatee@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import math
import time
import webbrowser
import fitz
from core.utils import *
from eaf_pdf_annot import AnnotAction
from eaf_pdf_document import PdfDocument
from eaf_pdf_utils import support_hit_max
from PyQt6.QtCore import QEvent, QPoint, QRect, Qt, QTimer, pyqtSignal
from PyQt6.QtGui import QColor, QCursor, QFont, QPainter, QPalette
from PyQt6.QtWidgets import QApplication, QToolTip, QWidget
def set_page_crop_box(page):
if hasattr(page, "set_cropbox"):
return page.set_cropbox
else:
return page.set_cropbox
class PdfViewerWidget(QWidget):
translate_double_click_word = pyqtSignal(str)
def __init__(self, url, background_color, buffer, buffer_id, synctex_info):
super(PdfViewerWidget, self).__init__()
self.url = url
self.config_dir = get_emacs_config_dir()
self.background_color = background_color
self.buffer = buffer
self.buffer_id = buffer_id
self.user_name = get_emacs_var("user-full-name")
self.is_button_press = False
self.synctex_info = synctex_info
self.installEventFilter(self)
self.setMouseTracking(True)
(self.marker_letters,
self.pdf_dark_mode,
self.pdf_dark_exclude_image,
self.pdf_default_zoom,
self.pdf_zoom_step,
self.pdf_scroll_ratio,
self.text_highlight_annot_color,
self.text_underline_annot_color,
self.inline_text_annot_color,
self.inline_text_annot_fontsize) = get_emacs_vars([
"eaf-marker-letters",
"eaf-pdf-dark-mode",
"eaf-pdf-dark-exclude-image",
"eaf-pdf-default-zoom",
"eaf-pdf-zoom-step",
"eaf-pdf-scroll-ratio",
"eaf-pdf-text-highlight-annot-color",
"eaf-pdf-text-underline-annot-color",
"eaf-pdf-inline-text-annot-color",
"eaf-pdf-inline-text-annot-fontsize"])
self.theme_mode = get_emacs_theme_mode()
self.theme_foreground_color = get_emacs_theme_foreground()
self.theme_background_color = get_emacs_theme_background()
# Init scale and scale mode.
self.scale = 1.0
self.scale_before_presentation = 1.0
self.read_mode = "fit_to_width"
self.read_mode_before_presentation = "fit_to_width"
self.rotation = 0
# Simple string comparation.
if (self.pdf_default_zoom != 1.0):
self.read_mode = "fit_to_customize"
self.scale = self.pdf_default_zoom
self.horizontal_offset = 0
# Undo/redo annot actions
self.annot_action_sequence = []
self.annot_action_index = -1
# mark link
self.is_mark_link = False
#jump link
self.is_jump_link = False
self.link_page_num = None
self.link_page_offset_x = None
self.link_page_offset_y = None
self.jump_link_key_cache_dict = {}
# hover link
self.is_hover_link = False
self.last_hover_link = None
#global search text
self.is_mark_search = False
self.search_term = ""
self.last_search_term = ""
self.search_mode_forward = False
self.search_mode_backward = False
self.search_text_offset_list = []
self.current_search_quads = None
self.search_text_quads_list = []
# select text
self.is_select_mode = False
self.start_char_rect_index = None
self.start_char_page_index = None
self.last_char_rect_index = None
self.last_char_page_index = None
self.select_area_annot_quad_cache_dict = {}
# text annot
self.is_hover_annot = False
self.hovered_annot = None
self.edited_annot_page = (None, None)
self.moved_annot_page = (None, None)
# popup text annot
self.popup_text_annot_timer = QTimer()
self.popup_text_annot_timer.setInterval(300)
self.popup_text_annot_timer.setSingleShot(True)
self.popup_text_annot_timer.timeout.connect(self.handle_popup_text_annot_mode) # type: ignore
self.is_popup_text_annot_mode = False
self.is_popup_text_annot_handler_waiting = False
self.popup_text_annot_pos = (None, None)
# inline text annot
self.inline_text_annot_timer = QTimer()
self.inline_text_annot_timer.setInterval(300)
self.inline_text_annot_timer.setSingleShot(True)
self.inline_text_annot_timer.timeout.connect(self.handle_inline_text_annot_mode) # type: ignore
self.is_inline_text_annot_mode = False
self.is_inline_text_annot_handler_waiting = False
self.inline_text_annot_pos = (None, None)
self.is_rect_annot_mode = False
self.rect_annot_beg_ex = 0
self.rect_annot_beg_ey = 0
# move text annot
self.move_text_annot_timer = QTimer()
self.move_text_annot_timer.setInterval(300)
self.move_text_annot_timer.setSingleShot(True)
self.move_text_annot_timer.timeout.connect(self.handle_move_text_annot_mode) # type: ignore
self.is_move_text_annot_mode = False
self.is_move_text_annot_handler_waiting = False
self.move_text_annot_pos = (None, None)
# Init scroll attributes.
self.scroll_offset = 0
self.scroll_offset_before_presentation = 0
self.scroll_ratio = 0.05
self.scroll_wheel_lasttime = time.time()
if self.pdf_scroll_ratio != 0.05:
self.scroll_ratio = self.pdf_scroll_ratio
# Default presentation mode
self.presentation_mode = False
# Padding between pages.
self.page_padding = 10
# Fill app background color
self.fill_background()
# Init font.
self.page_annotate_padding_x = 10
self.page_annotate_padding_y = 10
self.font = QFont() # type: ignore
self.font_size = 24
self.font.setPointSize(self.font_size)
# Page cache.
self.page_cache_pixmap_dict = {}
self.page_cache_scale = self.scale
self.page_cache_trans = None
self.page_cache_context_delay = 1000
self.last_action_time = 0
self.is_page_just_changed = False
self.remember_offset = None
self.last_hover_annot_id = None
# Saved positions
self.saved_pos_sequence = []
self.saved_pos_index = -1
self.remember_offset = None
self.start_page_index = 0
self.start_page_index_before_presentation = 0
self.current_page_index = 0
self.last_page_index = 0
self.load_document(url)
# Inverted mode.
self.inverted_mode = False
# Inverted mode exclude image. (current exclude image inner implement use PDF Only method)
self.inverted_image_mode = not self.pdf_dark_exclude_image and self.document.is_pdf
# synctex init page
if self.synctex_info.page_num is not None:
self.jump_to_page(self.synctex_info.page_num) # type: ignore
def fill_background(self):
pal = self.palette()
pal.setColor(QPalette.ColorRole.Window, self.background_color)
self.setAutoFillBackground(True)
self.setPalette(pal)
def load_document(self, url):
if self.page_cache_pixmap_dict:
self.page_cache_pixmap_dict.clear()
self.document.reset_cache()
# Load document first.
try:
self.document = PdfDocument(fitz.open(url)) # type: ignore
except Exception:
message_to_emacs("Failed to load PDF file: " + url)
return
# recompute width, height, total number since the file might be modified
self.document.watch_page_size_change(self.update_page_size)
self.page_width = self.document.get_page_width()
self.page_height = self.document.get_page_height()
self.page_total_number = self.document.page_count
# Register file watcher, when document is change, re-calling this function.
self.document.watch_file(url, self.load_document)
self.update()
def is_buffer_focused(self):
# This check is slow, use only when necessary
try:
return get_emacs_func_result("eaf-get-path-or-url", []) == self.url
except Exception:
return False
@interactive
def enter_presentation_mode(self):
self.presentation_mode = True
self.scale_before_presentation = self.scale
self.read_mode_before_presentation = self.read_mode
self.scroll_offset_before_presentation = self.scroll_offset
self.start_page_index_before_presentation = self.start_page_index
self.buffer.enter_fullscreen_request.emit()
# Make current page fill the view.
self.zoom_reset("fit_to_presentation")
@interactive
def quit_presentation_mode(self):
self.presentation_mode = False
self.buffer.exit_fullscreen_request.emit()
self.scale = self.scale_before_presentation
if self.start_page_index == self.start_page_index_before_presentation:
self.scroll_offset = self.scroll_offset_before_presentation
else:
self.scroll_offset = self.start_page_index * self.page_height * self.scale
if self.read_mode_before_presentation == "fit_to_width":
self.zoom_reset()
else:
self.read_mode = "fit_to_customize"
text_width = self.document.get_page_width()
fit_to_width = self.rect().width() / text_width
self.scale_to(min(max(10, fit_to_width), self.scale))
self.update()
@interactive
def toggle_presentation_mode(self):
'''
Toggle presentation mode.
'''
self.presentation_mode = not self.presentation_mode
if self.presentation_mode:
self.enter_presentation_mode()
else:
self.quit_presentation_mode()
@property
def scroll_step_vertical(self):
if self.presentation_mode:
return self.rect().height()
else:
return self.rect().size().height() * self.scroll_ratio
@property
def scroll_step_horizontal(self):
if self.presentation_mode:
return self.rect().width()
else:
return self.rect().size().width() * self.scroll_ratio
@interactive
def save_current_pos(self):
self.remember_offset = self.scroll_offset
self.saved_pos_index = len(self.saved_pos_sequence)
self.saved_pos_sequence.append(self.scroll_offset)
message_to_emacs("Saved current position.")
@interactive
def jump_to_saved_pos(self):
if self.remember_offset is None:
message_to_emacs("Cannot jump from this position.")
else:
current_scroll_offset = self.scroll_offset
self.scroll_offset = self.remember_offset
self.update()
self.remember_offset = current_scroll_offset
message_to_emacs("Jumped to saved position.")
@interactive
def jump_to_previous_saved_pos(self):
if self.saved_pos_index < 0:
message_to_emacs("No more previous saved postition.")
else:
if self.saved_pos_index + 1 == len(self.saved_pos_sequence):
self.saved_pos_sequence.append(self.scroll_offset)
self.scroll_offset = self.saved_pos_sequence[self.saved_pos_index]
self.saved_pos_index = self.saved_pos_index - 1
self.update()
message_to_emacs("Jumped to previous saved position.")
@interactive
def jump_to_next_saved_pos(self):
if self.saved_pos_index + 1 >= len(self.saved_pos_sequence):
message_to_emacs("No more next saved position.")
else:
self.scroll_offset = self.saved_pos_sequence[self.saved_pos_index]
self.saved_pos_index = self.saved_pos_index + 1
self.update()
message_to_emacs("Jumped to next saved position.")
def get_page_pixmap(self, index, scale, rotation=0):
# Just return cache pixmap when found match index and scale in cache dict.
if self.page_cache_scale == scale:
if index in self.page_cache_pixmap_dict.keys():
return self.page_cache_pixmap_dict[index]
# Clear dict if page scale changed.
else:
self.page_cache_pixmap_dict.clear()
self.page_cache_scale = scale
page = self.document[index]
if self.document.is_pdf:
page.set_rotation(rotation)
if self.is_mark_link:
page.add_mark_link()
else:
page.cleanup_mark_link()
# follow page search text
if self.is_mark_search:
page.mark_search_text(self.search_term, self.current_search_quads)
else:
page.cleanup_search_text()
if self.is_jump_link:
self.jump_link_key_cache_dict.update(page.mark_jump_link_tips(self.marker_letters))
else:
page.cleanup_jump_link_tips()
self.jump_link_key_cache_dict.clear()
qpixmap = page.get_qpixmap(scale, self.get_inverted_mode(), self.inverted_image_mode)
self.page_cache_pixmap_dict[index] = qpixmap
self.document.cache_page(index, page)
return qpixmap
def get_page_render_info(self, index):
# Get HiDPI scale factor.
# Note:
# Don't delete hidpi_scale_factor even it value is 1.0,
# PDF page will become blurred if delete this variable.
hidpi_scale_factor = self.devicePixelRatioF()
# Get page pixmap.
qpixmap = self.get_page_pixmap(index, self.scale * hidpi_scale_factor, self.rotation)
page_render_width = qpixmap.width() / hidpi_scale_factor
page_render_height = qpixmap.height() / hidpi_scale_factor
return (qpixmap, page_render_width, page_render_height)
def clean_unused_page_cache_pixmap(self):
# We need expand render index bound that avoid clean cache around current index.
index_list = list(range(self.start_page_index, self.last_page_index))
# Try to clean unused cache.
cache_index_list = list(self.page_cache_pixmap_dict.keys())
for cache_index in cache_index_list:
if cache_index not in index_list:
self.page_cache_pixmap_dict.pop(cache_index)
self.document.remove_cache(cache_index)
def resizeEvent(self, event):
# Update scale attributes after widget resize.
self.update_scale()
QWidget.resizeEvent(self, event)
def get_inverted_mode(self):
if self.pdf_dark_mode == "follow":
if self.theme_mode == "dark":
# Invert render BLACK font when load dark theme.
return not self.inverted_mode
else:
# Invert render WHITE font when load light theme.
return self.inverted_mode
elif self.pdf_dark_mode == "force":
# Always render WHITE font.
return True
else:
# Always render BLACK font.
return False
def get_render_background_color(self):
if self.pdf_dark_mode == "follow":
if self.theme_mode == "dark":
# When load dark theme.
# Invert render WHITE background, normal render background same as Emacs background.
return "#FFFFFF" if self.inverted_mode else self.theme_background_color
else:
# When load light theme.
# Invert render BLACK background, normal render background same as Emacs background.
return "#000000" if self.inverted_mode else self.theme_background_color
elif self.pdf_dark_mode == "force":
# When load dark theme, render background same as Emacs background.
# When load light theme, render BLACK background.
return self.theme_background_color if self.theme_mode == "dark" else "#000000"
else:
# Always render WHITE background.
return "#FFFFFF"
def get_render_foreground_color(self):
if self.pdf_dark_mode == "follow":
# Render invert color.
return self.theme_background_color if self.inverted_mode else self.theme_foreground_color
elif self.pdf_dark_mode == "force":
# Always render light color.
return self.theme_foreground_color if self.theme_mode == "dark" else self.theme_background_color
else:
# Alwasy render BLACK font.
return "#000000"
def paintEvent(self, event):
# update page base information
self.update_page_index()
# Init painter.
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceAtop)
painter.save()
# Draw background.
color = QColor(self.get_render_background_color())
painter.setBrush(color)
painter.setPen(color)
# Draw page.
if self.read_mode == "fit_to_presentation":
self.draw_presentation_page(painter, self.start_page_index)
else:
self.draw_scroll_pages(painter)
# Clean unused pixmap cache that avoid use too much memory.
self.clean_unused_page_cache_pixmap()
# Restore painter.
painter.restore()
# Render progress information.
painter.setFont(self.font) # type: ignore
painter.setPen(QColor(self.get_render_foreground_color()))
self.update_page_progress(painter)
def draw_presentation_page(self, painter, index):
# Get page render information.
(qpixmap, self.page_render_width, self.page_render_height) = self.get_page_render_info(index)
# Select char area when is_select_mode is True.
if self.is_select_mode:
qpixmap = self.mark_select_char_area(index, qpixmap)
# Init x and y coordinate.
self.page_render_x = (self.rect().width() - self.page_render_width) / 2
self.page_render_y = (self.rect().height() - self.page_render_height) / 2
# Adjust coordinate and size when actual size smaller than visiable area.
page_proportion = self.page_render_height * 1.0 / self.page_render_width
if page_proportion > 1:
self.page_render_y = 0
if self.rect().height() > self.page_render_height:
self.page_render_height = self.rect().height()
self.page_render_width = self.page_render_height / page_proportion
else:
self.page_render_x = 0
if self.rect().width() > self.page_render_width:
self.page_render_width = self.rect().width()
self.page_render_height = self.page_render_width * page_proportion
# Draw page.
rect = QRect(int(self.page_render_x), int(self.page_render_y), int(self.page_render_width), int(self.page_render_height))
painter.drawRect(rect)
painter.drawPixmap(rect, qpixmap)
def draw_scroll_pages(self, painter):
# Record start page index before change page.
old_start_page_index = self.start_page_index
# Calcucate render range.
self.start_page_index = min(
int(self.scroll_offset * 1.0 / self.scale / self.page_height),
self.page_total_number - 1)
self.last_page_index = min(
int((self.scroll_offset + self.rect().height()) * 1.0 / self.scale / self.page_height + 2),
self.page_total_number)
# We need adjust scroll offset if the actual height of the page is lower than the theoretical height returned by mupdf.
(_, _, page_render_height) = self.get_page_render_info(self.start_page_index)
if self.page_height * self.scale - page_render_height > 0:
self.scroll_offset += (self.start_page_index - old_start_page_index) * self.scroll_step_vertical
# Avoid scroll offset out of round.
self.scroll_offset = max(0, min(self.scroll_offset, self.max_scroll_offset()))
# Translate coordinate with scroll offset.
painter.translate(0, -self.scroll_offset)
for index in list(range(self.start_page_index, self.last_page_index)):
# Draw page.
self.draw_scroll_page(painter, index)
# Draw an indicator for synctex position
if self.synctex_info.page_num == index + 1 and self.synctex_info.pos_y is not None:
pos_y = int(self.page_render_y + self.synctex_info.pos_y * self.scale)
self.draw_arrow_indicator(painter, 15, pos_y)
elif self.link_page_num == index + 1 and self.link_page_offset_y is not None:
pos_x = int(self.page_render_x + self.link_page_offset_x)
pos_y = int(self.page_render_y + self.link_page_offset_y)
pos_x = max(0, pos_x - 30)
pos_y = pos_y + 12
self.draw_arrow_indicator(painter, pos_x, pos_y)
def draw_scroll_page(self, painter, index):
# Draw page padding.
if index != 0:
painter.translate(0, self.page_padding)
# Get page render information.
(qpixmap, self.page_render_width, self.page_render_height) = self.get_page_render_info(index)
# Select char area when is_select_mode is True.
if self.is_select_mode:
qpixmap = self.mark_select_char_area(index, qpixmap)
# Init x coordinate.
self.page_render_x = (self.rect().width() - self.page_render_width) / 2
# Adjust x coordinate coordinate of render page.
if self.read_mode == "fit_to_customize" and self.page_render_width >= self.rect().width():
# limit the visiable area size
self.page_render_x = max(min(self.page_render_x + self.horizontal_offset, 0), self.rect().width() - self.page_render_width)
# Render page with page index, scale and page height.
self.page_render_y = index * self.scale * self.page_height
# NOTE:
# We need translate coordinate inverse if the actual height of the page is lower than the theoretical height returned by mupdf.
# otherwise, padding between two pages will become too big.
height_deviation = (self.page_height * self.scale - self.page_render_height)
if self.scroll_offset < self.max_scroll_offset() - self.page_height:
# Scroll up deviation between actual height and render height.
painter.translate(0, -height_deviation)
else:
# Scroll down to avoid padding after last page.
painter.translate(0, height_deviation)
# Draw page.
rect = QRect(int(self.page_render_x), int(self.page_render_y), int(self.page_render_width), int(self.page_render_height))
painter.drawRect(rect)
painter.drawPixmap(rect, qpixmap)
def draw_arrow_indicator(self, painter, x, y):
from PyQt6.QtGui import QPolygon
painter.save()
arrow = QPolygon([QPoint(x, y), QPoint(x+13, y), QPoint(x+13, y-4),
QPoint(x+21, y+3),
QPoint(x+13, y+10), QPoint(x+13, y+6), QPoint(x, y+6),
QPoint(x, y)])
fill_color = QColor(236, 96, 31, 255)
border_color = QColor(255, 91, 15, 255)
painter.setBrush(fill_color)
painter.setPen(border_color)
painter.drawPolygon(arrow)
QTimer().singleShot(5000, self.clear_arrow_indicator)
painter.restore()
def clear_arrow_indicator(self):
self.synctex_info.reset()
self.link_page_num = None
self.link_page_offset_y = None
def update_page_progress(self, painter):
# Show in mode-line-position
eval_in_emacs("eaf--pdf-update-position", [self.buffer_id,
self.current_page_index,
self.page_total_number])
# Draw progress on page.
show_progress_on_page, = get_emacs_vars(["eaf-pdf-show-progress-on-page"])
if show_progress_on_page:
progress_rect = QRect(int(self.page_render_x + self.page_annotate_padding_x),
int(self.rect().y() + self.page_annotate_padding_y),
int(self.page_render_width - self.page_annotate_padding_x * 2),
int(self.rect().height() - self.page_annotate_padding_y * 2))
scaling_ratio = self.page_render_width / self.rect().width()
progress_font_size = max(int(self.font_size * (1 - math.cos(scaling_ratio * math.pi)) / 2), 0.1)
painter.setFont(QFont(self.font.family(), progress_font_size))
painter.drawText(progress_rect,
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignBottom,
self.get_page_progress())
def get_page_progress(self):
progress_percent = int(self.current_page_index * 100 / self.page_total_number)
return "{}% [{}/{}]".format(progress_percent,
self.current_page_index,
self.page_total_number)
def build_context_wrap(f): # type: ignore
def wrapper(*args):
# Get self instance object.
self_obj = args[0]
# Record page before action.
page_before_action = self_obj.start_page_index
# Do action.
ret = f(*args) # type: ignore
# Record page after action.
page_after_action = self_obj.start_page_index
self_obj.is_page_just_changed = (page_before_action != page_after_action)
# Start build context timer.
self_obj.last_action_time = time.time()
QTimer().singleShot(self_obj.page_cache_context_delay, self_obj.build_context_cache)
return ret
return wrapper
@build_context_wrap # type: ignore
def wheelEvent(self, event):
if not event.accept():
if event.angleDelta().y():
numSteps = event.angleDelta().y()
if self.presentation_mode:
# page scrolling
curtime = time.time()
if curtime - self.scroll_wheel_lasttime > 0.1:
numSteps = 1 if numSteps > 0 else -1
self.scroll_wheel_lasttime = curtime
else:
numSteps = 0
else:
# fixed pixel scrolling
numSteps = numSteps / 120
new_pos = self.scroll_offset - numSteps * self.scroll_step_vertical
max_pos = self.max_scroll_offset()
self.update_vertical_offset(max(min(new_pos, max_pos), 0)) # type: ignore
if event.angleDelta().x():
new_pos = (self.horizontal_offset + event.angleDelta().x() / 120 * self.scroll_step_horizontal)
max_pos = (self.page_width * self.scale - self.rect().width())
self.update_horizontal_offset(max(min(new_pos , max_pos), -max_pos)) # type: ignore
def update_page_index(self):
# Don't adjust start_page_index if is in presentation mode.
if self.read_mode != "fit_to_presentation":
self.start_page_index = min(int(self.scroll_offset * 1.0 / self.scale / self.page_height),
self.page_total_number - 1)
if self.scroll_offset == 0:
self.current_page_index = 1
elif self.scroll_offset == self.max_scroll_offset():
self.current_page_index = self.page_total_number
else:
self.current_page_index = max(math.ceil(((self.scroll_offset + self.rect().height() * 5.0 / 9.0) / self.scale / self.page_height)),
self.start_page_index + 1)
self.last_page_index = min(int((self.scroll_offset + self.rect().height()) * 1.0 / self.scale / self.page_height) + 1,
self.page_total_number)
def update_page_size(self, rect):
current_page_index = self.start_page_index
self.page_width = rect.width
self.page_height = rect.height
self.jump_to_page(current_page_index) # type: ignore
def build_context_cache(self):
# Just build context cache when action duration longer than delay
# Don't build contexnt cache when is_page_just_changed is True, avoid flickr when user change page.
last_action_duration = (time.time() - self.last_action_time) * 1000
if last_action_duration > self.page_cache_context_delay and not self.is_page_just_changed:
for index in list(range(self.start_page_index, self.last_page_index)):
self.get_page_pixmap(index, self.scale, self.rotation)
def scale_to(self, new_scale):
self.scroll_offset = new_scale * 1.0 / self.scale * self.scroll_offset
self.scale = new_scale
def scale_to_width(self):
self.scale_to(self.rect().width() * 1.0 / self.page_width)
def scale_to_presentation(self):
self.scale_to(min(self.rect().width() * 1.0 / self.page_width,
self.rect().height() * 1.0 / self.page_height))
def update_scale(self):
if self.read_mode == "fit_to_width":
self.scale_to_width()
elif self.read_mode == "fit_to_presentation":
self.scale_to_presentation()
def max_scroll_offset(self):
max_scroll_offset = self.scale * self.page_height * self.page_total_number - self.rect().height()
if max_scroll_offset < 0:
max_scroll_offset = 0
return max_scroll_offset
@interactive
def reload_document(self):
message_to_emacs("Reloaded PDF file!")
self.load_document(self.url)
@interactive
def toggle_read_mode(self):
if self.read_mode == "fit_to_customize":
self.read_mode = "fit_to_width"
elif self.read_mode == "fit_to_width":
self.read_mode = "fit_to_presentation"
elif self.read_mode == "fit_to_presentation":
self.read_mode = "fit_to_width"
self.update_scale()
self.update()
def next_page(self):
if self.start_page_index < self.page_total_number - 1:
self.start_page_index = self.start_page_index + 1
self.update()
def prev_page(self):
if self.start_page_index > 0:
self.start_page_index = self.start_page_index - 1
self.update()
@interactive
def scroll_up(self):
if self.read_mode == "fit_to_presentation":
self.next_page()
else:
self.update_vertical_offset(min(self.scroll_offset + self.scroll_step_vertical, self.max_scroll_offset())) # type: ignore
@interactive
def scroll_down(self):
if self.read_mode == "fit_to_presentation":
self.prev_page()
else:
self.update_vertical_offset(max(self.scroll_offset - self.scroll_step_vertical, 0)) # type: ignore
@interactive
def scroll_up_page(self):
if self.presentation_mode:
self.next_page()
else:
# Adjust scroll step to make users continue reading fluently.
self.update_vertical_offset(min(self.scroll_offset + self.rect().height() - self.scroll_step_vertical, self.max_scroll_offset())) # type: ignore
@interactive
def scroll_down_page(self):
if self.presentation_mode:
self.prev_page()
else:
# Adjust scroll step to make users continue reading fluently.
self.update_vertical_offset(max(self.scroll_offset - self.rect().height() + self.scroll_step_vertical, 0)) # type: ignore
@interactive
def scroll_right(self):
self.update_horizontal_offset(max(self.horizontal_offset - self.scroll_step_horizontal, (self.rect().width() - self.page_width * self.scale) / 2)) # type: ignore
@interactive
def scroll_left(self):
self.update_horizontal_offset(min(self.horizontal_offset + self.scroll_step_horizontal, (self.page_width * self.scale - self.rect().width()) / 2)) # type: ignore
@interactive
def scroll_center_horizontal(self):
self.update_horizontal_offset(0) # type: ignore
@interactive
def scroll_to_begin(self):
self.update_vertical_offset(0) # type: ignore
@interactive
def scroll_to_end(self):
self.update_vertical_offset(self.max_scroll_offset()) # type: ignore
@interactive
def zoom_in(self):
self.read_mode = "fit_to_customize"
text_width = self.document.get_page_width()
fit_to_width = self.rect().width() / text_width
self.scale_to(min(max(10, fit_to_width), self.scale + self.pdf_zoom_step))
self.update()
@interactive
def zoom_out(self):
self.read_mode = "fit_to_customize"
self.scale_to(max(1, self.scale - self.pdf_zoom_step))
self.update()
@interactive
def zoom_fit_text_width(self):
self.read_mode = "fit_to_customize"
text_width = self.document.get_page_width()
self.scale_to(self.rect().width() / text_width)
self.scroll_center_horizontal()
self.update()
@interactive
def zoom_close_to_text_width(self):
self.read_mode = "fit_to_customize"
text_width = self.document.get_page_width()
self.scale_to(self.rect().width() * 0.9 / text_width)
self.scroll_center_horizontal()
self.update()
@interactive
def zoom_reset(self, read_mode="fit_to_width"):
if self.is_mark_search:
self.cleanup_search()
self.read_mode = read_mode
self.update_scale()
self.update()
@interactive
def toggle_trim_white_margin(self):
current_page_index = self.start_page_index
self.document.toggle_trim_margin()
self.page_cache_pixmap_dict.clear()
self.update()
self.jump_to_page(current_page_index) # type: ignore
@interactive
def toggle_inverted_mode(self):
# Need clear page cache first, otherwise current page will not inverted until next page.
self.page_cache_pixmap_dict.clear()
self.inverted_mode = not self.inverted_mode
self.update()
return
@interactive
def toggle_inverted_image_mode(self):
# Toggle inverted image status.
if not self.document.is_pdf:
message_to_emacs("Only support PDF!")
return
self.page_cache_pixmap_dict.clear()
self.inverted_image_mode = not self.inverted_image_mode
# Re-render page.
self.update()
@interactive
def toggle_mark_link(self): # mark_link will add underline mark on link, using prompt link position.
self.is_mark_link = not self.is_mark_link and self.document.is_pdf
self.page_cache_pixmap_dict.clear()
self.update()
def update_rotate(self, rotate):
if self.document.is_pdf:
current_page_index = self.start_page_index
self.rotation = rotate
self.page_width, self.page_height = self.page_height, self.page_width
# Need clear page cache first, otherwise current page will not inverted until next page.
self.page_cache_pixmap_dict.clear()
self.update_scale()
self.update()
self.jump_to_page(current_page_index) # type: ignore
else:
message_to_emacs("Only support PDF!")
@interactive
def rotate_clockwise(self):
self.update_rotate((self.rotation + 90) % 360)
def add_annot_of_action(self, annot_action):
new_annot = None
page = self.document[annot_action.page_index]
quads = annot_action.annot_quads
if (annot_action.annot_type == fitz.PDF_ANNOT_HIGHLIGHT):
new_annot = page.add_highlight_annot(quads)
new_annot.set_colors(stroke=annot_action.annot_stroke_color)
new_annot.update()
elif (annot_action.annot_type == fitz.PDF_ANNOT_STRIKE_OUT):
new_annot = page.add_strikeout_annot(quads)
elif (annot_action.annot_type == fitz.PDF_ANNOT_UNDERLINE):
new_annot = page.add_underline_annot(quads)
new_annot.set_colors(stroke=annot_action.annot_stroke_color)
new_annot.update()
elif (annot_action.annot_type == fitz.PDF_ANNOT_SQUIGGLY):
new_annot = page.add_squiggly_annot(quads)
elif (annot_action.annot_type == fitz.PDF_ANNOT_TEXT):
new_annot = page.add_text_annot(annot_action.annot_top_left_point,
annot_action.annot_content, icon="Note")
elif (annot_action.annot_type == fitz.PDF_ANNOT_FREE_TEXT):
color = QColor(self.inline_text_annot_color)
color_r, color_g, color_b = color.redF(), color.greenF(), color.blueF()
text_color = [color_r, color_g, color_b]
new_annot = page.add_freetext_annot(annot_action.annot_rect,
annot_action.annot_content,
fontsize=self.inline_text_annot_fontsize,
fontname="Arial",
text_color=text_color, align=0)
elif (annot_action.annot_type == fitz.PDF_ANNOT_SQUARE):
new_annot = page.add_rect_annot(annot_action.annot_rect)
if new_annot:
new_annot.set_info(title=annot_action.annot_title)
new_annot.parent = page
self.save_annot()
def delete_annot_of_action(self, annot_action):
page = self.document[annot_action.page_index]
annot = AnnotAction.find_annot_of_annot_action(page, annot_action)
if annot:
page.delete_annot(annot)
self.save_annot()
@interactive
def rotate_counterclockwise(self):
self.update_rotate((self.rotation - 90) % 360)
@interactive
def undo_annot_action(self):
if (self.annot_action_index < 0):
message_to_emacs("No further undo action!")
else: