1#include "duckdb/common/printer.hpp"
2#include "duckdb/common/progress_bar/progress_bar.hpp"
3#include "duckdb/common/windows_util.hpp"
4#include "duckdb/common/windows.hpp"
5#include <stdio.h>
6
7#ifndef DUCKDB_DISABLE_PRINT
8#ifdef DUCKDB_WINDOWS
9#include <io.h>
10#else
11#include <sys/ioctl.h>
12#include <stdio.h>
13#include <unistd.h>
14#endif
15#endif
16
17namespace duckdb {
18
19void Printer::RawPrint(OutputStream stream, const string &str) {
20#ifndef DUCKDB_DISABLE_PRINT
21#ifdef DUCKDB_WINDOWS
22 if (IsTerminal(stream)) {
23 // print utf8 to terminal
24 auto unicode = WindowsUtil::UTF8ToMBCS(str.c_str());
25 fprintf(stream == OutputStream::STREAM_STDERR ? stderr : stdout, "%s", unicode.c_str());
26 return;
27 }
28#endif
29 fprintf(stream: stream == OutputStream::STREAM_STDERR ? stderr : stdout, format: "%s", str.c_str());
30#endif
31}
32
33// LCOV_EXCL_START
34void Printer::Print(OutputStream stream, const string &str) {
35 Printer::RawPrint(stream, str);
36 Printer::RawPrint(stream, str: "\n");
37}
38void Printer::Flush(OutputStream stream) {
39#ifndef DUCKDB_DISABLE_PRINT
40 fflush(stream: stream == OutputStream::STREAM_STDERR ? stderr : stdout);
41#endif
42}
43
44void Printer::Print(const string &str) {
45 Printer::Print(stream: OutputStream::STREAM_STDERR, str);
46}
47
48bool Printer::IsTerminal(OutputStream stream) {
49#ifndef DUCKDB_DISABLE_PRINT
50#ifdef DUCKDB_WINDOWS
51 auto stream_handle = stream == OutputStream::STREAM_STDERR ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE;
52 return GetFileType(GetStdHandle(stream_handle)) == FILE_TYPE_CHAR;
53#else
54 return isatty(fd: stream == OutputStream::STREAM_STDERR ? 2 : 1);
55#endif
56#else
57 throw InternalException("IsTerminal called while printing is disabled");
58#endif
59}
60
61idx_t Printer::TerminalWidth() {
62#ifndef DUCKDB_DISABLE_PRINT
63#ifdef DUCKDB_WINDOWS
64 CONSOLE_SCREEN_BUFFER_INFO csbi;
65 int columns, rows;
66
67 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
68 rows = csbi.srWindow.Right - csbi.srWindow.Left + 1;
69 return rows;
70#else
71 struct winsize w;
72 ioctl(fd: 0, TIOCGWINSZ, &w);
73 return w.ws_col;
74#endif
75#else
76 throw InternalException("TerminalWidth called while printing is disabled");
77#endif
78}
79// LCOV_EXCL_STOP
80
81} // namespace duckdb
82