TerminalWidget.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "TerminalWidget.h"
  7. #include <AK/LexicalPath.h>
  8. #include <AK/StdLibExtras.h>
  9. #include <AK/String.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/TemporaryChange.h>
  12. #include <AK/Utf32View.h>
  13. #include <AK/Utf8View.h>
  14. #include <LibCore/ConfigFile.h>
  15. #include <LibCore/MimeData.h>
  16. #include <LibDesktop/AppFile.h>
  17. #include <LibDesktop/Launcher.h>
  18. #include <LibGUI/Action.h>
  19. #include <LibGUI/Application.h>
  20. #include <LibGUI/Clipboard.h>
  21. #include <LibGUI/DragOperation.h>
  22. #include <LibGUI/Icon.h>
  23. #include <LibGUI/Menu.h>
  24. #include <LibGUI/Painter.h>
  25. #include <LibGUI/Scrollbar.h>
  26. #include <LibGUI/Window.h>
  27. #include <LibGfx/Font.h>
  28. #include <LibGfx/FontDatabase.h>
  29. #include <LibGfx/Palette.h>
  30. #include <LibGfx/StylePainter.h>
  31. #include <ctype.h>
  32. #include <errno.h>
  33. #include <math.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <sys/ioctl.h>
  38. #include <unistd.h>
  39. namespace VT {
  40. void TerminalWidget::set_pty_master_fd(int fd)
  41. {
  42. m_ptm_fd = fd;
  43. if (m_ptm_fd == -1) {
  44. m_notifier = nullptr;
  45. return;
  46. }
  47. m_notifier = Core::Notifier::construct(m_ptm_fd, Core::Notifier::Read);
  48. m_notifier->on_ready_to_read = [this] {
  49. u8 buffer[BUFSIZ];
  50. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  51. if (nread < 0) {
  52. dbgln("Terminal read error: {}", strerror(errno));
  53. perror("read(ptm)");
  54. GUI::Application::the()->quit(1);
  55. return;
  56. }
  57. if (nread == 0) {
  58. dbgln("TerminalWidget: EOF on master pty, firing on_command_exit hook.");
  59. if (on_command_exit)
  60. on_command_exit();
  61. int rc = close(m_ptm_fd);
  62. if (rc < 0) {
  63. perror("close");
  64. }
  65. set_pty_master_fd(-1);
  66. return;
  67. }
  68. for (ssize_t i = 0; i < nread; ++i)
  69. m_terminal.on_input(buffer[i]);
  70. flush_dirty_lines();
  71. };
  72. }
  73. TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Core::ConfigFile> config)
  74. : m_terminal(*this)
  75. , m_automatic_size_policy(automatic_size_policy)
  76. , m_config(move(config))
  77. {
  78. static_assert(sizeof(m_colors) == sizeof(xterm_colors));
  79. memcpy(m_colors, xterm_colors, sizeof(m_colors));
  80. set_override_cursor(Gfx::StandardCursor::IBeam);
  81. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  82. set_accepts_emoji_input(true);
  83. set_pty_master_fd(ptm_fd);
  84. m_cursor_blink_timer = add<Core::Timer>();
  85. m_visual_beep_timer = add<Core::Timer>();
  86. m_auto_scroll_timer = add<Core::Timer>();
  87. m_scrollbar = add<GUI::Scrollbar>(Orientation::Vertical);
  88. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  89. m_scrollbar->on_change = [this](int) {
  90. update();
  91. };
  92. dbgln("Load config file from {}", m_config->filename());
  93. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  94. "CursorBlinkInterval",
  95. 500));
  96. m_cursor_blink_timer->on_timeout = [this] {
  97. m_cursor_blink_state = !m_cursor_blink_state;
  98. update_cursor();
  99. };
  100. m_auto_scroll_timer->set_interval(50);
  101. m_auto_scroll_timer->on_timeout = [this] {
  102. if (m_auto_scroll_direction != AutoScrollDirection::None) {
  103. int scroll_amount = m_auto_scroll_direction == AutoScrollDirection::Up ? -1 : 1;
  104. m_scrollbar->set_value(m_scrollbar->value() + scroll_amount);
  105. }
  106. };
  107. m_auto_scroll_timer->start();
  108. auto font_entry = m_config->read_entry("Text", "Font", "default");
  109. if (font_entry == "default")
  110. set_font(Gfx::FontDatabase::default_fixed_width_font());
  111. else
  112. set_font(Gfx::FontDatabase::the().get_by_name(font_entry));
  113. m_line_height = font().glyph_height() + m_line_spacing;
  114. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  115. m_copy_action = GUI::Action::create("&Copy", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [this](auto&) {
  116. copy();
  117. });
  118. m_copy_action->set_swallow_key_event_when_disabled(true);
  119. m_paste_action = GUI::Action::create("&Paste", { Mod_Ctrl | Mod_Shift, Key_V }, Gfx::Bitmap::load_from_file("/res/icons/16x16/paste.png"), [this](auto&) {
  120. paste();
  121. });
  122. m_paste_action->set_swallow_key_event_when_disabled(true);
  123. m_clear_including_history_action = GUI::Action::create("Clear Including &History", { Mod_Ctrl | Mod_Shift, Key_K }, [this](auto&) {
  124. clear_including_history();
  125. });
  126. m_context_menu = GUI::Menu::construct();
  127. m_context_menu->add_action(copy_action());
  128. m_context_menu->add_action(paste_action());
  129. m_context_menu->add_separator();
  130. m_context_menu->add_action(clear_including_history_action());
  131. GUI::Clipboard::the().on_change = [this](const String&) {
  132. update_paste_action();
  133. };
  134. update_copy_action();
  135. update_paste_action();
  136. set_color_scheme(m_config->read_entry("Window", "ColorScheme", "Default"));
  137. }
  138. TerminalWidget::~TerminalWidget()
  139. {
  140. }
  141. Gfx::IntRect TerminalWidget::glyph_rect(u16 row, u16 column)
  142. {
  143. int y = row * m_line_height;
  144. int x = column * font().glyph_width('x');
  145. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  146. }
  147. Gfx::IntRect TerminalWidget::row_rect(u16 row)
  148. {
  149. int y = row * m_line_height;
  150. Gfx::IntRect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  151. rect.inflate(0, m_line_spacing);
  152. return rect;
  153. }
  154. void TerminalWidget::set_logical_focus(bool focus)
  155. {
  156. m_has_logical_focus = focus;
  157. if (!m_has_logical_focus) {
  158. m_cursor_blink_timer->stop();
  159. } else {
  160. m_cursor_blink_state = true;
  161. m_cursor_blink_timer->start();
  162. }
  163. m_auto_scroll_direction = AutoScrollDirection::None;
  164. invalidate_cursor();
  165. update();
  166. }
  167. void TerminalWidget::focusin_event(GUI::FocusEvent& event)
  168. {
  169. set_logical_focus(true);
  170. return GUI::Frame::focusin_event(event);
  171. }
  172. void TerminalWidget::focusout_event(GUI::FocusEvent& event)
  173. {
  174. set_logical_focus(false);
  175. return GUI::Frame::focusout_event(event);
  176. }
  177. void TerminalWidget::event(Core::Event& event)
  178. {
  179. if (event.type() == GUI::Event::WindowBecameActive)
  180. set_logical_focus(true);
  181. else if (event.type() == GUI::Event::WindowBecameInactive)
  182. set_logical_focus(false);
  183. return GUI::Frame::event(event);
  184. }
  185. void TerminalWidget::keydown_event(GUI::KeyEvent& event)
  186. {
  187. if (m_ptm_fd == -1) {
  188. event.ignore();
  189. return GUI::Frame::keydown_event(event);
  190. }
  191. // Reset timer so cursor doesn't blink while typing.
  192. m_cursor_blink_timer->stop();
  193. m_cursor_blink_state = true;
  194. m_cursor_blink_timer->start();
  195. if (event.key() == KeyCode::Key_PageUp && event.modifiers() == Mod_Shift) {
  196. m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
  197. return;
  198. }
  199. if (event.key() == KeyCode::Key_PageDown && event.modifiers() == Mod_Shift) {
  200. m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
  201. return;
  202. }
  203. if (event.key() == KeyCode::Key_Alt) {
  204. m_alt_key_held = true;
  205. return;
  206. }
  207. // Clear the selection if we type in/behind it.
  208. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  209. auto min_selection_row = min(m_selection.start().row(), m_selection.end().row());
  210. auto max_selection_row = max(m_selection.start().row(), m_selection.end().row());
  211. if (future_cursor_column <= last_selection_column_on_row(m_terminal.cursor_row()) && m_terminal.cursor_row() >= min_selection_row && m_terminal.cursor_row() <= max_selection_row) {
  212. m_selection.set_end({});
  213. update_copy_action();
  214. update();
  215. }
  216. m_terminal.handle_key_press(event.key(), event.code_point(), event.modifiers());
  217. if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_LeftShift && event.key() != Key_RightShift && event.key() != Key_Super)
  218. scroll_to_bottom();
  219. }
  220. void TerminalWidget::keyup_event(GUI::KeyEvent& event)
  221. {
  222. switch (event.key()) {
  223. case KeyCode::Key_Alt:
  224. m_alt_key_held = false;
  225. return;
  226. default:
  227. break;
  228. }
  229. }
  230. void TerminalWidget::paint_event(GUI::PaintEvent& event)
  231. {
  232. GUI::Frame::paint_event(event);
  233. GUI::Painter painter(*this);
  234. auto visual_beep_active = m_visual_beep_timer->is_active();
  235. painter.add_clip_rect(event.rect());
  236. Gfx::IntRect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
  237. painter.add_clip_rect(terminal_buffer_rect);
  238. if (visual_beep_active)
  239. painter.clear_rect(frame_inner_rect(), terminal_color_to_rgb(VT::Color::named(VT::Color::ANSIColor::Red)));
  240. else
  241. painter.clear_rect(frame_inner_rect(), terminal_color_to_rgb(VT::Color::named(VT::Color::ANSIColor::DefaultBackground)).with_alpha(m_opacity));
  242. invalidate_cursor();
  243. int rows_from_history = 0;
  244. int first_row_from_history = m_terminal.history_size();
  245. int row_with_cursor = m_terminal.cursor_row();
  246. if (m_scrollbar->value() != m_scrollbar->max()) {
  247. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  248. first_row_from_history = m_terminal.history_size() - (m_scrollbar->max() - m_scrollbar->value());
  249. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  250. }
  251. // Pass: Compute the rect(s) of the currently hovered link, if any.
  252. Vector<Gfx::IntRect> hovered_href_rects;
  253. if (!m_hovered_href_id.is_null()) {
  254. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  255. auto& line = m_terminal.line(first_row_from_history + visual_row);
  256. for (size_t column = 0; column < line.length(); ++column) {
  257. if (m_hovered_href_id == line.attribute_at(column).href_id) {
  258. bool merged_with_existing_rect = false;
  259. auto glyph_rect = this->glyph_rect(visual_row, column);
  260. for (auto& rect : hovered_href_rects) {
  261. if (rect.inflated(1, 1).intersects(glyph_rect)) {
  262. rect = rect.united(glyph_rect);
  263. merged_with_existing_rect = true;
  264. break;
  265. }
  266. }
  267. if (!merged_with_existing_rect)
  268. hovered_href_rects.append(glyph_rect);
  269. }
  270. }
  271. }
  272. }
  273. // Pass: Paint background & text decorations.
  274. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  275. auto row_rect = this->row_rect(visual_row);
  276. if (!event.rect().contains(row_rect))
  277. continue;
  278. auto& line = m_terminal.line(first_row_from_history + visual_row);
  279. bool has_only_one_background_color = line.has_only_one_background_color();
  280. if (visual_beep_active)
  281. painter.clear_rect(row_rect, terminal_color_to_rgb(VT::Color::named(VT::Color::ANSIColor::Red)));
  282. else if (has_only_one_background_color)
  283. painter.clear_rect(row_rect, terminal_color_to_rgb(line.attribute_at(0).effective_background_color()).with_alpha(m_opacity));
  284. for (size_t column = 0; column < line.length(); ++column) {
  285. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  286. && (m_cursor_style == VT::CursorStyle::SteadyBlock || m_cursor_style == VT::CursorStyle::BlinkingBlock)
  287. && m_has_logical_focus
  288. && visual_row == row_with_cursor
  289. && column == m_terminal.cursor_column();
  290. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  291. auto attribute = line.attribute_at(column);
  292. auto character_rect = glyph_rect(visual_row, column);
  293. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  294. auto text_color_before_bold_change = should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color();
  295. auto text_color = terminal_color_to_rgb(m_show_bold_text_as_bright ? text_color_before_bold_change.to_bright() : text_color_before_bold_change);
  296. if ((!visual_beep_active && !has_only_one_background_color) || should_reverse_fill_for_cursor_or_selection)
  297. painter.clear_rect(cell_rect, terminal_color_to_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_foreground_color() : attribute.effective_background_color()));
  298. if constexpr (TERMINAL_DEBUG) {
  299. if (line.termination_column() == column)
  300. painter.clear_rect(cell_rect, Gfx::Color::Magenta);
  301. }
  302. enum class UnderlineStyle {
  303. None,
  304. Dotted,
  305. Solid,
  306. };
  307. auto underline_style = UnderlineStyle::None;
  308. auto underline_color = text_color;
  309. if (attribute.flags & VT::Attribute::Underline) {
  310. // Content has specified underline
  311. underline_style = UnderlineStyle::Solid;
  312. } else if (!attribute.href.is_empty()) {
  313. // We're hovering a hyperlink
  314. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id) {
  315. underline_style = UnderlineStyle::Solid;
  316. underline_color = palette().active_link();
  317. } else {
  318. underline_style = UnderlineStyle::Dotted;
  319. underline_color = text_color.darkened(0.6f);
  320. }
  321. }
  322. if (underline_style == UnderlineStyle::Solid) {
  323. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), underline_color);
  324. } else if (underline_style == UnderlineStyle::Dotted) {
  325. int x1 = cell_rect.bottom_left().x();
  326. int x2 = cell_rect.bottom_right().x();
  327. int y = cell_rect.bottom_left().y();
  328. for (int x = x1; x <= x2; ++x) {
  329. if ((x % 3) == 0)
  330. painter.set_pixel({ x, y }, underline_color);
  331. }
  332. }
  333. }
  334. }
  335. // Paint the hovered link rects, if any.
  336. for (auto rect : hovered_href_rects) {
  337. rect.inflate(6, 6);
  338. painter.fill_rect(rect, palette().base());
  339. painter.draw_rect(rect.inflated(2, 2).intersected(frame_inner_rect()), palette().base_text());
  340. }
  341. auto& font = this->font();
  342. auto& bold_font = font.bold_variant();
  343. // Pass: Paint foreground (text).
  344. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  345. auto row_rect = this->row_rect(visual_row);
  346. if (!event.rect().contains(row_rect))
  347. continue;
  348. auto& line = m_terminal.line(first_row_from_history + visual_row);
  349. for (size_t column = 0; column < line.length(); ++column) {
  350. auto attribute = line.attribute_at(column);
  351. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  352. && (m_cursor_style == VT::CursorStyle::SteadyBlock || m_cursor_style == VT::CursorStyle::BlinkingBlock)
  353. && m_has_logical_focus
  354. && visual_row == row_with_cursor
  355. && column == m_terminal.cursor_column();
  356. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  357. auto text_color_before_bold_change = should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color();
  358. auto text_color = terminal_color_to_rgb(m_show_bold_text_as_bright ? text_color_before_bold_change.to_bright() : text_color_before_bold_change);
  359. u32 code_point = line.code_point(column);
  360. if (code_point == ' ')
  361. continue;
  362. auto character_rect = glyph_rect(visual_row, column);
  363. if (!m_hovered_href_id.is_null() && attribute.href_id == m_hovered_href_id) {
  364. text_color = palette().base_text();
  365. }
  366. painter.draw_glyph_or_emoji(
  367. character_rect.location(),
  368. code_point,
  369. attribute.flags & VT::Attribute::Bold ? bold_font : font,
  370. text_color);
  371. }
  372. }
  373. // Draw cursor.
  374. if (m_cursor_blink_state && row_with_cursor < m_terminal.rows()) {
  375. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  376. if (m_terminal.cursor_row() >= (m_terminal.rows() - rows_from_history))
  377. return;
  378. if (m_has_logical_focus && (m_cursor_style == VT::CursorStyle::BlinkingBlock || m_cursor_style == VT::CursorStyle::SteadyBlock))
  379. return; // This has already been handled by inverting the cell colors
  380. auto cursor_color = terminal_color_to_rgb(cursor_line.attribute_at(m_terminal.cursor_column()).effective_foreground_color());
  381. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  382. if (m_cursor_style == VT::CursorStyle::BlinkingUnderline || m_cursor_style == VT::CursorStyle::SteadyUnderline) {
  383. auto x1 = cell_rect.bottom_left().x();
  384. auto x2 = cell_rect.bottom_right().x();
  385. auto y = cell_rect.bottom_left().y();
  386. for (auto x = x1; x <= x2; ++x)
  387. painter.set_pixel({ x, y }, cursor_color);
  388. } else if (m_cursor_style == VT::CursorStyle::BlinkingBar || m_cursor_style == VT::CursorStyle::SteadyBar) {
  389. auto x = cell_rect.bottom_left().x();
  390. auto y1 = cell_rect.top_left().y();
  391. auto y2 = cell_rect.bottom_left().y();
  392. for (auto y = y1; y <= y2; ++y)
  393. painter.set_pixel({ x, y }, cursor_color);
  394. } else {
  395. // We fall back to a block if we don't support the selected cursor type.
  396. painter.draw_rect(cell_rect, cursor_color);
  397. }
  398. }
  399. }
  400. void TerminalWidget::set_window_progress(int value, int max)
  401. {
  402. float float_value = value;
  403. float float_max = max;
  404. float progress = (float_value / float_max) * 100.0f;
  405. window()->set_progress((int)roundf(progress));
  406. }
  407. void TerminalWidget::set_window_title(const StringView& title)
  408. {
  409. if (!Utf8View(title).validate()) {
  410. dbgln("TerminalWidget: Attempted to set window title to invalid UTF-8 string");
  411. return;
  412. }
  413. if (on_title_change)
  414. on_title_change(title);
  415. }
  416. void TerminalWidget::invalidate_cursor()
  417. {
  418. m_terminal.invalidate_cursor();
  419. }
  420. void TerminalWidget::flush_dirty_lines()
  421. {
  422. // FIXME: Update smarter when scrolled
  423. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  424. update();
  425. m_terminal.m_need_full_flush = false;
  426. return;
  427. }
  428. Gfx::IntRect rect;
  429. for (int i = 0; i < m_terminal.rows(); ++i) {
  430. if (m_terminal.visible_line(i).is_dirty()) {
  431. rect = rect.united(row_rect(i));
  432. m_terminal.visible_line(i).set_dirty(false);
  433. }
  434. }
  435. update(rect);
  436. }
  437. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  438. {
  439. relayout(event.size());
  440. }
  441. void TerminalWidget::relayout(const Gfx::IntSize& size)
  442. {
  443. if (!m_scrollbar)
  444. return;
  445. TemporaryChange change(m_in_relayout, true);
  446. auto base_size = compute_base_size();
  447. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  448. int new_rows = (size.height() - base_size.height()) / m_line_height;
  449. m_terminal.set_size(new_columns, new_rows);
  450. Gfx::IntRect scrollbar_rect = {
  451. size.width() - m_scrollbar->width() - frame_thickness(),
  452. frame_thickness(),
  453. m_scrollbar->width(),
  454. size.height() - frame_thickness() * 2,
  455. };
  456. m_scrollbar->set_relative_rect(scrollbar_rect);
  457. m_scrollbar->set_page_step(new_rows);
  458. }
  459. Gfx::IntSize TerminalWidget::compute_base_size() const
  460. {
  461. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  462. int base_height = frame_thickness() * 2 + m_inset * 2;
  463. return { base_width, base_height };
  464. }
  465. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  466. {
  467. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  468. window.set_base_size(compute_base_size());
  469. }
  470. void TerminalWidget::update_cursor()
  471. {
  472. invalidate_cursor();
  473. flush_dirty_lines();
  474. }
  475. void TerminalWidget::set_opacity(u8 new_opacity)
  476. {
  477. if (m_opacity == new_opacity)
  478. return;
  479. window()->set_has_alpha_channel(new_opacity < 255);
  480. m_opacity = new_opacity;
  481. update();
  482. }
  483. bool TerminalWidget::has_selection() const
  484. {
  485. return m_selection.is_valid();
  486. }
  487. void TerminalWidget::set_selection(const VT::Range& selection)
  488. {
  489. m_selection = selection;
  490. update_copy_action();
  491. update();
  492. }
  493. bool TerminalWidget::selection_contains(const VT::Position& position) const
  494. {
  495. if (!has_selection())
  496. return false;
  497. if (m_rectangle_selection) {
  498. auto m_selection_start = m_selection.start();
  499. auto m_selection_end = m_selection.end();
  500. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  501. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  502. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  503. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  504. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  505. }
  506. auto normalized_selection = m_selection.normalized();
  507. return position >= normalized_selection.start() && position <= normalized_selection.end();
  508. }
  509. VT::Position TerminalWidget::buffer_position_at(const Gfx::IntPoint& position) const
  510. {
  511. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  512. int row = adjusted_position.y() / m_line_height;
  513. int column = adjusted_position.x() / font().glyph_width('x');
  514. if (row < 0)
  515. row = 0;
  516. if (column < 0)
  517. column = 0;
  518. if (row >= m_terminal.rows())
  519. row = m_terminal.rows() - 1;
  520. auto& line = m_terminal.line(row);
  521. if (column >= (int)line.length())
  522. column = line.length() - 1;
  523. row += m_scrollbar->value();
  524. return { row, column };
  525. }
  526. u32 TerminalWidget::code_point_at(const VT::Position& position) const
  527. {
  528. VERIFY(position.is_valid());
  529. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  530. auto& line = m_terminal.line(position.row());
  531. if (static_cast<size_t>(position.column()) == line.length())
  532. return '\n';
  533. return line.code_point(position.column());
  534. }
  535. VT::Position TerminalWidget::next_position_after(const VT::Position& position, bool should_wrap) const
  536. {
  537. VERIFY(position.is_valid());
  538. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  539. auto& line = m_terminal.line(position.row());
  540. if (static_cast<size_t>(position.column()) == line.length()) {
  541. if (static_cast<size_t>(position.row()) == m_terminal.line_count() - 1) {
  542. if (should_wrap)
  543. return { 0, 0 };
  544. return {};
  545. }
  546. return { position.row() + 1, 0 };
  547. }
  548. return { position.row(), position.column() + 1 };
  549. }
  550. VT::Position TerminalWidget::previous_position_before(const VT::Position& position, bool should_wrap) const
  551. {
  552. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  553. if (position.column() == 0) {
  554. if (position.row() == 0) {
  555. if (should_wrap) {
  556. auto& last_line = m_terminal.line(m_terminal.line_count() - 1);
  557. return { static_cast<int>(m_terminal.line_count() - 1), static_cast<int>(last_line.length()) };
  558. }
  559. return {};
  560. }
  561. auto& prev_line = m_terminal.line(position.row() - 1);
  562. return { position.row() - 1, static_cast<int>(prev_line.length()) };
  563. }
  564. return { position.row(), position.column() - 1 };
  565. }
  566. static u32 to_lowercase_code_point(u32 code_point)
  567. {
  568. // FIXME: this only handles ascii characters, but handling unicode lowercasing seems like a mess
  569. if (code_point < 128)
  570. return tolower(code_point);
  571. return code_point;
  572. }
  573. VT::Range TerminalWidget::find_next(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  574. {
  575. if (needle.is_empty())
  576. return {};
  577. VT::Position position = start.is_valid() ? start : VT::Position(0, 0);
  578. VT::Position original_position = position;
  579. VT::Position start_of_potential_match;
  580. size_t needle_index = 0;
  581. do {
  582. auto ch = code_point_at(position);
  583. // FIXME: This is not the right way to use a Unicode needle!
  584. auto needle_ch = (u32)needle[needle_index];
  585. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  586. if (needle_index == 0)
  587. start_of_potential_match = position;
  588. ++needle_index;
  589. if (needle_index >= needle.length())
  590. return { start_of_potential_match, position };
  591. } else {
  592. if (needle_index > 0)
  593. position = start_of_potential_match;
  594. needle_index = 0;
  595. }
  596. position = next_position_after(position, should_wrap);
  597. } while (position.is_valid() && position != original_position);
  598. return {};
  599. }
  600. VT::Range TerminalWidget::find_previous(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  601. {
  602. if (needle.is_empty())
  603. return {};
  604. VT::Position position = start.is_valid() ? start : VT::Position(m_terminal.line_count() - 1, m_terminal.line(m_terminal.line_count() - 1).length() - 1);
  605. VT::Position original_position = position;
  606. VT::Position end_of_potential_match;
  607. size_t needle_index = needle.length() - 1;
  608. do {
  609. auto ch = code_point_at(position);
  610. // FIXME: This is not the right way to use a Unicode needle!
  611. auto needle_ch = (u32)needle[needle_index];
  612. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  613. if (needle_index == needle.length() - 1)
  614. end_of_potential_match = position;
  615. if (needle_index == 0)
  616. return { position, end_of_potential_match };
  617. --needle_index;
  618. } else {
  619. if (needle_index < needle.length() - 1)
  620. position = end_of_potential_match;
  621. needle_index = needle.length() - 1;
  622. }
  623. position = previous_position_before(position, should_wrap);
  624. } while (position.is_valid() && position != original_position);
  625. return {};
  626. }
  627. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  628. {
  629. if (event.button() == GUI::MouseButton::Left) {
  630. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  631. if (!attribute.href_id.is_null()) {
  632. dbgln("Open hyperlinked URL: '{}'", attribute.href);
  633. Desktop::Launcher::open(attribute.href);
  634. return;
  635. }
  636. m_triple_click_timer.start();
  637. auto position = buffer_position_at(event.position());
  638. auto& line = m_terminal.line(position.row());
  639. bool want_whitespace = line.code_point(position.column()) == ' ';
  640. int start_column = 0;
  641. int end_column = 0;
  642. for (int column = position.column(); column >= 0 && (line.code_point(column) == ' ') == want_whitespace; --column) {
  643. start_column = column;
  644. }
  645. for (int column = position.column(); column < (int)line.length() && (line.code_point(column) == ' ') == want_whitespace; ++column) {
  646. end_column = column;
  647. }
  648. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  649. update_copy_action();
  650. update();
  651. }
  652. GUI::Frame::doubleclick_event(event);
  653. }
  654. void TerminalWidget::paste()
  655. {
  656. if (m_ptm_fd == -1)
  657. return;
  658. auto mime_type = GUI::Clipboard::the().mime_type();
  659. if (!mime_type.starts_with("text/"))
  660. return;
  661. auto text = GUI::Clipboard::the().data();
  662. if (text.is_empty())
  663. return;
  664. send_non_user_input(text);
  665. }
  666. void TerminalWidget::copy()
  667. {
  668. if (has_selection())
  669. GUI::Clipboard::the().set_plain_text(selected_text());
  670. }
  671. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  672. {
  673. if (event.button() == GUI::MouseButton::Left) {
  674. if (!m_active_href_id.is_null()) {
  675. m_active_href = {};
  676. m_active_href_id = {};
  677. update();
  678. }
  679. m_auto_scroll_direction = AutoScrollDirection::None;
  680. }
  681. }
  682. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  683. {
  684. if (event.button() == GUI::MouseButton::Left) {
  685. m_left_mousedown_position = event.position();
  686. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  687. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  688. m_active_href = attribute.href;
  689. m_active_href_id = attribute.href_id;
  690. update();
  691. return;
  692. }
  693. m_active_href = {};
  694. m_active_href_id = {};
  695. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  696. int start_column = 0;
  697. int end_column = m_terminal.columns() - 1;
  698. auto position = buffer_position_at(event.position());
  699. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  700. } else {
  701. m_selection.set(buffer_position_at(event.position()), {});
  702. }
  703. if (m_alt_key_held)
  704. m_rectangle_selection = true;
  705. else if (m_rectangle_selection)
  706. m_rectangle_selection = false;
  707. update_copy_action();
  708. update();
  709. }
  710. }
  711. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  712. {
  713. auto position = buffer_position_at(event.position());
  714. auto attribute = m_terminal.attribute_at(position);
  715. if (attribute.href_id != m_hovered_href_id) {
  716. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  717. m_hovered_href_id = attribute.href_id;
  718. m_hovered_href = attribute.href;
  719. } else {
  720. m_hovered_href_id = {};
  721. m_hovered_href = {};
  722. }
  723. set_tooltip(m_hovered_href);
  724. show_or_hide_tooltip();
  725. if (!m_hovered_href.is_empty())
  726. set_override_cursor(Gfx::StandardCursor::Arrow);
  727. else
  728. set_override_cursor(Gfx::StandardCursor::IBeam);
  729. update();
  730. }
  731. if (!(event.buttons() & GUI::MouseButton::Left))
  732. return;
  733. if (!m_active_href_id.is_null()) {
  734. auto diff = event.position() - m_left_mousedown_position;
  735. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  736. constexpr int drag_distance_threshold = 5;
  737. if (distance_travelled_squared <= drag_distance_threshold)
  738. return;
  739. auto drag_operation = GUI::DragOperation::construct();
  740. drag_operation->set_text(m_active_href);
  741. drag_operation->set_data("text/uri-list", m_active_href);
  742. drag_operation->exec();
  743. m_active_href = {};
  744. m_active_href_id = {};
  745. m_hovered_href = {};
  746. m_hovered_href_id = {};
  747. update();
  748. return;
  749. }
  750. auto adjusted_position = event.position().translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  751. if (adjusted_position.y() < 0)
  752. m_auto_scroll_direction = AutoScrollDirection::Up;
  753. else if (adjusted_position.y() > m_terminal.rows() * m_line_height)
  754. m_auto_scroll_direction = AutoScrollDirection::Down;
  755. else
  756. m_auto_scroll_direction = AutoScrollDirection::None;
  757. VT::Position old_selection_end = m_selection.end();
  758. m_selection.set_end(position);
  759. if (old_selection_end != m_selection.end()) {
  760. update_copy_action();
  761. update();
  762. }
  763. }
  764. void TerminalWidget::leave_event(Core::Event&)
  765. {
  766. bool should_update = !m_hovered_href.is_empty();
  767. m_hovered_href = {};
  768. m_hovered_href_id = {};
  769. set_tooltip(m_hovered_href);
  770. set_override_cursor(Gfx::StandardCursor::IBeam);
  771. if (should_update)
  772. update();
  773. }
  774. void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
  775. {
  776. if (!is_scrollable())
  777. return;
  778. m_auto_scroll_direction = AutoScrollDirection::None;
  779. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta() * scroll_length());
  780. GUI::Frame::mousewheel_event(event);
  781. }
  782. bool TerminalWidget::is_scrollable() const
  783. {
  784. return m_scrollbar->is_scrollable();
  785. }
  786. int TerminalWidget::scroll_length() const
  787. {
  788. return m_scrollbar->step();
  789. }
  790. String TerminalWidget::selected_text() const
  791. {
  792. StringBuilder builder;
  793. auto normalized_selection = m_selection.normalized();
  794. auto start = normalized_selection.start();
  795. auto end = normalized_selection.end();
  796. for (int row = start.row(); row <= end.row(); ++row) {
  797. int first_column = first_selection_column_on_row(row);
  798. int last_column = last_selection_column_on_row(row);
  799. for (int column = first_column; column <= last_column; ++column) {
  800. auto& line = m_terminal.line(row);
  801. if (line.attribute_at(column).is_untouched()) {
  802. builder.append('\n');
  803. break;
  804. }
  805. // FIXME: This is a bit hackish.
  806. u32 code_point = line.code_point(column);
  807. builder.append(Utf32View(&code_point, 1));
  808. if (column == static_cast<int>(line.length()) - 1 || (m_rectangle_selection && column == last_column)) {
  809. builder.append('\n');
  810. }
  811. }
  812. }
  813. return builder.to_string();
  814. }
  815. int TerminalWidget::first_selection_column_on_row(int row) const
  816. {
  817. auto normalized_selection_start = m_selection.normalized().start();
  818. return row == normalized_selection_start.row() || m_rectangle_selection ? normalized_selection_start.column() : 0;
  819. }
  820. int TerminalWidget::last_selection_column_on_row(int row) const
  821. {
  822. auto normalized_selection_end = m_selection.normalized().end();
  823. return row == normalized_selection_end.row() || m_rectangle_selection ? normalized_selection_end.column() : m_terminal.columns() - 1;
  824. }
  825. void TerminalWidget::terminal_history_changed(int delta)
  826. {
  827. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  828. m_scrollbar->set_max(m_terminal.history_size());
  829. if (was_max)
  830. m_scrollbar->set_value(m_scrollbar->max());
  831. m_scrollbar->update();
  832. // If the history buffer wrapped around, the selection needs to be offset accordingly.
  833. if (m_selection.is_valid() && delta < 0)
  834. m_selection.offset_row(delta);
  835. }
  836. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  837. {
  838. auto pixel_size = widget_size_for_font(font());
  839. m_pixel_width = pixel_size.width();
  840. m_pixel_height = pixel_size.height();
  841. if (!m_in_relayout) {
  842. if (on_terminal_size_change)
  843. on_terminal_size_change(Gfx::IntSize { m_pixel_width, m_pixel_height });
  844. }
  845. if (m_automatic_size_policy) {
  846. set_fixed_size(m_pixel_width, m_pixel_height);
  847. }
  848. update();
  849. winsize ws;
  850. ws.ws_row = rows;
  851. ws.ws_col = columns;
  852. if (m_ptm_fd != -1) {
  853. if (ioctl(m_ptm_fd, TIOCSWINSZ, &ws) < 0) {
  854. // This can happen if we resize just as the shell exits.
  855. dbgln("Notifying the pseudo-terminal about a size change failed.");
  856. }
  857. }
  858. }
  859. void TerminalWidget::beep()
  860. {
  861. if (m_bell_mode == BellMode::Disabled) {
  862. return;
  863. }
  864. if (m_bell_mode == BellMode::AudibleBeep) {
  865. sysbeep();
  866. return;
  867. }
  868. m_visual_beep_timer->restart(200);
  869. m_visual_beep_timer->set_single_shot(true);
  870. m_visual_beep_timer->on_timeout = [this] {
  871. update();
  872. };
  873. update();
  874. }
  875. void TerminalWidget::emit(const u8* data, size_t size)
  876. {
  877. if (write(m_ptm_fd, data, size) < 0) {
  878. perror("TerminalWidget::emit: write");
  879. }
  880. }
  881. void TerminalWidget::set_cursor_style(CursorStyle style)
  882. {
  883. switch (style) {
  884. case None:
  885. m_cursor_blink_timer->stop();
  886. m_cursor_blink_state = false;
  887. break;
  888. case SteadyBlock:
  889. case SteadyUnderline:
  890. case SteadyBar:
  891. m_cursor_blink_timer->stop();
  892. m_cursor_blink_state = true;
  893. break;
  894. case BlinkingBlock:
  895. case BlinkingUnderline:
  896. case BlinkingBar:
  897. m_cursor_blink_state = true;
  898. m_cursor_blink_timer->restart();
  899. break;
  900. default:
  901. dbgln("Cursor style not implemented");
  902. }
  903. m_cursor_style = style;
  904. invalidate_cursor();
  905. }
  906. void TerminalWidget::context_menu_event(GUI::ContextMenuEvent& event)
  907. {
  908. if (m_hovered_href_id.is_null()) {
  909. m_context_menu->popup(event.screen_position());
  910. } else {
  911. m_context_menu_href = m_hovered_href;
  912. // Ask LaunchServer for a list of programs that can handle the right-clicked URL.
  913. auto handlers = Desktop::Launcher::get_handlers_for_url(m_hovered_href);
  914. if (handlers.is_empty()) {
  915. m_context_menu->popup(event.screen_position());
  916. return;
  917. }
  918. m_context_menu_for_hyperlink = GUI::Menu::construct();
  919. RefPtr<GUI::Action> context_menu_default_action;
  920. // Go through the list of handlers and see if we can find a nice display name + icon for them.
  921. // Then add them to the context menu.
  922. // FIXME: Adapt this code when we actually support calling LaunchServer with a specific handler in mind.
  923. for (auto& handler : handlers) {
  924. auto af = Desktop::AppFile::get_for_app(LexicalPath::basename(handler));
  925. if (!af->is_valid())
  926. continue;
  927. auto action = GUI::Action::create(String::formatted("&Open in {}", af->name()), af->icon().bitmap_for_size(16), [this, handler](auto&) {
  928. Desktop::Launcher::open(m_context_menu_href, handler);
  929. });
  930. if (context_menu_default_action.is_null()) {
  931. context_menu_default_action = action;
  932. }
  933. m_context_menu_for_hyperlink->add_action(action);
  934. }
  935. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy &URL", [this](auto&) {
  936. GUI::Clipboard::the().set_plain_text(m_context_menu_href);
  937. }));
  938. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy &Name", [&](auto&) {
  939. // file://courage/home/anon/something -> /home/anon/something
  940. auto path = URL(m_context_menu_href).path();
  941. // /home/anon/something -> something
  942. auto name = LexicalPath::basename(path);
  943. GUI::Clipboard::the().set_plain_text(name);
  944. }));
  945. m_context_menu_for_hyperlink->add_separator();
  946. m_context_menu_for_hyperlink->add_action(copy_action());
  947. m_context_menu_for_hyperlink->add_action(paste_action());
  948. m_context_menu_for_hyperlink->popup(event.screen_position(), context_menu_default_action);
  949. }
  950. }
  951. void TerminalWidget::drop_event(GUI::DropEvent& event)
  952. {
  953. if (event.mime_data().has_urls()) {
  954. event.accept();
  955. auto urls = event.mime_data().urls();
  956. bool first = true;
  957. for (auto& url : event.mime_data().urls()) {
  958. if (!first)
  959. send_non_user_input(" "sv.bytes());
  960. if (url.protocol() == "file")
  961. send_non_user_input(url.path().bytes());
  962. else
  963. send_non_user_input(url.to_string().bytes());
  964. first = false;
  965. }
  966. } else if (event.mime_data().has_text()) {
  967. event.accept();
  968. auto text = event.mime_data().text();
  969. send_non_user_input(text.bytes());
  970. }
  971. }
  972. void TerminalWidget::did_change_font()
  973. {
  974. GUI::Frame::did_change_font();
  975. m_line_height = font().glyph_height() + m_line_spacing;
  976. if (!size().is_empty())
  977. relayout(size());
  978. }
  979. void TerminalWidget::clear_including_history()
  980. {
  981. m_terminal.clear_including_history();
  982. }
  983. void TerminalWidget::scroll_to_bottom()
  984. {
  985. m_scrollbar->set_value(m_scrollbar->max());
  986. }
  987. void TerminalWidget::scroll_to_row(int row)
  988. {
  989. m_scrollbar->set_value(row);
  990. }
  991. void TerminalWidget::update_copy_action()
  992. {
  993. m_copy_action->set_enabled(has_selection());
  994. }
  995. void TerminalWidget::update_paste_action()
  996. {
  997. m_paste_action->set_enabled(GUI::Clipboard::the().mime_type().starts_with("text/") && !GUI::Clipboard::the().data().is_empty());
  998. }
  999. void TerminalWidget::set_color_scheme(const StringView& name)
  1000. {
  1001. if (name.contains('/')) {
  1002. dbgln("Shenanigans! Color scheme names can't contain slashes.");
  1003. return;
  1004. }
  1005. m_color_scheme_name = name;
  1006. constexpr StringView color_names[] = {
  1007. "Black",
  1008. "Red",
  1009. "Green",
  1010. "Yellow",
  1011. "Blue",
  1012. "Magenta",
  1013. "Cyan",
  1014. "White"
  1015. };
  1016. auto color_config = Core::ConfigFile::open(String::formatted("/res/terminal-colors/{}.ini", name));
  1017. m_show_bold_text_as_bright = color_config->read_bool_entry("Options", "ShowBoldTextAsBright", true);
  1018. auto default_background = Gfx::Color::from_string(color_config->read_entry("Primary", "Background"));
  1019. if (default_background.has_value())
  1020. m_default_background_color = default_background.value();
  1021. else
  1022. m_default_background_color = Gfx::Color::from_rgb(m_colors[(u8)VT::Color::ANSIColor::Black]);
  1023. auto default_foreground = Gfx::Color::from_string(color_config->read_entry("Primary", "Foreground"));
  1024. if (default_foreground.has_value())
  1025. m_default_foreground_color = default_foreground.value();
  1026. else
  1027. m_default_foreground_color = Gfx::Color::from_rgb(m_colors[(u8)VT::Color::ANSIColor::White]);
  1028. for (u8 color_idx = 0; color_idx < 8; ++color_idx) {
  1029. auto rgb = Gfx::Color::from_string(color_config->read_entry("Normal", color_names[color_idx]));
  1030. if (rgb.has_value())
  1031. m_colors[color_idx] = rgb.value().value();
  1032. }
  1033. for (u8 color_idx = 0; color_idx < 8; ++color_idx) {
  1034. auto rgb = Gfx::Color::from_string(color_config->read_entry("Bright", color_names[color_idx]));
  1035. if (rgb.has_value())
  1036. m_colors[color_idx + 8] = rgb.value().value();
  1037. }
  1038. update();
  1039. }
  1040. Gfx::IntSize TerminalWidget::widget_size_for_font(const Gfx::Font& font) const
  1041. {
  1042. return {
  1043. (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.columns() * font.glyph_width('x')) + m_scrollbar->width(),
  1044. (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.rows() * (font.glyph_height() + m_line_spacing))
  1045. };
  1046. }
  1047. constexpr Gfx::Color TerminalWidget::terminal_color_to_rgb(VT::Color color) const
  1048. {
  1049. switch (color.kind()) {
  1050. case VT::Color::Kind::RGB:
  1051. return Gfx::Color::from_rgb(color.as_rgb());
  1052. case VT::Color::Kind::Indexed:
  1053. return Gfx::Color::from_rgb(m_colors[color.as_indexed()]);
  1054. case VT::Color::Kind::Named: {
  1055. auto ansi = color.as_named();
  1056. if ((u16)ansi < 256)
  1057. return Gfx::Color::from_rgb(m_colors[(u16)ansi]);
  1058. else if (ansi == VT::Color::ANSIColor::DefaultForeground)
  1059. return m_default_foreground_color;
  1060. else if (ansi == VT::Color::ANSIColor::DefaultBackground)
  1061. return m_default_background_color;
  1062. else
  1063. VERIFY_NOT_REACHED();
  1064. }
  1065. default:
  1066. VERIFY_NOT_REACHED();
  1067. }
  1068. };
  1069. void TerminalWidget::set_font_and_resize_to_fit(const Gfx::Font& font)
  1070. {
  1071. set_font(font);
  1072. resize(widget_size_for_font(font));
  1073. }
  1074. // Used for sending data that was not directly typed by the user.
  1075. // This basically wraps the code that handles sending the escape sequence in bracketed paste mode.
  1076. void TerminalWidget::send_non_user_input(const ReadonlyBytes& bytes)
  1077. {
  1078. constexpr StringView leading_control_sequence = "\e[200~";
  1079. constexpr StringView trailing_control_sequence = "\e[201~";
  1080. int nwritten;
  1081. if (m_terminal.needs_bracketed_paste()) {
  1082. // We do not call write() separately for the control sequences and the data,
  1083. // because that would present a race condition where another process could inject data
  1084. // to prematurely terminate the escape. Could probably be solved by file locking.
  1085. Vector<u8> output;
  1086. output.ensure_capacity(leading_control_sequence.bytes().size() + bytes.size() + trailing_control_sequence.bytes().size());
  1087. // HACK: We don't have a `Vector<T>::unchecked_append(Span<T> const&)` yet :^(
  1088. output.append(leading_control_sequence.bytes().data(), leading_control_sequence.bytes().size());
  1089. output.append(bytes.data(), bytes.size());
  1090. output.append(trailing_control_sequence.bytes().data(), trailing_control_sequence.bytes().size());
  1091. nwritten = write(m_ptm_fd, output.data(), output.size());
  1092. } else {
  1093. nwritten = write(m_ptm_fd, bytes.data(), bytes.size());
  1094. }
  1095. if (nwritten < 0) {
  1096. perror("write");
  1097. VERIFY_NOT_REACHED();
  1098. }
  1099. }
  1100. }