TerminalWidget.cpp 51 KB

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