home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / hplip / makecopies < prev    next >
Encoding:
Text File  |  2007-04-04  |  12.3 KB  |  399 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  19. #
  20. # Author: Don Welch
  21. #
  22.  
  23. __version__ = '2.0'
  24. __title__ = "Make Copies Utility"
  25. __doc__ = "PC initiated make copies on supported HP AiO and MFP devices."
  26.  
  27. # Std Lib
  28. import sys, os, getopt, re, socket, Queue, time
  29.  
  30. # Local
  31. from base.g import *
  32. from base.msg import *
  33. from base import utils, device, pml, service
  34. from copier import copier
  35. from prnt import cups
  36.  
  37. log.set_module('hp-makecopies')
  38.  
  39. USAGE = [(__doc__, "", "name", True),
  40.          ("Usage: hp-makecopies [PRINTER|DEVICE-URI] [MODE] [OPTIONS]", "", "summary", True),
  41.          utils.USAGE_ARGS,
  42.          utils.USAGE_DEVICE,
  43.          ("To specify a CUPS printer:", "-P<printer>, -p<printer> or --printer=<printer>", "option", False),
  44.          utils.USAGE_SPACE,
  45.          ("[MODE]", "", "header", False),
  46.          ("Enter graphical UI mode:", "-u or --gui (Default)", "option", False),
  47.          ("Run in non-interactive mode (batch mode):", "-n or --non-interactive", "option", False),
  48.          utils.USAGE_SPACE,
  49.          utils.USAGE_OPTIONS,
  50.          ("Number of copies:", "-m<num_copies> or --copies=<num_copies> or --num=<num_copies> (1-99)", "option", False),
  51.          ("Reduction/enlargement:", "-r<%> or --reduction=<%> or --enlargement=<%> (25-400%)", "option", False),
  52.          ("Quality:", "-q<quality> or --quality=<quality> (where quality is: 'fast', 'draft', 'normal', 'presentation', or 'best')", "option", False),
  53.          ("Contrast:", "-c<contrast> or --contrast=<contrast> (-5 to +5)", "option", False),
  54.          ("Fit to page (flatbed only):", "-f or --fittopage or --fit (overrides reduction/enlargement)", "option", False),
  55.          utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
  56.          utils.USAGE_HELP,
  57.          utils.USAGE_SPACE,
  58.          utils.USAGE_NOTES,
  59.          utils.USAGE_STD_NOTES1, utils.USAGE_STD_NOTES2, 
  60.          ("3. If any copy parameter is not specified (contrast, reduction, etc), the default values from the device are used.", "", "note", False),
  61.          ]
  62.  
  63.  
  64. def usage(typ='text'):
  65.     if typ == 'text':
  66.         utils.log_title(__title__, __version__)
  67.  
  68.     utils.format_text(USAGE, typ, __title__, 'hp-makecopies', __version__)
  69.     sys.exit(0)
  70.  
  71.  
  72. try:
  73.     opts, args = getopt.getopt(sys.argv[1:], 'P:p:d:hl:gm:c:q:r:funb:',
  74.                                ['printer=', 'device=', 'help', 'logging=',
  75.                                 'num=', 'copies=', 'contrast=', 'quality='
  76.                                 'reduction=', 'enlargement=', 'fittopage', 
  77.                                 'fit', 'gui', 'help-rest', 'help-man',
  78.                                 'help-desc', 'non-interactive', 'bus='])
  79. except getopt.GetoptError:
  80.     usage()
  81.  
  82. printer_name = None
  83. device_uri = None
  84. log_level = logger.DEFAULT_LOG_LEVEL
  85. bus = 'cups'
  86. num_copies = None
  87. reduction = None
  88. reduction_spec = False
  89. contrast = None
  90. quality = None
  91. fit_to_page = None
  92. mode = GUI_MODE
  93. mode_specified = False
  94.  
  95. if os.getenv("HPLIP_DEBUG"):
  96.     log.set_level('debug')
  97.  
  98. for o, a in opts:
  99.     if o in ('-h', '--help'):
  100.         usage()
  101.  
  102.     elif o == '--help-rest':
  103.         usage('rest')
  104.  
  105.     elif o == '--help-man':
  106.         usage('man')
  107.  
  108.     elif o == '--help-desc':
  109.         print __doc__,
  110.         sys.exit(0)
  111.  
  112.     elif o in ('-p', '-P', '--printer'):
  113.         printer_name = a
  114.  
  115.     elif o in ('-d', '--device'):
  116.         device_uri = a
  117.  
  118.     elif o in ('-l', '--logging'):
  119.         log_level = a.lower().strip()
  120.         if not log.set_level(log_level):
  121.             usage()
  122.  
  123.     elif o == '-g':
  124.         log.set_level('debug')
  125.  
  126.     elif o in ('-m', '--num', '--copies'):
  127.         try:
  128.             num_copies = int(a)
  129.         except ValueError:
  130.             log.warning("Invalid number of copies. Set to default of 1.")
  131.             num_copies = 1
  132.  
  133.         if num_copies < 1: 
  134.             log.warning("Invalid number of copies. Set to minimum of 1.")
  135.             num_copies = 1
  136.  
  137.         elif num_copies > 99: 
  138.             log.warning("Invalid number of copies. Set to maximum of 99.")
  139.             num_copies = 99
  140.  
  141.     elif o in ('-c', '--contrast'):
  142.         try:
  143.             contrast = int(a)
  144.         except ValueError:
  145.             log.warning("Invalid contrast setting. Set to default of 0.")
  146.             contrast = 0
  147.  
  148.         if contrast < -5: 
  149.             log.warning("Invalid contrast setting. Set to minimum of -5.")
  150.             contrast = -5
  151.  
  152.         elif contrast > 5: 
  153.             log.warning("Invalid contrast setting. Set to maximum of +5.")
  154.             contrast = 5
  155.  
  156.         contrast *= 25
  157.  
  158.     elif o in ('-q', '--quality'):
  159.         a = a.lower().strip()
  160.  
  161.         if a == 'fast':
  162.             quality = pml.COPIER_QUALITY_FAST
  163.  
  164.         elif a.startswith('norm'):
  165.             quality = pml.COPIER_QUALITY_NORMAL
  166.  
  167.         elif a.startswith('pres'):
  168.             quality = pml.COPIER_QUALITY_PRESENTATION
  169.  
  170.         elif a.startswith('draf'):
  171.             quality = pml.COPIER_QUALITY_DRAFT
  172.  
  173.         elif a == 'best':
  174.             quality = pml.COPIER_QUALITY_BEST
  175.  
  176.         else:
  177.             log.warning("Invalid quality. Set to default of 'normal'.")
  178.  
  179.     elif o in ('-r', '--reduction', '--enlargement'):
  180.         reduction_spec = True
  181.         try:
  182.             reduction = int(a.replace('%', ''))
  183.         except ValueError:
  184.             log.warning("Invalid reduction %. Set to default of 100%.")
  185.             reduction = 100
  186.  
  187.         if reduction < 25:
  188.             log.warning("Invalid reduction %. Set to minimum of 25%.")
  189.             reduction = 25
  190.  
  191.         elif reduction > 400:
  192.             log.warning("Invalid reduction %. Set to maximum of 400%.")
  193.             reduction = 400
  194.  
  195.     elif o in ('-f', '--fittopage', '--fit'):
  196.         fit_to_page = pml.COPIER_FIT_TO_PAGE_ENABLED
  197.  
  198.     elif o in ('-n', '--non-interactive'):
  199.         if mode_specified:
  200.             log.error("You may only specify a single mode as a parameter (-n or -u).")
  201.             sys.exit(1)
  202.  
  203.         mode = NON_INTERACTIVE_MODE
  204.         mode_specified = True
  205.  
  206.     elif o in ('-u', '--gui'):
  207.         if mode_specified:
  208.             log.error("You may only specify a single mode as a parameter (-n or -u).")
  209.             sys.exit(1)
  210.  
  211.         mode = GUI_MODE
  212.         mode_specified = True
  213.  
  214.     elif o in ('-b', '--bus'):
  215.         bus = a.lower().strip()
  216.         if not device.validateBusList(bus):
  217.             usage()
  218.  
  219.  
  220.  
  221. if fit_to_page == pml.COPIER_FIT_TO_PAGE_ENABLED and reduction_spec:
  222.     log.warning("Fit to page specfied: Reduction/enlargement parameter ignored.")
  223.  
  224.  
  225. utils.log_title(__title__, __version__)
  226.  
  227. # Security: Do *not* create files that other users can muck around with
  228. os.umask (0077)
  229.  
  230. if mode == GUI_MODE:
  231.     if not os.getenv('DISPLAY'):
  232.         mode = NON_INTERACTIVE_MODE
  233.  
  234.     elif not utils.checkPyQtImport():
  235.         mode = NON_INTERACTIVE_MODE
  236.  
  237. if mode == GUI_MODE:
  238.     app = None
  239.     makecopiesdlg = None
  240.  
  241.     from qt import *
  242.     from ui.makecopiesform import MakeCopiesForm
  243.  
  244.     hpssd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  245.     try:
  246.         hpssd_sock.connect((prop.hpssd_host, prop.hpssd_port))
  247.     except socket.error:
  248.         log.error("Unable to connect to HPLIP I/O (hpssd).")
  249.         sys.exit(1)
  250.  
  251.     log.debug("Connected to hpssd on %s:%d" % (prop.hpssd_host, prop.hpssd_port))
  252.  
  253.     # create the main application object
  254.     app = QApplication(sys.argv)
  255.  
  256.     makecopiesdlg = MakeCopiesForm(hpssd_sock, bus, device_uri, printer_name, 
  257.                                    num_copies, contrast, quality, reduction, fit_to_page)
  258.  
  259.     makecopiesdlg.show()
  260.     app.setMainWidget(makecopiesdlg)
  261.  
  262.     user_config = os.path.expanduser('~/.hplip.conf')
  263.     loc = utils.loadTranslators(app, user_config)
  264.  
  265.     try:
  266.         log.debug("Starting GUI loop...")
  267.         app.exec_loop()
  268.     except KeyboardInterrupt:
  269.         pass
  270.     except:
  271.         log.exception()
  272.  
  273.     hpssd_sock.close()
  274.  
  275. else: # NON_INTERACTIVE_MODE
  276.     if not device_uri and not printer_name:
  277.         try:
  278.             device_uri = device.getInteractiveDeviceURI(bus, filter='copy')
  279.             if device_uri is None:
  280.                 sys.exit(1)
  281.         except Error:
  282.             log.error("Error occured during interactive mode. Exiting.")
  283.             sys.exit(1)
  284.  
  285.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  286.     try:
  287.         sock.connect((prop.hpssd_host, prop.hpssd_port))
  288.     except socket.error:
  289.         log.error("Unable to connect to HPLIP I/O (hpssd).")
  290.         sys.exit(1)
  291.  
  292.     dev = copier.PMLCopyDevice(device_uri, printer_name, 
  293.                                sock)
  294.  
  295.  
  296.     if dev.copy_type == COPY_TYPE_NONE:
  297.         log.error("Sorry, make copies functionality is not supported on this device.")
  298.         sys.exit(1)
  299.         
  300.     user_cfg.last_used.device_uri = dev.device_uri
  301.  
  302.     try:
  303.         dev.open()
  304.  
  305.         if num_copies is None:
  306.             result_code, num_copies = dev.getPML(pml.OID_COPIER_NUM_COPIES)
  307.  
  308.         if contrast is None:
  309.             result_code, contrast = dev.getPML(pml.OID_COPIER_CONTRAST)
  310.  
  311.         if reduction is None:
  312.             result_code, reduction = dev.getPML(pml.OID_COPIER_REDUCTION)
  313.  
  314.         if quality is None:
  315.             result_code, quality = dev.getPML(pml.OID_COPIER_QUALITY)
  316.  
  317.         if fit_to_page is None and dev.copy_type == COPY_TYPE_DEVICE:
  318.             result_code, fit_to_page = dev.getPML(pml.OID_COPIER_FIT_TO_PAGE)
  319.         else:
  320.             fit_to_page = pml.COPIER_FIT_TO_PAGE_DISABLED
  321.  
  322.         result_code, max_reduction = dev.getPML(pml.OID_COPIER_REDUCTION_MAXIMUM)
  323.         result_code, max_enlargement = dev.getPML(pml.OID_COPIER_ENLARGEMENT_MAXIMUM)
  324.  
  325.     except Error, e:
  326.         log.error(e.msg)
  327.         sys.exit(1)
  328.  
  329.     scan_style = dev.mq.get('scan-style', SCAN_STYLE_FLATBED)
  330.     log.debug(scan_style)
  331.  
  332.     if scan_style == SCAN_STYLE_SCROLLFED:
  333.         fit_to_page = pml.COPIER_FIT_TO_PAGE_DISABLED
  334.  
  335.     log.debug("num_copies = %d" % num_copies)
  336.     log.debug("contrast= %d" % contrast)
  337.     log.debug("reduction = %d" % reduction)
  338.     log.debug("quality = %d" % quality)
  339.     log.debug("fit_to_page = %d" % fit_to_page)
  340.     log.debug("max_reduction = %d" % max_reduction)
  341.     log.debug("max_enlargement = %d" % max_enlargement)
  342.     log.debug("scan_style = %d" % scan_style)
  343.  
  344.     update_queue = Queue.Queue()
  345.     event_queue = Queue.Queue()
  346.  
  347.     dev.copy(num_copies, contrast, reduction,
  348.              quality, fit_to_page, scan_style,
  349.              update_queue, event_queue)
  350.  
  351.     try:
  352.         cont = True
  353.         while cont:
  354.             while update_queue.qsize():
  355.                 try:
  356.                     status = update_queue.get(0)
  357.                 except Queue.Empty:
  358.                     break
  359.  
  360.                 if status == copier.STATUS_IDLE:
  361.                     log.debug("Idle")
  362.                     continue
  363.  
  364.                 elif status in (copier.STATUS_SETTING_UP, copier.STATUS_WARMING_UP):
  365.                     log.info("Warming up...")
  366.                     continue
  367.  
  368.                 elif status == copier.STATUS_ACTIVE:
  369.                     log.info("Copying...")
  370.                     continue
  371.  
  372.                 elif status in (copier.STATUS_ERROR, copier.STATUS_DONE):
  373.  
  374.                     if status == copier.STATUS_ERROR:
  375.                         log.error("Copier error!")
  376.                         service.sendEvent(sock, EVENT_COPY_JOB_FAIL, device_uri=device_uri)
  377.                         cont = False
  378.                         break
  379.  
  380.                     elif status == copier.STATUS_DONE:
  381.                         cont = False
  382.                         break
  383.  
  384.             time.sleep(2)
  385.  
  386.     except KeyboardInterrupt:
  387.         event_queue.put(copier.COPY_CANCELED)
  388.         service.sendEvent(sock, EVENT_COPY_JOB_CANCELED, device_uri=device_uri)            
  389.         log.error("Cancelling...")
  390.  
  391.     dev.close()
  392.  
  393.     dev.waitForCopyThread()
  394.     service.sendEvent(sock, EVENT_END_COPY_JOB, device_uri=device_uri)
  395.     log.info("Done.")
  396.  
  397. sys.exit(0)
  398.  
  399.