1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include <__config>
10
11 #if defined(_LIBCPP_WIN32API)
12
13 # include <cstdlib>
14 # include <print>
15
16 # define WIN32_LEAN_AND_MEAN
17 # define NOMINMAX
18 # include <io.h>
19 # include <windows.h>
20
21 # include <__system_error/system_error.h>
22
23 # include "filesystem/error.h"
24
25 _LIBCPP_BEGIN_NAMESPACE_STD
26
__is_windows_terminal(FILE * __stream)27 _LIBCPP_EXPORTED_FROM_ABI bool __is_windows_terminal(FILE* __stream) {
28 // Note the Standard does this in one call, but it's unclear whether
29 // an invalid handle is allowed when calling GetConsoleMode.
30 //
31 // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=msvc-170
32 // https://learn.microsoft.com/en-us/windows/console/getconsolemode
33 intptr_t __handle = _get_osfhandle(fileno(__stream));
34 if (__handle == -1)
35 return false;
36
37 unsigned long __mode;
38 return GetConsoleMode(reinterpret_cast<void*>(__handle), &__mode);
39 }
40
41 # ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
42 _LIBCPP_EXPORTED_FROM_ABI void
__write_to_windows_console(FILE * __stream,wstring_view __view)43 __write_to_windows_console([[maybe_unused]] FILE* __stream, [[maybe_unused]] wstring_view __view) {
44 // https://learn.microsoft.com/en-us/windows/console/writeconsole
45 if (WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fileno(__stream))), // clang-format aid
46 __view.data(),
47 __view.size(),
48 nullptr,
49 nullptr) == 0) {
50 __throw_system_error(filesystem::detail::make_windows_error(GetLastError()), "failed to write formatted output");
51 }
52 }
53 # endif // _LIBCPP_HAS_NO_WIDE_CHARACTERS
54
55 _LIBCPP_END_NAMESPACE_STD
56
57 #endif // !_LIBCPP_WIN32API
58