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#include <cstdlib>
12#include <print>
13
14#include <__system_error/system_error.h>
15
16#include "filesystem/error.h"
17
18#if defined(_LIBCPP_WIN32API)
19# define WIN32_LEAN_AND_MEAN
20# define NOMINMAX
21# include <io.h>
22# include <windows.h>
23#elif __has_include(<unistd.h>)
24# include <unistd.h>
25#endif
26
27_LIBCPP_BEGIN_NAMESPACE_STD
28
29#if defined(_LIBCPP_WIN32API)
30
31_LIBCPP_EXPORTED_FROM_ABI bool __is_windows_terminal(FILE* __stream) {
32 // Note the Standard does this in one call, but it's unclear whether
33 // an invalid handle is allowed when calling GetConsoleMode.
34 //
35 // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=msvc-170
36 // https://learn.microsoft.com/en-us/windows/console/getconsolemode
37 intptr_t __handle = _get_osfhandle(fileno(__stream));
38 if (__handle == -1)
39 return false;
40
41 unsigned long __mode;
42 return GetConsoleMode(reinterpret_cast<void*>(__handle), &__mode);
43}
44
45# ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
46_LIBCPP_EXPORTED_FROM_ABI void
47__write_to_windows_console([[maybe_unused]] FILE* __stream, [[maybe_unused]] wstring_view __view) {
48 // https://learn.microsoft.com/en-us/windows/console/writeconsole
49 if (WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fileno(__stream))), // clang-format aid
50 __view.data(),
51 __view.size(),
52 nullptr,
53 nullptr) == 0) {
54 __throw_system_error(filesystem::detail::make_windows_error(GetLastError()), "failed to write formatted output");
55 }
56}
57# endif // _LIBCPP_HAS_NO_WIDE_CHARACTERS
58
59#elif __has_include(<unistd.h>) // !_LIBCPP_WIN32API
60
61_LIBCPP_EXPORTED_FROM_ABI bool __is_posix_terminal(FILE* __stream) { return isatty(fileno(__stream)); }
62#endif
63
64_LIBCPP_END_NAMESPACE_STD
65

source code of libcxx/src/print.cpp