13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
17
"""Win32-specific helper functions
19
19
Only one dependency: ctypes should be installed.
30
from breezy.i18n import gettext
28
if sys.platform == 'win32':
29
_major,_minor,_build,_platform,_text = sys.getwindowsversion()
32
# The operating system platform.
33
# This member can be one of the following values.
34
# ========================== ======================================
36
# -------------------------- --------------------------------------
37
# VER_PLATFORM_WIN32_NT The operating system is Windows Vista,
38
# 2 Windows Server "Longhorn",
39
# Windows Server 2003, Windows XP,
40
# Windows 2000, or Windows NT.
42
# VER_PLATFORM_WIN32_WINDOWS The operating system is Windows Me,
43
# 1 Windows 98, or Windows 95.
44
# ========================== ======================================
48
# don't care about real Windows name, just to force safe operations
54
# We can cope without it; use a separate variable to help pyflakes
61
if winver == 'Windows 98':
62
create_buffer = ctypes.create_string_buffer
65
create_buffer = ctypes.create_unicode_buffer
33
69
# Special Win32 API constants
48
82
MAX_COMPUTERNAME_LENGTH = 31
50
# Registry data type ids
55
def debug_memory_win32api(message='', short=True):
56
"""Use trace.note() to dump the running memory info."""
58
from breezy import trace
59
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
60
"""Used by GetProcessMemoryInfo"""
61
_fields_ = [('cb', ctypes.c_ulong),
62
('PageFaultCount', ctypes.c_ulong),
63
('PeakWorkingSetSize', ctypes.c_size_t),
64
('WorkingSetSize', ctypes.c_size_t),
65
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
66
('QuotaPagedPoolUsage', ctypes.c_size_t),
67
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
68
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
69
('PagefileUsage', ctypes.c_size_t),
70
('PeakPagefileUsage', ctypes.c_size_t),
71
('PrivateUsage', ctypes.c_size_t),
73
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
74
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
75
ret = ctypes.windll.psapi.GetProcessMemoryInfo(
76
cur_process, ctypes.byref(mem_struct), ctypes.sizeof(mem_struct))
78
trace.note(gettext('Failed to GetProcessMemoryInfo()'))
80
info = {'PageFaultCount': mem_struct.PageFaultCount,
81
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
82
'WorkingSetSize': mem_struct.WorkingSetSize,
83
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
84
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
85
'QuotaPeakNonPagedPoolUsage':
86
mem_struct.QuotaPeakNonPagedPoolUsage,
87
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
88
'PagefileUsage': mem_struct.PagefileUsage,
89
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
90
'PrivateUsage': mem_struct.PrivateUsage,
93
# using base-2 units (see HACKING.txt).
94
trace.note(gettext('WorkingSize {0:>7}KiB'
95
'\tPeakWorking {1:>7}KiB\t{2}').format(
96
info['WorkingSetSize'] / 1024,
97
info['PeakWorkingSetSize'] / 1024,
101
trace.note('%s', message)
102
trace.note(gettext('WorkingSize %8d KiB'),
103
info['WorkingSetSize'] / 1024)
104
trace.note(gettext('PeakWorking %8d KiB'),
105
info['PeakWorkingSetSize'] / 1024)
106
trace.note(gettext('PagefileUsage %8d KiB'),
107
info.get('PagefileUsage', 0) / 1024)
108
trace.note(gettext('PeakPagefileUsage %8d KiB'),
109
info.get('PeakPagefileUsage', 0) / 1024)
110
trace.note(gettext('PrivateUsage %8d KiB'),
111
info.get('PrivateUsage', 0) / 1024)
112
trace.note(gettext('PageFaultCount %8d'), info.get('PageFaultCount', 0))
115
85
def get_console_size(defaultx=80, defaulty=25):
116
86
"""Return size of current console.
137
109
return (defaultx, defaulty)
140
def _get_sh_special_folder_path(csidl):
141
"""Call SHGetSpecialFolderPathW if available, or return None.
143
Result is always unicode (or None).
147
SHGetSpecialFolderPath = \
148
ctypes.windll.shell32.SHGetSpecialFolderPathW
149
except AttributeError:
152
buf = ctypes.create_unicode_buffer(MAX_PATH)
153
if SHGetSpecialFolderPath(None, buf, csidl, 0):
157
112
def get_appdata_location():
158
113
"""Return Application Data location.
159
114
Return None if we cannot obtain location.
161
Windows defines two 'Application Data' folders per user - a 'roaming'
162
one that moves with the user as they logon to different machines, and
163
a 'local' one that stays local to the machine. This returns the 'roaming'
164
directory, and thus is suitable for storing user-preferences, etc.
116
Returned value can be unicode or plain sring.
117
To convert plain string to unicode use
118
s.decode(bzrlib.user_encoding)
166
appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
122
SHGetSpecialFolderPath = \
123
ctypes.windll.shell32.SHGetSpecialFolderPathW
124
except AttributeError:
127
buf = ctypes.create_unicode_buffer(MAX_PATH)
128
if SHGetSpecialFolderPath(None,buf,CSIDL_APPDATA,0):
131
appdata = os.environ.get('APPDATA')
169
# Use APPDATA if defined, will return None if not
170
return os.environ.get('APPDATA')
173
def get_local_appdata_location():
174
"""Return Local Application Data location.
175
Return the same as get_appdata_location() if we cannot obtain location.
177
Windows defines two 'Application Data' folders per user - a 'roaming'
178
one that moves with the user as they logon to different machines, and
179
a 'local' one that stays local to the machine. This returns the 'local'
180
directory, and thus is suitable for caches, temp files and other things
181
which don't need to move with the user.
183
local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
186
# Vista supplies LOCALAPPDATA, but XP and earlier do not.
187
local = os.environ.get('LOCALAPPDATA')
190
return get_appdata_location()
134
# if we fall to this point we on win98
135
# at least try C:/WINDOWS/Application Data
136
windir = os.environ.get('windir')
138
appdata = os.path.join(windir, 'Application Data')
139
if os.path.isdir(appdata):
141
# did not find anything
193
145
def get_home_location():
195
147
Assume on win32 it's the <My Documents> folder.
196
148
If location cannot be obtained return system drive root,
151
Returned value can be unicode or plain sring.
152
To convert plain string to unicode use
153
s.decode(bzrlib.user_encoding)
199
home = _get_sh_special_folder_path(CSIDL_PERSONAL)
202
home = os.environ.get('HOME')
205
homepath = os.environ.get('HOMEPATH')
206
if homepath is not None:
207
return os.path.join(os.environ.get('HOMEDIR', ''), home)
157
SHGetSpecialFolderPath = \
158
ctypes.windll.shell32.SHGetSpecialFolderPathW
159
except AttributeError:
162
buf = ctypes.create_unicode_buffer(MAX_PATH)
163
if SHGetSpecialFolderPath(None,buf,CSIDL_PERSONAL,0):
165
# try for HOME env variable
166
home = os.path.expanduser('~')
208
169
# at least return windows root directory
209
windir = os.environ.get('WINDIR')
170
windir = os.environ.get('windir')
211
return os.path.splitdrive(windir)[0] + '/'
172
return os.path.splitdrive(windir) + '/'
212
173
# otherwise C:\ is good enough for 98% users
216
177
def get_user_name():
217
178
"""Return user name as login name.
218
179
If name cannot be obtained return None.
181
Returned value can be unicode or plain sring.
182
To convert plain string to unicode use
183
s.decode(bzrlib.user_encoding)
221
advapi32 = ctypes.windll.advapi32
222
GetUserName = getattr(advapi32, 'GetUserNameW')
223
except AttributeError:
226
buf = ctypes.create_unicode_buffer(UNLEN + 1)
227
n = ctypes.c_int(UNLEN + 1)
228
if GetUserName(buf, ctypes.byref(n)):
187
advapi32 = ctypes.windll.advapi32
188
GetUserName = getattr(advapi32, 'GetUserName'+suffix)
189
except AttributeError:
192
buf = create_buffer(UNLEN+1)
193
n = ctypes.c_int(UNLEN+1)
194
if GetUserName(buf, ctypes.byref(n)):
230
196
# otherwise try env variables
231
return os.environ.get('USERNAME')
234
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
235
# computer or the cluster associated with the local computer."
236
_WIN32_ComputerNameDnsHostname = 1
197
return os.environ.get('USERNAME', None)
239
200
def get_host_name():
240
201
"""Return host machine name.
241
202
If name cannot be obtained return None.
243
:return: A unicode string representing the host name.
246
buf = ctypes.create_unicode_buffer(MAX_COMPUTERNAME_LENGTH + 1)
247
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH + 1)
249
# Try GetComputerNameEx which gives a proper Unicode hostname
250
GetComputerNameEx = getattr(
251
ctypes.windll.kernel32, 'GetComputerNameExW', None)
252
if (GetComputerNameEx is not None
253
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
254
buf, ctypes.byref(n))):
256
return os.environ.get('COMPUTERNAME')
259
def _ensure_with_dir(path):
260
if (not os.path.split(path)[0] or path.startswith(u'*')
261
or path.startswith(u'?')):
262
return u'./' + path, True
267
def _undo_ensure_with_dir(path, corrected):
274
def glob_one(possible_glob):
275
"""Same as glob.glob().
277
work around bugs in glob.glob()
278
- Python bug #1001604 ("glob doesn't return unicode with ...")
279
- failing expansion for */* with non-iso-8859-* chars
281
corrected_glob, corrected = _ensure_with_dir(possible_glob)
282
glob_files = glob.glob(corrected_glob)
285
# special case to let the normal code path handle
286
# files that do not exist, etc.
287
glob_files = [possible_glob]
289
glob_files = [_undo_ensure_with_dir(elem, corrected)
290
for elem in glob_files]
291
return [elem.replace(u'\\', u'/') for elem in glob_files]
294
def glob_expand(file_list):
295
"""Replacement for glob expansion by the shell.
297
Win32's cmd.exe does not do glob expansion (eg ``*.py``), so we do our own
300
:param file_list: A list of filenames which may include shell globs.
301
:return: An expanded list of filenames.
303
Introduced in breezy 0.18.
307
expanded_file_list = []
308
for possible_glob in file_list:
309
expanded_file_list.extend(glob_one(possible_glob))
310
return expanded_file_list
313
def get_app_path(appname):
314
r"""Look up in Windows registry for full path to application executable.
315
Typically, applications create subkey with their basename
316
in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
318
:param appname: name of application (if no filename extension
319
is specified, .exe used)
320
:return: full path to aplication executable from registry,
321
or appname itself if nothing found.
326
if not os.path.splitext(basename)[1]:
327
basename = appname + '.exe'
330
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
331
'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
333
except EnvironmentError:
204
Returned value can be unicode or plain sring.
205
To convert plain string to unicode use
206
s.decode(bzrlib.user_encoding)
338
path, type_id = _winreg.QueryValueEx(hkey, '')
342
_winreg.CloseKey(hkey)
344
if type_id == REG_SZ:
349
def set_file_attr_hidden(path):
350
"""Set file attributes to hidden if possible"""
351
from ctypes.wintypes import BOOL, DWORD, LPWSTR
353
# <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
354
SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
355
SetFileAttributes.argtypes = LPWSTR, DWORD
356
SetFileAttributes.restype = BOOL
357
FILE_ATTRIBUTE_HIDDEN = 2
358
if not SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN):
359
e = ctypes.WinError()
361
trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
364
def _command_line_to_argv(command_line, argv, single_quotes_allowed=False):
365
"""Convert a Unicode command line into a list of argv arguments.
367
It performs wildcard expansion to make wildcards act closer to how they
368
work in posix shells, versus how they work by default on Windows. Quoted
369
arguments are left untouched.
371
:param command_line: The unicode string to split into an arg list.
372
:param single_quotes_allowed: Whether single quotes are accepted as quoting
373
characters like double quotes. False by
375
:return: A list of unicode strings.
377
# First, split the command line
378
s = cmdline.Splitter(
379
command_line, single_quotes_allowed=single_quotes_allowed)
381
# Bug #587868 Now make sure that the length of s agrees with sys.argv
382
# we do this by simply counting the number of arguments in each. The counts should
383
# agree no matter what encoding sys.argv is in (AFAIK)
384
# len(arguments) < len(sys.argv) should be an impossibility since python gets
385
# args from the very same PEB as does GetCommandLineW
388
# Now shorten the command line we get from GetCommandLineW to match sys.argv
389
if len(arguments) < len(argv):
390
raise AssertionError("Split command line can't be shorter than argv")
391
arguments = arguments[len(arguments) - len(argv):]
393
# Carry on to process globs (metachars) in the command line
394
# expand globs if necessary
395
# TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
398
for is_quoted, arg in arguments:
399
if is_quoted or not glob.has_magic(arg):
210
kernel32 = ctypes.windll.kernel32
211
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix)
212
except AttributeError:
402
args.extend(glob_one(arg))
406
def _ctypes_is_local_pid_dead(pid):
408
kernel32 = ctypes.wintypes.windll.kernel32
409
"""True if pid doesn't correspond to live process on this machine"""
410
handle = kernel32.OpenProcess(1, False, pid)
412
errorcode = ctypes.GetLastError()
413
if errorcode == 5: # ERROR_ACCESS_DENIED
414
# Probably something alive we're not allowed to kill
416
elif errorcode == 87: # ERROR_INVALID_PARAMETER
418
raise ctypes.WinError(errorcode)
419
Kernel32.CloseHandle(handle)
422
is_local_pid_dead = _ctypes_is_local_pid_dead
215
buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
216
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
217
if GetComputerName(buf, ctypes.byref(n)):
219
# otherwise try env variables
220
return os.environ.get('COMPUTERNAME', None)
223
def _ensure_unicode(s):
224
if s and type(s) != unicode:
226
s = s.decode(bzrlib.user_encoding)
230
def get_appdata_location_unicode():
231
return _ensure_unicode(get_appdata_location())
233
def get_home_location_unicode():
234
return _ensure_unicode(get_home_location())
236
def get_user_name_unicode():
237
return _ensure_unicode(get_user_name())
239
def get_host_name_unicode():
240
return _ensure_unicode(get_host_name())