TerminalWidget.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. /*
  2. * Copyright (c) 2018-2020, 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 "XtermColors.h"
  28. #include <AK/LexicalPath.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/String.h>
  31. #include <AK/StringBuilder.h>
  32. #include <AK/Utf32View.h>
  33. #include <AK/Utf8View.h>
  34. #include <LibCore/ConfigFile.h>
  35. #include <LibCore/MimeData.h>
  36. #include <LibDesktop/Launcher.h>
  37. #include <LibGUI/Action.h>
  38. #include <LibGUI/AppFile.h>
  39. #include <LibGUI/Application.h>
  40. #include <LibGUI/Clipboard.h>
  41. #include <LibGUI/DragOperation.h>
  42. #include <LibGUI/FileIconProvider.h>
  43. #include <LibGUI/Icon.h>
  44. #include <LibGUI/Menu.h>
  45. #include <LibGUI/Painter.h>
  46. #include <LibGUI/ScrollBar.h>
  47. #include <LibGUI/Window.h>
  48. #include <LibGfx/Font.h>
  49. #include <LibGfx/FontDatabase.h>
  50. #include <LibGfx/Palette.h>
  51. #include <errno.h>
  52. #include <math.h>
  53. #include <stdio.h>
  54. #include <stdlib.h>
  55. #include <string.h>
  56. #include <sys/ioctl.h>
  57. #include <unistd.h>
  58. //#define TERMINAL_DEBUG
  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. force_repaint();
  108. };
  109. set_scroll_length(m_config->read_num_entry("Window", "ScrollLength", 4));
  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::Font::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_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_Logo)
  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. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  273. auto row_rect = this->row_rect(visual_row);
  274. if (!event.rect().contains(row_rect))
  275. continue;
  276. auto& line = m_terminal.line(first_row_from_history + visual_row);
  277. bool has_only_one_background_color = line.has_only_one_background_color();
  278. if (visual_beep_active)
  279. painter.clear_rect(row_rect, Color::Red);
  280. else if (has_only_one_background_color)
  281. painter.clear_rect(row_rect, color_from_rgb(line.attributes()[0].background_color).with_alpha(m_opacity));
  282. for (size_t column = 0; column < line.length(); ++column) {
  283. u32 code_point = line.code_point(column);
  284. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  285. && m_has_logical_focus
  286. && visual_row == row_with_cursor
  287. && column == m_terminal.cursor_column();
  288. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  289. auto attribute = line.attributes()[column];
  290. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color);
  291. auto character_rect = glyph_rect(visual_row, column);
  292. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  293. if ((!visual_beep_active && !has_only_one_background_color) || should_reverse_fill_for_cursor_or_selection) {
  294. painter.clear_rect(cell_rect, color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.foreground_color : attribute.background_color).with_alpha(m_opacity));
  295. }
  296. enum class UnderlineStyle {
  297. None,
  298. Dotted,
  299. Solid,
  300. };
  301. auto underline_style = UnderlineStyle::None;
  302. if (attribute.flags & VT::Attribute::Underline) {
  303. // Content has specified underline
  304. underline_style = UnderlineStyle::Solid;
  305. } else if (!attribute.href.is_empty()) {
  306. // We're hovering a hyperlink
  307. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id)
  308. underline_style = UnderlineStyle::Solid;
  309. else
  310. underline_style = UnderlineStyle::Dotted;
  311. }
  312. if (underline_style == UnderlineStyle::Solid) {
  313. if (attribute.href_id == m_active_href_id && m_hovered_href_id == m_active_href_id)
  314. text_color = palette().active_link();
  315. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), text_color);
  316. } else if (underline_style == UnderlineStyle::Dotted) {
  317. auto dotted_line_color = text_color.darkened(0.6f);
  318. int x1 = cell_rect.bottom_left().x();
  319. int x2 = cell_rect.bottom_right().x();
  320. int y = cell_rect.bottom_left().y();
  321. for (int x = x1; x <= x2; ++x) {
  322. if ((x % 3) == 0)
  323. painter.set_pixel({ x, y }, dotted_line_color);
  324. }
  325. }
  326. if (code_point == ' ')
  327. continue;
  328. painter.draw_glyph_or_emoji(
  329. character_rect.location(),
  330. code_point,
  331. attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
  332. text_color);
  333. }
  334. }
  335. if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
  336. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  337. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  338. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  339. painter.draw_rect(cell_rect, color_from_rgb(cursor_line.attributes()[m_terminal.cursor_column()].foreground_color));
  340. }
  341. }
  342. }
  343. void TerminalWidget::set_window_progress(int value, int max)
  344. {
  345. float float_value = value;
  346. float float_max = max;
  347. float progress = (float_value / float_max) * 100.0f;
  348. window()->set_progress((int)roundf(progress));
  349. }
  350. void TerminalWidget::set_window_title(const StringView& title)
  351. {
  352. if (!Utf8View(title).validate()) {
  353. dbgln("TerminalWidget: Attempted to set window title to invalid UTF-8 string");
  354. return;
  355. }
  356. if (on_title_change)
  357. on_title_change(title);
  358. }
  359. void TerminalWidget::invalidate_cursor()
  360. {
  361. m_terminal.invalidate_cursor();
  362. }
  363. void TerminalWidget::flush_dirty_lines()
  364. {
  365. // FIXME: Update smarter when scrolled
  366. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  367. update();
  368. m_terminal.m_need_full_flush = false;
  369. return;
  370. }
  371. Gfx::IntRect rect;
  372. for (int i = 0; i < m_terminal.rows(); ++i) {
  373. if (m_terminal.visible_line(i).is_dirty()) {
  374. rect = rect.united(row_rect(i));
  375. m_terminal.visible_line(i).set_dirty(false);
  376. }
  377. }
  378. update(rect);
  379. }
  380. void TerminalWidget::force_repaint()
  381. {
  382. m_needs_background_fill = true;
  383. update();
  384. }
  385. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  386. {
  387. relayout(event.size());
  388. }
  389. void TerminalWidget::relayout(const Gfx::IntSize& size)
  390. {
  391. if (!m_scrollbar)
  392. return;
  393. auto base_size = compute_base_size();
  394. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  395. int new_rows = (size.height() - base_size.height()) / m_line_height;
  396. m_terminal.set_size(new_columns, new_rows);
  397. Gfx::IntRect scrollbar_rect = {
  398. size.width() - m_scrollbar->width() - frame_thickness(),
  399. frame_thickness(),
  400. m_scrollbar->width(),
  401. size.height() - frame_thickness() * 2,
  402. };
  403. m_scrollbar->set_relative_rect(scrollbar_rect);
  404. m_scrollbar->set_page(new_rows);
  405. }
  406. Gfx::IntSize TerminalWidget::compute_base_size() const
  407. {
  408. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  409. int base_height = frame_thickness() * 2 + m_inset * 2;
  410. return { base_width, base_height };
  411. }
  412. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  413. {
  414. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  415. window.set_base_size(compute_base_size());
  416. }
  417. void TerminalWidget::update_cursor()
  418. {
  419. invalidate_cursor();
  420. flush_dirty_lines();
  421. }
  422. void TerminalWidget::set_opacity(u8 new_opacity)
  423. {
  424. if (m_opacity == new_opacity)
  425. return;
  426. window()->set_has_alpha_channel(new_opacity < 255);
  427. m_opacity = new_opacity;
  428. force_repaint();
  429. }
  430. VT::Position TerminalWidget::normalized_selection_start() const
  431. {
  432. if (m_selection_start < m_selection_end)
  433. return m_selection_start;
  434. return m_selection_end;
  435. }
  436. VT::Position TerminalWidget::normalized_selection_end() const
  437. {
  438. if (m_selection_start < m_selection_end)
  439. return m_selection_end;
  440. return m_selection_start;
  441. }
  442. bool TerminalWidget::has_selection() const
  443. {
  444. return m_selection_start.is_valid() && m_selection_end.is_valid();
  445. }
  446. bool TerminalWidget::selection_contains(const VT::Position& position) const
  447. {
  448. if (!has_selection())
  449. return false;
  450. if (m_rectangle_selection) {
  451. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  452. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  453. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  454. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  455. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  456. }
  457. return position >= normalized_selection_start() && position <= normalized_selection_end();
  458. }
  459. VT::Position TerminalWidget::buffer_position_at(const Gfx::IntPoint& position) const
  460. {
  461. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  462. int row = adjusted_position.y() / m_line_height;
  463. int column = adjusted_position.x() / font().glyph_width('x');
  464. if (row < 0)
  465. row = 0;
  466. if (column < 0)
  467. column = 0;
  468. if (row >= m_terminal.rows())
  469. row = m_terminal.rows() - 1;
  470. if (column >= m_terminal.columns())
  471. column = m_terminal.columns() - 1;
  472. row += m_scrollbar->value();
  473. return { row, column };
  474. }
  475. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  476. {
  477. if (event.button() == GUI::MouseButton::Left) {
  478. m_triple_click_timer.start();
  479. auto position = buffer_position_at(event.position());
  480. auto& line = m_terminal.line(position.row());
  481. bool want_whitespace = line.code_point(position.column()) == ' ';
  482. int start_column = 0;
  483. int end_column = 0;
  484. for (int column = position.column(); column >= 0 && (line.code_point(column) == ' ') == want_whitespace; --column) {
  485. start_column = column;
  486. }
  487. for (int column = position.column(); column < m_terminal.columns() && (line.code_point(column) == ' ') == want_whitespace; ++column) {
  488. end_column = column;
  489. }
  490. m_selection_start = { position.row(), start_column };
  491. m_selection_end = { position.row(), end_column };
  492. update_copy_action();
  493. }
  494. GUI::Frame::doubleclick_event(event);
  495. }
  496. void TerminalWidget::paste()
  497. {
  498. if (m_ptm_fd == -1)
  499. return;
  500. auto mime_type = GUI::Clipboard::the().mime_type();
  501. if (!mime_type.starts_with("text/"))
  502. return;
  503. auto text = GUI::Clipboard::the().data();
  504. if (text.is_empty())
  505. return;
  506. int nwritten = write(m_ptm_fd, text.data(), text.size());
  507. if (nwritten < 0) {
  508. perror("write");
  509. ASSERT_NOT_REACHED();
  510. }
  511. }
  512. void TerminalWidget::copy()
  513. {
  514. if (has_selection())
  515. GUI::Clipboard::the().set_plain_text(selected_text());
  516. }
  517. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  518. {
  519. if (event.button() == GUI::MouseButton::Left) {
  520. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  521. if (!m_active_href_id.is_null() && attribute.href_id == m_active_href_id) {
  522. dbgln("Open hyperlinked URL: '{}'", attribute.href);
  523. Desktop::Launcher::open(attribute.href);
  524. }
  525. if (!m_active_href_id.is_null()) {
  526. m_active_href = {};
  527. m_active_href_id = {};
  528. update();
  529. }
  530. m_auto_scroll_direction = AutoScrollDirection::None;
  531. }
  532. }
  533. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  534. {
  535. if (event.button() == GUI::MouseButton::Left) {
  536. m_left_mousedown_position = event.position();
  537. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  538. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  539. m_active_href = attribute.href;
  540. m_active_href_id = attribute.href_id;
  541. update();
  542. return;
  543. }
  544. m_active_href = {};
  545. m_active_href_id = {};
  546. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  547. int start_column = 0;
  548. int end_column = m_terminal.columns() - 1;
  549. auto position = buffer_position_at(event.position());
  550. m_selection_start = { position.row(), start_column };
  551. m_selection_end = { position.row(), end_column };
  552. } else {
  553. m_selection_start = buffer_position_at(event.position());
  554. m_selection_end = {};
  555. }
  556. if (m_alt_key_held)
  557. m_rectangle_selection = true;
  558. else if (m_rectangle_selection)
  559. m_rectangle_selection = false;
  560. update_copy_action();
  561. update();
  562. }
  563. }
  564. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  565. {
  566. auto position = buffer_position_at(event.position());
  567. auto attribute = m_terminal.attribute_at(position);
  568. if (attribute.href_id != m_hovered_href_id) {
  569. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  570. m_hovered_href_id = attribute.href_id;
  571. m_hovered_href = attribute.href;
  572. } else {
  573. m_hovered_href_id = {};
  574. m_hovered_href = {};
  575. }
  576. if (!m_hovered_href.is_empty())
  577. set_override_cursor(Gfx::StandardCursor::Hand);
  578. else
  579. set_override_cursor(Gfx::StandardCursor::IBeam);
  580. update();
  581. }
  582. if (!(event.buttons() & GUI::MouseButton::Left))
  583. return;
  584. if (!m_active_href_id.is_null()) {
  585. auto diff = event.position() - m_left_mousedown_position;
  586. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  587. constexpr int drag_distance_threshold = 5;
  588. if (distance_travelled_squared <= drag_distance_threshold)
  589. return;
  590. auto drag_operation = GUI::DragOperation::construct();
  591. drag_operation->set_text(m_active_href);
  592. drag_operation->set_data("text/uri-list", m_active_href);
  593. drag_operation->exec();
  594. m_active_href = {};
  595. m_active_href_id = {};
  596. m_hovered_href = {};
  597. m_hovered_href_id = {};
  598. update();
  599. return;
  600. }
  601. auto adjusted_position = event.position().translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  602. if (adjusted_position.y() < 0)
  603. m_auto_scroll_direction = AutoScrollDirection::Up;
  604. else if (adjusted_position.y() > m_terminal.rows() * m_line_height)
  605. m_auto_scroll_direction = AutoScrollDirection::Down;
  606. else
  607. m_auto_scroll_direction = AutoScrollDirection::None;
  608. auto old_selection_end = m_selection_end;
  609. m_selection_end = position;
  610. if (old_selection_end != m_selection_end) {
  611. update_copy_action();
  612. update();
  613. }
  614. }
  615. void TerminalWidget::leave_event(Core::Event&)
  616. {
  617. bool should_update = !m_hovered_href.is_empty();
  618. m_hovered_href = {};
  619. m_hovered_href_id = {};
  620. if (should_update)
  621. update();
  622. }
  623. void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
  624. {
  625. if (!is_scrollable())
  626. return;
  627. m_auto_scroll_direction = AutoScrollDirection::None;
  628. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta() * scroll_length());
  629. GUI::Frame::mousewheel_event(event);
  630. }
  631. bool TerminalWidget::is_scrollable() const
  632. {
  633. return m_scrollbar->is_scrollable();
  634. }
  635. int TerminalWidget::scroll_length() const
  636. {
  637. return m_scrollbar->step();
  638. }
  639. void TerminalWidget::set_scroll_length(int length)
  640. {
  641. m_scrollbar->set_step(length);
  642. }
  643. String TerminalWidget::selected_text() const
  644. {
  645. StringBuilder builder;
  646. auto start = normalized_selection_start();
  647. auto end = normalized_selection_end();
  648. for (int row = start.row(); row <= end.row(); ++row) {
  649. int first_column = first_selection_column_on_row(row);
  650. int last_column = last_selection_column_on_row(row);
  651. for (int column = first_column; column <= last_column; ++column) {
  652. auto& line = m_terminal.line(row);
  653. if (line.attributes()[column].is_untouched()) {
  654. builder.append('\n');
  655. break;
  656. }
  657. // FIXME: This is a bit hackish.
  658. if (line.is_utf32()) {
  659. u32 code_point = line.code_point(column);
  660. builder.append(Utf32View(&code_point, 1));
  661. } else {
  662. builder.append(line.code_point(column));
  663. }
  664. if (column == line.length() - 1 || (m_rectangle_selection && column == last_column)) {
  665. builder.append('\n');
  666. }
  667. }
  668. }
  669. return builder.to_string();
  670. }
  671. int TerminalWidget::first_selection_column_on_row(int row) const
  672. {
  673. return row == normalized_selection_start().row() || m_rectangle_selection ? normalized_selection_start().column() : 0;
  674. }
  675. int TerminalWidget::last_selection_column_on_row(int row) const
  676. {
  677. return row == normalized_selection_end().row() || m_rectangle_selection ? normalized_selection_end().column() : m_terminal.columns() - 1;
  678. }
  679. void TerminalWidget::terminal_history_changed()
  680. {
  681. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  682. m_scrollbar->set_max(m_terminal.history_size());
  683. if (was_max)
  684. m_scrollbar->set_value(m_scrollbar->max());
  685. m_scrollbar->update();
  686. }
  687. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  688. {
  689. m_pixel_width = (frame_thickness() * 2) + (m_inset * 2) + (columns * font().glyph_width('x')) + m_scrollbar->width();
  690. m_pixel_height = (frame_thickness() * 2) + (m_inset * 2) + (rows * (font().glyph_height() + m_line_spacing));
  691. if (m_automatic_size_policy) {
  692. set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed);
  693. set_preferred_size(m_pixel_width, m_pixel_height);
  694. }
  695. m_needs_background_fill = true;
  696. force_repaint();
  697. winsize ws;
  698. ws.ws_row = rows;
  699. ws.ws_col = columns;
  700. if (m_ptm_fd != -1) {
  701. int rc = ioctl(m_ptm_fd, TIOCSWINSZ, &ws);
  702. ASSERT(rc == 0);
  703. }
  704. }
  705. void TerminalWidget::beep()
  706. {
  707. if (m_bell_mode == BellMode::Disabled) {
  708. return;
  709. }
  710. if (m_bell_mode == BellMode::AudibleBeep) {
  711. sysbeep();
  712. return;
  713. }
  714. m_visual_beep_timer->restart(200);
  715. m_visual_beep_timer->set_single_shot(true);
  716. m_visual_beep_timer->on_timeout = [this] {
  717. force_repaint();
  718. };
  719. force_repaint();
  720. }
  721. void TerminalWidget::emit(const u8* data, size_t size)
  722. {
  723. if (write(m_ptm_fd, data, size) < 0) {
  724. perror("TerminalWidget::emit: write");
  725. }
  726. }
  727. void TerminalWidget::context_menu_event(GUI::ContextMenuEvent& event)
  728. {
  729. if (m_hovered_href_id.is_null()) {
  730. m_context_menu->popup(event.screen_position());
  731. } else {
  732. m_context_menu_href = m_hovered_href;
  733. // Ask LaunchServer for a list of programs that can handle the right-clicked URL.
  734. auto handlers = Desktop::Launcher::get_handlers_for_url(m_hovered_href);
  735. if (handlers.is_empty()) {
  736. m_context_menu->popup(event.screen_position());
  737. return;
  738. }
  739. m_context_menu_for_hyperlink = GUI::Menu::construct();
  740. RefPtr<GUI::Action> context_menu_default_action;
  741. // Go through the list of handlers and see if we can find a nice display name + icon for them.
  742. // Then add them to the context menu.
  743. // FIXME: Adapt this code when we actually support calling LaunchServer with a specific handler in mind.
  744. for (auto& handler : handlers) {
  745. auto af = GUI::AppFile::get_for_app(LexicalPath(handler).basename());
  746. if (!af->is_valid())
  747. continue;
  748. auto action = GUI::Action::create(String::formatted("Open in {}", af->name()), af->icon().bitmap_for_size(16), [this, handler](auto&) {
  749. Desktop::Launcher::open(m_context_menu_href, handler);
  750. });
  751. if (context_menu_default_action.is_null()) {
  752. context_menu_default_action = action;
  753. }
  754. m_context_menu_for_hyperlink->add_action(action);
  755. }
  756. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy URL", [this](auto&) {
  757. GUI::Clipboard::the().set_plain_text(m_context_menu_href);
  758. }));
  759. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy name", [&](auto&) {
  760. // file://courage/home/anon/something -> /home/anon/something
  761. auto path = URL(m_context_menu_href).path();
  762. // /home/anon/something -> something
  763. auto name = LexicalPath(path).basename();
  764. GUI::Clipboard::the().set_plain_text(name);
  765. }));
  766. m_context_menu_for_hyperlink->add_separator();
  767. m_context_menu_for_hyperlink->add_action(copy_action());
  768. m_context_menu_for_hyperlink->add_action(paste_action());
  769. m_context_menu_for_hyperlink->popup(event.screen_position(), context_menu_default_action);
  770. }
  771. }
  772. void TerminalWidget::drop_event(GUI::DropEvent& event)
  773. {
  774. if (event.mime_data().has_text()) {
  775. event.accept();
  776. auto text = event.mime_data().text();
  777. write(m_ptm_fd, text.characters(), text.length());
  778. } else if (event.mime_data().has_urls()) {
  779. event.accept();
  780. auto urls = event.mime_data().urls();
  781. bool first = true;
  782. for (auto& url : event.mime_data().urls()) {
  783. if (!first) {
  784. write(m_ptm_fd, " ", 1);
  785. first = false;
  786. }
  787. if (url.protocol() == "file")
  788. write(m_ptm_fd, url.path().characters(), url.path().length());
  789. else
  790. write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
  791. }
  792. }
  793. }
  794. void TerminalWidget::did_change_font()
  795. {
  796. GUI::Frame::did_change_font();
  797. m_line_height = font().glyph_height() + m_line_spacing;
  798. // TODO: try to find a bold version of the new font (e.g. CsillaThin7x10 -> CsillaBold7x10)
  799. const Gfx::Font& bold_font = Gfx::Font::default_bold_fixed_width_font();
  800. if (bold_font.glyph_height() == font().glyph_height() && bold_font.glyph_width(' ') == font().glyph_width(' '))
  801. m_bold_font = &bold_font;
  802. else
  803. m_bold_font = font();
  804. if (!size().is_empty())
  805. relayout(size());
  806. }
  807. void TerminalWidget::clear_including_history()
  808. {
  809. m_terminal.clear_including_history();
  810. }
  811. void TerminalWidget::scroll_to_bottom()
  812. {
  813. m_scrollbar->set_value(m_scrollbar->max());
  814. }
  815. void TerminalWidget::update_copy_action()
  816. {
  817. m_copy_action->set_enabled(has_selection());
  818. }
  819. void TerminalWidget::update_paste_action()
  820. {
  821. m_paste_action->set_enabled(GUI::Clipboard::the().mime_type().starts_with("text/") && !GUI::Clipboard::the().data().is_empty());
  822. }