Debian Codegraph @

jobviewer.py

raw
1
2 ## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Red Hat, Inc.
3 ## Authors:
4 ## Tim Waugh <[email protected]>
5 ## Jiri Popelka <[email protected]>
6
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
16
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 import asyncconn
22 import authconn
23 import cups
24 import dbus
25 import dbus.glib
26 import dbus.service
27 import threading
28 import gi
29 gi.require_version('Notify', '0.7')
30 from gi.repository import Notify
31 from gi.repository import GLib
32 from gi.repository import GObject
33 from gi.repository import Gdk
34 from gi.repository import GdkPixbuf
35 from gi.repository import Gtk
36 from gui import GtkGUI
37 import monitor
38 import os, shutil
39 from gi.repository import Pango
40 import pwd
41 import smburi
42 import subprocess
43 import sys
44 import time
45 import urllib.parse
46 from xml.sax import saxutils
47
48 from debug import *
49 import config
50 import statereason
51 import errordialogs
52 from functools import reduce
53
54 cups.require("1.9.47")
55
56 try:
57 gi.require_version('Secret', '1')
58 from gi.repository import Secret
59 USE_SECRET=True
60 except ValueError:
61 USE_SECRET=False
62
63 import gettext
64 gettext.install(domain=config.PACKAGE, localedir=config.localedir)
65
66 from statereason import StateReason
67
68 pkgdata = config.pkgdatadir
69 ICON="printer"
70 ICON_SIZE=22
71 SEARCHING_ICON="document-print-preview"
72
73 # We need to call Notify.init before we can check the server for caps
74 Notify.init('System Config Printer Notification')
75
76 if USE_SECRET:
77 NETWORK_PASSWORD = Secret.Schema.new("org.system.config.printer.store", Secret.SchemaFlags.NONE,
78 {
79 "user": Secret.SchemaAttributeType.STRING,
80 "domain": Secret.SchemaAttributeType.STRING,
81 "object": Secret.SchemaAttributeType.STRING,
82 "protocol": Secret.SchemaAttributeType.STRING,
83 "port": Secret.SchemaAttributeType.INTEGER,
84 "server": Secret.SchemaAttributeType.STRING,
85 "authtype": Secret.SchemaAttributeType.STRING,
86 "uri": Secret.SchemaAttributeType.STRING,
87 }
88 )
89
90
91 class ServiceGet:
92 service = Secret.Service()
93
94 def __init__(self):
95 self.service = Secret.Service.get_sync(0,
96 None)
97
98 def get_service(self):
99 return self.service
100
101
102 class ItemSearch:
103 items = list()
104
105 def __init__(self, service, attrs):
106 self.items = Secret.Service.search_sync(service,
107 NETWORK_PASSWORD,
108 attrs,
109 Secret.SearchFlags.LOAD_SECRETS,
110 None)
111
112 def get_items(self):
113 return self.items
114
115
116 class PasswordStore:
117 def __init__(self, attrs, name, secret):
118 Secret.password_store(NETWORK_PASSWORD,
119 attrs,
120 Secret.COLLECTION_DEFAULT,
121 name,
122 secret,
123 None,
124 self.on_password_stored)
125
126 def on_password_stored(self, source, result, unused):
127 Secret.password_store_finish(result)
128
129
130 class PrinterURIIndex:
131 def __init__ (self, names=None):
132 self.printer = {}
133 if names is None:
134 names = []
135
136 self.names = names
137 self._collect_names ()
138
139 def _collect_names (self, connection=None):
140 if not self.names:
141 return
142
143 if not connection:
144 try:
145 c = cups.Connection ()
146 except RuntimeError:
147 return
148
149 for name in self.names:
150 self.add_printer (name, connection=c)
151
152 self.names = []
153
154 def add_printer (self, printer, connection=None):
155 try:
156 self._map_printer (name=printer, connection=connection)
157 except KeyError:
158 return
159
160 def update_from_attrs (self, printer, attrs):
161 uris = []
162 if 'printer-uri-supported' in attrs:
163 uri_supported = attrs['printer-uri-supported']
164 if type (uri_supported) != list:
165 uri_supported = [uri_supported]
166 uris.extend (uri_supported)
167 if 'notify-printer-uri' in attrs:
168 uris.append (attrs['notify-printer-uri'])
169 if 'printer-more-info' in attrs:
170 uris.append (attrs['printer-more-info'])
171
172 for uri in uris:
173 self.printer[uri] = printer
174
175 def remove_printer (self, printer):
176 # Remove references to this printer in the URI map.
177 self._collect_names ()
178 uris = list(self.printer.keys ())
179 for uri in uris:
180 if self.printer[uri] == printer:
181 del self.printer[uri]
182
183 def lookup (self, uri, connection=None):
184 self._collect_names ()
185 try:
186 return self.printer[uri]
187 except KeyError:
188 return self._map_printer (uri=uri, connection=connection)
189
190 def all_printer_names (self):
191 self._collect_names ()
192 return set (self.printer.values ())
193
194 def lookup_cached_by_name (self, name):
195 self._collect_names ()
196 for uri, printer in self.printer.items ():
197 if printer == name:
198 return uri
199
200 raise KeyError
201
202 def _map_printer (self, uri=None, name=None, connection=None):
203 try:
204 if connection is None:
205 connection = cups.Connection ()
206
207 r = ['printer-name', 'printer-uri-supported', 'printer-more-info']
208 if uri is not None:
209 attrs = connection.getPrinterAttributes (uri=uri,
210 requested_attributes=r)
211 else:
212 attrs = connection.getPrinterAttributes (name,
213 requested_attributes=r)
214 except RuntimeError:
215 # cups.Connection() failed
216 raise KeyError
217 except cups.IPPError:
218 # URI not known.
219 raise KeyError
220
221 name = attrs['printer-name']
222 self.update_from_attrs (name, attrs)
223 if uri is not None:
224 self.printer[uri] = name
225 return name
226
227
228 class CancelJobsOperation(GObject.GObject):
229 __gsignals__ = {
230 'destroy': (GObject.SignalFlags.RUN_LAST, None, ()),
231 'job-deleted': (GObject.SignalFlags.RUN_LAST, None, (int,)),
232 'ipp-error': (GObject.SignalFlags.RUN_LAST, None,
233 (int, GObject.TYPE_PYOBJECT)),
234 'finished': (GObject.SignalFlags.RUN_LAST, None, ())
235 }
236
237 def __init__ (self, parent, host, port, encryption, jobids, purge_job):
238 GObject.GObject.__init__ (self)
239 self.jobids = list (jobids)
240 self.purge_job = purge_job
241 self.host = host
242 self.port = port
243 self.encryption = encryption
244 if purge_job:
245 if len(self.jobids) > 1:
246 dialog_title = _("Delete Jobs")
247 dialog_label = _("Do you really want to delete these jobs?")
248 else:
249 dialog_title = _("Delete Job")
250 dialog_label = _("Do you really want to delete this job?")
251 else:
252 if len(self.jobids) > 1:
253 dialog_title = _("Cancel Jobs")
254 dialog_label = _("Do you really want to cancel these jobs?")
255 else:
256 dialog_title = _("Cancel Job")
257 dialog_label = _("Do you really want to cancel this job?")
258
259 dialog = Gtk.Dialog (title=dialog_title, transient_for=parent,
260 modal=True, destroy_with_parent=True)
261 dialog.add_buttons (_("Keep Printing"), Gtk.ResponseType.NO,
262 dialog_title, Gtk.ResponseType.YES)
263 dialog.set_default_response (Gtk.ResponseType.NO)
264 dialog.set_border_width (6)
265 dialog.set_resizable (False)
266 hbox = Gtk.HBox.new (False, 12)
267 image = Gtk.Image ()
268 image.set_from_stock (Gtk.STOCK_DIALOG_QUESTION, Gtk.IconSize.DIALOG)
269 image.set_alignment (0.0, 0.0)
270 hbox.pack_start (image, False, False, 0)
271 label = Gtk.Label(label=dialog_label)
272 label.set_line_wrap (True)
273 label.set_alignment (0.0, 0.0)
274 hbox.pack_start (label, False, False, 0)
275 dialog.vbox.pack_start (hbox, False, False, 0)
276 dialog.connect ("response", self.on_job_cancel_prompt_response)
277 dialog.connect ("delete-event", self.on_job_cancel_prompt_delete)
278 dialog.show_all ()
279 self.dialog = dialog
280 self.connection = None
281 debugprint ("+%s" % self)
282
283 def __del__ (self):
284 debugprint ("-%s" % self)
285
286 def do_destroy (self):
287 if self.connection:
288 self.connection.destroy ()
289 self.connection = None
290
291 if self.dialog:
292 self.dialog.destroy ()
293 self.dialog = None
294
295 debugprint ("DESTROY: %s" % self)
296
297 def destroy (self):
298 self.emit ('destroy')
299
300 def on_job_cancel_prompt_delete (self, dialog, event):
301 self.on_job_cancel_prompt_response (dialog, Gtk.ResponseType.NO)
302
303 def on_job_cancel_prompt_response (self, dialog, response):
304 dialog.destroy ()
305 self.dialog = None
306
307 if response != Gtk.ResponseType.YES:
308 self.emit ('finished')
309 return
310
311 if len(self.jobids) == 0:
312 self.emit ('finished')
313 return
314
315 asyncconn.Connection (host=self.host,
316 port=self.port,
317 encryption=self.encryption,
318 reply_handler=self._connected,
319 error_handler=self._connect_failed)
320
321 def _connect_failed (self, connection, exc):
322 debugprint ("CancelJobsOperation._connect_failed %s:%s" % (connection, repr (exc)))
323
324 def _connected (self, connection, result):
325 self.connection = connection
326
327 if self.purge_job:
328 operation = _("deleting job")
329 else:
330 operation = _("canceling job")
331
332 self.connection._begin_operation (operation)
333 self.connection.cancelJob (self.jobids[0], self.purge_job,
334 reply_handler=self.cancelJob_finish,
335 error_handler=self.cancelJob_error)
336
337 def cancelJob_error (self, connection, exc):
338 debugprint ("cancelJob_error %s:%s" % (connection, repr (exc)))
339 if type (exc) == cups.IPPError:
340 (e, m) = exc.args
341 if (e != cups.IPP_NOT_POSSIBLE and
342 e != cups.IPP_NOT_FOUND):
343 self.emit ('ipp-error', self.jobids[0], exc)
344 self.cancelJob_finish(connection, None)
345 else:
346 self.connection._end_operation ()
347 self.connection.destroy ()
348 self.connection = None
349 self.emit ('ipp-error', self.jobids[0], exc)
350 # Give up.
351 self.emit ('finished')
352 return
353
354 def cancelJob_finish (self, connection, result):
355 debugprint ("cancelJob_finish %s:%s" % (connection, repr (result)))
356 self.emit ('job-deleted', self.jobids[0])
357 del self.jobids[0]
358 if not self.jobids:
359 # Last job canceled.
360 self.connection._end_operation ()
361 self.connection.destroy ()
362 self.connection = None
363 self.emit ('finished')
364 return
365 else:
366 # there are other jobs to cancel/delete
367 connection.cancelJob (self.jobids[0], self.purge_job,
368 reply_handler=self.cancelJob_finish,
369 error_handler=self.cancelJob_error)
370
371 class JobViewer (GtkGUI):
372 required_job_attributes = set(['job-k-octets',
373 'job-name',
374 'job-originating-user-name',
375 'job-printer-uri',
376 'job-state',
377 'time-at-creation',
378 'auth-info-required',
379 'job-preserved'])
380
381 __gsignals__ = {
382 'finished': (GObject.SignalFlags.RUN_LAST, None, ())
383 }
384
385 def __init__(self, bus=None, loop=None,
386 applet=False, suppress_icon_hide=False,
387 my_jobs=True, specific_dests=None,
388 parent=None):
389 GObject.GObject.__init__ (self)
390 self.loop = loop
391 self.applet = applet
392 self.suppress_icon_hide = suppress_icon_hide
393 self.my_jobs = my_jobs
394 self.specific_dests = specific_dests
395 notify_caps = Notify.get_server_caps ()
396 self.notify_has_actions = "actions" in notify_caps
397 self.notify_has_persistence = "persistence" in notify_caps
398
399 self.jobs = {}
400 self.jobiters = {}
401 self.jobids = []
402 self.jobs_attrs = {} # dict of jobid->(GtkListStore, page_index)
403 self.active_jobs = set() # of job IDs
404 self.stopped_job_prompts = set() # of job IDs
405 self.printer_state_reasons = {}
406 self.num_jobs_when_hidden = 0
407 self.connecting_to_device = {} # dict of printer->time first seen
408 self.state_reason_notifications = {}
409 self.auth_info_dialogs = {} # by job ID
410 self.job_creation_times_timer = None
411 self.new_printer_notifications = {}
412 self.completed_job_notifications = {}
413 self.authenticated_jobs = set() # of job IDs
414 self.ops = []
415
416 self.getWidgets ({"JobsWindow":
417 ["JobsWindow",
418 "treeview",
419 "statusbar",
420 "toolbar"],
421 "statusicon_popupmenu":
422 ["statusicon_popupmenu"]},
423
424 domain=config.PACKAGE)
425
426 job_action_group = Gtk.ActionGroup (name="JobActionGroup")
427 job_action_group.add_actions ([
428 ("cancel-job", Gtk.STOCK_CANCEL, _("_Cancel"), None,
429 _("Cancel selected jobs"), self.on_job_cancel_activate),
430 ("delete-job", Gtk.STOCK_DELETE, _("_Delete"), None,
431 _("Delete selected jobs"), self.on_job_delete_activate),
432 ("hold-job", Gtk.STOCK_MEDIA_PAUSE, _("_Hold"), None,
433 _("Hold selected jobs"), self.on_job_hold_activate),
434 ("release-job", Gtk.STOCK_MEDIA_PLAY, _("_Release"), None,
435 _("Release selected jobs"), self.on_job_release_activate),
436 ("reprint-job", Gtk.STOCK_REDO, _("Re_print"), None,
437 _("Reprint selected jobs"), self.on_job_reprint_activate),
438 ("retrieve-job", Gtk.STOCK_SAVE_AS, _("Re_trieve"), None,
439 _("Retrieve selected jobs"), self.on_job_retrieve_activate),
440 ("move-job", None, _("_Move To"), None, None, None),
441 ("authenticate-job", None, _("_Authenticate"), None, None,
442 self.on_job_authenticate_activate),
443 ("job-attributes", None, _("_View Attributes"), None, None,
444 self.on_job_attributes_activate),
445 ("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
446 _("Close this window"), self.on_delete_event)
447 ])
448 self.job_ui_manager = Gtk.UIManager ()
449 self.job_ui_manager.insert_action_group (job_action_group, -1)
450 self.job_ui_manager.add_ui_from_string (
451 """
452 <ui>
453 <accelerator action="cancel-job"/>
454 <accelerator action="delete-job"/>
455 <accelerator action="hold-job"/>
456 <accelerator action="release-job"/>
457 <accelerator action="reprint-job"/>
458 <accelerator action="retrieve-job"/>
459 <accelerator action="move-job"/>
460 <accelerator action="authenticate-job"/>
461 <accelerator action="job-attributes"/>
462 <accelerator action="close"/>
463 </ui>
464 """
465 )
466 self.job_ui_manager.ensure_update ()
467 self.JobsWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
468 self.job_context_menu = Gtk.Menu ()
469 for action_name in ["cancel-job",
470 "delete-job",
471 "hold-job",
472 "release-job",
473 "reprint-job",
474 "retrieve-job",
475 "move-job",
476 None,
477 "authenticate-job",
478 "job-attributes"]:
479 if not action_name:
480 item = Gtk.SeparatorMenuItem ()
481 else:
482 action = job_action_group.get_action (action_name)
483 action.set_sensitive (False)
484 item = action.create_menu_item ()
485
486 if action_name == 'move-job':
487 self.move_job_menuitem = item
488 printers = Gtk.Menu ()
489 item.set_submenu (printers)
490
491 item.show ()
492 self.job_context_menu.append (item)
493
494 for action_name in ["cancel-job",
495 "delete-job",
496 "hold-job",
497 "release-job",
498 "reprint-job",
499 "retrieve-job",
500 "close"]:
501 action = job_action_group.get_action (action_name)
502 action.set_sensitive (action_name == "close")
503 action.set_is_important (action_name == "close")
504 item = action.create_tool_item ()
505 item.show ()
506 self.toolbar.insert (item, -1)
507
508 for skip, ellipsize, name, setter in \
509 [(False, False, _("Job"), self._set_job_job_number_text),
510 (True, False, _("User"), self._set_job_user_text),
511 (False, True, _("Document"), self._set_job_document_text),
512 (False, True, _("Printer"), self._set_job_printer_text),
513 (False, False, _("Size"), self._set_job_size_text)]:
514 if applet and skip:
515 # Skip the user column when running as applet.
516 continue
517
518 cell = Gtk.CellRendererText()
519 if ellipsize:
520 # Ellipsize the 'Document' and 'Printer' columns.
521 cell.set_property ("ellipsize", Pango.EllipsizeMode.END)
522 cell.set_property ("width-chars", 20)
523 column = Gtk.TreeViewColumn(name, cell)
524 column.set_cell_data_func (cell, setter, None)
525 column.set_resizable(True)
526 self.treeview.append_column(column)
527
528 cell = Gtk.CellRendererText ()
529 column = Gtk.TreeViewColumn (_("Time submitted"), cell, text=1)
530 column.set_resizable (True)
531 self.treeview.append_column (column)
532
533 column = Gtk.TreeViewColumn (_("Status"))
534 icon = Gtk.CellRendererPixbuf ()
535 column.pack_start (icon, False)
536 text = Gtk.CellRendererText ()
537 text.set_property ("ellipsize", Pango.EllipsizeMode.END)
538 text.set_property ("width-chars", 20)
539 column.pack_start (text, True)
540 column.set_cell_data_func (icon, self._set_job_status_icon, None)
541 column.set_cell_data_func (text, self._set_job_status_text, None)
542 self.treeview.append_column (column)
543
544 self.store = Gtk.TreeStore(int, str)
545 self.store.set_sort_column_id (0, Gtk.SortType.DESCENDING)
546 self.treeview.set_model(self.store)
547 self.treeview.set_rules_hint (True)
548 self.selection = self.treeview.get_selection()
549 self.selection.set_mode(Gtk.SelectionMode.MULTIPLE)
550 self.selection.connect('changed', self.on_selection_changed)
551 self.treeview.connect ('button_release_event',
552 self.on_treeview_button_release_event)
553 self.treeview.connect ('popup-menu', self.on_treeview_popup_menu)
554
555 self.JobsWindow.set_icon_name (ICON)
556 self.JobsWindow.hide ()
557
558 if specific_dests:
559 the_dests = reduce (lambda x, y: x + ", " + y, specific_dests)
560
561 if my_jobs:
562 if specific_dests:
563 title = _("my jobs on %s") % the_dests
564 else:
565 title = _("my jobs")
566 else:
567 if specific_dests:
568 title = "%s" % the_dests
569 else:
570 title = _("all jobs")
571 self.JobsWindow.set_title (_("Document Print Status (%s)") % title)
572
573 if parent:
574 self.JobsWindow.set_transient_for (parent)
575
576 def load_icon(theme, icon):
577 try:
578 pixbuf = theme.load_icon (icon, ICON_SIZE, 0)
579 except GObject.GError:
580 debugprint ("No %s icon available" % icon)
581 # Just create an empty pixbuf.
582 pixbuf = GdkPixbuf.Pixbuf.new (GdkPixbuf.Colorspace.RGB,
583 True, 8, ICON_SIZE, ICON_SIZE)
584 pixbuf.fill (0)
585 return pixbuf
586
587 theme = Gtk.IconTheme.get_default ()
588 self.icon_jobs = load_icon (theme, ICON)
589 self.icon_jobs_processing = load_icon (theme, "printer-printing")
590 self.icon_no_jobs = self.icon_jobs.copy ()
591 self.icon_no_jobs.fill (0)
592 self.icon_jobs.composite (self.icon_no_jobs,
593 0, 0,
594 self.icon_no_jobs.get_width(),
595 self.icon_no_jobs.get_height(),
596 0, 0,
597 1.0, 1.0,
598 GdkPixbuf.InterpType.BILINEAR,
599 127)
600 if self.applet and not self.notify_has_persistence:
601 self.statusicon = Gtk.StatusIcon ()
602 self.statusicon.set_from_pixbuf (self.icon_no_jobs)
603 self.statusicon.connect ('activate', self.toggle_window_display)
604 self.statusicon.connect ('popup-menu', self.on_icon_popupmenu)
605 self.statusicon.set_visible (False)
606
607 # D-Bus
608 if bus is None:
609 bus = dbus.SystemBus ()
610
611 self.connect_signals ()
612 self.set_process_pending (True)
613 self.host = cups.getServer ()
614 self.port = cups.getPort ()
615 self.encryption = cups.getEncryption ()
616 self.monitor = monitor.Monitor (bus=bus, my_jobs=my_jobs,
617 specific_dests=specific_dests,
618 host=self.host, port=self.port,
619 encryption=self.encryption)
620 self.monitor.connect ('refresh', self.on_refresh)
621 self.monitor.connect ('job-added', self.job_added)
622 self.monitor.connect ('job-event', self.job_event)
623 self.monitor.connect ('job-removed', self.job_removed)
624 self.monitor.connect ('state-reason-added', self.state_reason_added)
625 self.monitor.connect ('state-reason-removed', self.state_reason_removed)
626 self.monitor.connect ('still-connecting', self.still_connecting)
627 self.monitor.connect ('now-connected', self.now_connected)
628 self.monitor.connect ('printer-added', self.printer_added)
629 self.monitor.connect ('printer-event', self.printer_event)
630 self.monitor.connect ('printer-removed', self.printer_removed)
631 self.monitor.refresh ()
632
633 self.my_monitor = None
634 if not my_jobs:
635 self.my_monitor = monitor.Monitor(bus=bus, my_jobs=True,
636 host=self.host, port=self.port,
637 encryption=self.encryption)
638 self.my_monitor.connect ('job-added', self.job_added)
639 self.my_monitor.connect ('job-event', self.job_event)
640 self.my_monitor.refresh ()
641
642 if not self.applet:
643 self.JobsWindow.show ()
644
645 self.JobsAttributesWindow = Gtk.Window()
646 self.JobsAttributesWindow.set_title (_("Job attributes"))
647 self.JobsAttributesWindow.set_position(Gtk.WindowPosition.MOUSE)
648 self.JobsAttributesWindow.set_default_size(600, 600)
649 self.JobsAttributesWindow.set_transient_for (self.JobsWindow)
650 self.JobsAttributesWindow.connect("delete_event",
651 self.job_attributes_on_delete_event)
652 self.JobsAttributesWindow.add_accel_group (self.job_ui_manager.get_accel_group ())
653 attrs_action_group = Gtk.ActionGroup (name="AttrsActionGroup")
654 attrs_action_group.add_actions ([
655 ("close", Gtk.STOCK_CLOSE, None, "<ctrl>w",
656 _("Close this window"), self.job_attributes_on_delete_event)
657 ])
658 self.attrs_ui_manager = Gtk.UIManager ()
659 self.attrs_ui_manager.insert_action_group (attrs_action_group, -1)
660 self.attrs_ui_manager.add_ui_from_string (
661 """
662 <ui>
663 <accelerator action="close"/>
664 </ui>
665 """
666 )
667 self.attrs_ui_manager.ensure_update ()
668 self.JobsAttributesWindow.add_accel_group (self.attrs_ui_manager.get_accel_group ())
669 vbox = Gtk.VBox ()
670 self.JobsAttributesWindow.add (vbox)
671 toolbar = Gtk.Toolbar ()
672 action = self.attrs_ui_manager.get_action ("/close")
673 item = action.create_tool_item ()
674 item.set_is_important (True)
675 toolbar.insert (item, 0)
676 vbox.pack_start (toolbar, False, False, 0)
677 self.notebook = Gtk.Notebook()
678 vbox.pack_start (self.notebook, True, True, 0)
679
680 def cleanup (self):
681 self.monitor.cleanup ()
682 if self.my_monitor:
683 self.my_monitor.cleanup ()
684
685 self.JobsWindow.hide ()
686
687 # Close any open notifications.
688 for l in [self.new_printer_notifications.values (),
689 self.state_reason_notifications.values ()]:
690 for notification in l:
691 if getattr (notification, 'closed', None) != True:
692 try:
693 notification.close ()
694 except GLib.GError:
695 # Can fail if the notification wasn't even shown
696 # yet (as in bug #571603).
697 pass
698 notification.closed = True
699
700 if self.job_creation_times_timer is not None:
701 GLib.source_remove (self.job_creation_times_timer)
702 self.job_creation_times_timer = None
703
704 for op in self.ops:
705 op.destroy ()
706
707 if self.applet and not self.notify_has_persistence:
708 self.statusicon.set_visible (False)
709
710 self.emit ('finished')
711
712 def set_process_pending (self, whether):
713 self.process_pending_events = whether
714
715 def on_delete_event(self, *args):
716 if self.applet or not self.loop:
717 self.JobsWindow.hide ()
718 self.JobsWindow.visible = False
719 if not self.applet:
720 # Being run from main app, not applet
721 self.cleanup ()
722 else:
723 self.loop.quit ()
724 return True
725
726 def job_attributes_on_delete_event(self, widget, event=None):
727 for page in range(self.notebook.get_n_pages()):
728 self.notebook.remove_page(-1)
729 self.jobs_attrs = {}
730 self.JobsAttributesWindow.hide()
731 return True
732
733 def show_IPP_Error(self, exception, message):
734 return errordialogs.show_IPP_Error (exception, message, self.JobsWindow)
735
736 def toggle_window_display(self, icon, force_show=False):
737 visible = getattr (self.JobsWindow, 'visible', None)
738 if force_show:
739 visible = False
740
741 if self.notify_has_persistence:
742 if visible:
743 self.JobsWindow.hide ()
744 else:
745 self.JobsWindow.show ()
746 else:
747 if visible:
748 w = self.JobsWindow.get_window()
749 aw = self.JobsAttributesWindow.get_window()
750 (loc, s, area, o) = self.statusicon.get_geometry ()
751
752 if loc:
753 w.set_skip_taskbar_hint (True)
754 if aw is not None:
755 aw.set_skip_taskbar_hint (True)
756 self.JobsWindow.iconify ()
757 else:
758 self.JobsWindow.set_visible (False)
759 else:
760 self.JobsWindow.present ()
761 self.JobsWindow.set_skip_taskbar_hint (False)
762 aw = self.JobsAttributesWindow.get_window()
763 if aw is not None:
764 aw.set_skip_taskbar_hint (False)
765
766 self.JobsWindow.visible = not visible
767
768 def on_show_completed_jobs_clicked(self, toggletoolbutton):
769 if toggletoolbutton.get_active():
770 which_jobs = "all"
771 else:
772 which_jobs = "not-completed"
773 self.monitor.refresh(which_jobs=which_jobs, refresh_all=False)
774 if self.my_monitor:
775 self.my_monitor.refresh(which_jobs=which_jobs, refresh_all=False)
776
777 def update_job_creation_times(self):
778 now = time.time ()
779 need_update = False
780 for job, data in self.jobs.items():
781 t = _("Unknown")
782 if 'time-at-creation' in data:
783 created = data['time-at-creation']
784 ago = now - created
785 need_update = True
786 if ago < 2 * 60:
787 t = _("a minute ago")
788 elif ago < 60 * 60:
789 mins = int (ago / 60)
790 t = _("%d minutes ago") % mins
791 elif ago < 24 * 60 * 60:
792 hours = int (ago / (60 * 60))
793 if hours == 1:
794 t = _("an hour ago")
795 else:
796 t = _("%d hours ago") % hours
797 elif ago < 7 * 24 * 60 * 60:
798 days = int (ago / (24 * 60 * 60))
799 if days == 1:
800 t = _("yesterday")
801 else:
802 t = _("%d days ago") % days
803 elif ago < 6 * 7 * 24 * 60 * 60:
804 weeks = int (ago / (7 * 24 * 60 * 60))
805 if weeks == 1:
806 t = _("last week")
807 else:
808 t = _("%d weeks ago") % weeks
809 else:
810 need_update = False
811 t = time.strftime ("%B %Y", time.localtime (created))
812
813 if job in self.jobiters:
814 iter = self.jobiters[job]
815 self.store.set_value (iter, 1, t)
816
817 if need_update and not self.job_creation_times_timer:
818 def update_times_with_locking ():
819 Gdk.threads_enter ()
820 ret = self.update_job_creation_times ()
821 Gdk.threads_leave ()
822 return ret
823
824 t = GLib.timeout_add_seconds (60, update_times_with_locking)
825 self.job_creation_times_timer = t
826
827 if not need_update:
828 if self.job_creation_times_timer:
829 GLib.source_remove (self.job_creation_times_timer)
830 self.job_creation_times_timer = None
831
832 # Return code controls whether the timeout will recur.
833 return need_update
834
835 def print_error_dialog_response(self, dialog, response, jobid):
836 dialog.hide ()
837 dialog.destroy ()
838 self.stopped_job_prompts.remove (jobid)
839 if response == Gtk.ResponseType.NO:
840 # Diagnose
841 if 'troubleshooter' not in self.__dict__:
842 import troubleshoot
843 troubleshooter = troubleshoot.run (self.on_troubleshoot_quit)
844 self.troubleshooter = troubleshooter
845
846 def on_troubleshoot_quit(self, troubleshooter):
847 del self.troubleshooter
848
849 def add_job (self, job, data, connection=None):
850 self.update_job (job, data, connection=connection)
851
852 # There may have been an error fetching additional attributes,
853 # in which case we need to give up.
854 if job not in self.jobs:
855 return
856
857 store = self.store
858 iter = self.store.append (None)
859 store.set_value (iter, 0, job)
860 debugprint ("Job %d added" % job)
861 self.jobiters[job] = iter
862
863 range = self.treeview.get_visible_range ()
864 if range is not None:
865 (start, end) = range
866 if (self.store.get_sort_column_id () == (0,
867 Gtk.SortType.DESCENDING) and
868 start == Gtk.TreePath(1)):
869 # This job was added job above the visible range, and
870 # we are sorting by descending job ID. Scroll to it.
871 self.treeview.scroll_to_cell (Gtk.TreePath(), None,
872 False, 0.0, 0.0)
873
874 if not self.job_creation_times_timer:
875 def start_updating_job_creation_times():
876 Gdk.threads_enter ()
877 self.update_job_creation_times ()
878 Gdk.threads_leave ()
879 return False
880
881 GLib.timeout_add (500, start_updating_job_creation_times)
882
883 def update_monitor (self):
884 self.monitor.update ()
885 if self.my_monitor:
886 self.my_monitor.update ()
887
888 def update_job (self, job, data, connection=None):
889 # Fetch required attributes for this job if they are missing.
890 r = self.required_job_attributes - set (data.keys ())
891
892 # If we are showing attributes of this job at this moment, update them.
893 if job in self.jobs_attrs:
894 self.update_job_attributes_viewer(job)
895
896 if r:
897 attrs = None
898 try:
899 if connection is None:
900 connection = cups.Connection (host=self.host,
901 port=self.port,
902 encryption=self.encryption)
903
904 debugprint ("requesting %s" % r)
905 r = list (r)
906 attrs = connection.getJobAttributes (job,
907 requested_attributes=r)
908 except RuntimeError:
909 pass
910 except AttributeError:
911 pass
912 except cups.IPPError:
913 # someone else may have purged the job
914 return
915
916 if attrs:
917 data.update (attrs)
918
919 self.jobs[job] = data
920
921 job_requires_auth = False
922 try:
923 jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
924 s = int (jstate)
925
926 if s in [cups.IPP_JOB_HELD, cups.IPP_JOB_STOPPED]:
927 jattrs = ['job-state', 'job-hold-until', 'job-printer-uri']
928 pattrs = ['auth-info-required', 'device-uri']
929 # The current job-printer-uri may differ from the one that
930 # is returned when we request it over the connection.
931 # So while we use it to query the printer attributes we
932 # Update it afterwards to make sure that we really
933 # have the one cups uses in the job attributes.
934 uri = data.get ('job-printer-uri')
935 c = authconn.Connection (self.JobsWindow,
936 host=self.host,
937 port=self.port,
938 encryption=self.encryption)
939 attrs = c.getPrinterAttributes (uri = uri,
940 requested_attributes=pattrs)
941
942 try:
943 auth_info_required = attrs['auth-info-required']
944 except KeyError:
945 debugprint ("No auth-info-required attribute; "
946 "guessing instead")
947 auth_info_required = ['username', 'password']
948
949 if not isinstance (auth_info_required, list):
950 auth_info_required = [auth_info_required]
951 attrs['auth-info-required'] = auth_info_required
952
953 data.update (attrs)
954
955 attrs = c.getJobAttributes (job,
956 requested_attributes=jattrs)
957 data.update (attrs)
958 jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
959 s = int (jstate)
960 except ValueError:
961 pass
962 except RuntimeError:
963 pass
964 except cups.IPPError:
965 pass
966
967 # Invalidate the cached status description and redraw the treeview.
968 try:
969 del data['_status_text']
970 except KeyError:
971 pass
972 self.treeview.queue_draw ()
973
974 # Check whether authentication is required.
975 job_requires_auth = (s == cups.IPP_JOB_HELD and
976 data.get ('job-hold-until', 'none') ==
977 'auth-info-required')
978 if job_requires_auth:
979 # Try to get the authentication information. If we are not
980 # running as an applet just try to get the information silently
981 # and not prompt the user.
982 self.get_authentication (job, data.get ('device-uri'),
983 data.get ('job-printer-uri'),
984 data.get ('auth-info-required', []),
985 self.applet)
986
987 self.submenu_set = False
988 self.update_sensitivity ()
989
990 def get_authentication (self, job, device_uri, printer_uri,
991 auth_info_required, show_dialog):
992 # Check if we have requested authentication for this job already
993 if job not in self.auth_info_dialogs:
994 try:
995 cups.require ("1.9.37")
996 except:
997 debugprint ("Authentication required but "
998 "authenticateJob() not available")
999 return
1000
1001 # Find out which auth-info is required.
1002 try_secret = USE_SECRET
1003 informational_attrs = dict()
1004 auth_info = None
1005 if try_secret and 'password' in auth_info_required:
1006 (scheme, rest) = urllib.parse.splittype (device_uri)
1007 if scheme == 'smb':
1008 uri = smburi.SMBURI (uri=device_uri)
1009 (group, server, share,
1010 user, password) = uri.separate ()
1011 informational_attrs["domain"] = str (group)
1012 else:
1013 (serverport, rest) = urllib.parse.splithost (rest)
1014 if serverport is None:
1015 server = None
1016 else:
1017 (server, port) = urllib.parse.splitnport (serverport)
1018
1019 if scheme is None or server is None:
1020 try_secret = False
1021 else:
1022 informational_attrs.update ({ "server": str (server.lower ()),
1023 "protocol": str (scheme)})
1024
1025 if job in self.authenticated_jobs:
1026 # We've already tried to authenticate this job before.
1027 try_secret = False
1028
1029 # To increase compatibility and resolve problems with
1030 # multiple printers on one host we use the printers URI
1031 # as the identifying attribute. Versions <= 1.4.4 used
1032 # a combination of domain / server / protocol instead.
1033 # The old attributes are still used as a fallback for identifying
1034 # the secret but are otherwise only informational.
1035 identifying_attrs = { "uri": str (printer_uri) }
1036
1037 if try_secret and 'password' in auth_info_required:
1038 for keyring_attrs in [identifying_attrs, informational_attrs]:
1039 attrs = dict()
1040 for key, val in keyring_attrs.items ():
1041 key_val_dict = {key : val}
1042 attrs.update (key_val_dict)
1043 service_obj = ServiceGet()
1044 service = service_obj.get_service()
1045
1046 search_obj = ItemSearch(service, attrs)
1047 items = search_obj.get_items()
1048
1049 if items:
1050 auth_info = ['' for x in auth_info_required]
1051 ind = auth_info_required.index ('username')
1052 auth_info[ind] = items[0].get_attributes().get("user")
1053
1054 ind = auth_info_required.index ('password')
1055 auth_info[ind] = items[0].get_secret().get().decode()
1056 break
1057 else:
1058 debugprint ("Failed to find secret in keyring.")
1059
1060 if try_secret:
1061 try:
1062 c = authconn.Connection (self.JobsWindow,
1063 host=self.host,
1064 port=self.port,
1065 encryption=self.encryption)
1066 except RuntimeError:
1067 try_secret = False
1068
1069 if try_secret and auth_info is not None:
1070 try:
1071 c._begin_operation (_("authenticating job"))
1072 c.authenticateJob (job, auth_info)
1073 c._end_operation ()
1074 self.update_monitor ()
1075 debugprint ("Automatically authenticated job %d" % job)
1076 self.authenticated_jobs.add (job)
1077 return
1078 except cups.IPPError:
1079 c._end_operation ()
1080 nonfatalException ()
1081 return
1082 except:
1083 c._end_operation ()
1084 nonfatalException ()
1085
1086 if auth_info_required and show_dialog:
1087 username = pwd.getpwuid (os.getuid ())[0]
1088 keyring_attrs = informational_attrs.copy()
1089 keyring_attrs.update(identifying_attrs)
1090 keyring_attrs["user"] = str (username)
1091 self.display_auth_info_dialog (job, keyring_attrs)
1092
1093 def display_auth_info_dialog (self, job, keyring_attrs=None):
1094 data = self.jobs[job]
1095 try:
1096 auth_info_required = data['auth-info-required']
1097 except KeyError:
1098 debugprint ("No auth-info-required attribute; "
1099 "guessing instead")
1100 auth_info_required = ['username', 'password']
1101 dialog = authconn.AuthDialog (auth_info_required=auth_info_required,
1102 allow_remember=USE_SECRET)
1103 dialog.keyring_attrs = keyring_attrs
1104 dialog.auth_info_required = auth_info_required
1105 dialog.set_position (Gtk.WindowPosition.CENTER)
1106
1107 # Pre-fill 'username' field.
1108 auth_info = ['' for x in auth_info_required]
1109 username = pwd.getpwuid (os.getuid ())[0]
1110 if 'username' in auth_info_required:
1111 try:
1112 ind = auth_info_required.index ('username')
1113 auth_info[ind] = username
1114 dialog.set_auth_info (auth_info)
1115 except:
1116 nonfatalException ()
1117
1118 # Focus on the first empty field.
1119 index = 0
1120 for field in auth_info_required:
1121 if auth_info[index] == '':
1122 dialog.field_grab_focus (field)
1123 break
1124 index += 1
1125
1126 dialog.set_prompt (_("Authentication required for "
1127 "printing document `%s' (job %d)") %
1128 (data.get('job-name', _("Unknown")),
1129 job))
1130 self.auth_info_dialogs[job] = dialog
1131 dialog.connect ('response', self.auth_info_dialog_response)
1132 dialog.connect ('delete-event', self.auth_info_dialog_delete)
1133 dialog.job_id = job
1134 dialog.show_all ()
1135 dialog.set_keep_above (True)
1136 dialog.show_now ()
1137
1138 def auth_info_dialog_delete (self, dialog, event):
1139 self.auth_info_dialog_response (dialog, Gtk.ResponseType.CANCEL)
1140
1141 def auth_info_dialog_response (self, dialog, response):
1142 jobid = dialog.job_id
1143 del self.auth_info_dialogs[jobid]
1144
1145 if response != Gtk.ResponseType.OK:
1146 dialog.destroy ()
1147 return
1148
1149 auth_info = dialog.get_auth_info ()
1150 try:
1151 c = authconn.Connection (self.JobsWindow,
1152 host=self.host,
1153 port=self.port,
1154 encryption=self.encryption)
1155 except RuntimeError:
1156 debugprint ("Error connecting to CUPS for authentication")
1157 return
1158
1159 remember = False
1160 c._begin_operation (_("authenticating job"))
1161 try:
1162 c.authenticateJob (jobid, auth_info)
1163 remember = dialog.get_remember_password ()
1164 self.authenticated_jobs.add (jobid)
1165 self.update_monitor ()
1166 except cups.IPPError as e:
1167 (e, m) = e.args
1168 self.show_IPP_Error (e, m)
1169
1170 c._end_operation ()
1171
1172 if remember:
1173 try:
1174 keyring_attrs = getattr (dialog,
1175 "keyring_attrs",
1176 None)
1177 auth_info_required = getattr (dialog,
1178 "auth_info_required",
1179 None)
1180 if keyring_attrs is not None and auth_info_required is not None:
1181 try:
1182 ind = auth_info_required.index ('username')
1183 keyring_attrs['user'] = auth_info[ind]
1184 except IndexError:
1185 pass
1186
1187 name = "%s@%s (%s)" % (keyring_attrs.get ("user"),
1188 keyring_attrs.get ("server"),
1189 keyring_attrs.get ("protocol"))
1190 ind = auth_info_required.index ('password')
1191 secret = auth_info[ind]
1192 attrs = dict()
1193 for key, val in keyring_attrs.items ():
1194 key_val_dict = {key : val}
1195 attrs.update (key_val_dict)
1196 password_obj = PasswordStore(attrs,
1197 name,
1198 secret)
1199 debugprint ("keyring: created id %d for %s" % (id, name))
1200 except:
1201 nonfatalException ()
1202
1203 dialog.destroy ()
1204
1205 def set_statusicon_visibility (self):
1206 if not self.applet:
1207 return
1208
1209 if self.suppress_icon_hide:
1210 # Avoid hiding the icon if we've been woken up to notify
1211 # about a new printer.
1212 self.suppress_icon_hide = False
1213 return
1214
1215 open_notifications = len (self.new_printer_notifications.keys ())
1216 open_notifications += len (self.completed_job_notifications.keys ())
1217 for reason, notification in self.state_reason_notifications.items():
1218 if getattr (notification, 'closed', None) != True:
1219 open_notifications += 1
1220 num_jobs = len (self.active_jobs)
1221
1222 debugprint ("open notifications: %d" % open_notifications)
1223 debugprint ("num_jobs: %d" % num_jobs)
1224 debugprint ("num_jobs_when_hidden: %d" % self.num_jobs_when_hidden)
1225
1226 if self.notify_has_persistence:
1227 return
1228
1229 # Don't handle tooltips during the mainloop recursion at the
1230 # end of this function as it seems to cause havoc (bug #664044,
1231 # bug #739745).
1232 self.statusicon.set_has_tooltip (False)
1233
1234 self.statusicon.set_visible (open_notifications > 0 or
1235 num_jobs > self.num_jobs_when_hidden)
1236
1237 # Let the icon show/hide itself before continuing.
1238 while self.process_pending_events and Gtk.events_pending ():
1239 Gtk.main_iteration ()
1240
1241 def on_treeview_popup_menu (self, treeview):
1242 event = Gdk.Event (Gdk.EventType.NOTHING)
1243 self.show_treeview_popup_menu (treeview, event, 0)
1244
1245 def on_treeview_button_release_event(self, treeview, event):
1246 if event.button == 3:
1247 self.show_treeview_popup_menu (treeview, event, event.button)
1248
1249 def update_sensitivity (self, selection = None):
1250 if (selection is None):
1251 selection = self.treeview.get_selection ()
1252 (model, pathlist) = selection.get_selected_rows()
1253 cancel = self.job_ui_manager.get_action ("/cancel-job")
1254 delete = self.job_ui_manager.get_action ("/delete-job")
1255 hold = self.job_ui_manager.get_action ("/hold-job")
1256 release = self.job_ui_manager.get_action ("/release-job")
1257 reprint = self.job_ui_manager.get_action ("/reprint-job")
1258 retrieve = self.job_ui_manager.get_action ("/retrieve-job")
1259 authenticate = self.job_ui_manager.get_action ("/authenticate-job")
1260 attributes = self.job_ui_manager.get_action ("/job-attributes")
1261 move = self.job_ui_manager.get_action ("/move-job")
1262 if len (pathlist) == 0:
1263 for widget in [cancel, delete, hold, release, reprint, retrieve,
1264 move, authenticate, attributes]:
1265 widget.set_sensitive (False)
1266 return
1267
1268 cancel_sensitive = True
1269 hold_sensitive = True
1270 release_sensitive = True
1271 reprint_sensitive = True
1272 authenticate_sensitive = True
1273 move_sensitive = False
1274 other_printers = self.printer_uri_index.all_printer_names ()
1275 job_printers = dict()
1276
1277 self.jobids = []
1278 for path in pathlist:
1279 iter = self.store.get_iter (path)
1280 jobid = self.store.get_value (iter, 0)
1281 self.jobids.append(jobid)
1282 job = self.jobs[jobid]
1283
1284 if 'job-state' in job:
1285 s = job['job-state']
1286 if s >= cups.IPP_JOB_CANCELED:
1287 cancel_sensitive = False
1288 if s != cups.IPP_JOB_PENDING:
1289 hold_sensitive = False
1290 if s != cups.IPP_JOB_HELD:
1291 release_sensitive = False
1292 if (not job.get('job-preserved', False)):
1293 reprint_sensitive = False
1294
1295 if (job.get ('job-state',
1296 cups.IPP_JOB_CANCELED) != cups.IPP_JOB_HELD or
1297 job.get ('job-hold-until', 'none') != 'auth-info-required'):
1298 authenticate_sensitive = False
1299
1300 uri = job.get ('job-printer-uri', None)
1301 if uri:
1302 try:
1303 printer = self.printer_uri_index.lookup (uri)
1304 except KeyError:
1305 printer = uri
1306 job_printers[printer] = uri
1307
1308 if len (job_printers.keys ()) == 1:
1309 try:
1310 other_printers.remove (list(job_printers.keys ())[0])
1311 except KeyError:
1312 pass
1313
1314 if len (other_printers) > 0:
1315 printers_menu = Gtk.Menu ()
1316 other_printers = list (other_printers)
1317 other_printers.sort ()
1318 for printer in other_printers:
1319 try:
1320 uri = self.printer_uri_index.lookup_cached_by_name (printer)
1321 except KeyError:
1322 uri = None
1323 menuitem = Gtk.MenuItem (label=printer)
1324 menuitem.set_sensitive (uri is not None)
1325 menuitem.show ()
1326 self._submenu_connect_hack (menuitem,
1327 self.on_job_move_activate,
1328 uri)
1329 printers_menu.append (menuitem)
1330
1331 self.move_job_menuitem.set_submenu (printers_menu)
1332 move_sensitive = True
1333
1334 cancel.set_sensitive(cancel_sensitive)
1335 delete.set_sensitive(not cancel_sensitive)
1336 hold.set_sensitive(hold_sensitive)
1337 release.set_sensitive(release_sensitive)
1338 reprint.set_sensitive(reprint_sensitive)
1339 retrieve.set_sensitive(reprint_sensitive)
1340 move.set_sensitive (move_sensitive)
1341 authenticate.set_sensitive(authenticate_sensitive)
1342 attributes.set_sensitive(True)
1343
1344 def on_selection_changed (self, selection):
1345 self.update_sensitivity (selection)
1346
1347 def show_treeview_popup_menu (self, treeview, event, event_button):
1348 # Right-clicked.
1349 self.job_context_menu.popup (None, None, None, None, event_button,
1350 event.get_time ())
1351
1352 def on_icon_popupmenu(self, icon, button, time):
1353 self.statusicon_popupmenu.popup (None, None, None, None, button, time)
1354
1355 def on_icon_hide_activate(self, menuitem):
1356 self.num_jobs_when_hidden = len (self.jobs.keys ())
1357 self.set_statusicon_visibility ()
1358
1359 def on_icon_configure_printers_activate(self, menuitem):
1360 env = {}
1361 for name, value in os.environ.items ():
1362 if name == "SYSTEM_CONFIG_PRINTER_UI":
1363 continue
1364 env[name] = value
1365 p = subprocess.Popen ([ "system-config-printer" ],
1366 close_fds=True, env=env)
1367 GLib.timeout_add_seconds (10, self.poll_subprocess, p)
1368
1369 def poll_subprocess(self, process):
1370 returncode = process.poll ()
1371 return returncode is None
1372
1373 def on_icon_quit_activate (self, menuitem):
1374 self.cleanup ()
1375 if self.loop:
1376 self.loop.quit ()
1377
1378 def on_job_cancel_activate(self, menuitem):
1379 self.on_job_cancel_activate2(False)
1380
1381 def on_job_delete_activate(self, menuitem):
1382 self.on_job_cancel_activate2(True)
1383
1384 def on_job_cancel_activate2(self, purge_job):
1385 if self.jobids:
1386 op = CancelJobsOperation (self.JobsWindow, self.host, self.port,
1387 self.encryption, self.jobids, purge_job)
1388 self.ops.append (op)
1389 op.connect ('finished', self.on_canceljobs_finished)
1390 op.connect ('ipp-error', self.on_canceljobs_error)
1391
1392 def on_canceljobs_finished (self, canceljobsoperation):
1393 canceljobsoperation.destroy ()
1394 i = self.ops.index (canceljobsoperation)
1395 del self.ops[i]
1396 self.update_monitor ()
1397
1398 def on_canceljobs_error (self, canceljobsoperation, jobid, exc):
1399 self.update_monitor ()
1400 if type (exc) == cups.IPPError:
1401 (e, m) = exc.args
1402 if (e != cups.IPP_NOT_POSSIBLE and
1403 e != cups.IPP_NOT_FOUND):
1404 self.show_IPP_Error (e, m)
1405
1406 return
1407
1408 raise exc
1409
1410 def on_job_hold_activate(self, menuitem):
1411 try:
1412 c = authconn.Connection (self.JobsWindow,
1413 host=self.host,
1414 port=self.port,
1415 encryption=self.encryption)
1416 except RuntimeError:
1417 return
1418
1419 for jobid in self.jobids:
1420 c._begin_operation (_("holding job"))
1421 try:
1422 c.setJobHoldUntil (jobid, "indefinite")
1423 except cups.IPPError as e:
1424 (e, m) = e.args
1425 if (e != cups.IPP_NOT_POSSIBLE and
1426 e != cups.IPP_NOT_FOUND):
1427 self.show_IPP_Error (e, m)
1428 self.update_monitor ()
1429 c._end_operation ()
1430 return
1431 c._end_operation ()
1432
1433 del c
1434 self.update_monitor ()
1435
1436 def on_job_release_activate(self, menuitem):
1437 try:
1438 c = authconn.Connection (self.JobsWindow,
1439 host=self.host,
1440 port=self.port,
1441 encryption=self.encryption)
1442 except RuntimeError:
1443 return
1444
1445 for jobid in self.jobids:
1446 c._begin_operation (_("releasing job"))
1447 try:
1448 c.setJobHoldUntil (jobid, "no-hold")
1449 except cups.IPPError as e:
1450 (e, m) = e.args
1451 if (e != cups.IPP_NOT_POSSIBLE and
1452 e != cups.IPP_NOT_FOUND):
1453 self.show_IPP_Error (e, m)
1454 self.update_monitor ()
1455 c._end_operation ()
1456 return
1457 c._end_operation ()
1458
1459 del c
1460 self.update_monitor ()
1461
1462 def on_job_reprint_activate(self, menuitem):
1463 try:
1464 c = authconn.Connection (self.JobsWindow,
1465 host=self.host,
1466 port=self.port,
1467 encryption=self.encryption)
1468 for jobid in self.jobids:
1469 c.restartJob (jobid)
1470 del c
1471 except cups.IPPError as e:
1472 (e, m) = e.args
1473 self.show_IPP_Error (e, m)
1474 self.update_monitor ()
1475 return
1476 except RuntimeError:
1477 return
1478
1479 self.update_monitor ()
1480
1481 def on_job_retrieve_activate(self, menuitem):
1482 try:
1483 c = authconn.Connection (self.JobsWindow,
1484 host=self.host,
1485 port=self.port,
1486 encryption=self.encryption)
1487 except RuntimeError:
1488 return
1489
1490 for jobid in self.jobids:
1491 try:
1492 attrs=c.getJobAttributes(jobid)
1493 printer_uri=attrs['job-printer-uri']
1494 try:
1495 document_count = attrs['number-of-documents']
1496 except KeyError:
1497 document_count = attrs.get ('document-count', 0)
1498
1499 for document_number in range(1, document_count+1):
1500 document=c.getDocument(printer_uri, jobid, document_number)
1501 tempfile = document.get('file')
1502 name = document.get('document-name')
1503 format = document.get('document-format', '')
1504
1505 # if there's no document-name retrieved
1506 if name is None:
1507 # give the default filename some meaningful name
1508 name = _("retrieved")+str(document_number)
1509 # add extension according to format
1510 if format == 'application/postscript':
1511 name = name + ".ps"
1512 elif format.find('application/vnd.') != -1:
1513 name = name + format.replace('application/vnd', '')
1514 elif format.find('application/') != -1:
1515 name = name + format.replace('application/', '.')
1516
1517 if tempfile is not None:
1518 dialog = Gtk.FileChooserDialog (title=_("Save File"),
1519 transient_for=self.JobsWindow,
1520 action=Gtk.FileChooserAction.SAVE)
1521 dialog.add_buttons (
1522 Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
1523 Gtk.STOCK_SAVE, Gtk.ResponseType.OK)
1524 dialog.set_current_name(name)
1525 dialog.set_do_overwrite_confirmation(True)
1526
1527 response = dialog.run()
1528 if response == Gtk.ResponseType.OK:
1529 file_to_save = dialog.get_filename()
1530 try:
1531 shutil.copyfile(tempfile, file_to_save)
1532 except (IOError, shutil.Error):
1533 debugprint("Unable to save file "+file_to_save)
1534 elif response == Gtk.ResponseType.CANCEL:
1535 pass
1536 dialog.destroy()
1537 os.unlink(tempfile)
1538 else:
1539 debugprint("Unable to retrieve file from job file")
1540 return
1541
1542 except cups.IPPError as e:
1543 (e, m) = e.args
1544 self.show_IPP_Error (e, m)
1545 self.update_monitor ()
1546 return
1547
1548 del c
1549 self.update_monitor ()
1550
1551 def _submenu_connect_hack (self, item, callback, *args):
1552 # See https://bugzilla.gnome.org/show_bug.cgi?id=695488
1553 only_once = threading.Semaphore (1)
1554 def handle_event (item, event=None):
1555 if only_once.acquire (False):
1556 GObject.idle_add (callback, item, *args)
1557
1558 return (item.connect ('button-press-event', handle_event),
1559 item.connect ('activate', handle_event))
1560
1561 def on_job_move_activate(self, menuitem, job_printer_uri):
1562 try:
1563 c = authconn.Connection (self.JobsWindow,
1564 host=self.host,
1565 port=self.port,
1566 encryption=self.encryption)
1567 for jobid in self.jobids:
1568 c.moveJob (job_id=jobid, job_printer_uri=job_printer_uri)
1569 del c
1570 except cups.IPPError as e:
1571 (e, m) = e.args
1572 self.show_IPP_Error (e, m)
1573 self.update_monitor ()
1574 return
1575 except RuntimeError:
1576 return
1577
1578 self.update_monitor ()
1579
1580 def on_job_authenticate_activate(self, menuitem):
1581 try:
1582 c = cups.Connection (host=self.host,
1583 port=self.port,
1584 encryption=self.encryption)
1585 except RuntimeError:
1586 return False
1587
1588 jattrs_req = ['job-printer-uri']
1589 pattrs_req = ['auth-info-required', 'device-uri']
1590
1591 for jobid in self.jobids:
1592 # Get the required attributes for this job
1593 jattrs = c.getJobAttributes (jobid,
1594 requested_attributes=jattrs_req)
1595 uri = jattrs.get ('job-printer-uri')
1596 pattrs = c.getPrinterAttributes (uri = uri,
1597 requested_attributes=pattrs_req)
1598 try:
1599 auth_info_required = pattrs['auth-info-required']
1600 except KeyError:
1601 debugprint ("No auth-info-required attribute; "
1602 "guessing instead")
1603 auth_info_required = ['username', 'password']
1604
1605 self.get_authentication (jobid, pattrs.get ('device-uri'),
1606 uri, auth_info_required, True)
1607
1608 def on_refresh_clicked(self, toolbutton):
1609 self.monitor.refresh ()
1610 if self.my_monitor:
1611 self.my_monitor.refresh ()
1612
1613 self.update_job_creation_times ()
1614
1615 def on_job_attributes_activate(self, menuitem):
1616 """ For every selected job create notebook page with attributes. """
1617 try:
1618 c = cups.Connection (host=self.host,
1619 port=self.port,
1620 encryption=self.encryption)
1621 except RuntimeError:
1622 return False
1623
1624 for jobid in self.jobids:
1625 if jobid not in self.jobs_attrs:
1626 # add new notebook page with scrollable treeview
1627 scrolledwindow = Gtk.ScrolledWindow()
1628 label = Gtk.Label(label=str(jobid)) # notebook page has label with jobid
1629 page_index = self.notebook.append_page(scrolledwindow, label)
1630 attr_treeview = Gtk.TreeView()
1631 scrolledwindow.add(attr_treeview)
1632 cell = Gtk.CellRendererText ()
1633 attr_treeview.insert_column_with_attributes(0, _("Name"),
1634 cell, text=0)
1635 cell = Gtk.CellRendererText ()
1636 attr_treeview.insert_column_with_attributes(1, _("Value"),
1637 cell, text=1)
1638 attr_store = Gtk.ListStore(str, str)
1639 attr_treeview.set_model(attr_store)
1640 attr_treeview.get_selection().set_mode(Gtk.SelectionMode.NONE)
1641 attr_store.set_sort_column_id (0, Gtk.SortType.ASCENDING)
1642 self.jobs_attrs[jobid] = (attr_store, page_index)
1643 self.update_job_attributes_viewer (jobid, conn=c)
1644
1645 self.JobsAttributesWindow.show_all ()
1646
1647 def update_job_attributes_viewer(self, jobid, conn=None):
1648 """ Update attributes store with new values. """
1649 if conn is not None:
1650 c = conn
1651 else:
1652 try:
1653 c = cups.Connection (host=self.host,
1654 port=self.port,
1655 encryption=self.encryption)
1656 except RuntimeError:
1657 return False
1658
1659 if jobid in self.jobs_attrs:
1660 (attr_store, page) = self.jobs_attrs[jobid]
1661 try:
1662 attrs = c.getJobAttributes(jobid) # new attributes
1663 except AttributeError:
1664 return
1665 except cups.IPPError:
1666 # someone else may have purged the job,
1667 # remove jobs notebook page
1668 self.notebook.remove_page(page)
1669 del self.jobs_attrs[jobid]
1670 return
1671
1672 attr_store.clear() # remove old attributes
1673 for name, value in attrs.items():
1674 if name in ['job-id', 'job-printer-up-time']:
1675 continue
1676 attr_store.append([name, str(value)])
1677
1678 def job_is_active (self, jobdata):
1679 state = jobdata.get ('job-state', cups.IPP_JOB_CANCELED)
1680 if state >= cups.IPP_JOB_CANCELED:
1681 return False
1682
1683 return True
1684
1685 ## Icon manipulation
1686 def add_state_reason_emblem (self, pixbuf, printer=None):
1687 worst_reason = None
1688 if printer is None and self.worst_reason is not None:
1689 # Check that it's valid.
1690 printer = self.worst_reason.get_printer ()
1691 found = False
1692 for reason in self.printer_state_reasons.get (printer, []):
1693 if reason == self.worst_reason:
1694 worst_reason = self.worst_reason
1695 break
1696 if worst_reason is None:
1697 self.worst_reason = None
1698
1699 if printer is not None:
1700 for reason in self.printer_state_reasons.get (printer, []):
1701 if worst_reason is None:
1702 worst_reason = reason
1703 elif reason > worst_reason:
1704 worst_reason = reason
1705
1706 if worst_reason is not None:
1707 level = worst_reason.get_level ()
1708 if level > StateReason.REPORT:
1709 # Add an emblem to the icon.
1710 icon = StateReason.LEVEL_ICON[level]
1711 pixbuf = pixbuf.copy ()
1712 try:
1713 theme = Gtk.IconTheme.get_default ()
1714 emblem = theme.load_icon (icon, 22, 0)
1715 emblem.composite (pixbuf,
1716 pixbuf.get_width () / 2,
1717 pixbuf.get_height () / 2,
1718 emblem.get_width () / 2,
1719 emblem.get_height () / 2,
1720 pixbuf.get_width () / 2,
1721 pixbuf.get_height () / 2,
1722 0.5, 0.5,
1723 GdkPixbuf.InterpType.BILINEAR, 255)
1724 except GObject.GError:
1725 debugprint ("No %s icon available" % icon)
1726
1727 return pixbuf
1728
1729 def get_icon_pixbuf (self, have_jobs=None):
1730 if not self.applet:
1731 return
1732
1733 if have_jobs is None:
1734 have_jobs = len (self.jobs.keys ()) > 0
1735
1736 if have_jobs:
1737 pixbuf = self.icon_jobs
1738 for jobid, jobdata in self.jobs.items ():
1739 jstate = jobdata.get ('job-state', cups.IPP_JOB_PENDING)
1740 if jstate == cups.IPP_JOB_PROCESSING:
1741 pixbuf = self.icon_jobs_processing
1742 break
1743 else:
1744 pixbuf = self.icon_no_jobs
1745
1746 try:
1747 pixbuf = self.add_state_reason_emblem (pixbuf)
1748 except:
1749 nonfatalException ()
1750
1751 return pixbuf
1752
1753 def set_statusicon_tooltip (self, tooltip=None):
1754 if not self.applet:
1755 return
1756
1757 if tooltip is None:
1758 num_jobs = len (self.jobs)
1759 if num_jobs == 0:
1760 tooltip = _("No documents queued")
1761 elif num_jobs == 1:
1762 tooltip = _("1 document queued")
1763 else:
1764 tooltip = _("%d documents queued") % num_jobs
1765
1766 self.statusicon.set_tooltip_markup (tooltip)
1767
1768 def update_status (self, have_jobs=None):
1769 # Found out which printer state reasons apply to our active jobs.
1770 upset_printers = set()
1771 for printer, reasons in self.printer_state_reasons.items ():
1772 if len (reasons) > 0:
1773 upset_printers.add (printer)
1774 debugprint ("Upset printers: %s" % upset_printers)
1775
1776 my_upset_printers = set()
1777 if len (upset_printers):
1778 my_upset_printers = set()
1779 for jobid in self.active_jobs:
1780 # 'job-printer-name' is set by job_added/job_event
1781 printer = self.jobs[jobid]['job-printer-name']
1782 if printer in upset_printers:
1783 my_upset_printers.add (printer)
1784 debugprint ("My upset printers: %s" % my_upset_printers)
1785
1786 my_reasons = []
1787 for printer in my_upset_printers:
1788 my_reasons.extend (self.printer_state_reasons[printer])
1789
1790 # Find out which is the most problematic.
1791 self.worst_reason = None
1792 if len (my_reasons) > 0:
1793 worst_reason = my_reasons[0]
1794 for reason in my_reasons:
1795 if reason > worst_reason:
1796 worst_reason = reason
1797 self.worst_reason = worst_reason
1798 debugprint ("Worst reason: %s" % worst_reason)
1799
1800 Gdk.threads_enter ()
1801 self.statusbar.pop (0)
1802 if self.worst_reason is not None:
1803 (title, tooltip) = self.worst_reason.get_description ()
1804 self.statusbar.push (0, tooltip)
1805 else:
1806 tooltip = None
1807 status_message = ""
1808 processing = 0
1809 pending = 0
1810 for jobid in self.active_jobs:
1811 try:
1812 job_state = self.jobs[jobid]['job-state']
1813 except KeyError:
1814 continue
1815 if job_state == cups.IPP_JOB_PROCESSING:
1816 processing = processing + 1
1817 elif job_state == cups.IPP_JOB_PENDING:
1818 pending = pending + 1
1819 if ((processing > 0) or (pending > 0)):
1820 status_message = _("processing / pending: %d / %d") % (processing, pending)
1821 self.statusbar.push(0, status_message)
1822
1823 if self.applet and not self.notify_has_persistence:
1824 pixbuf = self.get_icon_pixbuf (have_jobs=have_jobs)
1825 self.statusicon.set_from_pixbuf (pixbuf)
1826 self.set_statusicon_visibility ()
1827 self.set_statusicon_tooltip (tooltip=tooltip)
1828
1829 Gdk.threads_leave ()
1830
1831 ## Notifications
1832 def notify_printer_state_reason_if_important (self, reason):
1833 level = reason.get_level ()
1834 if level < StateReason.WARNING:
1835 # Not important enough to justify a notification.
1836 return
1837
1838 blacklist = [
1839 # Some printers report 'other-warning' for no apparent
1840 # reason, e.g. Canon iR 3170C, Epson AL-CX11NF.
1841 # See bug #520815.
1842 "other",
1843
1844 # This seems to be some sort of 'magic' state reason that
1845 # is for internal use only.
1846 "com.apple.print.recoverable",
1847
1848 # Human-readable text for this reason has misleading wording,
1849 # suppress it.
1850 "connecting-to-device",
1851
1852 # "cups-remote-..." reasons have no human-readable text yet and
1853 # so get considered as errors, suppress them, too.
1854 "cups-remote-pending",
1855 "cups-remote-pending-held",
1856 "cups-remote-processing",
1857 "cups-remote-stopped",
1858 "cups-remote-canceled",
1859 "cups-remote-aborted",
1860 "cups-remote-completed",
1861
1862 # The cups-waiting-for-job-completed job state reason is normal and should not cause a desktop notification
1863 "cups-waiting-for-job-completed"
1864 ]
1865
1866 if reason.get_reason () in blacklist:
1867 return
1868
1869 self.notify_printer_state_reason (reason)
1870
1871 def notify_printer_state_reason (self, reason):
1872 tuple = reason.get_tuple ()
1873 if tuple in self.state_reason_notifications:
1874 debugprint ("Already sent notification for %s" % repr (reason))
1875 return
1876
1877 level = reason.get_level ()
1878 if (level == StateReason.ERROR or
1879 reason.get_reason () == "connecting-to-device"):
1880 urgency = Notify.Urgency.NORMAL
1881 else:
1882 urgency = Notify.Urgency.LOW
1883
1884 (title, text) = reason.get_description ()
1885 notification = Notify.Notification.new (title, text, 'printer')
1886 reason.user_notified = True
1887 notification.set_urgency (urgency)
1888 if self.notify_has_actions:
1889 notification.set_timeout (Notify.EXPIRES_NEVER)
1890 notification.connect ('closed',
1891 self.on_state_reason_notification_closed)
1892 self.state_reason_notifications[reason.get_tuple ()] = notification
1893 self.set_statusicon_visibility ()
1894 try:
1895 notification.show ()
1896 except GObject.GError:
1897 nonfatalException ()
1898
1899 def on_state_reason_notification_closed (self, notification, reason=None):
1900 debugprint ("Notification %s closed" % repr (notification))
1901 notification.closed = True
1902 self.set_statusicon_visibility ()
1903 return
1904
1905 def notify_completed_job (self, jobid):
1906 job = self.jobs.get (jobid, {})
1907 document = job.get ('job-name', _("Unknown"))
1908 printer_uri = job.get ('job-printer-uri')
1909 if printer_uri is not None:
1910 # Determine if this printer is remote. There's no need to
1911 # show a notification if the printer is connected to this
1912 # machine.
1913
1914 # Find out the device URI. We might already have
1915 # determined this if authentication was required.
1916 device_uri = job.get ('device-uri')
1917
1918 if device_uri is None:
1919 pattrs = ['device-uri']
1920 c = authconn.Connection (self.JobsWindow,
1921 host=self.host,
1922 port=self.port,
1923 encryption=self.encryption)
1924 try:
1925 attrs = c.getPrinterAttributes (uri=printer_uri,
1926 requested_attributes=pattrs)
1927 except cups.IPPError:
1928 return
1929
1930 device_uri = attrs.get ('device-uri')
1931
1932 if device_uri is not None:
1933 (scheme, rest) = urllib.parse.splittype (device_uri)
1934 if scheme not in ['socket', 'ipp', 'http', 'smb']:
1935 return
1936
1937 printer = job.get ('job-printer-name', _("Unknown"))
1938 notification = Notify.Notification.new (_("Document printed"),
1939 _("Document `%s' has been sent "
1940 "to `%s' for printing.") %
1941 (document,
1942 printer),
1943 'printer')
1944 notification.set_urgency (Notify.Urgency.LOW)
1945 notification.connect ('closed',
1946 self.on_completed_job_notification_closed)
1947 notification.jobid = jobid
1948 self.completed_job_notifications[jobid] = notification
1949 self.set_statusicon_visibility ()
1950 try:
1951 notification.show ()
1952 except GObject.GError:
1953 nonfatalException ()
1954
1955 def on_completed_job_notification_closed (self, notification, reason=None):
1956 jobid = notification.jobid
1957 del self.completed_job_notifications[jobid]
1958 self.set_statusicon_visibility ()
1959
1960 ## Monitor signal handlers
1961 def on_refresh (self, mon):
1962 self.store.clear ()
1963 self.jobs = {}
1964 self.active_jobs = set()
1965 self.jobiters = {}
1966 self.printer_uri_index = PrinterURIIndex ()
1967
1968 def job_added (self, mon, jobid, eventname, event, jobdata):
1969 uri = jobdata.get ('job-printer-uri', '')
1970 try:
1971 printer = self.printer_uri_index.lookup (uri)
1972 except KeyError:
1973 printer = uri
1974
1975 if self.specific_dests and printer not in self.specific_dests:
1976 return
1977
1978 jobdata['job-printer-name'] = printer
1979
1980 # We may be showing this job already, perhaps because we are showing
1981 # completed jobs and one was reprinted.
1982 if jobid not in self.jobiters:
1983 self.add_job (jobid, jobdata)
1984 elif mon == self.my_monitor:
1985 # Copy over any missing attributes such as user and title.
1986 for attr, value in jobdata.items ():
1987 if attr not in self.jobs[jobid]:
1988 self.jobs[jobid][attr] = value
1989 debugprint ("Add %s=%s (my job)" % (attr, value))
1990
1991 # If we failed to get required attributes for the job, bail.
1992 if jobid not in self.jobiters:
1993 return
1994
1995 if self.job_is_active (jobdata):
1996 self.active_jobs.add (jobid)
1997 elif jobid in self.active_jobs:
1998 self.active_jobs.remove (jobid)
1999
2000 self.update_status (have_jobs=True)
2001 if self.applet:
2002 if not self.job_is_active (jobdata):
2003 return
2004
2005 for reason in self.printer_state_reasons.get (printer, []):
2006 if not reason.user_notified:
2007 self.notify_printer_state_reason_if_important (reason)
2008
2009 def job_event (self, mon, jobid, eventname, event, jobdata):
2010 uri = jobdata.get ('job-printer-uri', '')
2011 try:
2012 printer = self.printer_uri_index.lookup (uri)
2013 except KeyError:
2014 printer = uri
2015
2016 if self.specific_dests and printer not in self.specific_dests:
2017 return
2018
2019 jobdata['job-printer-name'] = printer
2020
2021 if self.job_is_active (jobdata):
2022 self.active_jobs.add (jobid)
2023 elif jobid in self.active_jobs:
2024 self.active_jobs.remove (jobid)
2025
2026 self.update_job (jobid, jobdata)
2027 self.update_status ()
2028
2029 # Check that the job still exists, as update_status re-enters
2030 # the main loop in order to paint/hide the tray icon. Really
2031 # that should probably be deferred to the idle handler, but
2032 # for the moment just deal with the fact that the job might
2033 # have gone (bug #640904).
2034 if jobid not in self.jobs:
2035 return
2036
2037 jobdata = self.jobs[jobid]
2038
2039 # If the job has finished, let the user know.
2040 if self.applet and (eventname == 'job-completed' or
2041 (eventname == 'job-state-changed' and
2042 event['job-state'] == cups.IPP_JOB_COMPLETED)):
2043 reasons = event['job-state-reasons']
2044 if type (reasons) != list:
2045 reasons = [reasons]
2046
2047 canceled = False
2048 for reason in reasons:
2049 if reason.startswith ("job-canceled"):
2050 canceled = True
2051 break
2052
2053 if not canceled:
2054 self.notify_completed_job (jobid)
2055
2056 # Look out for stopped jobs.
2057 if (self.applet and
2058 (eventname == 'job-stopped' or
2059 (eventname == 'job-state-changed' and
2060 event['job-state'] in [cups.IPP_JOB_STOPPED,
2061 cups.IPP_JOB_PENDING])) and
2062 not jobid in self.stopped_job_prompts):
2063 # Why has the job stopped? It might be due to a job error
2064 # of some sort, or it might be that the backend requires
2065 # authentication. If the latter, the job will be held not
2066 # stopped, and the job-hold-until attribute will be
2067 # 'auth-info-required'. This was already checked for in
2068 # update_job.
2069 may_be_problem = True
2070 jstate = jobdata['job-state']
2071 if (jstate == cups.IPP_JOB_PROCESSING or
2072 (jstate == cups.IPP_JOB_HELD and
2073 jobdata['job-hold-until'] == 'auth-info-required')):
2074 # update_job already dealt with this.
2075 may_be_problem = False
2076 else:
2077 # Other than that, unfortunately the only
2078 # clue we get is the notify-text, which is not
2079 # translated into our native language. We'd better
2080 # try parsing it. In CUPS-1.3.6 the possible strings
2081 # are:
2082 #
2083 # "Job stopped due to filter errors; please consult
2084 # the error_log file for details."
2085 #
2086 # "Job stopped due to backend errors; please consult
2087 # the error_log file for details."
2088 #
2089 # "Job held due to backend errors; please consult the
2090 # error_log file for details."
2091 #
2092 # "Authentication is required for job %d."
2093 # [This case is handled in the update_job method.]
2094 #
2095 # "Job stopped due to printer being paused"
2096 # [This should be ignored, as the job was doing just
2097 # fine until the printer was stopped for other reasons.]
2098 notify_text = event['notify-text']
2099 document = jobdata['job-name']
2100 if notify_text.find ("backend errors") != -1:
2101 message = (_("There was a problem sending document `%s' "
2102 "(job %d) to the printer.") %
2103 (document, jobid))
2104 elif notify_text.find ("filter errors") != -1:
2105 message = _("There was a problem processing document `%s' "
2106 "(job %d).") % (document, jobid)
2107 elif (notify_text.find ("being paused") != -1 or
2108 jstate != cups.IPP_JOB_STOPPED):
2109 may_be_problem = False
2110 else:
2111 # Give up and use the provided message untranslated.
2112 message = (_("There was a problem printing document `%s' "
2113 "(job %d): `%s'.") %
2114 (document, jobid, notify_text))
2115
2116 if may_be_problem:
2117 debugprint ("Problem detected")
2118 self.toggle_window_display (None, force_show=True)
2119 dialog = Gtk.Dialog (title=_("Print Error"),
2120 transient_for=self.JobsWindow)
2121 dialog.add_buttons (_("_Diagnose"), Gtk.ResponseType.NO,
2122 Gtk.STOCK_OK, Gtk.ResponseType.OK)
2123 dialog.set_default_response (Gtk.ResponseType.OK)
2124 dialog.set_border_width (6)
2125 dialog.set_resizable (False)
2126 dialog.set_icon_name (ICON)
2127 hbox = Gtk.HBox.new (False, 12)
2128 hbox.set_border_width (6)
2129 image = Gtk.Image ()
2130 image.set_from_stock (Gtk.STOCK_DIALOG_ERROR,
2131 Gtk.IconSize.DIALOG)
2132 hbox.pack_start (image, False, False, 0)
2133 vbox = Gtk.VBox.new (False, 12)
2134
2135 markup = ('<span weight="bold" size="larger">' +
2136 _("Print Error") + '</span>\n\n' +
2137 saxutils.escape (message))
2138 try:
2139 if event['printer-state'] == cups.IPP_PRINTER_STOPPED:
2140 name = event['printer-name']
2141 markup += ' '
2142 markup += (_("The printer called `%s' has "
2143 "been disabled.") % name)
2144 except KeyError:
2145 pass
2146
2147 label = Gtk.Label(label=markup)
2148 label.set_use_markup (True)
2149 label.set_line_wrap (True)
2150 label.set_alignment (0, 0)
2151 vbox.pack_start (label, False, False, 0)
2152 hbox.pack_start (vbox, False, False, 0)
2153 dialog.vbox.pack_start (hbox, False, False, 0)
2154 dialog.connect ('response',
2155 self.print_error_dialog_response, jobid)
2156 self.stopped_job_prompts.add (jobid)
2157 dialog.show_all ()
2158
2159 def job_removed (self, mon, jobid, eventname, event):
2160 # If the job has finished, let the user know.
2161 if self.applet and (eventname == 'job-completed' or
2162 (eventname == 'job-state-changed' and
2163 event['job-state'] == cups.IPP_JOB_COMPLETED)):
2164 reasons = event['job-state-reasons']
2165 debugprint (reasons)
2166 if type (reasons) != list:
2167 reasons = [reasons]
2168
2169 canceled = False
2170 for reason in reasons:
2171 if reason.startswith ("job-canceled"):
2172 canceled = True
2173 break
2174
2175 if not canceled:
2176 self.notify_completed_job (jobid)
2177
2178 if jobid in self.jobiters:
2179 self.store.remove (self.jobiters[jobid])
2180 del self.jobiters[jobid]
2181 del self.jobs[jobid]
2182
2183 if jobid in self.active_jobs:
2184 self.active_jobs.remove (jobid)
2185
2186 if jobid in self.jobs_attrs:
2187 del self.jobs_attrs[jobid]
2188
2189 self.update_status ()
2190
2191 def state_reason_added (self, mon, reason):
2192 (title, text) = reason.get_description ()
2193 printer = reason.get_printer ()
2194
2195 try:
2196 l = self.printer_state_reasons[printer]
2197 except KeyError:
2198 l = []
2199 self.printer_state_reasons[printer] = l
2200
2201 reason.user_notified = False
2202 l.append (reason)
2203 self.update_status ()
2204 self.treeview.queue_draw ()
2205
2206 if not self.applet:
2207 return
2208
2209 # Find out if the user has jobs queued for that printer.
2210 for job, data in self.jobs.items ():
2211 if not self.job_is_active (data):
2212 continue
2213 if data['job-printer-name'] == printer:
2214 # Yes! Notify them of the state reason, if necessary.
2215 self.notify_printer_state_reason_if_important (reason)
2216 break
2217
2218 def state_reason_removed (self, mon, reason):
2219 printer = reason.get_printer ()
2220 try:
2221 reasons = self.printer_state_reasons[printer]
2222 except KeyError:
2223 debugprint ("Printer not found")
2224 return
2225
2226 try:
2227 i = reasons.index (reason)
2228 except IndexError:
2229 debugprint ("Reason not found")
2230 return
2231
2232 del reasons[i]
2233
2234 self.update_status ()
2235 self.treeview.queue_draw ()
2236
2237 if not self.applet:
2238 return
2239
2240 tuple = reason.get_tuple ()
2241 try:
2242 notification = self.state_reason_notifications[tuple]
2243 if getattr (notification, 'closed', None) != True:
2244 try:
2245 notification.close ()
2246 except GLib.GError:
2247 # Can fail if the notification wasn't even shown
2248 # yet (as in bug #545733).
2249 pass
2250
2251 del self.state_reason_notifications[tuple]
2252 self.set_statusicon_visibility ()
2253 except KeyError:
2254 pass
2255
2256 def still_connecting (self, mon, reason):
2257 if not self.applet:
2258 return
2259
2260 self.notify_printer_state_reason (reason)
2261
2262 def now_connected (self, mon, printer):
2263 if not self.applet:
2264 return
2265
2266 # Find the connecting-to-device state reason.
2267 try:
2268 reasons = self.printer_state_reasons[printer]
2269 reason = None
2270 for r in reasons:
2271 if r.get_reason () == "connecting-to-device":
2272 reason = r
2273 break
2274 except KeyError:
2275 debugprint ("Couldn't find state reason (no reasons)!")
2276
2277 if reason is not None:
2278 tuple = reason.get_tuple ()
2279 else:
2280 debugprint ("Couldn't find state reason in list!")
2281 tuple = None
2282 for (level,
2283 p,
2284 r) in self.state_reason_notifications.keys ():
2285 if p == printer and r == "connecting-to-device":
2286 debugprint ("Found from notifications list")
2287 tuple = (level, p, r)
2288 break
2289
2290 if tuple is None:
2291 debugprint ("Unexpected now_connected signal "
2292 "(reason not in notifications list)")
2293 return
2294
2295 try:
2296 notification = self.state_reason_notifications[tuple]
2297 except KeyError:
2298 debugprint ("Unexpected now_connected signal")
2299 return
2300
2301 if getattr (notification, 'closed', None) != True:
2302 try:
2303 notification.close ()
2304 except GLib.GError:
2305 # Can fail if the notification wasn't even shown
2306 pass
2307 notification.closed = True
2308
2309 def printer_added (self, mon, printer):
2310 self.printer_uri_index.add_printer (printer)
2311
2312 def printer_event (self, mon, printer, eventname, event):
2313 self.printer_uri_index.update_from_attrs (printer, event)
2314
2315 def printer_removed (self, mon, printer):
2316 self.printer_uri_index.remove_printer (printer)
2317
2318 ### Cell data functions
2319 def _set_job_job_number_text (self, column, cell, model, iter, *data):
2320 cell.set_property("text", str (model.get_value (iter, 0)))
2321
2322 def _set_job_user_text (self, column, cell, model, iter, *data):
2323 jobid = model.get_value (iter, 0)
2324 try:
2325 job = self.jobs[jobid]
2326 except KeyError:
2327 return
2328
2329 cell.set_property("text", job.get ('job-originating-user-name',
2330 _("Unknown")))
2331
2332 def _set_job_document_text (self, column, cell, model, iter, *data):
2333 jobid = model.get_value (iter, 0)
2334 try:
2335 job = self.jobs[jobid]
2336 except KeyError:
2337 return
2338
2339 cell.set_property("text", job.get('job-name', _("Unknown")))
2340
2341 def _set_job_printer_text (self, column, cell, model, iter, *data):
2342 jobid = model.get_value (iter, 0)
2343 try:
2344 reasons = self.jobs[jobid].get('job-state-reasons')
2345 except KeyError:
2346 return
2347
2348 if reasons == 'printer-stopped':
2349 reason = ' - ' + _("disabled")
2350 else:
2351 reason = ''
2352 cell.set_property("text", self.jobs[jobid]['job-printer-name']+reason)
2353
2354 def _set_job_size_text (self, column, cell, model, iter, *data):
2355 jobid = model.get_value (iter, 0)
2356 try:
2357 job = self.jobs[jobid]
2358 except KeyError:
2359 return
2360
2361 size = _("Unknown")
2362 if 'job-k-octets' in job:
2363 size = str (job['job-k-octets']) + 'k'
2364 cell.set_property("text", size)
2365
2366 def _find_job_state_text (self, job):
2367 try:
2368 data = self.jobs[job]
2369 except KeyError:
2370 return
2371
2372 jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
2373 s = int (jstate)
2374 job_requires_auth = (s == cups.IPP_JOB_HELD and
2375 data.get ('job-hold-until', 'none') ==
2376 'auth-info-required')
2377 state = None
2378 if job_requires_auth:
2379 state = _("Held for authentication")
2380 elif s == cups.IPP_JOB_HELD:
2381 state = _("Held")
2382 until = data.get ('job-hold-until')
2383 if until is not None:
2384 try:
2385 colon1 = until.find (':')
2386 if colon1 != -1:
2387 now = time.gmtime ()
2388 hh = int (until[:colon1])
2389 colon2 = until[colon1 + 1:].find (':')
2390 if colon2 != -1:
2391 colon2 += colon1 + 1
2392 mm = int (until[colon1 + 1:colon2])
2393 ss = int (until[colon2 + 1:])
2394 else:
2395 mm = int (until[colon1 + 1:])
2396 ss = 0
2397
2398 day = now.tm_mday
2399 if (hh < now.tm_hour or
2400 (hh == now.tm_hour and
2401 (mm < now.tm_min or
2402 (mm == now.tm_min and ss < now.tm_sec)))):
2403 day += 1
2404
2405 hold = (now.tm_year, now.tm_mon, day,
2406 hh, mm, ss, 0, 0, -1)
2407 old_tz = os.environ.get("TZ")
2408 os.environ["TZ"] = "UTC"
2409 simpletime = time.mktime (hold)
2410
2411 if old_tz is None:
2412 del os.environ["TZ"]
2413 else:
2414 os.environ["TZ"] = old_tz
2415
2416 local = time.localtime (simpletime)
2417 state = (_("Held until %s") %
2418 time.strftime ("%X", local))
2419 except ValueError:
2420 pass
2421 if until == "day-time":
2422 state = _("Held until day-time")
2423 elif until == "evening":
2424 state = _("Held until evening")
2425 elif until == "night":
2426 state = _("Held until night-time")
2427 elif until == "second-shift":
2428 state = _("Held until second shift")
2429 elif until == "third-shift":
2430 state = _("Held until third shift")
2431 elif until == "weekend":
2432 state = _("Held until weekend")
2433 else:
2434 try:
2435 state = { cups.IPP_JOB_PENDING: _("Pending"),
2436 cups.IPP_JOB_PROCESSING: _("Processing"),
2437 cups.IPP_JOB_STOPPED: _("Stopped"),
2438 cups.IPP_JOB_CANCELED: _("Canceled"),
2439 cups.IPP_JOB_ABORTED: _("Aborted"),
2440 cups.IPP_JOB_COMPLETED: _("Completed") }[s]
2441 except KeyError:
2442 pass
2443
2444 if state is None:
2445 state = _("Unknown")
2446
2447 return state
2448
2449 def _set_job_status_icon (self, column, cell, model, iter, *data):
2450 jobid = model.get_value (iter, 0)
2451 try:
2452 data = self.jobs[jobid]
2453 except KeyError:
2454 return
2455
2456 jstate = data.get ('job-state', cups.IPP_JOB_PROCESSING)
2457 s = int (jstate)
2458 if s == cups.IPP_JOB_PROCESSING:
2459 icon = self.icon_jobs_processing
2460 else:
2461 icon = self.icon_jobs
2462
2463 if s == cups.IPP_JOB_HELD:
2464 try:
2465 theme = Gtk.IconTheme.get_default ()
2466 emblem = theme.load_icon (Gtk.STOCK_MEDIA_PAUSE, 22 / 2, 0)
2467 copy = icon.copy ()
2468 emblem.composite (copy, 0, 0,
2469 copy.get_width (),
2470 copy.get_height (),
2471 copy.get_width () / 2 - 1,
2472 copy.get_height () / 2 - 1,
2473 1.0, 1.0,
2474 GdkPixbuf.InterpType.BILINEAR, 255)
2475 icon = copy
2476 except GObject.GError:
2477 debugprint ("No %s icon available" % Gtk.STOCK_MEDIA_PAUSE)
2478 else:
2479 # Check state reasons.
2480 printer = data['job-printer-name']
2481 icon = self.add_state_reason_emblem (icon, printer=printer)
2482
2483 cell.set_property ("pixbuf", icon)
2484
2485 def _set_job_status_text (self, column, cell, model, iter, *data):
2486 jobid = model.get_value (iter, 0)
2487 try:
2488 data = self.jobs[jobid]
2489 except KeyError:
2490 return
2491
2492 try:
2493 text = data['_status_text']
2494 except KeyError:
2495 text = self._find_job_state_text (jobid)
2496 data['_status_text'] = text
2497
2498 printer = data['job-printer-name']
2499 reasons = self.printer_state_reasons.get (printer, [])
2500 if len (reasons) > 0:
2501 worst_reason = reasons[0]
2502 for reason in reasons[1:]:
2503 if reason > worst_reason:
2504 worst_reason = reason
2505 (title, unused) = worst_reason.get_description ()
2506 text += " - " + title
2507
2508 cell.set_property ("text", text)