/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/win32utils.py

merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Win32-specific helper functions
18
18
 
64
64
    else:
65
65
        create_buffer = ctypes.create_unicode_buffer
66
66
        suffix = 'W'
 
67
try:
 
68
    import win32file
 
69
    has_win32file = True
 
70
except ImportError:
 
71
    has_win32file = False
 
72
try:
 
73
    import win32api
 
74
    has_win32api = True
 
75
except ImportError:
 
76
    has_win32api = False
67
77
 
 
78
# pulling in win32com.shell is a bit of overhead, and normally we don't need
 
79
# it as ctypes is preferred and common.  lazy_imports and "optional"
 
80
# modules don't work well, so we do our own lazy thing...
 
81
has_win32com_shell = None # Set to True or False once we know for sure...
68
82
 
69
83
# Special Win32 API constants
70
84
# Handles of std streams
74
88
 
75
89
# CSIDL constants (from MSDN 2003)
76
90
CSIDL_APPDATA = 0x001A      # Application Data folder
 
91
CSIDL_LOCAL_APPDATA = 0x001c# <user name>\Local Settings\Application Data (non roaming)
77
92
CSIDL_PERSONAL = 0x0005     # My Documents folder
78
93
 
79
94
# from winapi C headers
82
97
MAX_COMPUTERNAME_LENGTH = 31
83
98
 
84
99
 
 
100
def debug_memory_win32api(message='', short=True):
 
101
    """Use trace.note() to dump the running memory info."""
 
102
    from bzrlib import trace
 
103
    if has_ctypes:
 
104
        class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
 
105
            """Used by GetProcessMemoryInfo"""
 
106
            _fields_ = [('cb', ctypes.c_ulong),
 
107
                        ('PageFaultCount', ctypes.c_ulong),
 
108
                        ('PeakWorkingSetSize', ctypes.c_size_t),
 
109
                        ('WorkingSetSize', ctypes.c_size_t),
 
110
                        ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
 
111
                        ('QuotaPagedPoolUsage', ctypes.c_size_t),
 
112
                        ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
 
113
                        ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
 
114
                        ('PagefileUsage', ctypes.c_size_t),
 
115
                        ('PeakPagefileUsage', ctypes.c_size_t),
 
116
                        ('PrivateUsage', ctypes.c_size_t),
 
117
                       ]
 
118
        cur_process = ctypes.windll.kernel32.GetCurrentProcess()
 
119
        mem_struct = PROCESS_MEMORY_COUNTERS_EX()
 
120
        ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
 
121
            ctypes.byref(mem_struct),
 
122
            ctypes.sizeof(mem_struct))
 
123
        if not ret:
 
124
            trace.note('Failed to GetProcessMemoryInfo()')
 
125
            return
 
126
        info = {'PageFaultCount': mem_struct.PageFaultCount,
 
127
                'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
 
128
                'WorkingSetSize': mem_struct.WorkingSetSize,
 
129
                'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
 
130
                'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
 
131
                'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
 
132
                'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
 
133
                'PagefileUsage': mem_struct.PagefileUsage,
 
134
                'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
 
135
                'PrivateUsage': mem_struct.PrivateUsage,
 
136
               }
 
137
    elif has_win32api:
 
138
        import win32process
 
139
        # win32process does not return PrivateUsage, because it doesn't use
 
140
        # PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
 
141
        proc = win32process.GetCurrentProcess()
 
142
        info = win32process.GetProcessMemoryInfo(proc)
 
143
    else:
 
144
        trace.note('Cannot debug memory on win32 without ctypes'
 
145
                   ' or win32process')
 
146
        return
 
147
    if short:
 
148
        trace.note('WorkingSize %7dKB'
 
149
                   '\tPeakWorking %7dKB\t%s',
 
150
                   info['WorkingSetSize'] / 1024,
 
151
                   info['PeakWorkingSetSize'] / 1024,
 
152
                   message)
 
153
        return
 
154
    if message:
 
155
        trace.note('%s', message)
 
156
    trace.note('WorkingSize       %8d KB', info['WorkingSetSize'] / 1024)
 
157
    trace.note('PeakWorking       %8d KB', info['PeakWorkingSetSize'] / 1024)
 
158
    trace.note('PagefileUsage     %8d KB', info.get('PagefileUsage', 0) / 1024)
 
159
    trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
 
160
    trace.note('PrivateUsage      %8d KB', info.get('PrivateUsage', 0) / 1024)
 
161
    trace.note('PageFaultCount    %8d', info.get('PageFaultCount', 0))
 
162
 
 
163
 
85
164
def get_console_size(defaultx=80, defaulty=25):
86
165
    """Return size of current console.
87
166
 
109
188
        return (defaultx, defaulty)
110
189
 
111
190
 
 
191
def _get_sh_special_folder_path(csidl):
 
192
    """Call SHGetSpecialFolderPathW if available, or return None.
 
193
 
 
194
    Result is always unicode (or None).
 
195
    """
 
196
    if has_ctypes:
 
197
        try:
 
198
            SHGetSpecialFolderPath = \
 
199
                ctypes.windll.shell32.SHGetSpecialFolderPathW
 
200
        except AttributeError:
 
201
            pass
 
202
        else:
 
203
            buf = ctypes.create_unicode_buffer(MAX_PATH)
 
204
            if SHGetSpecialFolderPath(None,buf,csidl,0):
 
205
                return buf.value
 
206
 
 
207
    global has_win32com_shell
 
208
    if has_win32com_shell is None:
 
209
        try:
 
210
            from win32com.shell import shell
 
211
            has_win32com_shell = True
 
212
        except ImportError:
 
213
            has_win32com_shell = False
 
214
    if has_win32com_shell:
 
215
        # still need to bind the name locally, but this is fast.
 
216
        from win32com.shell import shell
 
217
        try:
 
218
            return shell.SHGetSpecialFolderPath(0, csidl, 0)
 
219
        except shell.error:
 
220
            # possibly E_NOTIMPL meaning we can't load the function pointer,
 
221
            # or E_FAIL meaning the function failed - regardless, just ignore it
 
222
            pass
 
223
    return None
 
224
 
 
225
 
112
226
def get_appdata_location():
113
227
    """Return Application Data location.
114
228
    Return None if we cannot obtain location.
115
229
 
116
 
    Returned value can be unicode or plain sring.
 
230
    Windows defines two 'Application Data' folders per user - a 'roaming'
 
231
    one that moves with the user as they logon to different machines, and
 
232
    a 'local' one that stays local to the machine.  This returns the 'roaming'
 
233
    directory, and thus is suitable for storing user-preferences, etc.
 
234
 
 
235
    Returned value can be unicode or plain string.
117
236
    To convert plain string to unicode use
118
 
    s.decode(bzrlib.user_encoding)
 
237
    s.decode(osutils.get_user_encoding())
 
238
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
119
239
    """
120
 
    if has_ctypes:
121
 
        try:
122
 
            SHGetSpecialFolderPath = \
123
 
                ctypes.windll.shell32.SHGetSpecialFolderPathW
124
 
        except AttributeError:
125
 
            pass
126
 
        else:
127
 
            buf = ctypes.create_unicode_buffer(MAX_PATH)
128
 
            if SHGetSpecialFolderPath(None,buf,CSIDL_APPDATA,0):
129
 
                return buf.value
 
240
    appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
 
241
    if appdata:
 
242
        return appdata
130
243
    # from env variable
131
244
    appdata = os.environ.get('APPDATA')
132
245
    if appdata:
142
255
    return None
143
256
 
144
257
 
 
258
def get_local_appdata_location():
 
259
    """Return Local Application Data location.
 
260
    Return the same as get_appdata_location() if we cannot obtain location.
 
261
 
 
262
    Windows defines two 'Application Data' folders per user - a 'roaming'
 
263
    one that moves with the user as they logon to different machines, and
 
264
    a 'local' one that stays local to the machine.  This returns the 'local'
 
265
    directory, and thus is suitable for caches, temp files and other things
 
266
    which don't need to move with the user.
 
267
 
 
268
    Returned value can be unicode or plain string.
 
269
    To convert plain string to unicode use
 
270
    s.decode(bzrlib.user_encoding)
 
271
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
 
272
    """
 
273
    local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
 
274
    if local:
 
275
        return local
 
276
    # Vista supplies LOCALAPPDATA, but XP and earlier do not.
 
277
    local = os.environ.get('LOCALAPPDATA')
 
278
    if local:
 
279
        return local
 
280
    return get_appdata_location()
 
281
 
 
282
 
145
283
def get_home_location():
146
284
    """Return user's home location.
147
285
    Assume on win32 it's the <My Documents> folder.
148
286
    If location cannot be obtained return system drive root,
149
287
    i.e. C:\
150
288
 
151
 
    Returned value can be unicode or plain sring.
 
289
    Returned value can be unicode or plain string.
152
290
    To convert plain string to unicode use
153
 
    s.decode(bzrlib.user_encoding)
 
291
    s.decode(osutils.get_user_encoding())
154
292
    """
155
 
    if has_ctypes:
156
 
        try:
157
 
            SHGetSpecialFolderPath = \
158
 
                ctypes.windll.shell32.SHGetSpecialFolderPathW
159
 
        except AttributeError:
160
 
            pass
161
 
        else:
162
 
            buf = ctypes.create_unicode_buffer(MAX_PATH)
163
 
            if SHGetSpecialFolderPath(None,buf,CSIDL_PERSONAL,0):
164
 
                return buf.value
 
293
    home = _get_sh_special_folder_path(CSIDL_PERSONAL)
 
294
    if home:
 
295
        return home
165
296
    # try for HOME env variable
166
297
    home = os.path.expanduser('~')
167
298
    if home != '~':
178
309
    """Return user name as login name.
179
310
    If name cannot be obtained return None.
180
311
 
181
 
    Returned value can be unicode or plain sring.
 
312
    Returned value can be unicode or plain string.
182
313
    To convert plain string to unicode use
183
 
    s.decode(bzrlib.user_encoding)
 
314
    s.decode(osutils.get_user_encoding())
184
315
    """
185
316
    if has_ctypes:
186
317
        try:
197
328
    return os.environ.get('USERNAME', None)
198
329
 
199
330
 
 
331
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
 
332
# computer or the cluster associated with the local computer."
 
333
_WIN32_ComputerNameDnsHostname = 1
 
334
 
200
335
def get_host_name():
201
336
    """Return host machine name.
202
337
    If name cannot be obtained return None.
203
338
 
204
 
    Returned value can be unicode or plain sring.
205
 
    To convert plain string to unicode use
206
 
    s.decode(bzrlib.user_encoding)
 
339
    :return: A unicode string representing the host name. On win98, this may be
 
340
        a plain string as win32 api doesn't support unicode.
207
341
    """
 
342
    if has_win32api:
 
343
        try:
 
344
            return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
 
345
        except (NotImplementedError, win32api.error):
 
346
            # NotImplemented will happen on win9x...
 
347
            pass
208
348
    if has_ctypes:
209
349
        try:
210
350
            kernel32 = ctypes.windll.kernel32
211
 
            GetComputerName = getattr(kernel32, 'GetComputerName'+suffix)
212
351
        except AttributeError:
213
 
            pass
 
352
            pass # Missing the module we need
214
353
        else:
215
354
            buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
216
355
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
217
 
            if GetComputerName(buf, ctypes.byref(n)):
218
 
                return buf.value
219
 
    # otherwise try env variables
220
 
    return os.environ.get('COMPUTERNAME', None)
 
356
 
 
357
            # Try GetComputerNameEx which gives a proper Unicode hostname
 
358
            GetComputerNameEx = getattr(kernel32, 'GetComputerNameEx'+suffix,
 
359
                                        None)
 
360
            if (GetComputerNameEx is not None
 
361
                and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
 
362
                                      buf, ctypes.byref(n))):
 
363
                return buf.value
 
364
 
 
365
            # Try GetComputerName in case GetComputerNameEx wasn't found
 
366
            # It returns the NETBIOS name, which isn't as good, but still ok.
 
367
            # The first GetComputerNameEx might have changed 'n', so reset it
 
368
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
 
369
            GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
 
370
                                      None)
 
371
            if (GetComputerName is not None
 
372
                and GetComputerName(buf, ctypes.byref(n))):
 
373
                return buf.value
 
374
    # otherwise try env variables, which will be 'mbcs' encoded
 
375
    # on Windows (Python doesn't expose the native win32 unicode environment)
 
376
    # According to this:
 
377
    # http://msdn.microsoft.com/en-us/library/aa246807.aspx
 
378
    # environment variables should always be encoded in 'mbcs'.
 
379
    try:
 
380
        return os.environ['COMPUTERNAME'].decode("mbcs")
 
381
    except KeyError:
 
382
        return None
221
383
 
222
384
 
223
385
def _ensure_unicode(s):
 
386
    from bzrlib import osutils
224
387
    if s and type(s) != unicode:
225
 
        import bzrlib
226
 
        s = s.decode(bzrlib.user_encoding)
 
388
        from bzrlib import osutils
 
389
        s = s.decode(osutils.get_user_encoding())
227
390
    return s
228
 
    
 
391
 
229
392
 
230
393
def get_appdata_location_unicode():
231
394
    return _ensure_unicode(get_appdata_location())
245
408
        return u'./' + path, True
246
409
    else:
247
410
        return path, False
248
 
    
 
411
 
249
412
def _undo_ensure_with_dir(path, corrected):
250
413
    if corrected:
251
414
        return path[2:]
270
433
    import glob
271
434
    expanded_file_list = []
272
435
    for possible_glob in file_list:
273
 
        
274
436
        # work around bugs in glob.glob()
275
437
        # - Python bug #1001604 ("glob doesn't return unicode with ...")
276
438
        # - failing expansion for */* with non-iso-8859-* chars
285
447
        else:
286
448
            glob_files = [_undo_ensure_with_dir(elem, corrected) for elem in glob_files]
287
449
            expanded_file_list += glob_files
288
 
            
289
 
    return [elem.replace(u'\\', u'/') for elem in expanded_file_list] 
 
450
 
 
451
    return [elem.replace(u'\\', u'/') for elem in expanded_file_list]
 
452
 
 
453
 
 
454
def get_app_path(appname):
 
455
    """Look up in Windows registry for full path to application executable.
 
456
    Typically, applications create subkey with their basename
 
457
    in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
 
458
 
 
459
    :param  appname:    name of application (if no filename extension
 
460
                        is specified, .exe used)
 
461
    :return:    full path to aplication executable from registry,
 
462
                or appname itself if nothing found.
 
463
    """
 
464
    import _winreg
 
465
    try:
 
466
        hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
 
467
                               r'SOFTWARE\Microsoft\Windows'
 
468
                               r'\CurrentVersion\App Paths')
 
469
    except EnvironmentError:
 
470
        return appname
 
471
 
 
472
    basename = appname
 
473
    if not os.path.splitext(basename)[1]:
 
474
        basename = appname + '.exe'
 
475
    try:
 
476
        try:
 
477
            fullpath = _winreg.QueryValue(hkey, basename)
 
478
        except WindowsError:
 
479
            fullpath = appname
 
480
    finally:
 
481
        _winreg.CloseKey(hkey)
 
482
 
 
483
    return fullpath
 
484
 
 
485
 
 
486
def set_file_attr_hidden(path):
 
487
    """Set file attributes to hidden if possible"""
 
488
    if has_win32file:
 
489
        win32file.SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
 
490
 
 
491
 
 
492
if has_ctypes and winver != 'Windows 98':
 
493
    def get_unicode_argv():
 
494
        LPCWSTR = ctypes.c_wchar_p
 
495
        INT = ctypes.c_int
 
496
        POINTER = ctypes.POINTER
 
497
        prototype = ctypes.WINFUNCTYPE(LPCWSTR)
 
498
        GetCommandLine = prototype(("GetCommandLineW",
 
499
                                    ctypes.windll.kernel32))
 
500
        prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
 
501
        CommandLineToArgv = prototype(("CommandLineToArgvW",
 
502
                                       ctypes.windll.shell32))
 
503
        c = INT(0)
 
504
        pargv = CommandLineToArgv(GetCommandLine(), ctypes.byref(c))
 
505
        # Skip the first argument, since we only care about parameters
 
506
        argv = [pargv[i] for i in range(1, c.value)]
 
507
        if getattr(sys, 'frozen', None) is None:
 
508
            # Invoked via 'python.exe' which takes the form:
 
509
            #   python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
 
510
            # we need to get only BZR_OPTIONS part,
 
511
            # so let's using sys.argv[1:] as reference to get the tail
 
512
            # of unicode argv
 
513
            tail_len = len(sys.argv[1:])
 
514
            ix = len(argv) - tail_len
 
515
            argv = argv[ix:]
 
516
        return argv
 
517
else:
 
518
    get_unicode_argv = None