~ubuntu-branches/ubuntu/lucid/system-config-printer/lucid-proposed

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
#!/bin/bash
shopt -s execfail
exec -a "$0" python -- "$@" <(tail -n +4 -- "$0") || exit 0 # -*- python -*-

## Copyright (C) 2009 Red Hat, Inc.
## Author: Tim Waugh <twaugh@redhat.com>

## 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., 675 Mass Ave, Cambridge, MA 02139, USA.

import sys

try:
    import cups
    CAN_EXAMINE_PPDS=True
except:
    CAN_EXAMINE_PPDS=False

from getopt import getopt
import os
import posix
import re
import shlex
import signal
import stat
import subprocess
import sys
import tempfile

class TimedOut(Exception):
    def __init__ (self):
        Exception.__init__ (self, "Timed out")

class DeviceIDs:
    def __init__ (self):
        self.ids = dict()

    def get_dict (self):
        return self.ids

    def get_tags (self):
        ret = []
        def squash(x):
            r = x.lower ()
            for a in [' ', '(', ')']:
                r = r.replace (a, '_')

            return r

        for mfg, mdlset in self.ids.iteritems ():
            mfgsquash = squash (mfg)
            for mdl in mdlset:
                mdlsquash = squash (mdl)
                ret.append ("postscriptdriver(%s;%s;)" % (mfgsquash,
                                                          mdlsquash))

        return ret

    def __add__ (self, other):
        if isinstance(other, DeviceIDs):
            for omfg, omdlset in other.ids.iteritems ():
                try:
                    mdlset = self.ids[omfg]
                except KeyError:
                    mdlset = set()
                    self.ids[omfg] = mdlset

                mdlset.update (omdlset)

            return self

        pieces = other.split (';')
        mfg = mdl = None
        for piece in pieces:
            s = piece.split (":")
            if len (s) != 2:
                continue
            key, value = s
            key = key.upper ()
            if key in ["MFG", "MANUFACTURER"]:
                mfg = value
            elif key in ["MDL", "MODEL"]:
                mdl = value

        if mfg and mdl:
            try:
                mdlset = self.ids[mfg]
            except KeyError:
                mdlset = set()
                self.ids[mfg] = mdlset

            mdlset.add (mdl)

        return self

class Driver:
    def __init__ (self):
        self.ids = DeviceIDs()

    def list (self):
        return self.ids

class PPDDriver(Driver):
    def __init__ (self, pathname=None):
        Driver.__init__ (self)
        self.pathname = pathname

    def list (self):
        if self.pathname != None:
            self.examine_file (self.pathname)

        return Driver.list (self)

    def examine_file (self, path):
        try:
            ppd = cups.PPD (path)
        except RuntimeError, e:
            # Not a PPD file.  Perhaps it's a drv file.
            drv = DrvDriver (path)
            self.ids += drv.list ()
            return

        attr = ppd.findAttr ('1284DeviceID')
        if attr:
            self.ids += attr.value

class DynamicDriver(Driver):
    def __init__ (self, driver):
        Driver.__init__ (self)
        self.driver = driver
        signal.signal (signal.SIGALRM, self._alarm)

    def _alarm (self, sig, stack):
        raise TimedOut

    def list (self):
        signal.alarm (60)
        p = subprocess.Popen ([self.driver, "list"],
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        try:
            (stdout, stderr) = p.communicate ()
            signal.alarm (0)
        except TimedOut:
            posix.kill (p.pid, signal.SIGKILL)
            raise

	if stderr:
		print >> sys.stderr, stderr

	ppds = []
	lines = stdout.split ('\n')
	for line in lines:
		l = shlex.split (line)
		if len (l) < 5:
                    continue
                self.ids += l[4]

        return Driver.list (self)

class DrvDriver(PPDDriver):
    def __init__ (self, pathname):
        PPDDriver.__init__ (self)
        self.drv = pathname

    def _alarm (self, sig, stack):
        raise TimedOut

    def list (self):
        tmpdir = os.environ.get ("TMPDIR", "/tmp") + os.path.sep
        outputdir = tempfile.mkdtemp (dir=tmpdir)
        
        argv = [ "ppdc",
                 "-d", outputdir,
                 "-I", "/usr/share/cups/ppdc",
                 self.drv ]

        signal.alarm (60)
        p = subprocess.Popen (argv,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        try:
            (stdout, stderr) = p.communicate ()
            signal.alarm (0)
        except TimedOut:
            posix.kill (p.pid, signal.SIGKILL)
            raise

        os.path.walk (outputdir, self.examine_directory, None)
        os.rmdir (outputdir)
        return Driver.list (self)

    def examine_directory (self, unused, dirname, fnames):
        for fname in fnames:
            path = dirname + os.path.sep + fname
            self.examine_file (path)
            os.unlink (path)

class TagBuilder:
    def __init__ (self, filelist=None):
        if filelist == None:
            filelist = sys.stdin

        paths = map (lambda x: x.rstrip (), filelist.readlines ())
        self.ids = DeviceIDs ()

        for path in paths:
            if path.find ("/usr/lib/cups/driver/") != -1:
                try:
                    self.ids += DynamicDriver (path).list ()
                except TimedOut:
                    pass

        if CAN_EXAMINE_PPDS:
            candidates = set()
            symlinks = set()
            for searchpath in ["/usr/share/cups/model/",
                               "/usr/share/ppd/",
                               "/usr/share/cups/drv/"]:
                for path in paths:
                    if path.find (searchpath) != -1:
                        st = os.lstat (path)
                        if stat.S_ISLNK (st.st_mode):
                            symlinks.add (path)
                        elif stat.S_ISREG (st.st_mode):
                            candidates.add (path)

            # Now check for symlinks (just one level)
            for each in symlinks:
                target = os.path.realpath (each)
                if target in candidates:
                    continue

                try:
                    st = os.lstat (target)
                except OSError:
                    continue

                if stat.S_ISREG (st.st_mode):
                    candidates.add (target)
                elif stat.S_ISDIR (st.st_mode):
                    if not target.endswith (os.path.sep):
                        target += os.path.sep

                    for path in paths:
                        if path.find (target) != -1:
                            st = os.lstat (path)
                            if stat.S_ISREG (st.st_mode):
                                candidates.add (path)

            for path in candidates:
                try:
                    self.ids += PPDDriver (path).list ()
                except TimedOut:
                    pass

    def get_tags (self):
        return self.ids.get_tags ()

if __name__ == "__main__":
    builder = TagBuilder ()
    tags = builder.get_tags ()
    for tag in tags:
        print tag