TerminalWidget.cpp 48 KB

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