root / pykota / trunk / pykota / pdlanalyzer.py @ 1981

Revision 1981, 43.0 kB (checked in by jalet, 19 years ago)

Outputs debug info to stderr

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.46  2004/12/13 20:48:33  jalet
25# Outputs debug info to stderr
26#
27# Revision 1.45  2004/12/13 20:39:46  jalet
28# Added a --debug command line option to pkpgcounter, for people interested
29# in seeing what happens, and what will be available in the future :-)
30#
31# Revision 1.44  2004/11/17 15:10:31  jalet
32# Fixed Epson Stylus Photo problem in software accounting
33#
34# Revision 1.43  2004/11/13 20:52:26  jalet
35# Heavy work done on PCL3/4/5 and PCLXL job analyzis
36#
37# Revision 1.42  2004/09/24 21:19:48  jalet
38# Did a pass of PyChecker
39#
40# Revision 1.41  2004/09/04 14:18:55  jalet
41# Support for more laserjet models added.
42#
43# Revision 1.40  2004/09/04 14:01:47  jalet
44# Support for PCL3 (HP Deskjets) added to generic PDL parser
45#
46# Revision 1.39  2004/09/02 23:30:05  jalet
47# Comments
48#
49# Revision 1.38  2004/09/02 22:08:37  jalet
50# First draft of PCL3GUI analyzer.
51#
52# Revision 1.37  2004/09/02 21:22:49  jalet
53# One more PCL tag
54#
55# Revision 1.36  2004/09/01 22:31:49  jalet
56# Some more work on ESC/P2 analyzer to avoid missing \r\n sequences. Not
57# exactly optimal though...
58#
59# Revision 1.35  2004/08/30 23:10:24  jalet
60# Improved the ESC/P2 analyzer so that more GhostScript devices are supported
61#
62# Revision 1.34  2004/08/27 09:08:22  jalet
63# Improvement in PostScript parser to avoid being fooled by clever "students"
64#
65# Revision 1.33  2004/08/27 09:02:34  jalet
66# Forgot to remove some special debugging code...
67#
68# Revision 1.32  2004/08/27 08:58:50  jalet
69# Relax checks for PCL5 header to accomodate strange printer drivers
70#
71# Revision 1.31  2004/08/22 08:25:33  jalet
72# Improved ESC/P2 miniparser thanks to Paulo Silva
73#
74# Revision 1.30  2004/08/21 23:16:57  jalet
75# First draft of ESC/P2 (mini-)parser.
76#
77# Revision 1.29  2004/08/11 16:25:38  jalet
78# Fixed index problem in PCLXL parser when retrieving number of copies for
79# each page
80#
81# Revision 1.28  2004/08/10 23:01:49  jalet
82# Fixed number of copies in PCL5 parser
83#
84# Revision 1.27  2004/08/09 18:14:22  jalet
85# Added workaround for number of copies and some PostScript drivers
86#
87# Revision 1.26  2004/07/22 13:49:51  jalet
88# Added support for binary PostScript through GhostScript if native DSC
89# compliant PostScript analyzer doesn't find any page. This is much
90# slower though, so native analyzer is tried first.
91#
92# Revision 1.25  2004/07/10 14:06:36  jalet
93# Fix for Python2.1 incompatibilities
94#
95# Revision 1.24  2004/07/05 21:00:39  jalet
96# Fix for number of copies for each page in PCLXL parser
97#
98# Revision 1.23  2004/07/03 08:21:59  jalet
99# Testsuite for PDL Analyzer added
100#
101# Revision 1.22  2004/06/29 14:21:41  jalet
102# Smallish optimization
103#
104# Revision 1.21  2004/06/28 23:11:26  jalet
105# Code de-factorization in PCLXL parser
106#
107# Revision 1.20  2004/06/28 22:38:41  jalet
108# Increased speed by a factor of 2 in PCLXL parser
109#
110# Revision 1.19  2004/06/28 21:20:30  jalet
111# PCLXL support now works !
112#
113# Revision 1.18  2004/06/27 22:59:37  jalet
114# More work on PCLXL parser
115#
116# Revision 1.17  2004/06/26 23:20:01  jalet
117# Additionnal speedup for GhostScript generated PCL5 files
118#
119# Revision 1.16  2004/06/26 15:31:00  jalet
120# mmap reintroduced in PCL5 parser
121#
122# Revision 1.15  2004/06/26 14:14:31  jalet
123# Now uses Psyco if it is available
124#
125# Revision 1.14  2004/06/25 09:50:28  jalet
126# More debug info in PCLXL parser
127#
128# Revision 1.13  2004/06/25 08:10:08  jalet
129# Another fix for PCL5 parser
130#
131# Revision 1.12  2004/06/24 23:09:53  jalet
132# Fix for number of copies in PCL5 parser
133#
134# Revision 1.11  2004/06/23 22:07:50  jalet
135# Fixed PCL5 parser according to the sources of rastertohp
136#
137# Revision 1.10  2004/06/18 22:24:03  jalet
138# Removed old comments
139#
140# Revision 1.9  2004/06/18 22:21:27  jalet
141# Native PDF parser greatly improved.
142# GhostScript based PDF parser completely removed because native code
143# is now portable across Python versions.
144#
145# Revision 1.8  2004/06/18 20:49:46  jalet
146# "ERROR:" prefix added
147#
148# Revision 1.7  2004/06/18 17:48:04  jalet
149# Added native fast PDF parsing method
150#
151# Revision 1.6  2004/06/18 14:00:16  jalet
152# Added PDF support in smart PDL analyzer (through GhostScript for now)
153#
154# Revision 1.5  2004/06/18 10:09:05  jalet
155# Resets file pointer to start of file in all cases
156#
157# Revision 1.4  2004/06/18 06:16:14  jalet
158# Fixes PostScript detection code for incorrect drivers
159#
160# Revision 1.3  2004/05/21 20:40:08  jalet
161# All the code for pkpgcounter is now in pdlanalyzer.py
162#
163# Revision 1.2  2004/05/19 19:09:36  jalet
164# Speed improvement
165#
166# Revision 1.1  2004/05/18 09:59:54  jalet
167# pkpgcounter is now just a wrapper around the PDLAnalyzer class
168#
169#
170#
171
172import sys
173import os
174import re
175from struct import unpack
176import tempfile
177import mmap
178import popen2
179   
180KILOBYTE = 1024   
181MEGABYTE = 1024 * KILOBYTE   
182LASTBLOCKSIZE = int(KILOBYTE / 4)
183
184class PDLAnalyzerError(Exception):
185    """An exception for PDL Analyzer related stuff."""
186    def __init__(self, message = ""):
187        self.message = message
188        Exception.__init__(self, message)
189    def __repr__(self):
190        return self.message
191    __str__ = __repr__
192   
193class PostScriptAnalyzer :
194    """A class to parse PostScript documents."""
195    def __init__(self, infile, debug=0) :
196        """Initialize PostScript Analyzer."""
197        self.debug = debug
198        self.infile = infile
199        self.copies = 1
200       
201    def throughGhostScript(self) :
202        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
203        if self.debug :
204            sys.stderr.write("Internal parser sucks, using GhostScript instead...\n")
205        self.infile.seek(0)
206        command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
207        child = popen2.Popen4(command)
208        try :
209            data = self.infile.read(MEGABYTE)   
210            while data :
211                child.tochild.write(data)
212                data = self.infile.read(MEGABYTE)
213            child.tochild.flush()
214            child.tochild.close()   
215        except (IOError, OSError), msg :   
216            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg
217           
218        pagecount = 0
219        try :
220            pagecount = int(child.fromchild.readline().strip())
221        except (IOError, OSError, AttributeError, ValueError), msg :
222            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg
223        child.fromchild.close()
224       
225        try :
226            child.wait()
227        except OSError, msg :   
228            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg
229        return pagecount * self.copies
230       
231    def natively(self) :
232        """Count pages in a DSC compliant PostScript document."""
233        self.infile.seek(0)
234        pagecount = 0
235        for line in self.infile.xreadlines() : 
236            if line.startswith("%%Page: ") :
237                pagecount += 1
238            elif line.startswith("%%BeginNonPPDFeature: NumCopies ") :
239                # handle # of copies set by some Windows printer driver
240                try :
241                    number = int(line.strip().split()[2])
242                except :     
243                    pass
244                else :   
245                    if number > self.copies :
246                        self.copies = number
247            elif line.startswith("1 dict dup /NumCopies ") :
248                # handle # of copies set by mozilla/kprinter
249                try :
250                    number = int(line.strip().split()[4])
251                except :     
252                    pass
253                else :   
254                    if number > self.copies :
255                        self.copies = number
256        return pagecount * self.copies
257       
258    def getJobSize(self) :   
259        """Count pages in PostScript document."""
260        return self.natively() or self.throughGhostScript()
261       
262class PDFAnalyzer :
263    """A class to parse PDF documents."""
264    def __init__(self, infile, debug=0) :
265        """Initialize PDF Analyzer."""
266        self.debug = debug
267        self.infile = infile
268               
269    def getJobSize(self) :   
270        """Counts pages in a PDF document."""
271        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
272        pagecount = 0
273        for line in self.infile.xreadlines() : 
274            pagecount += len(regexp.findall(line))
275        return pagecount   
276       
277class ESCP2Analyzer :
278    """A class to parse ESC/P2 documents."""
279    def __init__(self, infile, debug=0) :
280        """Initialize ESC/P2 Analyzer."""
281        self.debug = debug
282        self.infile = infile
283               
284    def getJobSize(self) :   
285        """Counts pages in an ESC/P2 document."""
286        # with Gimpprint, at least, for each page there
287        # are two Reset Printer sequences (ESC + @)
288        marker1 = "\033@"
289       
290        # with other software or printer driver, we
291        # may prefer to search for "\r\n\fESCAPE"
292        # or "\r\fESCAPE"
293        marker2r = "\r\f\033"
294        marker2rn = "\r\n\f\033"
295       
296        # and ghostscript's stcolor for example seems to
297        # output ESC + @ + \f for each page plus one
298        marker3 = "\033@\f"
299       
300        # while ghostscript's escp driver outputs instead
301        # \f + ESC + @
302        marker4 = "\f\033@"
303       
304        data = self.infile.read()
305        pagecount1 = data.count(marker1)
306        pagecount2 = max(data.count(marker2r), data.count(marker2rn))
307        pagecount3 = data.count(marker3)
308        pagecount4 = data.count(marker4)
309           
310        if pagecount2 :   
311            return pagecount2
312        elif pagecount3 > 1 :     
313            return pagecount3 - 1
314        elif pagecount4 :   
315            return pagecount4
316        else :   
317            return int(pagecount1 / 2)       
318       
319class PCLAnalyzer :
320    """A class to parse PCL3, PCL4, PCL5 documents."""
321    mediasizes = {  # ESC&l####A
322                    0 : "Default",
323                    1 : "Executive",
324                    2 : "Letter",
325                    3 : "Legal",
326                    6 : "Ledger", 
327                    25 : "A5",
328                    26 : "A4",
329                    27 : "A3",
330                    45 : "JB5",
331                    46 : "JB4",
332                    71 : "HagakiPostcard",
333                    72 : "OufukuHagakiPostcard",
334                    80 : "MonarchEnvelope",
335                    81 : "COM10Envelope",
336                    90 : "DLEnvelope",
337                    91 : "C5Envelope",
338                    100 : "B5Envelope",
339                    101 : "Custom",
340                 }   
341                 
342    mediasources = { # ESC&l####H
343                     0 : "Default",
344                     1 : "Main",
345                     2 : "Manual",
346                     3 : "ManualEnvelope",
347                     4 : "Alternate",
348                     5 : "OptionalLarge",
349                     6 : "EnvelopeFeeder",
350                     7 : "Auto",
351                     8 : "Tray1",
352                   }
353                   
354    orientations = { # ESC&l####O
355                     0 : "Portrait",
356                     1 : "Landscape",
357                     2 : "ReversePortrait",
358                     3 : "ReverseLandscape",
359                   }
360                   
361    mediatypes = { # ESC&l####M
362                     0 : "Plain",
363                     1 : "Bond",
364                     2 : "Special",
365                     3 : "Glossy",
366                     4 : "Transparent",
367                   }
368                   
369                   
370    def __init__(self, infile, debug=0) :
371        """Initialize PCL Analyzer."""
372        self.debug = debug
373        self.infile = infile
374       
375    def setPageDict(self, pages, number, attribute, value) :
376        """Initializes a page dictionnary."""
377        dict = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})
378        dict[attribute] = value
379       
380    def getJobSize(self) :     
381        """Count pages in a PCL5 document.
382         
383           Should also work for PCL3 and PCL4 documents.
384           
385           Algorithm from pclcount
386           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
387           published under the terms of the GNU General Public Licence v2.
388         
389           Backported from C to Python by Jerome Alet, then enhanced
390           with more PCL tags detected. I think all the necessary PCL tags
391           are recognized to correctly handle PCL5 files wrt their number
392           of pages. The documentation used for this was :
393         
394           HP PCL/PJL Reference Set
395           PCL5 Printer Language Technical Quick Reference Guide
396           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
397        """
398        infileno = self.infile.fileno()
399        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
400        tagsends = { "&n" : "W", 
401                     "&b" : "W", 
402                     "*i" : "W", 
403                     "*l" : "W", 
404                     "*m" : "W", 
405                     "*v" : "W", 
406                     "*c" : "W", 
407                     "(f" : "W", 
408                     "(s" : "W", 
409                     ")s" : "W", 
410                     "&p" : "X", 
411                     # "&l" : "XHAOM",  # treated specially
412                     "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side
413                     "*g" : "W",
414                     "*r" : "sbABC",
415                     # "*b" : "VW", # treated specially because it occurs very often
416                   } 
417        pagecount = resets = ejects = backsides = startgfx = endgfx = 0
418        starb = ampl = ispcl3 = 0
419        tag = None
420        pages = {}
421        pos = 0
422        try :
423            while 1 :
424                char = minfile[pos] ; pos += 1
425                if char == "\014" :   
426                    pagecount += 1
427                elif char == "\033" :   
428                    starb = ampl = 0
429                    #
430                    #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
431                    #     <ESC>*b###W -> Start of a raster data row/block
432                    #     <ESC>*b###V -> Start of a raster data plane
433                    #     <ESC>*c###W -> Start of a user defined pattern
434                    #     <ESC>*i###W -> Start of a viewing illuminant block
435                    #     <ESC>*l###W -> Start of a color lookup table
436                    #     <ESC>*m###W -> Start of a download dither matrix block
437                    #     <ESC>*v###W -> Start of a configure image data block
438                    #     <ESC>*r1A -> Start Gfx
439                    #     <ESC>(s###W -> Start of a characters description block
440                    #     <ESC>)s###W -> Start of a fonts description block
441                    #     <ESC>(f###W -> Start of a symbol set block
442                    #     <ESC>&b###W -> Start of configuration data block
443                    #     <ESC>&l###X -> Number of copies for current page
444                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
445                    #     <ESC>&p###X -> Start of a non printable characters block
446                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
447                    #     <ESC>*g###W -> Needed for planes in PCL3 output
448                    #     <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource
449                    #     <ESC>&l###A -> mediasize
450                    #     <ESC>&l###O -> orientation
451                    #     <ESC>&l###M -> mediatype
452                    #
453                    tagstart = minfile[pos] ; pos += 1
454                    if tagstart in "E9=YZ" : # one byte PCL tag
455                        if tagstart == "E" :
456                            resets += 1
457                        continue             # skip to next tag
458                    tag = tagstart + minfile[pos] ; pos += 1
459                    if tag == "*b" : 
460                        starb = 1
461                        tagend = "VW"
462                    elif tag == "&l" :   
463                        ampl = 1
464                        tagend = "XHAOM"
465                    else :   
466                        try :
467                            tagend = tagsends[tag]
468                        except KeyError :   
469                            continue # Unsupported PCL tag
470                    # Now read the numeric argument
471                    size = 0
472                    while 1 :
473                        char = minfile[pos] ; pos += 1
474                        if not char.isdigit() :
475                            break
476                        size = (size * 10) + int(char)   
477                    if char in tagend :   
478                        if tag == "&l" :
479                            if char == "X" : 
480                                self.setPageDict(pages, pagecount, "copies", size)
481                            elif char == "H" :
482                                self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
483                                ejects += 1 
484                            elif char == "A" :
485                                self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
486                            elif char == "O" :
487                                self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
488                            elif char == "M" :
489                                self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
490                        elif tag == "*r" :
491                            # Special tests for PCL3
492                            if (char == "s") and size :
493                                while 1 :
494                                    char = minfile[pos] ; pos += 1
495                                    if char == "A" :
496                                        break
497                            elif (char == "b") and (minfile[pos] == "C") and not size :
498                                ispcl3 = 1 # Certainely a PCL3 file
499                            startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
500                            endgfx += (not size) and (char in ("C", "B")) # End Gfx
501                        elif (tag == "&a") and (size == 2) :
502                            backsides += 1      # Back side in duplex mode
503                        else :   
504                            # we just ignore the block.
505                            if tag == "&n" : 
506                                # we have to take care of the operation id byte
507                                # which is before the string itself
508                                size += 1
509                            pos += size   
510                else :                           
511                    if starb :
512                        # special handling of PCL3 in which
513                        # *b introduces combined ESCape sequences
514                        size = 0
515                        while 1 :
516                            char = minfile[pos] ; pos += 1
517                            if not char.isdigit() :
518                                break
519                            size = (size * 10) + int(char)   
520                        if char in ("w", "v") :   
521                            ispcl3 = 1  # certainely a PCL3 document
522                            pos += size - 1
523                        elif char in ("y", "m") :   
524                            ispcl3 = 1  # certainely a PCL3 document
525                            pos -= 1    # fix position : we were ahead
526                    elif ampl :       
527                        # special handling of PCL3 in which
528                        # &l introduces combined ESCape sequences
529                        size = 0
530                        while 1 :
531                            char = minfile[pos] ; pos += 1
532                            if not char.isdigit() :
533                                break
534                            size = (size * 10) + int(char)   
535                        if char in ("a", "o", "h", "m") :   
536                            ispcl3 = 1  # certainely a PCL3 document
537                            pos -= 1    # fix position : we were ahead
538                            if char == "h" :
539                                self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
540                            elif char == "a" :
541                                self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
542                            elif char == "o" :
543                                self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
544                            elif char == "m" :
545                                self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
546        except IndexError : # EOF ?
547            minfile.close() # reached EOF
548                           
549        # if pagecount is still 0, we will use the number
550        # of resets instead of the number of form feed characters.
551        # but the number of resets is always at least 2 with a valid
552        # pcl file : one at the very start and one at the very end
553        # of the job's data. So we substract 2 from the number of
554        # resets. And since on our test data we needed to substract
555        # 1 more, we finally substract 3, and will test several
556        # PCL files with this. If resets < 2, then the file is
557        # probably not a valid PCL file, so we use 0
558        if not pagecount :
559            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
560        else :   
561            # here we add counters for other ways new pages may have
562            # been printed and ejected by the printer
563            pagecount += ejects + backsides
564       
565        # now handle number of copies for each page (may differ).
566        # in duplex mode, number of copies may be sent only once.
567        for pnum in range(pagecount) :
568            # if no number of copies defined, take the preceding one else the one set before any page else 1.
569            page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1 })))
570            pagecount += (page["copies"] - 1)
571           
572        # in PCL3 files, there's one Start Gfx tag per page
573        if ispcl3 :
574            if endgfx == int(startgfx / 2) : # special case for cdj1600
575                pagecount = endgfx 
576            elif startgfx :
577                pagecount = startgfx
578            elif endgfx :   
579                pagecount = endgfx
580               
581        if self.debug :       
582            for pnum in range(pagecount) :
583                # if no number of copies defined, take the preceding one else the one set before any page else 1.
584                page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})))
585                sys.stderr.write("%s*%s*%s*%s*%s\n" % (page["copies"], page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
586           
587        return pagecount
588       
589class PCLXLAnalyzer :
590    """A class to parse PCL6 (aka XL) documents."""
591    mediasizes = { 
592                    0 : "Letter",
593                    1 : "Legal",
594                    2 : "A4",
595                    3 : "Executive",
596                    4 : "Ledger",
597                    5 : "A3",
598                    6 : "COM10Envelope",
599                    7 : "MonarchEnvelope",
600                    8 : "C5Envelope",
601                    9 : "DLEnvelope",
602                    10 : "JB4",
603                    11 : "JB5",
604                    12 : "B5Envelope",
605                    14 : "JPostcard",
606                    15 : "JDoublePostcard",
607                    16 : "A5",
608                    17 : "A6",
609                    18 : "JB6",
610                 }   
611                 
612    mediasources = {             
613                     0 : "Default",
614                     1 : "Auto",
615                     2 : "Manual",
616                     3 : "MultiPurpose",
617                     4 : "UpperCassette",
618                     5 : "LowerCassette",
619                     6 : "EnvelopeTray",
620                     7 : "ThirdCassette",
621                   }
622                   
623    orientations = {               
624                     0 : "Portrait",
625                     1 : "Landscape",
626                     2 : "ReversePortrait",
627                     3 : "ReverseLandscape",
628                   }
629                   
630    def __init__(self, infile, debug=0) :
631        """Initialize PCLXL Analyzer."""
632        self.debug = debug
633        self.infile = infile
634        self.endianness = None
635        found = 0
636        while not found :
637            line = self.infile.readline()
638            if not line :
639                break
640            if line[1:12] == " HP-PCL XL;" :
641                found = 1
642                endian = ord(line[0])
643                if endian == 0x29 :
644                    self.littleEndian()
645                elif endian == 0x28 :   
646                    self.bigEndian()
647                # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements !
648                #
649                else :   
650                    raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian
651        if not found :
652            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
653        else :   
654            # Initialize table of tags
655            self.tags = [ 0 ] * 256   
656           
657            # GhostScript's sources tell us that HP printers
658            # only accept little endianness, but we can handle both.
659            self.tags[0x28] = self.bigEndian    # BigEndian
660            self.tags[0x29] = self.littleEndian # LittleEndian
661           
662            self.tags[0x43] = self.beginPage    # BeginPage
663            self.tags[0x44] = self.endPage      # EndPage
664           
665            self.tags[0xc0] = 1 # ubyte
666            self.tags[0xc1] = 2 # uint16
667            self.tags[0xc2] = 4 # uint32
668            self.tags[0xc3] = 2 # sint16
669            self.tags[0xc4] = 4 # sint32
670            self.tags[0xc5] = 4 # real32
671           
672            self.tags[0xc8] = self.array_8  # ubyte_array
673            self.tags[0xc9] = self.array_16 # uint16_array
674            self.tags[0xca] = self.array_32 # uint32_array
675            self.tags[0xcb] = self.array_16 # sint16_array
676            self.tags[0xcc] = self.array_32 # sint32_array
677            self.tags[0xcd] = self.array_32 # real32_array
678           
679            self.tags[0xd0] = 2 # ubyte_xy
680            self.tags[0xd1] = 4 # uint16_xy
681            self.tags[0xd2] = 8 # uint32_xy
682            self.tags[0xd3] = 4 # sint16_xy
683            self.tags[0xd4] = 8 # sint32_xy
684            self.tags[0xd5] = 8 # real32_xy
685           
686            self.tags[0xe0] = 4  # ubyte_box
687            self.tags[0xe1] = 8  # uint16_box
688            self.tags[0xe2] = 16 # uint32_box
689            self.tags[0xe3] = 8  # sint16_box
690            self.tags[0xe4] = 16 # sint32_box
691            self.tags[0xe5] = 16 # real32_box
692           
693            self.tags[0xf8] = 1 # attr_ubyte
694            self.tags[0xf9] = 2 # attr_uint16
695           
696            self.tags[0xfa] = self.embeddedData      # dataLength
697            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
698           
699    def beginPage(self) :
700        """Indicates the beginning of a new page, and extracts media information."""
701        self.pagecount += 1
702       
703        # Default values
704        mediatypelabel = "Plain"
705        mediasourcelabel = "Main"
706        mediasizelabel = "Default"
707        orientationlabel = "Portrait"
708       
709        # Now go upstream to decode media type, size, source, and orientation
710        # this saves time because we don't need a complete parser !
711        minfile = self.minfile
712        pos = self.pos - 2
713        while pos > 0 : # safety check : don't go back to far !
714            val = ord(minfile[pos])
715            if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page)
716                break
717            if val == 0x26 :   
718                mediasource = ord(minfile[pos - 2])
719                mediasourcelabel = self.mediasources.get(mediasource, str(mediasource))
720                pos = pos - 4
721            elif val == 0x25 :
722                mediasize = ord(minfile[pos - 2])
723                mediasizelabel = self.mediasizes.get(mediasize, str(mediasize))
724                pos = pos - 4
725            elif val == 0x28 :   
726                orientation = ord(minfile[pos - 2])
727                orienationlabel = self.orientations.get(orientation, str(orientation))
728                pos = pos - 4
729            elif val == 0x27 :   
730                savepos = pos
731                pos = pos - 1
732                while pos > 0 : # safety check : don't go back to far !
733                    val = ord(minfile[pos])
734                    pos -= 1   
735                    if val == 0xc8 :
736                        break
737                mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!!
738            # else : TODO : CUSTOM MEDIA SIZE AND UNIT !
739            else :   
740                pos = pos - 2   # ignored
741        self.pages[self.pagecount] = { "copies" : 1, 
742                                       "orientation" : orientationlabel, 
743                                       "mediatype" : mediatypelabel, 
744                                       "mediasize" : mediasizelabel,
745                                       "mediasource" : mediasourcelabel,
746                                     } 
747        return 0
748       
749    def endPage(self) :   
750        """Indicates the end of a page."""
751        pos = self.pos
752        minfile = self.minfile
753        if (ord(minfile[pos-3]) == 0xf8) and (ord(minfile[pos-2]) == 0x31) :
754            # The EndPage operator may be preceded by a PageCopies attribute
755            # So set number of copies for current page.
756            # From what I read in PCLXL documentation, the number
757            # of copies is an unsigned 16 bits integer
758            self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos-3])[0]
759        return 0
760       
761    def array_8(self) :   
762        """Handles byte arrays."""
763        pos = self.pos
764        datatype = self.minfile[pos]
765        pos += 1
766        length = self.tags[ord(datatype)]
767        if callable(length) :
768            self.pos = pos
769            length = length()
770            pos = self.pos
771        posl = pos + length
772        self.pos = posl
773        if length == 1 :   
774            return unpack("B", self.minfile[pos:posl])[0]
775        elif length == 2 :   
776            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
777        elif length == 4 :   
778            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
779        else :   
780            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
781       
782    def array_16(self) :   
783        """Handles byte arrays."""
784        pos = self.pos
785        datatype = self.minfile[pos]
786        pos += 1
787        length = self.tags[ord(datatype)]
788        if callable(length) :
789            self.pos = pos
790            length = length()
791            pos = self.pos
792        posl = pos + length
793        self.pos = posl
794        if length == 1 :   
795            return 2 * unpack("B", self.minfile[pos:posl])[0]
796        elif length == 2 :   
797            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
798        elif length == 4 :   
799            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
800        else :   
801            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
802       
803    def array_32(self) :   
804        """Handles byte arrays."""
805        pos = self.pos
806        datatype = self.minfile[pos]
807        pos += 1
808        length = self.tags[ord(datatype)]
809        if callable(length) :
810            self.pos = pos
811            length = length()
812            pos = self.pos
813        posl = pos + length
814        self.pos = posl
815        if length == 1 :   
816            return 4 * unpack("B", self.minfile[pos:posl])[0]
817        elif length == 2 :   
818            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
819        elif length == 4 :   
820            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
821        else :   
822            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
823       
824    def embeddedDataSmall(self) :
825        """Handle small amounts of data."""
826        pos = self.pos
827        length = ord(self.minfile[pos])
828        self.pos = pos + 1
829        return length
830       
831    def embeddedData(self) :
832        """Handle normal amounts of data."""
833        pos = self.pos
834        pos4 = pos + 4
835        self.pos = pos4
836        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
837       
838    def littleEndian(self) :       
839        """Toggles to little endianness."""
840        self.endianness = "<" # little endian
841        return 0
842       
843    def bigEndian(self) :   
844        """Toggles to big endianness."""
845        self.endianness = ">" # big endian
846        return 0
847   
848    def getJobSize(self) :
849        """Counts pages in a PCLXL (PCL6) document.
850       
851           Algorithm by Jerome Alet.
852           
853           The documentation used for this was :
854         
855           HP PCL XL Feature Reference
856           Protocol Class 2.0
857           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf
858        """
859        infileno = self.infile.fileno()
860        self.pages = {}
861        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
862        tags = self.tags
863        self.pagecount = 0
864        self.pos = pos = self.infile.tell()
865        try :
866            while 1 :
867                char = minfile[pos]
868                pos += 1
869                length = tags[ord(char)]
870                if not length :
871                    continue
872                if callable(length) :   
873                    self.pos = pos
874                    length = length()
875                    pos = self.pos
876                pos += length   
877        except IndexError : # EOF ?
878            self.minfile.close() # reached EOF
879           
880        # now handle number of copies for each page (may differ).
881        for pnum in range(1, self.pagecount + 1) :
882            # if no number of copies defined, take 1, as explained
883            # in PCLXL documentation.
884            # NB : is number of copies is 0, the page won't be output
885            # but the formula below is still correct : we want
886            # to decrease the total number of pages in this case.
887            page = self.pages.get(pnum, 1)
888            copies = page["copies"]
889            self.pagecount += (copies - 1)
890            if self.debug :
891                sys.stdrr.write("%s*%s*%s*%s*%s\n" % (copies, page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
892           
893        return self.pagecount
894       
895class PDLAnalyzer :   
896    """Generic PDL Analyzer class."""
897    def __init__(self, filename, debug=0) :
898        """Initializes the PDL analyzer.
899       
900           filename is the name of the file or '-' for stdin.
901           filename can also be a file-like object which
902           supports read() and seek().
903        """
904        self.debug = debug
905        self.filename = filename
906        try :
907            import psyco 
908        except ImportError :   
909            pass # Psyco is not installed
910        else :   
911            # Psyco is installed, tell it to compile
912            # the CPU intensive methods : PCL and PCLXL
913            # parsing will greatly benefit from this,
914            # for PostScript and PDF the difference is
915            # barely noticeable since they are already
916            # almost optimal, and much more speedy anyway.
917            psyco.bind(PostScriptAnalyzer.getJobSize)
918            psyco.bind(PDFAnalyzer.getJobSize)
919            psyco.bind(ESCP2Analyzer.getJobSize)
920            psyco.bind(PCLAnalyzer.getJobSize)
921            psyco.bind(PCLXLAnalyzer.getJobSize)
922       
923    def getJobSize(self) :   
924        """Returns the job's size."""
925        self.openFile()
926        try :
927            pdlhandler = self.detectPDLHandler()
928        except PDLAnalyzerError, msg :   
929            self.closeFile()
930            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
931        else :
932            try :
933                size = pdlhandler(self.infile, self.debug).getJobSize()
934            finally :   
935                self.closeFile()
936            return size
937       
938    def openFile(self) :   
939        """Opens the job's data stream for reading."""
940        self.mustclose = 0  # by default we don't want to close the file when finished
941        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
942            # filename is in fact a file-like object
943            infile = self.filename
944        elif self.filename == "-" :
945            # we must read from stdin
946            infile = sys.stdin
947        else :   
948            # normal file
949            self.infile = open(self.filename, "rb")
950            self.mustclose = 1
951            return
952           
953        # Use a temporary file, always seekable contrary to standard input.
954        self.infile = tempfile.TemporaryFile(mode="w+b")
955        while 1 :
956            data = infile.read(MEGABYTE) 
957            if not data :
958                break
959            self.infile.write(data)
960        self.infile.flush()   
961        self.infile.seek(0)
962           
963    def closeFile(self) :       
964        """Closes the job's data stream if we can close it."""
965        if self.mustclose :
966            self.infile.close()   
967        else :   
968            # if we don't have to close the file, then
969            # ensure the file pointer is reset to the
970            # start of the file in case the process wants
971            # to read the file again.
972            try :
973                self.infile.seek(0)
974            except :   
975                pass    # probably stdin, which is not seekable
976       
977    def isPostScript(self, sdata, edata) :   
978        """Returns 1 if data is PostScript, else 0."""
979        if sdata.startswith("%!") or \
980           sdata.startswith("\004%!") or \
981           sdata.startswith("\033%-12345X%!PS") or \
982           ((sdata[:128].find("\033%-12345X") != -1) and \
983             ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \
984              (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \
985              (sdata.find("LANGUAGE = Postscript") != -1))) or \
986              (sdata.find("%!PS-Adobe") != -1) :
987            if self.debug : 
988                sys.stderr.write("%s is a PostScript file\n" % str(self.filename))
989            return 1
990        else :   
991            return 0
992       
993    def isPDF(self, sdata, edata) :   
994        """Returns 1 if data is PDF, else 0."""
995        if sdata.startswith("%PDF-") or \
996           sdata.startswith("\033%-12345X%PDF-") or \
997           ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \
998           (sdata.find("%PDF-") != -1) :
999            if self.debug : 
1000                sys.stderr.write("%s is a PDF file\n" % str(self.filename))
1001            return 1
1002        else :   
1003            return 0
1004       
1005    def isPCL(self, sdata, edata) :   
1006        """Returns 1 if data is PCL, else 0."""
1007        if sdata.startswith("\033E\033") or \
1008           (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \
1009           sdata.startswith("\033%8\033") or \
1010           (sdata.find("\033%-12345X") != -1) :
1011            if self.debug : 
1012                sys.stderr.write("%s is a PCL3/4/5 file\n" % str(self.filename))
1013            return 1
1014        else :   
1015            return 0
1016       
1017    def isPCLXL(self, sdata, edata) :   
1018        """Returns 1 if data is PCLXL aka PCL6, else 0."""
1019        if ((sdata[:128].find("\033%-12345X") != -1) and \
1020             (sdata.find(" HP-PCL XL;") != -1) and \
1021             ((sdata.find("LANGUAGE=PCLXL") != -1) or \
1022              (sdata.find("LANGUAGE = PCLXL") != -1))) :
1023            if self.debug : 
1024                sys.stderr.write("%s is a PCLXL (aka PCL6) file\n" % str(self.filename))
1025            return 1
1026        else :   
1027            return 0
1028           
1029    def isESCP2(self, sdata, edata) :       
1030        """Returns 1 if data is ESC/P2, else 0."""
1031        if sdata.startswith("\033@") or \
1032           sdata.startswith("\033*") or \
1033           sdata.startswith("\n\033@") or \
1034           sdata.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284
1035            if self.debug : 
1036                sys.stderr.write("%s is an ESC/P2 file\n" % str(self.filename))
1037            return 1
1038        else :   
1039            return 0
1040   
1041    def detectPDLHandler(self) :   
1042        """Tries to autodetect the document format.
1043       
1044           Returns the correct PDL handler class or None if format is unknown
1045        """   
1046        # Try to detect file type by reading first block of datas   
1047        self.infile.seek(0)
1048        firstblock = self.infile.read(4 * KILOBYTE)
1049        try :
1050            self.infile.seek(-LASTBLOCKSIZE, 2)
1051        except IOError :   
1052            lastblock = ""
1053        else :   
1054            lastblock = self.infile.read(LASTBLOCKSIZE)
1055        self.infile.seek(0)
1056        if self.isPostScript(firstblock, lastblock) :
1057            return PostScriptAnalyzer
1058        elif self.isPCLXL(firstblock, lastblock) :   
1059            return PCLXLAnalyzer
1060        elif self.isPDF(firstblock, lastblock) :   
1061            return PDFAnalyzer
1062        elif self.isPCL(firstblock, lastblock) :   
1063            return PCLAnalyzer
1064        elif self.isESCP2(firstblock, lastblock) :   
1065            return ESCP2Analyzer
1066        else :   
1067            raise PDLAnalyzerError, "Analysis of first data block failed."
1068           
1069def main() :   
1070    """Entry point for PDL Analyzer."""
1071    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
1072        sys.argv.append("-")
1073       
1074    totalsize = 0   
1075    debug = 0
1076    minindex = 1
1077    if sys.argv[1] == "--debug" :
1078        minindex = 2
1079        debug = 1
1080    for arg in sys.argv[minindex:] :
1081        try :
1082            parser = PDLAnalyzer(arg, debug)
1083            totalsize += parser.getJobSize()
1084        except PDLAnalyzerError, msg :   
1085            sys.stderr.write("ERROR: %s\n" % msg)
1086            sys.stderr.flush()
1087    print "%s" % totalsize
1088   
1089if __name__ == "__main__" :   
1090    main()
Note: See TracBrowser for help on using the browser.