Debian Codegraph @

src/cdogs/rlutil/rlutil.h

raw symbols SCIP
1 #pragma once
2 /**
3 * File: rlutil.h
4 *
5 * About: Description
6 * This file provides some useful utilities for console mode
7 * roguelike game development with C and C++. It is aimed to
8 * be cross-platform (at least Windows and Linux).
9 *
10 * About: Copyright
11 * (C) 2010 Tapio Vierros
12 *
13 * About: Licensing
14 * See <License>
15 */
16
17
18 /// Define: RLUTIL_USE_ANSI
19 /// Define this to use ANSI escape sequences also on Windows
20 /// (defaults to using WinAPI instead).
21 #if 0
22 #define RLUTIL_USE_ANSI
23 #endif
24
25 /// Define: RLUTIL_STRING_T
26 /// Define/typedef this to your preference to override rlutil's string type.
27 ///
28 /// Defaults to std::string with C++ and char* with C.
29 #if 0
30 #define RLUTIL_STRING_T char*
31 #endif
32
33 #ifndef RLUTIL_INLINE
34 #ifdef _MSC_VER
35 #define RLUTIL_INLINE __inline
36 #else
37 #define RLUTIL_INLINE static __inline__
38 #endif
39 #endif
40
41 #ifdef __cplusplus
42 /// Common C++ headers
43 #include <iostream>
44 #include <string>
45 #include <cstdio> // for getch()
46 /// Namespace forward declarations
47 namespace rlutil {
48 RLUTIL_INLINE void locate(int x, int y);
49 }
50 #else
51 #include <stdio.h> // for getch() / printf()
52 #include <string.h> // for strlen()
53 RLUTIL_INLINE void locate(int x, int y); // Forward declare for C to avoid warnings
54 #endif // __cplusplus
55
56 #ifdef _WIN32
57 #include <windows.h> // for WinAPI and Sleep()
58 #define _NO_OLDNAMES // for MinGW compatibility
59 #include <conio.h> // for getch() and kbhit()
60 #define getch _getch
61 #define kbhit _kbhit
62 #else
63 #include <termios.h> // for getch() and kbhit()
64 #include <unistd.h> // for getch(), kbhit() and (u)sleep()
65 #include <sys/ioctl.h> // for getkey()
66 #include <sys/types.h> // for kbhit()
67 #include <sys/time.h> // for kbhit()
68
69 /// Function: getch
70 /// Get character without waiting for Return to be pressed.
71 /// Windows has this in conio.h
72 RLUTIL_INLINE int getch(void) {
73 // Here be magic.
74 struct termios oldt, newt;
75 int ch;
76 tcgetattr(STDIN_FILENO, &oldt);
77 newt = oldt;
78 newt.c_lflag &= ~(ICANON | ECHO);
79 tcsetattr(STDIN_FILENO, TCSANOW, &newt);
80 ch = getchar();
81 tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
82 return ch;
83 }
84
85 /// Function: kbhit
86 /// Determines if keyboard has been hit.
87 /// Windows has this in conio.h
88 RLUTIL_INLINE int kbhit(void) {
89 // Here be dragons.
90 static struct termios oldt, newt;
91 int cnt = 0;
92 tcgetattr(STDIN_FILENO, &oldt);
93 newt = oldt;
94 newt.c_lflag &= ~(ICANON | ECHO);
95 newt.c_iflag = 0; // input mode
96 newt.c_oflag = 0; // output mode
97 newt.c_cc[VMIN] = 1; // minimum time to wait
98 newt.c_cc[VTIME] = 1; // minimum characters to wait for
99 tcsetattr(STDIN_FILENO, TCSANOW, &newt);
100 ioctl(0, FIONREAD, &cnt); // Read count
101 struct timeval tv;
102 tv.tv_sec = 0;
103 tv.tv_usec = 100;
104 select(STDIN_FILENO+1, NULL, NULL, NULL, &tv); // A small time delay
105 tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
106 return cnt; // Return number of characters
107 }
108 #endif // _WIN32
109
110 #ifndef gotoxy
111 /// Function: gotoxy
112 /// Same as <rlutil.locate>.
113 RLUTIL_INLINE void gotoxy(int x, int y) {
114 #ifdef __cplusplus
115 rlutil::
116 #endif
117 locate(x,y);
118 }
119 #endif // gotoxy
120
121 #ifdef __cplusplus
122 /// Namespace: rlutil
123 /// In C++ all functions except <getch>, <kbhit> and <gotoxy> are arranged
124 /// under namespace rlutil. That is because some platforms have them defined
125 /// outside of rlutil.
126 namespace rlutil {
127 #endif
128
129 /**
130 * Defs: Internal typedefs and macros
131 * RLUTIL_STRING_T - String type depending on which one of C or C++ is used
132 * RLUTIL_PRINT(str) - Printing macro independent of C/C++
133 */
134 #ifndef RLUTIL_STRING_T
135 typedef const char* RLUTIL_STRING_T;
136 #endif // RLUTIL_STRING_T
137
138 #define RLUTIL_FPRINT(f, st) fprintf(f, "%s", st)
139 #define RLUTIL_PRINT(st) printf("%s", st)
140
141 /**
142 * Enums: Color codes
143 *
144 * BLACK - Black
145 * BLUE - Blue
146 * GREEN - Green
147 * CYAN - Cyan
148 * RED - Red
149 * MAGENTA - Magenta / purple
150 * BROWN - Brown / dark yellow
151 * GREY - Grey / dark white
152 * DARKGREY - Dark grey / light black
153 * LIGHTBLUE - Light blue
154 * LIGHTGREEN - Light green
155 * LIGHTCYAN - Light cyan
156 * LIGHTRED - Light red
157 * LIGHTMAGENTA - Light magenta / light purple
158 * YELLOW - Yellow (bright)
159 * WHITE - White (bright)
160 */
161 enum {
162 BLACK,
163 BLUE,
164 GREEN,
165 CYAN,
166 RED,
167 MAGENTA,
168 BROWN,
169 GREY,
170 DARKGREY,
171 LIGHTBLUE,
172 LIGHTGREEN,
173 LIGHTCYAN,
174 LIGHTRED,
175 LIGHTMAGENTA,
176 YELLOW,
177 WHITE
178 };
179
180 /**
181 * Consts: ANSI escape strings
182 *
183 * ANSI_CLS - Clears screen
184 * ANSI_CONSOLE_TITLE_PRE - Prefix for changing the window title, print the window title in between
185 * ANSI_CONSOLE_TITLE_POST - Suffix for changing the window title, print the window title in between
186 * ANSI_ATTRIBUTE_RESET - Resets all attributes
187 * ANSI_CURSOR_HIDE - Hides the cursor
188 * ANSI_CURSOR_SHOW - Shows the cursor
189 * ANSI_CURSOR_HOME - Moves the cursor home (0,0)
190 * ANSI_BLACK - Black
191 * ANSI_RED - Red
192 * ANSI_GREEN - Green
193 * ANSI_BROWN - Brown / dark yellow
194 * ANSI_BLUE - Blue
195 * ANSI_MAGENTA - Magenta / purple
196 * ANSI_CYAN - Cyan
197 * ANSI_GREY - Grey / dark white
198 * ANSI_DARKGREY - Dark grey / light black
199 * ANSI_LIGHTRED - Light red
200 * ANSI_LIGHTGREEN - Light green
201 * ANSI_YELLOW - Yellow (bright)
202 * ANSI_LIGHTBLUE - Light blue
203 * ANSI_LIGHTMAGENTA - Light magenta / light purple
204 * ANSI_LIGHTCYAN - Light cyan
205 * ANSI_WHITE - White (bright)
206 * ANSI_BACKGROUND_BLACK - Black background
207 * ANSI_BACKGROUND_RED - Red background
208 * ANSI_BACKGROUND_GREEN - Green background
209 * ANSI_BACKGROUND_YELLOW - Yellow background
210 * ANSI_BACKGROUND_BLUE - Blue background
211 * ANSI_BACKGROUND_MAGENTA - Magenta / purple background
212 * ANSI_BACKGROUND_CYAN - Cyan background
213 * ANSI_BACKGROUND_WHITE - White background
214 */
215 static const RLUTIL_STRING_T ANSI_CLS = "\033[2J\033[3J";
216 static const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_PRE = "\033]0;";
217 static const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST = "\007";
218 static const RLUTIL_STRING_T ANSI_ATTRIBUTE_RESET = "\033[0m";
219 static const RLUTIL_STRING_T ANSI_CURSOR_HIDE = "\033[?25l";
220 static const RLUTIL_STRING_T ANSI_CURSOR_SHOW = "\033[?25h";
221 static const RLUTIL_STRING_T ANSI_CURSOR_HOME = "\033[H";
222 static const RLUTIL_STRING_T ANSI_BLACK = "\033[22;30m";
223 static const RLUTIL_STRING_T ANSI_RED = "\033[22;31m";
224 static const RLUTIL_STRING_T ANSI_GREEN = "\033[22;32m";
225 static const RLUTIL_STRING_T ANSI_BROWN = "\033[22;33m";
226 static const RLUTIL_STRING_T ANSI_BLUE = "\033[22;34m";
227 static const RLUTIL_STRING_T ANSI_MAGENTA = "\033[22;35m";
228 static const RLUTIL_STRING_T ANSI_CYAN = "\033[22;36m";
229 static const RLUTIL_STRING_T ANSI_GREY = "\033[22;37m";
230 static const RLUTIL_STRING_T ANSI_DARKGREY = "\033[01;30m";
231 static const RLUTIL_STRING_T ANSI_LIGHTRED = "\033[01;31m";
232 static const RLUTIL_STRING_T ANSI_LIGHTGREEN = "\033[01;32m";
233 static const RLUTIL_STRING_T ANSI_YELLOW = "\033[01;33m";
234 static const RLUTIL_STRING_T ANSI_LIGHTBLUE = "\033[01;34m";
235 static const RLUTIL_STRING_T ANSI_LIGHTMAGENTA = "\033[01;35m";
236 static const RLUTIL_STRING_T ANSI_LIGHTCYAN = "\033[01;36m";
237 static const RLUTIL_STRING_T ANSI_WHITE = "\033[01;37m";
238 static const RLUTIL_STRING_T ANSI_BACKGROUND_BLACK = "\033[40m";
239 static const RLUTIL_STRING_T ANSI_BACKGROUND_RED = "\033[41m";
240 static const RLUTIL_STRING_T ANSI_BACKGROUND_GREEN = "\033[42m";
241 static const RLUTIL_STRING_T ANSI_BACKGROUND_YELLOW = "\033[43m";
242 static const RLUTIL_STRING_T ANSI_BACKGROUND_BLUE = "\033[44m";
243 static const RLUTIL_STRING_T ANSI_BACKGROUND_MAGENTA = "\033[45m";
244 static const RLUTIL_STRING_T ANSI_BACKGROUND_CYAN = "\033[46m";
245 static const RLUTIL_STRING_T ANSI_BACKGROUND_WHITE = "\033[47m";
246 // Remaining colors not supported as background colors
247
248 /**
249 * Enums: Key codes for keyhit()
250 *
251 * KEY_ESCAPE - Escape
252 * KEY_ENTER - Enter
253 * KEY_SPACE - Space
254 * KEY_INSERT - Insert
255 * KEY_HOME - Home
256 * KEY_END - End
257 * KEY_DELETE - Delete
258 * KEY_PGUP - PageUp
259 * KEY_PGDOWN - PageDown
260 * KEY_UP - Up arrow
261 * KEY_DOWN - Down arrow
262 * KEY_LEFT - Left arrow
263 * KEY_RIGHT - Right arrow
264 * KEY_F1 - F1
265 * KEY_F2 - F2
266 * KEY_F3 - F3
267 * KEY_F4 - F4
268 * KEY_F5 - F5
269 * KEY_F6 - F6
270 * KEY_F7 - F7
271 * KEY_F8 - F8
272 * KEY_F9 - F9
273 * KEY_F10 - F10
274 * KEY_F11 - F11
275 * KEY_F12 - F12
276 * KEY_NUMDEL - Numpad del
277 * KEY_NUMPAD0 - Numpad 0
278 * KEY_NUMPAD1 - Numpad 1
279 * KEY_NUMPAD2 - Numpad 2
280 * KEY_NUMPAD3 - Numpad 3
281 * KEY_NUMPAD4 - Numpad 4
282 * KEY_NUMPAD5 - Numpad 5
283 * KEY_NUMPAD6 - Numpad 6
284 * KEY_NUMPAD7 - Numpad 7
285 * KEY_NUMPAD8 - Numpad 8
286 * KEY_NUMPAD9 - Numpad 9
287 */
288 enum {
289 KEY_ESCAPE = 0,
290 KEY_ENTER = 1,
291 KEY_SPACE = 32,
292
293 KEY_INSERT = 2,
294 KEY_HOME = 3,
295 KEY_PGUP = 4,
296 KEY_DELETE = 5,
297 KEY_END = 6,
298 KEY_PGDOWN = 7,
299
300 KEY_UP = 14,
301 KEY_DOWN = 15,
302 KEY_LEFT = 16,
303 KEY_RIGHT = 17,
304
305 KEY_F1 = 18,
306 KEY_F2 = 19,
307 KEY_F3 = 20,
308 KEY_F4 = 21,
309 KEY_F5 = 22,
310 KEY_F6 = 23,
311 KEY_F7 = 24,
312 KEY_F8 = 25,
313 KEY_F9 = 26,
314 KEY_F10 = 27,
315 KEY_F11 = 28,
316 KEY_F12 = 29,
317
318 KEY_NUMDEL = 30,
319 KEY_NUMPAD0 = 31,
320 KEY_NUMPAD1 = 127,
321 KEY_NUMPAD2 = 128,
322 KEY_NUMPAD3 = 129,
323 KEY_NUMPAD4 = 130,
324 KEY_NUMPAD5 = 131,
325 KEY_NUMPAD6 = 132,
326 KEY_NUMPAD7 = 133,
327 KEY_NUMPAD8 = 134,
328 KEY_NUMPAD9 = 135
329 };
330
331 /// Function: getkey
332 /// Reads a key press (blocking) and returns a key code.
333 ///
334 /// See <Key codes for keyhit()>
335 ///
336 /// Note:
337 /// Only Arrows, Esc, Enter and Space are currently working properly.
338 RLUTIL_INLINE int getkey(void) {
339 #ifndef _WIN32
340 int cnt = kbhit(); // for ANSI escapes processing
341 #endif
342 int k = getch();
343 switch(k) {
344 case 0: {
345 int kk;
346 switch (kk = getch()) {
347 case 71: return KEY_NUMPAD7;
348 case 72: return KEY_NUMPAD8;
349 case 73: return KEY_NUMPAD9;
350 case 75: return KEY_NUMPAD4;
351 case 77: return KEY_NUMPAD6;
352 case 79: return KEY_NUMPAD1;
353 case 80: return KEY_NUMPAD2;
354 case 81: return KEY_NUMPAD3;
355 case 82: return KEY_NUMPAD0;
356 case 83: return KEY_NUMDEL;
357 default: return kk-59+KEY_F1; // Function keys
358 }}
359 case 224: {
360 int kk;
361 switch (kk = getch()) {
362 case 71: return KEY_HOME;
363 case 72: return KEY_UP;
364 case 73: return KEY_PGUP;
365 case 75: return KEY_LEFT;
366 case 77: return KEY_RIGHT;
367 case 79: return KEY_END;
368 case 80: return KEY_DOWN;
369 case 81: return KEY_PGDOWN;
370 case 82: return KEY_INSERT;
371 case 83: return KEY_DELETE;
372 default: return kk-123+KEY_F1; // Function keys
373 }}
374 case 13: return KEY_ENTER;
375 #ifdef _WIN32
376 case 27: return KEY_ESCAPE;
377 #else // _WIN32
378 case 155: // single-character CSI
379 case 27: {
380 // Process ANSI escape sequences
381 if (cnt >= 3 && getch() == '[') {
382 switch (k = getch()) {
383 case 'A': return KEY_UP;
384 case 'B': return KEY_DOWN;
385 case 'C': return KEY_RIGHT;
386 case 'D': return KEY_LEFT;
387 }
388 } else return KEY_ESCAPE;
389 }
390 #endif // _WIN32
391 default: return k;
392 }
393 }
394
395 /// Function: nb_getch
396 /// Non-blocking getch(). Returns 0 if no key was pressed.
397 RLUTIL_INLINE int nb_getch(void) {
398 if (kbhit()) return getch();
399 else return 0;
400 }
401
402 /// Function: getANSIColor
403 /// Return ANSI color escape sequence for specified number 0-15.
404 ///
405 /// See <Color Codes>
406 RLUTIL_INLINE RLUTIL_STRING_T getANSIColor(const int c) {
407 switch (c) {
408 case BLACK : return ANSI_BLACK;
409 case BLUE : return ANSI_BLUE; // non-ANSI
410 case GREEN : return ANSI_GREEN;
411 case CYAN : return ANSI_CYAN; // non-ANSI
412 case RED : return ANSI_RED; // non-ANSI
413 case MAGENTA : return ANSI_MAGENTA;
414 case BROWN : return ANSI_BROWN;
415 case GREY : return ANSI_GREY;
416 case DARKGREY : return ANSI_DARKGREY;
417 case LIGHTBLUE : return ANSI_LIGHTBLUE; // non-ANSI
418 case LIGHTGREEN : return ANSI_LIGHTGREEN;
419 case LIGHTCYAN : return ANSI_LIGHTCYAN; // non-ANSI;
420 case LIGHTRED : return ANSI_LIGHTRED; // non-ANSI;
421 case LIGHTMAGENTA: return ANSI_LIGHTMAGENTA;
422 case YELLOW : return ANSI_YELLOW; // non-ANSI
423 case WHITE : return ANSI_WHITE;
424 default: return "";
425 }
426 }
427
428 /// Function: getANSIBackgroundColor
429 /// Return ANSI background color escape sequence for specified number 0-15.
430 ///
431 /// See <Color Codes>
432 RLUTIL_INLINE RLUTIL_STRING_T getANSIBackgroundColor(const int c) {
433 switch (c) {
434 case BLACK : return ANSI_BACKGROUND_BLACK;
435 case BLUE : return ANSI_BACKGROUND_BLUE;
436 case GREEN : return ANSI_BACKGROUND_GREEN;
437 case CYAN : return ANSI_BACKGROUND_CYAN;
438 case RED : return ANSI_BACKGROUND_RED;
439 case MAGENTA: return ANSI_BACKGROUND_MAGENTA;
440 case BROWN : return ANSI_BACKGROUND_YELLOW;
441 case GREY : return ANSI_BACKGROUND_WHITE;
442 default: return "";
443 }
444 }
445
446 /// Function: setColor
447 /// Change color specified by number (Windows / QBasic colors).
448 /// Don't change the background color
449 ///
450 /// See <Color Codes>
451 RLUTIL_INLINE void setStreamColor(FILE *stream, const int c) {
452 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
453 HANDLE hConsole = GetStdHandle(
454 stream == stderr ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE);
455 CONSOLE_SCREEN_BUFFER_INFO csbi;
456
457 GetConsoleScreenBufferInfo(hConsole, &csbi);
458
459 SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFFF0) | (WORD)c); // Foreground colors take up the least significant byte
460 #else
461 RLUTIL_FPRINT(stream, getANSIColor(c));
462 #endif
463 }
464 RLUTIL_INLINE void setColor(const int c) {
465 setStreamColor(stdout, c);
466 }
467
468 /// Function: setBackgroundColor
469 /// Change background color specified by number (Windows / QBasic colors).
470 /// Don't change the foreground color
471 ///
472 /// See <Color Codes>
473 RLUTIL_INLINE void setBackgroundColor(int c) {
474 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
475 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
476 CONSOLE_SCREEN_BUFFER_INFO csbi;
477
478 GetConsoleScreenBufferInfo(hConsole, &csbi);
479
480 SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFF0F) | (((WORD)c) << 4)); // Background colors take up the second-least significant byte
481 #else
482 RLUTIL_PRINT(getANSIBackgroundColor(c));
483 #endif
484 }
485
486 /// Function: saveDefaultColor
487 /// Call once to preserve colors for use in resetColor()
488 /// on Windows without ANSI, no-op otherwise
489 ///
490 /// See <Color Codes>
491 /// See <resetColor>
492 RLUTIL_INLINE int saveStreamDefaultColor(FILE *stream) {
493 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
494 static char initialized = 0; // bool
495 static WORD attributes;
496
497 if (!initialized) {
498 CONSOLE_SCREEN_BUFFER_INFO csbi;
499 GetConsoleScreenBufferInfo(
500 GetStdHandle(stream == stderr ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE),
501 &csbi);
502 attributes = csbi.wAttributes;
503 initialized = 1;
504 }
505 return (int)attributes;
506 #else
507 (void)stream;
508 return -1;
509 #endif
510 }
511 RLUTIL_INLINE int saveDefaultColor(void) {
512 return saveStreamDefaultColor(stdout);
513 }
514
515 /// Function: resetColor
516 /// Reset color to default
517 /// Requires a call to saveDefaultColor() to set the defaults
518 ///
519 /// See <Color Codes>
520 /// See <setColor>
521 /// See <saveDefaultColor>
522 RLUTIL_INLINE void resetStreamColor(FILE *stream) {
523 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
524 SetConsoleTextAttribute(
525 GetStdHandle(stream == stderr ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE),
526 (WORD)saveDefaultColor());
527 #else
528 RLUTIL_FPRINT(stream, ANSI_ATTRIBUTE_RESET);
529 #endif
530 }
531 RLUTIL_INLINE void resetColor(void) {
532 resetStreamColor(stdout);
533 }
534
535 /// Function: cls
536 /// Clears screen, resets all attributes and moves cursor home.
537 RLUTIL_INLINE void cls(void) {
538 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
539 // Based on https://msdn.microsoft.com/en-us/library/windows/desktop/ms682022%28v=vs.85%29.aspx
540 const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
541 const COORD coordScreen = {0, 0};
542 DWORD cCharsWritten;
543 CONSOLE_SCREEN_BUFFER_INFO csbi;
544
545 GetConsoleScreenBufferInfo(hConsole, &csbi);
546 const DWORD dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
547 FillConsoleOutputCharacter(hConsole, (TCHAR)' ', dwConSize, coordScreen, &cCharsWritten);
548
549 GetConsoleScreenBufferInfo(hConsole, &csbi);
550 FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
551
552 SetConsoleCursorPosition(hConsole, coordScreen);
553 #else
554 RLUTIL_PRINT(ANSI_CLS);
555 RLUTIL_PRINT(ANSI_CURSOR_HOME);
556 #endif
557 }
558
559 /// Function: locate
560 /// Sets the cursor position to 1-based x,y.
561 RLUTIL_INLINE void locate(int x, int y) {
562 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
563 COORD coord;
564 // TODO: clamping/assert for x/y <= 0?
565 coord.X = (SHORT)(x - 1);
566 coord.Y = (SHORT)(y - 1); // Windows uses 0-based coordinates
567 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
568 #else // _WIN32 || USE_ANSI
569 #ifdef __cplusplus
570 RLUTIL_PRINT("\033[" << y << ";" << x << "H");
571 #else // __cplusplus
572 char buf[32];
573 sprintf(buf, "\033[%d;%df", y, x);
574 RLUTIL_PRINT(buf);
575 #endif // __cplusplus
576 #endif // _WIN32 || USE_ANSI
577 }
578
579 /// Function: setString
580 /// Prints the supplied string without advancing the cursor
581 #ifdef __cplusplus
582 RLUTIL_INLINE void setString(const RLUTIL_STRING_T & str_) {
583 const char * const str = str_.data();
584 unsigned int len = str_.size();
585 #else // __cplusplus
586 RLUTIL_INLINE void setString(RLUTIL_STRING_T str) {
587 unsigned int len = (unsigned int)strlen(str);
588 #endif // __cplusplus
589 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
590 HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
591 DWORD numberOfCharsWritten;
592 CONSOLE_SCREEN_BUFFER_INFO csbi;
593
594 GetConsoleScreenBufferInfo(hConsoleOutput, &csbi);
595 WriteConsoleOutputCharacter(hConsoleOutput, str, len, csbi.dwCursorPosition, &numberOfCharsWritten);
596 #else // _WIN32 || USE_ANSI
597 RLUTIL_PRINT(str);
598 #ifdef __cplusplus
599 RLUTIL_PRINT("\033[" << len << 'D');
600 #else // __cplusplus
601 char buf[3 + 20 + 1]; // 20 = max length of 64-bit unsigned int when printed as dec
602 sprintf(buf, "\033[%uD", len);
603 RLUTIL_PRINT(buf);
604 #endif // __cplusplus
605 #endif // _WIN32 || USE_ANSI
606 }
607
608 /// Function: setChar
609 /// Sets the character at the cursor without advancing the cursor
610 RLUTIL_INLINE void setChar(char ch) {
611 const char buf[] = {ch, 0};
612 setString(buf);
613 }
614
615 /// Function: setCursorVisibility
616 /// Shows/hides the cursor.
617 RLUTIL_INLINE void setCursorVisibility(char visible) {
618 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
619 HANDLE hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );
620 CONSOLE_CURSOR_INFO structCursorInfo;
621 GetConsoleCursorInfo( hConsoleOutput, &structCursorInfo ); // Get current cursor size
622 structCursorInfo.bVisible = (visible ? TRUE : FALSE);
623 SetConsoleCursorInfo( hConsoleOutput, &structCursorInfo );
624 #else // _WIN32 || USE_ANSI
625 RLUTIL_PRINT((visible ? ANSI_CURSOR_SHOW : ANSI_CURSOR_HIDE));
626 #endif // _WIN32 || USE_ANSI
627 }
628
629 /// Function: hidecursor
630 /// Hides the cursor.
631 RLUTIL_INLINE void hidecursor(void) {
632 setCursorVisibility(0);
633 }
634
635 /// Function: showcursor
636 /// Shows the cursor.
637 RLUTIL_INLINE void showcursor(void) {
638 setCursorVisibility(1);
639 }
640
641 /// Function: trows
642 /// Get the number of rows in the terminal window or -1 on error.
643 RLUTIL_INLINE int trows(void) {
644 #ifdef _WIN32
645 CONSOLE_SCREEN_BUFFER_INFO csbi;
646 if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
647 return -1;
648 else
649 return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Window height
650 // return csbi.dwSize.Y; // Buffer height
651 #else
652 #ifdef TIOCGSIZE
653 struct ttysize ts;
654 ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
655 return ts.ts_lines;
656 #elif defined(TIOCGWINSZ)
657 struct winsize ts;
658 ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
659 return ts.ws_row;
660 #else // TIOCGSIZE
661 return -1;
662 #endif // TIOCGSIZE
663 #endif // _WIN32
664 }
665
666 /// Function: tcols
667 /// Get the number of columns in the terminal window or -1 on error.
668 RLUTIL_INLINE int tcols(void) {
669 #ifdef _WIN32
670 CONSOLE_SCREEN_BUFFER_INFO csbi;
671 if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
672 return -1;
673 else
674 return csbi.srWindow.Right - csbi.srWindow.Left + 1; // Window width
675 // return csbi.dwSize.X; // Buffer width
676 #else
677 #ifdef TIOCGSIZE
678 struct ttysize ts;
679 ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
680 return ts.ts_cols;
681 #elif defined(TIOCGWINSZ)
682 struct winsize ts;
683 ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
684 return ts.ws_col;
685 #else // TIOCGSIZE
686 return -1;
687 #endif // TIOCGSIZE
688 #endif // _WIN32
689 }
690
691 /// Function: anykey
692 /// Waits until a key is pressed.
693 /// In C++, it either takes no arguments
694 /// or a template-type-argument-deduced
695 /// argument.
696 /// In C, it takes a const char* representing
697 /// the message to be displayed, or NULL
698 /// for no message.
699 #ifdef __cplusplus
700 RLUTIL_INLINE void anykey() {
701 getch();
702 }
703
704 template <class T> void anykey(const T& msg) {
705 RLUTIL_PRINT(msg);
706 #else
707 RLUTIL_INLINE void anykey(RLUTIL_STRING_T msg) {
708 if (msg)
709 RLUTIL_PRINT(msg);
710 #endif // __cplusplus
711 getch();
712 }
713
714 RLUTIL_INLINE void setConsoleTitle(RLUTIL_STRING_T title) {
715 const char * true_title =
716 #ifdef __cplusplus
717 title.c_str();
718 #else // __cplusplus
719 title;
720 #endif // __cplusplus
721 #if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
722 SetConsoleTitleA(true_title);
723 #else
724 RLUTIL_PRINT(ANSI_CONSOLE_TITLE_PRE);
725 RLUTIL_PRINT(true_title);
726 RLUTIL_PRINT(ANSI_CONSOLE_TITLE_POST);
727 #endif // defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
728 }
729
730 // Classes are here at the end so that documentation is pretty.
731
732 #ifdef __cplusplus
733 /// Class: CursorHider
734 /// RAII OOP wrapper for <rlutil.hidecursor>.
735 /// Hides the cursor and shows it again
736 /// when the object goes out of scope.
737 struct CursorHider {
738 CursorHider() { hidecursor(); }
739 ~CursorHider() { showcursor(); }
740 };
741
742 } // namespace rlutil
743 #endif