[PATCH] Detect console width on Windows

Patrick Mézard pmezard at gmail.com
Sun Apr 25 13:10:59 CDT 2010


Le 25/04/10 10:44, anatoly techtonik a écrit :
> On Sun, Apr 25, 2010 at 11:01 AM, Dirkjan Ochtman <dirkjan at ochtman.nl> wrote:
>>
>> You should probably just move the current termwidth() to posix.py and
>> implement your new termwidth() in win32.py. Don't call it
>> get_console_width(), that doesn't mash well with our coding style (see
>> the CodingStyle page in the wiki).
> 
> Done.
> 
> # HG changeset patch
> # Parent 33119d0252c1aa46da82a22aeb067fcd172ce804
> # User anatoly techtonik <techtonik at gmail.com>
> Detect console width on Windows

Here is what they do in bzr-2.0.3:

--------------------
def get_console_size(defaultx=80, defaulty=25):
    """Return size of current console.

    This function try to determine actual size of current working
    console window and return tuple (sizex, sizey) if success,
    or default size (defaultx, defaulty) otherwise.
    """
    if not has_ctypes:
        # no ctypes is found
        return (defaultx, defaulty)

    # To avoid problem with redirecting output via pipe
    # need to use stderr instead of stdout
    h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

    if res:
        (bufx, bufy, curx, cury, wattr,
        left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return (sizex, sizey)
    else:
        return (defaultx, defaulty)
--------------------

I tested your current version when piping to less and it actually fails and default to width=80, so I suggest we use WIN32_STDERR_HANDLE instead which is less likely to be redirected.

And there is the size computation part, where they take "left" in account while we assume it is zero. I don't how this thing can be changed but I think doing the same is harmless at worse.

--
Patrick Mézard


More information about the Mercurial-devel mailing list