Debian Codegraph @

cupshelpers/xmldriverprefs.py

raw
1 #!/usr/bin/python3
2
3 ## system-config-printer
4
5 ## Copyright (C) 2006, 2007, 2008, 2009, 2010 Red Hat, Inc.
6 ## Copyright (C) 2006 Florian Festi <[email protected]>
7 ## Copyright (C) 2006, 2007, 2008, 2009 Tim Waugh <[email protected]>
8
9 ## This program is free software; you can redistribute it and/or modify
10 ## it under the terms of the GNU General Public License as published by
11 ## the Free Software Foundation; either version 2 of the License, or
12 ## (at your option) any later version.
13
14 ## This program is distributed in the hope that it will be useful,
15 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ## GNU General Public License for more details.
18
19 ## You should have received a copy of the GNU General Public License
20 ## along with this program; if not, write to the Free Software
21 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
23 import fnmatch
24 import re
25 import xml.etree.ElementTree
26 from .cupshelpers import parseDeviceID
27
28 def PreferredDrivers (filename):
29 preferreddrivers = xml.etree.ElementTree.XML (open (filename).read ())
30 return list(preferreddrivers)
31
32 class DeviceIDMatch:
33 """
34 A set of fields and regular expressions for matching a Device ID.
35 """
36 def __init__ (self):
37 self._re = dict()
38
39 def add_field (self, field, pattern):
40 self._re[field.upper ()] = re.compile (pattern, re.I)
41
42 def match (self, deviceid):
43 """
44 Match against a parsed Device ID dictionary.
45
46 The CMD field is treated specially. If any of the
47 comma-separated words in this field value match, the Device ID
48 pattern is considered to match.
49 """
50
51 for field, match in self._re.items ():
52 if field not in deviceid:
53 return False
54
55 if field == "CMD":
56 this_field_matches = False
57 for cmd in deviceid[field]:
58 if match.match (cmd):
59 this_field_matches = True
60 break
61
62 if not this_field_matches:
63 return False
64
65 if not match.match (deviceid[field]):
66 return False
67
68 return True
69
70 class DriverType:
71 """
72 A type of driver.
73 """
74
75 FIT_EXACT_CMD = "exact-cmd"
76 FIT_EXACT = "exact"
77 FIT_CLOSE = "close"
78 FIT_GENERIC = "generic"
79 FIT_NONE = "none"
80
81 def __init__ (self, name):
82 self.name = name
83 self.ppd_name = None
84 self.attributes = []
85 self.deviceid = []
86
87 class AlwaysTrue:
88 def get (self, k, d=None):
89 return True
90
91 self._fit = AlwaysTrue ()
92 self._packagehint = None
93
94 def add_ppd_name (self, pattern):
95 """
96 An optional PPD name regular expression.
97 """
98 self.ppd_name = re.compile (pattern, re.I)
99
100 # If the PPD name pattern includes a scheme, we can perhaps
101 # deduce which package would provide this driver type.
102 if self._packagehint is not None:
103 return
104
105 parts = pattern.split (":", 1)
106 if len (parts) > 1:
107 scheme = parts[0]
108 if scheme == "drv":
109 rest = parts[1]
110 if rest.startswith ("///"):
111 drv = rest[3:]
112 f = drv.rfind ("/")
113 if f != -1:
114 drv = drv[:f]
115 self._packagehint = "/usr/share/cups/drv/%s" % drv
116 else:
117 self._packagehint = "/usr/lib/cups/driver/%s" % scheme
118
119 def add_attribute (self, name, pattern):
120 """
121 An optional IPP attribute name and regular expression to match
122 against its values.
123 """
124 self.attributes.append ((name, re.compile (pattern, re.I)))
125
126 def add_deviceid_match (self, deviceid_match):
127 """
128 An optional IEEE 1284 Device ID match.
129 """
130 self.deviceid.append (deviceid_match)
131
132 def add_fit (self, text):
133 self._fit = {}
134 for fittype in text.split():
135 self._fit[fittype] = True
136
137 # <fit>exact</fit> matches exact-cmd as well
138 if fittype == self.FIT_EXACT:
139 self._fit[self.FIT_EXACT_CMD] = True
140
141 def set_packagehint (self, hint):
142 self._packagekit = hint
143
144 def get_name (self):
145 """
146 Return the name for this driver type.
147 """
148 return self.name
149
150 def __repr__ (self):
151 return "<DriverType %s instance at 0x%x>" % (self.name, id (self))
152
153 def match (self, ppd_name, attributes, fit):
154 """
155 Return True if there is a match for all specified criteria.
156
157 ppdname: string
158
159 attributes: dict
160
161 fit: string
162 """
163
164 matches = self._fit.get (fit, False)
165 if matches and self.ppd_name and not self.ppd_name.match (ppd_name):
166 matches = False
167
168 if matches:
169 for name, match in self.attributes:
170 if name not in attributes:
171 matches = False
172 break
173
174 values = attributes[name]
175 if not isinstance (values, list):
176 # In case getPPDs() was used instead of getPPDs2()
177 values = [values]
178
179 any_value_matches = False
180 for value in values:
181 if match.match (value):
182 any_value_matches = True
183 break
184
185 if not any_value_matches:
186 matches = False
187 break
188
189 if matches:
190 if self.deviceid and "ppd-device-id" not in attributes:
191 matches = False
192 elif self.deviceid:
193 # This is a match if any of the ppd-device-id values
194 # match.
195 deviceidlist = attributes["ppd-device-id"]
196 if not isinstance (deviceidlist, list):
197 # In case getPPDs() was used instead of getPPDs2()
198 deviceidlist = [deviceidlist]
199
200 any_id_matches = False
201 for deviceidstr in deviceidlist:
202 deviceid = parseDeviceID (deviceidstr)
203 for match in self.deviceid:
204 if match.match (deviceid):
205 any_id_matches = True
206 break
207
208 if not any_id_matches:
209 matches = False
210
211 return matches
212
213 def get_packagehint (self):
214 return None
215
216 class DriverTypes:
217 """
218 A list of driver types.
219 """
220
221 def __init__ (self):
222 self.drivertypes = []
223
224 def load (self, drivertypes):
225 """
226 Load the list of driver types from an XML file.
227 """
228
229 types = []
230 for drivertype in list(drivertypes):
231 t = DriverType (drivertype.attrib["name"])
232
233 for child in list(drivertype):
234 if child.tag == "ppdname":
235 t.add_ppd_name (child.attrib["match"])
236 elif child.tag == "attribute":
237 t.add_attribute (child.attrib["name"],
238 child.attrib["match"])
239 elif child.tag == "deviceid":
240 deviceid_match = DeviceIDMatch ()
241 for field in list(child):
242 if field.tag == "field":
243 deviceid_match.add_field (field.attrib["name"],
244 field.attrib["match"])
245
246 t.add_deviceid_match (deviceid_match)
247 elif child.tag == "fit":
248 t.add_fit (child.text)
249
250 types.append (t)
251
252 self.drivertypes = types
253
254 def match (self, ppdname, ppddict, fit):
255 """
256 Return the first matching drivertype for a PPD, given its name,
257 attributes, and fitness, or None if there is no match.
258 """
259
260 for drivertype in self.drivertypes:
261 if drivertype.match (ppdname, ppddict, fit):
262 return drivertype
263
264 return None
265
266 def filter (self, pattern):
267 """
268 Return the subset of driver type names that match a glob
269 pattern.
270 """
271
272 return fnmatch.filter ([x.get_name () for x in self.drivertypes],
273 pattern)
274
275 def get_ordered_ppdnames (self, drivertypes, ppdsdict, fit):
276 """
277 Given a list of driver type names, a dict of PPD attributes by
278 PPD name, and a dict of driver fitness status codes by PPD
279 name, return a list of tuples in the form (driver-type-name,
280 PPD-name), representing PPDs that match the list of driver
281 types.
282
283 The returned tuples will have driver types in the same order
284 as the driver types given, with the exception that any
285 blacklisted driver types will be omitted from the returned
286 result.
287 """
288
289 ppdnames = []
290
291 # First find out what driver types we have
292 ppdtypes = {}
293 fit_default = DriverType.FIT_CLOSE
294 for ppd_name, ppd_dict in ppdsdict.items ():
295 drivertype = self.match (ppd_name, ppd_dict, fit.get (ppd_name,
296 fit_default))
297 if drivertype:
298 name = drivertype.get_name ()
299 else:
300 name = "none"
301
302 m = ppdtypes.get (name, [])
303 m.append (ppd_name)
304 ppdtypes[name] = m
305
306 # Now construct the list.
307 for drivertypename in drivertypes:
308 for ppd_name in ppdtypes.get (drivertypename, []):
309 if ppd_name in ppdnames:
310 continue
311
312 ppdnames.append ((drivertypename, ppd_name))
313
314 return ppdnames
315
316 class PrinterType:
317 """
318 A make-and-model pattern and/or set of IEEE 1284 Device ID
319 patterns for matching a set of printers, together with an ordered
320 list of driver type names.
321 """
322
323 def __init__ (self):
324 self.make_and_model = None
325 self.deviceid = []
326 self.drivertype_patterns = []
327 self.avoid = set()
328 self.blacklist = set()
329
330 def add_make_and_model (self, pattern):
331 """
332 Set a make-and-model regular expression. Only one is permitted.
333 """
334 self.make_and_model = re.compile (pattern, re.I)
335
336 def add_deviceid_match (self, deviceid_match):
337 """
338 Add a Device ID match.
339 """
340 self.deviceid.append (deviceid_match)
341
342 def add_drivertype_pattern (self, name):
343 """
344 Append a driver type pattern.
345 """
346 self.drivertype_patterns.append (name.strip ())
347
348 def get_drivertype_patterns (self):
349 """
350 Return the list of driver type patterns.
351 """
352 return self.drivertype_patterns
353
354 def add_avoidtype_pattern (self, name):
355 """
356 Add an avoid driver type pattern.
357 """
358 self.avoid.add (name)
359
360 def get_avoidtype_patterns (self):
361 """
362 Return the set of driver type patterns to avoid.
363 """
364 return self.avoid
365
366 def add_blacklisted (self, name):
367 """
368 Add a blacklisted driver type pattern.
369 """
370 self.blacklist.add (name)
371
372 def get_blacklist (self):
373 """
374 Return the set of blacklisted driver type patterns.
375 """
376 return self.blacklist
377
378 def match (self, make_and_model, deviceid):
379 """
380 Return True if there are no constraints to match against; if
381 the make-and-model pattern matches; or if all of the IEEE 1284
382 Device ID patterns match.
383
384 The deviceid parameter must be a dict indexed by Device ID
385 field key, of strings; except for the CMD field which must be
386 a list of strings.
387
388 Return False otherwise.
389 """
390
391 matches = (self.make_and_model is None and self.deviceid == [])
392 if self.make_and_model:
393 if self.make_and_model.match (make_and_model):
394 matches = True
395
396 if not matches:
397 for match in self.deviceid:
398 if match.match (deviceid):
399 matches = True
400 break
401
402 return matches
403
404 class PreferenceOrder:
405 """
406 A policy for choosing the preference order for drivers.
407 """
408
409 def __init__ (self):
410 self.ptypes = []
411
412 def load (self, preferreddrivers):
413 """
414 Load the policy from an XML file.
415 """
416
417 for printer in list(preferreddrivers):
418 ptype = PrinterType ()
419 for child in list(printer):
420 if child.tag == "make-and-model":
421 ptype.add_make_and_model (child.attrib["match"])
422 elif child.tag == "deviceid":
423 deviceid_match = DeviceIDMatch ()
424 for field in list(child):
425 if field.tag == "field":
426 deviceid_match.add_field (field.attrib["name"],
427 field.attrib["match"])
428 ptype.add_deviceid_match (deviceid_match)
429
430 elif child.tag == "drivers":
431 for drivertype in list(child):
432 ptype.add_drivertype_pattern (drivertype.text)
433
434 elif child.tag == "avoid":
435 for drivertype in list(child):
436 ptype.add_avoidtype_pattern (drivertype.text)
437
438 elif child.tag == "blacklist":
439 for drivertype in list(child):
440 ptype.add_blacklisted (drivertype.text)
441
442 self.ptypes.append (ptype)
443
444 def get_ordered_types (self, drivertypes, make_and_model, deviceid):
445 """
446 Return an accumulated list of driver types from all printer
447 types that match a given printer's device-make-and-model and
448 IEEE 1284 Device ID.
449
450 The deviceid parameter must be None or a dict indexed by
451 short-form upper-case field keys.
452 """
453
454 if deviceid is None:
455 deviceid = {}
456
457 if make_and_model is None:
458 make_and_model = ""
459
460 orderedtypes = []
461 blacklist = set()
462 avoidtypes = set()
463 for ptype in self.ptypes:
464 if ptype.match (make_and_model, deviceid):
465 for pattern in ptype.get_drivertype_patterns ():
466 # Match against the glob pattern
467 for drivertype in drivertypes.filter (pattern):
468 # Add each result if not already in the list.
469 if drivertype not in orderedtypes:
470 orderedtypes.append (drivertype)
471
472 for pattern in ptype.get_avoidtype_patterns ():
473 # Match against the glob pattern.
474 for drivertype in drivertypes.filter (pattern):
475 # Add each result to the set.
476 avoidtypes.add (drivertype)
477
478 for pattern in ptype.get_blacklist ():
479 # Match against the glob pattern.
480 for drivertype in drivertypes.filter (pattern):
481 # Add each result to the set.
482 blacklist.add (drivertype)
483
484 if avoidtypes:
485 avoided = []
486 for t in avoidtypes:
487 try:
488 i = orderedtypes.index (t)
489 del orderedtypes[i]
490 avoided.append (t)
491 except IndexError:
492 continue
493
494 orderedtypes.extend (avoided)
495
496 if blacklist:
497 # Remove blacklisted drivers.
498 remaining = []
499 for t in orderedtypes:
500 if t not in blacklist:
501 remaining.append (t)
502
503 orderedtypes = remaining
504
505 return orderedtypes
506
507
508 def test (xml_path=None, attached=False, deviceid=None, debug=False):
509 import cups
510 import locale
511 from . import ppds
512 from pprint import pprint
513 from time import time
514 import os.path
515
516 if debug:
517 def debugprint (x):
518 print (x)
519
520 ppds.set_debugprint_fn (debugprint)
521
522 locale.setlocale (locale.LC_ALL, "")
523 if xml_path is None:
524 xml_path = os.path.join (os.path.join (os.path.dirname (__file__),
525 ".."),
526 "xml")
527
528 os.environ["CUPSHELPERS_XMLDIR"] = xml_path
529 xml_path = os.path.join (xml_path, "preferreddrivers.xml")
530 loadstart = time ()
531 (xmldrivertypes, xmlpreferenceorder) = PreferredDrivers (xml_path)
532 drivertypes = DriverTypes ()
533 drivertypes.load (xmldrivertypes)
534
535 preforder = PreferenceOrder ()
536 preforder.load (xmlpreferenceorder)
537 loadtime = time () - loadstart
538 if debug:
539 print("Time to load %s: %.3fs" % (xml_path, loadtime))
540
541 c = cups.Connection ()
542 try:
543 cupsppds = c.getPPDs2 ()
544 except AttributeError:
545 # getPPDs2 requires pycups >= 1.9.52
546 cupsppds = c.getPPDs ()
547
548 ppdfinder = ppds.PPDs (cupsppds)
549
550 if attached or deviceid:
551 if attached:
552 cups.setUser ("root")
553 devices = c.getDevices ()
554 else:
555 devid = parseDeviceID (deviceid)
556 devices = { "xxx://yyy":
557 { "device-id": deviceid,
558 "device-make-and-model": "%s %s" % (devid["MFG"],
559 devid["MDL"])
560 }
561 }
562
563 for uri, device in devices.items ():
564 if uri.find (":") == -1:
565 continue
566
567 devid = device.get ("device-id", "")
568 if isinstance (devid, list):
569 devid = devid[0]
570
571 if not devid:
572 continue
573
574 if not uri.startswith ("xxx:"):
575 print (uri)
576
577 id_dict = parseDeviceID (devid)
578 fit = ppdfinder.getPPDNamesFromDeviceID (id_dict["MFG"],
579 id_dict["MDL"],
580 id_dict["DES"],
581 id_dict["CMD"],
582 uri)
583
584 mm = device.get ("device-make-and-model", "")
585 orderedtypes = preforder.get_ordered_types (drivertypes,
586 mm, id_dict)
587
588 ppds = {}
589 for ppdname in fit.keys ():
590 ppds[ppdname] = ppdfinder.getInfoFromPPDName (ppdname)
591
592 orderedppds = drivertypes.get_ordered_ppdnames (orderedtypes,
593 ppds,
594 fit)
595 i = 1
596 for t, ppd in orderedppds:
597 print("%d %s\n (%s, %s)" % (i, ppd, t, fit[ppd]))
598 i += 1
599 else:
600 for make in ppdfinder.getMakes ():
601 for model in ppdfinder.getModels (make):
602 ppdsdict = ppdfinder.getInfoFromModel (make, model)
603 mm = make + " " + model
604 orderedtypes = preforder.get_ordered_types (drivertypes,
605 mm, None)
606
607 fit = {}
608 for ppdname in ppdsdict.keys ():
609 fit[ppdname] = DriverType.FIT_CLOSE
610
611 orderedppds = drivertypes.get_ordered_ppdnames (orderedtypes,
612 ppdsdict, fit)
613 print(mm + ":")
614 i = 1
615 for t, ppd in orderedppds:
616 print("%d %s\n (%s)" % (i, ppd, t))
617 i += 1
618
619 print()