merge
[openerp-client.git] / bin / options.py
blob306d3e6efcf56b8b20ea9b43c6307b8a64780d77
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
6 # $Id$
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 ##############################################################################
31 import ConfigParser,optparse
32 import os, sys
33 import gtk
34 import gettext
36 def get_home_dir():
37 """Return the closest possible equivalent to a 'home' directory.
38 For Posix systems, this is $HOME, and on NT it's $HOMEDRIVE\$HOMEPATH.
39 Currently only Posix and NT are implemented, a HomeDirError exception is
40 raised for all other OSes. """
42 if os.name == 'posix':
43 return os.path.expanduser('~')
44 elif os.name == 'nt':
45 try:
46 return os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH'])
47 except:
48 try:
49 import _winreg as wreg
50 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
51 homedir = wreg.QueryValueEx(key,'Personal')[0]
52 key.Close()
53 return homedir
54 except:
55 return 'C:\\'
56 elif os.name == 'dos':
57 return 'C:\\'
58 else:
59 return '.'
61 class configmanager(object):
62 def __init__(self,fname=None):
63 self.options = {
64 'login.login': 'demo',
65 'login.server': 'localhost',
66 'login.port': '8070',
67 'login.protocol': 'socket://',
68 'login.db': 'terp',
69 'client.modepda': False,
70 'client.toolbar': 'both',
71 'client.theme': 'none',
72 'path.share': os.path.join(sys.prefix, 'share/tinyerp-client/'),
73 'path.pixmaps': os.path.join(sys.prefix, 'share/pixmaps/tinyerp-client/'),
74 'tip.autostart': False,
75 'tip.position': 0,
76 'survey.position': 0,
77 'form.autosave': False,
78 'printer.preview': True,
79 'printer.softpath': 'none',
80 'printer.softpath_html': 'none',
81 'printer.path': 'none',
82 'logging.logger': '',
83 'logging.level': 'DEBUG',
84 'logging.output': 'stdout',
85 'logging.verbose': False,
86 'client.default_path': os.path.expanduser('~'),
87 'support.recipient': 'support@tiny.be',
88 'support.support_id' : '',
89 'form.toolbar': True,
90 'client.form_tab': 'left',
91 'client.form_tab_orientation': 0,
92 'client.lang': False,
93 'client.filetype': {},
94 'help.index': 'http://www.openerp.com/documentation/user-manual/',
95 'help.context': 'http://www.openerp.com/scripts/context_index.php'
97 parser = optparse.OptionParser(version=_("Tiny ERP Client %s" % tinyerp_version))
98 parser.add_option("-c", "--config", dest="config",help=_("specify alternate config file"))
99 parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help=_("enable basic debugging"))
100 parser.add_option("-d", "--log", dest="log_logger", default='', help=_("specify channels to log"))
101 parser.add_option("-l", "--log-level", dest="log_level",default='ERROR', help=_("specify the log level: INFO, DEBUG, WARNING, ERROR, CRITICAL"))
102 parser.add_option("-u", "--user", dest="login", help=_("specify the user login"))
103 parser.add_option("-p", "--port", dest="port", help=_("specify the server port"))
104 parser.add_option("-s", "--server", dest="server", help=_("specify the server ip/name"))
105 (opt, args) = parser.parse_args()
107 self.rcfile = self._get_rcfile(fname, opt.config)
108 self.load()
110 if opt.verbose:
111 self.options['logging.verbose']=True
112 self.options['logging.logger'] = opt.log_logger
113 self.options['logging.level'] = opt.log_level
115 for arg in ('login', 'port', 'server'):
116 if getattr(opt, arg):
117 self.options['login.'+arg] = getattr(opt, arg)
119 def _get_rcfile(self, fname, optconfigfile):
120 rcfile = fname or optconfigfile or os.environ.get('TERPRC') or os.path.join(get_home_dir(), '.terprc')
121 if not os.path.exists(rcfile):
122 import logging
123 log = logging.getLogger('common.options')
124 additional_info = ""
125 if optconfigfile:
126 additional_info = " Be sure to specify an absolute path name if you are using the '-c' command line switch"
127 log.warn('Config file %s does not exist !%s'% (rcfile, additional_info ))
128 return os.path.abspath(rcfile)
130 def save(self, fname = None):
131 try:
132 p = ConfigParser.ConfigParser()
133 sections = {}
134 for o in self.options.keys():
135 if not len(o.split('.'))==2:
136 continue
137 osection,oname = o.split('.')
138 if not p.has_section(osection):
139 p.add_section(osection)
140 p.set(osection,oname,self.options[o])
141 p.write(file(self.rcfile,'wb'))
142 except:
143 import logging
144 log = logging.getLogger('common.options')
145 log.warn('Unable to write config file %s !'% (self.rcfile,))
146 return True
149 def load(self, fname=None):
150 try:
151 self.rcexist = False
152 if not os.path.isfile(self.rcfile):
153 self.save()
154 return False
155 self.rcexist = True
157 p = ConfigParser.ConfigParser()
158 p.read([self.rcfile])
159 for section in p.sections():
160 for (name,value) in p.items(section):
161 if value=='True' or value=='true':
162 value = True
163 if value=='False' or value=='false':
164 value = False
165 self.options[section+'.'+name] = value
166 except Exception, e:
167 import logging
168 log = logging.getLogger('common.options')
169 log.warn('Unable to read config file %s !'% (self.rcfile,))
170 return True
172 def __setitem__(self, key, value):
173 self.options[key]=value
175 def __getitem__(self, key):
176 return self.options[key]
178 options = configmanager()
181 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: