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 #include <cstdlib>
11 #include <print>
12 
13 #if defined(_LIBCPP_WIN32API)
14 #  define WIN32_LEAN_AND_MEAN
15 #  define NOMINMAX
16 #  include <io.h>
17 #  include <windows.h>
18 
19 #  include <__system_error/system_error.h>
20 
21 #  include "filesystem/error.h"
22 #endif
23 
24 _LIBCPP_BEGIN_NAMESPACE_STD
25 
26 #ifdef _WIN32
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
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 #    ifndef _LIBCPP_HAS_NO_EXCEPTIONS
51     // There is no __throw_system_error overload that takes an error code.
52     throw system_error{filesystem::detail::make_windows_error(GetLastError()), "failed to write formatted output"};
53 #    else  // _LIBCPP_HAS_NO_EXCEPTIONS
54     std::abort();
55 #    endif // _LIBCPP_HAS_NO_EXCEPTIONS
56   }
57 }
58 #  endif // _LIBCPP_HAS_NO_WIDE_CHARACTERS
59 
60 #endif // _WIN32
61 
62 _LIBCPP_END_NAMESPACE_STD
63