Debian Codegraph @

options.py

raw
1 ## system-config-printer
2
3 ## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Red Hat, Inc.
4 ## Authors:
5 ## Tim Waugh <[email protected]>
6 ## Florian Festi <[email protected]>
7
8 ## This program is free software; you can redistribute it and/or modify
9 ## it under the terms of the GNU General Public License as published by
10 ## the Free Software Foundation; either version 2 of the License, or
11 ## (at your option) any later version.
12
13 ## This program is distributed in the hope that it will be useful,
14 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ## GNU General Public License for more details.
17
18 ## You should have received a copy of the GNU General Public License
19 ## along with this program; if not, write to the Free Software
20 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
22 from debug import *
23 from gi.repository import Gtk
24 import cups
25 import ppdippstr
26 import re
27
28 cups.require ("1.9.55")
29
30 # Special IPP type
31 class IPPResolution(tuple):
32 def __new__ (cls, values):
33 cls.UNITS_BY_VAL = { cups.IPP_RES_PER_INCH: "dpi",
34 cups.IPP_RES_PER_CM: "dpc" }
35 cls.UNITS_DEFAULT = cups.IPP_RES_PER_INCH
36
37 cls.UNITS_BY_STR = {}
38 for v, s in cls.UNITS_BY_VAL.items ():
39 cls.UNITS_BY_STR[s] = v
40
41 if isinstance (values, str):
42 matches = re.match (r"(\d+)\D+(\d+)(.*)", values).groups ()
43 xres = int (matches[0])
44 yres = int (matches[1])
45 units = cls.UNITS_BY_STR.get (matches[2], cls.UNITS_DEFAULT)
46 else:
47 xres = values[0]
48 yres = values[1]
49 units = values[2]
50
51 self = tuple.__new__ (cls, (xres, yres, units))
52 self.xres = xres
53 self.yres = yres
54 self.units = units
55 return self
56
57 def __init__ (self, values):
58 return tuple.__init__ ((self.xres, self.yres, self.units))
59
60 def __str__ (self):
61 return "%sx%s%s" % (self.xres, self.yres,
62 self.UNITS_BY_VAL.get (self.units,
63 self.UNITS_DEFAULT))
64
65 def OptionWidget(name, v, s, on_change):
66 if isinstance(v, list):
67 # XXX
68 if isinstance(s, list):
69 for vv in v + s:
70 if not isinstance(vv, str): raise ValueError
71 return OptionSelectMany(name, v, s, on_change)
72 print(v, s)
73 raise NotImplementedError
74 else:
75 if (isinstance(s, int) or
76 isinstance(s, float) or
77 (isinstance(s, tuple) and
78 len(s) == 2 and
79 ((isinstance(s[0], int) and isinstance(s[1], int)) or
80 (isinstance(s[0], float) and isinstance(s[1], float))))):
81 try:
82 if (isinstance(s, int) or
83 isinstance(s, tuple) and isinstance(s[0], int)):
84 v = int(v)
85 else:
86 v = float(v)
87 except ValueError:
88 return OptionText(name, v, "", on_change)
89 return OptionNumeric(name, v, s, on_change)
90 elif isinstance(s, list):
91 for sv in s:
92 if isinstance(sv, tuple) and len (sv) == 3:
93 return OptionSelectOneResolution(name, v, s, on_change)
94 elif not isinstance(sv, int):
95 return OptionSelectOne(name, v, s, on_change)
96 try:
97 v = int(v)
98 except ValueError:
99 return OptionSelectOne(name, v, s, on_change)
100 return OptionSelectOneNumber(name, v, s, on_change)
101 elif isinstance(s, str):
102 return OptionText(name, v, s, on_change)
103 else:
104 raise ValueError
105
106 # ---------------------------------------------------------------------------
107
108 class OptionInterface:
109 def get_default(self):
110 return None
111
112 def get_current_value(self):
113 raise NotImplementedError
114
115 def is_changed(self):
116 raise NotImplementedError
117
118 class OptionAlwaysShown(OptionInterface):
119 # States
120 STATE_UNCHANGED=0
121 STATE_RESET=1
122 STATE_ADJUSTED=2
123
124 def __init__(self, name, ipp_type, system_default,
125 widget, button, combobox_map = None, use_supported = False):
126 self.name = name
127 self.widget = widget
128 self.button = button
129 if ipp_type == bool:
130 def bool_type (x):
131 if type (x) == str:
132 if x.lower () in ("false", "no", "off"):
133 return False
134 # Even the empty string is true.
135 return True
136 return bool (x)
137 ipp_type = bool_type
138 self.ipp_type = ipp_type
139 self.set_default (system_default)
140 self.combobox_map = combobox_map
141
142 if (type(self.widget) == Gtk.ComboBox and
143 self.widget.get_model () is None):
144 debugprint("No ComboBox model for %s" % self.name)
145 model = Gtk.ListStore (str)
146 self.widget.set_model (model)
147
148 if combobox_map is not None and ipp_type == int:
149 model = self.widget.get_model ()
150 i = 0
151 dict = {}
152 iter = model.get_iter_first ()
153 while iter:
154 dict[combobox_map[i]] = model.get_value (iter, 0)
155 i += 1
156 iter = model.iter_next (iter)
157 self.combobox_dict = dict
158 self.use_supported = use_supported
159 self.reinit (None)
160
161 def get_default(self):
162 return self.system_default
163
164 def set_default(self, system_default):
165 # For the media option, the system default depends on the printer's
166 # PageSize setting. This method allows the main module to tell us
167 # what that is.
168 self.system_default = self.ipp_type (system_default)
169
170 def reinit(self, original_value, supported=None):
171 """Set the original value of the option and the supported choices.
172 The special value None for original_value resets the option to the
173 system default."""
174 if (supported is not None and
175 self.use_supported):
176 if (type(self.widget) == Gtk.ComboBox and
177 self.ipp_type == str):
178 model = self.widget.get_model ()
179 model.clear ()
180 translations = ppdippstr.job_options.get (self.name)
181 if translations:
182 self.combobox_map = []
183 self.combobox_dict = dict()
184 i = 0
185
186 for each in supported:
187 txt = str (self.ipp_type (each))
188
189 if translations:
190 self.combobox_map.append (txt)
191 text = translations.get (txt)
192 self.combobox_dict[each] = text
193 i += 1
194 else:
195 text = txt
196
197 iter = model.append ()
198 model.set_value (iter, 0, text)
199 elif type(self.widget) == Gtk.ComboBoxText:
200 self.widget.remove_all () # emits 'changed'
201 translations = ppdippstr.job_options.get (self.name)
202 if translations:
203 self.combobox_map = []
204 self.combobox_dict = dict()
205 i = 0
206
207 for each in supported:
208 txt = str (self.ipp_type (each))
209 if translations:
210 self.combobox_map.append (txt)
211 text = translations.get (txt)
212 self.combobox_dict[each] = text
213 i += 1
214 else:
215 text = txt
216
217 self.widget.append_text (text)
218 elif (type(self.widget) == Gtk.ComboBox and
219 self.ipp_type == int and
220 self.combobox_map is not None):
221 model = self.widget.get_model ()
222 model.clear ()
223 for each in supported:
224 iter = model.append ()
225 model.set_value (iter, 0, self.combobox_dict[each])
226
227 if original_value is not None:
228 self.original_value = self.ipp_type (original_value)
229 self.set_widget_value (self.original_value)
230 self.button.set_sensitive (True)
231 else:
232 self.original_value = None
233 self.set_widget_value (self.system_default)
234 self.button.set_sensitive (False)
235 self.state = self.STATE_UNCHANGED
236
237 def set_widget_value(self, ipp_value):
238 t = type(self.widget)
239 if t == Gtk.SpinButton:
240 return self.widget.set_value (ipp_value)
241 elif t == Gtk.ComboBox or t == Gtk.ComboBoxText:
242 if ((self.ipp_type == str or self.ipp_type == IPPResolution)
243 and self.combobox_map is None):
244 model = self.widget.get_model ()
245 iter = model.get_iter_first ()
246 while (iter is not None and
247 self.ipp_type (model.get_value (iter, 0)) != ipp_value):
248 iter = model.iter_next (iter)
249 if iter:
250 self.widget.set_active_iter (iter)
251 else:
252 # It's an int.
253 if self.combobox_map:
254 index = self.combobox_map.index (ipp_value)
255 else:
256 index = ipp_value
257 return self.widget.set_active (index)
258 elif t == Gtk.CheckButton:
259 return self.widget.set_active (ipp_value)
260 else:
261 raise NotImplementedError(t, self.name)
262
263 def get_widget_value(self):
264 t = type(self.widget)
265 if t == Gtk.SpinButton:
266 # Ideally we would use self.widget.get_value() here, but
267 # it doesn't work if the value has been typed in and then
268 # the Apply button immediately clicked. To handle this,
269 # we use self.widget.get_text() and fall back to
270 # get_value() if the result cannot be interpreted as the
271 # type we expect.
272 try:
273 return self.ipp_type (self.widget.get_text ())
274 except ValueError:
275 # Can't convert result of get_text() to ipp_type.
276 return self.ipp_type (self.widget.get_value ())
277 elif t == Gtk.ComboBox:
278 if self.combobox_map:
279 return self.combobox_map[self.widget.get_active()]
280 return self.ipp_type (self.widget.get_active ())
281 elif t == Gtk.ComboBoxText:
282 s = self.widget.get_active_text ()
283 if s is None:
284 # If the widget is being re-initialised, there will be
285 # a changed signal emitted at the point where there
286 # are no entries to select from.
287 s = self.system_default
288 if self.combobox_map:
289 return self.combobox_map (s)
290 return self.ipp_type (s)
291 elif t == Gtk.CheckButton:
292 return self.ipp_type (self.widget.get_active ())
293
294 print(t, self.widget, self.ipp_type)
295 raise NotImplementedError
296
297 def get_current_value(self):
298 return self.get_widget_value ()
299
300 def is_changed(self):
301 if self.original_value is not None:
302 # There was a value set previously.
303 if self.state == self.STATE_RESET:
304 # It's been removed.
305 return True
306 if self.state == self.STATE_ADJUSTED:
307 if self.get_current_value () != self.original_value:
308 return True
309 return False
310
311 # The value is the same as before, and not reset.
312 return False
313
314 # There was no original value set.
315 if self.state == self.STATE_ADJUSTED:
316 # It's been adjusted.
317 return True
318
319 # It's been left alone, or possible adjusted and then reset.
320 return False
321
322 def reset(self):
323 self.set_widget_value (self.system_default)
324 self.state = self.STATE_RESET
325 self.button.set_sensitive (False)
326
327 def changed(self):
328 self.state = self.STATE_ADJUSTED
329 self.button.set_sensitive (True)
330
331 class OptionAlwaysShownSpecial(OptionAlwaysShown):
332 def __init__(self, name, ipp_type, system_default,
333 widget, button, combobox_map = None, use_supported = False,
334 special_choice = "System default"):
335 self.special_choice = special_choice
336 self.special_choice_shown = False
337 OptionAlwaysShown.__init__ (self, name, ipp_type, system_default,
338 widget, button,
339 combobox_map=combobox_map,
340 use_supported=use_supported)
341
342 def show_special_choice (self):
343 if self.special_choice_shown:
344 return
345
346 self.special_choice_shown = True
347 # Only works for ComboBox widgets
348 model = self.widget.get_model ()
349 iter = model.insert (0)
350 model.set_value (iter, 0, self.special_choice)
351 self.widget.set_active_iter (model.get_iter_first ())
352
353 def hide_special_choice (self):
354 if not self.special_choice_shown:
355 return
356
357 self.special_choice_shown = False
358 # Only works for ComboBox widgets
359 model = self.widget.get_model ()
360 model.remove (model.get_iter_first ())
361
362 def reinit(self, original_value, supported=None):
363 if original_value is not None:
364 self.hide_special_choice ()
365 else:
366 self.show_special_choice ()
367
368 OptionAlwaysShown.reinit (self, original_value, supported=supported)
369
370 def reset(self):
371 self.show_special_choice ()
372 OptionAlwaysShown.reset (self)
373
374 def changed(self):
375 OptionAlwaysShown.changed (self)
376 if self.widget.get_active () > 0:
377 self.hide_special_choice ()
378
379 class Option(OptionInterface):
380
381 conflicts = None
382
383 def __init__(self, name, value, supported, on_change):
384 self.name = name
385 self.value = value
386 self.supported = supported
387 self.on_change = on_change
388 self.is_new = False
389
390 label = name
391 if not label.endswith (':'):
392 label += ':'
393 self.label = Gtk.Label(label=label)
394 self.label.set_alignment(0.0, 0.5)
395
396 def get_current_value(self):
397 raise NotImplementedError
398
399 def is_changed(self):
400 return (self.is_new or
401 str (self.get_current_value()) != str (self.value))
402
403 def changed(self, widget, *args):
404 self.on_change(self)
405
406 # ---------------------------------------------------------------------------
407
408 class OptionSelectOne(Option):
409
410 def __init__(self, name, value, supported, on_change):
411 Option.__init__(self, name, value, supported, on_change)
412
413 self.selector = Gtk.ComboBoxText()
414
415 selected = None
416 for nr, choice in enumerate(supported):
417 self.selector.append_text(str(choice))
418 if str (value) == str (choice):
419 selected = nr
420 if selected is not None:
421 self.selector.set_active(selected)
422 else:
423 debugprint("Unknown value for %s: %s" % (name, value))
424 debugprint("Choices: %s" % (supported))
425 if len(supported) > 0:
426 debugprint("Selecting from choices:", supported[0])
427 self.selector.set_active(0)
428 self.selector.connect("changed", self.changed)
429
430 def get_current_value(self):
431 return self.selector.get_active_text()
432
433 # ---------------------------------------------------------------------------
434
435 class OptionSelectOneResolution(OptionSelectOne):
436 def __init__(self, name, value, supported, on_change):
437 self.UNITS_BY_VAL = { cups.IPP_RES_PER_INCH: "dpi",
438 cups.IPP_RES_PER_CM: "dpc" }
439 self.UNITS_DEFAULT = cups.IPP_RES_PER_INCH
440 self.UNITS_BY_STR = {}
441 for v, s in self.UNITS_BY_VAL.items ():
442 self.UNITS_BY_STR[s] = v
443
444 value = self.string (value)
445 supported = list(map (self.string, supported))
446 OptionSelectOne.__init__ (self, name, value, supported, on_change)
447
448 def string(self, value):
449 return "%sx%s%s" % (value[0], value[1],
450 self.UNITS_BY_VAL.get (value[2], ""))
451
452 def value(self, string):
453 matches = re.match (r"(\d+)\D+(\d+)(.*)", string).groups ()
454 return (int (matches[0]), int (matches[1]),
455 self.UNITS_BY_STR.get (matches[2], self.UNITS_DEFAULT))
456
457 def get_current_value(self):
458 return self.value (self.selector.get_active_text())
459
460 # ---------------------------------------------------------------------------
461
462 class OptionSelectOneNumber(OptionSelectOne):
463
464 def get_current_value(self):
465 return int(self.selector.get_active_text() or 0)
466
467 # ---------------------------------------------------------------------------
468
469 class OptionSelectMany(Option):
470
471 def __init__(self, name, value, supported, on_change):
472 Option.__init__(self, name, value, supported, on_change)
473 self.checkboxes = []
474 vbox = Gtk.VBox()
475
476 for s in supported:
477 checkbox = Gtk.CheckButton.new_with_label(s)
478 checkbox.set_active(s in value)
479 vbox.add(checkbox)
480 checkbox.connect("toggled", self.changed)
481 self.checkboxes.append(checkbox)
482 self.selector = vbox
483
484 def get_current_value(self):
485 return[s for s, chk in zip(self.supported, self.checkboxes)
486 if chk.get_active()]
487
488 # ---------------------------------------------------------------------------
489
490 class OptionNumeric(Option):
491 def __init__(self, name, value, supported, on_change):
492 self.is_float = (isinstance(supported, float) or
493 (isinstance(supported, tuple) and
494 isinstance(supported[0], float)))
495 if self.is_float:
496 digits = 2
497 else:
498 digits = 0
499
500 if not isinstance(supported, tuple):
501 supported = (0, supported)
502 Option.__init__(self, name, value, supported, on_change)
503 adj = Gtk.Adjustment(value=value, lower=supported[0],
504 upper=supported[1], step_increment=1.0,
505 page_increment=5.0, page_size=0.0)
506 self.selector = Gtk.SpinButton()
507 self.selector.set_adjustment(adj)
508 self.selector.set_digits(digits)
509 if not self.is_float:
510 self.selector.set_numeric(True)
511 self.selector.connect("changed", self.changed)
512
513 def get_current_value(self):
514 if self.is_float:
515 return self.selector.get_value()
516 return self.selector.get_value_as_int()
517
518 # ---------------------------------------------------------------------------
519
520 class OptionText(Option):
521 def __init__(self, name, value, supported, on_change):
522 Option.__init__(self, name, value, supported, on_change)
523
524 self.selector = Gtk.Entry()
525 self.selector.set_text(value)
526 self.selector.connect("changed", self.changed)
527
528 def get_current_value(self):
529 return self.selector.get_text()