Changeset 1911

Show
Ignore:
Timestamp:
11/13/04 00:46:44 (19 years ago)
Author:
jalet
Message:

Heavy work on pkbanner. Not finished yet though, but mostly works.

Location:
pykota/trunk
Files:
5 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/bin/pkbanner

    r1909 r1911  
    2424# 
    2525# $Log$ 
     26# Revision 1.3  2004/11/12 23:46:44  jalet 
     27# Heavy work on pkbanner. Not finished yet though, but mostly works. 
     28# 
    2629# Revision 1.2  2004/11/11 14:25:48  jalet 
    2730# Added some TODO comments 
     
    3538import sys 
    3639import os 
     40import cStringIO 
     41 
     42try : 
     43    from reportlab.pdfgen import canvas 
     44    from reportlab.lib import pagesizes 
     45    from reportlab.lib.units import cm 
     46except ImportError :     
     47    hasRL = 0 
     48else :     
     49    hasRL = 1 
     50     
     51try : 
     52    import PIL.Image  
     53except ImportError :     
     54    hasPIL = 0 
     55else :     
     56    hasPIL = 1 
     57     
     58from pykota.tool import Tool, PyKotaToolError, crashed, N_ 
     59 
     60__doc__ = N_("""pkbanner v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres 
     61 
     62Generates banners. 
     63 
     64command line usage : 
     65 
     66  pkbanner  [options]  [files] 
     67 
     68options : 
     69 
     70  -v | --version       Prints pkbanner's version number then exits. 
     71  -h | --help          Prints this message then exits. 
     72   
     73  ... TODO... 
     74   
     75examples :                               
     76 
     77  ... TODO... 
     78 
     79This program is free software; you can redistribute it and/or modify 
     80it under the terms of the GNU General Public License as published by 
     81the Free Software Foundation; either version 2 of the License, or 
     82(at your option) any later version. 
     83 
     84This program is distributed in the hope that it will be useful, 
     85but WITHOUT ANY WARRANTY; without even the implied warranty of 
     86MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
     87GNU General Public License for more details. 
     88 
     89You should have received a copy of the GNU General Public License 
     90along with this program; if not, write to the Free Software 
     91Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. 
     92 
     93Please e-mail bugs to: %s""") 
     94         
     95class PyKotaBanner(Tool) :         
     96    """A class for pkbanner.""" 
     97    primaryfields = [  
     98                ("PRINTERNAME", N_("Printer")), 
     99                ("USERNAME", N_("User")), 
     100                ("JOBID", N_("JobId")), 
     101                ("JOBORIGINATINGHOSTNAME", N_("Client host")), 
     102                ("TITLE", N_("Title")), 
     103                ("FILENAME", N_("Filename")), 
     104                ("COPIES", N_("Copies")), 
     105                ("JOBSIZEBYTES", N_("Job size in bytes")), 
     106                ("PRECOMPUTEDJOBSIZE", N_("Estimated job size")), 
     107                ("PRECOMPUTEDJOBPRICE", N_("Estimated job price")), 
     108             ]    
     109              
     110    secondaryfields = [ 
     111                ("LIMITBY", N_("Account limited by")), 
     112                ("BALANCE", N_("Account balance")), 
     113                ("PAGECOUNTER", N_("Number of pages on this printer")), 
     114                ("SOFTLIMIT", N_("Soft limit")), 
     115                ("HARDLIMIT", N_("Hard limit")), 
     116                ("DATELIMIT", N_("Date limit")), 
     117             ]                            
     118     
     119    tertiaryfields = [ 
     120                ("ACTION", N_("Action taken for current job")), 
     121             ]                            
     122     
     123    def getPageSize(self, pgsize) : 
     124        """Returns the correct page size or None if not found.""" 
     125        try : 
     126            return getattr(pagesizes, pgsize.upper()) 
     127        except AttributeError :     
     128            try : 
     129                return getattr(pagesizes, pgsize.lower()) 
     130            except AttributeError : 
     131                pass 
     132                 
     133    def genPDF(self, pagesize, logo, url) :             
     134        """Generates the banner in PDF format, return the PDF document as a string.""" 
     135        document = cStringIO.StringIO() 
     136        c = canvas.Canvas(document, pagesize=pagesize, pageCompression=1) 
     137         
     138        c.setAuthor("Jerome Alet") 
     139        c.setTitle("PyKota generated Banner") 
     140        c.setSubject("This is a print banner generated with PyKota") 
     141         
     142        xcenter = pagesize[0] / 2.0 
     143        ycenter = pagesize[1] / 2.0 
     144                     
     145        ypos = pagesize[1] - (2 * cm)             
     146        try :     
     147            imglogo = PIL.Image.open(logo) 
     148        except :     
     149            self.printInfo("Unable to open image %s" % logo, "warn") 
     150        else : 
     151            (width, height) = imglogo.size 
     152            multi = float(width) / (8 * cm)  
     153            width = float(width) / multi 
     154            height = float(height) / multi 
     155            xpos = xcenter - (width / 2.0) 
     156            ypos -= height 
     157            c.drawImage(logo, xpos, ypos, width, height) 
     158         
     159        # New top 
     160        xpos = pagesize[0] / 5.0 
     161        ypos -= (1 * cm) + 20 
     162         
     163        for fieldsgroup in [ self.primaryfields, self.secondaryfields, self.tertiaryfields] : 
     164            c.saveState() 
     165            for (varname, label) in fieldsgroup : 
     166                c.setFont("Helvetica-Bold", 14) 
     167                c.setFillColorRGB(0, 0, 0) 
     168                message = "%s :" % _(label).title() 
     169                c.drawRightString(xcenter, ypos, message) 
     170                c.setFont("Courier-Bold", 14) 
     171                c.setFillColorRGB(1, 0, 0) 
     172                c.drawString(xcenter + 0.5*cm, ypos, os.environ.get("PYKOTA%s" % varname, _("Unknown"))) 
     173                ypos -= 18  # next line 
     174            c.restoreState() 
     175            ypos -= 18      # skip an additionnal line 
     176         
     177        # URL 
     178        c.saveState() 
     179        c.setFont("Courier-Bold", 16) 
     180        c.setFillColorRGB(0, 0, 1) 
     181        c.drawCentredString(xcenter, 2 * cm, url) 
     182        c.restoreState() 
     183         
     184        c.showPage() 
     185        c.save() 
     186        return document.getvalue() 
     187     
     188    def main(self, files, options) : 
     189        """Generates a banner.""" 
     190        if not hasRL : 
     191            raise PyKotaToolError, "The ReportLab module is missing. Download it from http://www.reportlab.org" 
     192        if not hasPIL : 
     193            raise PyKotaToolError, "The Python Imaging Library is missing. Download it from http://www.pythonware.com/downloads" 
     194             
     195        pagesize = self.getPageSize(options["pagesize"]) 
     196        if pagesize is None : 
     197            pagesize = self.getPageSize("a4") 
     198            self.printInfo("Unknown page size %s, defaulting to A4." % options["pagesize"], "warn") 
     199             
     200        doc = self.genPDF(pagesize, options["logo"], options["url"].strip()) 
     201        print doc 
    37202 
    38203def getInfo(name) : 
     
    41206 
    42207if __name__ == "__main__" : 
    43     # TODO : --pagesize, --supporturl, extract admin's email address from pykota.conf 
    44     # TODO : --logourl and/or --logofile : to put a nice logo on the banner page 
    45208    # TODO : --papertray : to print banners on a different paper (colored for example) 
    46     pass 
     209    retcode = 0 
     210    try : 
     211        defaults = { \ 
     212                     "pagesize" : "a4", \ 
     213                     "logo" : "/usr/share/pykota/logos/pykota.jpeg", 
     214                     "url" : "http://www.librelogiciel.com/software/", 
     215                   } 
     216        short_options = "vhl:p:u:" 
     217        long_options = ["help", "version", "pagesize=", "logo=", "url="] 
     218         
     219        # Initializes the command line tool 
     220        banner = PyKotaBanner(doc=__doc__) 
     221         
     222        # parse and checks the command line 
     223        (options, args) = banner.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1) 
     224         
     225        # sets long options 
     226        options["help"] = options["h"] or options["help"] 
     227        options["version"] = options["v"] or options["version"] 
     228        options["pagesize"] = options["p"] or options["pagesize"] or defaults["pagesize"] 
     229        options["logo"] = options["l"] or options["logo"] or defaults["logo"] 
     230        options["url"] = options["u"] or options["url"] or defaults["url"] 
     231         
     232        if options["help"] : 
     233            banner.display_usage_and_quit() 
     234        elif options["version"] : 
     235            banner.display_version_and_quit() 
     236        else : 
     237            retcode = banner.main(args, options) 
     238    except SystemExit :         
     239        pass 
     240    except : 
     241        try : 
     242            banner.crashed("pkbanner failed") 
     243        except :     
     244            crashed("pkbanner failed") 
     245        retcode = -1 
     246         
     247    sys.exit(retcode)     
  • pykota/trunk/bin/pykotme

    r1803 r1911  
    2424# 
    2525# $Log$ 
     26# Revision 1.17  2004/11/12 23:46:44  jalet 
     27# Heavy work on pkbanner. Not finished yet though, but mostly works. 
     28# 
    2629# Revision 1.16  2004/10/11 22:53:05  jalet 
    2730# Postponed string interpolation to help message's output method 
     
    8891 
    8992from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_ 
    90 from pykota.config import PyKotaConfigError 
    91 from pykota.storage import PyKotaStorageError 
    9293from pykota.pdlanalyzer import PDLAnalyzer, PDLAnalyzerError 
    9394 
  • pykota/trunk/MANIFEST.in

    r1905 r1911  
    88recursive-include debian README pykota.templates Makefile.docs pykota.config pykota.cron.daily printquota.default Makefile.docs changelog control copyright dirs docs examples links rules 
    99recursive-include untested README *.sh *.ps *.pjl 
    10 recursive-include logos README *.png *.xcf 
     10recursive-include logos README *.png *.xcf *.jpeg 
    1111recursive-include contributed README *.pl *.sh *.py 
    1212recursive-include stylesheets README *.css 
  • pykota/trunk/pykota/tool.py

    r1898 r1911  
    2222# 
    2323# $Log$ 
     24# Revision 1.138  2004/11/12 23:46:44  jalet 
     25# Heavy work on pkbanner. Not finished yet though, but mostly works. 
     26# 
    2427# Revision 1.137  2004/11/01 16:21:17  jalet 
    2528# Little change for locale+gettext 
     
    539542    return msg 
    540543 
    541 class PyKotaTool :     
    542     """Base class for all PyKota command line tools.""" 
     544class Tool : 
     545    """Base class for tools with no database access.""" 
    543546    def __init__(self, lang="", charset=None, doc="PyKota %s (c) 2003-2004 %s" % (version.__version__, version.__author__)) : 
    544547        """Initializes the command line tool.""" 
     
    588591            self.maildomain = self.config.getMailDomain() 
    589592            self.logger = logger.openLogger(self.config.getLoggingBackend()) 
    590             self.storage = storage.openConnection(self) 
    591593        except (config.PyKotaConfigError, logger.PyKotaLoggingError, storage.PyKotaStorageError), msg : 
    592594            self.crashed(msg) 
     
    614616        sys.stderr.flush() 
    615617         
    616     def clean(self) :     
    617         """Ensures that the database is closed.""" 
    618         try : 
    619             self.storage.close() 
    620         except (TypeError, NameError, AttributeError) :     
    621             pass 
    622              
    623618    def display_version_and_quit(self) : 
    624619        """Displays version number, then exists successfully.""" 
     
    711706        return (parsed, args) 
    712707     
     708class PyKotaTool(Tool) :     
     709    """Base class for all PyKota command line tools.""" 
     710    def __init__(self, lang="", charset=None, doc="PyKota %s (c) 2003-2004 %s" % (version.__version__, version.__author__)) : 
     711        """Initializes the command line tool and opens the database.""" 
     712        Tool.__init__(self, lang, charset, doc) 
     713        try : 
     714            self.storage = storage.openConnection(self) 
     715        except storage.PyKotaStorageError, msg : 
     716            self.crashed(msg) 
     717            raise 
     718         
     719    def clean(self) :     
     720        """Ensures that the database is closed.""" 
     721        try : 
     722            self.storage.close() 
     723        except (TypeError, NameError, AttributeError) :     
     724            pass 
     725             
    713726    def isValidName(self, name) : 
    714727        """Checks if a user or printer name is valid.""" 
  • pykota/trunk/setup.py

    r1907 r1911  
    2424# 
    2525# $Log$ 
     26# Revision 1.58  2004/11/12 23:46:43  jalet 
     27# Heavy work on pkbanner. Not finished yet though, but mostly works. 
     28# 
    2629# Revision 1.57  2004/11/10 22:40:45  jalet 
    2730# Logos are installed now 
     
    283286data_files.append((os.sep.join([directory, "cgi-bin"]), ["cgi-bin/README", "cgi-bin/printquota.cgi"])) 
    284287 
    285 data_files.append((os.sep.join([directory, "logos"]), glob.glob(os.sep.join(["logos", "*.png"])) + glob.glob(os.sep.join(["logos", "*.xcf"])))) 
     288data_files.append((os.sep.join([directory, "logos"]), glob.glob(os.sep.join(["logos", "*.jpeg"])) + glob.glob(os.sep.join(["logos", "*.png"])) + glob.glob(os.sep.join(["logos", "*.xcf"])))) 
    286289 
    287290pgdirectory = os.sep.join([directory, "postgresql"])