Line data Source code
1 : #include "window.h"
2 : #include "termbox.h"
3 :
4 : #include <iostream>
5 : #include <thread>
6 :
7 : #ifdef NO_WINDOW // Null window (for testing)
8 :
9 : #include <iostream>
10 : #include <thread>
11 :
12 5 : Window::Window() {}
13 5 : Window::~Window() {}
14 :
15 1013591 : int32_t Window::width() const { return 256; }
16 1348439 : int32_t Window::height() const { return 128; }
17 :
18 0 : bool Window::handleEvents() {
19 0 : events_.clear();
20 : static int i = 0;
21 : static const std::vector<WindowEvent> evs{WindowEvent::ArrowUp, WindowEvent::ArrowLeft,
22 0 : WindowEvent::ArrowDown, WindowEvent::ArrowRight};
23 0 : events_.push_back(evs[(i++) % 4]);
24 0 : return true;
25 : }
26 :
27 5 : void Window::render() {
28 5 : std::cout << "Window::render()\n";
29 : using namespace std::chrono_literals;
30 5 : const auto delayPerFrame = 15ms;
31 5 : if (delayPerFrame != 0ms) {
32 5 : std::this_thread::sleep_for(delayPerFrame);
33 : }
34 5 : }
35 :
36 10 : void Window::clear() {}
37 :
38 175795 : void Window::set(int x, int y, char c, uint16_t fg, uint16_t bg) {
39 175795 : layoutEvents.push_back(Pos{x, y, c});
40 175798 : }
41 :
42 : #else // Terminal
43 :
44 : Window::Window() {
45 : int code = tb_init();
46 : if (code < 0) {
47 : std::cerr << "termbox init failed, code: %d\n";
48 : throw std::runtime_error("termbox failed");
49 : }
50 :
51 : tb_select_input_mode(TB_INPUT_ESC);
52 : tb_clear();
53 : tb_select_output_mode(TB_OUTPUT_NORMAL);
54 : }
55 :
56 : Window::~Window() { tb_shutdown(); }
57 :
58 : bool Window::handleEvents() {
59 : events_.clear();
60 :
61 : struct tb_event ev;
62 : if (tb_peek_event(&ev, 10)) {
63 : switch (ev.type) {
64 : case TB_EVENT_KEY:
65 : switch (ev.key) {
66 : case TB_KEY_ESC:
67 : return false;
68 : break;
69 : case TB_KEY_ARROW_LEFT:
70 : events_.push_back(WindowEvent::ArrowLeft);
71 : break;
72 : case TB_KEY_ARROW_RIGHT:
73 : events_.push_back(WindowEvent::ArrowRight);
74 : break;
75 : case TB_KEY_ARROW_UP:
76 : events_.push_back(WindowEvent::ArrowUp);
77 : break;
78 : case TB_KEY_ARROW_DOWN:
79 : events_.push_back(WindowEvent::ArrowDown);
80 : break;
81 : }
82 : break;
83 : case TB_EVENT_RESIZE:
84 : // draw_all();
85 : break;
86 : }
87 : }
88 :
89 : return true;
90 : }
91 :
92 : void Window::render() {
93 : using namespace std::chrono_literals;
94 : const auto delayPerFrame = 15ms;
95 :
96 : tb_present();
97 :
98 : if (delayPerFrame != 0ms) {
99 : std::this_thread::sleep_for(delayPerFrame);
100 : }
101 : }
102 :
103 : void Window::clear() { tb_clear(); }
104 :
105 : void Window::set(int x, int y, char c, uint16_t fg, uint16_t bg) {
106 : tb_change_cell(x, y, c, fg, bg);
107 : }
108 :
109 : int32_t Window::width() const { return tb_width(); }
110 :
111 : int32_t Window::height() const { return tb_height(); }
112 :
113 : #endif
|