-
Notifications
You must be signed in to change notification settings - Fork 44
/
pdfviewer.py
646 lines (507 loc) · 22.3 KB
/
pdfviewer.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
# Copyright (C) 2012, One Laptop Per Child
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
import os
import logging
from gettext import gettext as _
import gi
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import WebKit2
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.graphics.toolbutton import ToolButton
from sugar3.graphics.toggletoolbutton import ToggleToolButton
from sugar3.graphics.icon import Icon
from sugar3.graphics.progressicon import ProgressIcon
from sugar3.graphics import style
from sugar3.datastore import datastore
from sugar3.activity import activity
from sugar3.bundle.activitybundle import ActivityBundle
import downloadmanager
class EvinceViewer(Gtk.VBox):
"""PDF viewer with a toolbar overlay for basic navigation and an
option to save to Journal.
"""
__gsignals__ = {
'save-to-journal': (GObject.SignalFlags.RUN_FIRST,
None,
([])),
'open-link': (GObject.SignalFlags.RUN_FIRST,
None,
([str])), }
def __init__(self, uri):
GObject.GObject.__init__(self)
self._uri = uri
# delay Evince import until is needed to improve activity startup time
gi.require_version('EvinceDocument', '3.0')
gi.require_version('EvinceView', '3.0')
from gi.repository import EvinceDocument
from gi.repository import EvinceView
# Create Evince objects to handle the PDF in the URI:
EvinceDocument.init()
self._doc = EvinceDocument.Document.factory_get_document(uri)
self._view = EvinceView.View()
self._model = EvinceView.DocumentModel()
self._model.set_document(self._doc)
self._view.set_model(self._model)
self._EVINCE_MODE_FREE = EvinceView.SizingMode.FREE
self._view.connect('external-link', self.__handle_link_cb)
self._model.connect('page-changed', self.__page_changed_cb)
self._back_page_button = None
self._forward_page_button = None
self._toolbar_box = self._create_toolbar()
self._update_nav_buttons()
self._toolbar_box.set_halign(Gtk.Align.FILL)
self._toolbar_box.set_valign(Gtk.Align.END)
self.pack_end(self._toolbar_box, False, True, 0)
self._toolbar_box.show()
scrolled_window = Gtk.ScrolledWindow()
self.pack_start(scrolled_window, True, True, 0)
scrolled_window.show()
scrolled_window.add(self._view)
self._view.show()
def _create_toolbar(self):
toolbar_box = ToolbarBox()
zoom_out_button = ToolButton('zoom-out')
zoom_out_button.set_tooltip(_('Zoom out'))
zoom_out_button.connect('clicked', self.__zoom_out_cb)
toolbar_box.toolbar.insert(zoom_out_button, -1)
zoom_out_button.show()
zoom_in_button = ToolButton('zoom-in')
zoom_in_button.set_tooltip(_('Zoom in'))
zoom_in_button.connect('clicked', self.__zoom_in_cb)
toolbar_box.toolbar.insert(zoom_in_button, -1)
zoom_in_button.show()
zoom_original_button = ToolButton('zoom-original')
zoom_original_button.set_tooltip(_('Actual size'))
zoom_original_button.connect('clicked', self.__zoom_original_cb)
toolbar_box.toolbar.insert(zoom_original_button, -1)
zoom_original_button.show()
separator = Gtk.SeparatorToolItem()
separator.props.draw = True
toolbar_box.toolbar.insert(separator, -1)
separator.show()
self._back_page_button = ToolButton('go-previous-paired')
self._back_page_button.set_tooltip(_('Previous page'))
self._back_page_button.props.sensitive = False
self._back_page_button.connect('clicked', self.__go_back_page_cb)
toolbar_box.toolbar.insert(self._back_page_button, -1)
self._back_page_button.show()
self._forward_page_button = ToolButton('go-next-paired')
self._forward_page_button.set_tooltip(_('Next page'))
self._forward_page_button.props.sensitive = False
self._forward_page_button.connect('clicked', self.__go_forward_page_cb)
toolbar_box.toolbar.insert(self._forward_page_button, -1)
self._forward_page_button.show()
separator = Gtk.SeparatorToolItem()
separator.props.draw = True
toolbar_box.toolbar.insert(separator, -1)
separator.show()
self._save_to_journal_button = ToolButton('save-to-journal')
self._save_to_journal_button.set_tooltip(_('Save PDF to Journal'))
self._save_to_journal_button.connect('clicked',
self.__save_to_journal_button_cb)
toolbar_box.toolbar.insert(self._save_to_journal_button, -1)
self._save_to_journal_button.show()
separator = Gtk.SeparatorToolItem()
toolbar_box.toolbar.insert(separator, -1)
separator.show()
self._inverted_colors = ToggleToolButton(icon_name='dark-theme')
self._inverted_colors.set_tooltip(_('Inverted Colors'))
self._inverted_colors.set_accelerator('<Ctrl>i')
self._inverted_colors.connect(
'toggled', self.__inverted_colors_toggled_cb)
toolbar_box.toolbar.insert(self._inverted_colors, -1)
self._inverted_colors.show()
return toolbar_box
def disable_journal_button(self):
self._save_to_journal_button.props.sensitive = False
def __handle_link_cb(self, widget, url):
self.emit('open-link', url.get_uri())
def __page_changed_cb(self, model, page_from, page_to):
self._update_nav_buttons()
def __zoom_out_cb(self, widget):
self.zoom_out()
def __zoom_in_cb(self, widget):
self.zoom_in()
def __zoom_original_cb(self, widget):
self.zoom_original()
def __go_back_page_cb(self, widget):
self._view.previous_page()
def __go_forward_page_cb(self, widget):
self._view.next_page()
def __save_to_journal_button_cb(self, widget):
self.emit('save-to-journal')
self._save_to_journal_button.props.sensitive = False
def __inverted_colors_toggled_cb(self, button):
if hasattr(self._model, 'set_inverted_colors'):
self._model.set_inverted_colors(button.props.active)
if button.props.active:
button.set_icon_name('light-theme')
button.set_tooltip(_('Normal Colors'))
else:
button.set_icon_name('dark-theme')
button.set_tooltip(_('Inverted Colors'))
def show_inverted_colors_button(self):
self._inverted_colors.show()
def toggle_inverted_colors(self):
self._inverted_colors.set_active(
not self._inverted_colors.get_active())
def _update_nav_buttons(self):
current_page = self._model.props.page
self._back_page_button.props.sensitive = current_page > 0
self._forward_page_button.props.sensitive = \
current_page < self._doc.get_n_pages() - 1
def zoom_original(self):
self._model.props.sizing_mode = self._EVINCE_MODE_FREE
self._model.props.scale = 1.0
def zoom_in(self):
self._model.props.sizing_mode = self._EVINCE_MODE_FREE
self._view.zoom_in()
def zoom_out(self):
self._model.props.sizing_mode = self._EVINCE_MODE_FREE
self._view.zoom_out()
def get_pdf_title(self):
return self._doc.get_title()
class DummyBrowser(GObject.GObject):
"""Has the same interface as browser.Browser ."""
__gsignals__ = {
'new-tab': (GObject.SignalFlags.RUN_FIRST, None, ([str])),
'tab-close': (GObject.SignalFlags.RUN_FIRST, None, ([object])),
'load-changed': (GObject.SignalFlags.RUN_FIRST, None, ([int])),
'selection-changed': (GObject.SignalFlags.RUN_FIRST, None, ([])),
'security-status-changed': (GObject.SignalFlags.RUN_FIRST, None, ([])),
'enter-fullscreen': (GObject.SignalFlags.RUN_FIRST, None, ([])),
'leave-fullscreen': (GObject.SignalFlags.RUN_FIRST, None, ([])),
}
__gproperties__ = {
'title': (object, 'title', 'Title', GObject.PARAM_READWRITE),
'uri': (object, 'uri', 'URI', GObject.PARAM_READWRITE),
'estimated-load-progress': (object, 'estimated-load-progress',
'Progress', GObject.PARAM_READWRITE),
}
def __init__(self, tab):
GObject.GObject.__init__(self)
self._tab = tab
self._title = ""
self._uri = ""
self._progress = 0.0
self.security_status = None
def get_web_inspector(self):
return None
def do_get_property(self, prop):
if prop.name == 'title':
return self._title
elif prop.name == 'uri':
return self._uri
elif prop.name == 'estimated-load-progress':
return self._progress
else:
raise AttributeError('Unknown property %s' % prop.name)
def do_set_property(self, prop, value):
if prop.name == 'title':
self._title = value
elif prop.name == 'uri':
self._uri = value
elif prop.name == 'estimated-load-progress':
self._progress = value
if self._progress >= 1.0:
# Clear spinning cursor
self.emit('load-changed', WebKit2.LoadEvent.FINISHED)
else:
raise AttributeError('Unknown property %s' % prop.name)
def get_state(self):
return {'uri': self.props.uri, 'title': self.props.title}
def get_title(self):
return self._title
def get_uri(self):
return self._uri
def emit_new_tab(self, uri):
self.emit('new-tab', uri)
def emit_close_tab(self):
self.emit('tab-close', self._tab)
def get_legacy_history(self):
return [{'url': self.props.uri, 'title': self.props.title}]
def can_query_editing_commands(self):
return False
def set_history_index(self, index):
pass
def get_history_index(self):
return 0
def set_zoom_level(self, zoom_level):
pass
def get_zoom_level(self):
return 0
def stop_loading(self):
self._tab.close_tab()
def reload(self):
pass
def load_uri(self, uri):
pass
def grab_focus(self):
pass
def destroy(self):
pass
def get_window(self):
return self._tab.get_window()
def get_allocation(self):
return self._tab.get_allocation()
def translate_coordinates(self, widget, x, y):
return self._tab.translate_coordinates(widget, x, y)
# FIXME provide implementations
def can_execute_editing_command_finish(self):
pass
def get_find_controller(self):
return
class PDFProgressMessageBox(Gtk.EventBox):
def __init__(self, message, button_callback):
Gtk.EventBox.__init__(self)
self.modify_bg(Gtk.StateType.NORMAL,
style.COLOR_WHITE.get_gdk_color())
alignment = Gtk.Alignment.new(0.5, 0.5, 0.1, 0.1)
self.add(alignment)
alignment.show()
box = Gtk.VBox()
alignment.add(box)
box.show()
icon = ProgressIcon(icon_name='book',
pixel_size=style.LARGE_ICON_SIZE,
stroke_color=style.COLOR_BUTTON_GREY.get_svg(),
fill_color=style.COLOR_SELECTION_GREY.get_svg())
self.progress_icon = icon
box.pack_start(icon, expand=True, fill=False, padding=0)
icon.show()
label = Gtk.Label()
color = style.COLOR_BUTTON_GREY.get_html()
label.set_markup('<span weight="bold" color="%s">%s</span>' % (
color, GLib.markup_escape_text(message)))
box.pack_start(label, expand=True, fill=False, padding=0)
label.show()
button_box = Gtk.HButtonBox()
button_box.set_layout(Gtk.ButtonBoxStyle.CENTER)
box.pack_start(button_box, False, True, 0)
button_box.show()
button = Gtk.Button(label=_('Cancel'))
button.connect('clicked', button_callback)
button.props.image = Icon(icon_name='dialog-cancel',
pixel_size=style.SMALL_ICON_SIZE)
button_box.pack_start(button, expand=True, fill=False, padding=0)
button.show()
class PDFErrorMessageBox(Gtk.EventBox):
def __init__(self, title, message, button_callback):
Gtk.EventBox.__init__(self)
self.modify_bg(Gtk.StateType.NORMAL,
style.COLOR_WHITE.get_gdk_color())
alignment = Gtk.Alignment.new(0.5, 0.5, 0.1, 0.1)
self.add(alignment)
alignment.show()
box = Gtk.VBox()
alignment.add(box)
box.show()
# Get the icon of this activity through the bundle path.
bundle_path = activity.get_bundle_path()
activity_bundle = ActivityBundle(bundle_path)
icon = Icon(pixel_size=style.LARGE_ICON_SIZE,
file=activity_bundle.get_icon(),
stroke_color=style.COLOR_BUTTON_GREY.get_svg(),
fill_color=style.COLOR_TRANSPARENT.get_svg())
box.pack_start(icon, expand=True, fill=False, padding=0)
icon.show()
color = style.COLOR_BUTTON_GREY.get_html()
label = Gtk.Label()
label.set_markup('<span weight="bold" color="%s">%s</span>' % (
color, GLib.markup_escape_text(title)))
box.pack_start(label, expand=True, fill=False, padding=0)
label.show()
label = Gtk.Label()
label.set_markup('<span color="%s">%s</span>' % (
color, GLib.markup_escape_text(message)))
box.pack_start(label, expand=True, fill=False, padding=0)
label.show()
button_box = Gtk.HButtonBox()
button_box.set_layout(Gtk.ButtonBoxStyle.CENTER)
box.pack_start(button_box, False, True, 0)
button_box.show()
button = Gtk.Button(label=_('Try again'))
button.connect('clicked', button_callback)
button.props.image = Icon(icon_name='entry-refresh',
pixel_size=style.SMALL_ICON_SIZE,
stroke_color=style.COLOR_WHITE.get_svg(),
fill_color=style.COLOR_TRANSPARENT.get_svg())
button_box.pack_start(button, expand=True, fill=False, padding=0)
button.show()
class PDFTabPage(Gtk.HBox):
"""Shows a basic PDF viewer, download the file first if the PDF is
in a remote location.
When the file is remote, display a message while downloading.
"""
def __init__(self, state=None):
GObject.GObject.__init__(self)
self._browser = DummyBrowser(self)
self._message_box = None
self._evince_viewer = None
self._pdf_uri = None
self._requested_uri = None
self._download = None
self._downloaded_pdf = False
if state is not None:
self.setup(state['uri'], state['title'])
def setup(self, requested_uri, title=None):
self._requested_uri = requested_uri
# The title may be given from the Journal:
if title is not None:
self._browser.props.title = title
self._browser.props.uri = requested_uri
# show PDF directly if the file is local (from the system tree
# or from the journal)
if requested_uri.startswith('file://'):
self._pdf_uri = requested_uri
self._show_pdf()
elif requested_uri.startswith('journal://'):
self._pdf_uri = self._get_path_from_journal(requested_uri)
self._show_pdf(from_journal=True)
# download first if file is remote
elif requested_uri.startswith('http://') or \
requested_uri.startswith('https://'):
downloads_dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOWNLOAD)
if downloads_dir == None:
downloads_dir = os.path.expanduser("~")
local_path = os.path.join(downloads_dir, os.path.basename(requested_uri))
if os.path.isfile(local_path):
# If file already exists locally, no need to download
self._pdf_uri = "file://" + local_path
self._show_pdf()
else:
self._download_from_http(requested_uri)
def _get_browser(self):
return self._browser
browser = GObject.property(type=object, getter=_get_browser)
def _show_pdf(self, from_journal=False):
self._evince_viewer = EvinceViewer(self._pdf_uri)
self._evince_viewer.connect('save-to-journal',
self.__save_to_journal_cb)
self._evince_viewer.connect('open-link',
self.__open_link_cb)
# disable save to journal if the PDF is already loaded from
# the journal:
if from_journal:
self._evince_viewer.disable_journal_button()
self._evince_viewer.show()
self.pack_start(self._evince_viewer, True, True, 0)
# If the PDF has a title, set it as the browse page title,
# otherwise use the last part of the URI. Only when the title
# was not set already from the Journal.
if from_journal:
self._browser.props.title = self._browser.props.title
return
pdf_title = self._evince_viewer.get_pdf_title()
if pdf_title is not None:
self._browser.props.title = pdf_title
else:
self._browser.props.title = os.path.basename(self._requested_uri)
def _get_path_from_journal(self, journal_uri):
"""Get the system tree URI of the file for the Journal object."""
journal_id = self.__journal_id_from_uri(journal_uri)
jobject = datastore.get(journal_id)
return 'file://' + jobject.file_path
def _download_from_http(self, remote_uri):
"""Download the PDF from a remote location to a temporal file."""
# Display a message
self._message_box = PDFProgressMessageBox(
message=_("Downloading document..."),
button_callback=self.close_tab)
self.pack_start(self._message_box, True, True, 0)
self._message_box.show()
"""
# Figure out download URI
temp_path = os.path.join(activity.get_activity_root(), 'instance')
if not os.path.exists(temp_path):
os.makedirs(temp_path)
fd, dest_path = tempfile.mkstemp(dir=temp_path)
"""
context = WebKit2.WebContext.get_default()
context.connect('download-started', self.__download_started_cb)
downloadmanager.ignore_pdf(remote_uri)
def __download_started_cb(self, context, download):
self._download = download
download.connect('failed', self.__download_failed_cb)
download.connect('finished', self.__download_finished_cb)
download.connect('received-data', self.__download_received_data_cb)
context.disconnect_by_func(self.__download_started_cb)
def __download_received_data_cb(self, download, data_size):
self._browser.props.estimated_load_progress = \
self._download.get_estimated_progress()
self._message_box.progress_icon.update(
self._browser.props.estimated_load_progress)
def __download_finished_cb(self, download):
self._pdf_uri = download.get_destination()
logging.debug('FINISHED %s', self._pdf_uri)
self.remove(self._message_box)
self._message_box = None
self._show_pdf()
self._download = None
self._downloaded_pdf = True
def __download_failed_cb(self, download, error):
logging.debug('Download error! code %s, message %s' %
(error.code, error.message))
title = _('This document could not be loaded')
self._browser.props.title = title
if self._message_box is not None:
self.remove(self._message_box)
self._message_box = PDFErrorMessageBox(
title=title,
message=_('Please make sure you are connected to the Internet.'),
button_callback=self.reload)
self.pack_start(self._message_box, True, True, 0)
self._message_box.show()
self._download = None
def reload(self, button=None):
self.remove(self._message_box)
self._message_box = None
self.setup(self._requested_uri)
def close_tab(self, button=None):
self._browser.emit_close_tab()
def cancel_download(self):
if self._download is not None:
self._download.cancel()
try:
if self._downloaded_pdf:
os.remove(self._pdf_uri[len("file://"):])
except BaseException:
pass
def __journal_id_to_uri(self, journal_id):
"""Return an URI for a Journal object ID."""
return "journal://" + journal_id + ".pdf"
def __journal_id_from_uri(self, journal_uri):
"""Return a Journal object ID from an URI."""
return journal_uri[len("journal://"):-len(".pdf")]
def __save_to_journal_cb(self, widget):
"""Save the PDF in the Journal.
Put the PDF title as the title, or if the PDF doesn't have
one, use the filename instead. Put the requested uri as the
description.
"""
jobject = datastore.create()
jobject.metadata['title'] = self._browser.props.title
jobject.metadata['description'] = _('From: %s') % self._requested_uri
jobject.metadata['mime_type'] = "application/pdf"
jobject.file_path = self._pdf_uri[len("file://"):]
datastore.write(jobject)
# display the new URI:
self._browser.props.uri = self.__journal_id_to_uri(jobject.object_id)
def __open_link_cb(self, widget, uri):
"""Open the external link of a PDF in a new tab."""
self._browser.emit_new_tab(uri)