/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/win32console.py

  • Committer: Robert Collins
  • Date: 2005-12-24 02:20:45 UTC
  • mto: (1185.50.57 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1550.
  • Revision ID: robertc@robertcollins.net-20051224022045-14efc8dfa0e1a4e9
Start tests for api usage.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
2
 
#
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.
7
 
#
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.
12
 
#
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
16
 
 
17
 
"""Win32-specific helper functions
18
 
 
19
 
Only one dependency: ctypes should be installed.
20
 
"""
21
 
 
22
 
import glob
23
 
import os
 
1
 
 
2
"""
 
3
Set of functions to work with console on Windows.
 
4
Author: Alexander Belchenko (e-mail: bialix AT ukr.net)
 
5
License: Public domain
 
6
"""
 
7
 
24
8
import struct
25
 
import sys
26
 
 
27
 
from breezy import (
28
 
    cmdline,
29
 
    )
30
 
from breezy.i18n import gettext
31
 
 
32
 
 
33
 
# Special Win32 API constants
34
 
# Handles of std streams
35
 
WIN32_STDIN_HANDLE = -10
36
 
WIN32_STDOUT_HANDLE = -11
37
 
WIN32_STDERR_HANDLE = -12
38
 
 
39
 
# CSIDL constants (from MSDN 2003)
40
 
CSIDL_APPDATA = 0x001A      # Application Data folder
41
 
# <user name>\Local Settings\Application Data (non roaming)
42
 
CSIDL_LOCAL_APPDATA = 0x001c
43
 
CSIDL_PERSONAL = 0x0005     # My Documents folder
44
 
 
45
 
# from winapi C headers
46
 
MAX_PATH = 260
47
 
UNLEN = 256
48
 
MAX_COMPUTERNAME_LENGTH = 31
49
 
 
50
 
# Registry data type ids
51
 
REG_SZ = 1
52
 
REG_EXPAND_SZ = 2
53
 
 
54
 
 
55
 
def debug_memory_win32api(message='', short=True):
56
 
    """Use trace.note() to dump the running memory info."""
57
 
    import ctypes
58
 
    from breezy import trace
59
 
    class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
60
 
        """Used by GetProcessMemoryInfo"""
61
 
        _fields_ = [('cb', ctypes.c_ulong),
62
 
                    ('PageFaultCount', ctypes.c_ulong),
63
 
                    ('PeakWorkingSetSize', ctypes.c_size_t),
64
 
                    ('WorkingSetSize', ctypes.c_size_t),
65
 
                    ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
66
 
                    ('QuotaPagedPoolUsage', ctypes.c_size_t),
67
 
                    ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
68
 
                    ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
69
 
                    ('PagefileUsage', ctypes.c_size_t),
70
 
                    ('PeakPagefileUsage', ctypes.c_size_t),
71
 
                    ('PrivateUsage', ctypes.c_size_t),
72
 
                    ]
73
 
    cur_process = ctypes.windll.kernel32.GetCurrentProcess()
74
 
    mem_struct = PROCESS_MEMORY_COUNTERS_EX()
75
 
    ret = ctypes.windll.psapi.GetProcessMemoryInfo(
76
 
        cur_process, ctypes.byref(mem_struct), ctypes.sizeof(mem_struct))
77
 
    if not ret:
78
 
        trace.note(gettext('Failed to GetProcessMemoryInfo()'))
79
 
        return
80
 
    info = {'PageFaultCount': mem_struct.PageFaultCount,
81
 
            'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
82
 
            'WorkingSetSize': mem_struct.WorkingSetSize,
83
 
            'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
84
 
            'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
85
 
            'QuotaPeakNonPagedPoolUsage':
86
 
                mem_struct.QuotaPeakNonPagedPoolUsage,
87
 
            'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
88
 
            'PagefileUsage': mem_struct.PagefileUsage,
89
 
            'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
90
 
            'PrivateUsage': mem_struct.PrivateUsage,
91
 
            }
92
 
    if short:
93
 
        # using base-2 units (see HACKING.txt).
94
 
        trace.note(gettext('WorkingSize {0:>7}KiB'
95
 
                           '\tPeakWorking {1:>7}KiB\t{2}').format(
96
 
                   info['WorkingSetSize'] / 1024,
97
 
                   info['PeakWorkingSetSize'] / 1024,
98
 
                   message))
99
 
        return
100
 
    if message:
101
 
        trace.note('%s', message)
102
 
    trace.note(gettext('WorkingSize       %8d KiB'),
103
 
               info['WorkingSetSize'] / 1024)
104
 
    trace.note(gettext('PeakWorking       %8d KiB'),
105
 
               info['PeakWorkingSetSize'] / 1024)
106
 
    trace.note(gettext('PagefileUsage     %8d KiB'),
107
 
               info.get('PagefileUsage', 0) / 1024)
108
 
    trace.note(gettext('PeakPagefileUsage %8d KiB'),
109
 
               info.get('PeakPagefileUsage', 0) / 1024)
110
 
    trace.note(gettext('PrivateUsage      %8d KiB'),
111
 
               info.get('PrivateUsage', 0) / 1024)
112
 
    trace.note(gettext('PageFaultCount    %8d'), info.get('PageFaultCount', 0))
 
9
 
 
10
try:
 
11
   import ctypes
 
12
except ImportError:
 
13
   ctypes = None
113
14
 
114
15
 
115
16
def get_console_size(defaultx=80, defaulty=25):
116
 
    """Return size of current console.
117
 
 
118
 
    This function try to determine actual size of current working
119
 
    console window and return tuple (sizex, sizey) if success,
120
 
    or default size (defaultx, defaulty) otherwise.
121
 
    """
122
 
    import ctypes
123
 
    # To avoid problem with redirecting output via pipe
124
 
    # we need to use stderr instead of stdout
125
 
    h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
126
 
    csbi = ctypes.create_string_buffer(22)
127
 
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
128
 
 
129
 
    if res:
130
 
        (bufx, bufy, curx, cury, wattr,
131
 
         left, top, right, bottom, maxx, maxy) = struct.unpack(
132
 
            "hhhhHhhhhhh", csbi.raw)
133
 
        sizex = right - left + 1
134
 
        sizey = bottom - top + 1
135
 
        return (sizex, sizey)
136
 
    else:
137
 
        return (defaultx, defaulty)
138
 
 
139
 
 
140
 
def _get_sh_special_folder_path(csidl):
141
 
    """Call SHGetSpecialFolderPathW if available, or return None.
142
 
 
143
 
    Result is always unicode (or None).
144
 
    """
145
 
    import ctypes
146
 
    try:
147
 
        SHGetSpecialFolderPath = \
148
 
            ctypes.windll.shell32.SHGetSpecialFolderPathW
149
 
    except AttributeError:
150
 
        pass
151
 
    else:
152
 
        buf = ctypes.create_unicode_buffer(MAX_PATH)
153
 
        if SHGetSpecialFolderPath(None, buf, csidl, 0):
154
 
            return buf.value
155
 
 
156
 
 
157
 
def get_appdata_location():
158
 
    """Return Application Data location.
159
 
    Return None if we cannot obtain location.
160
 
 
161
 
    Windows defines two 'Application Data' folders per user - a 'roaming'
162
 
    one that moves with the user as they logon to different machines, and
163
 
    a 'local' one that stays local to the machine.  This returns the 'roaming'
164
 
    directory, and thus is suitable for storing user-preferences, etc.
165
 
    """
166
 
    appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
167
 
    if appdata:
168
 
        return appdata
169
 
    # Use APPDATA if defined, will return None if not
170
 
    return os.environ.get('APPDATA')
171
 
 
172
 
 
173
 
def get_local_appdata_location():
174
 
    """Return Local Application Data location.
175
 
    Return the same as get_appdata_location() if we cannot obtain location.
176
 
 
177
 
    Windows defines two 'Application Data' folders per user - a 'roaming'
178
 
    one that moves with the user as they logon to different machines, and
179
 
    a 'local' one that stays local to the machine.  This returns the 'local'
180
 
    directory, and thus is suitable for caches, temp files and other things
181
 
    which don't need to move with the user.
182
 
    """
183
 
    local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
184
 
    if local:
185
 
        return local
186
 
    # Vista supplies LOCALAPPDATA, but XP and earlier do not.
187
 
    local = os.environ.get('LOCALAPPDATA')
188
 
    if local:
189
 
        return local
190
 
    return get_appdata_location()
191
 
 
192
 
 
193
 
def get_home_location():
194
 
    """Return user's home location.
195
 
    Assume on win32 it's the <My Documents> folder.
196
 
    If location cannot be obtained return system drive root,
197
 
    i.e. C:\
198
 
    """
199
 
    home = _get_sh_special_folder_path(CSIDL_PERSONAL)
200
 
    if home:
201
 
        return home
202
 
    home = os.environ.get('HOME')
203
 
    if home is not None:
204
 
        return home
205
 
    homepath = os.environ.get('HOMEPATH')
206
 
    if homepath is not None:
207
 
        return os.path.join(os.environ.get('HOMEDIR', ''), home)
208
 
    # at least return windows root directory
209
 
    windir = os.environ.get('WINDIR')
210
 
    if windir:
211
 
        return os.path.splitdrive(windir)[0] + '/'
212
 
    # otherwise C:\ is good enough for 98% users
213
 
    return u'C:/'
214
 
 
215
 
 
216
 
def get_user_name():
217
 
    """Return user name as login name.
218
 
    If name cannot be obtained return None.
219
 
    """
220
 
    try:
221
 
        advapi32 = ctypes.windll.advapi32
222
 
        GetUserName = getattr(advapi32, 'GetUserNameW')
223
 
    except AttributeError:
224
 
        pass
225
 
    else:
226
 
        buf = ctypes.create_unicode_buffer(UNLEN + 1)
227
 
        n = ctypes.c_int(UNLEN + 1)
228
 
        if GetUserName(buf, ctypes.byref(n)):
229
 
            return buf.value
230
 
    # otherwise try env variables
231
 
    return os.environ.get('USERNAME')
232
 
 
233
 
 
234
 
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
235
 
# computer or the cluster associated with the local computer."
236
 
_WIN32_ComputerNameDnsHostname = 1
237
 
 
238
 
 
239
 
def get_host_name():
240
 
    """Return host machine name.
241
 
    If name cannot be obtained return None.
242
 
 
243
 
    :return: A unicode string representing the host name.
244
 
    """
245
 
    import ctypes
246
 
    buf = ctypes.create_unicode_buffer(MAX_COMPUTERNAME_LENGTH + 1)
247
 
    n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH + 1)
248
 
 
249
 
    # Try GetComputerNameEx which gives a proper Unicode hostname
250
 
    GetComputerNameEx = getattr(
251
 
        ctypes.windll.kernel32, 'GetComputerNameExW', None)
252
 
    if (GetComputerNameEx is not None
253
 
        and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
254
 
                              buf, ctypes.byref(n))):
255
 
        return buf.value
256
 
    return os.environ.get('COMPUTERNAME')
257
 
 
258
 
 
259
 
def _ensure_with_dir(path):
260
 
    if (not os.path.split(path)[0] or path.startswith(u'*')
261
 
            or path.startswith(u'?')):
262
 
        return u'./' + path, True
263
 
    else:
264
 
        return path, False
265
 
 
266
 
 
267
 
def _undo_ensure_with_dir(path, corrected):
268
 
    if corrected:
269
 
        return path[2:]
270
 
    else:
271
 
        return path
272
 
 
273
 
 
274
 
def glob_one(possible_glob):
275
 
    """Same as glob.glob().
276
 
 
277
 
    work around bugs in glob.glob()
278
 
    - Python bug #1001604 ("glob doesn't return unicode with ...")
279
 
    - failing expansion for */* with non-iso-8859-* chars
280
 
    """
281
 
    corrected_glob, corrected = _ensure_with_dir(possible_glob)
282
 
    glob_files = glob.glob(corrected_glob)
283
 
 
284
 
    if not glob_files:
285
 
        # special case to let the normal code path handle
286
 
        # files that do not exist, etc.
287
 
        glob_files = [possible_glob]
288
 
    elif corrected:
289
 
        glob_files = [_undo_ensure_with_dir(elem, corrected)
290
 
                      for elem in glob_files]
291
 
    return [elem.replace(u'\\', u'/') for elem in glob_files]
292
 
 
293
 
 
294
 
def glob_expand(file_list):
295
 
    """Replacement for glob expansion by the shell.
296
 
 
297
 
    Win32's cmd.exe does not do glob expansion (eg ``*.py``), so we do our own
298
 
    here.
299
 
 
300
 
    :param file_list: A list of filenames which may include shell globs.
301
 
    :return: An expanded list of filenames.
302
 
 
303
 
    Introduced in breezy 0.18.
304
 
    """
305
 
    if not file_list:
306
 
        return []
307
 
    expanded_file_list = []
308
 
    for possible_glob in file_list:
309
 
        expanded_file_list.extend(glob_one(possible_glob))
310
 
    return expanded_file_list
311
 
 
312
 
 
313
 
def get_app_path(appname):
314
 
    r"""Look up in Windows registry for full path to application executable.
315
 
    Typically, applications create subkey with their basename
316
 
    in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
317
 
 
318
 
    :param  appname:    name of application (if no filename extension
319
 
                        is specified, .exe used)
320
 
    :return:    full path to aplication executable from registry,
321
 
                or appname itself if nothing found.
322
 
    """
323
 
    import _winreg
324
 
 
325
 
    basename = appname
326
 
    if not os.path.splitext(basename)[1]:
327
 
        basename = appname + '.exe'
328
 
 
329
 
    try:
330
 
        hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
331
 
                               'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
332
 
                               basename)
333
 
    except EnvironmentError:
334
 
        return appname
335
 
 
336
 
    try:
337
 
        try:
338
 
            path, type_id = _winreg.QueryValueEx(hkey, '')
339
 
        except WindowsError:
340
 
            return appname
341
 
    finally:
342
 
        _winreg.CloseKey(hkey)
343
 
 
344
 
    if type_id == REG_SZ:
345
 
        return path
346
 
    return appname
347
 
 
348
 
 
349
 
def set_file_attr_hidden(path):
350
 
    """Set file attributes to hidden if possible"""
351
 
    from ctypes.wintypes import BOOL, DWORD, LPWSTR
352
 
    import ctypes
353
 
    # <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
354
 
    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
355
 
    SetFileAttributes.argtypes = LPWSTR, DWORD
356
 
    SetFileAttributes.restype = BOOL
357
 
    FILE_ATTRIBUTE_HIDDEN = 2
358
 
    if not SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN):
359
 
        e = ctypes.WinError()
360
 
        from . import trace
361
 
        trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
362
 
 
363
 
 
364
 
def _command_line_to_argv(command_line, argv, single_quotes_allowed=False):
365
 
    """Convert a Unicode command line into a list of argv arguments.
366
 
 
367
 
    It performs wildcard expansion to make wildcards act closer to how they
368
 
    work in posix shells, versus how they work by default on Windows. Quoted
369
 
    arguments are left untouched.
370
 
 
371
 
    :param command_line: The unicode string to split into an arg list.
372
 
    :param single_quotes_allowed: Whether single quotes are accepted as quoting
373
 
                                  characters like double quotes. False by
374
 
                                  default.
375
 
    :return: A list of unicode strings.
376
 
    """
377
 
    # First, split the command line
378
 
    s = cmdline.Splitter(
379
 
        command_line, single_quotes_allowed=single_quotes_allowed)
380
 
 
381
 
    # Bug #587868 Now make sure that the length of s agrees with sys.argv
382
 
    # we do this by simply counting the number of arguments in each. The counts should
383
 
    # agree no matter what encoding sys.argv is in (AFAIK)
384
 
    # len(arguments) < len(sys.argv) should be an impossibility since python gets
385
 
    # args from the very same PEB as does GetCommandLineW
386
 
    arguments = list(s)
387
 
 
388
 
    # Now shorten the command line we get from GetCommandLineW to match sys.argv
389
 
    if len(arguments) < len(argv):
390
 
        raise AssertionError("Split command line can't be shorter than argv")
391
 
    arguments = arguments[len(arguments) - len(argv):]
392
 
 
393
 
    # Carry on to process globs (metachars) in the command line
394
 
    # expand globs if necessary
395
 
    # TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
396
 
    #       '**/' style globs
397
 
    args = []
398
 
    for is_quoted, arg in arguments:
399
 
        if is_quoted or not glob.has_magic(arg):
400
 
            args.append(arg)
401
 
        else:
402
 
            args.extend(glob_one(arg))
403
 
    return args
404
 
 
405
 
 
406
 
def _ctypes_is_local_pid_dead(pid):
407
 
    import ctypes
408
 
    kernel32 = ctypes.wintypes.windll.kernel32
409
 
    """True if pid doesn't correspond to live process on this machine"""
410
 
    handle = kernel32.OpenProcess(1, False, pid)
411
 
    if not handle:
412
 
        errorcode = ctypes.GetLastError()
413
 
        if errorcode == 5:  # ERROR_ACCESS_DENIED
414
 
            # Probably something alive we're not allowed to kill
415
 
            return False
416
 
        elif errorcode == 87:  # ERROR_INVALID_PARAMETER
417
 
            return True
418
 
        raise ctypes.WinError(errorcode)
419
 
    Kernel32.CloseHandle(handle)
420
 
    return False
421
 
 
422
 
is_local_pid_dead = _ctypes_is_local_pid_dead
 
17
   """ Return size of current console.
 
18
 
 
19
   This function try to determine actual size of current working
 
20
   console window and return tuple (sizex, sizey) if success,
 
21
   or default size (defaultx, defaulty) otherwise.
 
22
 
 
23
   Dependencies: ctypes should be installed.
 
24
   """
 
25
   if ctypes is None:
 
26
       # no ctypes is found
 
27
       return (defaultx, defaulty)
 
28
 
 
29
   h = ctypes.windll.kernel32.GetStdHandle(-11)
 
30
   csbi = ctypes.create_string_buffer(22)
 
31
   res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
 
32
 
 
33
   if res:
 
34
       (bufx, bufy, curx, cury, wattr,
 
35
        left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
 
36
       sizex = right - left + 1
 
37
       sizey = bottom - top + 1
 
38
       return (sizex, sizey)
 
39
   else:
 
40
       return (defaultx, defaulty)