TerminalWidget.cpp 48 KB

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