-
Notifications
You must be signed in to change notification settings - Fork 89
/
newprinter.py
4538 lines (3992 loc) · 178 KB
/
newprinter.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 <[email protected]>
## Florian Festi <[email protected]>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# config is generated from config.py.in by configure
import config
import authconn
import cupshelpers
from OpenPrintingRequest import OpenPrintingRequest
import errno
import sys, os, tempfile, time, re, http.client
import locale
import string
import subprocess
from timedops import *
import dbus
from gi.repository import Gdk
from gi.repository import Gtk
import functools
import cups
try:
import pysmb
PYSMB_AVAILABLE=True
except:
PYSMB_AVAILABLE=False
import options
from gi.repository import GObject
from gi.repository import GLib
from gui import GtkGUI
from optionwidgets import OptionWidget
from debug import *
import probe_printer
import urllib.request, urllib.parse
from smburi import SMBURI
from errordialogs import *
from PhysicalDevice import PhysicalDevice
import firewallsettings
import asyncconn
import ppdsloader
import dnssdresolve
import installpackage
import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir)
HTTPS_TIMEOUT = 15.0
TEXT_adjust_firewall = _("The firewall may need adjusting in order to "
"detect network printers. Adjust the "
"firewall now?")
def validDeviceURI (uri):
"""Returns True is the provided URI is valid."""
(scheme, rest) = urllib.parse.splittype (uri)
if scheme is None or scheme == '':
return False
return True
# Both the printer properties window and the new printer window
# need to be able to drive 'class members' selections.
def moveClassMembers(treeview_from, treeview_to):
selection = treeview_from.get_selection()
model_from, rows = selection.get_selected_rows()
rows = [Gtk.TreeRowReference.new(model_from, row) for row in rows]
model_to = treeview_to.get_model()
for row in rows:
path = row.get_path()
iter = model_from.get_iter(path)
row_data = model_from.get(iter, 0)
model_to.append(row_data)
model_from.remove(iter)
def getCurrentClassMembers(treeview):
model = treeview.get_model()
iter = model.get_iter_first()
result = []
while iter:
result.append(model.get(iter, 0)[0])
iter = model.iter_next(iter)
result.sort()
return result
def checkNPName(printers, name):
if not name: return False
name = name.lower()
for printer in printers.values():
if not printer.discovered and printer.name.lower()==name:
return False
return True
def ready (win, cursor=None):
try:
gdkwin = win.get_window()
if gdkwin:
gdkwin.set_cursor (cursor)
while Gtk.events_pending ():
Gtk.main_iteration ()
except:
nonfatalException ()
def busy (win):
ready (win, Gdk.Cursor.new(Gdk.CursorType.WATCH))
def on_delete_just_hide (widget, event):
widget.hide ()
return True # stop other handlers
def _singleton (x):
"""If we don't know whether getPPDs() or getPPDs2() was used, this
function can unwrap an item from a list in either case."""
if isinstance (x, list):
return x[0]
return x
def download_gpg_fingerprint(url):
"""Get GPG fingerprint from URL.
Check that the URL is HTTPS with a valid and trusted server
certificate, read it, extract the GPG fingerprint from it, and return
it. Return None if the URL is invalid, not trusted, or the fingerprint
can't be found.
"""
if not url.startswith('https://'):
debugprint('Not a https fingerprint URL: %s, ignoring driver' % url)
return None
content = None
try:
with urllib.request.urlopen(url, timeout=HTTPS_TIMEOUT) as resp:
if resp.status == 200:
content = resp.read().decode('utf-8')
except Exception as e:
debugprint('Cannot retrieve %s: %s' % (url, e))
if content is None:
debugprint('Cannot retrieve %s' % url)
return None
keyid_re = re.compile(r' ((?:(?:[0-9A-F]{4})(?:\s+|$)){10})$', re.M)
m = keyid_re.search(content)
if m:
return m.group(1).strip().replace(' ','')
return None
class NewPrinterGUI(GtkGUI):
__gsignals__ = {
'destroy': (GObject.SignalFlags.RUN_LAST, None, ()),
'printer-added' : (GObject.SignalFlags.RUN_LAST, None, (str,)),
'printer-modified': (GObject.SignalFlags.RUN_LAST, None,
(str, # printer name
bool,)), # PPD modified?
'driver-download-checked': (GObject.SignalFlags.RUN_LAST, None, (str,)),
'dialog-canceled': (GObject.SignalFlags.RUN_LAST, None, ()),
}
# Page numbers used to name the different stages
PAGE_DESCRIBE_PRINTER = 0
PAGE_SELECT_DEVICE = 1
PAGE_SELECT_INSTALL_METHOD = 2
PAGE_CHOOSE_DRIVER_FROM_DB = 3
PAGE_CHOOSE_CLASS_MEMBERS = 4
PAGE_APPLY = 5
PAGE_INSTALLABLE_OPTIONS = 6
PAGE_DOWNLOAD_DRIVER = 7
# Values returned by _handlePrinterInstallationMode() and
# related sub-functions, to know whether to continue the
# execution of the remaining logic from calling functions
INSTALL_RESULT_DONE = True
INSTALL_RESULT_OPS_PENDING = False
new_printer_device_tabs = {
"parallel" : 0, # empty tab
"usb" : 0,
"bluetooth" : 0,
"hal" : 0,
"beh" : 0,
"hp" : 0,
"hpfax" : 0,
"dnssd" : 0,
"socket": 2,
"lpd" : 3,
"scsi" : 4,
"serial" : 5,
"smb" : 6,
"network": 7,
}
def __init__(self):
GObject.GObject.__init__ (self)
self.language = locale.getlocale (locale.LC_MESSAGES)
self.options = {} # keyword -> Option object
self.changed = set()
self.conflicts = set()
self.device = None
self.ppd = None
self.remotecupsqueue = False
self.exactdrivermatch = False
self.installable_options = False
self.ppdsloader = None
self.installed_driver_files = []
self.searchedfordriverpackages = False
self.founddownloadabledrivers = False
self.founddownloadableppd = False
self.downloadable_driver_for_printer = None
self.downloadable_printers = []
self.nextnptab_rerun = False
self.printers = {} # set in init()
self.recommended_model_selected = False
self._searchdialog = None
self._installdialog = None
self.getWidgets({"NewPrinterWindow":
["NewPrinterWindow",
"ntbkNewPrinter",
"btnNPBack",
"btnNPForward",
"btnNPApply",
"spinner",
"entNPName",
"entNPDescription",
"entNPLocation",
"tvNPDevices",
"ntbkNPType",
"lblNPDeviceDescription",
"expNPDeviceURIs",
"tvNPDeviceURIs",
"cmbNPTSerialBaud",
"cmbNPTSerialParity",
"cmbNPTSerialBits",
"cmbNPTSerialFlow",
"btnNPTLpdProbe",
"entNPTLpdHost",
"entNPTLpdQueue",
"entNPTJetDirectHostname",
"entNPTJetDirectPort",
"entSMBURI",
"btnSMBBrowse",
"tblSMBAuth",
"rbtnSMBAuthPrompt",
"rbtnSMBAuthSet",
"entSMBUsername",
"entSMBPassword",
"btnSMBVerify",
"entNPTNetworkHostname",
"btnNetworkFind",
"lblNetworkFindSearching",
"lblNetworkFindNotFound",
"entNPTDevice",
"tvNCMembers",
"tvNCNotMembers",
"btnNCAddMember",
"btnNCDelMember",
"ntbkPPDSource",
"rbtnNPPPD",
"tvNPMakes",
"rbtnNPFoomatic",
"filechooserPPD",
"rbtnNPDownloadableDriverSearch",
"entNPDownloadableDriverSearch",
"btnNPDownloadableDriverSearch",
"btnNPDownloadableDriverSearch_label",
"cmbNPDownloadableDriverFoundPrinters",
"tvNPModels",
"tvNPDrivers",
"rbtnChangePPDasIs",
"rbtnChangePPDKeepSettings",
"scrNPInstallableOptions",
"vbNPInstallOptions",
"tvNPDownloadableDrivers",
"ntbkNPDownloadableDriverProperties",
"lblNPDownloadableDriverSupplier",
"cbNPDownloadableDriverSupplierVendor",
"lblNPDownloadableDriverLicense",
"cbNPDownloadableDriverLicensePatents",
"cbNPDownloadableDriverLicenseFree",
"lblNPDownloadableDriverDescription",
"lblNPDownloadableDriverSupportContacts",
"hsDownloadableDriverPerfText",
"hsDownloadableDriverPerfLineArt",
"hsDownloadableDriverPerfGraphics",
"hsDownloadableDriverPerfPhoto",
"lblDownloadableDriverPerfTextUnknown",
"lblDownloadableDriverPerfLineArtUnknown",
"lblDownloadableDriverPerfGraphicsUnknown",
"lblDownloadableDriverPerfPhotoUnknown",
"frmNPDownloadableDriverLicenseTerms",
"tvNPDownloadableDriverLicense",
"rbtnNPDownloadLicenseYes",
"rbtnNPDownloadLicenseNo"],
"WaitWindow":
["WaitWindow",
"lblWait"],
"SMBBrowseDialog":
["SMBBrowseDialog",
"tvSMBBrowser",
"btnSMBBrowseOk"]},
domain=config.PACKAGE)
# Fill in liststores for combo-box widgets
for (widget,
opts) in [(self.cmbNPTSerialBaud,
[[_("Default"), ""],
["1200", "1200"],
["2400", "2400"],
["4800", "4800"],
["9600", "9600"],
["19200", "19200"],
["38400", "38400"],
["57600", "57600"],
["115200", "115200"]]),
(self.cmbNPTSerialParity,
[[_("Default"), ""],
[_("None"), "none"],
[_("Odd"), "odd"],
[_("Even"), "even"]]),
(self.cmbNPTSerialBits,
[[_("Default"), ""],
["8", "8"],
["7", "7"]]),
(self.cmbNPTSerialFlow,
[[_("Default"), ""],
[_("None"), "none"],
[_("XON/XOFF (Software)"), "soft"],
[_("RTS/CTS (Hardware)"), "hard"],
[_("DTR/DSR (Hardware)"), "hard"]]),
]:
store = Gtk.ListStore (str, str)
for row in opts:
store.append (row)
widget.set_model (store)
cell = Gtk.CellRendererText ()
widget.clear ()
widget.pack_start (cell, True)
widget.add_attribute (cell, 'text', 0)
# Set up some lists
m = Gtk.SelectionMode.MULTIPLE
s = Gtk.SelectionMode.SINGLE
b = Gtk.SelectionMode.BROWSE
for name, model, treeview, selection_mode in (
(_("Members of this class"), Gtk.ListStore(str),
self.tvNCMembers, m),
(_("Others"), Gtk.ListStore(str), self.tvNCNotMembers, m),
(_("Devices"), Gtk.ListStore(str), self.tvNPDevices, s),
(_("Connections"), Gtk.ListStore(str), self.tvNPDeviceURIs, s),
(_("Makes"), Gtk.ListStore(str, str), self.tvNPMakes,s),
(_("Models"), Gtk.ListStore(str, str), self.tvNPModels,s),
(_("Drivers"), Gtk.ListStore(str), self.tvNPDrivers,s),
(_("Downloadable Drivers"), Gtk.ListStore(str),
self.tvNPDownloadableDrivers, b),
):
cell = Gtk.CellRendererText()
column = Gtk.TreeViewColumn(name, cell, text=0)
treeview.set_model(model)
treeview.append_column(column)
treeview.get_selection().set_mode(selection_mode)
# Since some dialogs are reused we can't let the delete-event's
# default handler destroy them
self.SMBBrowseDialog.connect ("delete-event", on_delete_just_hide)
self.WaitWindow_handler = self.WaitWindow.connect ("delete-event",
on_delete_just_hide)
self.ntbkNewPrinter.set_show_tabs(False)
self.ntbkPPDSource.set_show_tabs(False)
self.ntbkNPType.set_show_tabs(False)
self.ntbkNPDownloadableDriverProperties.set_show_tabs(False)
self.spinner_count = 0
# Set up OpenPrinting widgets.
self.opreq = None
self.opreq_handlers = None
combobox = self.cmbNPDownloadableDriverFoundPrinters
cell = Gtk.CellRendererText()
combobox.pack_start (cell, True)
combobox.add_attribute(cell, 'text', 0)
if config.DOWNLOADABLE_ONLYFREE:
for widget in [self.cbNPDownloadableDriverLicenseFree,
self.cbNPDownloadableDriverLicensePatents]:
widget.hide ()
if os.path.exists('/etc/apt/sources.list') or os.path.exists(
'/etc/apt/sources.list.d'):
config.packagesystem = 'deb'
self.packageinstaller = 'apt'
elif os.path.exists('/etc/yum.conf'):
config.packagesystem = 'rpm'
self.packageinstaller = 'yum'
else:
# No known package system, so we only load single PPDs via
# OpenPrinting
config.DOWNLOADABLE_ONLYPPD = True
def protect_toggle (toggle_widget):
active = getattr (toggle_widget, 'protect_active', None)
if active is not None:
toggle_widget.set_active (active)
for widget in [self.cbNPDownloadableDriverSupplierVendor,
self.cbNPDownloadableDriverLicenseFree,
self.cbNPDownloadableDriverLicensePatents]:
widget.connect ('clicked', protect_toggle)
for widget in [self.hsDownloadableDriverPerfText,
self.hsDownloadableDriverPerfLineArt,
self.hsDownloadableDriverPerfGraphics,
self.hsDownloadableDriverPerfPhoto]:
widget.connect ('change-value',
lambda x, y, z: True)
# Device list
slct = self.tvNPDevices.get_selection ()
slct.set_select_function (self.device_select_function, None)
self.tvNPDevices.set_row_separator_func (self.device_row_separator_fn, None)
self.tvNPDevices.connect ("row-activated", self.device_row_activated)
self.tvNPDevices.connect ("row-expanded", self.device_row_expanded)
# Devices expander
self.expNPDeviceURIs.connect ("notify::expanded",
self.on_expNPDeviceURIs_expanded)
self.expNPDeviceURIs.set_expanded(1)
# SMB browser
self.smb_store = Gtk.TreeStore (GObject.TYPE_PYOBJECT)
self.btnSMBBrowse.set_sensitive (True)
if not PYSMB_AVAILABLE:
self.btnSMBBrowse.set_tooltip_text (_("Browsing requires pysmbc "
"module"))
self.tvSMBBrowser.set_model (self.smb_store)
# SMB list columns
col = Gtk.TreeViewColumn (_("Share"))
cell = Gtk.CellRendererText ()
col.pack_start (cell, False)
col.set_cell_data_func (cell, self.smbbrowser_cell_share, None)
self.tvSMBBrowser.append_column (col)
col = Gtk.TreeViewColumn (_("Comment"))
cell = Gtk.CellRendererText ()
col.pack_start (cell, False)
col.set_cell_data_func (cell, self.smbbrowser_cell_comment, None)
self.tvSMBBrowser.append_column (col)
slct = self.tvSMBBrowser.get_selection ()
slct.set_select_function (self.smb_select_function, None)
self.SMBBrowseDialog.set_transient_for(self.NewPrinterWindow)
self.tvNPDrivers.set_has_tooltip(True)
self.tvNPDrivers.connect("query-tooltip", self.on_NPDrivers_query_tooltip)
ppd_filter = Gtk.FileFilter()
ppd_filter.set_name(_("PostScript Printer Description files (*.ppd, *.PPD, *.ppd.gz, *.PPD.gz, *.PPD.GZ)"))
ppd_filter.add_pattern("*.ppd")
ppd_filter.add_pattern("*.PPD")
ppd_filter.add_pattern("*.ppd.gz")
ppd_filter.add_pattern("*.PPD.gz")
ppd_filter.add_pattern("*.PPD.GZ")
self.filechooserPPD.add_filter(ppd_filter)
ppd_filter = Gtk.FileFilter()
ppd_filter.set_name(_("All files (*)"))
ppd_filter.add_pattern("*")
self.filechooserPPD.add_filter(ppd_filter)
self.device_selected = -1
self.dialog_mode = "printer"
self.connect_signals ()
debugprint ("+%s" % self)
def __del__ (self):
debugprint ("-%s" % self)
def do_destroy (self):
debugprint ("DESTROY: %s" % self)
if self.SMBBrowseDialog:
self.SMBBrowseDialog.destroy ()
self.SMBBrowseDialog = None
if self.NewPrinterWindow:
self.NewPrinterWindow.destroy ()
self.NewPrinterWindow = None
if self.WaitWindow:
self.WaitWindow.destroy ()
self.WaitWindow = None
def inc_spinner_task (self):
if self.spinner_count == 0:
self.spinner.show ()
self.spinner.start ()
self.spinner_count += 1
def dec_spinner_task (self):
self.spinner_count -= 1
if self.spinner_count == 0:
self.spinner.hide ()
self.spinner.stop ()
def show_IPP_Error (self, exception, message):
debugprint ("%s: IPP error dialog (%s, %s)" % (self, repr (exception),
message))
return show_IPP_Error (exception, message, parent=self.NewPrinterWindow)
def option_changed(self, option):
if option.is_changed():
self.changed.add(option)
else:
self.changed.discard(option)
if option.conflicts:
self.conflicts.add(option)
else:
self.conflicts.discard(option)
self.setDataButtonState()
return
def setDataButtonState(self):
self.btnNPForward.set_sensitive(not bool(self.conflicts))
def makeNameUnique(self, name):
"""Make a suggested queue name valid and unique."""
name = name.replace (" ", "-")
name = name.replace ("/", "-")
name = name.replace ("#", "-")
if not checkNPName (self.printers, name):
suffix=2
while not checkNPName (self.printers, name + "-" + str (suffix)):
suffix += 1
if suffix == 100:
break
name += "-" + str (suffix)
return name
def destroy (self):
self.emit ('destroy')
def init(self, dialog_mode, device_uri=None, name=None, ppd=None,
devid="", host=None, encryption=None, parent=None, xid=0):
self.parent = parent
if not self.parent:
self.NewPrinterWindow.set_focus_on_map (False)
self.dialog_mode = dialog_mode
self._device_uri = device_uri
self.orig_ppd = ppd
self.devid = devid
self._host = host
self._encryption = encryption
self._name = name
if not host:
self._host = cups.getServer ()
if not encryption:
self._encryption = cups.getEncryption ()
self.options = {} # keyword -> Option object
self.changed = set()
self.conflicts = set()
self.fetchDevices_conn = None
self.ppds = None
self.ppdsmatch_result = None
self.printer_finder = None
if not self._validInitParameters ():
raise RuntimeError
# Get a current list of printers so that we can know whether
# the chosen name is unique.
try:
self.cups = authconn.Connection (parent=self.NewPrinterWindow,
host=self._host,
encryption=self._encryption)
except cups.HTTPError as e:
(s,) = e.args
show_HTTP_Error (s, self.parent)
return False
except RuntimeError:
show_HTTP_Error (-1, self.parent)
return False
except Exception as e:
nonfatalException (e)
return False
try:
self.printers = cupshelpers.getPrinters (self.cups)
except cups.IPPError as e:
(e, m) = e.args
show_IPP_Error (e, m, parent=self.parent)
return False
# Initialise widgets.
self.lblNetworkFindSearching.hide ()
self.entNPTNetworkHostname.set_sensitive (True)
self.entNPTNetworkHostname.set_text ('')
self.btnNetworkFind.set_sensitive (True)
self.lblNetworkFindNotFound.hide ()
# Clear out any previous list of makes.
model = self.tvNPMakes.get_model()
model.clear()
combobox = self.cmbNPDownloadableDriverFoundPrinters
combobox.set_model (Gtk.ListStore (str, str))
self.entNPDownloadableDriverSearch.set_text ('')
label = self.btnNPDownloadableDriverSearch_label
label.set_text (_("Search"))
self.entNPTJetDirectPort.set_text('9100')
self.rbtnSMBAuthPrompt.set_active(True)
if xid != 0 and self.parent:
self.NewPrinterWindow.show_now()
self.NewPrinterWindow.set_transient_for (self.parent)
if self.dialog_mode == "printer":
self._initialisePrinterMode ()
elif self.dialog_mode == "class":
self._initialiseClassMode ()
elif self.dialog_mode == "device":
self._initialiseDeviceMode ()
elif self.dialog_mode == "printer_with_uri":
self._initialisePrinterWithURIMode ()
elif self.dialog_mode == "ppd":
self._initialisePPDMode ()
elif self.dialog_mode == "download_driver":
self._initialiseDownloadDriverMode ()
return True
if xid == 0 and self.parent:
self.NewPrinterWindow.set_transient_for (parent)
self.NewPrinterWindow.show()
self.setNPButtons()
return True
def _validInitParameters (self):
if self.dialog_mode in ['printer_with_uri', 'device', 'ppd']:
return self._device_uri is not None
elif self.dialog_mode == 'download_driver':
return self.devid != ""
return True
def _initialiseClassMode (self):
self._initialiseWidgetsForMode ("class")
self.NewPrinterWindow.set_title (_("New Class"))
self.fillNewClassMembers ()
# Start on name page
self.ntbkNewPrinter.set_current_page (self.PAGE_DESCRIBE_PRINTER)
def _initialisePrinterMode (self):
self._initialiseWidgetsForMode ("printer")
self.NewPrinterWindow.set_title (_("New Printer"))
# Start on devices page (SELECT_DEVICE, not DESCRIBE_PRINTER)
self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_DEVICE)
self.fillDeviceTab ()
self.rbtnNPFoomatic.set_active (True)
self.on_rbtnNPFoomatic_toggled (self.rbtnNPFoomatic)
def _initialiseDeviceMode (self):
self.NewPrinterWindow.set_title (_("Change Device URI"))
self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_DEVICE)
self.fillDeviceTab (self._device_uri)
def _initialisePrinterWithURIMode (self):
self._initialiseWidgetsForMode ("printer")
self._initialiseDeviceFromURI ()
self.NewPrinterWindow.set_title (_("New Printer"))
self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_INSTALL_METHOD)
self.rbtnNPFoomatic.set_active (True)
self.on_rbtnNPFoomatic_toggled (self.rbtnNPFoomatic)
self.rbtnChangePPDKeepSettings.set_active (True)
self._initialiseAutoVariables ()
self.nextNPTab (step = 0)
def _initialiseDownloadDriverMode (self):
self.NewPrinterWindow.set_title (_("Download Printer Driver"))
self.ntbkNewPrinter.set_current_page (self.PAGE_DOWNLOAD_DRIVER)
self.nextnptab_rerun = True
self.nextNPTab (step = 0)
def _initialisePPDMode (self):
self._initialiseDeviceFromURI ()
self.NewPrinterWindow.set_title (_("Change Driver"))
# We'll need to know the Device ID for this device.
if not self.devid:
scheme = str (self._device_uri.split (":", 1)[0])
schemes = [scheme]
if scheme in ["socket", "lpd", "ipp"]:
schemes.extend (["snmp", "dnssd"])
self.fetchDevices_conn = asyncconn.Connection ()
self.fetchDevices_conn._begin_operation (_("fetching device list"))
self.inc_spinner_task ()
cupshelpers.getDevices (self.fetchDevices_conn,
include_schemes=schemes,
reply_handler=self.change_ppd_got_devs,
error_handler=self.change_ppd_got_devs)
self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_INSTALL_METHOD)
self.rbtnNPFoomatic.set_active (True)
self.on_rbtnNPFoomatic_toggled (self.rbtnNPFoomatic)
self.rbtnChangePPDKeepSettings.set_active (True)
self._initialiseAutoVariables ()
def _initialiseWidgetsForMode (self, mode_name):
self.entNPName.set_text (self.makeNameUnique (mode_name))
self.entNPName.grab_focus ()
for widget in [self.entNPLocation,
self.entNPDescription,
self.entSMBURI, self.entSMBUsername,
self.entSMBPassword]:
widget.set_text ('')
def _initialiseDeviceFromURI (self):
device_dict = { }
self.device = cupshelpers.Device (self._device_uri, **device_dict)
def _initialiseAutoVariables (self):
self.auto_make = ""
self.auto_model = ""
self.auto_driver = None
def change_ppd_got_devs (self, conn, result):
self.fetchDevices_conn._end_operation ()
self.fetchDevices_conn.destroy ()
self.fetchDevices_conn = None
self.dec_spinner_task ()
if isinstance (result, Exception):
current_devices = {}
else:
current_devices = result
devid = None
mm = None
if self.devid != "":
devid = self.devid
else:
device = current_devices.get (self.device.uri)
if device:
devid = device.id
mm = device.make_and_model
self.device = device
# We'll also need the list of PPDs
self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_INSTALL_METHOD)
self.nextNPTab(step = 0)
def on_ppdsloader_finished_next (self, ppdsloader):
"""
This method is called when the PPDs loader has finished
loading PPDs in preparation for the next screen the user will
see, having clicked 'Forward'. We are creating a new queue,
and dialog_mode is either "printer" or "printer_with_uri".
"""
self._getPPDs_reply (ppdsloader)
if not self.ppds:
return
if ppdsloader._jockey_has_answered:
self.searchedfordriverpackages = True
debugprint ("Loaded PPDs this time; try nextNPTab again...")
self.nextnptab_rerun = True
if self.ntbkNewPrinter.get_current_page () == self.PAGE_SELECT_INSTALL_METHOD:
self.nextNPTab (step = 0)
else:
self.nextNPTab ()
# get PPDs
def _getPPDs_reply (self, ppdsloader):
exc = ppdsloader.get_error ()
if exc:
ppdsloader.destroy ()
try:
raise exc
except cups.IPPError as e:
(e, m) = e.args
self.show_IPP_Error (e, m)
return
ppds = ppdsloader.get_ppds ()
if ppds:
self.ppds = ppds
self.ppdsmatch_result = ppdsloader.get_ppdsmatch_result ()
if ppdsloader._jockey_has_answered:
self.installed_driver_files = ppdsloader.get_installed_files ()
else:
self.ppds = None
self.ppdsmatch_result = None
ppdsloader.destroy ()
self.ppdsloader = None
# Class members
def fillNewClassMembers(self):
model = self.tvNCMembers.get_model()
model.clear()
model = self.tvNCNotMembers.get_model()
model.clear()
try:
self.printers = cupshelpers.getPrinters (self.cups)
except cups.IPPError:
self.printers = {}
for printer in self.printers.keys():
if not self.printers[printer].type & cups.CUPS_PRINTER_CLASS:
model.append((printer,))
def on_btnNCAddMember_clicked(self, button):
moveClassMembers(self.tvNCNotMembers, self.tvNCMembers)
self.btnNPApply.set_sensitive(
bool(getCurrentClassMembers(self.tvNCMembers)))
button.set_sensitive(False)
def on_btnNCDelMember_clicked(self, button):
moveClassMembers(self.tvNCMembers, self.tvNCNotMembers)
self.btnNPApply.set_sensitive(
bool(getCurrentClassMembers(self.tvNCMembers)))
button.set_sensitive(False)
def on_tvNCMembers_cursor_changed(self, widget):
selection = widget.get_selection()
if selection is None:
return
model_from, rows = selection.get_selected_rows()
self.btnNCDelMember.set_sensitive(rows != [])
def on_tvNCNotMembers_cursor_changed(self, widget):
selection = widget.get_selection()
if selection is None:
return
model_from, rows = selection.get_selected_rows()
self.btnNCAddMember.set_sensitive(rows != [])
# Navigation buttons
def on_NPCancel(self, widget, event=None):
if self.fetchDevices_conn:
self.fetchDevices_conn.destroy ()
self.fetchDevices_conn = None
self.dec_spinner_task ()
if self.ppdsloader:
self.ppdsloader.destroy ()
self.ppdsloader = None
if self.printer_finder:
self.printer_finder.cancel ()
self.printer_finder = None
self.dec_spinner_task ()
self.NewPrinterWindow.hide()
if self.opreq is not None:
for handler in self.opreq_handlers:
self.opreq.disconnect (handler)
self.opreq_handlers = None
self.opreq.cancel ()
self.opreq = None
self.device = None
self.printers = {}
self.emit ('dialog-canceled')
return True
def on_btnNPBack_clicked(self, widget):
self.nextNPTab(-1)
def on_btnNPForward_clicked(self, widget):
self.nextNPTab()
def installdriverpackage (self, driver):
install_info = self._getDriverInstallationInfo (driver)
if not install_info:
return False
name = install_info['name']
repo = install_info['repo']
keyid = install_info['keyid']
fmt = _("Installing driver %s") % name
self._installdialog = Gtk.MessageDialog (parent=self.NewPrinterWindow,
modal=True, destroy_with_parent=True,
type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.CANCEL,
text=fmt)
self._installdialog.format_secondary_text (_("Installing ..."))
# Add a progress bar to the message box
dialogarea = self._installdialog.get_message_area()
pbar = Gtk.ProgressBar()
dialogarea.add(pbar)
pbar.show()
# Save a reference to the progress bar in the dialog, so that
# we can easily reference it from do_installdriverpackage()
self._installdialog._progress_bar = pbar
self._installdialog.connect ("response", self._installdialog_response)
self._installdialog.show_all ()
# Perform the actual installation of the printer driver
ret = self.do_installdriverpackage (name, repo, keyid)
if self._installdialog:
self._installdialog.hide ()
self._installdialog.destroy ()
self._installdialog = None
return ret
def do_installdriverpackage(self, name, repo, keyid):
debugprint('Installing driver: %s; Repo: %s; Key ID: %s' %
(repr (name),
repr (repo),
repr (keyid)))
# Do the installation with a command line helper script
new_environ = os.environ.copy()
new_environ['LC_ALL'] = "C"
if keyid:
args = ["install-printerdriver", name, repo, keyid]
else:
args = ["install-printerdriver", name, repo]
debugprint ("Running command: " + repr(args))
ret = True
try:
self.p = subprocess.Popen (args, env=new_environ, close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE)
# Keep the UI refreshed while we wait for
# the drivers query to complete.
(stdout, stderr) = (self.p.stdout, self.p.stderr)
done = False
pbar = self._installdialog._progress_bar
while self.p.poll() is None:
line = stdout.readline ().strip()
if (len(line) > 0):
if line == "done":
done = True
break
elif line.startswith(b"P"):
try:
percentage = float(line[1:])
if percentage >= 0: