Gracefully degrade to 216 colors if no true colors

This commit is contained in:
Bob Polis 2024-01-29 13:38:41 +01:00
parent c7dde6716f
commit 971211eb41

View File

@ -1,7 +1,8 @@
#include "iomanip.hpp"
#include <unistd.h> #include <unistd.h>
#include <cmath> #include <cmath>
#include <cstdlib> #include <cstdlib>
#include "iomanip.hpp"
#include "utils.hpp"
using namespace sc::io; using namespace sc::io;
@ -248,12 +249,25 @@ sc::io::truecolorf::truecolorf(int r, int g, int b) : _r {r}, _g {g}, _b {b} {}
sc::io::truecolorb::truecolorb(int r, int g, int b) : _r {r}, _g {g}, _b {b} {} sc::io::truecolorb::truecolorb(int r, int g, int b) : _r {r}, _g {g}, _b {b} {}
// truecolor to palette color (216-color)
static inline int t2p(int val) {
return round(5 * val / 255.0);
}
std::ostream& sc::io::operator<<(std::ostream& out, const truecolorf& obj) { std::ostream& sc::io::operator<<(std::ostream& out, const truecolorf& obj) {
if (sc::term::has_truecolor()) {
out << "\x1b[38;2;" << obj._r << ';' << obj._g << ';' << obj._b << 'm'; out << "\x1b[38;2;" << obj._r << ';' << obj._g << ';' << obj._b << 'm';
} else {
out << sc::io::rgbf(t2p(obj._r), t2p(obj._g), t2p(obj._b));
}
return out; return out;
} }
std::ostream& sc::io::operator<<(std::ostream& out, const truecolorb& obj) { std::ostream& sc::io::operator<<(std::ostream& out, const truecolorb& obj) {
if (sc::term::has_truecolor()) {
out << "\x1b[48;2;" << obj._r << ';' << obj._g << ';' << obj._b << 'm'; out << "\x1b[48;2;" << obj._r << ';' << obj._g << ';' << obj._b << 'm';
} else {
out << sc::io::rgbb(t2p(obj._r), t2p(obj._g), t2p(obj._b));
}
return out; return out;
} }