7
7
# Christian Dannie Storgaard <cybolic@gmail.com>
18
self.registryCache = None
19
self.logging = logging.getLogger("python-wine.programs")
20
self.debug = self.logging.debug
21
self.error = self.logging.error
23
def __branch_to_dict(self, branch, dict):
25
for path in filter(len, branch.split('\\')):
26
pathname = 'dict%s' % ''.join([ '[\'%s\']' % i for i in parents ])
27
if path not in eval(pathname) or type(eval(pathname)) != type({}):
28
exec('%s[\'%s\'] = {}' % (pathname, path))
32
def __set_branch_values(self, branch, dict, items):
33
# Make sure the dict keys exist
34
dict = self.__branch_to_dict(branch, dict)
36
pathname = 'dict%s' % ''.join([ '[\'%s\']' % i for i in filter(len, branch.split('\\')) ])
37
for key, value in items.iteritems():
39
exec ('%s[\'%s\'] = value' % (pathname, key.replace('\\', '\\\\').replace("'", '\\')))
41
self.error("Error in registry! Pathname: %s\tKey: %s\tValue: %s" % (pathname, key, value))
44
def _writeRegistry(self, registrycontent):
45
regfilename = util.tempname('vineyard-setregistry-', '.reg')
46
regfile = open(regfilename, "w")
47
regfile.write(registrycontent)
49
returnvalue = subprocess.call(["regedit", regfilename], env=os.environ)
50
#os.remove(regfilename)
53
def __get_branch(self, branch=None, quiet=True):
56
process = subprocess.Popen(["regedit", "/E", "-"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
59
process = subprocess.Popen(["regedit", "/E", "-", branch], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
61
buffer = process.stdout.readline()
64
buffer = process.stdout.readline()
65
#if process.returncode and not quiet:
66
if registry == '' or registry.strip() == 'Success':
68
self.error("Warning: Registry branch '%s' doesn't exist." % branch)
72
def __get_branch_as_dict(self, branch=None):
73
registry = self.__get_branch(branch)
82
registrysplit = filter(len, [ i.strip() for i in registry.split("\r\n") ])+ ['[]']
83
for linenr in range(len(registrysplit)):
84
line = registrysplit[linenr]
86
if line.startswith('['):
87
""" If line is section header """
88
# Set the values of the last section, if any
90
registry_dict = self.__set_branch_values(path, registry_dict, values)
91
# Get the section path and start a new section values dict
92
path = ':'.join(line[1:].split(']')[:-1])
94
elif line.startswith('"') or line.startswith('@'):
95
""" If line is key/value """
96
key = line.split('=')[0].replace('"','')
97
value = "=".join(line.split('=')[1:]).strip()
98
value_is_string = True
99
value_type = value.split(':')[0].lower()
100
""" If value is multi-line """
101
if value.strip().endswith('\\'):
102
value = "%s%s" % (value.strip()[:-1], registrysplit[linenr+1].strip())
104
while value.strip().endswith('\\'):
105
value = value[:-1] + registrysplit[linenr].strip()
107
if value.endswith('\\'):
109
""" See what type of value this is.
110
For more info, see http://technet.microsoft.com/en-us/library/bb727154.aspx
112
if value_type.startswith('hex(2)'):
113
""" Expanded String """
115
new_value = util.hextoutf8(value)
116
original_value = value
118
except UnicodeDecodeError:
119
# This won't convert, it's probably an actual hex value, and not just stored as one
120
#print "Error in path \"%s\", string:" % path, value
121
value_is_string = False
122
print "Couldn't read registry! This is a serious error, please report this error along with this text at https://bugs.launchpad.net/vineyard"
123
print path, key, value_type, value
125
elif value_type.startswith('hex(7)'):
127
value_is_string = False
129
value = filter(len, util.hextoutf8(value).split('\x00'))
131
print "Couldn't read registry! This is a serious error, please report this error along with this text at https://bugs.launchpad.net/vineyard"
132
print path, key, value_type, value
134
elif value_type.startswith('hex'):
136
value_is_string = False
138
elif value_type.startswith('dword'):
139
value_is_string = False
140
elif value_type.startswith('null'):
141
value_is_string = False
143
elif value_type.startswith('quote') or value.startswith('str') or value.startswith('str(2)'):
146
if value.strip().startswith('"') and value.replace('\x00','').strip().endswith('"'):
147
value = '"'.join(value.strip().split('"')[1:-1])
150
#value = value.encode('utf-8').decode('string_escape').decode('utf-8').replace('\\\\', '\\').replace('\\\\', '\\').replace('\x00','')
151
if type(value) == list:
152
value = [ util.stringtoutf8(i) for i in value ]
154
value = util.stringtoutf8(value)
155
except UnicodeDecodeError:
156
print "Couldn't read registry! This is a serious error, please report this error along with this text at https://bugs.launchpad.net/vineyard"
157
print path, key, value_type, value.encode('hex')
161
values['_%s' % key] = original_value
164
def __branchpath_in_dict(self, dict, branch):
166
self.__get_dict_from_branchpath(dict, branch)
171
def __get_dict_from_branchpath(self, dict, branch):
173
return eval('dict%s' % ''.join([ '[\'%s\']' % i for i in filter(len, branch.split('\\'))]))
177
def __set_dict_from_branchpath(self, dict, branch, value):
178
exec('dict%s = value' % ''.join([ '[\'%s\']' % i for i in filter(len, branch.split('\\'))]))
181
def get(self, branch=None, findkey=None, quiet=True):
183
fullbranch = '%s\\%s' % (branch, findkey)
187
reg = self.__get_branch_as_dict(branch)
192
reg = self.__get_dict_from_branchpath(reg, branch)
196
retvalue = reg[findkey]
204
def set(self, branches):
205
# Set registry values
206
# Branches should be a dict similar to:
208
# 'HKEY_CURRENT_USER\\Software\\Wine':
209
# {"Version": "winnt"},
210
# 'HKEY_USERS\\S-1-5-4\\Control Panel\\Desktop':
211
# {"FontSmoothing": "2"}
215
registry = "REGEDIT4\n"
218
for b in sorted(branches.keys()):
219
branchwalk = b.split('\\')
220
for i in range(len(branchwalk)-1):
221
branch = "\n[%s\\%s]\n" % (branchwalk[0], '\\'.join(branchwalk[1:i+2]))
222
if branch not in definedbranches:
224
definedbranches.append(branch)
226
for key,value in sorted(branches[b].iteritems()):
227
if value == '-' or value == None:
228
registry += "\"%s\"=-\n" % str(key).encode('utf-8').encode('string_escape')
229
elif str(value).startswith('hex:') or str(value).startswith('dword:'):
230
registry += "\"%s\"=%s\n" % (str(key).encode('utf-8').encode('string_escape'), str(value))
233
registry += "\"%s\"=\"%s\"\n" % (str(key).encode('utf-8').encode('string_escape'), str(value).encode('utf-8').encode('string_escape').replace('"', '\\"'))
235
print "Error:",key,value
237
self._writeRegistry(registry)
240
self._wineprocess = subprocess.Popen("wineserver -p10", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
18
self.registryCache = None
19
self.logging = logging.getLogger("python-wine.programs")
20
self.debug = self.logging.debug
21
self.error = self.logging.error
23
def __branch_to_dict(self, branch, dict):
25
for path in filter(len, branch.split('\\')):
26
pathname = 'dict%s' % ''.join([ '[\'%s\']' % i for i in parents ])
27
if path not in eval(pathname) or type(eval(pathname)) != type({}):
28
exec('%s[\'%s\'] = {}' % (pathname, path))
32
def __set_branch_values(self, branch, dict, items):
33
# Make sure the dict keys exist
34
dict = self.__branch_to_dict(branch, dict)
36
pathname = 'dict%s' % ''.join([ '[\'%s\']' % i for i in filter(len, branch.split('\\')) ])
37
for key, value in items.iteritems():
39
exec ('%s[\'%s\'] = value' % (pathname, key.replace('\\', '\\\\').replace("'", '\\')))
41
self.error("Error in registry! Pathname: %s\tKey: %s\tValue: %s" % (pathname, key, value))
44
def _writeRegistry(self, registrycontent):
45
regfilename = util.tempname('vineyard-setregistry-', '.reg')
46
regfile = open(regfilename, "w")
47
regfile.write(registrycontent)
49
returnvalue = subprocess.call(["regedit", regfilename], env=os.environ)
50
#os.remove(regfilename)
53
def __get_branch(self, branch=None, quiet=True):
54
if branch.startswith('HKEY_LOCAL_MACHINE') and branch != 'HKEY_LOCAL_MACHINE\\System\\MountedDevices':
55
registry_file = open('%s/system.reg' % os.environ['WINEPREFIX'], 'r')
56
registry = registry_file.read()
58
#print "Using system.reg file as registry."
59
return ('HKEY_LOCAL_MACHINE', registry)
60
elif branch.startswith('HKEY_CURRENT_USER'):
61
registry_file = open('%s/user.reg' % os.environ['WINEPREFIX'], 'r')
62
registry = registry_file.read()
64
#print "Using user.reg file as registry."
65
return ('HKEY_CURRENT_USER', registry)
66
elif branch.startswith('HKEY_USERS\\.Default'):
67
registry_file = open('%s/userdef.reg' % os.environ['WINEPREFIX'], 'r')
68
registry = registry_file.read()
70
#print "Using userdef.reg file as registry."
71
return ('HKEY_USERS\\.Default', registry)
73
#print "Using regedit to read registry."
76
process = subprocess.Popen(["regedit", "/E", "-"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
79
process = subprocess.Popen(["regedit", "/E", "-", branch], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
81
buffer = process.stdout.readline()
84
buffer = process.stdout.readline()
85
#if process.returncode and not quiet:
86
if registry == '' or registry.strip() == 'Success':
88
self.error("Warning: Registry branch '%s' doesn't exist." % branch)
92
def __branchpath_in_dict(self, dict, branch):
94
self.__get_dict_from_branchpath(dict, branch)
99
def __get_dict_from_branchpath(self, dict, branch):
101
return eval('dict%s' % ''.join([ '[\'%s\']' % i for i in filter(len, branch.split('\\'))]))
105
def __set_dict_from_branchpath(self, dict, branch, value):
106
exec('dict%s = value' % ''.join([ '[\'%s\']' % i for i in filter(len, branch.split('\\'))]))
109
def get(self, branch=None, findkey=None, quiet=True):
111
fullbranch = '%s\\%s' % (branch, findkey)
115
#reg = self.__get_branch_as_dict(branch)
116
branch_output = self.__get_branch(branch)
117
if type(branch_output) == tuple:
118
reg = parsers.parseRegistry(branch_output[1], branch_output[0])
120
reg = parsers.parseRegistry(branch_output)
126
reg = self.__get_dict_from_branchpath(reg, branch)
135
retvalue = reg[findkey]
143
def set(self, branches):
144
# Set registry values
145
# Branches should be a dict similar to:
147
# 'HKEY_CURRENT_USER\\Software\\Wine':
148
# {"Version": "winnt"},
149
# 'HKEY_USERS\\S-1-5-4\\Control Panel\\Desktop':
150
# {"FontSmoothing": "2"}
154
registry = "REGEDIT4\n"
157
for b in sorted(branches.keys()):
158
branchwalk = b.split('\\')
159
for i in range(len(branchwalk)-1):
160
branch = "\n[%s\\%s]\n" % (branchwalk[0], '\\'.join(branchwalk[1:i+2]))
161
if branch not in definedbranches:
163
definedbranches.append(branch)
165
for key,value in sorted(branches[b].iteritems()):
166
if value == '-' or value == None:
167
registry += "\"%s\"=-\n" % str(key).encode('utf-8').encode('string_escape')
168
elif str(value).startswith('hex:') or str(value).startswith('dword:'):
169
registry += "\"%s\"=%s\n" % (str(key).encode('utf-8').encode('string_escape'), str(value))
172
registry += "\"%s\"=\"%s\"\n" % (str(key).encode('utf-8').encode('string_escape'), str(value).encode('utf-8').encode('string_escape').replace('"', '\\"'))
174
print "Error:",key,value
176
self._writeRegistry(registry)
179
self._wineprocess = subprocess.Popen("wineserver -p10", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)