82
97
MAX_COMPUTERNAME_LENGTH = 31
99
# Registry data type ids
104
def debug_memory_win32api(message='', short=True):
105
"""Use trace.note() to dump the running memory info."""
106
from bzrlib import trace
108
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
109
"""Used by GetProcessMemoryInfo"""
110
_fields_ = [('cb', ctypes.c_ulong),
111
('PageFaultCount', ctypes.c_ulong),
112
('PeakWorkingSetSize', ctypes.c_size_t),
113
('WorkingSetSize', ctypes.c_size_t),
114
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
115
('QuotaPagedPoolUsage', ctypes.c_size_t),
116
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
117
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
118
('PagefileUsage', ctypes.c_size_t),
119
('PeakPagefileUsage', ctypes.c_size_t),
120
('PrivateUsage', ctypes.c_size_t),
122
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
123
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
124
ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
125
ctypes.byref(mem_struct),
126
ctypes.sizeof(mem_struct))
128
trace.note('Failed to GetProcessMemoryInfo()')
130
info = {'PageFaultCount': mem_struct.PageFaultCount,
131
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
132
'WorkingSetSize': mem_struct.WorkingSetSize,
133
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
134
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
135
'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
136
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
137
'PagefileUsage': mem_struct.PagefileUsage,
138
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
139
'PrivateUsage': mem_struct.PrivateUsage,
143
# win32process does not return PrivateUsage, because it doesn't use
144
# PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
145
proc = win32process.GetCurrentProcess()
146
info = win32process.GetProcessMemoryInfo(proc)
148
trace.note('Cannot debug memory on win32 without ctypes'
152
trace.note('WorkingSize %7dKB'
153
'\tPeakWorking %7dKB\t%s',
154
info['WorkingSetSize'] / 1024,
155
info['PeakWorkingSetSize'] / 1024,
159
trace.note('%s', message)
160
trace.note('WorkingSize %8d KB', info['WorkingSetSize'] / 1024)
161
trace.note('PeakWorking %8d KB', info['PeakWorkingSetSize'] / 1024)
162
trace.note('PagefileUsage %8d KB', info.get('PagefileUsage', 0) / 1024)
163
trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
164
trace.note('PrivateUsage %8d KB', info.get('PrivateUsage', 0) / 1024)
165
trace.note('PageFaultCount %8d', info.get('PageFaultCount', 0))
85
168
def get_console_size(defaultx=80, defaulty=25):
86
169
"""Return size of current console.
109
192
return (defaultx, defaulty)
195
def _get_sh_special_folder_path(csidl):
196
"""Call SHGetSpecialFolderPathW if available, or return None.
198
Result is always unicode (or None).
202
SHGetSpecialFolderPath = \
203
ctypes.windll.shell32.SHGetSpecialFolderPathW
204
except AttributeError:
207
buf = ctypes.create_unicode_buffer(MAX_PATH)
208
if SHGetSpecialFolderPath(None,buf,csidl,0):
211
global has_win32com_shell
212
if has_win32com_shell is None:
214
from win32com.shell import shell
215
has_win32com_shell = True
217
has_win32com_shell = False
218
if has_win32com_shell:
219
# still need to bind the name locally, but this is fast.
220
from win32com.shell import shell
222
return shell.SHGetSpecialFolderPath(0, csidl, 0)
224
# possibly E_NOTIMPL meaning we can't load the function pointer,
225
# or E_FAIL meaning the function failed - regardless, just ignore it
112
230
def get_appdata_location():
113
231
"""Return Application Data location.
114
232
Return None if we cannot obtain location.
116
Returned value can be unicode or plain sring.
234
Windows defines two 'Application Data' folders per user - a 'roaming'
235
one that moves with the user as they logon to different machines, and
236
a 'local' one that stays local to the machine. This returns the 'roaming'
237
directory, and thus is suitable for storing user-preferences, etc.
239
Returned value can be unicode or plain string.
117
240
To convert plain string to unicode use
118
s.decode(bzrlib.user_encoding)
241
s.decode(osutils.get_user_encoding())
242
(XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
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):
244
appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
130
247
# from env variable
131
248
appdata = os.environ.get('APPDATA')
262
def get_local_appdata_location():
263
"""Return Local Application Data location.
264
Return the same as get_appdata_location() if we cannot obtain location.
266
Windows defines two 'Application Data' folders per user - a 'roaming'
267
one that moves with the user as they logon to different machines, and
268
a 'local' one that stays local to the machine. This returns the 'local'
269
directory, and thus is suitable for caches, temp files and other things
270
which don't need to move with the user.
272
Returned value can be unicode or plain string.
273
To convert plain string to unicode use
274
s.decode(osutils.get_user_encoding())
275
(XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
277
local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
280
# Vista supplies LOCALAPPDATA, but XP and earlier do not.
281
local = os.environ.get('LOCALAPPDATA')
284
return get_appdata_location()
145
287
def get_home_location():
146
288
"""Return user's home location.
147
289
Assume on win32 it's the <My Documents> folder.
148
290
If location cannot be obtained return system drive root,
151
Returned value can be unicode or plain sring.
293
Returned value can be unicode or plain string.
152
294
To convert plain string to unicode use
153
s.decode(bzrlib.user_encoding)
295
s.decode(osutils.get_user_encoding())
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):
297
home = _get_sh_special_folder_path(CSIDL_PERSONAL)
165
300
# try for HOME env variable
166
301
home = os.path.expanduser('~')
197
332
return os.environ.get('USERNAME', None)
335
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
336
# computer or the cluster associated with the local computer."
337
_WIN32_ComputerNameDnsHostname = 1
200
339
def get_host_name():
201
340
"""Return host machine name.
202
341
If name cannot be obtained return None.
204
Returned value can be unicode or plain sring.
205
To convert plain string to unicode use
206
s.decode(bzrlib.user_encoding)
343
:return: A unicode string representing the host name. On win98, this may be
344
a plain string as win32 api doesn't support unicode.
348
return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
349
except (NotImplementedError, win32api.error):
350
# NotImplemented will happen on win9x...
210
354
kernel32 = ctypes.windll.kernel32
211
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix)
212
355
except AttributeError:
356
pass # Missing the module we need
215
358
buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
216
359
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)
361
# Try GetComputerNameEx which gives a proper Unicode hostname
362
GetComputerNameEx = getattr(kernel32, 'GetComputerNameEx'+suffix,
364
if (GetComputerNameEx is not None
365
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
366
buf, ctypes.byref(n))):
369
# Try GetComputerName in case GetComputerNameEx wasn't found
370
# It returns the NETBIOS name, which isn't as good, but still ok.
371
# The first GetComputerNameEx might have changed 'n', so reset it
372
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
373
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
375
if (GetComputerName is not None
376
and GetComputerName(buf, ctypes.byref(n))):
378
# otherwise try env variables, which will be 'mbcs' encoded
379
# on Windows (Python doesn't expose the native win32 unicode environment)
381
# http://msdn.microsoft.com/en-us/library/aa246807.aspx
382
# environment variables should always be encoded in 'mbcs'.
384
return os.environ['COMPUTERNAME'].decode("mbcs")
223
389
def _ensure_unicode(s):
390
from bzrlib import osutils
224
391
if s and type(s) != unicode:
226
s = s.decode(bzrlib.user_encoding)
392
from bzrlib import osutils
393
s = s.decode(osutils.get_user_encoding())
230
397
def get_appdata_location_unicode():
231
398
return _ensure_unicode(get_appdata_location())
257
438
expanded_file_list = []
258
439
for possible_glob in file_list:
440
# work around bugs in glob.glob()
441
# - Python bug #1001604 ("glob doesn't return unicode with ...")
442
# - failing expansion for */* with non-iso-8859-* chars
443
possible_glob, corrected = _ensure_with_dir(possible_glob)
259
444
glob_files = glob.glob(possible_glob)
261
446
if glob_files == []:
262
447
# special case to let the normal code path handle
263
448
# files that do not exists
264
expanded_file_list.append(possible_glob)
449
expanded_file_list.append(
450
_undo_ensure_with_dir(possible_glob, corrected))
452
glob_files = [_undo_ensure_with_dir(elem, corrected) for elem in glob_files]
266
453
expanded_file_list += glob_files
267
return expanded_file_list
455
return [elem.replace(u'\\', u'/') for elem in expanded_file_list]
458
def get_app_path(appname):
459
"""Look up in Windows registry for full path to application executable.
460
Typically, applications create subkey with their basename
461
in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
463
:param appname: name of application (if no filename extension
464
is specified, .exe used)
465
:return: full path to aplication executable from registry,
466
or appname itself if nothing found.
471
if not os.path.splitext(basename)[1]:
472
basename = appname + '.exe'
475
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
476
'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
478
except EnvironmentError:
483
path, type_id = _winreg.QueryValueEx(hkey, '')
487
_winreg.CloseKey(hkey)
489
if type_id == REG_SZ:
491
if type_id == REG_EXPAND_SZ and has_win32api:
492
fullpath = win32api.ExpandEnvironmentStrings(path)
493
if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
494
fullpath = fullpath[1:-1] # remove quotes around value
499
def set_file_attr_hidden(path):
500
"""Set file attributes to hidden if possible"""
502
win32file.SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
505
if has_ctypes and winver != 'Windows 98':
506
def get_unicode_argv():
507
LPCWSTR = ctypes.c_wchar_p
509
POINTER = ctypes.POINTER
510
prototype = ctypes.WINFUNCTYPE(LPCWSTR)
511
GetCommandLine = prototype(("GetCommandLineW",
512
ctypes.windll.kernel32))
513
prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
514
CommandLineToArgv = prototype(("CommandLineToArgvW",
515
ctypes.windll.shell32))
517
pargv = CommandLineToArgv(GetCommandLine(), ctypes.byref(c))
518
# Skip the first argument, since we only care about parameters
519
argv = [pargv[i] for i in range(1, c.value)]
520
if getattr(sys, 'frozen', None) is None:
521
# Invoked via 'python.exe' which takes the form:
522
# python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
523
# we need to get only BZR_OPTIONS part,
524
# so let's using sys.argv[1:] as reference to get the tail
526
tail_len = len(sys.argv[1:])
527
ix = len(argv) - tail_len
531
get_unicode_argv = None