TerminalWidget.cpp 47 KB

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