-
Notifications
You must be signed in to change notification settings - Fork 84
/
ui.py
2032 lines (1574 loc) · 78.3 KB
/
ui.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 -*-
#
# ui.py
#
# Copyright 2010 Thomas Jost <thomas.jost@gmail.com>
# Copyright 2015 Cimbali <me@cimba.li>
#
# 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 2 of the License, or
# (at your option) 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
"""
:mod:`pympress.ui` -- GUI management
------------------------------------
This module contains the whole graphical user interface of pympress, which is
made of two separate windows: the Content window, which displays only the
current page in full size, and the Presenter window, which displays both the
current and the next page, as well as a time counter and a clock.
Both windows are managed by the :class:`~pympress.ui.UI` class.
"""
import logging
logger = logging.getLogger(__name__)
import pathlib
import math
import sys
import gc
from urllib.request import url2pathname
from urllib.parse import urlsplit
import gi
import cairo
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gtk, Gdk, GLib, GdkPixbuf, Gio
from pympress import (
document, surfacecache, util, pointer, scribble, deck, builder, talk_time, dialog, extras, editable_label
)
class UI(builder.Builder):
""" Pympress GUI management.
"""
#: The :class:`~pympress.app.Pympress` instance
app = None
#: Content window, as a :class:`~Gtk.Window` instance.
c_win = None
#: :class:`~Gtk.AspectFrame` for the Content window.
c_frame = None
#: :class:`~Gtk.DrawingArea` for the Content window.
c_da = None
#: Presenter window, as a :class:`~Gtk.Window` instance.
p_win = None
#: :class:`~Gtk.Box` for the Presenter window.
p_central = None
#: :class:`~Gtk.AspectFrame` for the current slide in the Presenter window.
p_frame_notes = None
#: :class:`~Gtk.DrawingArea` for the current slide in the Presenter window.
p_da_notes = None
#: :class:`~Gtk.Grid` for the next slide(s) in the Presenter window.
grid_next = None
#: `list` of :class:`~Gtk.AspectFrame` for the next slide in the Presenter window.
p_frames_next = None
#: :class:`~Gtk.DrawingArea` for the next slide in the Presenter window.
p_das_next = None
#: `int` the number of next slides currently on display in the “Next slides” pane, initialized to the maximal number
next_frames_count = 16
#: `list` of :class:`~Gtk.AspectFrame` for the current slide copy in the Presenter window.
p_frame_cur = None
#: :class:`~Gtk.DrawingArea` for the current slide copy in the Presenter window.
p_da_cur = None
#: :class:`~Gtk.Frame` for the annotations in the Presenter window.
p_frame_annot = None
#: Indicates whether we should delay redraws on some drawing areas to fluidify resizing gtk.paned
resize_panes = False
#: Tracks return values of GLib.timeout_add to cancel gtk.paned's redraw callbacks
redraw_timeout = 0
#: Whether to use notes mode or not
notes_mode = document.PdfPage.NONE
#: Current choice of mode to toggle notes
chosen_notes_mode = document.PdfPage.RIGHT
#: Whether to display annotations or not
show_annotations = True
#: Whether to display big buttons or not
show_bigbuttons = True
#: :class:`~Gtk.ToolButton` big button for touch screens, go to previous slide
prev_button = None
#: :class:`~Gtk.ToolButton` big button for touch screens, go to next slide
next_button = None
#: :class:`~Gtk.ToolButton` big button for touch screens, go toggle the pointer
laser_button = None
#: :class:`~Gtk.ToolButton` big button for touch screens, go to scribble on screen
highlight_button = None
#: number of page currently displayed in Content window's miniatures
current_page = -1
#: number of page currently displayed in Presenter window's miniatures
preview_page = -1
#: track whether we blank the screen
blanked = False
#: Dictionary of :class:`~Gtk.Widget` from the presenter window that can be dynamically rearranged
placeable_widgets = {}
#: Map of :class:`~Gtk.Paned` to the relative position (`float` between 0 and 1) of its handle
pane_handle_pos = {}
#: :class:`~pympress.config.Config` to remember preferences
config = None
#: :class:`~pympress.surfacecache.SurfaceCache` instance.
cache = None
#: Current :class:`~pympress.document.Document` instance.
doc = document.EmptyDocument()
#: Class :class:`~pympress.scribble.Scribble` managing drawing by the user on top of the current slide.
scribbler = None
#: Class :class:`~pympress.deck.Overview` displaying a view of all slides
deck = None
#: Class :class:`~pympress.extras.Annotations` managing the display of annotations
annotations = None
#: Class :class:`~pympress.extras.Media` managing keeping track of and callbacks on media overlays
medias = None
#: Class :class:`~pympress.extras.Zoom` managing the zoom level of the current slide.
zoom = None
#: Software-implemented laser pointer, :class:`~pympress.pointer.Pointer`
laser = None
#: :class:`~pympress.editable_label.PageNumber` displaying and setting current page numbers
page_number = None
#: :class:`~pympress.editable_label.EstimatedTalkTime` to set estimated/remaining talk time
est_time = None
#: :class:`~pympress.dialog.TimingReport` popup to show how much time was spent on which part
timing = None
#: :class:`~pympress.talk_time.TimeCounter` clock tracking talk time (elapsed, and remaining)
talk_time = None
#: A :class:`~Gtk.ShortcutsWindow` to show the shortcuts
shortcuts_window = None
#: :class:`~pympress.dialog.LayoutEditor` popup to configure the layouts of the presenter window
layout_editor = None
#: :class:`~pympress.dialog.AutoPlay` popup to configure automatic playing
autoplay = None
#: A :class:`~Gtk.AccelGroup` to store the shortcuts
accel_group = None
#: A :class:`~Gio.Menu` to display the recent files to open
recent_menu = None
#: A :class:`~pympress.extras.FileWatcher` object to reload modified files
file_watcher = None
#: `int` or `None`, may keep track of the Gtk.Application inhibit request
inhibit_cookie = None
##############################################################################
############################# UI setup #############################
##############################################################################
def __init__(self, app, config):
super(UI, self).__init__()
self.app = app
self.config = config
self.blanked = self.config.getboolean('content', 'start_blanked')
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
util.load_style_provider(Gtk.CssProvider()),
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)
# We may want some additional CSS changes
self.css_provider = Gtk.CssProvider()
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
self.css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)
self.show_annotations = self.config.getboolean('presenter', 'show_annotations')
self.chosen_notes_mode = document.PdfPage[self.config.get('notes position', 'horizontal').upper()]
self.show_bigbuttons = self.config.getboolean('presenter', 'show_bigbuttons')
# Surface cache
self.cache = surfacecache.SurfaceCache(self.doc, self.config.getint('cache', 'maxpages'))
# Make and populate windows
self.load_ui('presenter')
self.load_ui('content')
self.app.add_window(self.p_win)
self.app.add_window(self.c_win)
self.load_ui('menu_bar', ext='.xml')
self.app.set_menubar(self.get_object('menu_bar'))
self.recent_menu = self.get_object('recent_menu')
c_full = self.config.getboolean('content', 'start_fullscreen')
p_full = self.config.getboolean('presenter', 'start_fullscreen')
self.setup_actions({
'quit': dict(activate=self.app.quit),
'about': dict(activate=self.menu_about),
'big-buttons': dict(activate=self.switch_bigbuttons, state=self.show_bigbuttons),
'show-shortcuts': dict(activate=self.show_shortcuts),
'content-fullscreen': dict(activate=self.switch_fullscreen, state=c_full),
'presenter-fullscreen': dict(activate=self.switch_fullscreen, state=p_full),
'swap-screens': dict(activate=self.swap_screens),
'blank-screen': dict(activate=self.switch_blanked, state=self.blanked),
'notes-mode': dict(activate=self.switch_mode, state=False),
'notes-pos': dict(activate=self.change_notes_pos, parameter_type=str,
state=self.chosen_notes_mode.name.lower()),
'annotations': dict(activate=self.switch_annotations, state=self.show_annotations),
'validate-input': dict(activate=self.validate_current_input),
'cancel-input': dict(activate=self.cancel_current_input),
'align-content': dict(activate=self.adjust_frame_position),
'next-frames': dict(activate=self.reconfigure_next_frames, parameter_type=int,
state=self.next_frames_count),
})
self.setup_actions({
'open-file': dict(activate=self.open_file, parameter_type=str),
'close-file': dict(activate=self.close_file),
'save-file': dict(activate=self.save_file),
'save-file-as': dict(activate=self.save_file_as),
'pick-file': dict(activate=self.pick_file),
'list-recent-files': dict(change_state=self.populate_recent_menu, state=False),
'page': dict(activate=lambda gaction, param: self.goto_page(param.get_int64()),
parameter_type=int, state=self.current_page),
'next-page': dict(activate=self.doc_goto_next),
'next-label': dict(activate=self.doc_label_next),
'prev-page': dict(activate=self.doc_goto_prev),
'prev-label': dict(activate=self.doc_label_prev),
'hist-back': dict(activate=self.doc_hist_prev),
'hist-forward': dict(activate=self.doc_hist_next),
'first-page': dict(activate=self.doc_goto_home),
'last-page': dict(activate=self.doc_goto_end),
})
self.zoom = extras.Zoom(self)
self.scribbler = scribble.Scribbler(self.config, self, self.notes_mode)
self.deck = deck.Overview(self.config, self, self.notes_mode)
self.annotations = extras.Annotations(self)
self.medias = extras.Media(self, self.config)
self.laser = pointer.Pointer(self.config, self)
self.est_time = editable_label.EstimatedTalkTime(self)
self.page_number = editable_label.PageNumber(self, self.config.getboolean('presenter', 'scroll_number'))
self.timing = dialog.TimingReport(self)
self.autoplay = dialog.AutoPlay(self)
self.talk_time = talk_time.TimeCounter(self, self.est_time, self.timing, self.autoplay)
self.layout_editor = dialog.LayoutEditor(self, self.config)
self.file_watcher = extras.FileWatcher()
self.config.register_actions(self)
# Get placeable widgets. NB, get the highlight one manually from the scribbler class
self.placeable_widgets = {
name: self.get_object(widget_name) for name, widget_name in self.config.placeable_widgets.items()
}
self.placeable_widgets['highlight'] = self.scribbler.scribble_overlay
self.placeable_widgets['deck'] = self.deck.deck_viewport
# Initialize windows
self.make_cwin()
self.make_pwin()
self.connect_signals(self)
for action, shortcut_list in self.config.shortcuts.items():
if action == 'highlight-hold-to-erase':
continue # Not really an action but we define a shortcut for it
self.app.set_accels_for_action('app.' + action, shortcut_list)
# Common to both windows
self.load_icons()
# Adjust default visibility of items
self.prev_button.set_no_show_all(True)
self.next_button.set_no_show_all(True)
self.laser_button.set_no_show_all(True)
self.highlight_button.set_no_show_all(True)
self.p_frame_annot.set_no_show_all(True)
self.prev_button.set_visible(self.show_bigbuttons)
self.next_button.set_visible(self.show_bigbuttons)
self.laser_button.set_visible(self.show_bigbuttons)
self.highlight_button.set_visible(self.show_bigbuttons)
self.p_frame_annot.set_visible(self.show_annotations)
self.laser.activate_pointermode()
# Setup screens and show all windows
self.p_win.parse_geometry(self.config.get('presenter', 'geometry'))
self.c_win.parse_geometry(self.config.get('content', 'geometry'))
screen = self.p_win.get_screen()
self.setup_screens(screen, 'at startup')
screen.connect('monitors-changed', self.screens_changed)
self.c_win.show_all()
self.p_win.show_all()
# Queue some redraws
self.c_da.queue_draw()
self.redraw_panes()
self.do_page_change(unpause=False)
def load_icons(self):
""" Set the icon list for both windows.
"""
try:
icon_list = [GdkPixbuf.Pixbuf.new_from_file(i) for i in util.list_icons()]
except Exception:
logger.exception('Error loading icons')
return
self.c_win.set_icon_list(icon_list)
self.p_win.set_icon_list(icon_list)
def make_cwin(self):
""" Initializes the content window.
"""
self.c_frame.set_property('yalign', self.config.getfloat('content', 'yalign'))
self.c_frame.set_property('xalign', self.config.getfloat('content', 'xalign'))
page_type = self.notes_mode.complement()
self.cache.add_widget(self.c_da, page_type)
self.cache.add_widget(self.c_da, page_type, zoomed = True)
self.c_frame.set_property("ratio", self.doc.page(self.current_page).get_aspect_ratio(page_type))
colourclass = 'white' if self.config.getboolean('content', 'white_blanking') else 'black'
self.c_da.get_style_context().add_class(colourclass)
self.c_win.get_style_context().add_class(colourclass)
self.c_win.insert_action_group('content', self.c_win.get_action_group('win'))
self.c_win.insert_action_group('win', None)
def make_pwin(self):
""" Initializes the presenter window.
"""
layout = self.config.get_layout('notes' if self.notes_mode else 'plain')
pane_handles = self.replace_layout(layout, self.p_central, self.placeable_widgets, self.on_pane_event)
self.pane_handle_pos.update(pane_handles)
self.p_frames_next = [self.get_object('p_frame_next{}'.format(n)) for n in range(16)]
self.p_das_next = [self.get_object('p_da_next{}'.format(n)) for n in range(16)]
self.reconfigure_next_frames(None, GLib.Variant.new_int64(self.config.getint('presenter', 'next_slide_count')))
slide_type = self.notes_mode.complement()
self.cache.add_widget(self.p_da_cur, slide_type)
self.cache.add_widget(self.p_da_cur, slide_type, zoomed = True)
# A single cache for all next slides
self.cache.add_widget(self.p_das_next[0], slide_type)
self.cache.add_widget(self.p_da_notes, self.notes_mode, prerender_enabled = bool(self.notes_mode))
self.cache.add_widget(self.scribbler.scribble_p_da, slide_type, prerender_enabled = False)
self.cache.add_widget(self.scribbler.scribble_p_da, slide_type, zoomed = True)
self.cache.add_widget(self.deck.deck0, slide_type, prerender_enabled = False, ignore_max = True)
# set default value
self.page_number.set_last(self.doc.pages_number())
# Enable dropping files onto the window
self.p_win.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.COPY)
self.p_win.drag_dest_add_text_targets()
self.p_win.insert_action_group('presenter', self.c_win.get_action_group('win'))
self.p_win.insert_action_group('win', None)
def reconfigure_next_frames(self, gaction, param):
""" Callback to set the number of next frames to preview the the “next slides” panel
Args:
gaction (:class:`~Gio.Action`): the action triggering the call
param (:class:`~GLib.Variant`): the number of slides as a GVariant
"""
n_frames = param.get_int64()
if n_frames < 1:
n_frames = 1
if n_frames > 16:
n_frames = 16
self.reflow_next_frames(n_frames)
self.next_frames_count = n_frames
self.app.set_action_state('next-frames', n_frames)
self.config.set('presenter', 'next_slide_count', str(n_frames))
def reflow_next_frames(self, n_frames=None):
""" Set the number of next frames to preview the the “next slides” panel
Args:
n_frames (`int`): the number of frames
"""
for n in range(self.next_frames_count):
self.grid_next.remove(self.p_frames_next[n])
for n in range(4):
self.grid_next.remove_row(n)
self.grid_next.remove_column(n)
if n_frames is None:
n_frames = self.next_frames_count
ww, wh = self.grid_next.get_allocated_width(), self.grid_next.get_allocated_height()
rows, cols = self.compute_frame_grid(ww / wh, n_frames)
for n in range(n_frames):
self.grid_next.attach(self.p_frames_next[n], n % cols, n // cols, 1, 1)
def compute_frame_grid(self, grid_ar, n_frames):
""" Determine the arragement of frames in a grid to maximise their size given respective aspect ratios
Args:
grid_ar (`float`): aspect ratio of grid containing the slides
n_frames (`int`): the number of frames
"""
if not n_frames:
return 0, 0
page_ratio = self.doc.page(self.preview_page).get_aspect_ratio(self.notes_mode.complement())
grid_ar /= page_ratio
# works best when n_frames = rows * cols * grid_ar
rows = math.sqrt(n_frames / grid_ar)
# If rows < 1 always ceil
if rows < 1:
return 1, n_frames
# Check which of ceiling or flooring rows is better
rows = math.floor(rows)
f_cols, c_cols = (n_frames + rows - 1) // rows, (n_frames + rows) // (rows + 1)
if min(f_cols, grid_ar * rows) > min(c_cols, grid_ar * (rows + 1)):
return rows, f_cols
else:
return rows + 1, c_cols
def screens_changed(self, screen):
""" Handle ::monitors-changed events
Args:
screen (:class:`~Gdk.Screen`): the screen
"""
self.setup_screens(screen, 'at monitors-changed event')
GLib.timeout_add(1000, self.setup_screens, screen, 'delayed after monitors-changed event')
def setup_screens(self, screen, event_name=''):
""" If multiple monitors, fullscreen windows on monitors according to config.
Args:
screen (:class:`~Gdk.Screen`): the screen
event_name (`str`): a description of what caused the screen setup event, for debugging
"""
display = Gdk.Display.get_default()
c_monitor, p_monitor, primary, non_primary = ScreenArea.lookup_monitors(display, self.c_win, self.p_win)
# Noisy, but just for debug level
logger.debug('Detecting monitor layout ' + event_name + ': ' + ', '.join([
'Content window is at monitor ' + c_monitor.id,
'Presenter window is at monitor ' + p_monitor.id,
'Primary monitor is (or overlapped with) ' + primary.id,
'No non-primary monitor available' if primary.equal(non_primary)
else 'A non-primary monitor is (or overlapped with) ' + non_primary.id
]))
c_full = self.config.getboolean('content', 'start_fullscreen')
p_full = self.config.getboolean('presenter', 'start_fullscreen')
if not c_full and not p_full:
return
if primary.equal(non_primary):
logger.warning(_('Not starting content or presenter window full screen ' +
'because there is only one monitor'))
c_full, p_full = False, False
else:
# To start fullscreen, we need to ensure windows are on individual monitors
if not c_monitor.equal(p_monitor):
pass
elif c_monitor.equal(primary):
self.move_window(self.c_win, c_monitor, non_primary)
else: # not p_monitor.equal(primary)
self.move_window(self.p_win, p_monitor, primary)
if p_full:
self.p_win.fullscreen()
else:
self.p_win.unfullscreen()
if c_full:
self.c_win.fullscreen()
self.set_screensaver(True)
else:
self.c_win.unfullscreen()
self.set_screensaver(False)
self.app.set_action_state('content-fullscreen', c_full)
self.app.set_action_state('presenter-fullscreen', p_full)
def move_window(self, win, from_bounds, to_bounds):
""" Move window from monitor number from_monitor to monitor to_monitor.
"""
x, y, w, h = win.get_position() + win.get_size()
win_state = win.get_window().get_state() if win.get_window() is not None else 0
logger.debug('Moving {} window from screen {} to screen {}'.format(
'Content' if win is self.c_win else 'Presenter', from_bounds.id, to_bounds.id
))
if (win_state & Gdk.WindowState.FULLSCREEN) != 0:
win.unfullscreen()
if (win_state & Gdk.WindowState.MAXIMIZED) != 0:
win.unmaximize()
to_w = min(w, to_bounds.width)
to_h = min(h, to_bounds.height)
# Get fraction of free space that is left or top of window
x = (max(0, x - from_bounds.x) / (from_bounds.width - w)) if w < from_bounds.width else 0
y = (max(0, y - from_bounds.y) / (from_bounds.height - h)) if h < from_bounds.height else 0
win.resize(to_w, to_h)
win.move(to_bounds.x + x * (to_bounds.width - to_w), to_bounds.y + y * (to_bounds.height - to_h))
if (win_state & Gdk.WindowState.MAXIMIZED) != 0:
win.maximize()
if (win_state & Gdk.WindowState.FULLSCREEN) != 0:
win.fullscreen()
def show_shortcuts(self, *args):
""" Display the shortcuts window.
"""
# Use a different builder to load and be able to release the shortcuts window
shortcuts_builder = builder.Builder()
shortcuts_builder.load_ui('shortcuts')
self.shortcuts_window = shortcuts_builder.get_object('shortcuts_window')
for command, shortcut_list in self.config.items('shortcuts'):
display_shortcut = shortcuts_builder.get_object('shortcut_' + command.replace('-', '_').replace('::', '_'))
if display_shortcut is not None:
display_shortcut.props.accelerator = shortcut_list
self.shortcuts_window.set_transient_for(self.p_win)
self.shortcuts_window.show_all()
self.shortcuts_window.present()
def close_shortcuts(self, *args):
""" Destroy the shortcuts window once it is hidden.
"""
self.shortcuts_window.destroy()
self.shortcuts_window = None
##############################################################################
############################ Dynamic resize ##############################
##############################################################################
def on_configure_da(self, widget, event):
""" Manage "configure" events for all drawing areas, e.g. resizes.
We tell the local :class:`~pympress.surfacecache.SurfaceCache` cache about it, so that it can
invalidate its internal cache for the specified widget and pre-render next pages at a correct size.
Warning: Some not-explicitly sent signals contain wrong values! Just don't resize in that case,
since these always seem to happen after a correct signal that was sent explicitly.
Args:
widget (:class:`~Gtk.Widget`): the widget which has been resized
event (:class:`~Gdk.Event`): the GTK event, which contains the new dimensions of the widget
"""
# Don't trust those
if not event.send_event:
return
self.cache.resize_widget(widget.get_name().rstrip('0123456789'), event.width, event.height)
if widget is self.c_da:
self.medias.resize('content')
self.scribbler.reset_scribble_cache()
self.scribbler.prerender()
elif widget is self.p_da_cur:
self.medias.resize('presenter')
def on_configure_win(self, widget, event):
""" Manage "configure" events for both window widgets.
Args:
widget (:class:`~Gtk.Widget`): the window which has been moved or resized
event (:class:`~Gdk.Event`): the GTK event, which contains the new dimensions of the widget
"""
geom = '{}x{}{:+}{:+}'.format(*widget.get_size(), *widget.get_position())
if widget is self.p_win:
self.config.set('presenter', 'geometry', geom)
cw = self.p_central.get_allocated_width()
ch = self.p_central.get_allocated_height()
self.scribbler.scribble_off_render.set_size_request(cw, ch)
self.deck.deck_off_render.set_size_request(cw, ch)
if self.deck.deck_mode:
self.deck.reset_grid()
self.adjust_bottom_bar_font()
elif widget is self.c_win:
self.config.set('content', 'geometry', geom)
def adjust_bottom_bar_font(self):
""" Scale baseline font size of bottom bar, clipped to 6px..13px. Fonts are then scaled by CSS em indications.
"""
ww, wh = self.p_win.get_size()
font_size = max(6, min(13, ww / 120 if self.show_bigbuttons else ww / 75))
self.css_provider.load_from_data('#bottom {{ font-size: {:.1f}px; }}'.format(font_size).encode())
def redraw_panes(self):
""" Handler for :class:`~Gtk.Paned`'s resizing signal.
Used for delayed drawing events of drawing areas inside the panes.
This is very useful on windows where resizing gets sluggish if we try to redraw while resizing.
"""
self.resize_panes = False
self.reflow_next_frames()
self.p_da_cur.queue_draw()
for da in self.p_das_next:
da.queue_draw()
if self.notes_mode:
self.p_da_notes.queue_draw()
if self.redraw_timeout:
self.redraw_timeout = 0
self.config.update_layout_from_widgets(self.layout_name(self.notes_mode), self.p_central.get_children()[0],
self.pane_handle_pos)
def on_pane_event(self, widget, evt):
""" Signal handler for gtk.paned events.
This function allows one to delay drawing events when resizing, and to speed up redrawing when
moving the middle pane is done (which happens at the end of a mouse resize)
Args:
widget (:class:`~Gtk.Widget`): the widget in which the event occurred (ignored)
evt (:class:`~Gdk.Event`): the event that occurred
"""
if type(evt) == Gdk.EventButton and evt.type == Gdk.EventType.BUTTON_RELEASE:
self.redraw_panes()
elif type(evt) == GObject.GParamSpec and evt.name == "position":
self.resize_panes = True
if self.redraw_timeout:
GLib.Source.remove(self.redraw_timeout)
self.redraw_timeout = GLib.timeout_add(200, self.redraw_panes)
############################################################################
############################ Program lifetime ############################
############################################################################
def cleanup(self, *args):
""" Save configuration and exit the main loop.
"""
self.scribbler.disable_scribbling()
self.medias.hide_all()
self.doc.cleanup_media_files()
if self.app.get_action_state('content-fullscreen'):
# In case we used hard-disabling
self.set_screensaver(disabled=False)
def menu_about(self, *args):
""" Display the "About pympress" dialog.
Handles clicks on the "about" menu.
"""
about = Gtk.AboutDialog(transient_for = self.p_win)
pympress = util.get_pympress_meta()
about.set_program_name('pympress')
about.set_version(pympress['version'])
about.set_copyright(_('Contributors:') + '\n' + pympress['contributors'])
about.set_comments(_('pympress is a little PDF reader written in Python ' +
'using Poppler for PDF rendering and GTK for the GUI.\n') +
_('Some preferences are saved in ') + str(self.config.path_to_config()) + '\n' +
_('Resources are loaded from ') + str(util.get_locale_dir().parent) + '\n' +
_('The log is written to ') + str(util.get_log_path()) + '\n\n' +
_('Media support uses {}.').format(self.medias.backend_version) + '\n' +
_('Python version {}').format(sys.version))
about.set_website('https://github.com/Cimbali/pympress')
try:
about.set_logo(GdkPixbuf.Pixbuf.new_from_file(util.get_icon_path('pympress.png')))
except Exception:
logger.exception(_('Error loading icon for about window'))
about.run()
about.destroy()
##############################################################################
############################ Document manangement ############################
##############################################################################
def swap_document(self, doc_uri, page=0, reloading=False):
""" Replace the currently open document with a new one.
The new document is possibly and EmptyDocument if doc_uri is None.
The state of the ui and cache are updated accordingly.
Args:
doc_uri (`str`): the URI to the new document
page (`int`): the page at which to start the presentation
reloading (`bool`): whether we are reloading or detecting stuff from the document
"""
if self.unsaved_changes(reloading):
# If we keep the unsaved changes and were prompted by automatic file change,
# stop watching for file changes in the future.
if reloading:
self.file_watcher.stop_watching()
return
run_gc = self.doc.doc is not None
try:
self.doc = document.Document.create(self, doc_uri)
if not reloading and doc_uri:
Gtk.RecentManager.get_default().add_item(doc_uri)
self.file_watcher.watch_file(doc_uri, self.reload_document)
elif not reloading:
self.file_watcher.stop_watching()
except GLib.Error:
if reloading:
return
self.doc = document.Document.create(self, None)
self.error_opening_file(doc_uri)
self.file_watcher.stop_watching()
self.current_page = self.preview_page = self.doc.goto(page)
# Guess notes mode by default if the document has notes
if not reloading:
hpref = self.config.get('notes position', 'horizontal')
vpref = self.config.get('notes position', 'vertical')
target_mode = self.doc.guess_notes(hpref, vpref, self.current_page)
if self.notes_mode != target_mode:
self.switch_mode('notes-mode', target_mode=target_mode)
# don't toggle from NONE to NONE
if target_mode:
self.app.activate_action('notes-pos', target_mode.name.lower())
else:
self.doc.set_notes_pos(self.notes_mode.direction())
# Some things that need updating
self.cache.swap_document(self.doc)
self.page_number.set_last(self.doc.pages_number())
self.page_number.enable_labels(self.doc.has_labels())
self.autoplay.set_doc_pages(self.doc.pages_number())
self.medias.purge_media_overlays()
self.timing.set_document_metadata(self.doc.get_structure().copy(), self.doc.page_labels[:])
# A new document, restart at time 0, paused
if not reloading:
self.talk_time.pause()
self.talk_time.reset_timer()
self.page_number.setup_doc_callbacks(self.doc)
self.deck.setup_doc_callbacks(self.doc)
self.do_page_change(unpause=False)
# Now that all references to the old document have been replaced or removed, manually
# collect garbage to delete objects and release file handles / close file descriptors
if run_gc:
gc.collect(1)
def reload_document(self):
""" Reload the current document.
"""
self.swap_document(self.doc.get_uri(), page=self.current_page, reloading=True)
def populate_recent_menu(self, gaction, is_opening=None):
""" Callback for the recent document menu.
Gets the URI and requests the document swap.
Args:
gaction (:class:`~Gio.Action`): the action triggering the call
is_opening (:class:`~GLib.Variant`): a wrapped boolean indicating whether the menu is opening or closing.
"""
if not is_opening.get_boolean():
self.recent_menu.remove_all()
return
for file in Gtk.RecentManager.get_default().get_items():
if not file.exists() or not file.get_mime_type() == 'application/pdf':
continue
item = Gio.MenuItem.new(file.get_display_name(), 'app.open-file')
item.set_action_and_target_value('app.open-file', GLib.Variant.new_string(file.get_uri()))
item.set_icon(file.get_gicon())
self.recent_menu.append_item(item)
if self.recent_menu.get_n_items() >= 10:
break
def on_drag_drop(self, widget, drag_context, x, y, data, info, time):
""" Receive the drag-drops (as text only). If a file is dropped, open it.
Args:
widget (:class:`~Gtk.Widget`): The widget on which the dragged item was dropped
drag_context (:class:`~Gdk.DragContext`): Context object of the dragging
x (`float`): position of the drop
y (`float`): position of the drop
data (:class:`~Gtk.SelectionData`): container for the dropped data
info (`int`): info on the target
time (`int`): time of the drop
"""
uri_parts = urlsplit(data.get_text())
path = pathlib.Path(url2pathname(uri_parts.path) if uri_parts.scheme else uri_parts.path)
if path.is_file() and path.suffix.lower() == '.pdf':
self.swap_document(path.as_uri())
def unsaved_changes(self, reload=False):
""" Prompt the user about what to do with changes in the document: save, discard, or cancel action
Args:
reload (`bool`): The unsaved changes is prompted by reloading the file
Returns:
`bool`: `True` iff we need to cancel the current action
"""
if not self.doc.has_changes():
return False
dialog = Gtk.MessageDialog(title=_('Unsaved changes'), transient_for=self.p_win, type=Gtk.MessageType.WARNING)
dialog.set_position(Gtk.WindowPosition.CENTER)
if not reload:
dialog.set_markup(_('Save changes before closing?'))
dialog.format_secondary_markup(_('Unsaved changes will be lost'))
dialog.add_button(Gtk.STOCK_SAVE, Gtk.ResponseType.YES)
dialog.add_button(_('_Discard'), Gtk.ResponseType.NO).set_image(
Gtk.Button.new_from_icon_name('edit-delete', Gtk.IconSize.BUTTON).get_image()
)
dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
dialog.set_default_response(Gtk.ResponseType.YES)
else:
dialog.set_markup(_('The open file was modified outside of pympress but you have made unsaved changes.') +
'\n<b>' + _('Overwrite changes instead of reloading?') + '</b>')
dialog.format_secondary_markup(_('Saving changes will overwrite the changed file!') + '\n' +
_('Unsaved changes will be lost.'))
dialog.add_button(_('Overwrite'), Gtk.ResponseType.YES).set_image(
Gtk.Button.new_from_icon_name('document-save', Gtk.IconSize.BUTTON).get_image()
)
dialog.add_button(_('Reload'), Gtk.ResponseType.NO).set_image(
Gtk.Button.new_from_icon_name('view-refresh', Gtk.IconSize.BUTTON).get_image()
)
dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
dialog.set_default_response(Gtk.ResponseType.YES)
response = dialog.run()
dialog.destroy()
if response == Gtk.ResponseType.YES:
self.doc.save_changes()
return response == Gtk.ResponseType.CANCEL or (reload and Gtk.ResponseType == Gtk.ResponseType.YES)
def save_file_as(self, *args):
""" Remove the current document.
"""
# Use a GTK file dialog to choose file
dialog = Gtk.FileChooserDialog(title = _('Save as...'), transient_for = self.p_win,
action = Gtk.FileChooserAction.SAVE)
dialog.add_buttons(Gtk.STOCK_SAVE_AS, Gtk.ResponseType.OK)
dialog.set_default_response(Gtk.ResponseType.OK)
dialog.set_position(Gtk.WindowPosition.CENTER)
file_filter = Gtk.FileFilter()
file_filter.set_name(_('PDF files'))
file_filter.add_mime_type('application/pdf')
file_filter.add_pattern('*.pdf')
dialog.add_filter(file_filter)
file_filter = Gtk.FileFilter()
file_filter.set_name(_('All files'))
file_filter.add_pattern('*')
dialog.add_filter(file_filter)
response = dialog.run()
if response == Gtk.ResponseType.OK:
self.doc.save_changes(dialog.get_uri())
dialog.destroy()
def pick_file(self, *args):
""" Ask the user which file he means to open.
"""
# Use a GTK file dialog to choose file
dialog = Gtk.FileChooserDialog(title = _('Open...'), transient_for = self.p_win,
action = Gtk.FileChooserAction.OPEN)
dialog.add_buttons(Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
dialog.set_default_response(Gtk.ResponseType.OK)
dialog.set_position(Gtk.WindowPosition.CENTER)
file_filter = Gtk.FileFilter()
file_filter.set_name(_('PDF files'))
file_filter.add_mime_type('application/pdf')
file_filter.add_pattern('*.pdf')
dialog.add_filter(file_filter)
file_filter = Gtk.FileFilter()
file_filter.set_name(_('All files'))
file_filter.add_pattern('*')
dialog.add_filter(file_filter)
response = dialog.run()
if response == Gtk.ResponseType.OK:
self.swap_document(dialog.get_uri())
dialog.destroy()
def error_opening_file(self, uri):
""" Remove the current document.
Args:
uri (`str`): the URI of the document
"""
# Check if the path is valid
uri_parts = urlsplit(uri)
filename = pathlib.Path(url2pathname(uri_parts.path))
if uri_parts.scheme == 'file' and not filename.exists():
msg = _('Could not find the file "{}"').format(filename)
else:
msg = _('Error opening the file "{}"').format(uri)
dialog = Gtk.MessageDialog(transient_for=self.p_win, flags=Gtk.DialogFlags.MODAL,
message_type=Gtk.MessageType.ERROR, message_format=msg)
dialog.add_button(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
dialog.set_position(Gtk.WindowPosition.CENTER)
dialog.run()
dialog.destroy()
def close_file(self, *args):
""" Remove the current document.
"""
self.swap_document(None)