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 / base / g.py < prev    next >
Encoding:
Python Source  |  2007-04-04  |  9.6 KB  |  280 lines

  1. # -*- coding: utf-8 -*-
  2. #
  3. # (c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  18. #
  19. # Author: Don Welch
  20. #
  21. # NOTE: This module is safe for 'from g import *'
  22. #
  23.  
  24. # Std Lib
  25. import sys
  26. import os, os.path
  27. import ConfigParser
  28. import locale
  29. import pwd
  30. import stat
  31.  
  32. # Local
  33. from codes import *
  34. import logger
  35.  
  36. # System wide logger
  37. log = logger.Logger('', logger.Logger.LOG_LEVEL_INFO, logger.Logger.LOG_TO_CONSOLE)
  38. log.set_level('info')
  39.  
  40. MINIMUM_PYQT_MAJOR_VER = 3
  41. MINIMUM_PYQT_MINOR_VER = 14
  42. MINIMUM_QT_MAJOR_VER = 3
  43. MINIMUM_QT_MINOR_VER = 0
  44.  
  45. # System wide properties
  46. class Properties(dict):
  47.  
  48.     def __getattr__(self, attr):
  49.         if attr in self.keys():
  50.             return self.__getitem__(attr)
  51.         else:
  52.             return ""
  53.  
  54.     def __setattr__(self, attr, val):
  55.         self.__setitem__(attr, val)
  56.  
  57. prop = Properties()
  58.  
  59.  
  60. # User config file
  61. class ConfigSection(dict):
  62.     def __init__(self, section_name, config_obj, filename, *args, **kwargs):
  63.         dict.__setattr__(self, "section_name", section_name)
  64.         dict.__setattr__(self, "config_obj", config_obj)
  65.         dict.__setattr__(self, "filename", filename)
  66.         dict.__init__(self, *args, **kwargs)
  67.  
  68.     def __getattr__(self, attr):
  69.         if attr in self.keys():
  70.             return self.__getitem__(attr)
  71.         else:
  72.             return ""
  73.  
  74.     def __setattr__(self, option, val):
  75.         self.__setitem__(option, val)
  76.         if not self.config_obj.has_section(self.section_name):
  77.             self.config_obj.add_section(self.section_name)
  78.  
  79.         self.config_obj.set(self.section_name, option, val)
  80.         f = file(self.filename, 'w')
  81.         self.config_obj.write(f)
  82.         f.close()
  83.  
  84.  
  85. class Config(dict):
  86.     def __init__(self, filename, error_if_not_found=False, *args, **kwargs):
  87.         dict.__init__(self, *args, **kwargs)
  88.         dict.__setattr__(self, "config_obj", ConfigParser.ConfigParser())
  89.         dict.__setattr__(self, "filename", filename)
  90.  
  91.         try:
  92.             pathmode = os.stat(filename)[stat.ST_MODE]
  93.             if pathmode & 0022 != 0:
  94.                 return
  95.         except (IOError,OSError):
  96.             if error_if_not_found:
  97.                 log.warn("Config file %s not found or not readable." % filename)
  98.  
  99.             return
  100.  
  101.         log.debug("Reading config file %s" % filename)
  102.  
  103.         f = file(filename, 'r')
  104.         try:
  105.             self.config_obj.readfp(f)
  106.         except:
  107.             log.error("There is an error in the config file: %s" % filename)
  108.             sys.exit(1)
  109.  
  110.         f.close()
  111.  
  112.         for s in self.config_obj.sections():
  113.             opts = []
  114.             for o in self.config_obj.options(s):
  115.                 opts.append((o, self.config_obj.get(s, o)))
  116.  
  117.             self.__setitem__(s, ConfigSection(s, self.config_obj, filename, opts))
  118.  
  119.     def __getattr__(self, sect):
  120.         if sect not in self.keys():
  121.             self.__setitem__(sect, ConfigSection(sect, self.config_obj, self.filename))
  122.  
  123.         return self.__getitem__(sect)
  124.  
  125.     def __setattr__(self, sect, val):
  126.         self.__setitem__(sect, val)
  127.  
  128. # Config file: directories and ports
  129. prop.sys_config_file = '/etc/hp/hplip.conf'
  130. prop.user_config_file = os.path.expanduser('~/.hplip.conf')
  131.  
  132. sys_cfg = Config(prop.sys_config_file, True)
  133. user_cfg = Config(prop.user_config_file)
  134.  
  135.  
  136. # Language settings
  137. try:
  138.     locale.setlocale(locale.LC_ALL, '') # fails on Ubuntu 5.04
  139. except locale.Error:
  140.     log.error("Unable to set locale.")
  141.  
  142. try:
  143.     t, prop.encoding = locale.getdefaultlocale()
  144. except ValueError:
  145.     t = 'en_US'
  146.     prop.encoding = 'ISO8859-1'
  147.  
  148. try:
  149.     prop.lang_code = t[:2].lower()
  150. except TypeError:
  151.     prop.lang_code = 'en'
  152.  
  153. try:
  154.     prop.hpssd_cfg_port = int(sys_cfg.hpssd.port)
  155. except ValueError:
  156.     prop.hpssd_cfg_port = 0
  157.  
  158. prop.version = sys_cfg.hplip.version or 'x.x.x'
  159. prop.home_dir = sys_cfg.dirs.home or os.path.realpath(os.path.normpath(os.getcwd()))
  160. prop.run_dir = sys_cfg.dirs.run or '/var/run'
  161.  
  162. try:
  163.     prop.hpiod_port = int(file(os.path.join(prop.run_dir, 'hpiod.port'), 'r').read())
  164. except:
  165.     prop.hpiod_port = 0
  166.  
  167. try:
  168.     prop.hpssd_port = int(file(os.path.join(prop.run_dir, 'hpssd.port'), 'r').read())
  169. except:
  170.     prop.hpssd_port = 0
  171.  
  172.  
  173. prop.hpiod_host = 'localhost'
  174. prop.hpssd_host = 'localhost'
  175.  
  176. prop.username = pwd.getpwuid(os.getuid())[0]
  177. pdb = pwd.getpwnam(prop.username)
  178. prop.userhome = pdb[5]
  179.  
  180. prop.data_dir = os.path.join(prop.home_dir, 'data')
  181. prop.image_dir = os.path.join(prop.home_dir, 'data', 'images')
  182. prop.xml_dir = os.path.join(prop.home_dir, 'data', 'xml')
  183. prop.models_dir = os.path.join(prop.home_dir, 'data', 'models')
  184.  
  185. prop.max_message_len = 8192
  186. prop.max_message_read = 65536
  187. prop.read_timeout = 90
  188.  
  189. prop.ppd_search_path = '/usr/share;/usr/local/share;/usr/lib;/usr/local/lib;/usr/libexec;/opt;/usr/lib64'
  190. prop.ppd_search_pattern = 'HP-*.ppd.*'
  191. prop.ppd_download_url = 'http://www.linuxprinting.org/ppd-o-matic.cgi'
  192. prop.ppd_file_suffix = '-hpijs.ppd'
  193.  
  194. # Spinner, ala Gentoo Portage
  195. spinner = "\|/-\|/-"
  196. spinpos = 0
  197.  
  198. def update_spinner():
  199.     global spinner, spinpos
  200.     if log.get_level() != log.LOG_LEVEL_DEBUG and sys.stdout.isatty():
  201.         sys.stdout.write("\b" + spinner[spinpos])
  202.         spinpos=(spinpos + 1) % 8
  203.         sys.stdout.flush()
  204.  
  205. def cleanup_spinner():
  206.     if log.get_level() != log.LOG_LEVEL_DEBUG and sys.stdout.isatty():
  207.         sys.stdout.write("\b \b")
  208.         sys.stdout.flush()
  209.  
  210.  
  211. # Internal/messaging errors
  212.  
  213. ERROR_STRINGS = {
  214.                 ERROR_SUCCESS : 'No error',
  215.                 ERROR_UNKNOWN_ERROR : 'Unknown error',
  216.                 ERROR_DEVICE_NOT_FOUND : 'Device not found',
  217.                 ERROR_INVALID_DEVICE_ID : 'Unknown/invalid device-id field',
  218.                 ERROR_INVALID_DEVICE_URI : 'Unknown/invalid device-uri field',
  219.                 ERROR_INVALID_MSG_TYPE : 'Unknown message type',
  220.                 ERROR_INVALID_DATA_ENCODING : 'Unknown data encoding',
  221.                 ERROR_INVALID_CHAR_ENCODING : 'Unknown character encoding',
  222.                 ERROR_DATA_LENGTH_EXCEEDS_MAX : 'Data length exceeds maximum',
  223.                 ERROR_DATA_LENGTH_MISMATCH : "Data length doesn't match length field",
  224.                 ERROR_DATA_DIGEST_MISMATCH : "Digest of data doesn't match digest field",
  225.                 ERROR_INVALID_JOB_ID : 'Invalid job-id',
  226.                 ERROR_DEVICE_IO_ERROR : 'Device I/O error',
  227.                 ERROR_STRING_QUERY_FAILED : 'String/error query failed',
  228.                 ERROR_QUERY_FAILED : 'Query failed',
  229.                 ERROR_GUI_NOT_AVAILABLE : 'hpguid not running',
  230.                 ERROR_NO_CUPS_DEVICES_FOUND : 'No CUPS devices found (deprecated)',
  231.                 ERROR_NO_PROBED_DEVICES_FOUND : 'No probed devices found',
  232.                 ERROR_INVALID_BUS_TYPE : 'Invalid bus type',
  233.                 ERROR_BUS_TYPE_CANNOT_BE_PROBED : 'Bus cannot be probed',
  234.                 ERROR_DEVICE_BUSY : 'Device busy',
  235.                 ERROR_NO_DATA_AVAILABLE : 'No data avaiable',
  236.                 ERROR_INVALID_DEVICEID : 'Invalid/missing DeviceID',
  237.                 ERROR_INVALID_CUPS_VERSION : 'Invlaid CUPS version',
  238.                 ERROR_CUPS_NOT_RUNNING : 'CUPS not running',
  239.                 ERROR_DEVICE_STATUS_NOT_AVAILABLE : 'DeviceStatus not available',
  240.                 ERROR_DATA_IN_SHORT_READ: 'ChannelDataIn short read',
  241.                 ERROR_INVALID_SERVICE_NAME : 'Invalid service name',
  242.                 ERROR_INVALID_USER_ERROR_CODE : 'Invalid user level error code',
  243.                 ERROR_ERROR_INVALID_CHANNEL_ID : 'Invalid channel-id',
  244.                 ERROR_CHANNEL_BUSY : 'Channel busy/in-use',
  245.                 ERROR_CHANNEL_CLOSE_FAILED : 'ChannelClose failed. Channel not open',
  246.                 ERROR_UNSUPPORTED_BUS_TYPE : 'Unsupported bus type',
  247.                 ERROR_DEVICE_DOES_NOT_SUPPORT_OPERATION : 'Device does not support operation',
  248.                 ERROR_INTERNAL : 'Unknown internal error',
  249.                 ERROR_DEVICE_NOT_OPEN : 'Device not open',
  250.                 ERROR_UNABLE_TO_CONTACT_SERVICE : 'Unable to contact service',
  251.                 ERROR_UNABLE_TO_BIND_SOCKET : 'Unable to bind to socket',
  252.                 ERROR_DEVICEOPEN_FAILED_ONE_DEVICE_ONLY : 'Device open failed - 1 open per session allowed',
  253.                 ERROR_DEVICEOPEN_FAILED_DEV_NODE_MOVED : 'Device open failed - device node moved',
  254.                 ERROR_TEST_EMAIL_FAILED : "Email test failed",
  255.                 ERROR_INVALID_HOSTNAME : "Invalid hostname ip address",
  256.                 ERROR_INVALID_PORT_NUMBER : "Invalid JetDirect port number",
  257.                 ERROR_INTERFACE_BUSY : "Interface busy",
  258.                 ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE : "No CUPS queue found for device.",
  259.                 ERROR_UNSUPPORTED_MODEL : "Unsupported printer model.",
  260.                }
  261.  
  262. class Error(Exception):
  263.     def __init__(self, opt=ERROR_INTERNAL):
  264.         self.opt = opt
  265.         self.msg = ERROR_STRINGS.get(opt, ERROR_STRINGS[ERROR_INTERNAL])
  266.         log.debug("Exception: %d (%s)" % (opt, self.msg))
  267.         Exception.__init__(self, self.msg, opt)
  268.  
  269.  
  270. # Make sure True and False are avail. in pre-2.2 versions
  271. try:
  272.     True
  273. except NameError:
  274.     True = (1==1)
  275.     False = not True
  276.  
  277.  
  278.  
  279.  
  280.