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