Debian Codegraph @

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