-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolorterm.hpp
2223 lines (1887 loc) · 86.2 KB
/
colorterm.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
ColorTerm - The Fastest Feature-Rich C++ Terminal Color Cross-Platform Header Only Library for adding vibrant colors to terminal output.
Version: v0.0.1 (Alpha)
Copyright (c) 2024-2025 | Ben Gorlick | https://github.com/bgorlick/colorterm
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
https://www.boost.org/LICENSE_1_0.txt)
High level features include: 8-bit and 24-bit color support, gradient text, custom color and theme management, custom styles, and output formatting.
- Cross platform support for Windows, Linux, and macOS
- Highly optimized color application macros (benchmarked and optimized for performance)
- Over 50 predefined foreground and background colors and effects
- Support for 8bit and 24-bit colors and gradients
- Powerful and simple to use API for applying colors and themes to text
- Global enable/disable color and theme settings to quickly toggle color output on and off
- Easy API Logger class to add colored logs to you application with log Levels (such as [INFO], [DEBUG], [ERROR, etc])
- Custom color and theme management - create, set, insert, inspect, replace, erase, save, load, list, enable, disable, set_default, is_enabled, list_all_theme_maps
- Create colormaps that can be single chars or complex strings
- Create custom styles and apply them
- Built in Config class that saves your configs in memory
- Save themed colormaps to disk and load themes from disk
- Built in Output formatter class to output data to (JSON, XML, YAML, CSV, HTML and plain text) dynamically
- Provides customizable color functions and a custom palette management system.
- Employs compile-time constants for color definitions. It is easily extensible with custom color styles and attributes.
GET STARTED QUICKLY:
As this is a header only library, you can simply include the header file in your project and start using the library immediately.
#include "colorterm.hpp"
Quickly testing the library and seeing some of the features in action:
A file called benchmark.cpp is included in the repository that can be used to test and visibily see some of the features of the library.
To compile it with clang++, run the following command:
clang++ -std=c++17 -O3 -rtlib=compiler-rt -stdlib=libc++ -o benchmark benchmark.cpp \
-I/usr/local/include/c++/v1 \
-L/usr/local/lib \
-lc++ -lc++abi -lunwind -lgcc_s -lgcc -lm -lc -v -ferror-limit=50
Then run the compiled binary to see some of the color features: ./benchmark --verify-all
Some quick usage examples:
std::cout << colorterm::red << "Red text" << colorterm::reset << std::endl;
Logger::info("This is an info message"); // Apply predefined colors
Logger::error("This is an error message"); // Apply predefined colors
OutputFormatter::to_json(std::cout, data); // Output data in JSON format
ThemeManager::create("my_theme"); // Create a new theme
ThemeManager::set("my_theme"); // Set the current theme
ThemeManager::insert("bracket", "[]", "\033[38;5;34m"); // Set brackets to a greenish color
std::cout << colorterm::custom_color("bracket") << "{\n"; // Set the bracket color
std::cout << colorterm::reset << std::endl; // Reset the color
Applying multiple styles to a string:
colorterm::apply_styles(std::cout, "bold", "underline", "purple") << "Bold, underlined, and purple text" << colorterm::reset << std::endl; // Apply multiple styles
Applying all the most common ANSI styles via apply_styles, you can also directly use the main RGB colors like this:
Example: bright_red, bold_red, light_red, red
Apply a full gradient to your text like this:
colorterm::apply_gradient(std::cout, "This is a sentence that will be rendered with a gradient color text", 255, 0, 0, 0, 0, 255) << colorterm::reset << std::endl; // Apply gradient color
Easily apply foreground and background colors using both 8-bit and 24-bit color codes, as well as predefined styles and custom colors.
The library supports both ANSI escape codes for Unix-like systems and appropriate methods for Windows.
Key Features:
1. **Efficient Color Application Macros**: Utilizes macros like APPLY_COLOR_MACRO, APPLY_8BIT_COLOR_MACRO, and APPLY_RGB_COLOR_MACRO for efficient color application with minimal overhead.
2. **Customizable Color Functions**: Provides a flexible and extensible way to define and use custom color functions via the DEFINE_COLOR_FUNCTION macro, allowing for easy creation of new color styles and attributes.
3. **Cross-Platform Support with Platform-Specific Optimizations**: Seamlessly supports Windows, Linux, and macOS with platform-specific code, including Windows API functions for color handling and POSIX functions for determining terminal connections.
4. **Compile-Time Constants for Color Definitions**: Uses compile-time constants for color definitions, combined with templates, ensuring type safety and efficiency.
5. **8-bit and 24-bit Colors**: Functions to apply both 8-bit and 24-bit RGB colors to text and background.
6. **Predefined Colors and Styles**: Includes a variety of predefined colors and text styles, such as bold, italic, and underline.
7. **Custom Colors**: Allows users to define and use their custom colors and styles.
8. **Gradient Text**: Supports rendering text with gradient colors.
9. **Custom Palette Management**: Functions to manage a palette of custom colors, including setting and listing them.
10. **Custom Color Inspections**: Functions to inspect custom colors, themes, colormaps, and color codes.
ThemeManager and ColorMap API:
ThemeManager
1. void create(const std::string& themeName)
Usage: colorterm::create_theme("my_theme");
2. void set(const std::string& themeName)
Usage: colorterm::set_theme("my_theme");
3. void insert(const std::string& name, const std::string& characters, const std::string& colorCode, bool isKey = false, bool isValue = false)
Usage:
colorterm::insert_colormap("bracket", "[]", "\033[38;5;34m");
colorterm::insert_colormap("key", "name", "\033[38;5;208m", true);
colorterm::insert_colormap("value", "Alice", "\033[38;5;75m", false, true);
4. std::string apply(const std::string& text) const
Usage: std::string colored_text = colorterm::apply_theme(text);
5. std::unordered_map<char, std::string> inspect() const
Usage: std::unordered_map<char, std::string> colormap = colorterm::inspect_theme();
6. const std::string* inspect_color(char character) const
Usage: const std::string* color = colorterm::inspect_colormap_color('[');
7. const std::string* inspect_key_color(const std::string& key) const
Usage: const std::string* key_color = colorterm::inspect_key_color("name");
8. const std::string* inspect_value_color(const std::string& value) const
Usage: const std::string* value_color = colorterm::inspect_value_color("Alice");
9. std::vector<std::string> list() const
Usage: std::vector<std::string> themes = colorterm::list_themes();
10. void replace(const std::string& characters, const std::string& colorCode)
Usage: colorterm::replace_colormap("[]", "\033[38;5;40m");
11. void erase(const std::string& characters)
Usage: colorterm::erase_colormap("[]");
12. void save(const std::string& themeName, const std::string& filePath)
Usage: colorterm::save_theme("my_theme", "path/to/file");
13. void load(const std::string& themeName, const std::string& filePath)
Usage: colorterm::load_theme("my_theme", "path/to/file");
14. void set_default()
Usage: colorterm::set_default_theme();
15. void enable_colormap()
Usage: colorterm::enable_colormap();
16. void disable_colormap()
Usage: colorterm::disable_colormap();
17. bool is_enabled() const
Usage: bool enabled = colorterm::is_color_enabled();
18. std::string list_all_theme_maps() const
Usage: std::string all_mappings = colorterm::list_all_theme_maps();
ColorMap
1. void insert(const std::string& name, const std::string& characters, const std::string& colorCode, bool isKey = false, bool isValue = false)
Usage:
colorterm::insert_colormap("bracket", "[]", "\033[38;5;34m");
colorterm::insert_colormap("key", "name", "\033[38;5;208m", true);
colorterm::insert_colormap("value", "Alice", "\033[38;5;75m", false, true);
2. std::string apply(const std::string& text) const
Usage: std::string colored_text = colorterm::apply_theme(text);
3. std::unordered_map<char, std::string> get() const
Usage: std::unordered_map<char, std::string> colormap = colorterm::inspect_theme();
4. std::unordered_map<std::string, std::string> get_key_map() const
Usage: std::unordered_map<std::string, std::string> key_map = colorterm::inspect_key_theme();
5. std::unordered_map<std::string, std::string> get_value_map() const
Usage: std::unordered_map<std::string, std::string> value_map = colorterm::inspect_value_theme();
6. const std::string* inspect_color(char character) const
Usage: const std::string* color = colorterm::inspect_colormap_color('[');
7. const std::string* inspect_key_color(const std::string& key) const
Usage: const std::string* key_color = colorterm::inspect_key_color("name");
8. const std::string* inspect_value_color(const std::string& value) const
Usage: const std::string* value_color = colorterm::inspect_value_color("Alice");
9. void replace(const std::string& characters, const std::string& colorCode)
Usage: colorterm::replace_colormap("[]", "\033[38;5;40m");
10. void erase(const std::string& characters)
Usage: colorterm::erase_colormap("[]");
A few additional API functions:
apply_256bit_color - Apply a 256-bit color to the stream (Windows only)
apply_palette - Apply a custom palette to the stream
replace_color_all_instances - Replace all instances of a color in a string
highlight_pattern - Highlight a pattern in a string
set_custom_color_predefined - Set a custom color using a predefined color
custom_color - Apply a custom color to the stream
remove_custom_color - Remove a custom color
inspect_custom_color - Inspect a custom color
list_custom_colors - List all custom colors
reset_custom_colors - Reset all custom colors
scope_guard - Apply a color for the duration of a scope
colorize_string - Apply a color to a string
apply_output_format - Apply an output format to a stream
set_output_format - Set the output format
get_output_format - Get the current output format
list_output_formats - List all output formats
reset_output_format - Reset the output format
Usage:
Include the `colorterm.hpp` header in your C++ project and link against any necessary libraries. Use the predefined functions or define your own custom colors and styles to enhance the terminal output.
A sample of functionality below does the following:
- Applies predefined colors and styles.
- Applies 8-bit and 24-bit RGB colors.
- Applies a gradient color.
- Applies multiple styles.
- Lists all custom colors.
- Inspect a custom color.
- Output text with a predefined foreground color.
- Output text with a predefined background color.
- Output text with a predefined style.
- Shows gold background with black text and using the fullreset after applying a style.
#include "colorterm.hpp"
int main() {
std::cout << colorterm::red << "Red text" << colorterm::reset << std::endl; // Apply predefined colors
colorterm::set_custom_color("error", "\033[38;5;196m"); // Set a custom color
std::cout << colorterm::custom_color("error") << "Error message" << colorterm::reset << std::endl;
std::cout << colorterm::color<std::ostream>(9) << "8-bit color text" << colorterm::reset << std::endl; // Apply 8-bit RGB color
std::cout << colorterm::color<255, 165, 0> << "24-bit RGB color text" << colorterm::reset << std::endl; // Apply 24-bit RGB color
colorterm::apply_gradient(std::cout, "This is a sentence that will be rendered with a gradient color text", 255, 0, 0, 0, 0, 255) << colorterm::reset << std::endl; // Apply gradient color
colorterm::apply_styles(std::cout, "bold", "underline", "green") << "Bold, underlined, and green text" << colorterm::reset << std::endl; // Apply multiple styles
colorterm::list_custom_colors(); // List all custom colors
colorterm::inspect_custom_color("error"); // Inspect a custom color
std::cout << colorterm::red << "Red text" << colorterm::reset << std::endl; // Output text with a predefined foreground color
std::cout << colorterm::bg_gold << "Gold background" << colorterm::reset << std::endl; // Output text with a predefined background color
std::cout << colorterm::bold << "Bold text" << colorterm::reset << std::endl; // Output text with a predefined style
std::cout << colorterm::bg_gold << colorterm::black << colorterm::bold << "Gold background with black text" << colorterm::fullreset << std::endl; // Gold background with black text and using the fullreset after applying a style.
return 0;
}
*/
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef COLORTERM_HPP_
#define COLORTERM_HPP_
#include <cstdint>
#include <string_view>
#include <vector>
#include <algorithm>
#include <functional>
#include <mutex>
#include <stdexcept>
#include <cstring>
#include <memory>
#include <iostream>
#include <sstream>
#include <fstream>
#include <unordered_map>
// Global flags for color and theme
bool is_global_colored = true;
bool is_global_themed = true;
// Stream-specific flags (not in use right now)
bool is_stream_colored = true;
bool is_stream_themed = true;
#if defined(_WIN32) || defined(_WIN64)
#include <io.h>
#include <windows.h>
#define ISATTY(fd) _isatty(_fileno(fd))
#else
#include <unistd.h>
#define ISATTY(fd) ::isatty(fileno(fd))
#endif
#define CHECK_COLOR_AND_THEME(stream) (is_global_colored && is_global_themed)
#if defined(_WIN32) || defined(_WIN64)
template <typename CharT>
inline std::basic_ostream<CharT>& apply_windows_code(std::basic_ostream<CharT>& stream, WORD attr) __attribute__((always_inline));
template <typename CharT>
inline std::basic_ostream<CharT>& apply_windows_code(std::basic_ostream<CharT>& stream, WORD attr) {
if (colorterm::_internal::is_stream_colored(stream)) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole != INVALID_HANDLE_VALUE) {
SetConsoleTextAttribute(hConsole, attr);
}
}
return stream;
}
#endif
#if defined(_WIN32) || defined(_WIN64)
inline void apply_256bit_color(std::ostream& stream, uint8_t color, bool isForeground = true) {
if (color < 8) {
color += 30;
} else if (color < 16) {
color += 82;
} else {
color = 90 + (color - 16);
}
stream << "\033[" << (isForeground ? "38" : "48") << ";5;" << std::to_string(color) << "m";
}
#endif
namespace colorterm {
namespace _internal {
enum class Palette { SOLARIZED, MONOKAI };
// Helper struct to represent an RGB color
struct RGB {
int r, g, b;
};
struct ColorDefinition {
std::string code;
#if defined(_WIN32) || defined(_WIN64)
WORD win_attr;
#endif
};
inline int colorterm_index() { static int index = std::ios_base::xalloc(); return index; }
inline int colorterm_theme_index() { static int index = std::ios_base::xalloc(); return index; }
} // namespace _internal
template <typename CharT>
inline std::basic_ostream<CharT>& enable(std::basic_ostream<CharT>& stream) {
stream.iword(_internal::colorterm_index()) = 1L;
return stream;
}
template <typename CharT>
inline std::basic_ostream<CharT>& disable(std::basic_ostream<CharT>& stream) {
stream.iword(_internal::colorterm_index()) = 0L;
return stream;
}
inline void enable_global_color() {
is_global_colored = true;
}
inline void disable_global_color() {
is_global_colored = false;
}
inline void enable_global_theme() {
is_global_themed = true;
}
inline void disable_global_theme() {
is_global_themed = false;
}
template <typename CharT>
inline std::basic_ostream<CharT>& enable_stream(std::basic_ostream<CharT>& stream) {
stream.iword(_internal::colorterm_index()) = 1L;
return stream;
}
template <typename CharT>
inline std::basic_ostream<CharT>& disable_stream(std::basic_ostream<CharT>& stream) {
stream.iword(_internal::colorterm_index()) = 0L;
return stream;
}
} // namespace colorterm
namespace colorterm {
namespace _internal {
template <typename StreamType>
inline bool is_stream_colored(StreamType& stream) {
if constexpr (std::is_base_of_v<std::ostream, StreamType>) {
return stream.iword(colorterm_index()) != 0;
}
return false;
}
template <typename StreamType>
inline bool is_stream_themed(StreamType& stream) {
if constexpr (std::is_base_of_v<std::ostream, StreamType>) {
return stream.iword(colorterm_theme_index()) == 1;
}
return false;
}
template <typename WideCharT, typename NarrowCharT>
inline std::basic_string<NarrowCharT> to_string(const std::basic_string<WideCharT>& wstr) {
if (wstr.empty()) return std::basic_string<NarrowCharT>();
size_t size = wcstombs(nullptr, wstr.c_str(), 0);
if (size == static_cast<size_t>(-1)) throw std::runtime_error("Error converting wstring to string");
std::basic_string<NarrowCharT> str(size, '\0');
wcstombs(&str[0], wstr.c_str(), size);
return str;
}
template <typename StreamType>
inline void write_to_streambuf(StreamType& stream, const std::string& str) {
if constexpr (std::is_same_v<StreamType, std::stringstream> || std::is_same_v<StreamType, std::ofstream>) {
stream.rdbuf()->sputn(str.data(), str.size());
} else {
stream.rdbuf()->sputn(str.c_str(), str.size());
}
}
template <typename StreamType>
inline StreamType& operator<<(StreamType& stream, const std::wstring& wstr) {
if constexpr (std::is_same_v<StreamType, std::basic_ostream<wchar_t>>) {
stream.write(wstr.data(), wstr.size());
} else {
stream << _internal::to_string<wchar_t, typename StreamType::char_type>(wstr);
}
return stream;
}
template <typename StreamType>
inline bool is_atty(const StreamType& stream) {
if constexpr (std::is_same_v<StreamType, std::basic_ostream<char>>) {
return (&stream == &std::cout) ? ISATTY(stdout) : ((&stream == &std::cerr || &stream == &std::clog) ? ISATTY(stderr) : false);
} else if constexpr (std::is_same_v<StreamType, std::basic_ostream<wchar_t>>) {
return (&stream == &std::wcout) ? ISATTY(stdout) : ((&stream == &std::wcerr || &stream == &std::wclog) ? ISATTY(stderr) : false);
} else {
return false;
}
}
template <typename StreamType>
inline StreamType& apply_code(StreamType& stream, std::string_view code) {
if (CHECK_COLOR_AND_THEME(stream)) {
if constexpr (std::is_same_v<StreamType, std::basic_ostream<wchar_t>>) {
std::wstring wcode(code.begin(), code.end());
stream.rdbuf()->sputn(wcode.data(), wcode.size());
} else if constexpr (std::is_same_v<StreamType, std::stringstream> || std::is_same_v<StreamType, std::ofstream>) {
write_to_streambuf(stream, std::string(code));
} else {
stream.rdbuf()->sputn(code.data(), code.size());
}
}
return stream;
}
} // namespace _internal
} // namespace colorterm
namespace colorterm {
namespace _internal {
struct CustomColor {
std::string name;
std::function<void(std::ostream&)> apply;
};
struct PaletteRGB { uint8_t r, g, b; };
struct CustomPalette {
std::unordered_map<std::string, PaletteRGB> colors;
};
inline std::unordered_map<std::string, std::string>& predefined_colors() {
static std::unordered_map<std::string, std::string> colors;
return colors;
}
inline std::unordered_map<std::string, std::string>& custom_defined_colors() {
static std::unordered_map<std::string, std::string> colors;
return colors;
}
} // namespace _internal
} // namespace colorterm
#if defined(_WIN32) || defined(_WIN64)
#define DEFINE_COLOR_FUNCTION(NAME, CODE, ...) \
inline const colorterm::_internal::ColorDefinition NAME##_def = { CODE, __VA_ARGS__ }; \
template <typename CharT> \
inline std::basic_ostream<CharT>& NAME(std::basic_ostream<CharT>& stream) __attribute__((always_inline)); \
template <typename CharT> \
inline std::basic_ostream<CharT>& NAME(std::basic_ostream<CharT>& stream) { \
colorterm::_internal::apply_windows_code(stream, NAME##_def.win_attr); return stream; } \
inline void init_##NAME() { colorterm::_internal::predefined_colors()[#NAME] = CODE; } \
static const bool NAME##_init = (init_##NAME(), true)
#else
#define DEFINE_COLOR_FUNCTION(NAME, CODE, ...) \
inline const colorterm::_internal::ColorDefinition NAME##_def = { CODE }; \
template <typename CharT> \
inline std::basic_ostream<CharT>& NAME(std::basic_ostream<CharT>& stream) __attribute__((always_inline)); \
template <typename CharT> \
inline std::basic_ostream<CharT>& NAME(std::basic_ostream<CharT>& stream) { \
colorterm::_internal::apply_code(stream, NAME##_def.code); return stream; } \
inline void init_##NAME() { colorterm::_internal::predefined_colors()[#NAME] = CODE; } \
static const bool NAME##_init = (init_##NAME(), true)
#endif
// High Performance Color Application Macros
#define APPLY_COLOR_MACRO(stream, r, g, b, type) do { \
if (CHECK_COLOR_AND_THEME(stream)) { \
char buf[19]; char* p = buf; \
*p++ = '\033'; *p++ = '['; *p++ = type; *p++ = '8'; *p++ = ';'; \
*p++ = '2'; *p++ = ';'; *p++ = '0' + (r / 100); *p++ = '0' + ((r / 10) % 10); *p++ = '0' + (r % 10); \
*p++ = ';'; *p++ = '0' + (g / 100); *p++ = '0' + ((g / 10) % 10); *p++ = '0' + (g % 10); \
*p++ = ';'; *p++ = '0' + (b / 100); *p++ = '0' + ((b / 10) % 10); *p++ = '0' + (b % 10); \
*p++ = 'm'; stream.write(buf, p - buf); } \
} while (0)
#define APPLY_8BIT_COLOR_MACRO(stream, value, type) \
do { \
if (CHECK_COLOR_AND_THEME(stream)) { \
char buf[11] = "\033["; \
strcat(buf, type); \
strcat(buf, "8;5;"); \
char* p = buf + strlen(buf); \
uint8_t val = value; \
if (val >= 100) { *p++ = '0' + (val / 100); val %= 100; } \
else { *p++ = '0'; } \
if (val >= 10) { *p++ = '0' + (val / 10); val %= 10; } \
else { *p++ = '0'; } \
*p++ = '0' + val; \
*p++ = 'm'; \
stream.write(buf, p - buf); \
} \
} while (0)
#define APPLY_RGB_COLOR_MACRO(stream, r, g, b, type) do { \
if (CHECK_COLOR_AND_THEME(stream)) { \
char buf[19]; char* p = buf; *p++ = '\033'; *p++ = '['; *p++ = type; *p++ = '8'; *p++ = ';'; \
*p++ = '2'; *p++ = ';'; *p++ = '0' + (r / 100); int r_mod = r % 100; *p++ = '0' + (r_mod / 10); r_mod %= 10; *p++ = '0' + r_mod; \
*p++ = ';'; *p++ = '0' + (g / 100); int g_mod = g % 100; *p++ = '0' + (g_mod / 10); g_mod %= 10; *p++ = '0' + g_mod; \
*p++ = ';'; *p++ = '0' + (b / 100); int b_mod = b % 100; *p++ = '0' + (b_mod / 10); b_mod %= 10; *p++ = '0' + b_mod; *p++ = 'm'; \
stream.write(buf, p - buf); \
} \
} while (0)
#define APPLY_RGB_COLOR_MACRO_TO_STRING(stream, r, g, b, type) do { \
if (CHECK_COLOR_AND_THEME(stream)) { \
char buf[19]; char* p = buf; *p++ = '\033'; *p++ = '['; *p++ = type; *p++ = '8'; *p++ = ';'; \
int r_temp = r; int g_temp = g; int b_temp = b; \
*p++ = '2'; *p++ = ';'; *p++ = '0' + (r_temp / 100); r_temp %= 100; *p++ = '0' + (r_temp / 10); r_temp %= 10; *p++ = '0' + r_temp; \
*p++ = ';'; *p++ = '0' + (g_temp / 100); g_temp %= 100; *p++ = '0' + (g_temp / 10); g_temp %= 10; *p++ = '0' + g_temp; \
*p++ = ';'; *p++ = '0' + (b_temp / 100); b_temp %= 100; *p++ = '0' + (b_temp / 10); b_temp %= 10; *p++ = '0' + b_temp; *p++ = 'm'; \
stream = std::string(buf, p - buf); } \
} while (0)
namespace colorterm {
// Apply 24-bit RGB color
template <typename CharT>
inline void apply_color(std::ostream& stream, int r, int g, int b) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '3');
}
// Apply 24-bit RGB color
inline std::basic_ostream<char>& apply_color(std::basic_ostream<char>& stream, uint8_t r, uint8_t g, uint8_t b) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '3');
return stream;
}
// Apply 24-bit RGB background color
inline std::basic_ostream<char>& apply_bg_color(std::basic_ostream<char>& stream, uint8_t r, uint8_t g, uint8_t b) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '4');
return stream;
}
// Overload to apply a color using a single integer color code
inline std::ostream& apply_color(std::ostream& stream, int color_code) {
APPLY_8BIT_COLOR_MACRO(stream, color_code, "3");
return stream;
}
// Overload to apply a background color using a single integer color code
inline std::ostream& apply_bg_color(std::ostream& stream, int color_code) {
APPLY_8BIT_COLOR_MACRO(stream, color_code, "4");
return stream;
}
// Define the get_custom_palette function
inline _internal::CustomPalette& get_custom_palette() {
static _internal::CustomPalette palette;
// Define your custom colors here
palette.colors["red"] = {255, 0, 0};
palette.colors["green"] = {0, 255, 0};
palette.colors["blue"] = {0, 0, 255};
palette.colors["yellow"] = {255, 255, 0};
palette.colors["magenta"] = {255, 0, 255};
return palette;
}
// Apply custom background color by name
inline std::basic_ostream<char>& custom_bg_color(std::basic_ostream<char>& stream, const std::string& name) {
auto& palette = get_custom_palette().colors;
auto it = palette.find(name);
if (it != palette.end()) {
const colorterm::_internal::PaletteRGB& color = it->second;
return apply_bg_color(stream, color.r, color.g, color.b);
}
return stream;
}
// Set 24-bit color
template <typename CharT>
inline std::basic_ostream<CharT>& set_color(std::basic_ostream<CharT>& stream, uint8_t r, uint8_t g, uint8_t b) {
#if defined(_WIN32) || defined(_WIN64)
if (colorterm::_internal::is_stream_colored(stream)) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole != INVALID_HANDLE_VALUE) {
WORD color = 0;
if (r > 128) color |= FOREGROUND_RED;
if (g > 128) color |= FOREGROUND_GREEN;
if (b > 128) color |= FOREGROUND_BLUE;
if (r > 128 || g > 128 || b > 128) color |= FOREGROUND_INTENSITY;
_internal::set_color(hConsole, color);
}
}
#else
if (colorterm::_internal::is_stream_colored(stream)) {
stream << "\033[38;2;" << static_cast<int>(r) << ';' << static_cast<int>(g) << ';' << static_cast<int>(b) << 'm';
}
#endif
return stream;
}
// Apply 24-bit RGB color
inline std::basic_ostream<char>& apply_rgb_color(std::basic_ostream<char>& stream, uint8_t r, uint8_t g, uint8_t b) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '3');
return stream;
}
// Apply 24-bit RGB color to a string
inline void apply_rgb_color(std::string& stream, uint8_t r, uint8_t g, uint8_t b) {
APPLY_RGB_COLOR_MACRO_TO_STRING(stream, r, g, b, '3');
}
// 8-bit color functions
template <typename T, typename CharT>
inline std::basic_ostream<CharT>& color(std::basic_ostream<CharT>& stream, T code) {
APPLY_8BIT_COLOR_MACRO(stream, static_cast<uint8_t>(code), "3");
return stream;
}
// Template function to apply 24-bit RGB color
template <uint8_t r, uint8_t g, uint8_t b, typename CharT>
inline std::basic_ostream<CharT>& color(std::basic_ostream<CharT>& stream) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '3');
return stream;
}
// Apply 24-bit RGB color using template
template <uint8_t r, uint8_t g, uint8_t b, typename CharT = char>
inline std::basic_ostream<CharT>& apply_color(std::basic_ostream<CharT>& stream) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '3');
return stream;
}
// Apply 24-bit RGB background color using template
template <uint8_t r, uint8_t g, uint8_t b, typename CharT = char>
inline std::basic_ostream<CharT>& apply_bg_color(std::basic_ostream<CharT>& stream) {
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '4');
return stream;
}
// Apply custom color by name and return stream
inline std::ostream& apply_custom_color(std::ostream& stream, const std::string& name) {
auto& colors = _internal::custom_defined_colors();
auto it = colors.find(name);
if (it != colors.end()) {
_internal::apply_code(stream, it->second);
} else {
std::cerr << "Error: Custom color '" << name << "' not found." << std::endl;
}
return stream;
}
// Apply custom background color by name and return stream
inline std::ostream& apply_custom_bg_color(std::ostream& stream, const std::string& name) {
auto& colors = _internal::custom_defined_colors();
auto it = colors.find(name);
if (it != colors.end()) {
_internal::apply_code(stream, it->second);
} else {
std::cerr << "Error: Custom background color '" << name << "' not found." << std::endl;
}
return stream;
}
} // namespace colorterm
namespace colorterm {
// Set 24-bit background color
template <typename CharT>
inline std::basic_ostream<CharT>& set_background_color(std::basic_ostream<CharT>& stream, uint8_t r, uint8_t g, uint8_t b) {
#if defined(_WIN32) || defined(_WIN64)
if (CHECK_COLOR_AND_THEME(stream)) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole != INVALID_HANDLE_VALUE) {
WORD color = 0;
if (r > 128) color |= BACKGROUND_RED;
if (g > 128) color |= BACKGROUND_GREEN;
if (b > 128) color |= BACKGROUND_BLUE;
if (r > 128 || g > 128 || b > 128) color |= BACKGROUND_INTENSITY;
colorterm::_internal::set_color(hConsole, color);
}
}
#else
if (CHECK_COLOR_AND_THEME(stream)) {
stream << "\033[48;2;" << static_cast<int>(r) << ';' << static_cast<int>(g) << ';' << static_cast<int>(b) << 'm';
}
#endif
return stream;
}
// Apply 24-bit RGB background color to a string
inline void apply_rgb_background_color(std::string& stream, uint8_t r, uint8_t g, uint8_t b) {
APPLY_RGB_COLOR_MACRO_TO_STRING(stream, r, g, b, '4');
}
// Apply 24-bit RGB background color
inline std::basic_ostream<char>& apply_rgb_background_color(std::basic_ostream<char>& stream, uint8_t r, uint8_t g, uint8_t b) {
if (CHECK_COLOR_AND_THEME(stream)) {
uint8_t r_mod = r;
uint8_t g_mod = g;
uint8_t b_mod = b;
APPLY_RGB_COLOR_MACRO(stream, r_mod, g_mod, b_mod, '4');
}
return stream;
}
// Template function to apply 24-bit RGB background color
template <uint8_t r, uint8_t g, uint8_t b, typename CharT>
inline std::basic_ostream<CharT>& bg_color(std::basic_ostream<CharT>& stream) {
if (CHECK_COLOR_AND_THEME(stream)) {
uint8_t r_mod = r;
uint8_t g_mod = g;
uint8_t b_mod = b;
APPLY_RGB_COLOR_MACRO(stream, r_mod, g_mod, b_mod, '4');
}
return stream;
}
// 8-bit background color functions
template <uint8_t code, typename CharT>
inline std::basic_ostream<CharT>& bg_color(std::basic_ostream<CharT>& stream) {
APPLY_8BIT_COLOR_MACRO(stream, code, "4");
return stream;
}
} // namespace colorterm
namespace colorterm {
// Helper function for color interpolation
inline int interpolate(int start, int end, float ratio) {return start + static_cast<int>((end - start) * ratio);}
// Template function to apply a gradient with start and end colors specified by colorterm::_internal::RGB
template <typename CharT>
inline void apply_gradient(std::basic_ostream<CharT>& stream, colorterm::_internal::RGB start_col, colorterm::_internal::RGB end_col, const std::string& text) {
if (CHECK_COLOR_AND_THEME(stream)) {
size_t length = text.length();
for (size_t i = 0; i < length; ++i) {
float ratio = static_cast<float>(i) / (length - 1);
int r = interpolate(start_col.r, end_col.r, ratio);
int g = interpolate(start_col.g, end_col.g, ratio);
int b = interpolate(start_col.b, end_col.b, ratio);
apply_color(stream, r, g, b);
stream << text[i];
}
stream << "\033[0m"; // Reset color
} else {
stream << text;
}
}
// Template function to apply a gradient to a string and return the result with colorterm::_internal::RGB
template <typename CharT>
inline std::string apply_gradient(const std::string& text, colorterm::_internal::RGB start_col, colorterm::_internal::RGB end_col) {
std::ostringstream oss;
if (CHECK_COLOR_AND_THEME(oss)) {
size_t length = text.length();
for (size_t i = 0; i < length; ++i) {
double ratio = static_cast<double>(i) / (length - 1);
uint8_t r = static_cast<uint8_t>(start_col.r + ratio * (end_col.r - start_col.r));
uint8_t g = static_cast<uint8_t>(start_col.g + ratio * (end_col.g - start_col.g));
uint8_t b = static_cast<uint8_t>(start_col.b + ratio * (end_col.b - start_col.b));
APPLY_RGB_COLOR_MACRO(oss, r, g, b, '3');
oss << text[i];
}
oss << "\033[0m"; // Reset color
} else {
oss << text;
}
return oss.str();
}
// Custom overload to apply a gradient using start and end colors specified by colorterm::_internal::RGB and return a std::string
inline std::string apply_gradient(const std::string& text, colorterm::_internal::RGB start_col, colorterm::_internal::RGB end_col) {
std::ostringstream oss;
if (CHECK_COLOR_AND_THEME(oss)) {
size_t length = text.length();
for (size_t i = 0; i < length; ++i) {
double ratio = static_cast<double>(i) / (length - 1);
uint8_t r = static_cast<uint8_t>(start_col.r + ratio * (end_col.r - start_col.r));
uint8_t g = static_cast<uint8_t>(start_col.g + ratio * (end_col.g - start_col.g));
uint8_t b = static_cast<uint8_t>(start_col.b + ratio * (end_col.b - start_col.b));
APPLY_RGB_COLOR_MACRO(oss, r, g, b, '3');
oss << text[i];
}
oss << "\033[0m"; // Reset color
} else {
oss << text;
}
return oss.str();
}
// Overload to apply a gradient using start and end colors specified by RGB values
inline std::ostream& apply_gradient(std::ostream& stream, const std::string& text, int start_r, int start_g, int start_b, int end_r, int end_g, int end_b) {
colorterm::_internal::RGB start_col = {start_r, start_g, start_b};
colorterm::_internal::RGB end_col = {end_r, end_g, end_b};
apply_gradient(stream, start_col, end_col, text);
return stream;
}
// Overload to apply a gradient with start and end colors specified by colorterm::_internal::RGB and intensity
inline std::ostream& apply_gradient(std::ostream& stream, colorterm::_internal::RGB start_col, colorterm::_internal::RGB end_col, float intensity) {
if (CHECK_COLOR_AND_THEME(stream)) {
int r = interpolate(start_col.r, end_col.r, intensity);
int g = interpolate(start_col.g, end_col.g, intensity);
int b = interpolate(start_col.b, end_col.b, intensity);
APPLY_RGB_COLOR_MACRO(stream, r, g, b, '3');
}
return stream;
}
// Overload to apply a gradient with start and end colors specified by RGB values and intensity
inline void apply_gradient(std::ostream& stream, int start_r, int start_g, int start_b, int end_r, int end_g, int end_b, float intensity) {
colorterm::_internal::RGB start_col = {start_r, start_g, start_b};
colorterm::_internal::RGB end_col = {end_r, end_g, end_b};
if (CHECK_COLOR_AND_THEME(stream)) {
apply_gradient(stream, start_col, end_col, intensity);
} else {
// Apply default handling if color is not enabled
}
}
// Overload to apply a gradient using start and end colors specified by colorterm::_internal::RGB and return a std::string for integral types
inline std::string apply_gradient(const std::string& text, int start_r, int start_g, int start_b, int end_r, int end_g, int end_b) {
colorterm::_internal::RGB start_col = {start_r, start_g, start_b};
colorterm::_internal::RGB end_col = {end_r, end_g, end_b};
return apply_gradient(text, start_col, end_col);
}
// Overload to apply a gradient without predefined text for themes
inline void apply_gradient(std::ostream& stream, colorterm::_internal::RGB start_col, colorterm::_internal::RGB end_col) {
if (CHECK_COLOR_AND_THEME(stream)) {
for (int i = 0; i < 10; ++i) { // applying gradient to 10 spaces
float ratio = static_cast<float>(i) / 9; // 9 because we want to divide the range into 10 parts
int r = interpolate(start_col.r, end_col.r, ratio);
int g = interpolate(start_col.g, end_col.g, ratio);
int b = interpolate(start_col.b, end_col.b, ratio);
apply_color(stream, r, g, b);
stream << " ";
}
stream << "\033[0m"; // Reset color
}
}
} // namespace colorterm
namespace colorterm {
DEFINE_COLOR_FUNCTION(black, "\033[30m", 0);
DEFINE_COLOR_FUNCTION(red, "\033[31m", FOREGROUND_RED);
DEFINE_COLOR_FUNCTION(green, "\033[32m", FOREGROUND_GREEN);
DEFINE_COLOR_FUNCTION(yellow, "\033[33m", FOREGROUND_RED | FOREGROUND_GREEN);
DEFINE_COLOR_FUNCTION(blue, "\033[34m", FOREGROUND_BLUE);
DEFINE_COLOR_FUNCTION(magenta, "\033[35m", FOREGROUND_RED | FOREGROUND_BLUE);
DEFINE_COLOR_FUNCTION(cyan, "\033[36m", FOREGROUND_GREEN | FOREGROUND_BLUE);
DEFINE_COLOR_FUNCTION(white, "\033[37m", FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
DEFINE_COLOR_FUNCTION(bg_black, "\033[40m", 0);
DEFINE_COLOR_FUNCTION(bg_red, "\033[41m", BACKGROUND_RED);
DEFINE_COLOR_FUNCTION(bg_green, "\033[42m", BACKGROUND_GREEN);
DEFINE_COLOR_FUNCTION(bg_yellow, "\033[43m", BACKGROUND_RED | BACKGROUND_GREEN);
DEFINE_COLOR_FUNCTION(bg_blue, "\033[44m", BACKGROUND_BLUE);
DEFINE_COLOR_FUNCTION(bg_magenta, "\033[45m", BACKGROUND_RED | BACKGROUND_BLUE);
DEFINE_COLOR_FUNCTION(bg_cyan, "\033[46m", BACKGROUND_GREEN | BACKGROUND_BLUE);
DEFINE_COLOR_FUNCTION(bg_white, "\033[47m", BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);
DEFINE_COLOR_FUNCTION(reset, "\033[0m", 0);
}
namespace colorterm {
// LogLevel enum definition
enum class LogLevel { debug, info, warn, error, fatal, trace, unknown };
// Configuration storage class
class Config {
public:
using CustomStringMap = std::unordered_map<std::string, std::string>;
using CustomLogMap = std::unordered_map<LogLevel, CustomStringMap>;
using ColorFunctionMap = std::unordered_map<LogLevel, _internal::ColorDefinition>;
static CustomLogMap& UserConfig_Logger() {
static CustomLogMap config;
return config;
}
static ColorFunctionMap& UserColorConfig_Logger() {
static ColorFunctionMap colorConfig;
return colorConfig;
}
static std::string logLevelToString(LogLevel level) {
auto& userConfig = UserConfig_Logger();
static std::unordered_map<LogLevel, std::string> defaultMessages;
if (defaultMessages.size() == 0) {
defaultMessages[LogLevel::debug] = "DEBUG";
defaultMessages[LogLevel::info] = "INFO";
defaultMessages[LogLevel::warn] = "WARNING";
defaultMessages[LogLevel::error] = "ERROR";
defaultMessages[LogLevel::fatal] = "FATAL";
defaultMessages[LogLevel::trace] = "TRACE";
defaultMessages[LogLevel::unknown] = "UNKNOWN";
}
auto it = userConfig.find(level);
if (it != userConfig.end()) {
auto subIt = it->second.find("message");
if (subIt != it->second.end()) {
return subIt->second;
}
}
return defaultMessages[level];
}
static std::ostream& applyLogLevelColor(std::ostream& os, LogLevel level) {
auto& userConfig = UserColorConfig_Logger();
static std::unordered_map<LogLevel, _internal::ColorDefinition> defaultColors;
if (defaultColors.size() == 0) {
defaultColors[LogLevel::debug] = colorterm::cyan_def;
defaultColors[LogLevel::info] = colorterm::green_def;
defaultColors[LogLevel::warn] = colorterm::yellow_def;
defaultColors[LogLevel::error] = colorterm::red_def;
defaultColors[LogLevel::fatal] = colorterm::magenta_def;
defaultColors[LogLevel::trace] = colorterm::blue_def;
defaultColors[LogLevel::unknown] = colorterm::white_def;
}
if (CHECK_COLOR_AND_THEME(os)) {
auto it = userConfig.find(level);
if (it != userConfig.end() && !it->second.code.empty()) {
return colorterm::_internal::apply_code(os, it->second.code);
}
}
return colorterm::_internal::apply_code(os, defaultColors[level].code);
}
static void setLogLevelColor(LogLevel level, _internal::ColorDefinition colorDef) {
UserColorConfig_Logger()[level] = colorDef;
}
static void setLogLevelMessage(LogLevel level, const std::string& message) {
UserConfig_Logger()[level]["message"] = message;
}
static void setColorFullMessage(bool colorFull) {
auto& userConfig = UserConfig_Logger();
for (auto level : {LogLevel::debug, LogLevel::info, LogLevel::warn, LogLevel::error, LogLevel::fatal, LogLevel::trace, LogLevel::unknown}) {
userConfig[level]["colorFull"] = colorFull ? "true" : "false";
}
}
};
} // namespace colorterm