~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/win32utils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-27 01:34:47 UTC
  • mfrom: (4650.2.2 bug-393677)
  • Revision ID: pqm@pqm.ubuntu.com-20090827013447-ndjtt02ad7nfdoiy
(robertc) Pass IncompatibleRepositories error over the smart server.
        (Robert Collins)

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
 
66
66
        suffix = 'W'
67
67
try:
68
68
    import win32file
 
69
    import pywintypes
69
70
    has_win32file = True
70
71
except ImportError:
71
72
    has_win32file = False
75
76
except ImportError:
76
77
    has_win32api = False
77
78
 
 
79
# pulling in win32com.shell is a bit of overhead, and normally we don't need
 
80
# it as ctypes is preferred and common.  lazy_imports and "optional"
 
81
# modules don't work well, so we do our own lazy thing...
 
82
has_win32com_shell = None # Set to True or False once we know for sure...
78
83
 
79
84
# Special Win32 API constants
80
85
# Handles of std streams
84
89
 
85
90
# CSIDL constants (from MSDN 2003)
86
91
CSIDL_APPDATA = 0x001A      # Application Data folder
 
92
CSIDL_LOCAL_APPDATA = 0x001c# <user name>\Local Settings\Application Data (non roaming)
87
93
CSIDL_PERSONAL = 0x0005     # My Documents folder
88
94
 
89
95
# from winapi C headers
91
97
UNLEN = 256
92
98
MAX_COMPUTERNAME_LENGTH = 31
93
99
 
 
100
# Registry data type ids
 
101
REG_SZ = 1
 
102
REG_EXPAND_SZ = 2
 
103
 
 
104
 
 
105
def debug_memory_win32api(message='', short=True):
 
106
    """Use trace.note() to dump the running memory info."""
 
107
    from bzrlib import trace
 
108
    if has_ctypes:
 
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),
 
122
                       ]
 
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))
 
128
        if not ret:
 
129
            trace.note('Failed to GetProcessMemoryInfo()')
 
130
            return
 
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,
 
141
               }
 
142
    elif has_win32api:
 
143
        import win32process
 
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)
 
148
    else:
 
149
        trace.note('Cannot debug memory on win32 without ctypes'
 
150
                   ' or win32process')
 
151
        return
 
152
    if short:
 
153
        trace.note('WorkingSize %7dKB'
 
154
                   '\tPeakWorking %7dKB\t%s',
 
155
                   info['WorkingSetSize'] / 1024,
 
156
                   info['PeakWorkingSetSize'] / 1024,
 
157
                   message)
 
158
        return
 
159
    if message:
 
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))
 
167
 
94
168
 
95
169
def get_console_size(defaultx=80, defaulty=25):
96
170
    """Return size of current console.
119
193
        return (defaultx, defaulty)
120
194
 
121
195
 
 
196
def _get_sh_special_folder_path(csidl):
 
197
    """Call SHGetSpecialFolderPathW if available, or return None.
 
198
 
 
199
    Result is always unicode (or None).
 
200
    """
 
201
    if has_ctypes:
 
202
        try:
 
203
            SHGetSpecialFolderPath = \
 
204
                ctypes.windll.shell32.SHGetSpecialFolderPathW
 
205
        except AttributeError:
 
206
            pass
 
207
        else:
 
208
            buf = ctypes.create_unicode_buffer(MAX_PATH)
 
209
            if SHGetSpecialFolderPath(None,buf,csidl,0):
 
210
                return buf.value
 
211
 
 
212
    global has_win32com_shell
 
213
    if has_win32com_shell is None:
 
214
        try:
 
215
            from win32com.shell import shell
 
216
            has_win32com_shell = True
 
217
        except ImportError:
 
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
 
222
        try:
 
223
            return shell.SHGetSpecialFolderPath(0, csidl, 0)
 
224
        except shell.error:
 
225
            # possibly E_NOTIMPL meaning we can't load the function pointer,
 
226
            # or E_FAIL meaning the function failed - regardless, just ignore it
 
227
            pass
 
228
    return None
 
229
 
 
230
 
122
231
def get_appdata_location():
123
232
    """Return Application Data location.
124
233
    Return None if we cannot obtain location.
125
234
 
126
 
    Returned value can be unicode or plain sring.
 
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.
 
239
 
 
240
    Returned value can be unicode or plain string.
127
241
    To convert plain string to unicode use
128
 
    s.decode(bzrlib.user_encoding)
 
242
    s.decode(osutils.get_user_encoding())
 
243
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
129
244
    """
130
 
    if has_ctypes:
131
 
        try:
132
 
            SHGetSpecialFolderPath = \
133
 
                ctypes.windll.shell32.SHGetSpecialFolderPathW
134
 
        except AttributeError:
135
 
            pass
136
 
        else:
137
 
            buf = ctypes.create_unicode_buffer(MAX_PATH)
138
 
            if SHGetSpecialFolderPath(None,buf,CSIDL_APPDATA,0):
139
 
                return buf.value
 
245
    appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
 
246
    if appdata:
 
247
        return appdata
140
248
    # from env variable
141
249
    appdata = os.environ.get('APPDATA')
142
250
    if appdata:
152
260
    return None
153
261
 
154
262
 
 
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.
 
266
 
 
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.
 
272
 
 
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')
 
277
    """
 
278
    local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
 
279
    if local:
 
280
        return local
 
281
    # Vista supplies LOCALAPPDATA, but XP and earlier do not.
 
282
    local = os.environ.get('LOCALAPPDATA')
 
283
    if local:
 
284
        return local
 
285
    return get_appdata_location()
 
286
 
 
287
 
155
288
def get_home_location():
156
289
    """Return user's home location.
157
290
    Assume on win32 it's the <My Documents> folder.
158
291
    If location cannot be obtained return system drive root,
159
292
    i.e. C:\
160
293
 
161
 
    Returned value can be unicode or plain sring.
 
294
    Returned value can be unicode or plain string.
162
295
    To convert plain string to unicode use
163
 
    s.decode(bzrlib.user_encoding)
 
296
    s.decode(osutils.get_user_encoding())
164
297
    """
165
 
    if has_ctypes:
166
 
        try:
167
 
            SHGetSpecialFolderPath = \
168
 
                ctypes.windll.shell32.SHGetSpecialFolderPathW
169
 
        except AttributeError:
170
 
            pass
171
 
        else:
172
 
            buf = ctypes.create_unicode_buffer(MAX_PATH)
173
 
            if SHGetSpecialFolderPath(None,buf,CSIDL_PERSONAL,0):
174
 
                return buf.value
 
298
    home = _get_sh_special_folder_path(CSIDL_PERSONAL)
 
299
    if home:
 
300
        return home
175
301
    # try for HOME env variable
176
302
    home = os.path.expanduser('~')
177
303
    if home != '~':
188
314
    """Return user name as login name.
189
315
    If name cannot be obtained return None.
190
316
 
191
 
    Returned value can be unicode or plain sring.
 
317
    Returned value can be unicode or plain string.
192
318
    To convert plain string to unicode use
193
 
    s.decode(bzrlib.user_encoding)
 
319
    s.decode(osutils.get_user_encoding())
194
320
    """
195
321
    if has_ctypes:
196
322
        try:
262
388
 
263
389
 
264
390
def _ensure_unicode(s):
 
391
    from bzrlib import osutils
265
392
    if s and type(s) != unicode:
266
 
        import bzrlib
267
 
        s = s.decode(bzrlib.user_encoding)
 
393
        from bzrlib import osutils
 
394
        s = s.decode(osutils.get_user_encoding())
268
395
    return s
269
396
 
270
397
 
286
413
        return u'./' + path, True
287
414
    else:
288
415
        return path, False
289
 
    
 
416
 
290
417
def _undo_ensure_with_dir(path, corrected):
291
418
    if corrected:
292
419
        return path[2:]
311
438
    import glob
312
439
    expanded_file_list = []
313
440
    for possible_glob in file_list:
314
 
        
315
441
        # work around bugs in glob.glob()
316
442
        # - Python bug #1001604 ("glob doesn't return unicode with ...")
317
443
        # - failing expansion for */* with non-iso-8859-* chars
326
452
        else:
327
453
            glob_files = [_undo_ensure_with_dir(elem, corrected) for elem in glob_files]
328
454
            expanded_file_list += glob_files
329
 
            
330
 
    return [elem.replace(u'\\', u'/') for elem in expanded_file_list] 
 
455
 
 
456
    return [elem.replace(u'\\', u'/') for elem in expanded_file_list]
331
457
 
332
458
 
333
459
def get_app_path(appname):
334
460
    """Look up in Windows registry for full path to application executable.
335
 
    Typicaly, applications create subkey with their basename
 
461
    Typically, applications create subkey with their basename
336
462
    in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
337
463
 
338
464
    :param  appname:    name of application (if no filename extension
341
467
                or appname itself if nothing found.
342
468
    """
343
469
    import _winreg
 
470
 
 
471
    basename = appname
 
472
    if not os.path.splitext(basename)[1]:
 
473
        basename = appname + '.exe'
 
474
 
344
475
    try:
345
476
        hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
346
 
                               r'SOFTWARE\Microsoft\Windows'
347
 
                               r'\CurrentVersion\App Paths')
 
477
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
 
478
            basename)
348
479
    except EnvironmentError:
349
480
        return appname
350
481
 
351
 
    basename = appname
352
 
    if not os.path.splitext(basename)[1]:
353
 
        basename = appname + '.exe'
354
482
    try:
355
483
        try:
356
 
            fullpath = _winreg.QueryValue(hkey, basename)
 
484
            path, type_id = _winreg.QueryValueEx(hkey, '')
357
485
        except WindowsError:
358
 
            fullpath = appname
 
486
            return appname
359
487
    finally:
360
488
        _winreg.CloseKey(hkey)
361
489
 
362
 
    return fullpath
 
490
    if type_id == REG_SZ:
 
491
        return path
 
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
 
496
        return fullpath
 
497
    return appname
363
498
 
364
499
 
365
500
def set_file_attr_hidden(path):
366
501
    """Set file attributes to hidden if possible"""
367
502
    if has_win32file:
368
 
        win32file.SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
 
503
        if winver != 'Windows 98':
 
504
            SetFileAttributes = win32file.SetFileAttributesW
 
505
        else:
 
506
            SetFileAttributes = win32file.SetFileAttributes
 
507
        try:
 
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)
 
512
 
 
513
 
 
514
if has_ctypes and winver != 'Windows 98':
 
515
    def get_unicode_argv():
 
516
        LPCWSTR = ctypes.c_wchar_p
 
517
        INT = ctypes.c_int
 
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))
 
525
        c = INT(0)
 
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
 
534
            # of unicode argv
 
535
            tail_len = len(sys.argv[1:])
 
536
            ix = len(argv) - tail_len
 
537
            argv = argv[ix:]
 
538
        return argv
 
539
else:
 
540
    get_unicode_argv = None