Files
indicators/include/progress/bar.hpp

97 lines
2.1 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 17:01:47 -06:00
size_t _bar_width{100};
2019-12-03 16:53:17 -06:00
std::string _start{"[ "};
std::string _fill{""};
std::string _lead{""};
2019-12-03 16:56:39 -06:00
std::string _remainder{"-"};
2019-12-03 16:53:17 -06:00
std::string _end{" ]"};
2019-12-03 09:54:50 -06:00
std::mutex _mutex;
std::atomic<bool> _completed;
2019-12-03 19:59:43 -06:00
void _print_progress() {
std::unique_lock<std::mutex> lock{_mutex};
std::cout << _start;
float pos = _progress * static_cast<float>(_bar_width) / 100.0;
for (size_t i = 0; i < _bar_width; ++i) {
if (i < pos) std::cout << _fill;
else if (i == pos) std::cout << _lead;
else std::cout << _remainder;
}
std::cout << _end << " " << static_cast<int>(_progress) << "%";
std::cout << " " << _name << "\r";
std::cout.flush();
if (_completed)
std::cout << std::endl;
}
2019-12-03 09:54:50 -06:00
public:
2019-12-03 19:59:43 -06:00
void bar_width(size_t bar_width) {
std::unique_lock<std::mutex> lock{_mutex};
_bar_width = bar_width;
}
void start_with(const std::string& start) {
std::unique_lock<std::mutex> lock{_mutex};
2019-12-03 16:53:17 -06:00
_start = start;
}
2019-12-03 19:59:43 -06:00
void fill_progress_with(const std::string& fill) {
std::unique_lock<std::mutex> lock{_mutex};
2019-12-03 16:53:17 -06:00
_fill = fill;
}
2019-12-03 19:59:43 -06:00
void lead_progress_with(const std::string& lead) {
std::unique_lock<std::mutex> lock{_mutex};
2019-12-03 16:53:17 -06:00
_lead = lead;
}
2019-12-03 19:59:43 -06:00
void fill_remainder_with(const std::string& remainder) {
std::unique_lock<std::mutex> lock{_mutex};
2019-12-03 16:56:39 -06:00
_remainder = remainder;
2019-12-03 16:53:17 -06:00
}
2019-12-03 19:59:43 -06:00
void end_with(const std::string& end) {
std::unique_lock<std::mutex> lock{_mutex};
2019-12-03 16:53:17 -06:00
_end = end;
}
2019-12-03 11:54:06 -06:00
2019-12-03 19:59:43 -06:00
void set_progress(float value) {
{
std::unique_lock<std::mutex> lock{_mutex};
if (_completed) return;
_progress = value;
if (_progress >= 100.0) {
_completed = true;
}
2019-12-03 09:54:50 -06:00
}
2019-12-03 19:59:43 -06:00
_print_progress();
2019-12-03 09:54:50 -06:00
}
2019-12-03 19:59:43 -06:00
void tick() {
{
std::unique_lock<std::mutex> lock{_mutex};
if (_completed) return;
_progress += 1;
if (_progress >= 100.0) {
_completed = true;
}
}
_print_progress();
}
bool completed() {
return _completed;
2019-12-03 19:59:43 -06:00
}
2019-12-03 09:54:50 -06:00
};