Terminal.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Daniel Bertalan <dani@danielbertalan.dev>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/Queue.h>
  9. #include <AK/StringBuilder.h>
  10. #include <AK/StringView.h>
  11. #include <AK/TemporaryChange.h>
  12. #include <LibVT/Color.h>
  13. #include <LibVT/Terminal.h>
  14. #ifdef KERNEL
  15. # include <Kernel/TTY/VirtualConsole.h>
  16. #endif
  17. namespace VT {
  18. #ifndef KERNEL
  19. Terminal::Terminal(TerminalClient& client)
  20. #else
  21. Terminal::Terminal(Kernel::VirtualConsole& client)
  22. #endif
  23. : m_client(client)
  24. , m_parser(*this)
  25. {
  26. }
  27. #ifndef KERNEL
  28. void Terminal::clear()
  29. {
  30. dbgln_if(TERMINAL_DEBUG, "Clear the entire screen");
  31. for (size_t i = 0; i < rows(); ++i)
  32. active_buffer()[i]->clear();
  33. set_cursor(0, 0);
  34. }
  35. void Terminal::clear_history()
  36. {
  37. dbgln_if(TERMINAL_DEBUG, "Clear history");
  38. auto previous_history_size = m_history.size();
  39. m_history.clear();
  40. m_history_start = 0;
  41. m_client.terminal_history_changed(-previous_history_size);
  42. }
  43. #endif
  44. void Terminal::alter_ansi_mode(bool should_set, Parameters params)
  45. {
  46. for (auto mode : params) {
  47. switch (mode) {
  48. // FIXME: implement *something* for this
  49. default:
  50. dbgln("Terminal::alter_ansi_mode: Unimplemented mode {} (should_set={})", mode, should_set);
  51. break;
  52. }
  53. }
  54. }
  55. void Terminal::alter_private_mode(bool should_set, Parameters params)
  56. {
  57. for (auto mode : params) {
  58. switch (mode) {
  59. case 1:
  60. // Cursor Keys Mode (DECCKM)
  61. dbgln_if(TERMINAL_DEBUG, "Setting cursor keys mode (should_set={})", should_set);
  62. m_cursor_keys_mode = should_set ? CursorKeysMode::Application : CursorKeysMode::Cursor;
  63. break;
  64. case 3: {
  65. // 80/132-column mode (DECCOLM)
  66. unsigned new_columns = should_set ? 132 : 80;
  67. dbgln_if(TERMINAL_DEBUG, "Setting {}-column mode", new_columns);
  68. set_size(new_columns, rows());
  69. clear();
  70. break;
  71. }
  72. case 12:
  73. if (should_set) {
  74. // Start blinking cursor
  75. m_client.set_cursor_blinking(true);
  76. } else {
  77. // Stop blinking cursor
  78. m_client.set_cursor_blinking(false);
  79. }
  80. break;
  81. case 25:
  82. if (should_set) {
  83. // Show cursor
  84. m_cursor_shape = m_saved_cursor_shape;
  85. m_client.set_cursor_shape(m_cursor_shape);
  86. } else {
  87. // Hide cursor
  88. m_saved_cursor_shape = m_cursor_shape;
  89. m_cursor_shape = VT::CursorShape::None;
  90. m_client.set_cursor_shape(VT::CursorShape::None);
  91. }
  92. break;
  93. case 1047:
  94. #ifndef KERNEL
  95. if (should_set) {
  96. dbgln_if(TERMINAL_DEBUG, "Switching to Alternate Screen Buffer");
  97. m_use_alternate_screen_buffer = true;
  98. clear();
  99. m_client.terminal_history_changed(-m_history.size());
  100. } else {
  101. dbgln_if(TERMINAL_DEBUG, "Switching to Normal Screen Buffer");
  102. m_use_alternate_screen_buffer = false;
  103. m_client.terminal_history_changed(m_history.size());
  104. }
  105. m_need_full_flush = true;
  106. #else
  107. dbgln("Alternate Screen Buffer is not supported");
  108. #endif
  109. break;
  110. case 1048:
  111. if (should_set)
  112. SCOSC();
  113. else
  114. SCORC();
  115. break;
  116. case 1049:
  117. #ifndef KERNEL
  118. if (should_set) {
  119. dbgln_if(TERMINAL_DEBUG, "Switching to Alternate Screen Buffer and saving state");
  120. m_normal_saved_state = m_current_state;
  121. m_use_alternate_screen_buffer = true;
  122. clear();
  123. m_client.terminal_history_changed(-m_history.size());
  124. } else {
  125. dbgln_if(TERMINAL_DEBUG, "Switching to Normal Screen Buffer and restoring state");
  126. m_current_state = m_normal_saved_state;
  127. m_use_alternate_screen_buffer = false;
  128. set_cursor(cursor_row(), cursor_column());
  129. m_client.terminal_history_changed(m_history.size());
  130. }
  131. m_need_full_flush = true;
  132. #else
  133. dbgln("Alternate Screen Buffer is not supported");
  134. #endif
  135. break;
  136. case 2004:
  137. dbgln_if(TERMINAL_DEBUG, "Setting bracketed mode enabled={}", should_set);
  138. m_needs_bracketed_paste = should_set;
  139. break;
  140. default:
  141. dbgln("Terminal::alter_private_mode: Unimplemented private mode {} (should_set={})", mode, should_set);
  142. break;
  143. }
  144. }
  145. }
  146. void Terminal::RM(Parameters params)
  147. {
  148. alter_ansi_mode(false, params);
  149. }
  150. void Terminal::DECRST(Parameters params)
  151. {
  152. alter_private_mode(false, params);
  153. }
  154. void Terminal::SM(Parameters params)
  155. {
  156. alter_ansi_mode(true, params);
  157. }
  158. void Terminal::DECSET(Parameters params)
  159. {
  160. alter_private_mode(true, params);
  161. }
  162. void Terminal::SGR(Parameters params)
  163. {
  164. if (params.is_empty()) {
  165. m_current_state.attribute.reset();
  166. return;
  167. }
  168. auto parse_color = [&]() -> Optional<Color> {
  169. if (params.size() < 2) {
  170. dbgln("Color code has no type");
  171. return {};
  172. }
  173. u32 rgb = 0;
  174. switch (params[1]) {
  175. case 5: // 8-bit
  176. if (params.size() < 3) {
  177. dbgln("8-bit color code has too few parameters");
  178. return {};
  179. }
  180. if (params[2] > 255) {
  181. dbgln("8-bit color code has out-of-bounds value");
  182. return {};
  183. }
  184. return Color::indexed(params[2]);
  185. case 2: // 24-bit
  186. if (params.size() < 5) {
  187. dbgln("24-bit color code has too few parameters");
  188. return {};
  189. }
  190. for (size_t i = 0; i < 3; ++i) {
  191. rgb <<= 8;
  192. rgb |= params[i + 2];
  193. }
  194. return Color::rgb(rgb);
  195. default:
  196. dbgln("Unknown color type {}", params[1]);
  197. return {};
  198. }
  199. };
  200. if (params[0] == 38) {
  201. m_current_state.attribute.foreground_color = parse_color().value_or(m_current_state.attribute.foreground_color);
  202. } else if (params[0] == 48) {
  203. m_current_state.attribute.background_color = parse_color().value_or(m_current_state.attribute.background_color);
  204. } else {
  205. // A single escape sequence may set multiple parameters.
  206. for (auto param : params) {
  207. switch (param) {
  208. case 0:
  209. // Reset
  210. m_current_state.attribute.reset();
  211. break;
  212. case 1:
  213. m_current_state.attribute.flags |= Attribute::Flags::Bold;
  214. break;
  215. case 3:
  216. m_current_state.attribute.flags |= Attribute::Flags::Italic;
  217. break;
  218. case 4:
  219. m_current_state.attribute.flags |= Attribute::Flags::Underline;
  220. break;
  221. case 5:
  222. m_current_state.attribute.flags |= Attribute::Flags::Blink;
  223. break;
  224. case 7:
  225. m_current_state.attribute.flags |= Attribute::Flags::Negative;
  226. break;
  227. case 22:
  228. m_current_state.attribute.flags &= ~Attribute::Flags::Bold;
  229. break;
  230. case 23:
  231. m_current_state.attribute.flags &= ~Attribute::Flags::Italic;
  232. break;
  233. case 24:
  234. m_current_state.attribute.flags &= ~Attribute::Flags::Underline;
  235. break;
  236. case 25:
  237. m_current_state.attribute.flags &= ~Attribute::Flags::Blink;
  238. break;
  239. case 27:
  240. m_current_state.attribute.flags &= ~Attribute::Flags::Negative;
  241. break;
  242. case 30:
  243. case 31:
  244. case 32:
  245. case 33:
  246. case 34:
  247. case 35:
  248. case 36:
  249. case 37:
  250. // Foreground color
  251. m_current_state.attribute.foreground_color = Color::named(static_cast<Color::ANSIColor>(param - 30));
  252. break;
  253. case 39:
  254. // reset foreground
  255. m_current_state.attribute.foreground_color = Attribute::default_foreground_color;
  256. break;
  257. case 40:
  258. case 41:
  259. case 42:
  260. case 43:
  261. case 44:
  262. case 45:
  263. case 46:
  264. case 47:
  265. // Background color
  266. m_current_state.attribute.background_color = Color::named(static_cast<Color::ANSIColor>(param - 40));
  267. break;
  268. case 49:
  269. // reset background
  270. m_current_state.attribute.background_color = Attribute::default_background_color;
  271. break;
  272. case 90:
  273. case 91:
  274. case 92:
  275. case 93:
  276. case 94:
  277. case 95:
  278. case 96:
  279. case 97:
  280. // Bright foreground color
  281. m_current_state.attribute.foreground_color = Color::named(static_cast<Color::ANSIColor>(8 + param - 90));
  282. break;
  283. case 100:
  284. case 101:
  285. case 102:
  286. case 103:
  287. case 104:
  288. case 105:
  289. case 106:
  290. case 107:
  291. // Bright background color
  292. m_current_state.attribute.background_color = Color::named(static_cast<Color::ANSIColor>(8 + param - 100));
  293. break;
  294. default:
  295. dbgln("FIXME: SGR: p: {}", param);
  296. }
  297. }
  298. }
  299. }
  300. void Terminal::SCOSC()
  301. {
  302. dbgln_if(TERMINAL_DEBUG, "Save cursor position");
  303. m_saved_cursor_position = m_current_state.cursor;
  304. }
  305. void Terminal::SCORC()
  306. {
  307. dbgln_if(TERMINAL_DEBUG, "Restore cursor position");
  308. m_current_state.cursor = m_saved_cursor_position;
  309. set_cursor(cursor_row(), cursor_column());
  310. }
  311. void Terminal::DECSC()
  312. {
  313. dbgln_if(TERMINAL_DEBUG, "Save cursor (and other state)");
  314. if (m_use_alternate_screen_buffer) {
  315. m_alternate_saved_state = m_current_state;
  316. } else {
  317. m_normal_saved_state = m_current_state;
  318. }
  319. }
  320. void Terminal::DECRC()
  321. {
  322. dbgln_if(TERMINAL_DEBUG, "Restore cursor (and other state)");
  323. if (m_use_alternate_screen_buffer) {
  324. m_current_state = m_alternate_saved_state;
  325. } else {
  326. m_current_state = m_normal_saved_state;
  327. }
  328. set_cursor(cursor_row(), cursor_column());
  329. }
  330. void Terminal::XTERM_WM(Parameters params)
  331. {
  332. if (params.size() < 1)
  333. return;
  334. switch (params[0]) {
  335. case 22: {
  336. #ifndef KERNEL
  337. if (params.size() > 1 && params[1] == 1) {
  338. dbgln("FIXME: we don't support icon titles");
  339. return;
  340. }
  341. dbgln_if(TERMINAL_DEBUG, "Title stack push: {}", m_current_window_title);
  342. (void)m_title_stack.try_append(move(m_current_window_title));
  343. #endif
  344. break;
  345. }
  346. case 23: {
  347. #ifndef KERNEL
  348. if (params.size() > 1 && params[1] == 1)
  349. return;
  350. if (m_title_stack.is_empty()) {
  351. dbgln("Shenanigans: Tried to pop from empty title stack");
  352. return;
  353. }
  354. m_current_window_title = m_title_stack.take_last();
  355. dbgln_if(TERMINAL_DEBUG, "Title stack pop: {}", m_current_window_title);
  356. m_client.set_window_title(m_current_window_title);
  357. #endif
  358. break;
  359. }
  360. default:
  361. dbgln("FIXME: XTERM_WM: Ps: {} (param count: {})", params[0], params.size());
  362. }
  363. }
  364. void Terminal::DECSTBM(Parameters params)
  365. {
  366. unsigned top = 1;
  367. unsigned bottom = m_rows;
  368. if (params.size() >= 1 && params[0] != 0)
  369. top = params[0];
  370. if (params.size() >= 2 && params[1] != 0)
  371. bottom = params[1];
  372. if ((bottom - top) < 2 || bottom > m_rows) {
  373. dbgln("Error: DECSTBM: scrolling region invalid: {}-{}", top, bottom);
  374. return;
  375. }
  376. if (top >= bottom) {
  377. return;
  378. }
  379. m_scroll_region_top = top - 1;
  380. m_scroll_region_bottom = bottom - 1;
  381. set_cursor(0, 0);
  382. dbgln_if(TERMINAL_DEBUG, "Set scrolling region: {}-{}", m_scroll_region_top, m_scroll_region_bottom);
  383. }
  384. void Terminal::CUP(Parameters params)
  385. {
  386. // CUP – Cursor Position
  387. unsigned row = 1;
  388. unsigned col = 1;
  389. if (params.size() >= 1 && params[0] != 0)
  390. row = params[0];
  391. if (params.size() >= 2 && params[1] != 0)
  392. col = params[1];
  393. set_cursor(row - 1, col - 1);
  394. }
  395. void Terminal::HVP(Parameters params)
  396. {
  397. unsigned row = 1;
  398. unsigned col = 1;
  399. if (params.size() >= 1 && params[0] != 0)
  400. row = params[0];
  401. if (params.size() >= 2 && params[1] != 0)
  402. col = params[1];
  403. set_cursor(row - 1, col - 1);
  404. }
  405. void Terminal::CUU(Parameters params)
  406. {
  407. unsigned num = 1;
  408. if (params.size() >= 1 && params[0] != 0)
  409. num = params[0];
  410. int new_row = cursor_row() - num;
  411. if (new_row < 0)
  412. new_row = 0;
  413. set_cursor(new_row, cursor_column());
  414. }
  415. void Terminal::CUD(Parameters params)
  416. {
  417. unsigned num = 1;
  418. if (params.size() >= 1 && params[0] != 0)
  419. num = params[0];
  420. unsigned new_row = cursor_row() + num;
  421. if (new_row >= m_rows)
  422. new_row = m_rows - 1;
  423. set_cursor(new_row, cursor_column());
  424. }
  425. void Terminal::CUF(Parameters params)
  426. {
  427. unsigned num = 1;
  428. if (params.size() >= 1 && params[0] != 0)
  429. num = params[0];
  430. unsigned new_column = cursor_column() + num;
  431. if (new_column >= m_columns)
  432. new_column = m_columns - 1;
  433. set_cursor(cursor_row(), new_column);
  434. }
  435. void Terminal::CUB(Parameters params)
  436. {
  437. unsigned num = 1;
  438. if (params.size() >= 1 && params[0] != 0)
  439. num = params[0];
  440. int new_column = (int)cursor_column() - num;
  441. if (new_column < 0)
  442. new_column = 0;
  443. set_cursor(cursor_row(), new_column);
  444. }
  445. void Terminal::CNL(Parameters params)
  446. {
  447. unsigned num = 1;
  448. if (params.size() >= 1 && params[0] != 0)
  449. num = params[0];
  450. unsigned new_row = cursor_row() + num;
  451. if (new_row >= m_columns)
  452. new_row = m_columns - 1;
  453. set_cursor(new_row, 0);
  454. }
  455. void Terminal::CPL(Parameters params)
  456. {
  457. unsigned num = 1;
  458. if (params.size() >= 1 && params[0] != 0)
  459. num = params[0];
  460. int new_row = (int)cursor_row() - num;
  461. if (new_row < 0)
  462. new_row = 0;
  463. set_cursor(new_row, 0);
  464. }
  465. void Terminal::CHA(Parameters params)
  466. {
  467. unsigned new_column = 1;
  468. if (params.size() >= 1 && params[0] != 0)
  469. new_column = params[0];
  470. if (new_column > m_columns)
  471. new_column = m_columns;
  472. set_cursor(cursor_row(), new_column - 1);
  473. }
  474. void Terminal::REP(Parameters params)
  475. {
  476. unsigned count = 1;
  477. if (params.size() >= 1 && params[0] != 0)
  478. count = params[0];
  479. for (unsigned i = 0; i < count; ++i)
  480. put_character_at(m_current_state.cursor.row, m_current_state.cursor.column++, m_last_code_point);
  481. }
  482. void Terminal::VPA(Parameters params)
  483. {
  484. unsigned new_row = 1;
  485. if (params.size() >= 1 && params[0] != 0)
  486. new_row = params[0];
  487. if (new_row > m_rows)
  488. new_row = m_rows;
  489. set_cursor(new_row - 1, cursor_column());
  490. }
  491. void Terminal::VPR(Parameters params)
  492. {
  493. unsigned num = 1;
  494. if (params.size() >= 1 && params[0] != 0)
  495. num = params[0];
  496. int new_row = cursor_row() + num;
  497. if (new_row >= m_rows)
  498. new_row = m_rows - 1;
  499. set_cursor(new_row, cursor_column());
  500. }
  501. void Terminal::HPA(Parameters params)
  502. {
  503. unsigned new_column = 1;
  504. if (params.size() >= 1 && params[0] != 0)
  505. new_column = params[0];
  506. if (new_column > m_columns)
  507. new_column = m_columns;
  508. set_cursor(cursor_row(), new_column - 1);
  509. }
  510. void Terminal::HPR(Parameters params)
  511. {
  512. unsigned num = 1;
  513. if (params.size() >= 1 && params[0] != 0)
  514. num = params[0];
  515. unsigned new_column = cursor_column() + num;
  516. if (new_column >= m_columns)
  517. new_column = m_columns - 1;
  518. set_cursor(cursor_row(), new_column);
  519. }
  520. void Terminal::ECH(Parameters params)
  521. {
  522. // Erase characters (without moving cursor)
  523. unsigned num = 1;
  524. if (params.size() >= 1 && params[0] != 0)
  525. num = params[0];
  526. // Clear num characters from the right of the cursor.
  527. auto clear_end = min<unsigned>(m_columns, cursor_column() + num - 1);
  528. dbgln_if(TERMINAL_DEBUG, "Erase characters {}-{} on line {}", cursor_column(), clear_end, cursor_row());
  529. clear_in_line(cursor_row(), cursor_column(), clear_end);
  530. }
  531. void Terminal::EL(Parameters params)
  532. {
  533. unsigned mode = 0;
  534. if (params.size() >= 1)
  535. mode = params[0];
  536. switch (mode) {
  537. case 0:
  538. dbgln_if(TERMINAL_DEBUG, "Clear line {} from cursor column ({}) to the end", cursor_row(), cursor_column());
  539. clear_in_line(cursor_row(), cursor_column(), m_columns - 1);
  540. break;
  541. case 1:
  542. dbgln_if(TERMINAL_DEBUG, "Clear line {} from the start to cursor column ({})", cursor_row(), cursor_column());
  543. clear_in_line(cursor_row(), 0, cursor_column());
  544. break;
  545. case 2:
  546. dbgln_if(TERMINAL_DEBUG, "Clear line {} completely", cursor_row());
  547. clear_in_line(cursor_row(), 0, m_columns - 1);
  548. break;
  549. default:
  550. unimplemented_csi_sequence(params, {}, 'K');
  551. break;
  552. }
  553. }
  554. void Terminal::ED(Parameters params)
  555. {
  556. unsigned mode = 0;
  557. if (params.size() >= 1)
  558. mode = params[0];
  559. switch (mode) {
  560. case 0:
  561. dbgln_if(TERMINAL_DEBUG, "Clear from cursor ({},{}) to end of screen", cursor_row(), cursor_column());
  562. clear_in_line(cursor_row(), cursor_column(), m_columns - 1);
  563. for (int row = cursor_row() + 1; row < m_rows; ++row)
  564. clear_in_line(row, 0, m_columns - 1);
  565. break;
  566. case 1:
  567. dbgln_if(TERMINAL_DEBUG, "Clear from beginning of screen to cursor ({},{})", cursor_row(), cursor_column());
  568. clear_in_line(cursor_row(), 0, cursor_column());
  569. for (int row = cursor_row() - 1; row >= 0; --row)
  570. clear_in_line(row, 0, m_columns - 1);
  571. break;
  572. case 2:
  573. clear();
  574. break;
  575. case 3:
  576. clear_history();
  577. break;
  578. default:
  579. unimplemented_csi_sequence(params, {}, 'J');
  580. break;
  581. }
  582. }
  583. void Terminal::SU(Parameters params)
  584. {
  585. unsigned count = 1;
  586. if (params.size() >= 1 && params[0] != 0)
  587. count = params[0];
  588. scroll_up(count);
  589. }
  590. void Terminal::SD(Parameters params)
  591. {
  592. unsigned count = 1;
  593. if (params.size() >= 1 && params[0] != 0)
  594. count = params[0];
  595. scroll_down(count);
  596. }
  597. void Terminal::DECSCUSR(Parameters params)
  598. {
  599. unsigned style = 1;
  600. if (params.size() >= 1 && params[0] != 0)
  601. style = params[0];
  602. switch (style) {
  603. case 1:
  604. m_client.set_cursor_shape(VT::CursorShape::Block);
  605. m_client.set_cursor_blinking(true);
  606. break;
  607. case 2:
  608. m_client.set_cursor_shape(VT::CursorShape::Block);
  609. m_client.set_cursor_blinking(false);
  610. break;
  611. case 3:
  612. m_client.set_cursor_shape(VT::CursorShape::Underline);
  613. m_client.set_cursor_blinking(true);
  614. break;
  615. case 4:
  616. m_client.set_cursor_shape(VT::CursorShape::Underline);
  617. m_client.set_cursor_blinking(false);
  618. break;
  619. case 5:
  620. m_client.set_cursor_shape(VT::CursorShape::Bar);
  621. m_client.set_cursor_blinking(true);
  622. break;
  623. case 6:
  624. m_client.set_cursor_shape(VT::CursorShape::Bar);
  625. m_client.set_cursor_blinking(false);
  626. break;
  627. default:
  628. dbgln("Unknown cursor style {}", style);
  629. }
  630. }
  631. void Terminal::IL(Parameters params)
  632. {
  633. size_t count = 1;
  634. if (params.size() >= 1 && params[0] != 0)
  635. count = params[0];
  636. if (!is_within_scroll_region(cursor_row())) {
  637. dbgln("Shenanigans! Tried to insert line outside the scroll region");
  638. return;
  639. }
  640. scroll_down(cursor_row(), m_scroll_region_bottom, count);
  641. }
  642. void Terminal::DA(Parameters)
  643. {
  644. emit_string("\033[?1;0c"sv);
  645. }
  646. void Terminal::DL(Parameters params)
  647. {
  648. size_t count = 1;
  649. if (params.size() >= 1 && params[0] != 0)
  650. count = params[0];
  651. if (!is_within_scroll_region(cursor_row())) {
  652. dbgln("Shenanigans! Tried to delete line outside the scroll region");
  653. return;
  654. }
  655. scroll_up(cursor_row(), m_scroll_region_bottom, count);
  656. }
  657. void Terminal::DCH(Parameters params)
  658. {
  659. int num = 1;
  660. if (params.size() >= 1 && params[0] != 0)
  661. num = params[0];
  662. num = min<int>(num, columns() - cursor_column());
  663. scroll_left(cursor_row(), cursor_column(), num);
  664. }
  665. void Terminal::linefeed()
  666. {
  667. u16 new_row = cursor_row();
  668. #ifndef KERNEL
  669. if (!m_controls_are_logically_generated)
  670. active_buffer()[new_row]->set_terminated(m_column_before_carriage_return.value_or(cursor_column()));
  671. #endif
  672. if (cursor_row() == m_scroll_region_bottom) {
  673. scroll_up();
  674. } else {
  675. ++new_row;
  676. };
  677. // We shouldn't jump to the first column after receiving a line feed.
  678. // The TTY will take care of generating the carriage return.
  679. set_cursor(new_row, cursor_column());
  680. }
  681. void Terminal::carriage_return()
  682. {
  683. dbgln_if(TERMINAL_DEBUG, "Carriage return");
  684. m_column_before_carriage_return = cursor_column();
  685. set_cursor(cursor_row(), 0);
  686. }
  687. void Terminal::scroll_up(size_t count)
  688. {
  689. scroll_up(m_scroll_region_top, m_scroll_region_bottom, count);
  690. }
  691. void Terminal::scroll_down(size_t count)
  692. {
  693. scroll_down(m_scroll_region_top, m_scroll_region_bottom, count);
  694. }
  695. #ifndef KERNEL
  696. // Insert `count` blank lines at the bottom of the region. Text moves up, top lines get added to the scrollback.
  697. void Terminal::scroll_up(u16 region_top, u16 region_bottom, size_t count)
  698. {
  699. VERIFY(region_top <= region_bottom);
  700. VERIFY(region_bottom < rows());
  701. // Only the specified region should be affected.
  702. size_t region_size = region_bottom - region_top + 1;
  703. count = min(count, region_size);
  704. dbgln_if(TERMINAL_DEBUG, "Scroll up {} lines in region {}-{}", count, region_top, region_bottom);
  705. // NOTE: We have to invalidate the cursor first.
  706. invalidate_cursor();
  707. int history_delta = -count;
  708. bool should_move_to_scrollback = !m_use_alternate_screen_buffer && max_history_size() != 0;
  709. if (should_move_to_scrollback) {
  710. auto remaining_lines = max_history_size() - history_size();
  711. history_delta = (count > remaining_lines) ? remaining_lines - count : 0;
  712. for (size_t i = 0; i < count; ++i)
  713. add_line_to_history(move(active_buffer().at(region_top + i)));
  714. }
  715. // Move lines into their new place.
  716. for (u16 row = region_top; row + count <= region_bottom; ++row)
  717. swap(active_buffer().at(row), active_buffer().at(row + count));
  718. // Clear 'new' lines at the bottom.
  719. if (should_move_to_scrollback) {
  720. // Since we moved the previous lines into history, we can't just clear them.
  721. for (u16 row = region_bottom + 1 - count; row <= region_bottom; ++row)
  722. active_buffer().at(row) = make<Line>(columns());
  723. } else {
  724. // The new lines haven't been moved and we don't want to leak memory.
  725. for (u16 row = region_bottom + 1 - count; row <= region_bottom; ++row)
  726. active_buffer()[row]->clear();
  727. }
  728. // Set dirty flag on swapped lines.
  729. // The other lines have implicitly been set dirty by being cleared.
  730. for (u16 row = region_top; row + count <= region_bottom; ++row)
  731. active_buffer()[row]->set_dirty(true);
  732. m_client.terminal_history_changed(history_delta);
  733. }
  734. // Insert `count` blank lines at the top of the region. Text moves down. Does not affect the scrollback buffer.
  735. void Terminal::scroll_down(u16 region_top, u16 region_bottom, size_t count)
  736. {
  737. VERIFY(region_top <= region_bottom);
  738. VERIFY(region_bottom < rows());
  739. // Only the specified region should be affected.
  740. size_t region_size = region_bottom - region_top + 1;
  741. count = min(count, region_size);
  742. dbgln_if(TERMINAL_DEBUG, "Scroll down {} lines in region {}-{}", count, region_top, region_bottom);
  743. // NOTE: We have to invalidate the cursor first.
  744. invalidate_cursor();
  745. // Move lines into their new place.
  746. for (int row = region_bottom; row >= static_cast<int>(region_top + count); --row)
  747. swap(active_buffer().at(row), active_buffer().at(row - count));
  748. // Clear the 'new' lines at the top.
  749. for (u16 row = region_top; row < region_top + count; ++row)
  750. active_buffer()[row]->clear();
  751. // Set dirty flag on swapped lines.
  752. // The other lines have implicitly been set dirty by being cleared.
  753. for (u16 row = region_top + count; row <= region_bottom; ++row)
  754. active_buffer()[row]->set_dirty(true);
  755. }
  756. // Insert `count` blank cells at the end of the line. Text moves left.
  757. void Terminal::scroll_left(u16 row, u16 column, size_t count)
  758. {
  759. VERIFY(row < rows());
  760. VERIFY(column < columns());
  761. count = min<size_t>(count, columns() - column);
  762. dbgln_if(TERMINAL_DEBUG, "Scroll left {} columns from line {} column {}", count, row, column);
  763. auto& line = active_buffer()[row];
  764. for (size_t i = column; i < columns() - count; ++i)
  765. swap(line->cell_at(i), line->cell_at(i + count));
  766. clear_in_line(row, columns() - count, columns() - 1);
  767. line->set_dirty(true);
  768. }
  769. // Insert `count` blank cells after `row`. Text moves right.
  770. void Terminal::scroll_right(u16 row, u16 column, size_t count)
  771. {
  772. VERIFY(row < rows());
  773. VERIFY(column < columns());
  774. count = min<size_t>(count, columns() - column);
  775. dbgln_if(TERMINAL_DEBUG, "Scroll right {} columns from line {} column {}", count, row, column);
  776. auto& line = active_buffer()[row];
  777. for (int i = columns() - 1; i >= static_cast<int>(column + count); --i)
  778. swap(line->cell_at(i), line->cell_at(i - count));
  779. clear_in_line(row, column, column + count - 1);
  780. line->set_dirty(true);
  781. }
  782. void Terminal::put_character_at(unsigned row, unsigned column, u32 code_point)
  783. {
  784. VERIFY(row < rows());
  785. VERIFY(column < columns());
  786. auto& line = active_buffer()[row];
  787. line->set_code_point(column, code_point);
  788. line->attribute_at(column) = m_current_state.attribute;
  789. line->attribute_at(column).flags |= Attribute::Flags::Touched;
  790. line->set_dirty(true);
  791. m_last_code_point = code_point;
  792. }
  793. void Terminal::clear_in_line(u16 row, u16 first_column, u16 last_column)
  794. {
  795. VERIFY(row < rows());
  796. active_buffer()[row]->clear_range(first_column, last_column, m_current_state.attribute);
  797. }
  798. #endif
  799. void Terminal::set_cursor(unsigned a_row, unsigned a_column, bool skip_debug)
  800. {
  801. unsigned row = min(a_row, m_rows - 1u);
  802. unsigned column = min(a_column, m_columns - 1u);
  803. m_stomp = false;
  804. if (row == cursor_row() && column == cursor_column())
  805. return;
  806. VERIFY(row < rows());
  807. VERIFY(column < columns());
  808. invalidate_cursor();
  809. m_current_state.cursor.row = row;
  810. m_current_state.cursor.column = column;
  811. invalidate_cursor();
  812. if (!skip_debug)
  813. dbgln_if(TERMINAL_DEBUG, "Set cursor position: {},{}", cursor_row(), cursor_column());
  814. }
  815. void Terminal::NEL()
  816. {
  817. if (cursor_row() == m_scroll_region_bottom)
  818. scroll_up();
  819. else
  820. set_cursor(cursor_row() + 1, 0);
  821. }
  822. void Terminal::IND()
  823. {
  824. // Not equivalent to CUD: if we are at the bottom margin, we have to scroll up.
  825. if (cursor_row() == m_scroll_region_bottom)
  826. scroll_up();
  827. else
  828. set_cursor(cursor_row() + 1, cursor_column());
  829. }
  830. void Terminal::RI()
  831. {
  832. // Not equivalent to CUU : if we at the top margin , we have to scroll down.
  833. if (cursor_row() == m_scroll_region_top)
  834. scroll_down();
  835. else
  836. set_cursor(cursor_row() - 1, cursor_column());
  837. }
  838. void Terminal::DECFI()
  839. {
  840. if (cursor_column() == columns() - 1)
  841. scroll_left(cursor_row(), 0, 1);
  842. else
  843. set_cursor(cursor_row(), cursor_column() + 1);
  844. }
  845. void Terminal::DECBI()
  846. {
  847. if (cursor_column() == 0)
  848. scroll_right(cursor_row(), 0, 1);
  849. else
  850. set_cursor(cursor_row(), cursor_column() - 1);
  851. }
  852. void Terminal::DECIC(Parameters params)
  853. {
  854. unsigned num = 1;
  855. if (params.size() >= 1 && params[0] != 0)
  856. num = params[0];
  857. num = min<unsigned>(num, columns() - cursor_column());
  858. for (unsigned row = cursor_row(); row <= m_scroll_region_bottom; ++row)
  859. scroll_right(row, cursor_column(), num);
  860. }
  861. void Terminal::DECDC(Parameters params)
  862. {
  863. unsigned num = 1;
  864. if (params.size() >= 1 && params[0] != 0)
  865. num = params[0];
  866. num = min<unsigned>(num, columns() - cursor_column());
  867. for (unsigned row = cursor_row(); row <= m_scroll_region_bottom; ++row)
  868. scroll_left(row, cursor_column(), num);
  869. }
  870. void Terminal::DECPNM()
  871. {
  872. dbgln("FIXME: implement setting the keypad to numeric mode");
  873. }
  874. void Terminal::DECPAM()
  875. {
  876. dbgln("FIXME: implement setting the keypad to application mode");
  877. }
  878. void Terminal::DSR(Parameters params)
  879. {
  880. if (params.size() == 1 && params[0] == 5) {
  881. // Device status
  882. emit_string("\033[0n"sv); // Terminal status OK!
  883. } else if (params.size() == 1 && params[0] == 6) {
  884. // Cursor position query
  885. StringBuilder builder;
  886. MUST(builder.try_appendff("\e[{};{}R", cursor_row() + 1, cursor_column() + 1)); // StringBuilder's inline capacity of 256 is enough to guarantee no allocations
  887. emit_string(builder.string_view());
  888. } else {
  889. dbgln("Unknown DSR");
  890. }
  891. }
  892. void Terminal::ICH(Parameters params)
  893. {
  894. unsigned num = 1;
  895. if (params.size() >= 1 && params[0] != 0)
  896. num = params[0];
  897. num = min<unsigned>(num, columns() - cursor_column());
  898. scroll_right(cursor_row(), cursor_column(), num);
  899. }
  900. void Terminal::on_input(u8 byte)
  901. {
  902. m_parser.on_input(byte);
  903. }
  904. void Terminal::emit_code_point(u32 code_point)
  905. {
  906. auto working_set = m_working_sets[m_active_working_set_index];
  907. code_point = m_character_set_translator.translate_code_point(working_set, code_point);
  908. auto new_column = cursor_column() + 1;
  909. if (new_column < columns()) {
  910. put_character_at(cursor_row(), cursor_column(), code_point);
  911. set_cursor(cursor_row(), new_column, true);
  912. return;
  913. }
  914. if (m_stomp) {
  915. m_stomp = false;
  916. TemporaryChange change { m_controls_are_logically_generated, true };
  917. carriage_return();
  918. linefeed();
  919. put_character_at(cursor_row(), cursor_column(), code_point);
  920. set_cursor(cursor_row(), 1);
  921. } else {
  922. // Curious: We wait once on the right-hand side
  923. m_stomp = true;
  924. put_character_at(cursor_row(), cursor_column(), code_point);
  925. }
  926. }
  927. void Terminal::execute_control_code(u8 code)
  928. {
  929. ArmedScopeGuard clear_position_before_cr {
  930. [&] {
  931. m_column_before_carriage_return.clear();
  932. }
  933. };
  934. switch (code) {
  935. case '\a':
  936. m_client.beep();
  937. return;
  938. case '\b':
  939. if (cursor_column()) {
  940. set_cursor(cursor_row(), cursor_column() - 1);
  941. return;
  942. }
  943. return;
  944. case '\t': {
  945. for (unsigned i = cursor_column() + 1; i < columns(); ++i) {
  946. if (m_horizontal_tabs[i]) {
  947. set_cursor(cursor_row(), i);
  948. return;
  949. }
  950. }
  951. return;
  952. }
  953. case '\n':
  954. case '\v':
  955. case '\f':
  956. if (m_column_before_carriage_return == m_columns - 1)
  957. m_column_before_carriage_return = m_columns;
  958. linefeed();
  959. return;
  960. case '\r':
  961. carriage_return();
  962. clear_position_before_cr.disarm();
  963. return;
  964. default:
  965. unimplemented_control_code(code);
  966. }
  967. }
  968. void Terminal::execute_escape_sequence(Intermediates intermediates, bool ignore, u8 last_byte)
  969. {
  970. // FIXME: Handle it somehow?
  971. if (ignore)
  972. dbgln("Escape sequence has its ignore flag set.");
  973. if (intermediates.size() == 0) {
  974. switch (last_byte) {
  975. case 'D':
  976. IND();
  977. return;
  978. case 'E':
  979. NEL();
  980. return;
  981. case 'M':
  982. RI();
  983. return;
  984. case '\\':
  985. // ST (string terminator) -- do nothing
  986. return;
  987. case '6':
  988. DECBI();
  989. return;
  990. case '7':
  991. DECSC();
  992. return;
  993. case '8':
  994. DECRC();
  995. return;
  996. case '9':
  997. DECFI();
  998. return;
  999. case '=':
  1000. DECPAM();
  1001. return;
  1002. case '>':
  1003. DECPNM();
  1004. return;
  1005. }
  1006. unimplemented_escape_sequence(intermediates, last_byte);
  1007. return;
  1008. }
  1009. char intermediate = intermediates[0];
  1010. switch (intermediate) {
  1011. case '#':
  1012. switch (last_byte) {
  1013. case '8':
  1014. // Confidence Test - Fill screen with E's
  1015. for (size_t row = 0; row < m_rows; ++row) {
  1016. for (size_t column = 0; column < m_columns; ++column) {
  1017. put_character_at(row, column, 'E');
  1018. }
  1019. }
  1020. return;
  1021. }
  1022. break;
  1023. case '(':
  1024. case ')':
  1025. case '*':
  1026. case '+':
  1027. // Determine G0..G3 index
  1028. size_t working_set_index = intermediate - '(';
  1029. CharacterSet new_set;
  1030. switch (last_byte) {
  1031. case 'B':
  1032. new_set = CharacterSet::Iso_8859_1;
  1033. break;
  1034. case '0':
  1035. new_set = CharacterSet::VT100;
  1036. break;
  1037. case 'U':
  1038. new_set = CharacterSet::Null;
  1039. break;
  1040. case 'K':
  1041. new_set = CharacterSet::UserDefined;
  1042. break;
  1043. default:
  1044. unimplemented_escape_sequence(intermediates, last_byte);
  1045. return;
  1046. }
  1047. dbgln_if(TERMINAL_DEBUG, "Setting G{} working set to character set {}", working_set_index, to_underlying(new_set));
  1048. VERIFY(working_set_index <= 3);
  1049. m_working_sets[working_set_index] = new_set;
  1050. return;
  1051. }
  1052. unimplemented_escape_sequence(intermediates, last_byte);
  1053. }
  1054. void Terminal::execute_csi_sequence(Parameters parameters, Intermediates intermediates, bool ignore, u8 last_byte)
  1055. {
  1056. // FIXME: Handle it somehow?
  1057. if (ignore)
  1058. dbgln("CSI sequence has its ignore flag set.");
  1059. if (intermediates.is_empty()) {
  1060. switch (last_byte) {
  1061. case '@':
  1062. return ICH(parameters);
  1063. case 'A':
  1064. return CUU(parameters);
  1065. case 'B':
  1066. return CUD(parameters);
  1067. case 'C':
  1068. return CUF(parameters);
  1069. case 'D':
  1070. return CUB(parameters);
  1071. case 'E':
  1072. return CNL(parameters);
  1073. case 'F':
  1074. return CPL(parameters);
  1075. case 'G':
  1076. return CHA(parameters);
  1077. case 'H':
  1078. return CUP(parameters);
  1079. case 'J':
  1080. return ED(parameters);
  1081. case 'K':
  1082. return EL(parameters);
  1083. case 'L':
  1084. return IL(parameters);
  1085. case 'M':
  1086. return DL(parameters);
  1087. case 'P':
  1088. return DCH(parameters);
  1089. case 'S':
  1090. return SU(parameters);
  1091. case 'T':
  1092. return SD(parameters);
  1093. case 'X':
  1094. return ECH(parameters);
  1095. case '`':
  1096. return HPA(parameters);
  1097. case 'a':
  1098. return HPR(parameters);
  1099. case 'b':
  1100. return REP(parameters);
  1101. case 'c':
  1102. return DA(parameters);
  1103. case 'd':
  1104. return VPA(parameters);
  1105. case 'e':
  1106. return VPR(parameters);
  1107. case 'f':
  1108. return HVP(parameters);
  1109. case 'h':
  1110. return SM(parameters);
  1111. case 'l':
  1112. return RM(parameters);
  1113. case 'm':
  1114. return SGR(parameters);
  1115. case 'n':
  1116. return DSR(parameters);
  1117. case 'r':
  1118. return DECSTBM(parameters);
  1119. case 's':
  1120. return SCOSC();
  1121. case 't':
  1122. return XTERM_WM(parameters);
  1123. case 'u':
  1124. return SCORC();
  1125. }
  1126. } else if (intermediates.size() == 1 && intermediates[0] == '?') {
  1127. switch (last_byte) {
  1128. case 'h':
  1129. return DECSET(parameters);
  1130. case 'l':
  1131. return DECRST(parameters);
  1132. }
  1133. } else if (intermediates.size() == 1 && intermediates[0] == '\'') {
  1134. switch (last_byte) {
  1135. case '}':
  1136. return DECIC(parameters);
  1137. case '~':
  1138. return DECDC(parameters);
  1139. }
  1140. } else if (intermediates.size() == 1 && intermediates[0] == ' ') {
  1141. switch (last_byte) {
  1142. case 'q':
  1143. return DECSCUSR(parameters);
  1144. }
  1145. }
  1146. unimplemented_csi_sequence(parameters, intermediates, last_byte);
  1147. }
  1148. void Terminal::execute_osc_sequence(OscParameters parameters, u8 last_byte)
  1149. {
  1150. auto stringview_ify = [&](size_t param_idx) {
  1151. return StringView(parameters[param_idx]);
  1152. };
  1153. if (parameters.size() == 0 || parameters[0].is_empty()) {
  1154. unimplemented_osc_sequence(parameters, last_byte);
  1155. return;
  1156. }
  1157. auto command_number = stringview_ify(0).to_uint();
  1158. if (!command_number.has_value()) {
  1159. unimplemented_osc_sequence(parameters, last_byte);
  1160. return;
  1161. }
  1162. switch (command_number.value()) {
  1163. case 0:
  1164. case 1:
  1165. case 2:
  1166. if (parameters.size() < 2) {
  1167. dbgln("Attempted to set window title without any parameters");
  1168. } else {
  1169. // FIXME: the split breaks titles containing semicolons.
  1170. // Should we expose the raw OSC string from the parser? Or join by semicolon?
  1171. #ifndef KERNEL
  1172. m_current_window_title = stringview_ify(1).to_deprecated_string();
  1173. m_client.set_window_title(m_current_window_title);
  1174. #endif
  1175. }
  1176. break;
  1177. case 8:
  1178. #ifndef KERNEL
  1179. if (parameters.size() < 3) {
  1180. dbgln("Attempted to set href but gave too few parameters");
  1181. } else if (parameters[1].is_empty() && parameters[2].is_empty()) {
  1182. // Clear hyperlink
  1183. m_current_state.attribute.href = DeprecatedString();
  1184. m_current_state.attribute.href_id = DeprecatedString();
  1185. } else {
  1186. m_current_state.attribute.href = stringview_ify(2);
  1187. // FIXME: Respect the provided ID
  1188. m_current_state.attribute.href_id = DeprecatedString::number(m_next_href_id++);
  1189. }
  1190. #endif
  1191. break;
  1192. case 9:
  1193. if (parameters.size() < 2)
  1194. dbgln("Atttempted to set window progress but gave too few parameters");
  1195. else if (parameters.size() == 2)
  1196. m_client.set_window_progress(stringview_ify(1).to_int().value_or(-1), 0);
  1197. else
  1198. m_client.set_window_progress(stringview_ify(1).to_int().value_or(-1), stringview_ify(2).to_int().value_or(0));
  1199. break;
  1200. default:
  1201. unimplemented_osc_sequence(parameters, last_byte);
  1202. }
  1203. }
  1204. void Terminal::dcs_hook(Parameters, Intermediates, bool, u8)
  1205. {
  1206. dbgln("Received DCS parameters, but we don't support it yet");
  1207. }
  1208. void Terminal::receive_dcs_char(u8 byte)
  1209. {
  1210. dbgln_if(TERMINAL_DEBUG, "DCS string character {:c}", byte);
  1211. }
  1212. void Terminal::execute_dcs_sequence()
  1213. {
  1214. }
  1215. void Terminal::inject_string(StringView str)
  1216. {
  1217. for (size_t i = 0; i < str.length(); ++i)
  1218. on_input(str[i]);
  1219. }
  1220. void Terminal::emit_string(StringView string)
  1221. {
  1222. m_client.emit((u8 const*)string.characters_without_null_termination(), string.length());
  1223. }
  1224. void Terminal::handle_key_press(KeyCode key, u32 code_point, u8 flags)
  1225. {
  1226. bool ctrl = flags & Mod_Ctrl;
  1227. bool alt = flags & Mod_Alt;
  1228. bool shift = flags & Mod_Shift;
  1229. unsigned modifier_mask = int(shift) + (int(alt) << 1) + (int(ctrl) << 2);
  1230. auto emit_final_with_modifier = [this, modifier_mask](char final) {
  1231. char escape_character = m_cursor_keys_mode == CursorKeysMode::Application ? 'O' : '[';
  1232. StringBuilder builder;
  1233. if (modifier_mask)
  1234. MUST(builder.try_appendff("\e{}1;{}{:c}", escape_character, modifier_mask + 1, final)); // StringBuilder's inline capacity of 256 is enough to guarantee no allocations
  1235. else
  1236. MUST(builder.try_appendff("\e{}{:c}", escape_character, final)); // StringBuilder's inline capacity of 256 is enough to guarantee no allocations
  1237. emit_string(builder.string_view());
  1238. };
  1239. auto emit_tilde_with_modifier = [this, modifier_mask](unsigned num) {
  1240. StringBuilder builder;
  1241. if (modifier_mask)
  1242. MUST(builder.try_appendff("\e[{};{}~", num, modifier_mask + 1)); // StringBuilder's inline capacity of 256 is enough to guarantee no allocations
  1243. else
  1244. MUST(builder.try_appendff("\e[{}~", num)); // StringBuilder's inline capacity of 256 is enough to guarantee no allocations
  1245. emit_string(builder.string_view());
  1246. };
  1247. switch (key) {
  1248. case KeyCode::Key_Up:
  1249. emit_final_with_modifier('A');
  1250. return;
  1251. case KeyCode::Key_Down:
  1252. emit_final_with_modifier('B');
  1253. return;
  1254. case KeyCode::Key_Right:
  1255. emit_final_with_modifier('C');
  1256. return;
  1257. case KeyCode::Key_Left:
  1258. emit_final_with_modifier('D');
  1259. return;
  1260. case KeyCode::Key_Insert:
  1261. emit_tilde_with_modifier(2);
  1262. return;
  1263. case KeyCode::Key_Delete:
  1264. emit_tilde_with_modifier(3);
  1265. return;
  1266. case KeyCode::Key_Home:
  1267. emit_final_with_modifier('H');
  1268. return;
  1269. case KeyCode::Key_End:
  1270. emit_final_with_modifier('F');
  1271. return;
  1272. case KeyCode::Key_PageUp:
  1273. emit_tilde_with_modifier(5);
  1274. return;
  1275. case KeyCode::Key_PageDown:
  1276. emit_tilde_with_modifier(6);
  1277. return;
  1278. case KeyCode::Key_Backspace:
  1279. if (ctrl) {
  1280. // This is an extension that allows Editor.cpp to delete whole words when
  1281. // Ctrl+Backspace is pressed. Ctrl cannot be transmitted without a CSI, and
  1282. // ANSI delete (127) is within the valid range for CSI codes in Editor.cpp.
  1283. // The code also has the same behavior as backspace when emitted with no CSI,
  1284. // though the backspace code (8) is preserved when Ctrl is not pressed.
  1285. emit_final_with_modifier(127);
  1286. return;
  1287. }
  1288. break;
  1289. case KeyCode::Key_Return:
  1290. // The standard says that CR should be generated by the return key.
  1291. // The TTY will take care of translating it to CR LF for the terminal.
  1292. emit_string("\r"sv);
  1293. return;
  1294. default:
  1295. break;
  1296. }
  1297. if (!code_point) {
  1298. // Probably a modifier being pressed.
  1299. return;
  1300. }
  1301. if (shift && key == KeyCode::Key_Tab) {
  1302. emit_string("\033[Z"sv);
  1303. return;
  1304. }
  1305. // Key event was not one of the above special cases,
  1306. // attempt to treat it as a character...
  1307. if (ctrl) {
  1308. if (code_point >= 'a' && code_point <= 'z') {
  1309. code_point = code_point - 'a' + 1;
  1310. } else if (code_point == '\\') {
  1311. code_point = 0x1c;
  1312. }
  1313. }
  1314. // Alt modifier sends escape prefix.
  1315. if (alt)
  1316. emit_string("\033"sv);
  1317. StringBuilder sb;
  1318. sb.append_code_point(code_point);
  1319. emit_string(sb.string_view());
  1320. }
  1321. void Terminal::unimplemented_control_code(u8 code)
  1322. {
  1323. dbgln_if(TERMINAL_DEBUG, "Unimplemented control code {:02x}", code);
  1324. }
  1325. void Terminal::unimplemented_escape_sequence(Intermediates intermediates, u8 last_byte)
  1326. {
  1327. StringBuilder builder;
  1328. builder.appendff("Unimplemented escape sequence {:c}", last_byte);
  1329. if (!intermediates.is_empty()) {
  1330. builder.append(", intermediates: "sv);
  1331. for (size_t i = 0; i < intermediates.size(); ++i)
  1332. builder.append((char)intermediates[i]);
  1333. }
  1334. dbgln("{}", builder.string_view());
  1335. }
  1336. void Terminal::unimplemented_csi_sequence(Parameters parameters, Intermediates intermediates, u8 last_byte)
  1337. {
  1338. StringBuilder builder;
  1339. builder.appendff("Unimplemented CSI sequence: {:c}", last_byte);
  1340. if (!parameters.is_empty()) {
  1341. builder.append(", parameters: ["sv);
  1342. for (size_t i = 0; i < parameters.size(); ++i)
  1343. builder.appendff("{}{}", (i == 0) ? "" : ", ", parameters[i]);
  1344. builder.append("]"sv);
  1345. }
  1346. if (!intermediates.is_empty()) {
  1347. builder.append(", intermediates:"sv);
  1348. for (size_t i = 0; i < intermediates.size(); ++i)
  1349. builder.append((char)intermediates[i]);
  1350. }
  1351. dbgln("{}", builder.string_view());
  1352. }
  1353. void Terminal::unimplemented_osc_sequence(OscParameters parameters, u8 last_byte)
  1354. {
  1355. StringBuilder builder;
  1356. builder.appendff("Unimplemented OSC sequence parameters: (bel_terminated={}) [ ", last_byte == '\a');
  1357. bool first = true;
  1358. for (auto parameter : parameters) {
  1359. if (!first)
  1360. builder.append(", "sv);
  1361. builder.append('[');
  1362. for (auto character : parameter)
  1363. builder.append((char)character);
  1364. builder.append(']');
  1365. first = false;
  1366. }
  1367. builder.append(" ]"sv);
  1368. dbgln("{}", builder.string_view());
  1369. }
  1370. #ifndef KERNEL
  1371. void Terminal::set_size(u16 columns, u16 rows)
  1372. {
  1373. if (!columns)
  1374. columns = 1;
  1375. if (!rows)
  1376. rows = 1;
  1377. if (columns == m_columns && rows == m_rows)
  1378. return;
  1379. // If we're making the terminal larger (column-wise), start at the end and go up, taking cells from the line below.
  1380. // otherwise start at the beginning and go down, pushing cells into the line below.
  1381. auto resize_and_rewrap = [&](auto& buffer, auto& old_cursor) {
  1382. auto cursor_on_line = [&](auto index) {
  1383. return index == old_cursor.row ? &old_cursor : nullptr;
  1384. };
  1385. // Two passes, one from top to bottom, another from bottom to top
  1386. for (size_t pass = 0; pass < 2; ++pass) {
  1387. auto forwards = (pass == 0) ^ (columns < m_columns);
  1388. if (forwards) {
  1389. for (size_t i = 1; i <= buffer.size(); ++i) {
  1390. auto is_at_seam = i == 1;
  1391. Line* next_line = is_at_seam ? nullptr : buffer[buffer.size() - i + 1].ptr();
  1392. Line* line = buffer[buffer.size() - i].ptr();
  1393. auto next_cursor = cursor_on_line(buffer.size() - i + 1);
  1394. line->rewrap(columns, next_line, next_cursor ?: cursor_on_line(buffer.size() - i), !!next_cursor);
  1395. }
  1396. } else {
  1397. for (size_t i = 0; i < buffer.size(); ++i) {
  1398. auto is_at_seam = i + 1 == buffer.size();
  1399. Line* next_line = is_at_seam ? nullptr : buffer[i + 1].ptr();
  1400. auto next_cursor = cursor_on_line(i + 1);
  1401. buffer[i]->rewrap(columns, next_line, next_cursor ?: cursor_on_line(i), !!next_cursor);
  1402. }
  1403. }
  1404. Queue<size_t> lines_to_reevaluate;
  1405. for (size_t i = 0; i < buffer.size(); ++i) {
  1406. if (buffer[i]->length() != columns)
  1407. lines_to_reevaluate.enqueue(i);
  1408. }
  1409. while (!lines_to_reevaluate.is_empty()) {
  1410. auto index = lines_to_reevaluate.dequeue();
  1411. auto is_at_seam = index + 1 == buffer.size();
  1412. Line* const next_line = is_at_seam ? nullptr : buffer[index + 1].ptr();
  1413. Line* const line = buffer[index].ptr();
  1414. auto next_cursor = cursor_on_line(index + 1);
  1415. line->rewrap(columns, next_line, next_cursor ?: cursor_on_line(index), !!next_cursor);
  1416. if (line->length() > columns) {
  1417. auto current_cursor = cursor_on_line(index);
  1418. // Split the line into two (or more)
  1419. ++index;
  1420. buffer.insert(index, make<Line>(0));
  1421. VERIFY(buffer[index]->length() == 0);
  1422. line->rewrap(columns, buffer[index].ptr(), current_cursor, false);
  1423. // If we inserted a line and the old cursor was after that line, increment its row
  1424. if (!current_cursor && old_cursor.row >= index)
  1425. ++old_cursor.row;
  1426. if (buffer[index]->length() != columns)
  1427. lines_to_reevaluate.enqueue(index);
  1428. }
  1429. if (next_line && next_line->length() != columns)
  1430. lines_to_reevaluate.enqueue(index + 1);
  1431. }
  1432. }
  1433. for (auto& line : buffer)
  1434. line->set_length(columns);
  1435. return old_cursor;
  1436. };
  1437. auto old_history_size = m_history.size();
  1438. m_history.extend(move(m_normal_screen_buffer));
  1439. CursorPosition cursor_tracker { cursor_row() + old_history_size, cursor_column() };
  1440. resize_and_rewrap(m_history, cursor_tracker);
  1441. if (auto extra_lines = m_history.size() - rows) {
  1442. while (extra_lines > 0) {
  1443. if (m_history.size() <= cursor_tracker.row)
  1444. break;
  1445. if (m_history.last()->is_empty()) {
  1446. if (m_history.size() >= 2 && m_history[m_history.size() - 2]->termination_column().has_value())
  1447. break;
  1448. --extra_lines;
  1449. (void)m_history.take_last();
  1450. continue;
  1451. }
  1452. break;
  1453. }
  1454. }
  1455. // FIXME: This can use a more performant way to move the last N entries
  1456. // from the history into the normal buffer
  1457. m_normal_screen_buffer.ensure_capacity(rows);
  1458. while (m_normal_screen_buffer.size() < rows) {
  1459. if (!m_history.is_empty())
  1460. m_normal_screen_buffer.prepend(m_history.take_last());
  1461. else
  1462. m_normal_screen_buffer.unchecked_append(make<Line>(columns));
  1463. }
  1464. cursor_tracker.row -= m_history.size();
  1465. if (m_history.size() != old_history_size) {
  1466. m_client.terminal_history_changed(-old_history_size);
  1467. m_client.terminal_history_changed(m_history.size());
  1468. }
  1469. CursorPosition dummy_cursor_tracker {};
  1470. resize_and_rewrap(m_alternate_screen_buffer, dummy_cursor_tracker);
  1471. if (m_alternate_screen_buffer.size() > rows)
  1472. m_alternate_screen_buffer.remove(0, m_alternate_screen_buffer.size() - rows);
  1473. if (rows > m_rows) {
  1474. while (m_normal_screen_buffer.size() < rows)
  1475. m_normal_screen_buffer.append(make<Line>(columns));
  1476. while (m_alternate_screen_buffer.size() < rows)
  1477. m_alternate_screen_buffer.append(make<Line>(columns));
  1478. } else {
  1479. m_normal_screen_buffer.shrink(rows);
  1480. m_alternate_screen_buffer.shrink(rows);
  1481. }
  1482. m_columns = columns;
  1483. m_rows = rows;
  1484. m_scroll_region_top = 0;
  1485. m_scroll_region_bottom = rows - 1;
  1486. m_current_state.cursor.clamp(m_rows - 1, m_columns - 1);
  1487. m_normal_saved_state.cursor.clamp(m_rows - 1, m_columns - 1);
  1488. m_alternate_saved_state.cursor.clamp(m_rows - 1, m_columns - 1);
  1489. m_saved_cursor_position.clamp(m_rows - 1, m_columns - 1);
  1490. m_horizontal_tabs.resize(columns);
  1491. for (unsigned i = 0; i < columns; ++i)
  1492. m_horizontal_tabs[i] = (i % 8) == 0;
  1493. // Rightmost column is always last tab on line.
  1494. m_horizontal_tabs[columns - 1] = 1;
  1495. set_cursor(cursor_tracker.row, cursor_tracker.column);
  1496. m_client.terminal_did_resize(m_columns, m_rows);
  1497. dbgln_if(TERMINAL_DEBUG, "Set terminal size: {}x{}", m_rows, m_columns);
  1498. }
  1499. #endif
  1500. #ifndef KERNEL
  1501. void Terminal::invalidate_cursor()
  1502. {
  1503. if (cursor_row() < active_buffer().size())
  1504. active_buffer()[cursor_row()]->set_dirty(true);
  1505. }
  1506. Attribute Terminal::attribute_at(Position const& position) const
  1507. {
  1508. if (!position.is_valid())
  1509. return {};
  1510. if (position.row() >= static_cast<int>(line_count()))
  1511. return {};
  1512. auto& line = this->line(position.row());
  1513. if (static_cast<size_t>(position.column()) >= line.length())
  1514. return {};
  1515. return line.attribute_at(position.column());
  1516. }
  1517. #endif
  1518. }