Skip to content

Commit

Permalink
Merge pull request #52 from Ttibsi/hex-codes
Browse files Browse the repository at this point in the history
hex values to Color objects
  • Loading branch information
Ttibsi authored Aug 20, 2024
2 parents 1d42382 + db0b8ae commit f16bbf0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
33 changes: 33 additions & 0 deletions rawterm/color.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,44 @@
#include "color.h"

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

#include "core.h"
#include "cursor.h"

namespace rawterm {
Color::Color(const std::string& hex) {
if (hex.at(0) != '#') {
throw std::invalid_argument("Value passed not valid hex code");
}

if (hex.length() != 7) {
throw std::invalid_argument("Hex code must be 7 characters long including the #");
}

std::istringstream ss(hex.substr(1, 2));
ss >> std::hex >> red;

ss.clear();
ss.str(hex.substr(3, 2));
ss >> std::hex >> green;

ss.clear();
ss.str(hex.substr(5, 2));
ss >> std::hex >> blue;
}

const std::string Color::to_hex() {
std::ostringstream ss;
ss << "#" << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << red
<< std::setw(2) << std::setfill('0') << green << std::setw(2) << std::setfill('0')
<< blue;

return ss.str();
}

[[nodiscard]] std::string set_foreground(const std::string& s, const Color& color) {
return "\x1B[38;2;" + std::to_string(color.red) + ';' + std::to_string(color.green) + ';' +
std::to_string(color.blue) + 'm' + s + "\x1B[39m";
Expand Down Expand Up @@ -43,4 +75,5 @@ namespace rawterm {

rawterm::Cursor::load_cursor_position();
}

} // namespace rawterm
3 changes: 3 additions & 0 deletions rawterm/color.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ namespace rawterm {

Color() : red(0), green(0), blue(0) {}
Color(int x, int y, int z) : red(x), green(y), blue(z) {}
Color(const std::string&);

const std::string to_hex();

friend std::ostream& operator<<(std::ostream& os, const Color& c) {
return os << std::to_string(c.red) + ";" + std::to_string(c.green) + ";" +
Expand Down

0 comments on commit f16bbf0

Please sign in to comment.