OpenMC/src/progress_bar.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

74 lines
1.3 KiB
C++
Raw Normal View History

2018-10-29 18:02:00 -05:00
#include "openmc/progress_bar.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#if defined(__unix__) || defined(__unix) || \
(defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#endif
2018-10-29 18:02:00 -05:00
#define BAR_WIDTH 72
bool is_terminal()
{
#ifdef _POSIX_VERSION
2018-10-30 20:13:36 -05:00
return isatty(STDOUT_FILENO) != 0;
#else
return false;
#endif
}
2018-10-29 18:02:00 -05:00
ProgressBar::ProgressBar()
{
// initialize bar
2018-10-29 18:02:00 -05:00
set_value(0.0);
}
void ProgressBar::set_value(double val)
{
if (!is_terminal())
return;
2018-11-02 23:08:51 -05:00
2018-10-29 18:02:00 -05:00
// set the bar percentage
if (val >= 100.0) {
bar.append("100");
} else if (val <= 0.0) {
bar.append(" 0");
} else {
std::stringstream ss;
ss << std::setfill(' ') << std::setw(3) << (int)val;
bar.append(ss.str());
}
bar.append("% |");
// remaining width of the bar
2018-10-30 19:41:30 -05:00
int remaining_width = BAR_WIDTH - bar.size() - 2;
2018-11-02 23:08:51 -05:00
2018-10-29 18:02:00 -05:00
// set the bar width
if (val >= 100.0) {
2018-10-30 19:41:30 -05:00
bar.append(remaining_width, '=');
} else if (val < 0.0) {
2018-11-02 23:08:51 -05:00
bar.append(remaining_width, ' ');
2018-10-29 18:02:00 -05:00
} else {
2018-10-30 19:41:30 -05:00
int width = (int)((double)remaining_width * val / 100);
2018-10-29 18:02:00 -05:00
bar.append(width, '=');
bar.append(1, '>');
2018-10-30 19:41:30 -05:00
bar.append(remaining_width - width - 1, ' ');
2018-10-29 18:02:00 -05:00
}
bar.append("|+");
2018-11-02 23:08:51 -05:00
2018-10-29 18:02:00 -05:00
// write the bar
std::cout << '\r' << bar << std::flush;
if (val >= 100.0) {
std::cout << "\n";
}
2018-11-02 23:08:51 -05:00
2018-10-29 18:02:00 -05:00
// reset the bar value
2018-10-29 22:09:13 -05:00
bar = "";
2018-10-29 18:02:00 -05:00
}