-
Notifications
You must be signed in to change notification settings - Fork 89
/
jobviewer.py
2508 lines (2165 loc) · 96.6 KB
/
jobviewer.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
## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Red Hat, Inc.
## Authors:
## Tim Waugh <[email protected]>
## Jiri Popelka <[email protected]>
## 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.
import asyncconn
import authconn
import cups
import dbus
import dbus.glib
import dbus.service
import threading
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Gtk
from gui import GtkGUI
import monitor
import os, shutil
from gi.repository import Pango
import pwd
import smburi
import subprocess
import sys
import time
import urllib.parse
from xml.sax import saxutils
from debug import *
import config
import statereason
import errordialogs
from functools import reduce
cups.require("1.9.47")
try:
gi.require_version('Secret', '1')
from gi.repository import Secret
USE_SECRET=True
except ValueError:
USE_SECRET=False
import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir)
from statereason import StateReason
pkgdata = config.pkgdatadir
ICON="printer"
ICON_SIZE=22
SEARCHING_ICON="document-print-preview"
# We need to call Notify.init before we can check the server for caps
Notify.init('System Config Printer Notification')
if USE_SECRET:
NETWORK_PASSWORD = Secret.Schema.new("org.system.config.printer.store", Secret.SchemaFlags.NONE,
{
"user": Secret.SchemaAttributeType.STRING,
"domain": Secret.SchemaAttributeType.STRING,
"object": Secret.SchemaAttributeType.STRING,
"protocol": Secret.SchemaAttributeType.STRING,
"port": Secret.SchemaAttributeType.INTEGER,
"server": Secret.SchemaAttributeType.STRING,
"authtype": Secret.SchemaAttributeType.STRING,
"uri": Secret.SchemaAttributeType.STRING,
}
)
class ServiceGet:
service = Secret.Service()
def __init__(self):
self.service = Secret.Service.get_sync(0,
None)
def get_service(self):
return self.service
class ItemSearch:
items = list()
def __init__(self, service, attrs):
self.items = Secret.Service.search_sync(service,
NETWORK_PASSWORD,
attrs,
Secret.SearchFlags.LOAD_SECRETS,
None)
def get_items(self):
return self.items
class PasswordStore:
def __init__(self, attrs, name, secret):
Secret.password_store(NETWORK_PASSWORD,
attrs,
Secret.COLLECTION_DEFAULT,
name,
secret,
None,
self.on_password_stored)
def on_password_stored(self, source, result, unused):
Secret.password_store_finish(result)
class PrinterURIIndex:
def __init__ (self, names=None):
self.printer = {}
if names is None:
names = []
self.names = names
self._collect_names ()
def _collect_names (self, connection=None):
if not self.names:
return
if not connection:
try:
c = cups.Connection ()
except RuntimeError:
return
for name in self.names:
self.add_printer (name, connection=c)
self.names = []
def add_printer (self, printer, connection=None):
try:
self._map_printer (name=printer, connection=connection)
except KeyError:
return
def update_from_attrs (self, printer, attrs):
uris = []
if 'printer-uri-supported' in attrs:
uri_supported = attrs['printer-uri-supported']
if type (uri_supported) != list:
uri_supported = [uri_supported]
uris.extend (uri_supported)
if 'notify-printer-uri' in attrs:
uris.append (attrs['notify-printer-uri'])
if 'printer-more-info' in attrs:
uris.append (attrs['printer-more-info'])
for uri in uris:
self.printer[uri] = printer
def remove_printer (self, printer):
# Remove references to this printer in the URI map.
self._collect_names ()
uris = list(self.printer.keys ())
for uri in uris:
if self.printer[uri] == printer:
del self.printer[uri]
def lookup (self, uri, connection=None):
self._collect_names ()
try:
return self.printer[uri]
except KeyError:
return self._map_printer (uri=uri, connection=connection)
def all_printer_names (self):
self._collect_names ()
return set (self.printer.values ())
def lookup_cached_by_name (self, name):
self._collect_names ()
for uri, printer in self.printer.items ():
if printer == name:
return uri
raise KeyError
def _map_printer (self, uri=None, name=None, connection=None):
try:
if connection is None:
connection = cups.Connection ()
r = ['printer-name', 'printer-uri-supported', 'printer-more-info']
if uri is not None:
attrs = connection.getPrinterAttributes (uri=uri,
requested_attributes=r)
else:
attrs = connection.getPrinterAttributes (name,
requested_attributes=r)
except RuntimeError:
# cups.Connection() failed
raise KeyError
except cups.IPPError:
# URI not known.
raise KeyError
name = attrs['printer-name']
self.update_from_attrs (name, attrs)
if uri is not None:
self.printer[uri] = name
return name
class CancelJobsOperation(GObject.GObject):
__gsignals__ = {
'destroy': (GObject.SignalFlags.RUN_LAST, None, ()),
'job-deleted': (GObject.SignalFlags.RUN_LAST, None, (int,)),
'ipp-error': (GObject.SignalFlags.RUN_LAST, None,
(int, GObject.TYPE_PYOBJECT)),
'finished': (GObject.SignalFlags.RUN_LAST, None, ())
}
def __init__ (self, parent, host, port, encryption, jobids, purge_job):
GObject.GObject.__init__ (self)
self.jobids = list (jobids)
self.purge_job = purge_job
self.host = host
self.port = port
self.encryption = encryption
if purge_job:
if len(self.jobids) > 1:
dialog_title = _("Delete Jobs")
dialog_label = _("Do you really want to delete these jobs?")
else:
dialog_title = _("Delete Job")
dialog_label = _("Do you really want to delete this job?")
else:
if len(self.jobids) > 1:
dialog_title = _("Cancel Jobs")
dialog_label = _("Do you really want to cancel these jobs?")
else:
dialog_title = _("Cancel Job")
dialog_label = _("Do you really want to cancel this job?")
dialog = Gtk.Dialog (title=dialog_title, transient_for=parent,
modal=True, destroy_with_parent=True)
dialog.add_buttons (_("Keep Printing"), Gtk.ResponseType.NO,
dialog_title, Gtk.ResponseType.YES)
dialog.set_default_response (Gtk.ResponseType.NO)
dialog.set_border_width (6)
dialog.set_resizable (False)
hbox = Gtk.HBox.new (False, 12)
image = Gtk.Image ()
image.set_from_stock (Gtk.STOCK_DIALOG_QUESTION, Gtk.IconSize.DIALOG)
image.set_alignment (0.0, 0.0)
hbox.pack_start (image, False, False, 0)
label = Gtk.Label(label=dialog_label)
label.set_line_wrap (True)
label.set_alignment (0.0, 0.0)
hbox.pack_start (label, False, False, 0)
dialog.vbox.pack_start (hbox, False, False, 0)
dialog.connect ("response", self.on_job_cancel_prompt_response)
dialog.connect ("delete-event", self.on_job_cancel_prompt_delete)
dialog.show_all ()
self.dialog = dialog
self.connection = None
debugprint ("+%s" % self)
def __del__ (self):
debugprint ("-%s" % self)
def do_destroy (self):
if self.connection:
self.connection.destroy ()
self.connection = None
if self.dialog:
self.dialog.destroy ()
self.dialog = None
debugprint ("DESTROY: %s" % self)
def destroy (self):
self.emit ('destroy')
def on_job_cancel_prompt_delete (self, dialog, event):
self.on_job_cancel_prompt_response (dialog, Gtk.ResponseType.NO)
def on_job_cancel_prompt_response (self, dialog, response):
dialog.destroy ()
self.dialog = None
if response != Gtk.ResponseType.YES:
self.emit ('finished')
return
if len(self.jobids) == 0:
self.emit ('finished')
return
asyncconn.Connection (host=self.host,
port=self.port,
encryption=self.encryption,
reply_handler=self._connected,
error_handler=self._connect_failed)
def _connect_failed (self, connection, exc):
debugprint ("CancelJobsOperation._connect_failed %s:%s" % (connection, repr (exc)))
def _connected (self, connection, result):
self.connection = connection
if self.purge_job:
operation = _("deleting job")
else:
operation = _("canceling job")
self.connection._begin_operation (operation)
self.connection.cancelJob (self.jobids[0], self.purge_job,
reply_handler=self.cancelJob_finish,
error_handler=self.cancelJob_error)
def cancelJob_error (self, connection, exc):
debugprint ("cancelJob_error %s:%s" % (connection, repr (exc)))
if type (exc) == cups.IPPError:
(e, m) = exc.args
if (e != cups.IPP_NOT_POSSIBLE and
e != cups.IPP_NOT_FOUND):
self.emit ('ipp-error', self.jobids[0], exc)
self.cancelJob_finish(connection, None)
else:
self.connection._end_operation ()
self.connection.destroy ()
self.connection = None
self.emit ('ipp-error', self.jobids[0], exc)
# Give up.
self.emit ('finished')
return
def cancelJob_finish (self, connection, result):
debugprint ("cancelJob_finish %s:%s" % (connection, repr (result)))
self.emit ('job-deleted', self.jobids[0])
del self.jobids[0]
if not self.jobids:
# Last job canceled.
self.connection._end_operation ()
self.connection.destroy ()
self.connection = None
self.emit ('finished')
return
else:
# there are other jobs to cancel/delete
connection.cancelJob (self.jobids[0], self.purge_job,
reply_handler=self.cancelJob_finish,
error_handler=self.cancelJob_error)
class JobViewer (GtkGUI):
required_job_attributes = set(['job-k-octets',
'job-name',
'job-originating-user-name',
'job-printer-uri',
'job-state',
'time-at-creation',
'auth-info-required',
'job-preserved'])
__gsignals__ = {
'finished': (GObject.SignalFlags.RUN_LAST, None, ())
}
def __init__(self, bus=None, loop=None,
applet=False, suppress_icon_hide=False,
my_jobs=True, specific_dests=None,
parent=None):
GObject.GObject.__init__ (self)
self.loop = loop
self.applet = applet
self.suppress_icon_hide = suppress_icon_hide
self.my_jobs = my_jobs
self.specific_dests = specific_dests
notify_caps = Notify.get_server_caps ()
self.notify_has_actions = "actions" in notify_caps
self.notify_has_persistence = "persistence" in notify_caps
self.jobs = {}
self.jobiters = {}
self.jobids = []
self.jobs_attrs = {} # dict of jobid->(GtkListStore, page_index)
self.active_jobs = set() # of job IDs
self.stopped_job_prompts = set() # of job IDs
self.printer_state_reasons = {}
self.num_jobs_when_hidden = 0
self.connecting_to_device = {} # dict of printer->time first seen
self.state_reason_notifications = {}
self.auth_info_dialogs = {} # by job ID
self.job_creation_times_timer = None
self.new_printer_notifications = {}
self.completed_job_notifications = {}
self.authenticated_jobs = set() # of job IDs
self.ops = []
self.getWidgets ({"JobsWindow":
["JobsWindow",
"treeview",
"statusbar",
"toolbar"],
"statusicon_popupmenu":
["statusicon_popupmenu"]},
domain=config.PACKAGE)
job_action_group = Gtk.ActionGroup (name="JobActionGroup")
job_action_group.add_actions ([
("cancel-job", Gtk.STOCK_CANCEL, _("_Cancel"), None,
_("Cancel selected jobs"), self.on_job_cancel_activate),
("delete-job", Gtk.STOCK_DELETE, _("_Delete"), None,
_("Delete selected jobs"), self.on_job_delete_activate),
("hold-job", Gtk.STOCK_MEDIA_PAUSE, _("_Hold"), None,
_("Hold selected jobs"), self.on_job_hold_activate),
("release-job", Gtk.STOCK_MEDIA_PLAY, _("_Release"), None,
_("Release selected jobs"), self.on_job_release_activate),
("reprint-job", Gtk.STOCK_REDO, _("Re_print"), None,
_("Reprint selected jobs"), self.on_job_reprint_activate),
("retrieve-job", Gtk.STOCK_SAVE_AS, _("Re_trieve"), None,
_("Retrieve selected jobs"), self.on_job_retrieve_activate),
("move-job", None, _("_Move To"), None, None, None),
("authenticate-job", None, _("_Authenticate"), None, None,
self.on_job_authenticate_activate),
("job-attributes", None, _("_View Attributes"), None, None,
self.on_job_attributes_activate),
("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
_("Close this window"), self.on_delete_event)
])
self.job_ui_manager = Gtk.UIManager ()
self.job_ui_manager.insert_action_group (job_action_group, -1)
self.job_ui_manager.add_ui_from_string (
"""
<ui>
<accelerator action="cancel-job"/>
<accelerator action="delete-job"/>
<accelerator action="hold-job"/>
<accelerator action="release-job"/>
<accelerator action="reprint-job"/>
<accelerator action="retrieve-job"/>
<accelerator action="move-job"/>
<accelerator action="authenticate-job"/>
<accelerator action="job-attributes"/>
<accelerator action="close"/>
</ui>
"""
)
self.job_ui_manager.ensure_update ()
self.JobsWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
self.job_context_menu = Gtk.Menu ()
for action_name in ["cancel-job",
"delete-job",
"hold-job",
"release-job",
"reprint-job",
"retrieve-job",
"move-job",
None,
"authenticate-job",
"job-attributes"]:
if not action_name:
item = Gtk.SeparatorMenuItem ()
else:
action = job_action_group.get_action (action_name)
action.set_sensitive (False)
item = action.create_menu_item ()
if action_name == 'move-job':
self.move_job_menuitem = item
printers = Gtk.Menu ()
item.set_submenu (printers)
item.show ()
self.job_context_menu.append (item)
for action_name in ["cancel-job",
"delete-job",
"hold-job",
"release-job",
"reprint-job",
"retrieve-job",
"close"]:
action = job_action_group.get_action (action_name)
action.set_sensitive (action_name == "close")
action.set_is_important (action_name == "close")
item = action.create_tool_item ()
item.show ()
self.toolbar.insert (item, -1)
for skip, ellipsize, name, setter in \
[(False, False, _("Job"), self._set_job_job_number_text),
(True, False, _("User"), self._set_job_user_text),
(False, True, _("Document"), self._set_job_document_text),
(False, True, _("Printer"), self._set_job_printer_text),
(False, False, _("Size"), self._set_job_size_text)]:
if applet and skip:
# Skip the user column when running as applet.
continue
cell = Gtk.CellRendererText()
if ellipsize:
# Ellipsize the 'Document' and 'Printer' columns.
cell.set_property ("ellipsize", Pango.EllipsizeMode.END)
cell.set_property ("width-chars", 20)
column = Gtk.TreeViewColumn(name, cell)
column.set_cell_data_func (cell, setter, None)
column.set_resizable(True)
self.treeview.append_column(column)
cell = Gtk.CellRendererText ()
column = Gtk.TreeViewColumn (_("Time submitted"), cell, text=1)
column.set_resizable (True)
self.treeview.append_column (column)
column = Gtk.TreeViewColumn (_("Status"))
icon = Gtk.CellRendererPixbuf ()
column.pack_start (icon, False)
text = Gtk.CellRendererText ()
text.set_property ("ellipsize", Pango.EllipsizeMode.END)
text.set_property ("width-chars", 20)
column.pack_start (text, True)
column.set_cell_data_func (icon, self._set_job_status_icon, None)
column.set_cell_data_func (text, self._set_job_status_text, None)
self.treeview.append_column (column)
self.store = Gtk.TreeStore(int, str)
self.store.set_sort_column_id (0, Gtk.SortType.DESCENDING)
self.treeview.set_model(self.store)
self.treeview.set_rules_hint (True)
self.selection = self.treeview.get_selection()
self.selection.set_mode(Gtk.SelectionMode.MULTIPLE)
self.selection.connect('changed', self.on_selection_changed)
self.treeview.connect ('button_release_event',
self.on_treeview_button_release_event)
self.treeview.connect ('popup-menu', self.on_treeview_popup_menu)
self.JobsWindow.set_icon_name (ICON)
self.JobsWindow.hide ()
if specific_dests:
the_dests = reduce (lambda x, y: x + ", " + y, specific_dests)
if my_jobs:
if specific_dests:
title = _("my jobs on %s") % the_dests
else:
title = _("my jobs")
else:
if specific_dests:
title = "%s" % the_dests
else:
title = _("all jobs")
self.JobsWindow.set_title (_("Document Print Status (%s)") % title)
if parent:
self.JobsWindow.set_transient_for (parent)
def load_icon(theme, icon):
try:
pixbuf = theme.load_icon (icon, ICON_SIZE, 0)
except GObject.GError:
debugprint ("No %s icon available" % icon)
# Just create an empty pixbuf.
pixbuf = GdkPixbuf.Pixbuf.new (GdkPixbuf.Colorspace.RGB,
True, 8, ICON_SIZE, ICON_SIZE)
pixbuf.fill (0)
return pixbuf
theme = Gtk.IconTheme.get_default ()
self.icon_jobs = load_icon (theme, ICON)
self.icon_jobs_processing = load_icon (theme, "printer-printing")
self.icon_no_jobs = self.icon_jobs.copy ()
self.icon_no_jobs.fill (0)
self.icon_jobs.composite (self.icon_no_jobs,
0, 0,
self.icon_no_jobs.get_width(),
self.icon_no_jobs.get_height(),
0, 0,
1.0, 1.0,
GdkPixbuf.InterpType.BILINEAR,
127)
if self.applet and not self.notify_has_persistence:
self.statusicon = Gtk.StatusIcon ()
self.statusicon.set_from_pixbuf (self.icon_no_jobs)
self.statusicon.connect ('activate', self.toggle_window_display)
self.statusicon.connect ('popup-menu', self.on_icon_popupmenu)
self.statusicon.set_visible (False)
# D-Bus
if bus is None:
bus = dbus.SystemBus ()
self.connect_signals ()
self.set_process_pending (True)
self.host = cups.getServer ()
self.port = cups.getPort ()
self.encryption = cups.getEncryption ()
self.monitor = monitor.Monitor (bus=bus, my_jobs=my_jobs,
specific_dests=specific_dests,
host=self.host, port=self.port,
encryption=self.encryption)
self.monitor.connect ('refresh', self.on_refresh)
self.monitor.connect ('job-added', self.job_added)
self.monitor.connect ('job-event', self.job_event)
self.monitor.connect ('job-removed', self.job_removed)
self.monitor.connect ('state-reason-added', self.state_reason_added)
self.monitor.connect ('state-reason-removed', self.state_reason_removed)
self.monitor.connect ('still-connecting', self.still_connecting)
self.monitor.connect ('now-connected', self.now_connected)
self.monitor.connect ('printer-added', self.printer_added)
self.monitor.connect ('printer-event', self.printer_event)
self.monitor.connect ('printer-removed', self.printer_removed)
self.monitor.refresh ()
self.my_monitor = None
if not my_jobs:
self.my_monitor = monitor.Monitor(bus=bus, my_jobs=True,
host=self.host, port=self.port,
encryption=self.encryption)
self.my_monitor.connect ('job-added', self.job_added)
self.my_monitor.connect ('job-event', self.job_event)
self.my_monitor.refresh ()
if not self.applet:
self.JobsWindow.show ()
self.JobsAttributesWindow = Gtk.Window()
self.JobsAttributesWindow.set_title (_("Job attributes"))
self.JobsAttributesWindow.set_position(Gtk.WindowPosition.MOUSE)
self.JobsAttributesWindow.set_default_size(600, 600)
self.JobsAttributesWindow.set_transient_for (self.JobsWindow)
self.JobsAttributesWindow.connect("delete_event",
self.job_attributes_on_delete_event)
self.JobsAttributesWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
attrs_action_group = Gtk.ActionGroup (name="AttrsActionGroup")
attrs_action_group.add_actions ([
("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
_("Close this window"), self.job_attributes_on_delete_event)
])
self.attrs_ui_manager = Gtk.UIManager ()
self.attrs_ui_manager.insert_action_group (attrs_action_group, -1)
self.attrs_ui_manager.add_ui_from_string (
"""
<ui>
<accelerator action="close"/>
</ui>
"""
)
self.attrs_ui_manager.ensure_update ()
self.JobsAttributesWindow.add_accel_group (self.attrs_ui_manager.get_accel_group ())
vbox = Gtk.VBox ()
self.JobsAttributesWindow.add (vbox)
toolbar = Gtk.Toolbar ()
action = self.attrs_ui_manager.get_action ("/close")
item = action.create_tool_item ()
item.set_is_important (True)
toolbar.insert (item, 0)
vbox.pack_start (toolbar, False, False, 0)
self.notebook = Gtk.Notebook()
vbox.pack_start (self.notebook, True, True, 0)
def cleanup (self):
self.monitor.cleanup ()
if self.my_monitor:
self.my_monitor.cleanup ()
self.JobsWindow.hide ()
# Close any open notifications.
for l in [self.new_printer_notifications.values (),
self.state_reason_notifications.values ()]:
for notification in l:
if getattr (notification, 'closed', None) != True:
try:
notification.close ()
except GLib.GError:
# Can fail if the notification wasn't even shown
# yet (as in bug #571603).
pass
notification.closed = True
if self.job_creation_times_timer is not None:
GLib.source_remove (self.job_creation_times_timer)
self.job_creation_times_timer = None
for op in self.ops:
op.destroy ()
if self.applet and not self.notify_has_persistence:
self.statusicon.set_visible (False)
self.emit ('finished')
def set_process_pending (self, whether):
self.process_pending_events = whether
def on_delete_event(self, *args):
if self.applet or not self.loop:
self.JobsWindow.hide ()
self.JobsWindow.visible = False
if not self.applet:
# Being run from main app, not applet
self.cleanup ()
else:
self.loop.quit ()
return True
def job_attributes_on_delete_event(self, widget, event=None):
for page in range(self.notebook.get_n_pages()):
self.notebook.remove_page(-1)
self.jobs_attrs = {}
self.JobsAttributesWindow.hide()
return True
def show_IPP_Error(self, exception, message):
return errordialogs.show_IPP_Error (exception, message, self.JobsWindow)
def toggle_window_display(self, icon, force_show=False):
visible = getattr (self.JobsWindow, 'visible', None)
if force_show:
visible = False
if self.notify_has_persistence:
if visible:
self.JobsWindow.hide ()
else:
self.JobsWindow.show ()
else:
if visible:
w = self.JobsWindow.get_window()
aw = self.JobsAttributesWindow.get_window()
(loc, s, area, o) = self.statusicon.get_geometry ()
if loc:
w.set_skip_taskbar_hint (True)
if aw is not None:
aw.set_skip_taskbar_hint (True)
self.JobsWindow.iconify ()
else:
self.JobsWindow.set_visible (False)
else:
self.JobsWindow.present ()
self.JobsWindow.set_skip_taskbar_hint (False)
aw = self.JobsAttributesWindow.get_window()
if aw is not None:
aw.set_skip_taskbar_hint (False)
self.JobsWindow.visible = not visible
def on_show_completed_jobs_clicked(self, toggletoolbutton):
if toggletoolbutton.get_active():
which_jobs = "all"
else:
which_jobs = "not-completed"
self.monitor.refresh(which_jobs=which_jobs, refresh_all=False)
if self.my_monitor:
self.my_monitor.refresh(which_jobs=which_jobs, refresh_all=False)
def update_job_creation_times(self):
now = time.time ()
need_update = False
for job, data in self.jobs.items():
t = _("Unknown")
if 'time-at-creation' in data:
created = data['time-at-creation']
ago = now - created
need_update = True
if ago < 2 * 60:
t = _("a minute ago")
elif ago < 60 * 60:
mins = int (ago / 60)
t = _("%d minutes ago") % mins
elif ago < 24 * 60 * 60:
hours = int (ago / (60 * 60))
if hours == 1:
t = _("an hour ago")
else:
t = _("%d hours ago") % hours
elif ago < 7 * 24 * 60 * 60:
days = int (ago / (24 * 60 * 60))
if days == 1:
t = _("yesterday")
else:
t = _("%d days ago") % days
elif ago < 6 * 7 * 24 * 60 * 60:
weeks = int (ago / (7 * 24 * 60 * 60))
if weeks == 1:
t = _("last week")
else:
t = _("%d weeks ago") % weeks
else:
need_update = False
t = time.strftime ("%B %Y", time.localtime (created))
if job in self.jobiters:
iter = self.jobiters[job]
self.store.set_value (iter, 1, t)
if need_update and not self.job_creation_times_timer:
def update_times_with_locking ():
Gdk.threads_enter ()
ret = self.update_job_creation_times ()
Gdk.threads_leave ()
return ret
t = GLib.timeout_add_seconds (60, update_times_with_locking)
self.job_creation_times_timer = t
if not need_update:
if self.job_creation_times_timer:
GLib.source_remove (self.job_creation_times_timer)
self.job_creation_times_timer = None
# Return code controls whether the timeout will recur.
return need_update
def print_error_dialog_response(self, dialog, response, jobid):
dialog.hide ()
dialog.destroy ()
self.stopped_job_prompts.remove (jobid)
if response == Gtk.ResponseType.NO:
# Diagnose
if 'troubleshooter' not in self.__dict__:
import troubleshoot
troubleshooter = troubleshoot.run (self.on_troubleshoot_quit)
self.troubleshooter = troubleshooter
def on_troubleshoot_quit(self, troubleshooter):
del self.troubleshooter
def add_job (self, job, data, connection=None):
self.update_job (job, data, connection=connection)
# There may have been an error fetching additional attributes,
# in which case we need to give up.
if job not in self.jobs:
return
store = self.store
iter = self.store.append (None)
store.set_value (iter, 0, job)
debugprint ("Job %d added" % job)
self.jobiters[job] = iter
range = self.treeview.get_visible_range ()
if range is not None:
(start, end) = range
if (self.store.get_sort_column_id () == (0,
Gtk.SortType.DESCENDING) and
start == Gtk.TreePath(1)):
# This job was added job above the visible range, and
# we are sorting by descending job ID. Scroll to it.
self.treeview.scroll_to_cell (Gtk.TreePath(), None,
False, 0.0, 0.0)
if not self.job_creation_times_timer:
def start_updating_job_creation_times():
Gdk.threads_enter ()
self.update_job_creation_times ()
Gdk.threads_leave ()
return False
GLib.timeout_add (500, start_updating_job_creation_times)
def update_monitor (self):
self.monitor.update ()
if self.my_monitor:
self.my_monitor.update ()
def update_job (self, job, data, connection=None):
# Fetch required attributes for this job if they are missing.
r = self.required_job_attributes - set (data.keys ())
# If we are showing attributes of this job at this moment, update them.
if job in self.jobs_attrs:
self.update_job_attributes_viewer(job)
if r:
attrs = None
try:
if connection is None:
connection = cups.Connection (host=self.host,
port=self.port,
encryption=self.encryption)
debugprint ("requesting %s" % r)
r = list (r)
attrs = connection.getJobAttributes (job,
requested_attributes=r)
except RuntimeError:
pass
except AttributeError:
pass
except cups.IPPError:
# someone else may have purged the job
return
if attrs:
data.update (attrs)
self.jobs[job] = data
job_requires_auth = False
try:
jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
s = int (jstate)
if s in [cups.IPP_JOB_HELD, cups.IPP_JOB_STOPPED]:
jattrs = ['job-state', 'job-hold-until', 'job-printer-uri']
pattrs = ['auth-info-required', 'device-uri']
# The current job-printer-uri may differ from the one that
# is returned when we request it over the connection.
# So while we use it to query the printer attributes we
# Update it afterwards to make sure that we really
# have the one cups uses in the job attributes.
uri = data.get ('job-printer-uri')
c = authconn.Connection (self.JobsWindow,
host=self.host,
port=self.port,
encryption=self.encryption)
attrs = c.getPrinterAttributes (uri = uri,
requested_attributes=pattrs)
try:
auth_info_required = attrs['auth-info-required']
except KeyError:
debugprint ("No auth-info-required attribute; "
"guessing instead")
auth_info_required = ['username', 'password']
if not isinstance (auth_info_required, list):
auth_info_required = [auth_info_required]
attrs['auth-info-required'] = auth_info_required
data.update (attrs)
attrs = c.getJobAttributes (job,
requested_attributes=jattrs)
data.update (attrs)
jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
s = int (jstate)
except ValueError:
pass
except RuntimeError:
pass
except cups.IPPError:
pass
# Invalidate the cached status description and redraw the treeview.
try:
del data['_status_text']
except KeyError:
pass
self.treeview.queue_draw ()
# Check whether authentication is required.
job_requires_auth = (s == cups.IPP_JOB_HELD and
data.get ('job-hold-until', 'none') ==
'auth-info-required')
if job_requires_auth:
# Try to get the authentication information. If we are not
# running as an applet just try to get the information silently
# and not prompt the user.
self.get_authentication (job, data.get ('device-uri'),
data.get ('job-printer-uri'),
data.get ('auth-info-required', []),
self.applet)
self.submenu_set = False
self.update_sensitivity ()
def get_authentication (self, job, device_uri, printer_uri,
auth_info_required, show_dialog):
# Check if we have requested authentication for this job already
if job not in self.auth_info_dialogs:
try:
cups.require ("1.9.37")
except:
debugprint ("Authentication required but "
"authenticateJob() not available")
return