TerminalWidget.cpp 30 KB

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