-
Notifications
You must be signed in to change notification settings - Fork 89
/
system-config-printer.py
executable file
·2281 lines (1971 loc) · 86.8 KB
/
system-config-printer.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
#!/usr/bin/python3
## system-config-printer
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Red Hat, Inc.
## Authors:
## Tim Waugh <twaugh@redhat.com>
## Florian Festi <ffesti@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 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.
# config is generated from config.py.in by configure
import config
import sys, os, time, re
import _thread
import dbus
import gi
try:
gi.require_version('Polkit', '1.0')
from gi.repository import Polkit
except:
Polkit = False
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf
try:
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
Gtk.init (sys.argv)
except RuntimeError as e:
print ("system-config-printer:", e)
print ("This is a graphical application and requires DISPLAY to be set.")
sys.exit (1)
try:
# Optional dependency, requires libhandy >= 1.5
gi.require_version('Handy', '1')
from gi.repository import Handy
Handy.init()
# Support GNOME 42 dark mode
Handy.StyleManager.get_default().set_color_scheme(Handy.ColorScheme.PREFER_LIGHT)
except:
pass
def show_help():
print ("\nThis is system-config-printer, " \
"a CUPS server configuration program.\n\n"
"Options:\n\n"
" --debug Enable debugging output.\n"
" --show-jobs <printer> Show the print queue for <printer>\n"
" --embedded Enable to start in Embedded mode.\n "
" --help Show this message.\n")
if len(sys.argv)>1 and sys.argv[1] == '--help':
show_help ()
sys.exit (0)
import cups
cups.require ("1.9.46")
cups.ppdSetConformance (cups.PPD_CONFORM_RELAXED)
import locale
try:
locale.setlocale (locale.LC_ALL, "")
except locale.Error:
os.environ['LC_ALL'] = 'C'
locale.setlocale (locale.LC_ALL, "")
import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir)
import cupshelpers
from gi.repository import GObject
from gi.repository import GLib
from gui import GtkGUI
from debug import *
import urllib.request, urllib.parse, urllib.error
import troubleshoot
import installpackage
import jobviewer
import authconn
import monitor
import errordialogs
from errordialogs import *
import userdefault
from serversettings import ServerSettings
from ToolbarSearchEntry import *
from SearchCriterion import *
import statereason
import newprinter
from newprinter import busy, ready
import printerproperties
import ppdippstr
ppdippstr.init ()
pkgdata = config.pkgdatadir
iconpath = os.path.join (pkgdata, 'icons/')
sys.path.append (pkgdata)
PlugWindow = None
PlugWindowId = None
#set program name
GLib.set_prgname("system-config-printer")
def CUPS_server_hostname ():
host = cups.getServer ()
if host[0] == '/':
return 'localhost'
return host
class ServiceStart:
def _get_iface (self, iface):
bus = dbus.SystemBus ()
obj = bus.get_object (self.NAME, self.PATH)
proxy = dbus.Interface (obj, iface)
return proxy
def can_start (self):
try:
proxy = self._get_iface (dbus.INTROSPECTABLE_IFACE)
introspect = proxy.Introspect()
except:
return False
return True
def start(self, reply_handler, error_handler):
proxy = self._get_iface(self.IFACE)
self._start(proxy, reply_handler, error_handler)
class SysVServiceStart(ServiceStart):
NAME="org.fedoraproject.Config.Services"
PATH="/org/fedoraproject/Config/Services/ServiceHerders/SysVServiceHerder/Services/cups"
IFACE="org.fedoraproject.Config.Services.SysVService"
def _start(self, proxy, reply_handler, error_handler):
proxy.start(reply_handler=reply_handler,
error_handler=error_handler)
class SystemDServiceStart(ServiceStart):
NAME="org.freedesktop.systemd1"
PATH="/org/freedesktop/systemd1"
IFACE="org.freedesktop.systemd1.Manager"
CUPS_SERVICE="org.cups.cupsd.service"
def _start(self, proxy, reply_handler, error_handler):
proxy.StartUnit(self.CUPS_SERVICE, 'fail',
reply_handler=reply_handler,
error_handler=error_handler)
class GUI(GtkGUI):
printer_states = { cups.IPP_PRINTER_IDLE: _("Idle"),
cups.IPP_PRINTER_PROCESSING: _("Processing"),
cups.IPP_PRINTER_BUSY: _("Busy"),
cups.IPP_PRINTER_STOPPED: _("Stopped") }
DESTS_PAGE_DESTS=0
DESTS_PAGE_NO_PRINTERS=1
DESTS_PAGE_NO_SERVICE=2
def __init__(self):
super (GtkGUI, self).__init__ ()
try:
self.language = locale.getlocale(locale.LC_MESSAGES)
self.encoding = locale.getlocale(locale.LC_CTYPE)
except:
nonfatalException()
os.environ['LC_ALL'] = 'C'
locale.setlocale (locale.LC_ALL, "")
self.language = locale.getlocale(locale.LC_MESSAGES)
self.encoding = locale.getlocale(locale.LC_CTYPE)
self.printers = {}
self.connect_server = cups.getServer()
self.connect_encrypt = cups.getEncryption ()
self.connect_user = cups.getUser()
self.monitor = None
self.populateList_timer = None
self.servers = set((self.connect_server,))
self.server_is_publishing = None # not known
self.changed = set() # of options
# WIDGETS
# =======
self.updating_widgets = False
self.getWidgets({"PrintersWindow":
["PrintersWindow",
"hboxMenuBar",
"view_area_vbox",
"view_area_scrolledwindow",
"dests_notebook",
"dests_iconview",
"btnAddFirstPrinter",
"btnStartService",
"btnConnectNoService",
"statusbarMain",
"toolbar",
"server_menubar_item",
"printer_menubar_item",
"view_discovered_printers"],
"AboutDialog":
["AboutDialog"],
"ConnectDialog":
["ConnectDialog",
"chkEncrypted",
"cmbServername",
"btnConnect"],
"ConnectingDialog":
["ConnectingDialog",
"lblConnecting",
"pbarConnecting"],
"NewPrinterName":
["NewPrinterName",
"entDuplicateName",
"btnDuplicateOk"],
"InstallDialog":
["InstallDialog",
"lblInstall"]},
domain=config.PACKAGE)
if PlugWindowId:
self.PrintersWindow.hide()
# the "vbox4" widget
vbox = self.PrintersWindow.get_children()[0]
PlugWindow = Gtk.Plug.new(PlugWindowId)
Gtk.Container.remove(self.PrintersWindow, vbox)
PlugWindow.add(vbox)
self.PrintersWindow.set_transient_for(PlugWindow)
PlugWindow.show_all()
self.PrintersWindow = PlugWindow
# Since some dialogs are reused we can't let the delete-event's
# default handler destroy them
self.ConnectingDialog.connect ("delete-event",
self.on_connectingdialog_delete)
Gtk.Window.set_default_icon_name ('printer')
edit_action = 'org.opensuse.cupspkhelper.mechanism.all-edit'
self.edit_permission = None
if Polkit:
try:
self.edit_permission = Polkit.Permission.new_sync (edit_action,
None, None)
except GLib.GError:
pass # Maybe cups-pk-helper isn't installed.
self.unlock_button = Gtk.LockButton ()
if self.edit_permission is not None:
self.edit_permission.connect ("notify::allowed",
self.polkit_permission_changed)
self.unlock_button.connect ("notify::permission",
self.polkit_permission_changed)
self.hboxMenuBar.pack_start (self.unlock_button, False, False, 12)
# Printer Actions
printer_manager_action_group = \
Gtk.ActionGroup (name="PrinterManagerActionGroup")
printer_manager_action_group.add_actions ([
("connect-to-server", Gtk.STOCK_CONNECT, _("_Connect..."),
None, _("Choose a different CUPS server"),
self.on_connect_activate),
("server-settings", Gtk.STOCK_PREFERENCES, _("_Settings..."),
None, _("Adjust server settings"),
self.on_server_settings_activate),
("new-printer", Gtk.STOCK_PRINT, _("_Printer"),
None, None, self.on_new_printer_activate),
("new-class", Gtk.STOCK_DND_MULTIPLE, _("_Class"),
None, None, self.on_new_class_activate),
("quit", Gtk.STOCK_QUIT, None, None, None,
self.on_quit_activate)])
printer_manager_action_group.add_actions ([
("rename-printer", None, _("_Rename"),
None, None, self.on_rename_activate),
("duplicate-printer", Gtk.STOCK_COPY, _("_Duplicate"),
"<Ctrl>d", None, self.on_duplicate_activate),
("delete-printer", Gtk.STOCK_DELETE, None,
None, None, self.on_delete_activate),
("set-default-printer", Gtk.STOCK_HOME, _("Set As De_fault"),
None, None, self.on_set_as_default_activate),
("edit-printer", Gtk.STOCK_PROPERTIES, None,
None, None, self.on_edit_activate),
("create-class", Gtk.STOCK_DND_MULTIPLE, _("_Create class"),
None, None, self.on_create_class_activate),
("view-print-queue", Gtk.STOCK_FIND, _("View Print _Queue"),
None, None, self.on_view_print_queue_activate),
])
printer_manager_action_group.add_toggle_actions ([
("enable-printer", None, _("E_nabled"),
None, None, self.on_enabled_activate),
("share-printer", None, _("_Shared"),
None, None, self.on_shared_activate),
])
printer_manager_action_group.add_radio_actions ([
("filter-name", None, _("Name")),
("filter-description", None, _("Description")),
("filter-location", None, _("Location")),
("filter-manufacturer", None, _("Manufacturer / Model")),
], 1, self.on_filter_criterion_changed)
for action in printer_manager_action_group.list_actions ():
action.set_sensitive (False)
for action in ["connect-to-server",
"quit",
"view-print-queue",
"filter-name",
"filter-description",
"filter-location",
"filter-manufacturer"]:
act = printer_manager_action_group.get_action (action)
act.set_sensitive (True)
self.ui_manager = Gtk.UIManager ()
self.ui_manager.insert_action_group (printer_manager_action_group, -1)
self.ui_manager.add_ui_from_string (
"""
<ui>
<accelerator action="connect-to-server"/>
<accelerator action="server-settings"/>
<accelerator action="new-printer"/>
<accelerator action="new-class"/>
<accelerator action="quit"/>
<accelerator action="rename-printer"/>
<accelerator action="duplicate-printer"/>
<accelerator action="delete-printer"/>
<accelerator action="set-default-printer"/>
<accelerator action="edit-printer"/>
<accelerator action="create-class"/>
<accelerator action="view-print-queue"/>
<accelerator action="enable-printer"/>
<accelerator action="share-printer"/>
<accelerator action="filter-name"/>
<accelerator action="filter-description"/>
<accelerator action="filter-location"/>
<accelerator action="filter-manufacturer"/>
</ui>
"""
)
self.ui_manager.ensure_update ()
self.PrintersWindow.add_accel_group (self.ui_manager.get_accel_group ())
# Toolbar
# Glade-3 doesn't have support for MenuToolButton, so we do that here.
self.btnNew = Gtk.MenuToolButton ()
self.btnNew.set_label (_("Add"))
self.btnNew.set_icon_name ("list-add")
self.btnNew.set_is_important (True)
newmenu = Gtk.Menu ()
action = self.ui_manager.get_action ("/new-printer")
newprinteritem = action.create_menu_item ()
action = self.ui_manager.get_action ("/new-class")
newclassitem = action.create_menu_item ()
newprinteritem.show ()
newclassitem.show ()
newmenu.attach (newprinteritem, 0, 1, 0, 1)
newmenu.attach (newclassitem, 0, 1, 1, 2)
self.btnNew.set_menu (newmenu)
self.btnNew.connect ('clicked', self.on_new_printer_activate)
self.toolbar.add (self.btnNew)
self.toolbar.add (Gtk.SeparatorToolItem ())
self.refreshbutton = Gtk.ToolButton ()
self.refreshbutton.set_label (_("Refresh"))
self.refreshbutton.set_icon_name ("view-refresh")
self.refreshbutton.connect ('clicked', self.on_btnRefresh_clicked)
self.toolbar.add (self.refreshbutton)
self.toolbar.show_all ()
server_context_menu = Gtk.Menu ()
for action_name in ["connect-to-server",
"server-settings",
None,
"new",
None,
"quit"]:
if action_name == "new":
item = Gtk.MenuItem.new_with_mnemonic(_("_New"))
item.set_sensitive (True)
self.menuItemNew = item
elif not action_name:
item = Gtk.SeparatorMenuItem ()
else:
action = printer_manager_action_group.get_action (action_name)
item = action.create_menu_item ()
item.show ()
server_context_menu.append (item)
self.server_menubar_item.set_submenu (server_context_menu)
new_menu = Gtk.Menu ()
for action_name in ["new-printer",
"new-class"]:
action = printer_manager_action_group.get_action (action_name)
item = action.create_menu_item ()
item.show ()
new_menu.append (item)
self.menuItemNew.set_submenu (new_menu)
self.printer_context_menu = Gtk.Menu ()
for action_name in ["edit-printer",
"duplicate-printer",
"rename-printer",
"delete-printer",
None,
"enable-printer",
"share-printer",
"create-class",
"set-default-printer",
None,
"view-print-queue"]:
if not action_name:
item = Gtk.SeparatorMenuItem ()
else:
action = printer_manager_action_group.get_action (action_name)
item = action.create_menu_item ()
item.show ()
self.printer_context_menu.append (item)
self.printer_menubar_item.set_submenu (self.printer_context_menu)
self.jobviewers = [] # to keep track of jobviewer windows
# New Printer Dialog
self.newPrinterGUI = np = newprinter.NewPrinterGUI()
np.connect ("printer-added", self.on_new_printer_added)
np.connect ("printer-modified", self.on_printer_modified)
np.connect ("dialog-canceled", self.on_new_printer_not_added)
# Set up "About" dialog
self.AboutDialog.set_program_name(config.PACKAGE)
self.AboutDialog.set_version(config.VERSION)
self.AboutDialog.set_icon_name('printer')
try:
self.cups = authconn.Connection(self.PrintersWindow)
except RuntimeError:
self.cups = None
self.status_context_id = self.statusbarMain.get_context_id(
"Connection")
# Setup search
self.setup_toolbar_for_search_entry ()
self.current_filter_text = ""
self.current_filter_mode = "filter-name"
# Search entry drop down menu
menu = Gtk.Menu ()
for action_name in ["filter-name",
"filter-description",
"filter-location",
"filter-manufacturer"]:
action = printer_manager_action_group.get_action (action_name)
item = action.create_menu_item ()
menu.append (item)
menu.show_all ()
self.search_entry.set_drop_down_menu (menu)
if os.path.exists("/usr/lib/systemd"):
self.servicestart = SystemDServiceStart()
else:
self.servicestart = SysVServiceStart()
# Setup icon view
self.mainlist = Gtk.ListStore(GObject.TYPE_PYOBJECT, # Object
GdkPixbuf.Pixbuf, # Pixbuf
str, # Name
str) # Tooltip
self.dests_iconview.set_model(self.mainlist)
self.dests_iconview.set_column_spacing (30)
self.dests_iconview.set_row_spacing (20)
self.dests_iconview.set_pixbuf_column (1)
self.dests_iconview.set_text_column (2)
self.dests_iconview.set_tooltip_column (3)
self.dests_iconview.set_has_tooltip(True)
self.dests_iconview.connect ('key-press-event',
self.dests_iconview_key_press_event)
self.dests_iconview.connect ('item-activated',
self.dests_iconview_item_activated)
self.dests_iconview.connect ('selection-changed',
self.dests_iconview_selection_changed)
self.dests_iconview.connect ('button-press-event',
self.dests_iconview_button_press_event)
self.dests_iconview.connect ('popup-menu',
self.dests_iconview_popup_menu)
self.dests_iconview_selection_changed (self.dests_iconview)
self.dests_iconview.enable_model_drag_source (Gdk.ModifierType.BUTTON1_MASK,
# should use a variable
# instead of 0
[Gtk.TargetEntry.new("queue", 0, 0)],
Gdk.DragAction.COPY)
self.dests_iconview.connect ("drag-data-get",
self.dests_iconview_drag_data_get)
self.btnStartService.connect ('clicked', self.on_start_service_clicked)
self.btnConnectNoService.connect ('clicked', self.on_connect_activate)
self.btnAddFirstPrinter.connect ('clicked',
self.on_new_printer_activate)
# Printer Properties dialog
self.propertiesDlg = printerproperties.PrinterPropertiesDialog ()
self.propertiesDlg.connect ("dialog-closed",
self.on_properties_dialog_closed)
self.connect_signals ()
try:
self.populateList()
except cups.HTTPError as e:
(s,) = e.args
self.cups = None
self.populateList()
show_HTTP_Error(s, self.PrintersWindow)
self.setConnected()
if len (self.printers) > 4:
self.PrintersWindow.set_default_size (720, 345)
elif len (self.printers) > 2:
self.PrintersWindow.set_default_size (500, 345)
elif len (self.printers) > 1:
self.PrintersWindow.set_default_size (500, 180)
self.PrintersWindow.show()
def display_properties_dialog_for (self, queue):
model = self.dests_iconview.get_model ()
iter = model.get_iter_first ()
while iter is not None:
name = model.get_value (iter, 2)
if name == queue:
path = model.get_path (iter)
self.dests_iconview.scroll_to_path (path, True, 0.5, 0.5)
self.dests_iconview.set_cursor (path=path, cell=None,
start_editing=False)
self.dests_iconview.item_activated (path)
break
iter = model.iter_next (iter)
if iter is None:
raise RuntimeError
def setup_toolbar_for_search_entry (self):
separator = Gtk.SeparatorToolItem ()
separator.set_draw (False)
self.toolbar.insert (separator, -1)
self.toolbar.child_set_property (separator, "expand", True)
self.search_entry = ToolbarSearchEntry ()
self.search_entry.connect ('search', self.on_search_entry_search)
tool_item = Gtk.ToolItem ()
tool_item.add (self.search_entry)
self.toolbar.insert (tool_item, -1)
self.toolbar.show_all ()
def on_search_entry_search (self, UNUSED, text):
self.current_filter_text = text
self.populateList ()
def on_filter_criterion_changed (self, UNUSED, selected_action):
self.current_filter_mode = selected_action.get_name ()
self.populateList ()
def dests_iconview_item_activated (self, iconview, path):
model = iconview.get_model ()
iter = model.get_iter (path)
name = model.get_value (iter, 2)
object = model.get_value (iter, 0)
self.desensitise_main_window_widgets ()
try:
self.propertiesDlg.show (name, host=self.connect_server,
encryption=self.connect_encrypt,
parent=self.PrintersWindow)
except cups.IPPError as e:
(e, m) = e.args
self.sensitise_main_window_widgets ()
show_IPP_Error (e, m, self.PrintersWindow)
if e == cups.IPP_SERVICE_UNAVAILABLE:
self.cups = None
self.setConnected ()
self.populateList ()
return
except RuntimeError:
self.sensitise_main_window_widgets ()
# Perhaps cupsGetPPD2 failed for a browsed printer.
# Check that we're still connected.
self.monitor.update ()
return
def on_properties_dialog_closed (self, obj):
self.sensitise_main_window_widgets ()
def dests_iconview_selection_changed (self, iconview):
self.updating_widgets = True
permission = self.unlock_button.get_permission ()
if permission:
can_edit = permission.get_allowed ()
else:
can_edit = True
if not can_edit:
return
paths = iconview.get_selected_items ()
any_disabled = False
any_enabled = False
any_discovered = False
any_shared = False
any_unshared = False
model = iconview.get_model ()
for path in paths:
iter = model.get_iter (path)
object = model.get_value (iter, 0)
name = model.get_value (iter, 2)
if object.discovered:
any_discovered = True
if object.enabled:
any_enabled = True
else:
any_disabled = True
if object.is_shared:
any_shared = True
else:
any_unshared = True
n = len (paths)
self.ui_manager.get_action ("/edit-printer").set_sensitive (n == 1)
self.ui_manager.get_action ("/duplicate-printer").set_sensitive (n == 1)
self.ui_manager.get_action ("/rename-printer").set_sensitive (
n == 1 and not any_discovered)
userdef = userdefault.UserDefaultPrinter ().get ()
if (n != 1 or
(userdef is None and self.default_printer == name)):
set_default_sensitivity = False
else:
set_default_sensitivity = True
self.ui_manager.get_action ("/set-default-printer").set_sensitive (
set_default_sensitivity)
action = self.ui_manager.get_action ("/enable-printer")
action.set_sensitive (n > 0 and not any_discovered)
for widget in action.get_proxies ():
if isinstance (widget, Gtk.CheckMenuItem):
widget.set_inconsistent (n > 1 and any_enabled and any_disabled)
action.set_active (any_discovered or not any_disabled)
action = self.ui_manager.get_action ("/share-printer")
action.set_sensitive (n > 0 and not any_discovered)
for widget in action.get_proxies ():
if isinstance (widget, Gtk.CheckMenuItem):
widget.set_inconsistent (n > 1 and any_shared and any_unshared)
action.set_active (any_discovered or not any_unshared)
self.ui_manager.get_action ("/delete-printer").set_sensitive (
n > 0 and not any_discovered)
self.ui_manager.get_action ("/create-class").set_sensitive (n > 1)
self.updating_widgets = False
def dests_iconview_popup_menu (self, iconview):
self.printer_context_menu.popup_for_device (None, None, None, None,
None, 0, 0)
def dests_iconview_button_press_event (self, iconview, event):
if event.button > 1:
click_path = iconview.get_path_at_pos (int (event.x),
int (event.y))
paths = iconview.get_selected_items ()
if click_path is None:
iconview.unselect_all ()
elif click_path not in paths:
iconview.unselect_all ()
iconview.select_path (click_path)
cells = iconview.get_cells ()
for cell in cells:
if type (cell) == Gtk.CellRendererText:
break
iconview.set_cursor (click_path, cell, False)
self.printer_context_menu.popup_for_device (None, None, None, None,
None, event.button, event.time)
return False
def dests_iconview_key_press_event (self, iconview, event):
modifiers = Gtk.accelerator_get_default_mod_mask ()
if ((event.keyval == Gdk.KEY_BackSpace or
event.keyval == Gdk.KEY_Delete or
event.keyval == Gdk.KEY_KP_Delete) and
((event.get_state() & modifiers) == 0)):
self.ui_manager.get_action ("/delete-printer").activate ()
return True
if ((event.keyval == Gdk.KEY_F2) and
((event.get_state() & modifiers) == 0)):
self.ui_manager.get_action ("/rename-printer").activate ()
return True
return False
def dests_iconview_drag_data_get (self, iconview, context,
selection_data, info, timestamp):
if info == 0: # FIXME: should use an "enum" here
model = iconview.get_model ()
paths = iconview.get_selected_items ()
selected_printer_names = ""
for path in paths:
selected_printer_names += \
model.get_value (model.get_iter (path), 2) + "\n"
if len (selected_printer_names) > 0:
selection_data.set ("queue", 8, selected_printer_names)
else:
nonfatalException ()
def dests_iconview_set_accessible_names (self):
iv_acc = self.dests_iconview.get_accessible ()
for i in range (iv_acc.get_n_accessible_children ()):
acc = iv_acc.ref_accessible_child (i)
acc.set_name (acc.get_text (0, -1))
def on_server_settings_activate (self, menuitem):
try:
self.serverSettings = ServerSettings (host=self.connect_server,
encryption=self.connect_encrypt,
parent=self.PrintersWindow)
self.serverSettings.connect ('problems-clicked',
self.on_problems_button_clicked)
except (cups.IPPError, cups.HTTPError):
# Not authorized.
return
except RuntimeError:
self.monitor.update ()
def setConnected(self):
connected = bool(self.cups)
host = CUPS_server_hostname ()
self.PrintersWindow.set_title(_("Print Settings - %s") % host)
if connected:
status_msg = _("Connected to %s") % host
else:
status_msg = _("Not connected")
self.statusbarMain.push(self.status_context_id, status_msg)
for widget in (self.btnNew,
self.menuItemNew):
widget.set_sensitive(connected)
for action_name in ["/server-settings",
"/new-printer",
"/new-class"]:
action = self.ui_manager.get_action (action_name)
action.set_sensitive (connected)
if connected:
if self.monitor:
self.monitor.cleanup ()
self.monitor = monitor.Monitor (monitor_jobs=False,
host=self.connect_server,
encryption=self.connect_encrypt)
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.connect ('cups-connection-error',
self.cups_connection_error)
self.monitor.connect ('cups-connection-recovered',
self.cups_connection_recovered)
GLib.idle_add (self.monitor.refresh)
self.propertiesDlg.set_monitor (self.monitor)
if connected:
if self.cups._using_polkit ():
self.unlock_button.set_permission (self.edit_permission)
else:
self.unlock_button.set_permission (None)
else:
self.unlock_button.set_permission (None)
def polkit_permission_changed (self, widget, UNUSED):
permission = self.unlock_button.get_permission ()
if permission:
can_edit = permission.get_allowed ()
else:
can_edit = True
self.btnNew.set_sensitive (can_edit)
self.btnAddFirstPrinter.set_sensitive (can_edit)
for action in ["/new-printer",
"/new-class"]:
act = self.ui_manager.get_action (action)
act.set_sensitive (can_edit)
if can_edit:
self.dests_iconview_selection_changed (self.dests_iconview)
else:
for action in ["/rename-printer",
"/duplicate-printer",
"/delete-printer",
"/edit-printer",
"/create-class",
"/enable-printer",
"/share-printer"]:
act = self.ui_manager.get_action (action)
act.set_sensitive (False)
def getServers(self):
self.servers.discard(None)
known_servers = list(self.servers)
known_servers.sort()
return known_servers
def populateList(self, prompt_allowed=True):
# Save selection of printers.
selected_printers = set()
paths = self.dests_iconview.get_selected_items ()
model = self.dests_iconview.get_model ()
for path in paths:
iter = model.get_iter (path)
name = model.get_value (iter, 2)
selected_printers.add (name)
if self.cups:
kill_connection = False
self.cups._set_prompt_allowed (prompt_allowed)
self.cups._begin_operation (_("obtaining queue details"))
try:
# get Printers
self.printers = cupshelpers.getPrinters(self.cups)
# Get default printer.
self.default_printer = self.cups.getDefault ()
except cups.IPPError as e:
(e, m) = e.args
show_IPP_Error(e, m, self.PrintersWindow)
self.printers = {}
self.default_printer = None
if e == cups.IPP_SERVICE_UNAVAILABLE:
kill_connection = True
self.cups._end_operation ()
self.cups._set_prompt_allowed (True)
if kill_connection:
self.cups = None
else:
self.printers = {}
self.default_printer = None
for name, printer in self.printers.items():
self.servers.add(printer.getServer())
userdef = userdefault.UserDefaultPrinter ().get ()
local_printers = []
local_classes = []
remote_printers = []
remote_classes = []
delete_action = self.ui_manager.get_action ("/delete-printer")
delete_action.set_properties (label = None)
printers_set = self.printers
# Filter printers
if len (self.current_filter_text) > 0:
printers_subset = {}
pattern = re.compile (self.current_filter_text, re.I) # ignore case
if self.current_filter_mode == "filter-name":
for name in printers_set.keys ():
if pattern.search (name) is not None:
printers_subset[name] = printers_set[name]
elif self.current_filter_mode == "filter-description":
for name, printer in printers_set.items ():
if pattern.search (printer.info) is not None:
printers_subset[name] = printers_set[name]
elif self.current_filter_mode == "filter-location":
for name, printer in printers_set.items ():
if pattern.search (printer.location) is not None:
printers_subset[name] = printers_set[name]
elif self.current_filter_mode == "filter-manufacturer":
for name, printer in printers_set.items ():
if pattern.search (printer.make_and_model) is not None:
printers_subset[name] = printers_set[name]
else:
nonfatalException ()
printers_set = printers_subset
if not self.view_discovered_printers.get_active ():
printers_subset = {}
for name, printer in printers_set.items ():
if not printer.discovered:
printers_subset[name] = printer
printers_set = printers_subset
for name, printer in list(printers_set.items()):
if printer.remote:
if printer.is_class: remote_classes.append(name)
else: remote_printers.append(name)
else:
if printer.is_class: local_classes.append(name)
else: local_printers.append(name)
local_printers.sort()
local_classes.sort()
remote_printers.sort()
remote_classes.sort()
# remove old printers/classes
self.mainlist.clear ()
# add new
PRINTER_TYPE = { 'discovered-printer':
(_("Network printer (discovered)"),
'i-network-printer'),
'discovered-class':
(_("Network class (discovered)"),
'i-network-printer'),
'local-printer':
(_("Printer"),
'printer'),
'local-fax':
(_("Fax"),
'printer'),
'local-class':
(_("Class"),
'printer'),
'ipp-printer':
(_("Network printer"),
'i-network-printer'),
'smb-printer':
(_("Network print share"),
'i-network-printer'),
'network-printer':
(_("Network printer"),
'i-network-printer'),
}
theme = Gtk.IconTheme.get_default ()
for printers in (local_printers,
local_classes,
remote_printers,
remote_classes):
if not printers: continue
for name in printers:
type = 'local-printer'
object = printers_set[name]
if object.discovered:
if object.is_class:
type = 'discovered-class'
else:
type = 'discovered-printer'
elif object.is_class:
type = 'local-class'
else:
parsed = urllib.parse.urlparse (object.device_uri)
if parsed.scheme in ['ipp', 'ipps']:
if parsed.netloc.startswith("localhost"): # IPP-over-USB
type = 'local-printer'
else: # IPP network printer
type = 'ipp-printer'
elif parsed.scheme == 'smb':
type = 'smb-printer'
elif parsed.scheme == 'hpfax':