1
# Copyright (C) 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
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
17
"""Win32-specific helper functions
19
Only one dependency: ctypes should be installed.
32
if sys.platform == 'win32':
33
_major,_minor,_build,_platform,_text = sys.getwindowsversion()
36
# The operating system platform.
37
# This member can be one of the following values.
38
# ========================== ======================================
40
# -------------------------- --------------------------------------
41
# VER_PLATFORM_WIN32_NT The operating system is Windows Vista,
42
# 2 Windows Server "Longhorn",
43
# Windows Server 2003, Windows XP,
44
# Windows 2000, or Windows NT.
46
# VER_PLATFORM_WIN32_WINDOWS The operating system is Windows Me,
47
# 1 Windows 98, or Windows 95.
48
# ========================== ======================================
52
# don't care about real Windows name, just to force safe operations
58
# We can cope without it; use a separate variable to help pyflakes
65
if winver == 'Windows 98':
66
create_buffer = ctypes.create_string_buffer
69
create_buffer = ctypes.create_unicode_buffer
83
# pulling in win32com.shell is a bit of overhead, and normally we don't need
84
# it as ctypes is preferred and common. lazy_imports and "optional"
85
# modules don't work well, so we do our own lazy thing...
86
has_win32com_shell = None # Set to True or False once we know for sure...
88
# Special Win32 API constants
89
# Handles of std streams
90
WIN32_STDIN_HANDLE = -10
91
WIN32_STDOUT_HANDLE = -11
92
WIN32_STDERR_HANDLE = -12
94
# CSIDL constants (from MSDN 2003)
95
CSIDL_APPDATA = 0x001A # Application Data folder
96
CSIDL_LOCAL_APPDATA = 0x001c# <user name>\Local Settings\Application Data (non roaming)
97
CSIDL_PERSONAL = 0x0005 # My Documents folder
99
# from winapi C headers
102
MAX_COMPUTERNAME_LENGTH = 31
104
# Registry data type ids
109
def debug_memory_win32api(message='', short=True):
110
"""Use trace.note() to dump the running memory info."""
111
from bzrlib import trace
113
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
114
"""Used by GetProcessMemoryInfo"""
115
_fields_ = [('cb', ctypes.c_ulong),
116
('PageFaultCount', ctypes.c_ulong),
117
('PeakWorkingSetSize', ctypes.c_size_t),
118
('WorkingSetSize', ctypes.c_size_t),
119
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
120
('QuotaPagedPoolUsage', ctypes.c_size_t),
121
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
122
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
123
('PagefileUsage', ctypes.c_size_t),
124
('PeakPagefileUsage', ctypes.c_size_t),
125
('PrivateUsage', ctypes.c_size_t),
127
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
128
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
129
ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
130
ctypes.byref(mem_struct),
131
ctypes.sizeof(mem_struct))
133
trace.note('Failed to GetProcessMemoryInfo()')
135
info = {'PageFaultCount': mem_struct.PageFaultCount,
136
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
137
'WorkingSetSize': mem_struct.WorkingSetSize,
138
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
139
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
140
'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
141
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
142
'PagefileUsage': mem_struct.PagefileUsage,
143
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
144
'PrivateUsage': mem_struct.PrivateUsage,
148
# win32process does not return PrivateUsage, because it doesn't use
149
# PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
150
proc = win32process.GetCurrentProcess()
151
info = win32process.GetProcessMemoryInfo(proc)
153
trace.note('Cannot debug memory on win32 without ctypes'
157
trace.note('WorkingSize %7dKB'
158
'\tPeakWorking %7dKB\t%s',
159
info['WorkingSetSize'] / 1024,
160
info['PeakWorkingSetSize'] / 1024,
164
trace.note('%s', message)
165
trace.note('WorkingSize %8d KB', info['WorkingSetSize'] / 1024)
166
trace.note('PeakWorking %8d KB', info['PeakWorkingSetSize'] / 1024)
167
trace.note('PagefileUsage %8d KB', info.get('PagefileUsage', 0) / 1024)
168
trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
169
trace.note('PrivateUsage %8d KB', info.get('PrivateUsage', 0) / 1024)
170
trace.note('PageFaultCount %8d', info.get('PageFaultCount', 0))
173
def get_console_size(defaultx=80, defaulty=25):
174
"""Return size of current console.
176
This function try to determine actual size of current working
177
console window and return tuple (sizex, sizey) if success,
178
or default size (defaultx, defaulty) otherwise.
182
return (defaultx, defaulty)
184
# To avoid problem with redirecting output via pipe
185
# need to use stderr instead of stdout
186
h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
187
csbi = ctypes.create_string_buffer(22)
188
res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
191
(bufx, bufy, curx, cury, wattr,
192
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
193
sizex = right - left + 1
194
sizey = bottom - top + 1
195
return (sizex, sizey)
197
return (defaultx, defaulty)
200
def _get_sh_special_folder_path(csidl):
201
"""Call SHGetSpecialFolderPathW if available, or return None.
203
Result is always unicode (or None).
207
SHGetSpecialFolderPath = \
208
ctypes.windll.shell32.SHGetSpecialFolderPathW
209
except AttributeError:
212
buf = ctypes.create_unicode_buffer(MAX_PATH)
213
if SHGetSpecialFolderPath(None,buf,csidl,0):
216
global has_win32com_shell
217
if has_win32com_shell is None:
219
from win32com.shell import shell
220
has_win32com_shell = True
222
has_win32com_shell = False
223
if has_win32com_shell:
224
# still need to bind the name locally, but this is fast.
225
from win32com.shell import shell
227
return shell.SHGetSpecialFolderPath(0, csidl, 0)
229
# possibly E_NOTIMPL meaning we can't load the function pointer,
230
# or E_FAIL meaning the function failed - regardless, just ignore it
235
def get_appdata_location():
236
"""Return Application Data location.
237
Return None if we cannot obtain location.
239
Windows defines two 'Application Data' folders per user - a 'roaming'
240
one that moves with the user as they logon to different machines, and
241
a 'local' one that stays local to the machine. This returns the 'roaming'
242
directory, and thus is suitable for storing user-preferences, etc.
244
Returned value can be unicode or plain string.
245
To convert plain string to unicode use
246
s.decode(osutils.get_user_encoding())
247
(XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
249
appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
253
appdata = os.environ.get('APPDATA')
256
# if we fall to this point we on win98
257
# at least try C:/WINDOWS/Application Data
258
windir = os.environ.get('windir')
260
appdata = os.path.join(windir, 'Application Data')
261
if os.path.isdir(appdata):
263
# did not find anything
267
def get_local_appdata_location():
268
"""Return Local Application Data location.
269
Return the same as get_appdata_location() if we cannot obtain location.
271
Windows defines two 'Application Data' folders per user - a 'roaming'
272
one that moves with the user as they logon to different machines, and
273
a 'local' one that stays local to the machine. This returns the 'local'
274
directory, and thus is suitable for caches, temp files and other things
275
which don't need to move with the user.
277
Returned value can be unicode or plain string.
278
To convert plain string to unicode use
279
s.decode(osutils.get_user_encoding())
280
(XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
282
local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
285
# Vista supplies LOCALAPPDATA, but XP and earlier do not.
286
local = os.environ.get('LOCALAPPDATA')
289
return get_appdata_location()
292
def get_home_location():
293
"""Return user's home location.
294
Assume on win32 it's the <My Documents> folder.
295
If location cannot be obtained return system drive root,
298
Returned value can be unicode or plain string.
299
To convert plain string to unicode use
300
s.decode(osutils.get_user_encoding())
302
home = _get_sh_special_folder_path(CSIDL_PERSONAL)
305
# try for HOME env variable
306
home = os.path.expanduser('~')
309
# at least return windows root directory
310
windir = os.environ.get('windir')
312
return os.path.splitdrive(windir)[0] + '/'
313
# otherwise C:\ is good enough for 98% users
318
"""Return user name as login name.
319
If name cannot be obtained return None.
321
Returned value can be unicode or plain string.
322
To convert plain string to unicode use
323
s.decode(osutils.get_user_encoding())
327
advapi32 = ctypes.windll.advapi32
328
GetUserName = getattr(advapi32, 'GetUserName'+suffix)
329
except AttributeError:
332
buf = create_buffer(UNLEN+1)
333
n = ctypes.c_int(UNLEN+1)
334
if GetUserName(buf, ctypes.byref(n)):
336
# otherwise try env variables
337
return os.environ.get('USERNAME', None)
340
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
341
# computer or the cluster associated with the local computer."
342
_WIN32_ComputerNameDnsHostname = 1
345
"""Return host machine name.
346
If name cannot be obtained return None.
348
:return: A unicode string representing the host name. On win98, this may be
349
a plain string as win32 api doesn't support unicode.
353
return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
354
except (NotImplementedError, win32api.error):
355
# NotImplemented will happen on win9x...
359
kernel32 = ctypes.windll.kernel32
360
except AttributeError:
361
pass # Missing the module we need
363
buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
364
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
366
# Try GetComputerNameEx which gives a proper Unicode hostname
367
GetComputerNameEx = getattr(kernel32, 'GetComputerNameEx'+suffix,
369
if (GetComputerNameEx is not None
370
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
371
buf, ctypes.byref(n))):
374
# Try GetComputerName in case GetComputerNameEx wasn't found
375
# It returns the NETBIOS name, which isn't as good, but still ok.
376
# The first GetComputerNameEx might have changed 'n', so reset it
377
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
378
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
380
if (GetComputerName is not None
381
and GetComputerName(buf, ctypes.byref(n))):
383
# otherwise try env variables, which will be 'mbcs' encoded
384
# on Windows (Python doesn't expose the native win32 unicode environment)
386
# http://msdn.microsoft.com/en-us/library/aa246807.aspx
387
# environment variables should always be encoded in 'mbcs'.
389
return os.environ['COMPUTERNAME'].decode("mbcs")
394
def _ensure_unicode(s):
395
from bzrlib import osutils
396
if s and type(s) != unicode:
397
from bzrlib import osutils
398
s = s.decode(osutils.get_user_encoding())
402
def get_appdata_location_unicode():
403
return _ensure_unicode(get_appdata_location())
405
def get_home_location_unicode():
406
return _ensure_unicode(get_home_location())
408
def get_user_name_unicode():
409
return _ensure_unicode(get_user_name())
411
def get_host_name_unicode():
412
return _ensure_unicode(get_host_name())
415
def _ensure_with_dir(path):
416
if not os.path.split(path)[0] or path.startswith(u'*') or path.startswith(u'?'):
417
return u'./' + path, True
421
def _undo_ensure_with_dir(path, corrected):
429
def glob_one(possible_glob):
430
"""Same as glob.glob().
432
work around bugs in glob.glob()
433
- Python bug #1001604 ("glob doesn't return unicode with ...")
434
- failing expansion for */* with non-iso-8859-* chars
436
corrected_glob, corrected = _ensure_with_dir(possible_glob)
437
glob_files = glob.glob(corrected_glob)
440
# special case to let the normal code path handle
441
# files that do not exist, etc.
442
glob_files = [possible_glob]
444
glob_files = [_undo_ensure_with_dir(elem, corrected)
445
for elem in glob_files]
446
return [elem.replace(u'\\', u'/') for elem in glob_files]
449
def glob_expand(file_list):
450
"""Replacement for glob expansion by the shell.
452
Win32's cmd.exe does not do glob expansion (eg ``*.py``), so we do our own
455
:param file_list: A list of filenames which may include shell globs.
456
:return: An expanded list of filenames.
458
Introduced in bzrlib 0.18.
462
expanded_file_list = []
463
for possible_glob in file_list:
464
expanded_file_list.extend(glob_one(possible_glob))
465
return expanded_file_list
468
def get_app_path(appname):
469
"""Look up in Windows registry for full path to application executable.
470
Typically, applications create subkey with their basename
471
in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
473
:param appname: name of application (if no filename extension
474
is specified, .exe used)
475
:return: full path to aplication executable from registry,
476
or appname itself if nothing found.
481
if not os.path.splitext(basename)[1]:
482
basename = appname + '.exe'
485
hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
486
'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
488
except EnvironmentError:
493
path, type_id = _winreg.QueryValueEx(hkey, '')
497
_winreg.CloseKey(hkey)
499
if type_id == REG_SZ:
501
if type_id == REG_EXPAND_SZ and has_win32api:
502
fullpath = win32api.ExpandEnvironmentStrings(path)
503
if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
504
fullpath = fullpath[1:-1] # remove quotes around value
509
def set_file_attr_hidden(path):
510
"""Set file attributes to hidden if possible"""
512
if winver != 'Windows 98':
513
SetFileAttributes = win32file.SetFileAttributesW
515
SetFileAttributes = win32file.SetFileAttributes
517
SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
518
except pywintypes.error, e:
519
from bzrlib import trace
520
trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
524
class UnicodeShlex(object):
525
"""This is a very simplified version of shlex.shlex.
527
The main change is that it supports non-ascii input streams. The internal
528
structure is quite simplified relative to shlex.shlex, since we aren't
529
trying to handle multiple input streams, etc. In fact, we don't use a
530
file-like api either.
533
def __init__(self, uni_string):
534
self._input = uni_string
535
self._input_iter = iter(self._input)
536
self._whitespace_match = re.compile(u'\s').match
537
self._word_match = re.compile(u'\S').match
538
self._quote_chars = u'"'
539
# self._quote_match = re.compile(u'[\'"]').match
540
self._escape_match = lambda x: None # Never matches
543
# ' ' - after whitespace, starting a new token
544
# 'a' - after text, currently working on a token
545
# '"' - after ", currently in a "-delimited quoted section
546
# "\" - after '\', checking the next char
548
self._token = [] # Current token being parsed
550
def _get_token(self):
551
# Were there quote chars as part of this token?
554
for nextchar in self._input_iter:
555
if self._state == ' ':
556
if self._whitespace_match(nextchar):
557
# if self._token: return token
559
elif nextchar in self._quote_chars:
560
self._state = nextchar # quoted state
561
elif self._word_match(nextchar):
562
self._token.append(nextchar)
565
raise AssertionError('wtttf?')
566
elif self._state in self._quote_chars:
568
if nextchar == self._state: # End of quote
569
self._state = 'a' # posix allows 'foo'bar to translate to
571
elif self._state == '"' and nextchar == self._escape:
572
quoted_state = self._state
573
self._state = nextchar
575
self._token.append(nextchar)
576
elif self._state == self._escape:
578
self._token.append('\\')
579
elif nextchar == '"':
580
self._token.append(nextchar)
582
self._token.append('\\' + nextchar)
583
self._state = quoted_state
584
elif self._state == 'a':
585
if self._whitespace_match(nextchar):
587
break # emit this token
589
continue # no token to emit
590
elif nextchar in self._quote_chars:
591
# Start a new quoted section
592
self._state = nextchar
594
elif (self._word_match(nextchar)
595
or nextchar in self._quote_chars
596
# or whitespace_split?
598
self._token.append(nextchar)
600
raise AssertionError('state == "a", char: %r'
603
raise AssertionError('unknown state: %r' % (self._state,))
604
result = ''.join(self._token)
606
if not quoted and result == '':
608
return quoted, result
614
quoted, token = self._get_token()
620
def _command_line_to_argv(command_line):
621
"""Convert a Unicode command line into a set of argv arguments.
623
This does wildcard expansion, etc. It is intended to make wildcards act
624
closer to how they work in posix shells, versus how they work by default on
627
s = UnicodeShlex(command_line)
628
# Now that we've split the content, expand globs
629
# TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
632
for is_quoted, arg in s:
633
if is_quoted or not glob.has_magic(arg):
634
args.append(arg.replace(u'\\', u'/'))
636
args.extend(glob_one(arg))
640
if has_ctypes and winver != 'Windows 98':
641
def get_unicode_argv():
642
LPCWSTR = ctypes.c_wchar_p
644
POINTER = ctypes.POINTER
645
prototype = ctypes.WINFUNCTYPE(LPCWSTR)
646
GetCommandLine = prototype(("GetCommandLineW",
647
ctypes.windll.kernel32))
648
prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
649
command_line = GetCommandLine()
650
# Skip the first argument, since we only care about parameters
651
argv = _command_line_to_argv(GetCommandLine())[1:]
652
if getattr(sys, 'frozen', None) is None:
653
# Invoked via 'python.exe' which takes the form:
654
# python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
655
# we need to get only BZR_OPTIONS part,
656
# We already removed 'python.exe' so we remove everything up to and
657
# including the first non-option ('-') argument.
658
for idx in xrange(len(argv)):
659
if argv[idx][:1] != '-':
664
get_unicode_argv = None