jaffarCommon
Loading...
Searching...
No Matches
ncurses.hpp
Go to the documentation of this file.
1#pragma once
2
8#include "../string.hpp"
9#include <ncurses.h>
10#include <stdarg.h>
11#include <stdexcept>
12#include <stdio.h>
13#include <unistd.h>
14
15namespace jaffarCommon
16{
17
18namespace logger
19{
20
24static bool _useNCurses = false;
25
32template <typename... Args>
33__JAFFAR_COMMON__INLINE__ void log(const char* f, Args... args)
34{
35 auto string = jaffarCommon::string::formatString(f, args...);
36 if (_useNCurses == true) printw("%s", string.c_str());
37 if (_useNCurses == false) printf("%s", string.c_str());
38}
39
46__JAFFAR_COMMON__INLINE__ int kbhit()
47{
48 int ch, r;
49
50 // turn off getch() blocking and echo
51 nodelay(stdscr, TRUE);
52 noecho();
53
54 // check for input
55 ch = getch();
56 if (ch == ERR) // no input
57 r = FALSE;
58 else // input
59 {
60 r = TRUE;
61 ungetch(ch);
62 }
63
64 // restore block and echo
65 echo();
66 nodelay(stdscr, FALSE);
67
68 return (r);
69}
70
79__JAFFAR_COMMON__INLINE__ int waitForKeyPress()
80{
81 if (_useNCurses == false) return getchar();
82
83 while (!kbhit())
84 {
85 usleep(100000ul);
86 refresh();
87 }
88 return getch();
89}
90
98__JAFFAR_COMMON__INLINE__ int getKeyPress()
99{
100 if (_useNCurses == false) return 0;
101
102 nodelay(stdscr, TRUE);
103 noecho();
104
105 int ch = getch();
106
107 // restore block and echo
108 echo();
109 nodelay(stdscr, FALSE);
110
111 return ch;
112}
113
117__JAFFAR_COMMON__INLINE__ void initializeTerminal()
118{
119 // Instructing the log function to use printw
120 _useNCurses = true;
121
122 // Initializing ncurses screen
123 initscr();
124 cbreak();
125 noecho();
126 nodelay(stdscr, TRUE);
127 scrollok(stdscr, TRUE);
128}
129
133__JAFFAR_COMMON__INLINE__ void clearTerminal()
134{
135 if (_useNCurses == true) clear();
136}
137
141__JAFFAR_COMMON__INLINE__ void finalizeTerminal()
142{
143 // Instructing the log function to use printf
144 _useNCurses = false;
145
146 endwin();
147}
148
152__JAFFAR_COMMON__INLINE__ void refreshTerminal()
153{
154 if (_useNCurses == true) refresh();
155}
156
157} // namespace logger
158
159} // namespace jaffarCommon
160
161#undef ERR
162#undef OK
__JAFFAR_COMMON__INLINE__ void initializeTerminal()
Definition ncurses.hpp:117
__JAFFAR_COMMON__INLINE__ void clearTerminal()
Definition ncurses.hpp:133
__JAFFAR_COMMON__INLINE__ int kbhit()
Definition ncurses.hpp:46
__JAFFAR_COMMON__INLINE__ void refreshTerminal()
Definition ncurses.hpp:152
__JAFFAR_COMMON__INLINE__ void log(const char *f, Args... args)
Definition ncurses.hpp:33
static bool _useNCurses
Definition ncurses.hpp:24
__JAFFAR_COMMON__INLINE__ int getKeyPress()
Definition ncurses.hpp:98
__JAFFAR_COMMON__INLINE__ void finalizeTerminal()
Definition ncurses.hpp:141
__JAFFAR_COMMON__INLINE__ int waitForKeyPress()
Definition ncurses.hpp:79