CPGen
C++ project generator
Loading...
Searching...
No Matches
Terminal.hpp
Go to the documentation of this file.
1#pragma once
2
17#ifdef _WIN32
18#include <windows.h>
19#else
20#include <termios.h>
21#include <unistd.h>
22#endif
23
24#include <csignal>
25#include <cstdio>
26#include <cstdlib>
27
44class Terminal {
45public:
55#ifndef _WIN32
56 (void)tcgetattr(STDIN_FILENO, &m_original);
57 s_original = m_original;
58
59 struct termios raw = m_original;
60 raw.c_lflag &=
61 ~(static_cast<tcflag_t>(ICANON) | static_cast<tcflag_t>(ECHO));
62 (void)tcsetattr(STDIN_FILENO, TCSANOW, &raw);
63#endif
64 (void)std::fputs("\033[?25l", stdout); // Hide cursor
65 (void)std::fflush(stdout);
66
67 // Hook signals so Ctrl+C / kill always restores the terminal
68 (void)std::signal(SIGINT, signalHandler);
69 (void)std::signal(SIGTERM, signalHandler);
70 }
71
75 ~Terminal() { restore(); }
76
77 Terminal(const Terminal &) = delete;
78 Terminal &operator=(const Terminal &) = delete;
79 Terminal(Terminal &&) = delete;
80 Terminal &operator=(Terminal &&) = delete;
81
82private:
90 static void restore() {
91#ifndef _WIN32
92 (void)tcsetattr(STDIN_FILENO, TCSANOW, &s_original);
93#endif
94 (void)std::fputs("\033[?25h", stdout); // Show cursor
95 (void)std::fflush(stdout);
96 }
97
107 static void signalHandler(int /*sig*/) {
108 restore();
109 std::_Exit(130);
110 }
111
112#ifndef _WIN32
113 struct termios m_original{};
115 static inline struct termios
116 s_original{};
117#endif
118};
RAII raw-mode terminal handler.
Definition Terminal.hpp:44
Terminal & operator=(Terminal &&)=delete
Non-movable.
Terminal & operator=(const Terminal &)=delete
Non-copyable.
Terminal()
Enter raw mode and hide the cursor.
Definition Terminal.hpp:54
Terminal(Terminal &&)=delete
Non-movable.
~Terminal()
Restore the original terminal state and show the cursor.
Definition Terminal.hpp:75
Terminal(const Terminal &)=delete
Non-copyable.