ppforest2 v0.1.0
Projection Pursuit Decision Trees and Random Forests
Loading...
Searching...
No Matches
Color.hpp
Go to the documentation of this file.
1
10#pragma once
11
12#include <string>
13
14#include <fmt/color.h>
15#include <fmt/format.h>
16
17#ifdef _WIN32
18#include <windows.h>
19#else
20#include <unistd.h>
21#endif
22
36 inline bool& color_enabled() {
37 static bool enabled = true;
38 return enabled;
39 }
40
49 inline void init_color(bool no_color) {
50 if (no_color) {
51 color_enabled() = false;
52 return;
53 }
54
55#ifdef _WIN32
56 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
57 DWORD dwMode = 0;
58
59 if (hOut != INVALID_HANDLE_VALUE && GetConsoleMode(hOut, &dwMode)) {
60 SetConsoleMode(hOut, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
61 color_enabled() = true;
62 } else {
63 color_enabled() = false;
64 }
65
66#else
67 color_enabled() = isatty(fileno(stdout));
68#endif
69 }
70
76 inline std::string styled(std::string const& s, fmt::terminal_color c) {
77 if (!color_enabled())
78 return s;
79
80 return fmt::format("\033[{}m{}\033[39m", static_cast<uint8_t>(c), s);
81 }
82
86 inline std::string error(std::string const& s) {
87 return styled(s, fmt::terminal_color::red);
88 }
89
93 inline std::string success(std::string const& s) {
94 return styled(s, fmt::terminal_color::green);
95 }
96
103 inline std::string emphasis(std::string const& s) {
104 if (!color_enabled())
105 return s;
106
107 return fmt::format("\033[1m{}\033[22m", s);
108 }
109
113 inline std::string muted(std::string const& s) {
114 return styled(s, fmt::terminal_color::bright_black);
115 }
116
120 inline std::string info(std::string const& s) {
121 return styled(s, fmt::terminal_color::cyan);
122 }
123
127 inline std::string warning(std::string const& s) {
128 return styled(s, fmt::terminal_color::yellow);
129 }
130}
TTY-aware ANSI colored output utilities.
Definition Color.hpp:31
std::string error(std::string const &s)
Format text in red (for error messages).
Definition Color.hpp:86
void init_color(bool no_color)
Initialize color support based on TTY detection and user preference.
Definition Color.hpp:49
bool & color_enabled()
Global toggle for colored output.
Definition Color.hpp:36
std::string info(std::string const &s)
Format text in cyan (for informational highlights like progress bars).
Definition Color.hpp:120
std::string emphasis(std::string const &s)
Format text in bold (for emphasis / labels).
Definition Color.hpp:103
std::string warning(std::string const &s)
Format text in yellow (for warnings).
Definition Color.hpp:127
std::string styled(std::string const &s, fmt::terminal_color c)
Apply a foreground color with a specific reset (\033[39m) instead of fmt's full reset,...
Definition Color.hpp:76
std::string success(std::string const &s)
Format text in green (for success messages).
Definition Color.hpp:93
std::string muted(std::string const &s)
Format text in dim gray (for hints and secondary info).
Definition Color.hpp:113