FTXUI  0.11.1
C++ functional terminal UI.
graph.cpp
Go to the documentation of this file.
1 #include <functional> // for function
2 #include <memory> // for allocator, make_shared
3 #include <string> // for string
4 #include <vector> // for vector
5 
6 #include "ftxui/dom/elements.hpp" // for GraphFunction, Element, graph
7 #include "ftxui/dom/node.hpp" // for Node
8 #include "ftxui/dom/requirement.hpp" // for Requirement
9 #include "ftxui/screen/box.hpp" // for Box
10 #include "ftxui/screen/screen.hpp" // for Screen
11 
12 namespace ftxui {
13 
14 static std::string charset[] =
15 #if defined(FTXUI_MICROSOFT_TERMINAL_FALLBACK)
16  // Microsoft's terminals often use fonts not handling the 8 unicode
17  // characters for representing the whole graph. Fallback with less.
18  {" ", " ", "█", " ", "█", "█", "█", "█", "█"};
19 #else
20  {" ", "▗", "▐", "▖", "▄", "▟", "▌", "▙", "█"};
21 #endif
22 
23 class Graph : public Node {
24  public:
25  Graph(GraphFunction graph_function) : graph_function_(graph_function) {}
26 
27  void ComputeRequirement() override {
32  requirement_.min_x = 3;
33  requirement_.min_y = 3;
34  }
35 
36  void Render(Screen& screen) override {
37  int width = (box_.x_max - box_.x_min + 1) * 2;
38  int height = (box_.y_max - box_.y_min + 1) * 2;
39  auto data = graph_function_(width, height);
40  int i = 0;
41  for (int x = box_.x_min; x <= box_.x_max; ++x) {
42  int height_1 = 2 * box_.y_max - data[i++];
43  int height_2 = 2 * box_.y_max - data[i++];
44  for (int y = box_.y_min; y <= box_.y_max; ++y) {
45  int yy = 2 * y;
46  int i_1 = yy < height_1 ? 0 : yy == height_1 ? 3 : 6;
47  int i_2 = yy < height_2 ? 0 : yy == height_2 ? 1 : 2;
48  screen.at(x, y) = charset[i_1 + i_2];
49  }
50  }
51  }
52 
53  private:
54  GraphFunction graph_function_;
55 };
56 
57 /// @brief Draw a graph using a GraphFunction.
58 /// @param graph_function the function to be called to get the data.
59 Element graph(GraphFunction graph_function) {
60  return std::make_shared<Graph>(graph_function);
61 }
62 
63 } // namespace ftxui
64 
65 // Copyright 2020 Arthur Sonzogni. All rights reserved.
66 // Use of this source code is governed by the MIT license that can be found in
67 // the LICENSE file.
Requirement requirement_
Definition: node.hpp:49
Box box_
Definition: node.hpp:50
std::shared_ptr< Node > Element
Definition: elements.hpp:16
std::function< std::vector< int >(int, int)> GraphFunction
Definition: elements.hpp:19
void Render(Screen &screen, const Element &node)
Display an element on a ftxui::Screen.
Definition: node.cpp:40
Element graph(GraphFunction)
Draw a graph using a GraphFunction.
Definition: graph.cpp:59
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