Added output channel setting

This commit is contained in:
Bob Polis 2021-12-12 00:09:27 +01:00
parent d9f9688020
commit a93b5d7b0e
2 changed files with 24 additions and 17 deletions

View File

@ -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();
}

View File

@ -4,14 +4,16 @@
#include <unistd.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <iostream>
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();
};