FTXUI  0.11.0
C++ functional terminal UI.
Loading...
Searching...
No Matches
gauge.cpp
Go to the documentation of this file.
1#include <algorithm> // for max, min
2#include <memory> // for allocator, make_shared
3#include <string> // for string
4
5#include "ftxui/dom/elements.hpp" // for Element, gauge
6#include "ftxui/dom/node.hpp" // for Node
7#include "ftxui/dom/requirement.hpp" // for Requirement
8#include "ftxui/screen/box.hpp" // for Box
9#include "ftxui/screen/screen.hpp" // for Screen
10
11namespace ftxui {
12
13static std::string charset[11] = {
14#if defined(FTXUI_MICROSOFT_TERMINAL_FALLBACK)
15 // Microsoft's terminals often use fonts not handling the 8 unicode
16 // characters for representing the whole gauge. Fallback with less.
17 " ", " ", " ", " ", "▌", "▌", "▌", "█", "█", "█",
18#else
19 " ", " ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█",
20#endif
21 // An extra character in case when the fuzzer manage to have:
22 // int(9 * (limit - limit_int) = 9
23 "█"};
24
25class Gauge : public Node {
26 public:
27 Gauge(float progress) : progress_(std::min(std::max(progress, 0.f), 1.f)) {}
28
29 void ComputeRequirement() override {
36 }
37
38 void Render(Screen& screen) override {
39 int y = box_.y_min;
40 if (y > box_.y_max)
41 return;
42
43 float limit = box_.x_min + progress_ * (box_.x_max - box_.x_min + 1);
44 int limit_int = limit;
45 int x = box_.x_min;
46 while (x < limit_int)
47 screen.at(x++, y) = charset[9];
48 screen.at(x++, y) = charset[int(9 * (limit - limit_int))];
49 while (x <= box_.x_max)
50 screen.at(x++, y) = charset[0];
51 }
52
53 private:
54 float progress_;
55};
56
57/// @brief Draw a high definition progress bar.
58/// @param progress The proportion of the area to be filled. Belong to [0,1].
59/// @ingroup dom
60///
61/// ### Example
62///
63/// A gauge. It can be used to represent a progress bar.
64/// ~~~cpp
65/// border(gauge(0.5))
66/// ~~~
67///
68/// #### Output
69///
70/// ~~~bash
71/// ┌──────────────────────────────────────────────────────────────────────────┐
72/// │█████████████████████████████████████ │
73/// └──────────────────────────────────────────────────────────────────────────┘
74/// ~~~
75Element gauge(float progress) {
76 return std::make_shared<Gauge>(progress);
77}
78
79} // namespace ftxui
80
81// Copyright 2020 Arthur Sonzogni. All rights reserved.
82// Use of this source code is governed by the MIT license that can be found in
83// the LICENSE file.
Requirement requirement_
Definition node.hpp:40
Box box_
Definition node.hpp:41
std::shared_ptr< Node > Element
Definition elements.hpp:15
Element gauge(float ratio)
Draw a high definition progress bar.
Definition gauge.cpp:75
int x_max
Definition box.hpp:8
int y_min
Definition box.hpp:9
int y_max
Definition box.hpp:10
int x_min
Definition box.hpp:7