TerminalWidget.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "TerminalWidget.h"
  27. #include <AK/LexicalPath.h>
  28. #include <AK/StdLibExtras.h>
  29. #include <AK/String.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/TemporaryChange.h>
  32. #include <AK/Utf32View.h>
  33. #include <AK/Utf8View.h>
  34. #include <LibCore/ConfigFile.h>
  35. #include <LibCore/MimeData.h>
  36. #include <LibDesktop/AppFile.h>
  37. #include <LibDesktop/Launcher.h>
  38. #include <LibGUI/Action.h>
  39. #include <LibGUI/Application.h>
  40. #include <LibGUI/Clipboard.h>
  41. #include <LibGUI/DragOperation.h>
  42. #include <LibGUI/Icon.h>
  43. #include <LibGUI/Menu.h>
  44. #include <LibGUI/Painter.h>
  45. #include <LibGUI/ScrollBar.h>
  46. #include <LibGUI/Window.h>
  47. #include <LibGfx/Font.h>
  48. #include <LibGfx/FontDatabase.h>
  49. #include <LibGfx/Palette.h>
  50. #include <LibGfx/StylePainter.h>
  51. #include <ctype.h>
  52. #include <errno.h>
  53. #include <math.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <sys/ioctl.h>
  58. #include <unistd.h>
  59. namespace VT {
  60. void TerminalWidget::set_pty_master_fd(int fd)
  61. {
  62. m_ptm_fd = fd;
  63. if (m_ptm_fd == -1) {
  64. m_notifier = nullptr;
  65. return;
  66. }
  67. m_notifier = Core::Notifier::construct(m_ptm_fd, Core::Notifier::Read);
  68. m_notifier->on_ready_to_read = [this] {
  69. u8 buffer[BUFSIZ];
  70. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  71. if (nread < 0) {
  72. dbgln("Terminal read error: {}", strerror(errno));
  73. perror("read(ptm)");
  74. GUI::Application::the()->quit(1);
  75. return;
  76. }
  77. if (nread == 0) {
  78. dbgln("TerminalWidget: EOF on master pty, firing on_command_exit hook.");
  79. if (on_command_exit)
  80. on_command_exit();
  81. int rc = close(m_ptm_fd);
  82. if (rc < 0) {
  83. perror("close");
  84. }
  85. set_pty_master_fd(-1);
  86. return;
  87. }
  88. for (ssize_t i = 0; i < nread; ++i)
  89. m_terminal.on_input(buffer[i]);
  90. flush_dirty_lines();
  91. };
  92. }
  93. TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Core::ConfigFile> config)
  94. : m_terminal(*this)
  95. , m_automatic_size_policy(automatic_size_policy)
  96. , m_config(move(config))
  97. {
  98. set_override_cursor(Gfx::StandardCursor::IBeam);
  99. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  100. set_accepts_emoji_input(true);
  101. set_pty_master_fd(ptm_fd);
  102. m_cursor_blink_timer = add<Core::Timer>();
  103. m_visual_beep_timer = add<Core::Timer>();
  104. m_auto_scroll_timer = add<Core::Timer>();
  105. m_scrollbar = add<GUI::ScrollBar>(Orientation::Vertical);
  106. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  107. m_scrollbar->on_change = [this](int) {
  108. update();
  109. };
  110. dbgln("Load config file from {}", m_config->file_name());
  111. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  112. "CursorBlinkInterval",
  113. 500));
  114. m_cursor_blink_timer->on_timeout = [this] {
  115. m_cursor_blink_state = !m_cursor_blink_state;
  116. update_cursor();
  117. };
  118. m_auto_scroll_timer->set_interval(50);
  119. m_auto_scroll_timer->on_timeout = [this] {
  120. if (m_auto_scroll_direction != AutoScrollDirection::None) {
  121. int scroll_amount = m_auto_scroll_direction == AutoScrollDirection::Up ? -1 : 1;
  122. m_scrollbar->set_value(m_scrollbar->value() + scroll_amount);
  123. }
  124. };
  125. m_auto_scroll_timer->start();
  126. auto font_entry = m_config->read_entry("Text", "Font", "default");
  127. if (font_entry == "default")
  128. set_font(Gfx::FontDatabase::default_fixed_width_font());
  129. else
  130. set_font(Gfx::FontDatabase::the().get_by_name(font_entry));
  131. m_line_height = font().glyph_height() + m_line_spacing;
  132. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  133. m_copy_action = GUI::Action::create("&Copy", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [this](auto&) {
  134. copy();
  135. });
  136. m_copy_action->set_swallow_key_event_when_disabled(true);
  137. m_paste_action = GUI::Action::create("&Paste", { Mod_Ctrl | Mod_Shift, Key_V }, Gfx::Bitmap::load_from_file("/res/icons/16x16/paste.png"), [this](auto&) {
  138. paste();
  139. });
  140. m_paste_action->set_swallow_key_event_when_disabled(true);
  141. m_clear_including_history_action = GUI::Action::create("&Clear Including History", { Mod_Ctrl | Mod_Shift, Key_K }, [this](auto&) {
  142. clear_including_history();
  143. });
  144. m_context_menu = GUI::Menu::construct();
  145. m_context_menu->add_action(copy_action());
  146. m_context_menu->add_action(paste_action());
  147. m_context_menu->add_separator();
  148. m_context_menu->add_action(clear_including_history_action());
  149. GUI::Clipboard::the().on_change = [this](const String&) {
  150. update_paste_action();
  151. };
  152. update_copy_action();
  153. update_paste_action();
  154. }
  155. TerminalWidget::~TerminalWidget()
  156. {
  157. }
  158. static inline Color color_from_rgb(unsigned color)
  159. {
  160. return Color::from_rgb(color);
  161. }
  162. Gfx::IntRect TerminalWidget::glyph_rect(u16 row, u16 column)
  163. {
  164. int y = row * m_line_height;
  165. int x = column * font().glyph_width('x');
  166. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  167. }
  168. Gfx::IntRect TerminalWidget::row_rect(u16 row)
  169. {
  170. int y = row * m_line_height;
  171. Gfx::IntRect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  172. rect.inflate(0, m_line_spacing);
  173. return rect;
  174. }
  175. void TerminalWidget::set_logical_focus(bool focus)
  176. {
  177. m_has_logical_focus = focus;
  178. if (!m_has_logical_focus) {
  179. m_cursor_blink_timer->stop();
  180. } else {
  181. m_cursor_blink_state = true;
  182. m_cursor_blink_timer->start();
  183. }
  184. m_auto_scroll_direction = AutoScrollDirection::None;
  185. invalidate_cursor();
  186. update();
  187. }
  188. void TerminalWidget::focusin_event(GUI::FocusEvent& event)
  189. {
  190. set_logical_focus(true);
  191. return GUI::Frame::focusin_event(event);
  192. }
  193. void TerminalWidget::focusout_event(GUI::FocusEvent& event)
  194. {
  195. set_logical_focus(false);
  196. return GUI::Frame::focusout_event(event);
  197. }
  198. void TerminalWidget::event(Core::Event& event)
  199. {
  200. if (event.type() == GUI::Event::WindowBecameActive)
  201. set_logical_focus(true);
  202. else if (event.type() == GUI::Event::WindowBecameInactive)
  203. set_logical_focus(false);
  204. return GUI::Frame::event(event);
  205. }
  206. void TerminalWidget::keydown_event(GUI::KeyEvent& event)
  207. {
  208. if (m_ptm_fd == -1) {
  209. event.ignore();
  210. return GUI::Frame::keydown_event(event);
  211. }
  212. // Reset timer so cursor doesn't blink while typing.
  213. m_cursor_blink_timer->stop();
  214. m_cursor_blink_state = true;
  215. m_cursor_blink_timer->start();
  216. if (event.key() == KeyCode::Key_PageUp && event.modifiers() == Mod_Shift) {
  217. m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
  218. return;
  219. }
  220. if (event.key() == KeyCode::Key_PageDown && event.modifiers() == Mod_Shift) {
  221. m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
  222. return;
  223. }
  224. if (event.key() == KeyCode::Key_Alt) {
  225. m_alt_key_held = true;
  226. return;
  227. }
  228. // Clear the selection if we type in/behind it.
  229. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  230. auto min_selection_row = min(m_selection.start().row(), m_selection.end().row());
  231. auto max_selection_row = max(m_selection.start().row(), m_selection.end().row());
  232. 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) {
  233. m_selection.set_end({});
  234. update_copy_action();
  235. update();
  236. }
  237. m_terminal.handle_key_press(event.key(), event.code_point(), event.modifiers());
  238. if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_LeftShift && event.key() != Key_RightShift && event.key() != Key_Super)
  239. scroll_to_bottom();
  240. }
  241. void TerminalWidget::keyup_event(GUI::KeyEvent& event)
  242. {
  243. switch (event.key()) {
  244. case KeyCode::Key_Alt:
  245. m_alt_key_held = false;
  246. return;
  247. default:
  248. break;
  249. }
  250. }
  251. void TerminalWidget::paint_event(GUI::PaintEvent& event)
  252. {
  253. GUI::Frame::paint_event(event);
  254. GUI::Painter painter(*this);
  255. auto visual_beep_active = m_visual_beep_timer->is_active();
  256. painter.add_clip_rect(event.rect());
  257. Gfx::IntRect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
  258. painter.add_clip_rect(terminal_buffer_rect);
  259. if (visual_beep_active)
  260. painter.clear_rect(frame_inner_rect(), Color::Red);
  261. else
  262. painter.clear_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  263. invalidate_cursor();
  264. int rows_from_history = 0;
  265. int first_row_from_history = m_terminal.history_size();
  266. int row_with_cursor = m_terminal.cursor_row();
  267. if (m_scrollbar->value() != m_scrollbar->max()) {
  268. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  269. first_row_from_history = m_terminal.history_size() - (m_scrollbar->max() - m_scrollbar->value());
  270. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  271. }
  272. // Pass: Compute the rect(s) of the currently hovered link, if any.
  273. Vector<Gfx::IntRect> hovered_href_rects;
  274. if (!m_hovered_href_id.is_null()) {
  275. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  276. auto& line = m_terminal.line(first_row_from_history + visual_row);
  277. for (size_t column = 0; column < line.length(); ++column) {
  278. if (m_hovered_href_id == line.attribute_at(column).href_id) {
  279. bool merged_with_existing_rect = false;
  280. auto glyph_rect = this->glyph_rect(visual_row, column);
  281. for (auto& rect : hovered_href_rects) {
  282. if (rect.inflated(1, 1).intersects(glyph_rect)) {
  283. rect = rect.united(glyph_rect);
  284. merged_with_existing_rect = true;
  285. break;
  286. }
  287. }
  288. if (!merged_with_existing_rect)
  289. hovered_href_rects.append(glyph_rect);
  290. }
  291. }
  292. }
  293. }
  294. // Pass: Paint background & text decorations.
  295. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  296. auto row_rect = this->row_rect(visual_row);
  297. if (!event.rect().contains(row_rect))
  298. continue;
  299. auto& line = m_terminal.line(first_row_from_history + visual_row);
  300. bool has_only_one_background_color = line.has_only_one_background_color();
  301. if (visual_beep_active)
  302. painter.clear_rect(row_rect, Color::Red);
  303. else if (has_only_one_background_color)
  304. painter.clear_rect(row_rect, color_from_rgb(line.attribute_at(0).effective_background_color()).with_alpha(m_opacity));
  305. for (size_t column = 0; column < line.length(); ++column) {
  306. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  307. && m_has_logical_focus
  308. && visual_row == row_with_cursor
  309. && column == m_terminal.cursor_column();
  310. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  311. auto attribute = line.attribute_at(column);
  312. auto character_rect = glyph_rect(visual_row, column);
  313. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  314. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color());
  315. if ((!visual_beep_active && !has_only_one_background_color) || should_reverse_fill_for_cursor_or_selection)
  316. painter.clear_rect(cell_rect, color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_foreground_color() : attribute.effective_background_color()));
  317. enum class UnderlineStyle {
  318. None,
  319. Dotted,
  320. Solid,
  321. };
  322. auto underline_style = UnderlineStyle::None;
  323. if (attribute.flags & VT::Attribute::Underline) {
  324. // Content has specified underline
  325. underline_style = UnderlineStyle::Solid;
  326. } else if (!attribute.href.is_empty()) {
  327. // We're hovering a hyperlink
  328. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id)
  329. underline_style = UnderlineStyle::Solid;
  330. else
  331. underline_style = UnderlineStyle::Dotted;
  332. }
  333. if (underline_style == UnderlineStyle::Solid) {
  334. if (attribute.href_id == m_active_href_id && m_hovered_href_id == m_active_href_id)
  335. text_color = palette().active_link();
  336. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), text_color);
  337. } else if (underline_style == UnderlineStyle::Dotted) {
  338. auto dotted_line_color = text_color.darkened(0.6f);
  339. int x1 = cell_rect.bottom_left().x();
  340. int x2 = cell_rect.bottom_right().x();
  341. int y = cell_rect.bottom_left().y();
  342. for (int x = x1; x <= x2; ++x) {
  343. if ((x % 3) == 0)
  344. painter.set_pixel({ x, y }, dotted_line_color);
  345. }
  346. }
  347. }
  348. }
  349. // Paint the hovered link rects, if any.
  350. for (auto rect : hovered_href_rects) {
  351. rect.inflate(6, 6);
  352. painter.fill_rect(rect, palette().base());
  353. painter.draw_rect(rect.inflated(2, 2).intersected(frame_inner_rect()), palette().base_text());
  354. }
  355. // Pass: Paint foreground (text).
  356. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  357. auto row_rect = this->row_rect(visual_row);
  358. if (!event.rect().contains(row_rect))
  359. continue;
  360. auto& line = m_terminal.line(first_row_from_history + visual_row);
  361. for (size_t column = 0; column < line.length(); ++column) {
  362. auto attribute = line.attribute_at(column);
  363. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  364. && m_has_logical_focus
  365. && visual_row == row_with_cursor
  366. && column == m_terminal.cursor_column();
  367. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  368. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color());
  369. u32 code_point = line.code_point(column);
  370. if (code_point == ' ')
  371. continue;
  372. auto character_rect = glyph_rect(visual_row, column);
  373. if (!m_hovered_href_id.is_null() && attribute.href_id == m_hovered_href_id) {
  374. text_color = palette().base_text();
  375. }
  376. painter.draw_glyph_or_emoji(
  377. character_rect.location(),
  378. code_point,
  379. attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
  380. text_color);
  381. }
  382. }
  383. // Draw cursor.
  384. if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
  385. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  386. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  387. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  388. painter.draw_rect(cell_rect, color_from_rgb(cursor_line.attribute_at(m_terminal.cursor_column()).effective_foreground_color()));
  389. }
  390. }
  391. }
  392. void TerminalWidget::set_window_progress(int value, int max)
  393. {
  394. float float_value = value;
  395. float float_max = max;
  396. float progress = (float_value / float_max) * 100.0f;
  397. window()->set_progress((int)roundf(progress));
  398. }
  399. void TerminalWidget::set_window_title(const StringView& title)
  400. {
  401. if (!Utf8View(title).validate()) {
  402. dbgln("TerminalWidget: Attempted to set window title to invalid UTF-8 string");
  403. return;
  404. }
  405. if (on_title_change)
  406. on_title_change(title);
  407. }
  408. void TerminalWidget::invalidate_cursor()
  409. {
  410. m_terminal.invalidate_cursor();
  411. }
  412. void TerminalWidget::flush_dirty_lines()
  413. {
  414. // FIXME: Update smarter when scrolled
  415. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  416. update();
  417. m_terminal.m_need_full_flush = false;
  418. return;
  419. }
  420. Gfx::IntRect rect;
  421. for (int i = 0; i < m_terminal.rows(); ++i) {
  422. if (m_terminal.visible_line(i).is_dirty()) {
  423. rect = rect.united(row_rect(i));
  424. m_terminal.visible_line(i).set_dirty(false);
  425. }
  426. }
  427. update(rect);
  428. }
  429. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  430. {
  431. relayout(event.size());
  432. }
  433. void TerminalWidget::relayout(const Gfx::IntSize& size)
  434. {
  435. if (!m_scrollbar)
  436. return;
  437. TemporaryChange change(m_in_relayout, true);
  438. auto base_size = compute_base_size();
  439. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  440. int new_rows = (size.height() - base_size.height()) / m_line_height;
  441. m_terminal.set_size(new_columns, new_rows);
  442. Gfx::IntRect scrollbar_rect = {
  443. size.width() - m_scrollbar->width() - frame_thickness(),
  444. frame_thickness(),
  445. m_scrollbar->width(),
  446. size.height() - frame_thickness() * 2,
  447. };
  448. m_scrollbar->set_relative_rect(scrollbar_rect);
  449. m_scrollbar->set_page_step(new_rows);
  450. }
  451. Gfx::IntSize TerminalWidget::compute_base_size() const
  452. {
  453. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  454. int base_height = frame_thickness() * 2 + m_inset * 2;
  455. return { base_width, base_height };
  456. }
  457. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  458. {
  459. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  460. window.set_base_size(compute_base_size());
  461. }
  462. void TerminalWidget::update_cursor()
  463. {
  464. invalidate_cursor();
  465. flush_dirty_lines();
  466. }
  467. void TerminalWidget::set_opacity(u8 new_opacity)
  468. {
  469. if (m_opacity == new_opacity)
  470. return;
  471. window()->set_has_alpha_channel(new_opacity < 255);
  472. m_opacity = new_opacity;
  473. update();
  474. }
  475. bool TerminalWidget::has_selection() const
  476. {
  477. return m_selection.is_valid();
  478. }
  479. void TerminalWidget::set_selection(const VT::Range& selection)
  480. {
  481. m_selection = selection;
  482. update_copy_action();
  483. update();
  484. }
  485. bool TerminalWidget::selection_contains(const VT::Position& position) const
  486. {
  487. if (!has_selection())
  488. return false;
  489. if (m_rectangle_selection) {
  490. auto m_selection_start = m_selection.start();
  491. auto m_selection_end = m_selection.end();
  492. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  493. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  494. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  495. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  496. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  497. }
  498. auto normalized_selection = m_selection.normalized();
  499. return position >= normalized_selection.start() && position <= normalized_selection.end();
  500. }
  501. VT::Position TerminalWidget::buffer_position_at(const Gfx::IntPoint& position) const
  502. {
  503. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  504. int row = adjusted_position.y() / m_line_height;
  505. int column = adjusted_position.x() / font().glyph_width('x');
  506. if (row < 0)
  507. row = 0;
  508. if (column < 0)
  509. column = 0;
  510. if (row >= m_terminal.rows())
  511. row = m_terminal.rows() - 1;
  512. if (column >= m_terminal.columns())
  513. column = m_terminal.columns() - 1;
  514. row += m_scrollbar->value();
  515. return { row, column };
  516. }
  517. u32 TerminalWidget::code_point_at(const VT::Position& position) const
  518. {
  519. VERIFY(position.is_valid());
  520. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  521. auto& line = m_terminal.line(position.row());
  522. if (static_cast<size_t>(position.column()) == line.length())
  523. return '\n';
  524. return line.code_point(position.column());
  525. }
  526. VT::Position TerminalWidget::next_position_after(const VT::Position& position, bool should_wrap) 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. if (static_cast<size_t>(position.row()) == m_terminal.line_count() - 1) {
  533. if (should_wrap)
  534. return { 0, 0 };
  535. return {};
  536. }
  537. return { position.row() + 1, 0 };
  538. }
  539. return { position.row(), position.column() + 1 };
  540. }
  541. VT::Position TerminalWidget::previous_position_before(const VT::Position& position, bool should_wrap) const
  542. {
  543. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  544. if (position.column() == 0) {
  545. if (position.row() == 0) {
  546. if (should_wrap) {
  547. auto& last_line = m_terminal.line(m_terminal.line_count() - 1);
  548. return { static_cast<int>(m_terminal.line_count() - 1), static_cast<int>(last_line.length()) };
  549. }
  550. return {};
  551. }
  552. auto& prev_line = m_terminal.line(position.row() - 1);
  553. return { position.row() - 1, static_cast<int>(prev_line.length()) };
  554. }
  555. return { position.row(), position.column() - 1 };
  556. }
  557. static u32 to_lowercase_code_point(u32 code_point)
  558. {
  559. // FIXME: this only handles ascii characters, but handling unicode lowercasing seems like a mess
  560. if (code_point < 128)
  561. return tolower(code_point);
  562. return code_point;
  563. }
  564. VT::Range TerminalWidget::find_next(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  565. {
  566. if (needle.is_empty())
  567. return {};
  568. VT::Position position = start.is_valid() ? start : VT::Position(0, 0);
  569. VT::Position original_position = position;
  570. VT::Position start_of_potential_match;
  571. size_t needle_index = 0;
  572. do {
  573. auto ch = code_point_at(position);
  574. // FIXME: This is not the right way to use a Unicode needle!
  575. auto needle_ch = (u32)needle[needle_index];
  576. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  577. if (needle_index == 0)
  578. start_of_potential_match = position;
  579. ++needle_index;
  580. if (needle_index >= needle.length())
  581. return { start_of_potential_match, position };
  582. } else {
  583. if (needle_index > 0)
  584. position = start_of_potential_match;
  585. needle_index = 0;
  586. }
  587. position = next_position_after(position, should_wrap);
  588. } while (position.is_valid() && position != original_position);
  589. return {};
  590. }
  591. VT::Range TerminalWidget::find_previous(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  592. {
  593. if (needle.is_empty())
  594. return {};
  595. VT::Position position = start.is_valid() ? start : VT::Position(m_terminal.line_count() - 1, m_terminal.line(m_terminal.line_count() - 1).length() - 1);
  596. VT::Position original_position = position;
  597. VT::Position end_of_potential_match;
  598. size_t needle_index = needle.length() - 1;
  599. do {
  600. auto ch = code_point_at(position);
  601. // FIXME: This is not the right way to use a Unicode needle!
  602. auto needle_ch = (u32)needle[needle_index];
  603. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  604. if (needle_index == needle.length() - 1)
  605. end_of_potential_match = position;
  606. if (needle_index == 0)
  607. return { position, end_of_potential_match };
  608. --needle_index;
  609. } else {
  610. if (needle_index < needle.length() - 1)
  611. position = end_of_potential_match;
  612. needle_index = needle.length() - 1;
  613. }
  614. position = previous_position_before(position, should_wrap);
  615. } while (position.is_valid() && position != original_position);
  616. return {};
  617. }
  618. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  619. {
  620. if (event.button() == GUI::MouseButton::Left) {
  621. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  622. if (!attribute.href_id.is_null()) {
  623. dbgln("Open hyperlinked URL: '{}'", attribute.href);
  624. Desktop::Launcher::open(attribute.href);
  625. return;
  626. }
  627. m_triple_click_timer.start();
  628. auto position = buffer_position_at(event.position());
  629. auto& line = m_terminal.line(position.row());
  630. bool want_whitespace = line.code_point(position.column()) == ' ';
  631. int start_column = 0;
  632. int end_column = 0;
  633. for (int column = position.column(); column >= 0 && (line.code_point(column) == ' ') == want_whitespace; --column) {
  634. start_column = column;
  635. }
  636. for (int column = position.column(); column < m_terminal.columns() && (line.code_point(column) == ' ') == want_whitespace; ++column) {
  637. end_column = column;
  638. }
  639. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  640. update_copy_action();
  641. update();
  642. }
  643. GUI::Frame::doubleclick_event(event);
  644. }
  645. void TerminalWidget::paste()
  646. {
  647. if (m_ptm_fd == -1)
  648. return;
  649. auto mime_type = GUI::Clipboard::the().mime_type();
  650. if (!mime_type.starts_with("text/"))
  651. return;
  652. auto text = GUI::Clipboard::the().data();
  653. if (text.is_empty())
  654. return;
  655. int nwritten = write(m_ptm_fd, text.data(), text.size());
  656. if (nwritten < 0) {
  657. perror("write");
  658. VERIFY_NOT_REACHED();
  659. }
  660. }
  661. void TerminalWidget::copy()
  662. {
  663. if (has_selection())
  664. GUI::Clipboard::the().set_plain_text(selected_text());
  665. }
  666. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  667. {
  668. if (event.button() == GUI::MouseButton::Left) {
  669. if (!m_active_href_id.is_null()) {
  670. m_active_href = {};
  671. m_active_href_id = {};
  672. update();
  673. }
  674. m_auto_scroll_direction = AutoScrollDirection::None;
  675. }
  676. }
  677. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  678. {
  679. if (event.button() == GUI::MouseButton::Left) {
  680. m_left_mousedown_position = event.position();
  681. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  682. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  683. m_active_href = attribute.href;
  684. m_active_href_id = attribute.href_id;
  685. update();
  686. return;
  687. }
  688. m_active_href = {};
  689. m_active_href_id = {};
  690. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  691. int start_column = 0;
  692. int end_column = m_terminal.columns() - 1;
  693. auto position = buffer_position_at(event.position());
  694. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  695. } else {
  696. m_selection.set(buffer_position_at(event.position()), {});
  697. }
  698. if (m_alt_key_held)
  699. m_rectangle_selection = true;
  700. else if (m_rectangle_selection)
  701. m_rectangle_selection = false;
  702. update_copy_action();
  703. update();
  704. }
  705. }
  706. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  707. {
  708. auto position = buffer_position_at(event.position());
  709. auto attribute = m_terminal.attribute_at(position);
  710. if (attribute.href_id != m_hovered_href_id) {
  711. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  712. m_hovered_href_id = attribute.href_id;
  713. m_hovered_href = attribute.href;
  714. } else {
  715. m_hovered_href_id = {};
  716. m_hovered_href = {};
  717. }
  718. set_tooltip(m_hovered_href);
  719. show_or_hide_tooltip();
  720. if (!m_hovered_href.is_empty())
  721. set_override_cursor(Gfx::StandardCursor::Arrow);
  722. else
  723. set_override_cursor(Gfx::StandardCursor::IBeam);
  724. update();
  725. }
  726. if (!(event.buttons() & GUI::MouseButton::Left))
  727. return;
  728. if (!m_active_href_id.is_null()) {
  729. auto diff = event.position() - m_left_mousedown_position;
  730. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  731. constexpr int drag_distance_threshold = 5;
  732. if (distance_travelled_squared <= drag_distance_threshold)
  733. return;
  734. auto drag_operation = GUI::DragOperation::construct();
  735. drag_operation->set_text(m_active_href);
  736. drag_operation->set_data("text/uri-list", m_active_href);
  737. drag_operation->exec();
  738. m_active_href = {};
  739. m_active_href_id = {};
  740. m_hovered_href = {};
  741. m_hovered_href_id = {};
  742. update();
  743. return;
  744. }
  745. auto adjusted_position = event.position().translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  746. if (adjusted_position.y() < 0)
  747. m_auto_scroll_direction = AutoScrollDirection::Up;
  748. else if (adjusted_position.y() > m_terminal.rows() * m_line_height)
  749. m_auto_scroll_direction = AutoScrollDirection::Down;
  750. else
  751. m_auto_scroll_direction = AutoScrollDirection::None;
  752. VT::Position old_selection_end = m_selection.end();
  753. m_selection.set_end(position);
  754. if (old_selection_end != m_selection.end()) {
  755. update_copy_action();
  756. update();
  757. }
  758. }
  759. void TerminalWidget::leave_event(Core::Event&)
  760. {
  761. bool should_update = !m_hovered_href.is_empty();
  762. m_hovered_href = {};
  763. m_hovered_href_id = {};
  764. set_tooltip(m_hovered_href);
  765. set_override_cursor(Gfx::StandardCursor::IBeam);
  766. if (should_update)
  767. update();
  768. }
  769. void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
  770. {
  771. if (!is_scrollable())
  772. return;
  773. m_auto_scroll_direction = AutoScrollDirection::None;
  774. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta() * scroll_length());
  775. GUI::Frame::mousewheel_event(event);
  776. }
  777. bool TerminalWidget::is_scrollable() const
  778. {
  779. return m_scrollbar->is_scrollable();
  780. }
  781. int TerminalWidget::scroll_length() const
  782. {
  783. return m_scrollbar->step();
  784. }
  785. String TerminalWidget::selected_text() const
  786. {
  787. StringBuilder builder;
  788. auto normalized_selection = m_selection.normalized();
  789. auto start = normalized_selection.start();
  790. auto end = normalized_selection.end();
  791. for (int row = start.row(); row <= end.row(); ++row) {
  792. int first_column = first_selection_column_on_row(row);
  793. int last_column = last_selection_column_on_row(row);
  794. for (int column = first_column; column <= last_column; ++column) {
  795. auto& line = m_terminal.line(row);
  796. if (line.attribute_at(column).is_untouched()) {
  797. builder.append('\n');
  798. break;
  799. }
  800. // FIXME: This is a bit hackish.
  801. u32 code_point = line.code_point(column);
  802. builder.append(Utf32View(&code_point, 1));
  803. if (column == static_cast<int>(line.length()) - 1 || (m_rectangle_selection && column == last_column)) {
  804. builder.append('\n');
  805. }
  806. }
  807. }
  808. return builder.to_string();
  809. }
  810. int TerminalWidget::first_selection_column_on_row(int row) const
  811. {
  812. auto normalized_selection_start = m_selection.normalized().start();
  813. return row == normalized_selection_start.row() || m_rectangle_selection ? normalized_selection_start.column() : 0;
  814. }
  815. int TerminalWidget::last_selection_column_on_row(int row) const
  816. {
  817. auto normalized_selection_end = m_selection.normalized().end();
  818. return row == normalized_selection_end.row() || m_rectangle_selection ? normalized_selection_end.column() : m_terminal.columns() - 1;
  819. }
  820. void TerminalWidget::terminal_history_changed()
  821. {
  822. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  823. m_scrollbar->set_max(m_terminal.history_size());
  824. if (was_max)
  825. m_scrollbar->set_value(m_scrollbar->max());
  826. m_scrollbar->update();
  827. }
  828. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  829. {
  830. auto pixel_size = widget_size_for_font(font());
  831. m_pixel_width = pixel_size.width();
  832. m_pixel_height = pixel_size.height();
  833. if (!m_in_relayout) {
  834. if (on_terminal_size_change)
  835. on_terminal_size_change(Gfx::IntSize { m_pixel_width, m_pixel_height });
  836. }
  837. if (m_automatic_size_policy) {
  838. set_fixed_size(m_pixel_width, m_pixel_height);
  839. }
  840. update();
  841. winsize ws;
  842. ws.ws_row = rows;
  843. ws.ws_col = columns;
  844. if (m_ptm_fd != -1) {
  845. if (ioctl(m_ptm_fd, TIOCSWINSZ, &ws) < 0) {
  846. // This can happen if we resize just as the shell exits.
  847. dbgln("Notifying the pseudo-terminal about a size change failed.");
  848. }
  849. }
  850. }
  851. void TerminalWidget::beep()
  852. {
  853. if (m_bell_mode == BellMode::Disabled) {
  854. return;
  855. }
  856. if (m_bell_mode == BellMode::AudibleBeep) {
  857. sysbeep();
  858. return;
  859. }
  860. m_visual_beep_timer->restart(200);
  861. m_visual_beep_timer->set_single_shot(true);
  862. m_visual_beep_timer->on_timeout = [this] {
  863. update();
  864. };
  865. update();
  866. }
  867. void TerminalWidget::emit(const u8* data, size_t size)
  868. {
  869. if (write(m_ptm_fd, data, size) < 0) {
  870. perror("TerminalWidget::emit: write");
  871. }
  872. }
  873. void TerminalWidget::context_menu_event(GUI::ContextMenuEvent& event)
  874. {
  875. if (m_hovered_href_id.is_null()) {
  876. m_context_menu->popup(event.screen_position());
  877. } else {
  878. m_context_menu_href = m_hovered_href;
  879. // Ask LaunchServer for a list of programs that can handle the right-clicked URL.
  880. auto handlers = Desktop::Launcher::get_handlers_for_url(m_hovered_href);
  881. if (handlers.is_empty()) {
  882. m_context_menu->popup(event.screen_position());
  883. return;
  884. }
  885. m_context_menu_for_hyperlink = GUI::Menu::construct();
  886. RefPtr<GUI::Action> context_menu_default_action;
  887. // Go through the list of handlers and see if we can find a nice display name + icon for them.
  888. // Then add them to the context menu.
  889. // FIXME: Adapt this code when we actually support calling LaunchServer with a specific handler in mind.
  890. for (auto& handler : handlers) {
  891. auto af = Desktop::AppFile::get_for_app(LexicalPath(handler).basename());
  892. if (!af->is_valid())
  893. continue;
  894. auto action = GUI::Action::create(String::formatted("&Open in {}", af->name()), af->icon().bitmap_for_size(16), [this, handler](auto&) {
  895. Desktop::Launcher::open(m_context_menu_href, handler);
  896. });
  897. if (context_menu_default_action.is_null()) {
  898. context_menu_default_action = action;
  899. }
  900. m_context_menu_for_hyperlink->add_action(action);
  901. }
  902. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy &URL", [this](auto&) {
  903. GUI::Clipboard::the().set_plain_text(m_context_menu_href);
  904. }));
  905. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy &Name", [&](auto&) {
  906. // file://courage/home/anon/something -> /home/anon/something
  907. auto path = URL(m_context_menu_href).path();
  908. // /home/anon/something -> something
  909. auto name = LexicalPath(path).basename();
  910. GUI::Clipboard::the().set_plain_text(name);
  911. }));
  912. m_context_menu_for_hyperlink->add_separator();
  913. m_context_menu_for_hyperlink->add_action(copy_action());
  914. m_context_menu_for_hyperlink->add_action(paste_action());
  915. m_context_menu_for_hyperlink->popup(event.screen_position(), context_menu_default_action);
  916. }
  917. }
  918. void TerminalWidget::drop_event(GUI::DropEvent& event)
  919. {
  920. if (event.mime_data().has_text()) {
  921. event.accept();
  922. auto text = event.mime_data().text();
  923. write(m_ptm_fd, text.characters(), text.length());
  924. } else if (event.mime_data().has_urls()) {
  925. event.accept();
  926. auto urls = event.mime_data().urls();
  927. bool first = true;
  928. for (auto& url : event.mime_data().urls()) {
  929. if (!first) {
  930. write(m_ptm_fd, " ", 1);
  931. first = false;
  932. }
  933. if (url.protocol() == "file")
  934. write(m_ptm_fd, url.path().characters(), url.path().length());
  935. else
  936. write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
  937. }
  938. }
  939. }
  940. void TerminalWidget::did_change_font()
  941. {
  942. GUI::Frame::did_change_font();
  943. m_line_height = font().glyph_height() + m_line_spacing;
  944. // TODO: try to find a bold version of the new font (e.g. CsillaThin7x10 -> CsillaBold7x10)
  945. const Gfx::Font& bold_font = Gfx::FontDatabase::default_bold_fixed_width_font();
  946. if (bold_font.glyph_height() == font().glyph_height() && bold_font.glyph_width(' ') == font().glyph_width(' '))
  947. m_bold_font = &bold_font;
  948. else
  949. m_bold_font = font();
  950. if (!size().is_empty())
  951. relayout(size());
  952. }
  953. void TerminalWidget::clear_including_history()
  954. {
  955. m_terminal.clear_including_history();
  956. }
  957. void TerminalWidget::scroll_to_bottom()
  958. {
  959. m_scrollbar->set_value(m_scrollbar->max());
  960. }
  961. void TerminalWidget::scroll_to_row(int row)
  962. {
  963. m_scrollbar->set_value(row);
  964. }
  965. void TerminalWidget::update_copy_action()
  966. {
  967. m_copy_action->set_enabled(has_selection());
  968. }
  969. void TerminalWidget::update_paste_action()
  970. {
  971. m_paste_action->set_enabled(GUI::Clipboard::the().mime_type().starts_with("text/") && !GUI::Clipboard::the().data().is_empty());
  972. }
  973. Gfx::IntSize TerminalWidget::widget_size_for_font(const Gfx::Font& font) const
  974. {
  975. return {
  976. (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.columns() * font.glyph_width('x')) + m_scrollbar->width(),
  977. (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.rows() * (font.glyph_height() + m_line_spacing))
  978. };
  979. }
  980. void TerminalWidget::set_font_and_resize_to_fit(const Gfx::Font& font)
  981. {
  982. set_font(font);
  983. resize(widget_size_for_font(font));
  984. }
  985. }