/* */ #ifndef D_COLORIZED_STREAM_H #define D_COLORIZED_STREAM_H #include #include #include #include "config.h" namespace aria2 { namespace colors { class Color { private: std::string str_; public: explicit Color(const char* str) : str_(std::string("\033[") + str + "m") {} const std::string& str() const { return str_; } }; extern const Color black; extern const Color red; extern const Color green; extern const Color yellow; extern const Color blue; extern const Color magenta; extern const Color cyan; extern const Color white; extern const Color lightred; extern const Color lightgreen; extern const Color lightyellow; extern const Color lightblue; extern const Color lightmagenta; extern const Color lightcyan; extern const Color lightwhite; extern const Color clear; } // namespace colors typedef std::char_traits traits_t; class ColorizedStreamBuf : public std::basic_streambuf { enum part_t { eColor, eString }; typedef std::pair elem_t; typedef std::deque elems_t; elems_t elems; public: ColorizedStreamBuf() { elems.push_back(std::make_pair(eString, "")); } void setColor(const colors::Color& color) { elems.push_back(std::make_pair(eColor, color.str())); elems.push_back(std::make_pair(eString, "")); } traits_t::int_type overflow(traits_t::int_type c) CXX11_OVERRIDE { elems.back().second.push_back((char)c); return std::char_traits::not_eof(c); } void append(const std::string& str) { elems.back().second += str; } void append(const char* str) { elems.back().second += str; } std::string str(bool color) const; std::string str(bool color, size_t max) const; }; class ColorizedStream : public std::basic_ostream { public: ColorizedStream() : std::basic_ios(&buf), std::basic_ostream(&buf) { init(&buf); } void setColor(const colors::Color& color) { buf.setColor(color); } void append(const std::string& str) { buf.append(str); } void append(const char* str) { buf.append(str); } std::string str(bool colors) const { return buf.str(colors); } std::string str(bool colors, size_t max) const { return buf.str(colors, max); } private: ColorizedStreamBuf buf; }; inline ColorizedStream& operator<<(ColorizedStream& stream, const std::string& str) { stream.append(str); return stream; } inline ColorizedStream& operator<<(ColorizedStream& stream, const char* str) { stream.append(str); return stream; } inline ColorizedStream& operator<<(ColorizedStream& stream, const colors::Color& c) { stream.setColor(c); return stream; } } // namespace aria2 #endif // D_COLORIZED_STREAM_H