Debian Codegraph @

cupshelpers/ppds.py

raw
1 #!/usr/bin/python3
2
3 ## system-config-printer
4
5 ## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2014, 2015 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 cups
24 from .cupshelpers import parseDeviceID
25 from . import xmldriverprefs
26 import itertools
27 import string
28 import time
29 import locale
30 import os.path
31 import functools
32 import re
33 from . import _debugprint, set_debugprint_fn
34 from functools import reduce
35
36 __all__ = ['ppdMakeModelSplit',
37 'PPDs']
38
39 _MFR_BY_RANGE = [
40 # Fill in missing manufacturer names based on model name
41 ("HP", re.compile("deskjet"
42 "|dj[ 0-9]?"
43 "|laserjet"
44 "|lj"
45 "|color laserjet"
46 "|color lj"
47 "|designjet"
48 "|officejet"
49 "|oj"
50 "|photosmart"
51 "|ps "
52 "|psc"
53 "|edgeline")),
54 ("Epson", re.compile("stylus|aculaser")),
55 ("Apple", re.compile("stylewriter"
56 "|imagewriter"
57 "|deskwriter"
58 "|laserwriter")),
59 ("Canon", re.compile("pixus"
60 "|pixma"
61 "|selphy"
62 "|imagerunner"
63 "|bj"
64 "|lbp")),
65 ("Brother", re.compile("hl|dcp|mfc")),
66 ("Xerox", re.compile("docuprint"
67 "|docupage"
68 "|phaser"
69 "|workcentre"
70 "|homecentre")),
71 ("Lexmark", re.compile("optra|(:color )?jetprinter")),
72 ("KONICA MINOLTA", re.compile("magicolor"
73 "|pageworks"
74 "|pagepro")),
75 ("Kyocera", re.compile("fs-"
76 "|km-"
77 "|taskalfa")),
78 ("Ricoh", re.compile("aficio")),
79 ("Oce", re.compile("varioprint")),
80 ("Oki", re.compile("okipage|microline"))
81 ]
82
83 _MFR_NAMES_BY_LOWER = {}
84 for mfr, regexp in _MFR_BY_RANGE:
85 _MFR_NAMES_BY_LOWER[mfr.lower ()] = mfr
86
87 _HP_MODEL_BY_NAME = {
88 "dj": "DeskJet",
89 "lj": "LaserJet",
90 "oj": "OfficeJet",
91 "color lj": "Color LaserJet",
92 "ps ": "PhotoSmart",
93 "hp ": ""
94 }
95
96 _RE_turboprint = re.compile ("turboprint")
97 _RE_version_numbers = re.compile (r" v(?:er\.)?\d(?:\d*\.\d+)?(?: |$)")
98 _RE_ignore_suffix = re.compile (","
99 "| hpijs"
100 "| foomatic/"
101 "| - "
102 "| w/"
103 "| \\("
104 "| postscript"
105 "| ps"
106 "| pdf"
107 "| pxl"
108 "| zjs" # hpcups
109 "| zxs" # hpcups
110 "| pcl3" # hpcups
111 "| printer" # hpcups
112 "|_bt"
113 "| pcl" # Canon CQue
114 "| ufr ii" # Canon UFR II
115 "| br-script" # Brother PPDs
116 )
117 _RE_ignore_series = re.compile (" series| all-in-one", re.I)
118
119 def ppdMakeModelSplit (ppd_make_and_model):
120 """
121 Split a ppd-make-and-model string into a canonical make and model pair.
122
123 @type ppd_make_and_model: string
124 @param ppd_make_and_model: IPP ppd-make-and-model attribute
125 @return: a string pair representing the make and the model
126 """
127
128 # If the string starts with a known model name (like "LaserJet") assume
129 # that the manufacturer name is missing and add the manufacturer name
130 # corresponding to the model name
131 ppd_make_and_model.strip ()
132 make = None
133 cleanup_make = False
134 l = ppd_make_and_model.lower ()
135 for mfr, regexp in _MFR_BY_RANGE:
136 if regexp.match (l):
137 make = mfr
138 model = ppd_make_and_model
139 break
140
141 # Handle PPDs provided by Turboprint
142 if make is None and _RE_turboprint.search (l):
143 t = ppd_make_and_model.find (" TurboPrint")
144 if t != -1:
145 t2 = ppd_make_and_model.rfind (" TurboPrint")
146 if t != t2:
147 ppd_make_and_model = ppd_make_and_model[t + 12:t2]
148 else:
149 ppd_make_and_model = ppd_make_and_model[:t]
150 try:
151 make, model = ppd_make_and_model.split("_", 1)
152 except:
153 make = ppd_make_and_model
154 model = ''
155 make = re.sub (r"(?<=[a-z])(?=[0-9])", " ", make)
156 make = re.sub (r"(?<=[a-z])(?=[A-Z])", " ", make)
157 model = re.sub (r"(?<=[a-z])(?=[0-9])", " ", model)
158 model = re.sub (r"(?<=[a-z])(?=[A-Z])", " ", model)
159 model = re.sub (r" Jet", "Jet", model)
160 model = re.sub (r"Photo Smart", "PhotoSmart", model)
161 cleanup_make = True
162
163 # Special handling for two-word manufacturers
164 elif l.startswith ("konica minolta "):
165 make = "KONICA MINOLTA"
166 model = ppd_make_and_model[15:]
167 elif l.startswith ("lexmark international "):
168 make = "Lexmark"
169 model = ppd_make_and_model[22:]
170 elif l.startswith ("kyocera mita "):
171 make = "Kyocera"
172 model = ppd_make_and_model[13:]
173 elif l.startswith ("kyocera "):
174 make = "Kyocera"
175 model = ppd_make_and_model[8:]
176 elif l.startswith ("fuji xerox "):
177 make = "Fuji Xerox"
178 model = ppd_make_and_model[11:]
179
180 # Finally, take the first word as the name of the manufacturer.
181 else:
182 cleanup_make = True
183 try:
184 make, model = ppd_make_and_model.split(" ", 1)
185 except:
186 make = ppd_make_and_model
187 model = ''
188
189 # Standardised names for manufacturers.
190 makel = make.lower ()
191 if cleanup_make:
192 if (makel.startswith ("hewlett") and
193 makel.endswith ("packard")):
194 make = "HP"
195 makel = "hp"
196 elif (makel.startswith ("konica") and
197 makel.endswith ("minolta")):
198 make = "KONICA MINOLTA"
199 makel = "konica minolta"
200 else:
201 # Fix case errors.
202 mfr = _MFR_NAMES_BY_LOWER.get (makel)
203 if mfr:
204 make = mfr
205
206 # HP and Canon PostScript PPDs give NickNames like:
207 # *NickName: "HP LaserJet 4 Plus v2013.111 Postscript (recommended)"
208 # *NickName: "Canon MG4100 series Ver.3.90"
209 # Find the version number and truncate at that point. But beware,
210 # other model names can legitimately look like version numbers,
211 # e.g. Epson PX V500.
212 # Truncate only if the version number has only one digit, or a dot
213 # with digits before and after.
214 modell = model.lower ()
215 v = modell.find (" v")
216 if v != -1:
217 # Look for " v" or " ver." followed by a digit, optionally
218 # followed by more digits, a dot, and more digits; and
219 # terminated by a space of the end of the line.
220 vmatch = _RE_version_numbers.search (modell)
221 if vmatch:
222 # Found it -- truncate at that point.
223 vstart = vmatch.start ()
224 modell = modell[:vstart]
225 model = model[:vstart]
226
227 suffix = _RE_ignore_suffix.search (modell)
228 if suffix:
229 suffixstart = suffix.start ()
230 modell = modell[:suffixstart]
231 model = model[:suffixstart]
232
233 # Remove the word "Series" if present. Some models are referred
234 # to as e.g. HP OfficeJet Series 300 (from hpcups, and in the
235 # Device IDs of such models), and other groups of models are
236 # referred to in drivers as e.g. Epson Stylus Color Series (CUPS).
237 (model, n) = _RE_ignore_series.subn ("", model, count=1)
238 if n:
239 modell = model.lower ()
240
241 if makel == "hp":
242 for name, fullname in _HP_MODEL_BY_NAME.items ():
243 if modell.startswith (name):
244 model = fullname + model[len (name):]
245 modell = model.lower ()
246 break
247
248 model = model.strip ()
249 return (make, model)
250
251 def normalize (strin):
252 """
253 This function normalizes manufacturer and model names for comparing.
254 The string is turned to lower case and leading and trailing white
255 space is removed. After that each sequence of non-alphanumeric
256 characters (including white space) is replaced by a single space and
257 also at each change between letters and numbers a single space is added.
258 This makes the comparison only done by alphanumeric characters and the
259 words formed from them. So mostly two strings which sound the same when
260 you pronounce them are considered equal. Printer manufacturers do not
261 market two models whose names sound the same but differ only by
262 upper/lower case, spaces, dashes, ..., but in printer drivers names can
263 be easily supplied with these details of the name written in the wrong
264 way, especially if the IEEE-1284 device ID of the printer is not known.
265 This way we get a very reliable matching of printer model names.
266 Examples:
267 - Epson PM-A820 -> epson pm a 820
268 - Epson PM A820 -> epson pm a 820
269 - HP PhotoSmart C 8100 -> hp photosmart c 8100
270 - hp Photosmart C8100 -> hp photosmart c 8100
271
272 @type strin: string that can be the make or the model
273 @return: a normalized lowercase string in which punctuations have been replaced with spaces.
274 """
275 lstrin = strin.strip ().lower ()
276 normalized = ""
277
278 BLANK=0
279 ALPHA=1
280 DIGIT=2
281 lastchar = BLANK
282
283 alnumfound = False
284 for i in range (len (lstrin)):
285 if lstrin[i].isalpha ():
286 if lastchar != ALPHA and alnumfound:
287 normalized += " ";
288 lastchar = ALPHA
289 elif lstrin[i].isdigit ():
290 if lastchar != DIGIT and alnumfound:
291 normalized += " ";
292 lastchar = DIGIT
293 else:
294 lastchar = BLANK
295
296 if lstrin[i].isalnum ():
297 normalized += lstrin[i]
298 alnumfound = True
299
300 return normalized
301
302 def _singleton (x):
303 """If we don't know whether getPPDs() or getPPDs2() was used, this
304 function can unwrap an item from a list in either case."""
305 if isinstance (x, list):
306 return x[0]
307 return x
308
309 class PPDs:
310 """
311 This class is for handling the list of PPDs returned by CUPS. It
312 indexes by PPD name and device ID, filters by natural language so
313 that foreign-language PPDs are not included, and sorts by driver
314 type. If an exactly-matching PPD is not available, it can
315 substitute with a PPD for a similar model or for a generic driver.
316 """
317
318 # Status of match.
319 STATUS_SUCCESS = 0
320 STATUS_MODEL_MISMATCH = 1
321 STATUS_GENERIC_DRIVER = 2
322 STATUS_NO_DRIVER = 3
323
324 FIT_EXACT_CMD = xmldriverprefs.DriverType.FIT_EXACT_CMD
325 FIT_EXACT = xmldriverprefs.DriverType.FIT_EXACT
326 FIT_CLOSE = xmldriverprefs.DriverType.FIT_CLOSE
327 FIT_GENERIC = xmldriverprefs.DriverType.FIT_GENERIC
328 FIT_NONE = xmldriverprefs.DriverType.FIT_NONE
329
330 _fit_to_status = { FIT_EXACT_CMD: STATUS_SUCCESS,
331 FIT_EXACT: STATUS_SUCCESS,
332 FIT_CLOSE: STATUS_MODEL_MISMATCH,
333 FIT_GENERIC: STATUS_GENERIC_DRIVER,
334 FIT_NONE: STATUS_NO_DRIVER }
335
336 def __init__ (self, ppds, language=None, xml_dir=None):
337 """
338 @type ppds: dict
339 @param ppds: dict of PPDs as returned by cups.Connection.getPPDs()
340 or cups.Connection.getPPDs2()
341
342 @type language: string
343 @param language: language name, as given by the first element
344 of the pair returned by locale.getlocale()
345 """
346 self.ppds = ppds.copy ()
347 self.makes = None
348 self.ids = None
349
350 self.drivertypes = xmldriverprefs.DriverTypes ()
351 self.preforder = xmldriverprefs.PreferenceOrder ()
352 if xml_dir is None:
353 xml_dir = os.environ.get ("CUPSHELPERS_XMLDIR")
354 if xml_dir is None:
355 from . import config
356 xml_dir = os.path.join (config.sysconfdir, "cupshelpers")
357
358 try:
359 xmlfile = os.path.join (xml_dir, "preferreddrivers.xml")
360 (drivertypes, preferenceorder) = \
361 xmldriverprefs.PreferredDrivers (xmlfile)
362 self.drivertypes.load (drivertypes)
363 self.preforder.load (preferenceorder)
364 except Exception as e:
365 print("Error loading %s: %s" % (xmlfile, e))
366 self.drivertypes = None
367 self.preforder = None
368
369 if (language is None or
370 language == "C" or
371 language == "POSIX"):
372 language = "en_US"
373
374 u = language.find ("_")
375 if u != -1:
376 short_language = language[:u]
377 else:
378 short_language = language
379
380 to_remove = []
381 for ppdname, ppddict in self.ppds.items ():
382 try:
383 natural_language = _singleton (ppddict['ppd-natural-language'])
384 except KeyError:
385 continue
386
387 if natural_language == "en":
388 # Some manufacturer's PPDs are only available in this
389 # language, so always let them though.
390 continue
391
392 if natural_language == language:
393 continue
394
395 if natural_language == short_language:
396 continue
397
398 to_remove.append (ppdname)
399
400 for ppdname in to_remove:
401 del self.ppds[ppdname]
402
403 # CUPS sets the 'raw' model's ppd-make-and-model to 'Raw Queue'
404 # which unfortunately then appears as manufacturer Raw and
405 # model Queue. Use 'Generic' for this model.
406 if 'raw' in self.ppds:
407 makemodel = _singleton (self.ppds['raw']['ppd-make-and-model'])
408 if not makemodel.startswith ("Generic "):
409 self.ppds['raw']['ppd-make-and-model'] = "Generic " + makemodel
410
411 def getMakes (self):
412 """
413 @returns: a list of strings representing makes, sorted according
414 to the current locale
415 """
416 self._init_makes ()
417 makes_list = list(self.makes.keys ())
418 makes_list.sort (key=locale.strxfrm)
419 try:
420 # "Generic" should be listed first.
421 makes_list.remove ("Generic")
422 makes_list.insert (0, "Generic")
423 except ValueError:
424 pass
425 return makes_list
426
427 def getModels (self, make):
428 """
429 @returns: a list of strings representing models, sorted using
430 cups.modelSort()
431 """
432 self._init_makes ()
433 try:
434 models_list = list(self.makes[make].keys ())
435 except KeyError:
436 return []
437
438 def compare_models (a,b):
439 first = normalize (a)
440 second = normalize (b)
441 return cups.modelSort(first, second)
442 models_list.sort(key=functools.cmp_to_key(compare_models))
443 return models_list
444
445 def getInfoFromModel (self, make, model):
446 """
447 Obtain a list of PPDs that are suitable for use with a
448 particular printer model, given its make and model name.
449
450 @returns: a dict, indexed by ppd-name, of dicts representing
451 PPDs (as given by cups.Connection.getPPDs)
452 """
453 self._init_makes ()
454 try:
455 return self.makes[make][model]
456 except KeyError:
457 return {}
458
459 def getInfoFromPPDName (self, ppdname):
460 """
461 @returns: a dict representing a PPD, as given by
462 cups.Connection.getPPDs
463 """
464 return self.ppds[ppdname]
465
466 def getStatusFromFit (self, fit):
467 return self._fit_to_status.get (fit, xmldriverprefs.DriverType.FIT_NONE)
468
469 def orderPPDNamesByPreference (self, ppdnamelist=None,
470 downloadedfiles=None,
471 make_and_model=None,
472 devid=None, fit=None):
473 """
474
475 Sort a list of PPD names by preferred driver type.
476
477 @param ppdnamelist: PPD names
478 @type ppdnamelist: string list
479 @param downloadedfiles: Filenames from packages downloaded
480 @type downloadedfiles: string list
481 @param make_and_model: device-make-and-model name
482 @type make_and_model: string
483 @param devid: Device ID dict
484 @type devid: dict indexed by Device ID field name, of strings;
485 except for CMD field which must be a string list
486 @param fit: Driver fit string for each PPD name
487 @type fit: dict of PPD name:fit
488 @returns: string list
489 """
490 if ppdnamelist is None:
491 ppdnamelist = []
492
493 if downloadedfiles is None:
494 downloadedfiles = []
495
496 if fit is None:
497 fit = {}
498
499 if self.drivertypes and self.preforder:
500 ppds = {}
501 for ppdname in ppdnamelist:
502 ppds[ppdname] = self.ppds[ppdname]
503
504 orderedtypes = self.preforder.get_ordered_types (self.drivertypes,
505 make_and_model,
506 devid)
507 _debugprint("Valid driver types for this printer in priority order: %s" % repr(orderedtypes))
508 orderedppds = self.drivertypes.get_ordered_ppdnames (orderedtypes,
509 ppds, fit)
510 _debugprint("PPDs with assigned driver types in priority order: %s" % repr(orderedppds))
511 ppdnamelist = [typ_name[1] for typ_name in orderedppds]
512 _debugprint("Resulting PPD list in priority order: %s" % repr(ppdnamelist))
513
514 # Special handling for files we've downloaded. First collect
515 # their basenames.
516 downloadedfnames = set()
517 for downloadedfile in downloadedfiles:
518 (path, slash, fname) = downloadedfile.rpartition ("/")
519 downloadedfnames.add (fname)
520
521 if downloadedfnames:
522 # Next compare the basenames of each ppdname
523 downloadedppdnames = []
524 for ppdname in ppdnamelist:
525 (path, slash, ppdfname) = ppdname.rpartition ("/")
526 if ppdfname in downloadedfnames:
527 downloadedppdnames.append (ppdname)
528
529 # Finally, promote the matching ones to the head of the list.
530 if downloadedppdnames:
531 for ppdname in ppdnamelist:
532 if ppdname not in downloadedppdnames:
533 downloadedppdnames.append (ppdname)
534
535 ppdnamelist = downloadedppdnames
536
537 return ppdnamelist
538
539 def getPPDNamesFromDeviceID (self, mfg, mdl, description="",
540 commandsets=None, uri=None,
541 make_and_model=None):
542 """
543 Obtain a best-effort PPD match for an IEEE 1284 Device ID.
544
545 @param mfg: MFG or MANUFACTURER field
546 @type mfg: string
547 @param mdl: MDL or MODEL field
548 @type mdl: string
549 @param description: DES or DESCRIPTION field, optional
550 @type description: string
551 @param commandsets: CMD or COMMANDSET field, optional
552 @type commandsets: string
553 @param uri: device URI, optional (only needed for debugging)
554 @type uri: string
555 @param make_and_model: device-make-and-model string
556 @type make_and_model: string
557 @returns: a dict of fit (string) indexed by PPD name
558 """
559 _debugprint ("\n%s %s" % (mfg, mdl))
560 orig_mfg = mfg
561 orig_mdl = mdl
562 self._init_ids ()
563
564 if commandsets is None:
565 commandsets = []
566
567 # Start with an empty result list and build it up using
568 # several search methods, in increasing order of fuzziness.
569 fit = {}
570
571 # First, try looking up the device using the manufacturer and
572 # model fields from the Device ID exactly as they appear (but
573 # case-insensitively).
574 mfgl = mfg.lower ()
575 mdll = mdl.lower ()
576
577 id_matched = False
578 try:
579 for each in self.ids[mfgl][mdll]:
580 fit[each] = self.FIT_EXACT
581 id_matched = True
582 except KeyError:
583 pass
584
585 # The HP PPDs say "HP" not "Hewlett-Packard", so try that.
586 if mfgl == "hewlett-packard":
587 try:
588 for each in self.ids["hp"][mdll]:
589 fit[each] = self.FIT_EXACT
590 _debugprint ("**** Incorrect IEEE 1284 Device ID: %s" %
591 self.ids["hp"][mdll])
592 _debugprint ("**** Actual ID is MFG:%s;MDL:%s;" % (mfg, mdl))
593 _debugprint ("**** Please report a bug against the HPLIP component")
594 id_matched = True
595 except KeyError:
596 pass
597
598 # Now try looking up the device by ppd-make-and-model.
599 _debugprint ("Trying make/model names")
600 mdls = None
601 self._init_makes ()
602 make = None
603 if mfgl == "":
604 (mfg, mdl) = ppdMakeModelSplit (mdl)
605 mfgl = normalize (mfg)
606 mdll = normalize (mdl)
607
608 _debugprint ("mfgl: %s" % mfgl)
609 _debugprint ("mdll: %s" % mdll)
610 mfgrepl = {"hewlett-packard": "hp",
611 "lexmark international": "lexmark",
612 "kyocera": "kyocera mita"}
613 if mfgl in self.lmakes:
614 # Found manufacturer.
615 make = self.lmakes[mfgl]
616 elif mfgl in mfgrepl:
617 rmfg = mfgrepl[mfgl]
618 if rmfg in self.lmakes:
619 mfg = rmfg
620 mfgl = mfg
621 # Found manufacturer (after mapping to canonical name)
622 _debugprint ("remapped mfgl: %s" % mfgl)
623 make = self.lmakes[mfgl]
624
625 _debugprint ("make: %s" % make)
626 if make is not None:
627 mdls = self.makes[make]
628 mdlsl = self.lmodels[normalize(make)]
629
630 # Remove manufacturer name from model field
631 for prefix in [mfgl, 'hewlett-packard', 'hp']:
632 if mdll.startswith (prefix + ' '):
633 mdl = mdl[len (prefix) + 1:]
634 mdll = normalize (mdl)
635 _debugprint ("unprefixed mdll: %s" % mdll)
636
637 if mdll in self.lmodels[mfgl]:
638 model = mdlsl[mdll]
639 for each in mdls[model].keys ():
640 fit[each] = self.FIT_EXACT
641 _debugprint ("%s: %s" % (fit[each], each))
642 else:
643 # Make use of the model name clean-up in the
644 # ppdMakeModelSplit () function
645 (mfg2, mdl2) = ppdMakeModelSplit (mfg + " " + mdl)
646 mdl2l = normalize (mdl2)
647 _debugprint ("re-split mdll: %s" % mdl2l)
648 if mdl2l in self.lmodels[mfgl]:
649 model = mdlsl[mdl2l]
650 for each in list(mdls[model].keys ()):
651 fit[each] = self.FIT_EXACT
652 _debugprint ("%s: %s" % (fit[each], each))
653
654 if not fit and mdls:
655 (s, ppds) = self._findBestMatchPPDs (mdls, mdl)
656 if s != self.FIT_NONE:
657 for each in ppds:
658 fit[each] = s
659 _debugprint ("%s: %s" % (fit[each], each))
660
661 if commandsets:
662 if type (commandsets) != list:
663 commandsets = commandsets.split (',')
664
665 _debugprint ("Checking CMD field")
666 generic = self._getPPDNameFromCommandSet (commandsets)
667 if generic:
668 for driver in generic:
669 fit[driver] = self.FIT_GENERIC
670 _debugprint ("%s: %s" % (fit[driver], driver))
671
672 # Check by the URI whether our printer is connected via IPP
673 # and if not, remove the PPD entries for driverless printing
674 # (ppdname = "driverless:..." from the list)
675 if (not uri or
676 (not uri.startswith("ipp:") and
677 not uri.startswith("ipps:") and
678 (not uri.startswith("dnssd") or
679 not "._ipp" in uri))):
680 failed = set()
681 for ppdname in fit.keys ():
682 if (ppdname.startswith("driverless:")):
683 failed.add (ppdname)
684 if (len(failed) > 0):
685 _debugprint ("Removed %s due to non-IPP connection" % failed)
686 for each in failed:
687 del fit[each]
688 failed = set()
689
690 # What about the CMD field of the Device ID? Some devices
691 # have optional units for page description languages, such as
692 # PostScript, and they will report different CMD strings
693 # accordingly.
694 #
695 # By convention, if a PPD contains a Device ID with a CMD
696 # field, that PPD can only be used whenever any of the
697 # comma-separated words in the CMD field appear in the
698 # device's ID.
699 # (See Red Hat bug #630058).
700 #
701 # We'll do that check now, and any PPDs that fail
702 # (e.g. PostScript PPD for non-PostScript printer) can be
703 # eliminated from the list.
704 #
705 # The reason we don't do this check any earlier is that we
706 # don't want to eliminate PPDs only to have the fuzzy matcher
707 # add them back in afterwards.
708 #
709 # While doing this, any drivers that we can positively confirm
710 # as using a command set understood by the printer will be
711 # converted from FIT_EXACT to FIT_EXACT_CMD.
712 if id_matched and len (commandsets) > 0:
713 failed = set()
714 exact_cmd = set()
715 for ppdname in fit.keys ():
716 ppd_cmd_field = None
717 ppd = self.ppds[ppdname]
718 ppd_device_id = _singleton (ppd.get ('ppd-device-id'))
719 if ppd_device_id:
720 ppd_device_id_dict = parseDeviceID (ppd_device_id)
721 ppd_cmd_field = ppd_device_id_dict["CMD"]
722
723 if (not ppd_cmd_field and
724 # ppd-type is not reliable for driver-generated
725 # PPDs (see CUPS STR #3720). Neither gutenprint
726 # nor foomatic specify ppd-type in their CUPS
727 # drivers.
728 ppdname.find (":") == -1):
729 # If this is a PostScript PPD we know which
730 # command set it will use.
731 ppd_type = _singleton (ppd.get ('ppd-type'))
732 if ppd_type == "postscript":
733 ppd_cmd_field = ["POSTSCRIPT"]
734
735 if not ppd_cmd_field:
736 # We can't be sure which command set this driver
737 # uses.
738 continue
739
740 usable = False
741 for pdl in ppd_cmd_field:
742 if pdl in commandsets:
743 usable = True
744 break
745
746 if usable:
747 exact_cmd.add (ppdname)
748 else:
749 failed.add (ppdname)
750
751 # Assign the more specific fit "exact-cmd" to those that
752 # positively matched the CMD field.
753 for each in exact_cmd:
754 if fit[each] == self.FIT_EXACT:
755 fit[each] = self.FIT_EXACT_CMD
756 _debugprint (self.FIT_EXACT_CMD + ": %s" % each)
757
758 if len (failed) < len ([d for (d, m) in fit.items ()
759 if m != 'generic']):
760 _debugprint ("Removed %s due to CMD mis-match" % failed)
761 for each in failed:
762 del fit[each]
763 else:
764 _debugprint ("Not removing %s " % failed +
765 "due to CMD mis-match as it would "
766 "leave nothing good")
767
768 if not fit:
769 fallbacks = ["textonly.ppd", "postscript.ppd"]
770 found = False
771 for fallback in fallbacks:
772 _debugprint ("'%s' fallback" % fallback)
773 fallbackgz = fallback + ".gz"
774 for ppdpath in self.ppds.keys ():
775 if (ppdpath.endswith (fallback) or
776 ppdpath.endswith (fallbackgz)):
777 fit[ppdpath] = self.FIT_NONE
778 found = True
779 break
780
781 if found:
782 break
783
784 _debugprint ("Fallback '%s' not available" % fallback)
785
786 if not found:
787 _debugprint ("No fallback available; choosing any")
788 fit[list(self.ppds.keys ())[0]] = self.FIT_NONE
789
790 if not id_matched:
791 sanitised_uri = re.sub (pattern="//[^@]*@/?", repl="//",
792 string=str (uri))
793 try:
794 cmd = reduce (lambda x, y: x + ","+ y, commandsets)
795 except TypeError:
796 cmd = ""
797 id = "MFG:%s;MDL:%s;" % (orig_mfg, orig_mdl)
798 if cmd:
799 id += "CMD:%s;" % cmd
800 if description:
801 id += "DES:%s;" % description
802
803 _debugprint ("No ID match for device %s:" % sanitised_uri)
804 _debugprint (id)
805
806 return fit
807
808 def getPPDNameFromDeviceID (self, mfg, mdl, description="",
809 commandsets=None, uri=None,
810 downloadedfiles=None,
811 make_and_model=None):
812 """
813 Obtain a best-effort PPD match for an IEEE 1284 Device ID.
814 The status is one of:
815
816 - L{STATUS_SUCCESS}: the match was successful, and an exact
817 match was found
818
819 - L{STATUS_MODEL_MISMATCH}: a similar match was found, but
820 the model name does not exactly match
821
822 - L{STATUS_GENERIC_DRIVER}: no match was found, but a
823 generic driver is available that can drive this device
824 according to its command set list
825
826 - L{STATUS_NO_DRIVER}: no match was found at all, and the
827 returned PPD name is a last resort
828
829 @param mfg: MFG or MANUFACTURER field
830 @type mfg: string
831 @param mdl: MDL or MODEL field
832 @type mdl: string
833 @param description: DES or DESCRIPTION field, optional
834 @type description: string
835 @param commandsets: CMD or COMMANDSET field, optional
836 @type commandsets: string
837 @param uri: device URI, optional (only needed for debugging)
838 @type uri: string
839 @param downloadedfiles: filenames from downloaded packages
840 @type downloadedfiles: string list
841 @param make_and_model: device-make-and-model string
842 @type make_and_model: string
843 @returns: an integer,string pair of (status,ppd-name)
844 """
845
846 if commandsets is None:
847 commandsets = []
848
849 if downloadedfiles is None:
850 downloadedfiles = []
851
852 fit = self.getPPDNamesFromDeviceID (mfg, mdl, description,
853 commandsets, uri,
854 make_and_model)
855
856 # We've got a set of PPDs, any of which will drive the device.
857 # Now we have to choose the "best" one. This is quite tricky
858 # to decide, so let's sort them in order of preference and
859 # take the first.
860 devid = { "MFG": mfg, "MDL": mdl,
861 "DES": description,
862 "CMD": commandsets }
863 ppdnamelist = self.orderPPDNamesByPreference (list(fit.keys ()),
864 downloadedfiles,
865 make_and_model,
866 devid, fit)
867 _debugprint ("Found PPDs: %s" % str (ppdnamelist))
868
869 status = self.getStatusFromFit (fit[ppdnamelist[0]])
870 _debugprint ("Using %s (status: %d)" % (ppdnamelist[0], status))
871 return (status, ppdnamelist[0])
872
873 def _findBestMatchPPDs (self, mdls, mdl):
874 """
875 Find the best-matching PPDs based on the MDL Device ID.
876 This function could be made a lot smarter.
877 """
878
879 _debugprint ("Trying best match")
880 mdll = mdl.lower ()
881 if mdll.endswith (" series"):
882 # Strip " series" from the end of the MDL field.
883 mdll = mdll[:-7]
884 mdl = mdl[:-7]
885 best_mdl = None
886 best_matchlen = 0
887 mdlnames = list(mdls.keys ())
888
889 # Perform a case-insensitive model sort on the names.
890 mdlnamesl = [(x, x.lower()) for x in mdlnames]
891 mdlnamesl.append ((mdl, mdll))
892 mdlnamesl.sort (key=functools.cmp_to_key(lambda x, y: cups.modelSort(x[1], y[1])))
893 i = mdlnamesl.index ((mdl, mdll))
894 candidates = [mdlnamesl[i - 1]]
895 if i + 1 < len (mdlnamesl):
896 candidates.append (mdlnamesl[i + 1])
897 _debugprint (candidates[0][0] + " <= " + mdl + " <= " +
898 candidates[1][0])
899 else:
900 _debugprint (candidates[0][0] + " <= " + mdl)
901
902 # Look at the models immediately before and after ours in the
903 # sorted list, and pick the one with the longest initial match.
904 for (candidate, candidatel) in candidates:
905 prefix = os.path.commonprefix ([candidatel, mdll])
906 if len (prefix) > best_matchlen:
907 best_mdl = list(mdls[candidate].keys ())
908 best_matchlen = len (prefix)
909 _debugprint ("%s: match length %d" % (candidate, best_matchlen))
910
911 # Did we match more than half of the model name?
912 if best_mdl and best_matchlen > (len (mdll) / 2):
913 ppdnamelist = best_mdl
914 if best_matchlen == len (mdll):
915 fit = self.FIT_EXACT
916 else:
917 fit = self.FIT_CLOSE
918 else:
919 fit = self.FIT_NONE
920 ppdnamelist = None
921
922 # Last resort. Find the "most important" word in the MDL
923 # field and look for a match based solely on that. If
924 # there are digits, try lowering the number of
925 # significant figures.
926 mdlnames.sort (key=functools.cmp_to_key(cups.modelSort))
927 mdlitems = [(x.lower (), mdls[x]) for x in mdlnames]
928 modelid = None
929 for word in mdll.split (' '):
930 if modelid is None:
931 modelid = word
932
933 have_digits = False
934 for i in range (len (word)):
935 if word[i].isdigit ():
936 have_digits = True
937 break
938
939 if have_digits:
940 modelid = word
941 break
942
943 digits = 0
944 digits_start = -1
945 digits_end = -1
946 for i in range (len (modelid)):
947 if modelid[i].isdigit ():
948 if digits_start == -1:
949 digits_start = i
950 digits_end = i
951 digits += 1
952 elif digits_start != -1:
953 break
954 digits_end += 1
955 modelnumber = 0
956 if digits > 0:
957 modelnumber = int (modelid[digits_start:digits_end])
958 modelpattern = (modelid[:digits_start] + "%d" +
959 modelid[digits_end:])
960 _debugprint ("Searching for model ID '%s', '%s' %% %d" %
961 (modelid, modelpattern, modelnumber))
962 ignore_digits = 0
963 best_mdl = None
964 found = False
965 while ignore_digits < digits:
966 div = pow (10, ignore_digits)
967 modelid = modelpattern % ((modelnumber / div) * div)
968 _debugprint ("Ignoring %d of %d digits, trying %s" %
969 (ignore_digits, digits, modelid))
970
971 for (name, ppds) in mdlitems:
972 for word in name.split (' '):
973 if word.lower () == modelid:
974 found = True
975 break
976
977 if found:
978 best_mdl = list(ppds.keys ())
979 break
980
981 if found:
982 break
983
984 ignore_digits += 1
985 if digits < 2:
986 break
987
988 if found:
989 ppdnamelist = best_mdl
990 fit = self.FIT_CLOSE
991
992 return (fit, ppdnamelist)
993
994 def _getPPDNameFromCommandSet (self, commandsets=None):
995 """Return ppd-name list or None, given a list of strings representing
996 the command sets supported."""
997
998 if commandsets is None:
999 commandsets = []
1000
1001 try:
1002 self._init_makes ()
1003 models = self.makes["Generic"]
1004 except KeyError:
1005 return None
1006
1007 def get (*candidates):
1008 for model in candidates:
1009 (s, ppds) = self._findBestMatchPPDs (models, model)
1010 if s == self.FIT_EXACT:
1011 return ppds
1012 return None
1013
1014 cmdsets = [x.lower () for x in commandsets]
1015 if (("postscript" in cmdsets) or ("postscript2" in cmdsets) or
1016 ("postscript level 2 emulation" in cmdsets)):
1017 return get ("PostScript")
1018 elif (("pclxl" in cmdsets) or ("pcl-xl" in cmdsets) or
1019 ("pcl6" in cmdsets) or ("pcl 6 emulation" in cmdsets)):
1020 return get ("PCL 6/PCL XL", "PCL Laser")
1021 elif "pcl5e" in cmdsets:
1022 return get ("PCL 5e", "PCL Laser")
1023 elif "pcl5c" in cmdsets:
1024 return get ("PCL 5c", "PCL Laser")
1025 elif ("pcl5" in cmdsets) or ("pcl 5 emulation" in cmdsets):
1026 return get ("PCL 5", "PCL Laser")
1027 elif "pcl" in cmdsets:
1028 return get ("PCL 3", "PCL Laser")
1029 elif (("escpl2" in cmdsets) or ("esc/p2" in cmdsets) or
1030 ("escp2e" in cmdsets)):
1031 return get ("ESC/P Dot Matrix")
1032 return None
1033
1034 def _init_makes (self):
1035 if self.makes:
1036 return
1037
1038 tstart = time.time ()
1039 makes = {}
1040 lmakes = {}
1041 lmodels = {}
1042 aliases = {} # Generic model name: set(specific model names)
1043 for ppdname, ppddict in self.ppds.items ():
1044 # One entry for ppd-make-and-model
1045 ppd_make_and_model = _singleton (ppddict['ppd-make-and-model'])
1046 ppd_mm_split = ppdMakeModelSplit (ppd_make_and_model)
1047 ppd_makes_and_models = set([ppd_mm_split])
1048
1049 # The ppd-product IPP attribute contains values from each
1050 # Product PPD attribute as well as the value from the
1051 # ModelName attribute if present. The Product attribute
1052 # values are surrounded by parentheses; the ModelName
1053 # attribute value is not.
1054
1055 # Add another entry for each ppd-product that came from a
1056 # Product attribute in the PPD file.
1057 ppd_products = ppddict.get ('ppd-product', [])
1058 if not isinstance (ppd_products, list):
1059 ppd_products = [ppd_products]
1060 ppd_products = set ([x for x in ppd_products if x.startswith ("(")])
1061 if ppd_products:
1062 # If there is only one ppd-product value it is
1063 # unlikely to be useful.
1064 if len (ppd_products) == 1:
1065 ppd_products = set()
1066
1067 make = _singleton (ppddict.get ('ppd-make', '')).rstrip ()
1068 if make:
1069 make += ' '
1070 lmake = normalize (make)
1071 for ppd_product in ppd_products:
1072 # *Product: attribute is "(text)"
1073 if (ppd_product.startswith ("(") and
1074 ppd_product.endswith (")")):
1075 ppd_product = ppd_product[1:len (ppd_product) - 1]
1076
1077 if not ppd_product:
1078 continue
1079
1080 # If manufacturer name missing, take it from ppd-make
1081 lprod = normalize (ppd_product)
1082 if not lprod.startswith (lmake):
1083 ppd_product = make + ppd_product
1084
1085 ppd_makes_and_models.add (ppdMakeModelSplit (ppd_product))
1086
1087 # Add the entries to our dictionary
1088 for make, model in ppd_makes_and_models:
1089 lmake = normalize (make)
1090 lmodel = normalize (model)
1091 if lmake not in lmakes:
1092 lmakes[lmake] = make
1093 lmodels[lmake] = {}
1094 makes[make] = {}
1095 else:
1096 make = lmakes[lmake]
1097
1098 if lmodel not in lmodels[lmake]:
1099 lmodels[lmake][lmodel] = model
1100 makes[make][model] = {}
1101 else:
1102 model = lmodels[lmake][lmodel]
1103
1104 makes[make][model][ppdname] = ppddict
1105
1106 # Build list of model aliases
1107 if ppd_mm_split in ppd_makes_and_models:
1108 ppd_makes_and_models.remove (ppd_mm_split)
1109
1110 if ppd_makes_and_models:
1111 (make, model) = ppd_mm_split
1112 if make in aliases:
1113 models = aliases[make].get (model, set())
1114 else:
1115 aliases[make] = {}
1116 models = set()
1117
1118 models = models.union ([x[1] for x in ppd_makes_and_models])
1119 aliases[make][model] = models
1120
1121 # Now, for each set of model aliases, add all drivers from the
1122 # "main" (generic) model name to each of the specific models.
1123 for make, models in aliases.items ():
1124 lmake = normalize (make)
1125 main_make = lmakes[lmake]
1126 for model, modelnames in models.items ():
1127 main_model = lmodels[lmake].get (normalize (model))
1128 if not main_model:
1129 continue
1130
1131 main_ppds = makes[main_make][main_model]
1132
1133 for eachmodel in modelnames:
1134 this_model = lmodels[lmake].get (normalize (eachmodel))
1135 ppds = makes[main_make][this_model]
1136 ppds.update (main_ppds)
1137
1138 self.makes = makes
1139 self.lmakes = lmakes
1140 self.lmodels = lmodels
1141 _debugprint ("init_makes: %.3fs" % (time.time () - tstart))
1142
1143 def _init_ids (self):
1144 if self.ids:
1145 return
1146
1147 ids = {}
1148 for ppdname, ppddict in self.ppds.items ():
1149 id = _singleton (ppddict.get ('ppd-device-id'))
1150 if not id:
1151 continue
1152
1153 id_dict = parseDeviceID (id)
1154 lmfg = id_dict['MFG'].lower ()
1155 lmdl = id_dict['MDL'].lower ()
1156
1157 bad = False
1158 if len (lmfg) == 0:
1159 bad = True
1160 if len (lmdl) == 0:
1161 bad = True
1162 if bad:
1163 continue
1164
1165 if lmfg not in ids:
1166 ids[lmfg] = {}
1167
1168 if lmdl not in ids[lmfg]:
1169 ids[lmfg][lmdl] = []
1170
1171 ids[lmfg][lmdl].append (ppdname)
1172
1173 self.ids = ids
1174
1175 def _show_help():
1176 print ("usage: ppds.py [--deviceid] [--list-models] [--list-ids] [--debug]")