Files
indicators/include/progress/bar.hpp

69 lines
1.5 KiB
C++
Raw Normal View History

2019-12-03 09:54:50 -06:00
#pragma once
#include <iostream>
#include <string>
#include <atomic>
#include <mutex>
#include <thread>
2019-12-03 11:54:06 -06:00
class ProgressBar {
std::string _name{""};
float _progress{0.0};
2019-12-03 10:46:25 -06:00
size_t _bar_width{80};
2019-12-03 16:53:17 -06:00
std::string _start{"[ "};
std::string _fill{""};
std::string _lead{""};
std::string _negative_space{"-"};
std::string _end{" ]"};
2019-12-03 09:54:50 -06:00
std::mutex _mutex;
void hide_cursor() {
std::cout << "\e[?25l";
}
void show_cursor() {
std::cout << "\e[?25h";
}
2019-12-03 09:54:50 -06:00
public:
2019-12-03 16:53:17 -06:00
ProgressBar& start_with(const std::string& start) {
_start = start;
return *this;
}
ProgressBar& fill_with(const std::string& fill) {
_fill = fill;
return *this;
}
ProgressBar& lead_with(const std::string& lead) {
_lead = lead;
return *this;
}
ProgressBar& negative_space(const std::string& negative_space) {
_negative_space = negative_space;
return *this;
}
ProgressBar& end_with(const std::string& end) {
_end = end;
return *this;
}
2019-12-03 11:54:06 -06:00
void increment(float value) {
std::unique_lock<std::mutex> lock{_mutex};
2019-12-03 10:46:25 -06:00
_progress = value / 100.0;
std::cout << _start;
2019-12-03 11:54:06 -06:00
float pos = _progress * static_cast<float>(_bar_width);
2019-12-03 10:46:25 -06:00
for (size_t i = 0; i < _bar_width; ++i) {
2019-12-03 16:53:17 -06:00
if (i < pos) std::cout << _fill;
else if (i == pos) std::cout << _lead;
else std::cout << _negative_space;
2019-12-03 09:54:50 -06:00
}
std::cout << _end << " " << static_cast<int>(value) << "%";
std::cout << " " << _name << "\r";
2019-12-03 11:54:06 -06:00
std::cout.flush();
2019-12-03 09:54:50 -06:00
}
};