TerminalWidget.cpp 48 KB

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