summaryrefslogtreecommitdiff
path: root/utils/Win32Console.cc
blob: ea46e17b6cdbf715e7161e384fabc102214d05eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//========================================================================
//
// Win32Console.cc
//
// This file is licensed under the GPLv2 or later
//
// Copyright (C) 2017 Adrian Johnson <ajohnson@redneon.com>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================

#ifdef _WIN32

#    include "goo/gmem.h"
#    include "UTF.h"

#    define WIN32_CONSOLE_IMPL
#    include "Win32Console.h"

#    include <windows.h>
#    include <shellapi.h>

static const int BUF_SIZE = 4096;
static int bufLen = 0;
static char buf[BUF_SIZE];
static wchar_t wbuf[BUF_SIZE];
static bool stdoutIsConsole = true;
static bool stderrIsConsole = true;
static HANDLE consoleHandle = nullptr;

// If all = true, flush all characters to console.
// If all = false, flush up to and including last newline.
// Also flush all if buffer > half full to ensure space for future
// writes.
static void flush(bool all = false)
{
    int nchars = 0;

    if (all || bufLen > BUF_SIZE / 2) {
        nchars = bufLen;
    } else if (bufLen > 0) {
        // find num chars up to and including last '\n'
        for (nchars = bufLen; nchars > 0; --nchars) {
            if (buf[nchars - 1] == '\n')
                break;
        }
    }

    if (nchars > 0) {
        DWORD wlen = utf8ToUtf16(buf, (uint16_t *)wbuf, BUF_SIZE, nchars);
        WriteConsoleW(consoleHandle, wbuf, wlen, &wlen, nullptr);
        if (nchars < bufLen) {
            memmove(buf, buf + nchars, bufLen - nchars);
            bufLen -= nchars;
        } else {
            bufLen = 0;
        }
    }
}

static inline bool streamIsConsole(FILE *stream)
{
    return ((stream == stdout && stdoutIsConsole) || (stream == stderr && stderrIsConsole));
}

int win32_fprintf(FILE *stream, ...)
{
    va_list args;
    int ret = 0;

    va_start(args, stream);
    const char *format = va_arg(args, const char *);
    if (streamIsConsole(stream)) {
        ret = vsnprintf(buf + bufLen, BUF_SIZE - bufLen, format, args);
        bufLen += ret;
        if (ret >= BUF_SIZE - bufLen) {
            // output was truncated
            buf[BUF_SIZE - 1] = 0;
            bufLen = BUF_SIZE - 1;
        }
        flush();
    } else {
        vfprintf(stream, format, args);
    }
    va_end(args);

    return ret;
}

size_t win32_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t ret = 0;

    if (streamIsConsole(stream)) {
        int n = size * nmemb;
        if (n > BUF_SIZE - bufLen - 1)
            n = BUF_SIZE - bufLen - 1;
        memcpy(buf + bufLen, ptr, n);
        bufLen += n;
        buf[bufLen] = 0;
        flush();
    } else {
        ret = fwrite(ptr, size, nmemb, stream);
    }

    return ret;
}

Win32Console::Win32Console(int *argc, char **argv[])
{
    LPWSTR *wargv;
    fpos_t pos;

    argList = nullptr;
    privateArgList = nullptr;
    wargv = CommandLineToArgvW(GetCommandLineW(), &numArgs);
    if (wargv) {
        argList = new char *[numArgs];
        privateArgList = new char *[numArgs];
        for (int i = 0; i < numArgs; i++) {
            argList[i] = utf16ToUtf8((uint16_t *)(wargv[i]));
            // parseArgs will rearrange the argv list so we keep our own copy
            // to use for freeing all the strings
            privateArgList[i] = argList[i];
        }
        LocalFree(wargv);
        *argc = numArgs;
        *argv = argList;
    }

    bufLen = 0;
    buf[0] = 0;
    wbuf[0] = 0;

    // check if stdout or stderr redirected
    // GetFileType() returns CHAR for console and special devices COMx, PRN, CON, NUL etc
    // fgetpos() succeeds on all CHAR devices except console and CON.

    stdoutIsConsole = (GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)) == FILE_TYPE_CHAR) && (fgetpos(stdout, &pos) != 0);

    stderrIsConsole = (GetFileType(GetStdHandle(STD_ERROR_HANDLE)) == FILE_TYPE_CHAR) && (fgetpos(stderr, &pos) != 0);

    // Need a handle to the console. Doesn't matter if we use stdout or stderr as
    // long as the handle output is to the console.
    if (stdoutIsConsole)
        consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    else if (stderrIsConsole)
        consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
}

Win32Console::~Win32Console()
{
    flush(true);
    if (argList) {
        for (int i = 0; i < numArgs; i++)
            gfree(privateArgList[i]);
        delete[] argList;
        delete[] privateArgList;
    }
}

#endif // _WIN32