File: options.py

package info (click to toggle)
tinyerp-client 3.4.2-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 4,832 kB
  • ctags: 1,024
  • sloc: python: 7,566; sh: 2,253; makefile: 81
file content (157 lines) | stat: -rw-r--r-- 5,511 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
##############################################################################
#
# Copyright (c) 2004 TINY SPRL. (http://tiny.be) All Rights Reserved.
#                    Fabien Pinckaers <fp@tiny.Be>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import ConfigParser,optparse
import os
import gtk

def get_home_dir():
	"""Return the closest possible equivalent to a 'home' directory.
	For Posix systems, this is $HOME, and on NT it's $HOMEDRIVE\$HOMEPATH.
	Currently only Posix and NT are implemented, a HomeDirError exception is
	raised for all other OSes. """

	if os.name == 'posix':
		return os.path.expanduser('~')
	elif os.name == 'nt':
		try:
			return os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH'])
		except:
			try:
				import _winreg as wreg
				key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
				homedir = wreg.QueryValueEx(key,'Personal')[0]
				key.Close()
				return homedir
			except:
				return 'C:\\'
	elif os.name == 'dos':
		return 'C:\\'
	else:
		return '.'

class configmanager(object):
	def __init__(self,fname=None):
		self.options = {
			'login.login': 'demo',
			'login.server': 'localhost',
			'login.port': '8069',
			'login.secure': False,
			'client.modepda': False,
			'client.toolbar': 'both',
			'client.theme': 'none',
			'path.share': os.path.dirname(__file__),
			'path.pixmaps': os.path.dirname(__file__),
			'tip.autostart': True,
			'tip.position': 0,
			'survey.position': 0,
			'form.autosave': False,
			'printer.preview': True,
			'printer.softpath': 'none',
			'printer.softpath_html': 'none',
			'printer.path': 'none',
			'logging.logger': '',
			'logging.level': 'DEBUG',
			'logging.output': 'stdout',
			'logging.verbose': False,
			'client.default_path': os.path.expanduser('~'),
			'support.recipient': 'support@tiny.be',
			'support.support_id' : '',
		}
		parser = optparse.OptionParser(version=_("Tiny ERP Client %s" % tinyerp_version))
		parser.add_option("-c", "--config", dest="config",help=_("specify alternate config file"))
		parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help=_("enable basic debugging"))
		parser.add_option("-d", "--log", dest="log_logger", default='', help=_("specify channels to log"))
		parser.add_option("-l", "--log-level", dest="log_level",default='ERROR', help=_("specify the log level: INFO, DEBUG, WARNING, ERROR, CRITICAL"))
		parser.add_option("-u", "--user", dest="login", help=_("specify the user login"))
		parser.add_option("-p", "--port", dest="port", help=_("specify the server port"))
		parser.add_option("-s", "--server", dest="server", help=_("specify the server ip/name"))
		(opt, args) = parser.parse_args()


		self.rcfile = fname or opt.config or os.environ.get('TERPRC') or os.path.join(get_home_dir(), '.terprc')
		self.load()

		if opt.verbose:
			self.options['logging.verbose']=True
		self.options['logging.logger'] = opt.log_logger
		self.options['logging.level'] = opt.log_level
	
		for arg in ('login', 'port', 'server'):
			if getattr(opt, arg):
				self.options['login.'+arg] = getattr(opt, arg)

	def save(self, fname = None):
		try:
			p = ConfigParser.ConfigParser()
			sections = {}
			for o in self.options.keys():
				if not len(o.split('.'))==2:
					continue
				osection,oname = o.split('.')
				if not p.has_section(osection):
					p.add_section(osection)
				p.set(osection,oname,self.options[o])
			p.write(file(self.rcfile,'wb'))
		except:
			import logging
			log = logging.getLogger('common.options')
			log.warn('Unable to write config file %s !'% (self.rcfile,))
		return True

	def load(self, fname=None):
		try:
			self.rcexist = False
			if not os.path.isfile(self.rcfile):
				self.save()
				return False
			self.rcexist = True

			p = ConfigParser.ConfigParser()
			p.read([self.rcfile])
			for section in p.sections():
				for (name,value) in p.items(section):
					if value=='True' or value=='true':
						value = True
					if value=='False' or value=='false':
						value = False
					self.options[section+'.'+name] = value
		except Exception, e:
			import logging
			log = logging.getLogger('common.options')
			log.warn('Unable to read config file %s !'% (self.rcfile,))
		return True

	def __setitem__(self, key, value):
		self.options[key]=value

	def __getitem__(self, key):
		return self.options[key]

options = configmanager()