TerminalWidget.cpp 46 KB

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