forked from OpenPrinting/system-config-printer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
printerproperties.py
executable file
·1961 lines (1687 loc) · 78.8 KB
/
printerproperties.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 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 os, tempfile
from gi.repository import Gtk
import cups
import locale
import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir)
import cupshelpers, options
from gi.repository import GObject
from gi.repository import GLib
from gui import GtkGUI
from optionwidgets import OptionWidget
from debug import *
import authconn
from errordialogs import *
import gtkinklevel
import ppdcache
import statereason
import monitor
import newprinter
from newprinter import busy, ready
import ppdippstr
pkgdata = config.pkgdatadir
def CUPS_server_hostname ():
host = cups.getServer ()
if host[0] == '/':
return 'localhost'
return host
def on_delete_just_hide (widget, event):
widget.hide ()
return True # stop other handlers
class PrinterPropertiesDialog(GtkGUI):
__gsignals__ = {
'destroy': ( GObject.SignalFlags.RUN_LAST, None, ()),
'dialog-closed': ( GObject.SignalFlags.RUN_LAST, None, ()),
}
printer_states = { cups.IPP_PRINTER_IDLE:
_("Idle"),
cups.IPP_PRINTER_PROCESSING:
_("Processing"),
cups.IPP_PRINTER_BUSY:
_("Busy"),
cups.IPP_PRINTER_STOPPED:
_("Stopped") }
def __init__(self):
GObject.GObject.__init__ (self)
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.parent = None
self.printer = self.ppd = None
self.conflicts = set() # of options
self.changed = set() # of options
self.signal_ids = dict()
# WIDGETS
# =======
self.updating_widgets = False
self.getWidgets({"PrinterPropertiesDialog":
["PrinterPropertiesDialog",
"tvPrinterProperties",
"btnPrinterPropertiesCancel",
"btnPrinterPropertiesOK",
"btnPrinterPropertiesApply",
"btnPrinterPropertiesClose",
"ntbkPrinter",
"entPDescription",
"entPLocation",
"entPMakeModel",
"lblPMakeModel2",
"entPState",
"entPDevice",
"lblPDevice2",
"btnSelectDevice",
"btnChangePPD",
"chkPEnabled",
"chkPAccepting",
"chkPShared",
"lblNotPublished",
"btnPrintTestPage",
"btnSelfTest",
"btnCleanHeads",
"btnConflict",
"cmbPStartBanner",
"cmbPEndBanner",
"cmbPErrorPolicy",
"cmbPOperationPolicy",
"rbtnPAllow",
"rbtnPDeny",
"tvPUsers",
"entPUser",
"btnPAddUser",
"btnPDelUser",
"lblPInstallOptions",
"swPInstallOptions",
"vbPInstallOptions",
"swPOptions",
"lblPOptions",
"vbPOptions",
"vbClassMembers",
"lblClassMembers",
"tvClassMembers",
"tvClassNotMembers",
"btnClassAddMember",
"btnClassDelMember",
"btnRefreshMarkerLevels",
"tvPrinterStateReasons",
"ntbkPrinterStateReasons",
# Job options
"sbJOCopies", "btnJOResetCopies",
"cmbJOOrientationRequested", "btnJOResetOrientationRequested",
"cbJOFitplot", "btnJOResetFitplot",
"cmbJONumberUp", "btnJOResetNumberUp",
"cmbJONumberUpLayout", "btnJOResetNumberUpLayout",
"sbJOBrightness", "btnJOResetBrightness",
"cmbJOFinishings", "btnJOResetFinishings",
"sbJOJobPriority", "btnJOResetJobPriority",
"cmbJOMedia", "btnJOResetMedia",
"cmbJOSides", "btnJOResetSides",
"cmbJOHoldUntil", "btnJOResetHoldUntil",
"cmbJOOutputOrder", "btnJOResetOutputOrder",
"cmbJOPrintQuality", "btnJOResetPrintQuality",
"cmbJOPrinterResolution",
"btnJOResetPrinterResolution",
"cmbJOOutputBin", "btnJOResetOutputBin",
"cbJOMirror", "btnJOResetMirror",
"sbJOScaling", "btnJOResetScaling",
"sbJOSaturation", "btnJOResetSaturation",
"sbJOHue", "btnJOResetHue",
"sbJOGamma", "btnJOResetGamma",
"sbJOCpi", "btnJOResetCpi",
"sbJOLpi", "btnJOResetLpi",
"sbJOPageLeft", "btnJOResetPageLeft",
"sbJOPageRight", "btnJOResetPageRight",
"sbJOPageTop", "btnJOResetPageTop",
"sbJOPageBottom", "btnJOResetPageBottom",
"cbJOPrettyPrint", "btnJOResetPrettyPrint",
"cbJOWrap", "btnJOResetWrap",
"sbJOColumns", "btnJOResetColumns",
"tblJOOther",
"entNewJobOption", "btnNewJobOption",
# Marker levels
"vboxMarkerLevels",
"btnRefreshMarkerLevels"]},
domain=config.PACKAGE)
self.dialog = self.PrinterPropertiesDialog
# Don't let delete-event destroy the dialog.
self.dialog.connect ("delete-event", self.on_delete)
# Printer properties combo boxes
for combobox in [self.cmbPStartBanner,
self.cmbPEndBanner,
self.cmbPErrorPolicy,
self.cmbPOperationPolicy]:
cell = Gtk.CellRendererText ()
combobox.clear ()
combobox.pack_start (cell, True)
combobox.add_attribute (cell, 'text', 0)
btn = self.btnRefreshMarkerLevels
btn.connect ("clicked", self.on_btnRefreshMarkerLevels_clicked)
# Printer state reasons list
column = Gtk.TreeViewColumn (_("Message"))
icon = Gtk.CellRendererPixbuf ()
column.pack_start (icon, False)
text = Gtk.CellRendererText ()
column.pack_start (text, False)
column.set_cell_data_func (icon, self.set_printer_state_reason_icon, None)
column.set_cell_data_func (text, self.set_printer_state_reason_text, None)
column.set_resizable (True)
self.tvPrinterStateReasons.append_column (column)
selection = self.tvPrinterStateReasons.get_selection ()
selection.set_mode (Gtk.SelectionMode.NONE)
store = Gtk.ListStore (int, str)
self.tvPrinterStateReasons.set_model (store)
self.PrinterPropertiesDialog.connect ("delete-event",
on_delete_just_hide)
self.static_tabs = 3
# setup some lists
for name, treeview in (
(_("Members of this class"), self.tvClassMembers),
(_("Others"), self.tvClassNotMembers),
(_("Users"), self.tvPUsers),
):
model = Gtk.ListStore(str)
cell = Gtk.CellRendererText()
column = Gtk.TreeViewColumn(name, cell, text=0)
treeview.set_model(model)
treeview.append_column(column)
treeview.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
# Printer Properties dialog
self.dialog.connect ('response', self.printer_properties_response)
# Printer Properties tree view
col = Gtk.TreeViewColumn ('', Gtk.CellRendererText (), markup=0)
self.tvPrinterProperties.append_column (col)
sel = self.tvPrinterProperties.get_selection ()
sel.connect ('changed', self.on_tvPrinterProperties_selection_changed)
sel.set_mode (Gtk.SelectionMode.SINGLE)
# Job Options widgets.
for (widget,
opts) in [(self.cmbJOOrientationRequested,
[[_("Portrait (no rotation)")],
[_("Landscape (90 degrees)")],
[_("Reverse landscape (270 degrees)")],
[_("Reverse portrait (180 degrees)")]]),
(self.cmbJONumberUp,
[["1"], ["2"], ["4"], ["6"], ["9"], ["16"]]),
(self.cmbJONumberUpLayout,
[[_("Left to right, top to bottom")],
[_("Left to right, bottom to top")],
[_("Right to left, top to bottom")],
[_("Right to left, bottom to top")],
[_("Top to bottom, left to right")],
[_("Top to bottom, right to left")],
[_("Bottom to top, left to right")],
[_("Bottom to top, right to left")]]),
(self.cmbJOFinishings,
# See section 4.2.6 of this document for explanation of finishing types:
# ftp://ftp.pwg.org/pub/pwg/candidates/cs-ippfinishings10-20010205-5100.1.pdf
[[_("None")],
[_("Staple")],
[_("Punch")],
[_("Cover")],
[_("Bind")],
[_("Saddle stitch")],
[_("Edge stitch")],
[_("Fold")],
[_("Trim")],
[_("Bale")],
[_("Booklet maker")],
[_("Job offset")],
[_("Staple (top left)")],
[_("Staple (bottom left)")],
[_("Staple (top right)")],
[_("Staple (bottom right)")],
[_("Edge stitch (left)")],
[_("Edge stitch (top)")],
[_("Edge stitch (right)")],
[_("Edge stitch (bottom)")],
[_("Staple dual (left)")],
[_("Staple dual (top)")],
[_("Staple dual (right)")],
[_("Staple dual (bottom)")],
[_("Bind (left)")],
[_("Bind (top)")],
[_("Bind (right)")],
[_("Bind (bottom)")]]),
(self.cmbJOMedia, []),
(self.cmbJOSides,
[[_("One-sided")],
[_("Two-sided (long edge)")],
[_("Two-sided (short edge)")]]),
(self.cmbJOHoldUntil, []),
(self.cmbJOOutputOrder,
[[_("Normal")],
[_("Reverse")]]),
(self.cmbJOPrintQuality,
[[_("Draft")],
[_("Normal")],
[_("High")]]),
(self.cmbJOOutputBin, []),
]:
model = Gtk.ListStore (str)
for row in opts:
model.append (row=row)
cell = Gtk.CellRendererText ()
widget.pack_start (cell, True)
widget.add_attribute (cell, 'text', 0)
widget.set_model (model)
opts = [ options.OptionAlwaysShown ("copies", int, 1,
self.sbJOCopies,
self.btnJOResetCopies),
options.OptionAlwaysShownSpecial \
("orientation-requested", int, 3,
self.cmbJOOrientationRequested,
self.btnJOResetOrientationRequested,
combobox_map = [3, 4, 5, 6],
special_choice=_("Automatic rotation")),
options.OptionAlwaysShown ("fitplot", bool, False,
self.cbJOFitplot,
self.btnJOResetFitplot),
options.OptionAlwaysShown ("number-up", int, 1,
self.cmbJONumberUp,
self.btnJOResetNumberUp,
combobox_map=[1, 2, 4, 6, 9, 16],
use_supported = True),
options.OptionAlwaysShown ("number-up-layout", str, "lrtb",
self.cmbJONumberUpLayout,
self.btnJOResetNumberUpLayout,
combobox_map = [ "lrtb",
"lrbt",
"rltb",
"rlbt",
"tblr",
"tbrl",
"btlr",
"btrl" ]),
options.OptionAlwaysShown ("brightness", int, 100,
self.sbJOBrightness,
self.btnJOResetBrightness),
options.OptionAlwaysShown ("finishings", int, 3,
self.cmbJOFinishings,
self.btnJOResetFinishings,
combobox_map = [ 3, 4, 5, 6,
7, 8, 9, 10,
11, 12, 13, 14,
20, 21, 22, 23,
24, 25, 26, 27,
28, 29, 30, 31,
50, 51, 52, 53 ],
use_supported = True),
options.OptionAlwaysShown ("job-priority", int, 50,
self.sbJOJobPriority,
self.btnJOResetJobPriority),
options.OptionAlwaysShown ("media", str,
"A4", # This is the default for
# when media-default is
# not supplied by the IPP
# server. Fortunately it
# is a mandatory attribute.
self.cmbJOMedia,
self.btnJOResetMedia,
use_supported = True),
options.OptionAlwaysShown ("sides", str, "one-sided",
self.cmbJOSides,
self.btnJOResetSides,
combobox_map =
[ "one-sided",
"two-sided-long-edge",
"two-sided-short-edge" ],
use_supported = True),
options.OptionAlwaysShown ("job-hold-until", str,
"no-hold",
self.cmbJOHoldUntil,
self.btnJOResetHoldUntil,
use_supported = True),
options.OptionAlwaysShown ("outputorder", str,
"normal",
self.cmbJOOutputOrder,
self.btnJOResetOutputOrder,
combobox_map =
[ "normal",
"reverse" ]),
options.OptionAlwaysShown ("print-quality", int, 3,
self.cmbJOPrintQuality,
self.btnJOResetPrintQuality,
combobox_map = [ 3, 4, 5 ],
use_supported = True),
options.OptionAlwaysShown ("printer-resolution",
options.IPPResolution,
options.IPPResolution((300,300,3)),
self.cmbJOPrinterResolution,
self.btnJOResetPrinterResolution,
use_supported = True),
options.OptionAlwaysShown ("output-bin", str,
"face-up",
self.cmbJOOutputBin,
self.btnJOResetOutputBin,
use_supported = True),
options.OptionAlwaysShown ("mirror", bool, False,
self.cbJOMirror,
self.btnJOResetMirror),
options.OptionAlwaysShown ("scaling", int, 100,
self.sbJOScaling,
self.btnJOResetScaling),
options.OptionAlwaysShown ("saturation", int, 100,
self.sbJOSaturation,
self.btnJOResetSaturation),
options.OptionAlwaysShown ("hue", int, 0,
self.sbJOHue,
self.btnJOResetHue),
options.OptionAlwaysShown ("gamma", int, 1000,
self.sbJOGamma,
self.btnJOResetGamma),
options.OptionAlwaysShown ("cpi", float, 10.0,
self.sbJOCpi, self.btnJOResetCpi),
options.OptionAlwaysShown ("lpi", float, 6.0,
self.sbJOLpi, self.btnJOResetLpi),
options.OptionAlwaysShown ("page-left", int, 0,
self.sbJOPageLeft,
self.btnJOResetPageLeft),
options.OptionAlwaysShown ("page-right", int, 0,
self.sbJOPageRight,
self.btnJOResetPageRight),
options.OptionAlwaysShown ("page-top", int, 0,
self.sbJOPageTop,
self.btnJOResetPageTop),
options.OptionAlwaysShown ("page-bottom", int, 0,
self.sbJOPageBottom,
self.btnJOResetPageBottom),
options.OptionAlwaysShown ("prettyprint", bool, False,
self.cbJOPrettyPrint,
self.btnJOResetPrettyPrint),
options.OptionAlwaysShown ("wrap", bool, False, self.cbJOWrap,
self.btnJOResetWrap),
options.OptionAlwaysShown ("columns", int, 1,
self.sbJOColumns,
self.btnJOResetColumns),
]
self.job_options_widgets = {}
self.job_options_buttons = {}
for option in opts:
self.job_options_widgets[option.widget] = option
self.job_options_buttons[option.button] = option
self._monitor = None
self._ppdcache = None
self.connect_signals ()
debugprint ("+%s" % self)
def __del__ (self):
debugprint ("-%s" % self)
del self._monitor
def _connect (self, collection, obj, name, handler):
c = self.signal_ids.get (collection, [])
c.append ((obj, obj.connect (name, handler)))
self.signal_ids[collection] = c
def _disconnect (self, collection=None):
if collection:
collection = [collection]
else:
collection = list(self.signal_ids.keys ())
for coll in collection:
if coll in self.signal_ids:
for (obj, signal_id) in self.signal_ids[coll]:
obj.disconnect (signal_id)
del self.signal_ids[coll]
def do_destroy (self):
if self.PrinterPropertiesDialog:
self.PrinterPropertiesDialog.destroy ()
self.PrinterPropertiesDialog = None
def destroy (self):
debugprint ("DESTROY: %s" % self)
self._disconnect ()
self.ppd = None
self.ppd_local = None
self.printer = None
self.emit ('destroy')
def set_monitor (self, monitor):
self._monitor = monitor
if not monitor:
return
self._monitor.connect ('printer-event', self.on_printer_event)
self._monitor.connect ('printer-removed', self.on_printer_removed)
self._monitor.connect ('state-reason-added', self.on_state_reason_added)
self._monitor.connect ('state-reason-removed',
self.on_state_reason_removed)
self._monitor.connect ('cups-connection-error',
self.on_cups_connection_error)
def show (self, name, host=None, encryption=None, parent=None):
self.parent = parent
self._host = host
self._encryption = encryption
if not host:
self._host = cups.getServer()
if not encryption:
self._encryption = cups.getEncryption ()
if self._monitor == None:
self.set_monitor (monitor.Monitor (monitor_jobs=False))
self._ppdcache = self._monitor.get_ppdcache ()
self._disconnect ("newPrinterGUI")
self.newPrinterGUI = newprinter.NewPrinterGUI ()
self._connect ("newPrinterGUI", self.newPrinterGUI,
"printer-modified", self.on_printer_modified)
self._connect ("newPrinterGUI", self.newPrinterGUI,
"dialog-canceled", self.on_printer_not_modified)
if parent:
self.dialog.set_transient_for (parent)
self.load (name, host=host, encryption=encryption, parent=parent)
if not self.printer:
return
for button in [self.btnPrinterPropertiesCancel,
self.btnPrinterPropertiesOK,
self.btnPrinterPropertiesApply]:
if self.printer.discovered:
button.hide ()
else:
button.show ()
if self.printer.discovered:
self.btnPrinterPropertiesClose.show ()
else:
self.btnPrinterPropertiesClose.hide ()
self.setDataButtonState ()
self.btnPrintTestPage.set_tooltip_text(_("CUPS test page"))
self.btnSelfTest.set_tooltip_text(_("Typically shows whether all jets "
"on a print head are functioning "
"and that the print feed mechanisms"
" are working properly."))
treeview = self.tvPrinterProperties
treeview.set_cursor (Gtk.TreePath(), None, False)
host = CUPS_server_hostname ()
self.dialog.set_title (_("Printer Properties - "
"'%s' on %s") % (name, host))
self.dialog.show ()
def printer_properties_response (self, dialog, response):
if not self.printer:
response = Gtk.ResponseType.CANCEL
if response == Gtk.ResponseType.REJECT:
# The Conflict button was pressed.
message = _("There are conflicting options.\n"
"Changes can only be applied after\n"
"these conflicts are resolved.")
message += "\n\n"
for option in self.conflicts:
message += option.option.text + "\n"
dialog = Gtk.MessageDialog(parent=self.dialog,
modal=True, destroy_with_parent=True,
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.CLOSE,
text=message)
dialog.run()
dialog.destroy()
return
if (response == Gtk.ResponseType.OK or
response == Gtk.ResponseType.APPLY):
if (response == Gtk.ResponseType.OK and len (self.changed) == 0):
failed = False
else:
failed = self.save_printer (self.printer)
if response == Gtk.ResponseType.APPLY and not failed:
try:
self.load (self.printer.name)
except:
pass
self.setDataButtonState ()
if ((response == Gtk.ResponseType.OK and not failed) or
response == Gtk.ResponseType.CANCEL):
self.ppd = None
self.ppd_local = None
self.printer = None
dialog.hide ()
self.emit ('dialog-closed')
if self.newPrinterGUI.NewPrinterWindow.get_property ("visible"):
self.newPrinterGUI.on_NPCancel (None)
# Data handling
def on_delete(self, dialog, event):
self.printer_properties_response (dialog, Gtk.ResponseType.CANCEL)
def on_printer_changed(self, widget):
if isinstance(widget, Gtk.CheckButton):
value = widget.get_active()
elif isinstance(widget, Gtk.Entry):
value = widget.get_text()
elif isinstance(widget, Gtk.RadioButton):
value = widget.get_active()
elif isinstance(widget, Gtk.ComboBox):
model = widget.get_model ()
iter = widget.get_active_iter()
value = model.get_value (iter, 1)
else:
raise ValueError("Widget type not supported (yet)")
p = self.printer
old_values = {
self.entPDescription : p.info,
self.entPLocation : p.location,
self.entPDevice : p.device_uri,
self.chkPEnabled : p.enabled,
self.chkPAccepting : not p.rejecting,
self.chkPShared : p.is_shared,
self.cmbPStartBanner : p.job_sheet_start,
self.cmbPEndBanner : p.job_sheet_end,
self.cmbPErrorPolicy : p.error_policy,
self.cmbPOperationPolicy : p.op_policy,
self.rbtnPAllow: p.default_allow,
}
old_value = old_values[widget]
if old_value == value:
self.changed.discard(widget)
else:
self.changed.add(widget)
self.setDataButtonState()
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()
if (self.option_manualfeed and self.option_inputslot and
option == self.option_manualfeed):
if option.get_current_value() == "True":
self.option_inputslot.disable ()
else:
self.option_inputslot.enable ()
# Access control
def getPUsers(self):
"""return list of usernames from the GUI"""
model = self.tvPUsers.get_model()
result = []
model.foreach(lambda model, path, iter, data:
result.append(model.get(iter, 0)[0]), None)
result.sort()
return result
def setPUsers(self, users):
"""write list of usernames inot the GUI"""
model = self.tvPUsers.get_model()
model.clear()
for user in users:
model.append((user,))
self.on_entPUser_changed(self.entPUser)
self.on_tvPUsers_cursor_changed(self.tvPUsers)
def checkPUsersChanged(self):
"""check if users in GUI and printer are different
and set self.changed"""
if not self.printer:
return
if self.getPUsers() != self.printer.except_users:
self.changed.add(self.tvPUsers)
else:
self.changed.discard(self.tvPUsers)
self.on_tvPUsers_cursor_changed(self.tvPUsers)
self.setDataButtonState()
def on_btnPAddUser_clicked(self, button):
user = self.entPUser.get_text()
if user:
self.tvPUsers.get_model().insert(0, (user,))
self.entPUser.set_text("")
self.checkPUsersChanged()
def on_btnPDelUser_clicked(self, button):
model, rows = self.tvPUsers.get_selection().get_selected_rows()
rows = [Gtk.TreeRowReference.new (model, row) for row in rows]
for row in rows:
path = row.get_path()
iter = model.get_iter(path)
model.remove(iter)
self.checkPUsersChanged()
def on_entPUser_changed(self, widget):
self.btnPAddUser.set_sensitive(bool(widget.get_text()))
def on_tvPUsers_cursor_changed(self, widget):
selection = widget.get_selection ()
if selection == None:
return
model, rows = selection.get_selected_rows()
self.btnPDelUser.set_sensitive(bool(rows))
# Server side options
def on_job_option_reset(self, button):
option = self.job_options_buttons[button]
option.reset ()
# Remember to set this option for removal in the IPP request.
if option.name in self.server_side_options:
del self.server_side_options[option.name]
if option.is_changed ():
self.changed.add(option)
else:
self.changed.discard(option)
self.setDataButtonState()
def on_job_option_changed(self, widget):
if not self.printer:
return
option = self.job_options_widgets[widget]
option.changed ()
if option.is_changed ():
self.server_side_options[option.name] = option
self.changed.add(option)
else:
if option.name in self.server_side_options:
del self.server_side_options[option.name]
self.changed.discard(option)
self.setDataButtonState()
# Don't set the reset button insensitive if the option hasn't
# changed from the original value: it's still meaningful to
# reset the option to the system default.
def draw_other_job_options (self, editable=True):
n = len (self.other_job_options)
if n == 0:
self.tblJOOther.hide()
return
self.tblJOOther.resize (n, 3)
children = self.tblJOOther.get_children ()
for child in children:
self.tblJOOther.remove (child)
i = 0
for opt in self.other_job_options:
self.tblJOOther.attach (opt.label, 0, 1, i, i + 1,
xoptions=Gtk.AttachOptions.FILL,
yoptions=Gtk.AttachOptions.FILL)
opt.label.set_alignment (0.0, 0.5)
self.tblJOOther.attach (opt.selector, 1, 2, i, i + 1,
xoptions=Gtk.AttachOptions.FILL,
yoptions=0)
opt.selector.set_sensitive (editable)
btn = Gtk.Button.new_from_icon_name (Gtk.STOCK_REMOVE,
Gtk.IconSize.BUTTON)
btn.connect("clicked", self.on_btnJOOtherRemove_clicked)
btn.pyobject = opt
btn.set_sensitive (editable)
self.tblJOOther.attach(btn, 2, 3, i, i + 1,
xoptions=0,
yoptions=0)
i += 1
self.tblJOOther.show_all ()
def add_job_option(self, name, value = "", supported = "", is_new=True,
editable=True):
try:
option = options.OptionWidget(name, value, supported,
self.option_changed)
except ValueError:
# We can't deal with this option type for some reason.
nonfatalException ()
return
option.is_new = is_new
self.other_job_options.append (option)
self.draw_other_job_options (editable=editable)
self.server_side_options[name] = option
if name in self.changed: # was deleted before
option.is_new = False
self.changed.add(option)
self.setDataButtonState()
if is_new:
option.selector.grab_focus ()
def on_btnJOOtherRemove_clicked(self, button):
option = button.pyobject
self.other_job_options.remove (option)
self.draw_other_job_options ()
if option.is_new:
self.changed.discard(option)
else:
# keep name as reminder that option got deleted
self.changed.add(option.name)
del self.server_side_options[option.name]
self.setDataButtonState()
def on_btnNewJobOption_clicked(self, button):
name = self.entNewJobOption.get_text()
self.add_job_option(name)
self.tblJOOther.show_all()
self.entNewJobOption.set_text ('')
self.btnNewJobOption.set_sensitive (False)
self.setDataButtonState()
def on_entNewJobOption_changed(self, widget):
text = self.entNewJobOption.get_text()
active = (len(text) > 0) and text not in self.server_side_options
self.btnNewJobOption.set_sensitive(active)
def on_entNewJobOption_activate(self, widget):
self.on_btnNewJobOption_clicked (widget) # wrong widget but ok
# set buttons sensitivity
def setDataButtonState(self):
try:
attrs = self.printer.other_attributes
formats = attrs.get('document-format-supported', [])
printable = (not bool (self.changed) and
self.printer.enabled and
not self.printer.rejecting)
try:
formats.index ('application/postscript')
testpage = printable
except ValueError:
# PostScript not accepted
testpage = False
self.btnPrintTestPage.set_sensitive (testpage)
adjustable = not (self.printer.discovered or bool (self.changed))
for button in [self.btnChangePPD,
self.btnSelectDevice]:
button.set_sensitive (adjustable)
selftest = False
cleanheads = False
if (printable and
(self.printer.type & cups.CUPS_PRINTER_COMMANDS) != 0):
try:
# Is the command format supported?
formats.index ('application/vnd.cups-command')
# Yes...
commands = attrs.get('printer-commands', [])
for command in commands:
if command == "PrintSelfTestPage":
selftest = True
if cleanheads:
break
elif command == "Clean":
cleanheads = True
if selftest:
break
except ValueError:
# Command format not supported.
pass
for cond, button in [(selftest, self.btnSelfTest),
(cleanheads, self.btnCleanHeads)]:
if cond:
button.show ()
else:
button.hide ()
except:
nonfatalException()
if self.ppd or \
((self.printer.remote or \
((self.printer.device_uri.startswith('dnssd:') or \
self.printer.device_uri.startswith('mdns:')) and \
self.printer.device_uri.endswith('/cups'))) and not \
self.printer.discovered):
self.btnPrintTestPage.show ()
else:
self.btnPrintTestPage.hide ()
installablebold = False
optionsbold = False
if self.conflicts:
debugprint ("Conflicts detected")
self.btnConflict.show()
for option in self.conflicts:
if option.tab_label.get_text () == self.lblPInstallOptions.get_text ():
installablebold = True
else:
optionsbold = True
else:
self.btnConflict.hide()
installabletext = _("Installable Options")
optionstext = _("Printer Options")
if installablebold:
installabletext = "<b>%s</b>" % installabletext
if optionsbold:
optionstext = "<b>%s</b>" % optionstext
self.lblPInstallOptions.set_markup (installabletext)
self.lblPOptions.set_markup (optionstext)
store = self.tvPrinterProperties.get_model ()
if store:
for n in range (self.ntbkPrinter.get_n_pages ()):
page = self.ntbkPrinter.get_nth_page (n)
label = self.ntbkPrinter.get_tab_label (page).get_text ()
try:
if label == self.lblPInstallOptions.get_text():
iter = store.get_iter ((n,))
store.set_value (iter, 0, installabletext)
elif label == self.lblPOptions.get_text ():
iter = store.get_iter ((n,))
store.set_value (iter, 0, optionstext)
except ValueError:
# If we get here, the store has not yet been set
# up (trac #111).
pass
self.btnPrinterPropertiesApply.set_sensitive (len (self.changed) > 0 and
not self.conflicts)
self.btnPrinterPropertiesOK.set_sensitive (not self.conflicts)
def save_printer(self, printer, saveall=False, parent=None):
if parent == None:
parent = self.dialog
class_deleted = False
name = printer.name
if printer.is_class:
self.cups._begin_operation (_("modifying class %s") % name)