terminal_chat_console.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. Minetest
  3. Copyright (C) 2015 est31 <MTest31@outlook.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include <inttypes.h>
  17. #include "config.h"
  18. #if USE_CURSES
  19. #include "version.h"
  20. #include "terminal_chat_console.h"
  21. #include "porting.h"
  22. #include "settings.h"
  23. #include "util/numeric.h"
  24. #include "util/string.h"
  25. #include "chat_interface.h"
  26. TerminalChatConsole g_term_console;
  27. // include this last to avoid any conflicts
  28. // (likes to set macros to common names, conflicting various stuff)
  29. #if CURSES_HAVE_NCURSESW_NCURSES_H
  30. #include <ncursesw/ncurses.h>
  31. #elif CURSES_HAVE_NCURSESW_CURSES_H
  32. #include <ncursesw/curses.h>
  33. #elif CURSES_HAVE_CURSES_H
  34. #include <curses.h>
  35. #elif CURSES_HAVE_NCURSES_H
  36. #include <ncurses.h>
  37. #elif CURSES_HAVE_NCURSES_NCURSES_H
  38. #include <ncurses/ncurses.h>
  39. #elif CURSES_HAVE_NCURSES_CURSES_H
  40. #include <ncurses/curses.h>
  41. #endif
  42. // Some functions to make drawing etc position independent
  43. static bool reformat_backend(ChatBackend *backend, int rows, int cols)
  44. {
  45. if (rows < 2)
  46. return false;
  47. backend->reformat(cols, rows - 2);
  48. return true;
  49. }
  50. static void move_for_backend(int row, int col)
  51. {
  52. move(row + 1, col);
  53. }
  54. void TerminalChatConsole::initOfCurses()
  55. {
  56. initscr();
  57. cbreak(); //raw();
  58. noecho();
  59. keypad(stdscr, TRUE);
  60. nodelay(stdscr, TRUE);
  61. timeout(100);
  62. // To make esc not delay up to one second. According to the internet,
  63. // this is the value vim uses, too.
  64. set_escdelay(25);
  65. getmaxyx(stdscr, m_rows, m_cols);
  66. m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
  67. }
  68. void TerminalChatConsole::deInitOfCurses()
  69. {
  70. endwin();
  71. }
  72. void *TerminalChatConsole::run()
  73. {
  74. BEGIN_DEBUG_EXCEPTION_HANDLER
  75. std::cout << "========================" << std::endl;
  76. std::cout << "Begin log output over terminal"
  77. << " (no stdout/stderr backlog during that)" << std::endl;
  78. // Make the loggers to stdout/stderr shut up.
  79. // Go over our own loggers instead.
  80. LogLevelMask err_mask = g_logger.removeOutput(&stderr_output);
  81. LogLevelMask out_mask = g_logger.removeOutput(&stdout_output);
  82. g_logger.addOutput(&m_log_output);
  83. // Inform the server of our nick
  84. m_chat_interface->command_queue.push_back(
  85. new ChatEventNick(CET_NICK_ADD, m_nick));
  86. {
  87. // Ensures that curses is deinitialized even on an exception being thrown
  88. CursesInitHelper helper(this);
  89. while (!stopRequested()) {
  90. int ch = getch();
  91. if (stopRequested())
  92. break;
  93. step(ch);
  94. }
  95. }
  96. if (m_kill_requested)
  97. *m_kill_requested = true;
  98. g_logger.removeOutput(&m_log_output);
  99. g_logger.addOutputMasked(&stderr_output, err_mask);
  100. g_logger.addOutputMasked(&stdout_output, out_mask);
  101. std::cout << "End log output over terminal"
  102. << " (no stdout/stderr backlog during that)" << std::endl;
  103. std::cout << "========================" << std::endl;
  104. END_DEBUG_EXCEPTION_HANDLER
  105. return NULL;
  106. }
  107. void TerminalChatConsole::typeChatMessage(const std::wstring &msg)
  108. {
  109. // Discard empty line
  110. if (msg.empty())
  111. return;
  112. // Send to server
  113. m_chat_interface->command_queue.push_back(
  114. new ChatEventChat(m_nick, msg));
  115. // Print if its a command (gets eaten by server otherwise)
  116. if (msg[0] == L'/') {
  117. m_chat_backend.addMessage(L"", (std::wstring)L"Issued command: " + msg);
  118. }
  119. }
  120. void TerminalChatConsole::handleInput(int ch, bool &complete_redraw_needed)
  121. {
  122. ChatPrompt &prompt = m_chat_backend.getPrompt();
  123. // Helpful if you want to collect key codes that aren't documented
  124. /*if (ch != ERR) {
  125. m_chat_backend.addMessage(L"",
  126. (std::wstring)L"Pressed key " + utf8_to_wide(
  127. std::string(keyname(ch)) + " (code " + itos(ch) + ")"));
  128. complete_redraw_needed = true;
  129. }//*/
  130. // All the key codes below are compatible to xterm
  131. // Only add new ones if you have tried them there,
  132. // to ensure compatibility with not just xterm but the wide
  133. // range of terminals that are compatible to xterm.
  134. switch (ch) {
  135. case ERR: // no input
  136. break;
  137. case 27: // ESC
  138. // Toggle ESC mode
  139. m_esc_mode = !m_esc_mode;
  140. break;
  141. case KEY_PPAGE:
  142. m_chat_backend.scrollPageUp();
  143. complete_redraw_needed = true;
  144. break;
  145. case KEY_NPAGE:
  146. m_chat_backend.scrollPageDown();
  147. complete_redraw_needed = true;
  148. break;
  149. case KEY_ENTER:
  150. case '\r':
  151. case '\n': {
  152. prompt.addToHistory(prompt.getLine());
  153. typeChatMessage(prompt.replace(L""));
  154. break;
  155. }
  156. case KEY_UP:
  157. prompt.historyPrev();
  158. break;
  159. case KEY_DOWN:
  160. prompt.historyNext();
  161. break;
  162. case KEY_LEFT:
  163. // Left pressed
  164. // move character to the left
  165. prompt.cursorOperation(
  166. ChatPrompt::CURSOROP_MOVE,
  167. ChatPrompt::CURSOROP_DIR_LEFT,
  168. ChatPrompt::CURSOROP_SCOPE_CHARACTER);
  169. break;
  170. case 545:
  171. // Ctrl-Left pressed
  172. // move word to the left
  173. prompt.cursorOperation(
  174. ChatPrompt::CURSOROP_MOVE,
  175. ChatPrompt::CURSOROP_DIR_LEFT,
  176. ChatPrompt::CURSOROP_SCOPE_WORD);
  177. break;
  178. case KEY_RIGHT:
  179. // Right pressed
  180. // move character to the right
  181. prompt.cursorOperation(
  182. ChatPrompt::CURSOROP_MOVE,
  183. ChatPrompt::CURSOROP_DIR_RIGHT,
  184. ChatPrompt::CURSOROP_SCOPE_CHARACTER);
  185. break;
  186. case 560:
  187. // Ctrl-Right pressed
  188. // move word to the right
  189. prompt.cursorOperation(
  190. ChatPrompt::CURSOROP_MOVE,
  191. ChatPrompt::CURSOROP_DIR_RIGHT,
  192. ChatPrompt::CURSOROP_SCOPE_WORD);
  193. break;
  194. case KEY_HOME:
  195. // Home pressed
  196. // move to beginning of line
  197. prompt.cursorOperation(
  198. ChatPrompt::CURSOROP_MOVE,
  199. ChatPrompt::CURSOROP_DIR_LEFT,
  200. ChatPrompt::CURSOROP_SCOPE_LINE);
  201. break;
  202. case KEY_END:
  203. // End pressed
  204. // move to end of line
  205. prompt.cursorOperation(
  206. ChatPrompt::CURSOROP_MOVE,
  207. ChatPrompt::CURSOROP_DIR_RIGHT,
  208. ChatPrompt::CURSOROP_SCOPE_LINE);
  209. break;
  210. case KEY_BACKSPACE:
  211. case '\b':
  212. case 127:
  213. // Backspace pressed
  214. // delete character to the left
  215. prompt.cursorOperation(
  216. ChatPrompt::CURSOROP_DELETE,
  217. ChatPrompt::CURSOROP_DIR_LEFT,
  218. ChatPrompt::CURSOROP_SCOPE_CHARACTER);
  219. break;
  220. case KEY_DC:
  221. // Delete pressed
  222. // delete character to the right
  223. prompt.cursorOperation(
  224. ChatPrompt::CURSOROP_DELETE,
  225. ChatPrompt::CURSOROP_DIR_RIGHT,
  226. ChatPrompt::CURSOROP_SCOPE_CHARACTER);
  227. break;
  228. case 519:
  229. // Ctrl-Delete pressed
  230. // delete word to the right
  231. prompt.cursorOperation(
  232. ChatPrompt::CURSOROP_DELETE,
  233. ChatPrompt::CURSOROP_DIR_RIGHT,
  234. ChatPrompt::CURSOROP_SCOPE_WORD);
  235. break;
  236. case 21:
  237. // Ctrl-U pressed
  238. // kill line to left end
  239. prompt.cursorOperation(
  240. ChatPrompt::CURSOROP_DELETE,
  241. ChatPrompt::CURSOROP_DIR_LEFT,
  242. ChatPrompt::CURSOROP_SCOPE_LINE);
  243. break;
  244. case 11:
  245. // Ctrl-K pressed
  246. // kill line to right end
  247. prompt.cursorOperation(
  248. ChatPrompt::CURSOROP_DELETE,
  249. ChatPrompt::CURSOROP_DIR_RIGHT,
  250. ChatPrompt::CURSOROP_SCOPE_LINE);
  251. break;
  252. case KEY_TAB:
  253. // Tab pressed
  254. // Nick completion
  255. prompt.nickCompletion(m_nicks, false);
  256. break;
  257. default:
  258. // Add character to the prompt,
  259. // assuming UTF-8.
  260. if (IS_UTF8_MULTB_START(ch)) {
  261. m_pending_utf8_bytes.append(1, (char)ch);
  262. m_utf8_bytes_to_wait += UTF8_MULTB_START_LEN(ch) - 1;
  263. } else if (m_utf8_bytes_to_wait != 0) {
  264. m_pending_utf8_bytes.append(1, (char)ch);
  265. m_utf8_bytes_to_wait--;
  266. if (m_utf8_bytes_to_wait == 0) {
  267. std::wstring w = utf8_to_wide(m_pending_utf8_bytes);
  268. m_pending_utf8_bytes = "";
  269. // hopefully only one char in the wstring...
  270. for (size_t i = 0; i < w.size(); i++) {
  271. prompt.input(w.c_str()[i]);
  272. }
  273. }
  274. } else if (IS_ASCII_PRINTABLE_CHAR(ch)) {
  275. prompt.input(ch);
  276. } else {
  277. // Silently ignore characters we don't handle
  278. //warningstream << "Pressed invalid character '"
  279. // << keyname(ch) << "' (code " << itos(ch) << ")" << std::endl;
  280. }
  281. break;
  282. }
  283. }
  284. void TerminalChatConsole::step(int ch)
  285. {
  286. bool complete_redraw_needed = false;
  287. // empty queues
  288. while (!m_chat_interface->outgoing_queue.empty()) {
  289. ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx();
  290. switch (evt->type) {
  291. case CET_NICK_REMOVE:
  292. m_nicks.remove(((ChatEventNick *)evt)->nick);
  293. break;
  294. case CET_NICK_ADD:
  295. m_nicks.push_back(((ChatEventNick *)evt)->nick);
  296. break;
  297. case CET_CHAT:
  298. complete_redraw_needed = true;
  299. // This is only used for direct replies from commands
  300. // or for lua's print() functionality
  301. m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg);
  302. break;
  303. case CET_TIME_INFO:
  304. ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt;
  305. m_game_time = tevt->game_time;
  306. m_time_of_day = tevt->time;
  307. };
  308. delete evt;
  309. }
  310. while (!m_log_output.queue.empty()) {
  311. complete_redraw_needed = true;
  312. std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx();
  313. if (p.first > m_log_level)
  314. continue;
  315. std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first));
  316. if (!g_settings->getBool("disable_escape_sequences")) {
  317. error_message = std::wstring(L"\x1b(c@red)").append(error_message)
  318. .append(L"\x1b(c@white)");
  319. }
  320. m_chat_backend.addMessage(error_message, utf8_to_wide(p.second));
  321. }
  322. // handle input
  323. if (!m_esc_mode) {
  324. handleInput(ch, complete_redraw_needed);
  325. } else {
  326. switch (ch) {
  327. case ERR: // no input
  328. break;
  329. case 27: // ESC
  330. // Toggle ESC mode
  331. m_esc_mode = !m_esc_mode;
  332. break;
  333. case 'L':
  334. m_log_level--;
  335. m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible
  336. break;
  337. case 'l':
  338. m_log_level++;
  339. m_log_level = MYMIN(m_log_level, LL_MAX - 1);
  340. break;
  341. }
  342. }
  343. // was there a resize?
  344. int xn, yn;
  345. getmaxyx(stdscr, yn, xn);
  346. if (xn != m_cols || yn != m_rows) {
  347. m_cols = xn;
  348. m_rows = yn;
  349. m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
  350. complete_redraw_needed = true;
  351. }
  352. // draw title
  353. move(0, 0);
  354. clrtoeol();
  355. addstr(PROJECT_NAME_C);
  356. addstr(" ");
  357. addstr(g_version_hash);
  358. u32 minutes = m_time_of_day % 1000;
  359. u32 hours = m_time_of_day / 1000;
  360. minutes = (float)minutes / 1000 * 60;
  361. if (m_game_time)
  362. printw(" | Game %" PRIu64 " Time of day %02d:%02d ",
  363. m_game_time, hours, minutes);
  364. // draw text
  365. if (complete_redraw_needed && m_can_draw_text)
  366. draw_text();
  367. // draw prompt
  368. if (!m_esc_mode) {
  369. // normal prompt
  370. ChatPrompt& prompt = m_chat_backend.getPrompt();
  371. std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion());
  372. move(m_rows - 1, 0);
  373. clrtoeol();
  374. addstr(prompt_text.c_str());
  375. // Draw cursor
  376. s32 cursor_pos = prompt.getVisibleCursorPosition();
  377. if (cursor_pos >= 0) {
  378. move(m_rows - 1, cursor_pos);
  379. }
  380. } else {
  381. // esc prompt
  382. move(m_rows - 1, 0);
  383. clrtoeol();
  384. printw("[ESC] Toggle ESC mode |"
  385. " [CTRL+C] Shut down |"
  386. " (L) in-, (l) decrease loglevel %s",
  387. Logger::getLevelLabel((LogLevel) m_log_level).c_str());
  388. }
  389. refresh();
  390. }
  391. void TerminalChatConsole::draw_text()
  392. {
  393. ChatBuffer& buf = m_chat_backend.getConsoleBuffer();
  394. for (u32 row = 0; row < buf.getRows(); row++) {
  395. move_for_backend(row, 0);
  396. clrtoeol();
  397. const ChatFormattedLine& line = buf.getFormattedLine(row);
  398. if (line.fragments.empty())
  399. continue;
  400. for (const ChatFormattedFragment &fragment : line.fragments) {
  401. addstr(wide_to_utf8(fragment.text.getString()).c_str());
  402. }
  403. }
  404. }
  405. void TerminalChatConsole::stopAndWaitforThread()
  406. {
  407. clearKillStatus();
  408. stop();
  409. wait();
  410. }
  411. #endif