TerminalWidget.cpp 46 KB

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