98
82
MAX_COMPUTERNAME_LENGTH = 31
100
# Registry data type ids
105
def debug_memory_win32api(message='', short=True):
106
"""Use trace.note() to dump the running memory info."""
107
from bzrlib import trace
109
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
110
"""Used by GetProcessMemoryInfo"""
111
_fields_ = [('cb', ctypes.c_ulong),
112
('PageFaultCount', ctypes.c_ulong),
113
('PeakWorkingSetSize', ctypes.c_size_t),
114
('WorkingSetSize', ctypes.c_size_t),
115
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
116
('QuotaPagedPoolUsage', ctypes.c_size_t),
117
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
118
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
119
('PagefileUsage', ctypes.c_size_t),
120
('PeakPagefileUsage', ctypes.c_size_t),
121
('PrivateUsage', ctypes.c_size_t),
123
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
124
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
125
ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
126
ctypes.byref(mem_struct),
127
ctypes.sizeof(mem_struct))
129
trace.note('Failed to GetProcessMemoryInfo()')
131
info = {'PageFaultCount': mem_struct.PageFaultCount,
132
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
133
'WorkingSetSize': mem_struct.WorkingSetSize,
134
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
135
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
136
'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
137
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
138
'PagefileUsage': mem_struct.PagefileUsage,
139
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
140
'PrivateUsage': mem_struct.PrivateUsage,
144
# win32process does not return PrivateUsage, because it doesn't use
145
# PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
146
proc = win32process.GetCurrentProcess()
147
info = win32process.GetProcessMemoryInfo(proc)
149
trace.note('Cannot debug memory on win32 without ctypes'
153
trace.note('WorkingSize %7dKB'
154
'\tPeakWorking %7dKB\t%s',
155
info['WorkingSetSize'] / 1024,
156
info['PeakWorkingSetSize'] / 1024,
160
trace.note('%s', message)
161
trace.note('WorkingSize %8d KB', info['WorkingSetSize'] / 1024)
162
trace.note('PeakWorking %8d KB', info['PeakWorkingSetSize'] / 1024)
163
trace.note('PagefileUsage %8d KB', info.get('PagefileUsage', 0) / 1024)
164
trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
165
trace.note('PrivateUsage %8d KB', info.get('PrivateUsage', 0) / 1024)
166
trace.note('PageFaultCount %8d', info.get('PageFaultCount', 0))
169
85
def get_console_size(defaultx=80, defaulty=25):
170
86
"""Return size of current console.
193
109
return (defaultx, defaulty)
196
def _get_sh_special_folder_path(csidl):
197
"""Call SHGetSpecialFolderPathW if available, or return None.
199
Result is always unicode (or None).
203
SHGetSpecialFolderPath = \
204
ctypes.windll.shell32.SHGetSpecialFolderPathW
205
except AttributeError:
208
buf = ctypes.create_unicode_buffer(MAX_PATH)
209
if SHGetSpecialFolderPath(None,buf,csidl,0):
212
global has_win32com_shell
213
if has_win32com_shell is None:
215
from win32com.shell import shell
216
has_win32com_shell = True
218
has_win32com_shell = False
219
if has_win32com_shell:
220
# still need to bind the name locally, but this is fast.
221
from win32com.shell import shell
223
return shell.SHGetSpecialFolderPath(0, csidl, 0)
225
# possibly E_NOTIMPL meaning we can't load the function pointer,
226
# or E_FAIL meaning the function failed - regardless, just ignore it
231
112
def get_appdata_location():
232
113
"""Return Application Data location.
233
114
Return None if we cannot obtain location.
235
Windows defines two 'Application Data' folders per user - a 'roaming'
236
one that moves with the user as they logon to different machines, and
237
a 'local' one that stays local to the machine. This returns the 'roaming'
238
directory, and thus is suitable for storing user-preferences, etc.
240
Returned value can be unicode or plain string.
116
Returned value can be unicode or plain sring.
241
117
To convert plain string to unicode use
242
s.decode(osutils.get_user_encoding())
243
(XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
118
s.decode(bzrlib.user_encoding)
245
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):
248
130
# from env variable
249
131
appdata = os.environ.get('APPDATA')
263
def get_local_appdata_location():
264
"""Return Local Application Data location.
265
Return the same as get_appdata_location() if we cannot obtain location.
267
Windows defines two 'Application Data' folders per user - a 'roaming'
268
one that moves with the user as they logon to different machines, and
269
a 'local' one that stays local to the machine. This returns the 'local'
270
directory, and thus is suitable for caches, temp files and other things
271
which don't need to move with the user.
273
Returned value can be unicode or plain string.
274
To convert plain string to unicode use
275
s.decode(osutils.get_user_encoding())
276
(XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
278
local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
281
# Vista supplies LOCALAPPDATA, but XP and earlier do not.
282
local = os.environ.get('LOCALAPPDATA')
285
return get_appdata_location()
288
145
def get_home_location():
289
146
"""Return user's home location.
290
147
Assume on win32 it's the <My Documents> folder.
291
148
If location cannot be obtained return system drive root,
294
Returned value can be unicode or plain string.
151
Returned value can be unicode or plain sring.
295
152
To convert plain string to unicode use
296
s.decode(osutils.get_user_encoding())
153
s.decode(bzrlib.user_encoding)
298
home = _get_sh_special_folder_path(CSIDL_PERSONAL)
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):
301
165
# try for HOME env variable
302
166
home = os.path.expanduser('~')
333
197
return os.environ.get('USERNAME', None)
336
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
337
# computer or the cluster associated with the local computer."
338
_WIN32_ComputerNameDnsHostname = 1
340
200
def get_host_name():
341
201
"""Return host machine name.
342
202
If name cannot be obtained return None.
344
:return: A unicode string representing the host name. On win98, this may be
345
a plain string as win32 api doesn't support unicode.
204
Returned value can be unicode or plain sring.
205
To convert plain string to unicode use
206
s.decode(bzrlib.user_encoding)
349
return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
350
except (NotImplementedError, win32api.error):
351
# NotImplemented will happen on win9x...
355
210
kernel32 = ctypes.windll.kernel32
211
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix)
356
212
except AttributeError:
357
pass # Missing the module we need
359
215
buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
360
216
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
362
# Try GetComputerNameEx which gives a proper Unicode hostname
363
GetComputerNameEx = getattr(kernel32, 'GetComputerNameEx'+suffix,
365
if (GetComputerNameEx is not None
366
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
367
buf, ctypes.byref(n))):
370
# Try GetComputerName in case GetComputerNameEx wasn't found
371
# It returns the NETBIOS name, which isn't as good, but still ok.
372
# The first GetComputerNameEx might have changed 'n', so reset it
373
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
374
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
376
if (GetComputerName is not None
377
and GetComputerName(buf, ctypes.byref(n))):
379
# otherwise try env variables, which will be 'mbcs' encoded
380
# on Windows (Python doesn't expose the native win32 unicode environment)
382
# http://msdn.microsoft.com/en-us/library/aa246807.aspx
383
# environment variables should always be encoded in 'mbcs'.
385
return os.environ['COMPUTERNAME'].decode("mbcs")
217
if GetComputerName(buf, ctypes.byref(n)):
219
# otherwise try env variables
220
return os.environ.get('COMPUTERNAME', None)
390
223
def _ensure_unicode(s):
391
from bzrlib import osutils
392
224
if s and type(s) != unicode:
393
from bzrlib import osutils
394
s = s.decode(osutils.get_user_encoding())
226
s = s.decode(bzrlib.user_encoding)
398
230
def get_appdata_location_unicode():
399
231
return _ensure_unicode(get_appdata_location())
453
286
glob_files = [_undo_ensure_with_dir(elem, corrected) for elem in glob_files]
454
287
expanded_file_list += glob_files
456
return [elem.replace(u'\\', u'/') for elem in expanded_file_list]
289
return [elem.replace(u'\\', u'/') for elem in expanded_file_list]
459
292
def get_app_path(appname):
460
293
"""Look up in Windows registry for full path to application executable.
461
Typically, applications create subkey with their basename
294
Typicaly, applications create subkey with their basename
462
295
in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
464
297
:param appname: name of application (if no filename extension
467
300
or appname itself if nothing found.
304
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
305
r'SOFTWARE\Microsoft\Windows'
306
r'\CurrentVersion\App Paths')
307
except EnvironmentError:
471
310
basename = appname
472
311
if not os.path.splitext(basename)[1]:
473
312
basename = appname + '.exe'
476
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
477
'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
479
except EnvironmentError:
484
path, type_id = _winreg.QueryValueEx(hkey, '')
315
fullpath = _winreg.QueryValue(hkey, basename)
485
316
except WindowsError:
488
319
_winreg.CloseKey(hkey)
490
if type_id == REG_SZ:
492
if type_id == REG_EXPAND_SZ and has_win32api:
493
fullpath = win32api.ExpandEnvironmentStrings(path)
494
if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
495
fullpath = fullpath[1:-1] # remove quotes around value
500
def set_file_attr_hidden(path):
501
"""Set file attributes to hidden if possible"""
503
if winver != 'Windows 98':
504
SetFileAttributes = win32file.SetFileAttributesW
506
SetFileAttributes = win32file.SetFileAttributes
508
SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
509
except pywintypes.error, e:
510
from bzrlib import trace
511
trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
514
if has_ctypes and winver != 'Windows 98':
515
def get_unicode_argv():
516
LPCWSTR = ctypes.c_wchar_p
518
POINTER = ctypes.POINTER
519
prototype = ctypes.WINFUNCTYPE(LPCWSTR)
520
GetCommandLine = prototype(("GetCommandLineW",
521
ctypes.windll.kernel32))
522
prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
523
CommandLineToArgv = prototype(("CommandLineToArgvW",
524
ctypes.windll.shell32))
526
pargv = CommandLineToArgv(GetCommandLine(), ctypes.byref(c))
527
# Skip the first argument, since we only care about parameters
528
argv = [pargv[i] for i in range(1, c.value)]
529
if getattr(sys, 'frozen', None) is None:
530
# Invoked via 'python.exe' which takes the form:
531
# python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
532
# we need to get only BZR_OPTIONS part,
533
# so let's using sys.argv[1:] as reference to get the tail
535
tail_len = len(sys.argv[1:])
536
ix = len(argv) - tail_len
540
get_unicode_argv = None