TerminalWidget.cpp 30 KB

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