diff --git a/src/utils.cpp b/src/utils.cpp index 8ff37ca..576cebd 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -7,18 +7,23 @@ using namespace sc; -term::term() { - if (isatty(STDOUT_FILENO)) { - throw_if_min1(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws)); +term::term(int fd) { + if (isatty(fd)) { + throw_if_min1(ioctl(fd, TIOCGWINSZ, &_ws)); + } + switch (fd) { + case STDOUT_FILENO: _out = &std::cout; break; + case STDERR_FILENO: _out = &std::cerr; break; + default: break; } } int term::rows() const { - return ws.ws_row; + return _ws.ws_row; } int term::cols() const { - return ws.ws_col; + return _ws.ws_col; } void term::progress(double cur, double total) const { @@ -31,27 +36,27 @@ void term::progress(double cur, double total) const { int maxsteps = barwidth * 8; int steps = round(cur * maxsteps / total); int perc = round(100 * cur / total); - std::cerr << '\r' << std::setw(3) << perc << "% "; + *_out << '\r' << std::setw(3) << perc << "% "; for (int i = 0; i < steps / 8; ++i) { - std::cerr << bar[7]; + *_out << bar[7]; } if (steps % 8) { - std::cerr << bar[steps % 8 - 1]; + *_out << bar[steps % 8 - 1]; } } void term::hide_cursor() const { - std::cerr << "\x1b[?25l"; + *_out << "\x1b[?25l"; } void term::show_cursor() const { - std::cerr << "\x1b[?25h"; + *_out << "\x1b[?25h"; } -cursor_hider::cursor_hider() { - t.hide_cursor(); +cursor_hider::cursor_hider(int fd) : _t {fd} { + _t.hide_cursor(); } cursor_hider::~cursor_hider() { - t.show_cursor(); + _t.show_cursor(); } diff --git a/src/utils.hpp b/src/utils.hpp index f4c8853..c17b4f4 100644 --- a/src/utils.hpp +++ b/src/utils.hpp @@ -4,14 +4,16 @@ #include #include #include +#include namespace sc { class term { - struct winsize ws; + struct winsize _ws; + std::ostream* _out {nullptr}; public: - term(); + term(int fd); int rows() const; int cols() const; @@ -23,10 +25,10 @@ namespace sc { }; class cursor_hider { - term t; + term _t; public: - cursor_hider(); + cursor_hider(int fd); ~cursor_hider(); };