TerminalWidget.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. void TerminalWidget::set_pty_master_fd(int fd)
  60. {
  61. m_ptm_fd = fd;
  62. if (m_ptm_fd == -1) {
  63. m_notifier = nullptr;
  64. return;
  65. }
  66. m_notifier = Core::Notifier::construct(m_ptm_fd, Core::Notifier::Read);
  67. m_notifier->on_ready_to_read = [this] {
  68. u8 buffer[BUFSIZ];
  69. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  70. if (nread < 0) {
  71. dbgln("Terminal read error: {}", strerror(errno));
  72. perror("read(ptm)");
  73. GUI::Application::the()->quit(1);
  74. return;
  75. }
  76. if (nread == 0) {
  77. dbgln("TerminalWidget: EOF on master pty, firing on_command_exit hook.");
  78. if (on_command_exit)
  79. on_command_exit();
  80. int rc = close(m_ptm_fd);
  81. if (rc < 0) {
  82. perror("close");
  83. }
  84. set_pty_master_fd(-1);
  85. return;
  86. }
  87. for (ssize_t i = 0; i < nread; ++i)
  88. m_terminal.on_input(buffer[i]);
  89. flush_dirty_lines();
  90. };
  91. }
  92. TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Core::ConfigFile> config)
  93. : m_terminal(*this)
  94. , m_automatic_size_policy(automatic_size_policy)
  95. , m_config(move(config))
  96. {
  97. set_override_cursor(Gfx::StandardCursor::IBeam);
  98. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  99. set_accepts_emoji_input(true);
  100. set_pty_master_fd(ptm_fd);
  101. m_cursor_blink_timer = add<Core::Timer>();
  102. m_visual_beep_timer = add<Core::Timer>();
  103. m_auto_scroll_timer = add<Core::Timer>();
  104. m_scrollbar = add<GUI::ScrollBar>(Orientation::Vertical);
  105. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  106. m_scrollbar->on_change = [this](int) {
  107. update();
  108. };
  109. dbgln("Load config file from {}", m_config->file_name());
  110. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  111. "CursorBlinkInterval",
  112. 500));
  113. m_cursor_blink_timer->on_timeout = [this] {
  114. m_cursor_blink_state = !m_cursor_blink_state;
  115. update_cursor();
  116. };
  117. m_auto_scroll_timer->set_interval(50);
  118. m_auto_scroll_timer->on_timeout = [this] {
  119. if (m_auto_scroll_direction != AutoScrollDirection::None) {
  120. int scroll_amount = m_auto_scroll_direction == AutoScrollDirection::Up ? -1 : 1;
  121. m_scrollbar->set_value(m_scrollbar->value() + scroll_amount);
  122. }
  123. };
  124. m_auto_scroll_timer->start();
  125. auto font_entry = m_config->read_entry("Text", "Font", "default");
  126. if (font_entry == "default")
  127. set_font(Gfx::FontDatabase::default_fixed_width_font());
  128. else
  129. set_font(Gfx::FontDatabase::the().get_by_name(font_entry));
  130. m_line_height = font().glyph_height() + m_line_spacing;
  131. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  132. 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&) {
  133. copy();
  134. });
  135. m_copy_action->set_swallow_key_event_when_disabled(true);
  136. 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&) {
  137. paste();
  138. });
  139. m_paste_action->set_swallow_key_event_when_disabled(true);
  140. m_clear_including_history_action = GUI::Action::create("Clear including history", { Mod_Ctrl | Mod_Shift, Key_K }, [this](auto&) {
  141. clear_including_history();
  142. });
  143. m_context_menu = GUI::Menu::construct();
  144. m_context_menu->add_action(copy_action());
  145. m_context_menu->add_action(paste_action());
  146. m_context_menu->add_separator();
  147. m_context_menu->add_action(clear_including_history_action());
  148. GUI::Clipboard::the().on_change = [this](const String&) {
  149. update_paste_action();
  150. };
  151. update_copy_action();
  152. update_paste_action();
  153. }
  154. TerminalWidget::~TerminalWidget()
  155. {
  156. }
  157. static inline Color color_from_rgb(unsigned color)
  158. {
  159. return Color::from_rgb(color);
  160. }
  161. Gfx::IntRect TerminalWidget::glyph_rect(u16 row, u16 column)
  162. {
  163. int y = row * m_line_height;
  164. int x = column * font().glyph_width('x');
  165. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  166. }
  167. Gfx::IntRect TerminalWidget::row_rect(u16 row)
  168. {
  169. int y = row * m_line_height;
  170. Gfx::IntRect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  171. rect.inflate(0, m_line_spacing);
  172. return rect;
  173. }
  174. void TerminalWidget::set_logical_focus(bool focus)
  175. {
  176. m_has_logical_focus = focus;
  177. if (!m_has_logical_focus) {
  178. m_cursor_blink_timer->stop();
  179. } else {
  180. m_cursor_blink_state = true;
  181. m_cursor_blink_timer->start();
  182. }
  183. m_auto_scroll_direction = AutoScrollDirection::None;
  184. invalidate_cursor();
  185. update();
  186. }
  187. void TerminalWidget::focusin_event(GUI::FocusEvent& event)
  188. {
  189. set_logical_focus(true);
  190. return GUI::Frame::focusin_event(event);
  191. }
  192. void TerminalWidget::focusout_event(GUI::FocusEvent& event)
  193. {
  194. set_logical_focus(false);
  195. return GUI::Frame::focusout_event(event);
  196. }
  197. void TerminalWidget::event(Core::Event& event)
  198. {
  199. if (event.type() == GUI::Event::WindowBecameActive)
  200. set_logical_focus(true);
  201. else if (event.type() == GUI::Event::WindowBecameInactive)
  202. set_logical_focus(false);
  203. return GUI::Frame::event(event);
  204. }
  205. void TerminalWidget::keydown_event(GUI::KeyEvent& event)
  206. {
  207. if (m_ptm_fd == -1) {
  208. event.ignore();
  209. return GUI::Frame::keydown_event(event);
  210. }
  211. // Reset timer so cursor doesn't blink while typing.
  212. m_cursor_blink_timer->stop();
  213. m_cursor_blink_state = true;
  214. m_cursor_blink_timer->start();
  215. if (event.key() == KeyCode::Key_PageUp && event.modifiers() == Mod_Shift) {
  216. m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
  217. return;
  218. }
  219. if (event.key() == KeyCode::Key_PageDown && event.modifiers() == Mod_Shift) {
  220. m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
  221. return;
  222. }
  223. if (event.key() == KeyCode::Key_Alt) {
  224. m_alt_key_held = true;
  225. return;
  226. }
  227. // Clear the selection if we type in/behind it.
  228. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  229. auto min_selection_row = min(m_selection.start().row(), m_selection.end().row());
  230. auto max_selection_row = max(m_selection.start().row(), m_selection.end().row());
  231. 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) {
  232. m_selection.set_end({});
  233. update_copy_action();
  234. update();
  235. }
  236. m_terminal.handle_key_press(event.key(), event.code_point(), event.modifiers());
  237. if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_LeftShift && event.key() != Key_RightShift && event.key() != Key_Logo)
  238. scroll_to_bottom();
  239. }
  240. void TerminalWidget::keyup_event(GUI::KeyEvent& event)
  241. {
  242. switch (event.key()) {
  243. case KeyCode::Key_Alt:
  244. m_alt_key_held = false;
  245. return;
  246. default:
  247. break;
  248. }
  249. }
  250. void TerminalWidget::paint_event(GUI::PaintEvent& event)
  251. {
  252. GUI::Frame::paint_event(event);
  253. GUI::Painter painter(*this);
  254. auto visual_beep_active = m_visual_beep_timer->is_active();
  255. painter.add_clip_rect(event.rect());
  256. Gfx::IntRect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
  257. painter.add_clip_rect(terminal_buffer_rect);
  258. if (visual_beep_active)
  259. painter.clear_rect(frame_inner_rect(), Color::Red);
  260. else
  261. painter.clear_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  262. invalidate_cursor();
  263. int rows_from_history = 0;
  264. int first_row_from_history = m_terminal.history_size();
  265. int row_with_cursor = m_terminal.cursor_row();
  266. if (m_scrollbar->value() != m_scrollbar->max()) {
  267. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  268. first_row_from_history = m_terminal.history_size() - (m_scrollbar->max() - m_scrollbar->value());
  269. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  270. }
  271. // Pass: Compute the rect(s) of the currently hovered link, if any.
  272. Vector<Gfx::IntRect> hovered_href_rects;
  273. if (!m_hovered_href_id.is_null()) {
  274. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  275. auto& line = m_terminal.line(first_row_from_history + visual_row);
  276. for (size_t column = 0; column < line.length(); ++column) {
  277. if (m_hovered_href_id == line.attributes()[column].href_id) {
  278. bool merged_with_existing_rect = false;
  279. auto glyph_rect = this->glyph_rect(visual_row, column);
  280. for (auto& rect : hovered_href_rects) {
  281. if (rect.inflated(1, 1).intersects(glyph_rect)) {
  282. rect = rect.united(glyph_rect);
  283. merged_with_existing_rect = true;
  284. break;
  285. }
  286. }
  287. if (!merged_with_existing_rect)
  288. hovered_href_rects.append(glyph_rect);
  289. }
  290. }
  291. }
  292. }
  293. // Pass: Paint background & text decorations.
  294. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  295. auto row_rect = this->row_rect(visual_row);
  296. if (!event.rect().contains(row_rect))
  297. continue;
  298. auto& line = m_terminal.line(first_row_from_history + visual_row);
  299. bool has_only_one_background_color = line.has_only_one_background_color();
  300. if (visual_beep_active)
  301. painter.clear_rect(row_rect, Color::Red);
  302. else if (has_only_one_background_color)
  303. painter.clear_rect(row_rect, color_from_rgb(line.attributes()[0].effective_background_color()).with_alpha(m_opacity));
  304. for (size_t column = 0; column < line.length(); ++column) {
  305. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  306. && m_has_logical_focus
  307. && visual_row == row_with_cursor
  308. && column == m_terminal.cursor_column();
  309. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  310. auto attribute = line.attributes()[column];
  311. auto character_rect = glyph_rect(visual_row, column);
  312. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  313. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color());
  314. if ((!visual_beep_active && !has_only_one_background_color) || should_reverse_fill_for_cursor_or_selection)
  315. painter.clear_rect(cell_rect, color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_foreground_color() : attribute.effective_background_color()));
  316. enum class UnderlineStyle {
  317. None,
  318. Dotted,
  319. Solid,
  320. };
  321. auto underline_style = UnderlineStyle::None;
  322. if (attribute.flags & VT::Attribute::Underline) {
  323. // Content has specified underline
  324. underline_style = UnderlineStyle::Solid;
  325. } else if (!attribute.href.is_empty()) {
  326. // We're hovering a hyperlink
  327. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id)
  328. underline_style = UnderlineStyle::Solid;
  329. else
  330. underline_style = UnderlineStyle::Dotted;
  331. }
  332. if (underline_style == UnderlineStyle::Solid) {
  333. if (attribute.href_id == m_active_href_id && m_hovered_href_id == m_active_href_id)
  334. text_color = palette().active_link();
  335. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), text_color);
  336. } else if (underline_style == UnderlineStyle::Dotted) {
  337. auto dotted_line_color = text_color.darkened(0.6f);
  338. int x1 = cell_rect.bottom_left().x();
  339. int x2 = cell_rect.bottom_right().x();
  340. int y = cell_rect.bottom_left().y();
  341. for (int x = x1; x <= x2; ++x) {
  342. if ((x % 3) == 0)
  343. painter.set_pixel({ x, y }, dotted_line_color);
  344. }
  345. }
  346. }
  347. }
  348. // Paint the hovered link rects, if any.
  349. for (auto rect : hovered_href_rects) {
  350. rect.inflate(6, 6);
  351. painter.fill_rect(rect, palette().base());
  352. painter.draw_rect(rect.inflated(2, 2).intersected(frame_inner_rect()), palette().base_text());
  353. }
  354. // Pass: Paint foreground (text).
  355. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  356. auto row_rect = this->row_rect(visual_row);
  357. if (!event.rect().contains(row_rect))
  358. continue;
  359. auto& line = m_terminal.line(first_row_from_history + visual_row);
  360. for (size_t column = 0; column < line.length(); ++column) {
  361. auto attribute = line.attributes()[column];
  362. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  363. && m_has_logical_focus
  364. && visual_row == row_with_cursor
  365. && column == m_terminal.cursor_column();
  366. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  367. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color());
  368. u32 code_point = line.code_point(column);
  369. if (code_point == ' ')
  370. continue;
  371. auto character_rect = glyph_rect(visual_row, column);
  372. if (!m_hovered_href_id.is_null() && attribute.href_id == m_hovered_href_id) {
  373. text_color = palette().base_text();
  374. }
  375. painter.draw_glyph_or_emoji(
  376. character_rect.location(),
  377. code_point,
  378. attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
  379. text_color);
  380. }
  381. }
  382. // Draw cursor.
  383. if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
  384. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  385. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  386. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  387. painter.draw_rect(cell_rect, color_from_rgb(cursor_line.attributes()[m_terminal.cursor_column()].effective_foreground_color()));
  388. }
  389. }
  390. }
  391. void TerminalWidget::set_window_progress(int value, int max)
  392. {
  393. float float_value = value;
  394. float float_max = max;
  395. float progress = (float_value / float_max) * 100.0f;
  396. window()->set_progress((int)roundf(progress));
  397. }
  398. void TerminalWidget::set_window_title(const StringView& title)
  399. {
  400. if (!Utf8View(title).validate()) {
  401. dbgln("TerminalWidget: Attempted to set window title to invalid UTF-8 string");
  402. return;
  403. }
  404. if (on_title_change)
  405. on_title_change(title);
  406. }
  407. void TerminalWidget::invalidate_cursor()
  408. {
  409. m_terminal.invalidate_cursor();
  410. }
  411. void TerminalWidget::flush_dirty_lines()
  412. {
  413. // FIXME: Update smarter when scrolled
  414. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  415. update();
  416. m_terminal.m_need_full_flush = false;
  417. return;
  418. }
  419. Gfx::IntRect rect;
  420. for (int i = 0; i < m_terminal.rows(); ++i) {
  421. if (m_terminal.visible_line(i).is_dirty()) {
  422. rect = rect.united(row_rect(i));
  423. m_terminal.visible_line(i).set_dirty(false);
  424. }
  425. }
  426. update(rect);
  427. }
  428. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  429. {
  430. relayout(event.size());
  431. }
  432. void TerminalWidget::relayout(const Gfx::IntSize& size)
  433. {
  434. if (!m_scrollbar)
  435. return;
  436. TemporaryChange change(m_in_relayout, true);
  437. auto base_size = compute_base_size();
  438. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  439. int new_rows = (size.height() - base_size.height()) / m_line_height;
  440. m_terminal.set_size(new_columns, new_rows);
  441. Gfx::IntRect scrollbar_rect = {
  442. size.width() - m_scrollbar->width() - frame_thickness(),
  443. frame_thickness(),
  444. m_scrollbar->width(),
  445. size.height() - frame_thickness() * 2,
  446. };
  447. m_scrollbar->set_relative_rect(scrollbar_rect);
  448. m_scrollbar->set_page_step(new_rows);
  449. }
  450. Gfx::IntSize TerminalWidget::compute_base_size() const
  451. {
  452. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  453. int base_height = frame_thickness() * 2 + m_inset * 2;
  454. return { base_width, base_height };
  455. }
  456. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  457. {
  458. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  459. window.set_base_size(compute_base_size());
  460. }
  461. void TerminalWidget::update_cursor()
  462. {
  463. invalidate_cursor();
  464. flush_dirty_lines();
  465. }
  466. void TerminalWidget::set_opacity(u8 new_opacity)
  467. {
  468. if (m_opacity == new_opacity)
  469. return;
  470. window()->set_has_alpha_channel(new_opacity < 255);
  471. m_opacity = new_opacity;
  472. update();
  473. }
  474. bool TerminalWidget::has_selection() const
  475. {
  476. return m_selection.is_valid();
  477. }
  478. void TerminalWidget::set_selection(const VT::Range& selection)
  479. {
  480. m_selection = selection;
  481. update_copy_action();
  482. update();
  483. }
  484. bool TerminalWidget::selection_contains(const VT::Position& position) const
  485. {
  486. if (!has_selection())
  487. return false;
  488. if (m_rectangle_selection) {
  489. auto m_selection_start = m_selection.start();
  490. auto m_selection_end = m_selection.end();
  491. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  492. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  493. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  494. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  495. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  496. }
  497. auto normalized_selection = m_selection.normalized();
  498. return position >= normalized_selection.start() && position <= normalized_selection.end();
  499. }
  500. VT::Position TerminalWidget::buffer_position_at(const Gfx::IntPoint& position) const
  501. {
  502. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  503. int row = adjusted_position.y() / m_line_height;
  504. int column = adjusted_position.x() / font().glyph_width('x');
  505. if (row < 0)
  506. row = 0;
  507. if (column < 0)
  508. column = 0;
  509. if (row >= m_terminal.rows())
  510. row = m_terminal.rows() - 1;
  511. if (column >= m_terminal.columns())
  512. column = m_terminal.columns() - 1;
  513. row += m_scrollbar->value();
  514. return { row, column };
  515. }
  516. u32 TerminalWidget::code_point_at(const VT::Position& position) const
  517. {
  518. ASSERT(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  519. auto& line = m_terminal.line(position.row());
  520. if (position.column() == line.length())
  521. return '\n';
  522. return line.code_point(position.column());
  523. }
  524. VT::Position TerminalWidget::next_position_after(const VT::Position& position, bool should_wrap) const
  525. {
  526. ASSERT(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  527. auto& line = m_terminal.line(position.row());
  528. if (position.column() == line.length()) {
  529. if (static_cast<size_t>(position.row()) == m_terminal.line_count() - 1) {
  530. if (should_wrap)
  531. return { 0, 0 };
  532. return {};
  533. }
  534. return { position.row() + 1, 0 };
  535. }
  536. return { position.row(), position.column() + 1 };
  537. }
  538. VT::Position TerminalWidget::previous_position_before(const VT::Position& position, bool should_wrap) const
  539. {
  540. ASSERT(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  541. if (position.column() == 0) {
  542. if (position.row() == 0) {
  543. if (should_wrap) {
  544. auto& last_line = m_terminal.line(m_terminal.line_count() - 1);
  545. return { static_cast<int>(m_terminal.line_count() - 1), last_line.length() };
  546. }
  547. return {};
  548. }
  549. auto& prev_line = m_terminal.line(position.row() - 1);
  550. return { position.row() - 1, prev_line.length() };
  551. }
  552. return { position.row(), position.column() - 1 };
  553. }
  554. static u32 to_lowercase_code_point(u32 code_point)
  555. {
  556. // FIXME: this only handles ascii characters, but handling unicode lowercasing seems like a mess
  557. if (code_point < 128)
  558. return tolower(code_point);
  559. return code_point;
  560. }
  561. VT::Range TerminalWidget::find_next(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  562. {
  563. if (needle.is_empty())
  564. return {};
  565. VT::Position position = start.is_valid() ? start : VT::Position(0, 0);
  566. VT::Position original_position = position;
  567. VT::Position start_of_potential_match;
  568. size_t needle_index = 0;
  569. do {
  570. auto ch = code_point_at(position);
  571. // FIXME: This is not the right way to use a Unicode needle!
  572. auto needle_ch = (u32)needle[needle_index];
  573. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  574. if (needle_index == 0)
  575. start_of_potential_match = position;
  576. ++needle_index;
  577. if (needle_index >= needle.length())
  578. return { start_of_potential_match, position };
  579. } else {
  580. if (needle_index > 0)
  581. position = start_of_potential_match;
  582. needle_index = 0;
  583. }
  584. position = next_position_after(position, should_wrap);
  585. } while (position.is_valid() && position != original_position);
  586. return {};
  587. }
  588. VT::Range TerminalWidget::find_previous(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  589. {
  590. if (needle.is_empty())
  591. return {};
  592. VT::Position position = start.is_valid() ? start : VT::Position(m_terminal.line_count() - 1, m_terminal.line(m_terminal.line_count() - 1).length() - 1);
  593. VT::Position original_position = position;
  594. VT::Position end_of_potential_match;
  595. size_t needle_index = needle.length() - 1;
  596. do {
  597. auto ch = code_point_at(position);
  598. // FIXME: This is not the right way to use a Unicode needle!
  599. auto needle_ch = (u32)needle[needle_index];
  600. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  601. if (needle_index == needle.length() - 1)
  602. end_of_potential_match = position;
  603. if (needle_index == 0)
  604. return { position, end_of_potential_match };
  605. --needle_index;
  606. } else {
  607. if (needle_index < needle.length() - 1)
  608. position = end_of_potential_match;
  609. needle_index = needle.length() - 1;
  610. }
  611. position = previous_position_before(position, should_wrap);
  612. } while (position.is_valid() && position != original_position);
  613. return {};
  614. }
  615. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  616. {
  617. if (event.button() == GUI::MouseButton::Left) {
  618. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  619. if (!attribute.href_id.is_null()) {
  620. dbgln("Open hyperlinked URL: '{}'", attribute.href);
  621. Desktop::Launcher::open(attribute.href);
  622. return;
  623. }
  624. m_triple_click_timer.start();
  625. auto position = buffer_position_at(event.position());
  626. auto& line = m_terminal.line(position.row());
  627. bool want_whitespace = line.code_point(position.column()) == ' ';
  628. int start_column = 0;
  629. int end_column = 0;
  630. for (int column = position.column(); column >= 0 && (line.code_point(column) == ' ') == want_whitespace; --column) {
  631. start_column = column;
  632. }
  633. for (int column = position.column(); column < m_terminal.columns() && (line.code_point(column) == ' ') == want_whitespace; ++column) {
  634. end_column = column;
  635. }
  636. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  637. update_copy_action();
  638. }
  639. GUI::Frame::doubleclick_event(event);
  640. }
  641. void TerminalWidget::paste()
  642. {
  643. if (m_ptm_fd == -1)
  644. return;
  645. auto mime_type = GUI::Clipboard::the().mime_type();
  646. if (!mime_type.starts_with("text/"))
  647. return;
  648. auto text = GUI::Clipboard::the().data();
  649. if (text.is_empty())
  650. return;
  651. int nwritten = write(m_ptm_fd, text.data(), text.size());
  652. if (nwritten < 0) {
  653. perror("write");
  654. ASSERT_NOT_REACHED();
  655. }
  656. }
  657. void TerminalWidget::copy()
  658. {
  659. if (has_selection())
  660. GUI::Clipboard::the().set_plain_text(selected_text());
  661. }
  662. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  663. {
  664. if (event.button() == GUI::MouseButton::Left) {
  665. if (!m_active_href_id.is_null()) {
  666. m_active_href = {};
  667. m_active_href_id = {};
  668. update();
  669. }
  670. m_auto_scroll_direction = AutoScrollDirection::None;
  671. }
  672. }
  673. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  674. {
  675. if (event.button() == GUI::MouseButton::Left) {
  676. m_left_mousedown_position = event.position();
  677. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  678. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  679. m_active_href = attribute.href;
  680. m_active_href_id = attribute.href_id;
  681. update();
  682. return;
  683. }
  684. m_active_href = {};
  685. m_active_href_id = {};
  686. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  687. int start_column = 0;
  688. int end_column = m_terminal.columns() - 1;
  689. auto position = buffer_position_at(event.position());
  690. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  691. } else {
  692. m_selection.set(buffer_position_at(event.position()), {});
  693. }
  694. if (m_alt_key_held)
  695. m_rectangle_selection = true;
  696. else if (m_rectangle_selection)
  697. m_rectangle_selection = false;
  698. update_copy_action();
  699. update();
  700. }
  701. }
  702. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  703. {
  704. auto position = buffer_position_at(event.position());
  705. auto attribute = m_terminal.attribute_at(position);
  706. if (attribute.href_id != m_hovered_href_id) {
  707. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  708. m_hovered_href_id = attribute.href_id;
  709. m_hovered_href = attribute.href;
  710. } else {
  711. m_hovered_href_id = {};
  712. m_hovered_href = {};
  713. }
  714. set_tooltip(m_hovered_href);
  715. show_or_hide_tooltip();
  716. if (!m_hovered_href.is_empty())
  717. set_override_cursor(Gfx::StandardCursor::Arrow);
  718. else
  719. set_override_cursor(Gfx::StandardCursor::IBeam);
  720. update();
  721. }
  722. if (!(event.buttons() & GUI::MouseButton::Left))
  723. return;
  724. if (!m_active_href_id.is_null()) {
  725. auto diff = event.position() - m_left_mousedown_position;
  726. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  727. constexpr int drag_distance_threshold = 5;
  728. if (distance_travelled_squared <= drag_distance_threshold)
  729. return;
  730. auto drag_operation = GUI::DragOperation::construct();
  731. drag_operation->set_text(m_active_href);
  732. drag_operation->set_data("text/uri-list", m_active_href);
  733. drag_operation->exec();
  734. m_active_href = {};
  735. m_active_href_id = {};
  736. m_hovered_href = {};
  737. m_hovered_href_id = {};
  738. update();
  739. return;
  740. }
  741. auto adjusted_position = event.position().translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  742. if (adjusted_position.y() < 0)
  743. m_auto_scroll_direction = AutoScrollDirection::Up;
  744. else if (adjusted_position.y() > m_terminal.rows() * m_line_height)
  745. m_auto_scroll_direction = AutoScrollDirection::Down;
  746. else
  747. m_auto_scroll_direction = AutoScrollDirection::None;
  748. VT::Position old_selection_end = m_selection.end();
  749. m_selection.set_end(position);
  750. if (old_selection_end != m_selection.end()) {
  751. update_copy_action();
  752. update();
  753. }
  754. }
  755. void TerminalWidget::leave_event(Core::Event&)
  756. {
  757. bool should_update = !m_hovered_href.is_empty();
  758. m_hovered_href = {};
  759. m_hovered_href_id = {};
  760. set_tooltip(m_hovered_href);
  761. set_override_cursor(Gfx::StandardCursor::IBeam);
  762. if (should_update)
  763. update();
  764. }
  765. void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
  766. {
  767. if (!is_scrollable())
  768. return;
  769. m_auto_scroll_direction = AutoScrollDirection::None;
  770. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta() * scroll_length());
  771. GUI::Frame::mousewheel_event(event);
  772. }
  773. bool TerminalWidget::is_scrollable() const
  774. {
  775. return m_scrollbar->is_scrollable();
  776. }
  777. int TerminalWidget::scroll_length() const
  778. {
  779. return m_scrollbar->step();
  780. }
  781. String TerminalWidget::selected_text() const
  782. {
  783. StringBuilder builder;
  784. auto normalized_selection = m_selection.normalized();
  785. auto start = normalized_selection.start();
  786. auto end = normalized_selection.end();
  787. for (int row = start.row(); row <= end.row(); ++row) {
  788. int first_column = first_selection_column_on_row(row);
  789. int last_column = last_selection_column_on_row(row);
  790. for (int column = first_column; column <= last_column; ++column) {
  791. auto& line = m_terminal.line(row);
  792. if (line.attributes()[column].is_untouched()) {
  793. builder.append('\n');
  794. break;
  795. }
  796. // FIXME: This is a bit hackish.
  797. if (line.is_utf32()) {
  798. u32 code_point = line.code_point(column);
  799. builder.append(Utf32View(&code_point, 1));
  800. } else {
  801. builder.append(line.code_point(column));
  802. }
  803. if (column == 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. }