home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / hplip / base / g.py < prev    next >
Encoding:
Python Source  |  2006-08-30  |  9.8 KB  |  274 lines

  1. # -*- coding: utf-8 -*-
  2. #
  3. # (c) Copyright 2003-2006 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 = 8
  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, *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.             return
  97.         
  98.         f = file(filename, 'r')
  99.         self.config_obj.readfp(f)
  100.         f.close()
  101.  
  102.         for s in self.config_obj.sections():
  103.             opts = []
  104.             for o in self.config_obj.options(s):
  105.                 opts.append((o, self.config_obj.get(s, o)))
  106.  
  107.             self.__setitem__(s, ConfigSection(s, self.config_obj, filename, opts))
  108.         
  109.     def __getattr__(self, sect):
  110.         if sect not in self.keys():
  111.             self.__setitem__(sect, ConfigSection(sect, self.config_obj, self.filename))
  112.  
  113.         return self.__getitem__(sect)
  114.  
  115.     def __setattr__(self, sect, val):
  116.         self.__setitem__(sect, val)
  117.  
  118. # Config file: directories and ports
  119. prop.sys_config_file = '/etc/hp/hplip.conf'
  120. prop.user_config_file = os.path.expanduser('~/.hplip.conf')
  121.   
  122. sys_cfg = Config(prop.sys_config_file)
  123. user_cfg = Config(prop.user_config_file)
  124.  
  125.  
  126. # Language settings
  127. try:
  128.     locale.setlocale(locale.LC_ALL, '') # fails on Ubuntu 5.04
  129. except locale.Error:
  130.     # TODO: Is this the right thing to do?
  131.     log.error("Unable to set locale.")
  132.     locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  133.     
  134. try:
  135.     t, prop.encoding = locale.getdefaultlocale()
  136. except ValueError:
  137.     t = 'en_US'
  138.     prop.encoding = 'ISO8859-1'
  139.  
  140. try:
  141.     prop.lang_code = t[:2].lower()
  142. except TypeError:
  143.     prop.lang_code = 'en'
  144.  
  145. try:
  146.     prop.hpssd_cfg_port = int(sys_cfg.hpssd.port)
  147. except ValueError:
  148.     prop.hpssd_cfg_port = 0
  149.     
  150. prop.version = sys_cfg.hplip.version or 'x.x.x'
  151. prop.home_dir = sys_cfg.dirs.home or os.path.realpath(os.path.normpath(os.getcwd()))
  152. prop.run_dir = sys_cfg.dirs.run or '/var/run'
  153.  
  154. try:
  155.     prop.hpiod_port = int(file(os.path.join(prop.run_dir, 'hpiod.port'), 'r').read())
  156. except:
  157.     prop.hpiod_port = 0
  158.  
  159. try:
  160.     prop.hpssd_port = int(file(os.path.join(prop.run_dir, 'hpssd.port'), 'r').read())
  161. except:
  162.     prop.hpssd_port = 0
  163.  
  164.  
  165. prop.hpiod_host = 'localhost'
  166. prop.hpssd_host = 'localhost'
  167.  
  168. prop.username = pwd.getpwuid(os.getuid())[0]
  169. pdb = pwd.getpwnam(prop.username)
  170. prop.userhome = pdb[5]
  171.  
  172. prop.data_dir = os.path.join(prop.home_dir, 'data')
  173. prop.i18n_dir = os.path.join(prop.home_dir, 'data', 'qm')
  174. prop.image_dir = os.path.join(prop.home_dir, 'data', 'images')
  175. prop.xml_dir = os.path.join(prop.home_dir, 'data', 'xml')
  176.  
  177. prop.max_message_len = 8192
  178. prop.max_message_read = 65536
  179. prop.read_timeout = 90
  180.  
  181. prop.ppd_search_path = '/usr/share;/usr/local/share;/usr/lib;/usr/local/lib;/usr/libexec;/opt'
  182. prop.ppd_search_pattern = 'HP-*.ppd.*'
  183. prop.ppd_download_url = 'http://www.linuxprinting.org/ppd-o-matic.cgi'
  184. prop.ppd_file_suffix = '-hpijs.ppd'
  185.  
  186. prop.errors_file = os.path.join(prop.home_dir, 'data', 'xml', 'errors.xml')
  187. prop.strings_file = os.path.join(prop.home_dir, 'data', 'xml', 'strings.xml')
  188. prop.models_file = os.path.join(prop.home_dir, 'data', 'xml', 'models.xml')
  189.  
  190. # Spinner, ala Gentoo Portage
  191. spinner = "\|/-\|/-"
  192. #spinner = "oOo.oOo."
  193. spinpos = 0
  194.  
  195. def update_spinner():
  196.     global spinner, spinpos
  197.     if sys.stdout.isatty():
  198.         sys.stdout.write("\b" + spinner[spinpos])
  199.         spinpos=(spinpos + 1) % 8
  200.         sys.stdout.flush()
  201.  
  202.  
  203. # Internal/messaging errors
  204.  
  205. ERROR_STRINGS = {
  206.                 ERROR_SUCCESS : 'No error',
  207.                 ERROR_UNKNOWN_ERROR : 'Unknown error',
  208.                 ERROR_DEVICE_NOT_FOUND : 'Device not found',
  209.                 ERROR_INVALID_DEVICE_ID : 'Unknown/invalid device-id field',
  210.                 ERROR_INVALID_DEVICE_URI : 'Unknown/invalid device-uri field',
  211.                 ERROR_INVALID_MSG_TYPE : 'Unknown message type',
  212.                 ERROR_INVALID_DATA_ENCODING : 'Unknown data encoding',
  213.                 ERROR_INVALID_CHAR_ENCODING : 'Unknown character encoding',
  214.                 ERROR_DATA_LENGTH_EXCEEDS_MAX : 'Data length exceeds maximum',
  215.                 ERROR_DATA_LENGTH_MISMATCH : "Data length doesn't match length field",
  216.                 ERROR_DATA_DIGEST_MISMATCH : "Digest of data doesn't match digest field",
  217.                 ERROR_INVALID_JOB_ID : 'Invalid job-id',
  218.                 ERROR_DEVICE_IO_ERROR : 'Device I/O error',
  219.                 ERROR_STRING_QUERY_FAILED : 'String/error query failed',
  220.                 ERROR_QUERY_FAILED : 'Query failed',
  221.                 ERROR_GUI_NOT_AVAILABLE : 'hpguid not running',
  222.                 ERROR_NO_CUPS_DEVICES_FOUND : 'No CUPS devices found (deprecated)',
  223.                 ERROR_NO_PROBED_DEVICES_FOUND : 'No probed devices found',
  224.                 ERROR_INVALID_BUS_TYPE : 'Invalid bus type',
  225.                 ERROR_BUS_TYPE_CANNOT_BE_PROBED : 'Bus cannot be probed',
  226.                 ERROR_DEVICE_BUSY : 'Device busy',
  227.                 ERROR_NO_DATA_AVAILABLE : 'No data avaiable',
  228.                 ERROR_INVALID_DEVICEID : 'Invalid/missing DeviceID',
  229.                 ERROR_INVALID_CUPS_VERSION : 'Invlaid CUPS version',
  230.                 ERROR_CUPS_NOT_RUNNING : 'CUPS not running',
  231.                 ERROR_DEVICE_STATUS_NOT_AVAILABLE : 'DeviceStatus not available',
  232.                 ERROR_DATA_IN_SHORT_READ: 'ChannelDataIn short read',
  233.                 ERROR_INVALID_SERVICE_NAME : 'Invalid service name',
  234.                 ERROR_INVALID_USER_ERROR_CODE : 'Invalid user level error code',
  235.                 ERROR_ERROR_INVALID_CHANNEL_ID : 'Invalid channel-id',
  236.                 ERROR_CHANNEL_BUSY : 'Channel busy/in-use',
  237.                 ERROR_CHANNEL_CLOSE_FAILED : 'ChannelClose failed. Channel not open',
  238.                 ERROR_UNSUPPORTED_BUS_TYPE : 'Unsupported bus type',
  239.                 ERROR_DEVICE_DOES_NOT_SUPPORT_OPERATION : 'Device does not support operation',
  240.                 ERROR_INTERNAL : 'Unknown internal error',
  241.                 ERROR_DEVICE_NOT_OPEN : 'Device not open',
  242.                 ERROR_UNABLE_TO_CONTACT_SERVICE : 'Unable to contact service',
  243.                 ERROR_UNABLE_TO_BIND_SOCKET : 'Unable to bind to socket',
  244.                 ERROR_DEVICEOPEN_FAILED_ONE_DEVICE_ONLY : 'Device open failed - 1 open per session allowed',
  245.                 ERROR_DEVICEOPEN_FAILED_DEV_NODE_MOVED : 'Device open failed - device node moved',
  246.                 ERROR_TEST_EMAIL_FAILED : "Email test failed",
  247.                 #ERROR_SMTP_CONNECT_ERROR : "SMTP server connect error",
  248.                 #ERROR_SMTP_RECIPIENTS_REFUSED : "SMTP recipients refused",
  249.                 #ERROR_SMTP_HELO_ERROR : "SMTP HELO error",
  250.                 #ERROR_SMTP_SENDER_REFUSED : "STMP sender refused",
  251.                 #ERROR_SMTP_DATA_ERROR : "SMTP data error",
  252.                 ERROR_INVALID_HOSTNAME : "Invalid hostname ip address",
  253.                 ERROR_INVALID_PORT_NUMBER : "Invalid JetDirect port number",
  254.                 ERROR_INTERFACE_BUSY : "Interface busy",
  255.                 ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE : "No CUPS queue found for device.",
  256.                 ERROR_UNSUPPORTED_MODEL : "Unsupported printer model.",
  257.                }
  258.  
  259. class Error(Exception):
  260.     def __init__(self, opt=ERROR_INTERNAL):
  261.         self.opt = opt
  262.         self.msg = ERROR_STRINGS.get(opt, ERROR_STRINGS[ERROR_INTERNAL])
  263.         log.debug("Exception: %d (%s)" % (opt, self.msg))
  264.         Exception.__init__(self, self.msg, opt)
  265.  
  266.  
  267. # Make sure True and False are avail. in pre-2.2 versions
  268. try:
  269.     True
  270. except NameError:
  271.     True = (1==1)
  272.     False = not True
  273.     
  274.