TerminalWidget.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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_override_cursor(Gfx::StandardCursor::IBeam);
  94. set_accepts_emoji_input(true);
  95. set_pty_master_fd(ptm_fd);
  96. m_cursor_blink_timer = add<Core::Timer>();
  97. m_visual_beep_timer = add<Core::Timer>();
  98. m_scrollbar = add<GUI::ScrollBar>(Orientation::Vertical);
  99. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  100. m_scrollbar->on_change = [this](int) {
  101. force_repaint();
  102. };
  103. set_scroll_length(m_config->read_num_entry("Window", "ScrollLength", 4));
  104. dbg() << "Load config file from " << m_config->file_name();
  105. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  106. "CursorBlinkInterval",
  107. 500));
  108. m_cursor_blink_timer->on_timeout = [this] {
  109. m_cursor_blink_state = !m_cursor_blink_state;
  110. update_cursor();
  111. };
  112. auto font_entry = m_config->read_entry("Text", "Font", "default");
  113. if (font_entry == "default")
  114. set_font(Gfx::Font::default_fixed_width_font());
  115. else
  116. set_font(Gfx::Font::load_from_file(font_entry));
  117. m_line_height = font().glyph_height() + m_line_spacing;
  118. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  119. 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&) {
  120. copy();
  121. });
  122. 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&) {
  123. paste();
  124. });
  125. m_clear_including_history_action = GUI::Action::create("Clear including history", { Mod_Ctrl | Mod_Shift, Key_K }, [this](auto&) {
  126. clear_including_history();
  127. });
  128. m_context_menu = GUI::Menu::construct();
  129. m_context_menu->add_action(copy_action());
  130. m_context_menu->add_action(paste_action());
  131. m_context_menu->add_separator();
  132. m_context_menu->add_action(clear_including_history_action());
  133. }
  134. TerminalWidget::~TerminalWidget()
  135. {
  136. }
  137. static inline Color color_from_rgb(unsigned color)
  138. {
  139. return Color::from_rgb(color);
  140. }
  141. Gfx::IntRect TerminalWidget::glyph_rect(u16 row, u16 column)
  142. {
  143. int y = row * m_line_height;
  144. int x = column * font().glyph_width('x');
  145. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  146. }
  147. Gfx::IntRect TerminalWidget::row_rect(u16 row)
  148. {
  149. int y = row * m_line_height;
  150. Gfx::IntRect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  151. rect.inflate(0, m_line_spacing);
  152. return rect;
  153. }
  154. void TerminalWidget::set_logical_focus(bool focus)
  155. {
  156. m_has_logical_focus = focus;
  157. if (!m_has_logical_focus) {
  158. m_cursor_blink_timer->stop();
  159. } else {
  160. m_cursor_blink_state = true;
  161. m_cursor_blink_timer->start();
  162. }
  163. invalidate_cursor();
  164. update();
  165. }
  166. void TerminalWidget::focusin_event(GUI::FocusEvent& event)
  167. {
  168. set_logical_focus(true);
  169. return GUI::Frame::focusin_event(event);
  170. }
  171. void TerminalWidget::focusout_event(GUI::FocusEvent& event)
  172. {
  173. set_logical_focus(false);
  174. return GUI::Frame::focusout_event(event);
  175. }
  176. void TerminalWidget::event(Core::Event& event)
  177. {
  178. if (event.type() == GUI::Event::WindowBecameActive)
  179. set_logical_focus(true);
  180. else if (event.type() == GUI::Event::WindowBecameInactive)
  181. set_logical_focus(false);
  182. return GUI::Frame::event(event);
  183. }
  184. void TerminalWidget::keydown_event(GUI::KeyEvent& event)
  185. {
  186. if (m_ptm_fd == -1) {
  187. event.ignore();
  188. return GUI::Frame::keydown_event(event);
  189. }
  190. // Reset timer so cursor doesn't blink while typing.
  191. m_cursor_blink_timer->stop();
  192. m_cursor_blink_state = true;
  193. m_cursor_blink_timer->start();
  194. if (event.key() == KeyCode::Key_PageUp && event.modifiers() == Mod_Shift) {
  195. m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
  196. return;
  197. }
  198. if (event.key() == KeyCode::Key_PageDown && event.modifiers() == Mod_Shift) {
  199. m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
  200. return;
  201. }
  202. if (event.key() == KeyCode::Key_Alt) {
  203. m_alt_key_held = true;
  204. return;
  205. }
  206. // Clear the selection if we type in/behind it.
  207. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  208. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  209. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  210. 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) {
  211. m_selection_end = {};
  212. update();
  213. }
  214. m_terminal.handle_key_press(event.key(), event.code_point(), event.modifiers());
  215. if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_LeftShift && event.key() != Key_RightShift && event.key() != Key_Logo)
  216. m_scrollbar->set_value(m_scrollbar->max());
  217. }
  218. void TerminalWidget::keyup_event(GUI::KeyEvent& event)
  219. {
  220. switch (event.key()) {
  221. case KeyCode::Key_Alt:
  222. m_alt_key_held = false;
  223. return;
  224. default:
  225. break;
  226. }
  227. }
  228. void TerminalWidget::paint_event(GUI::PaintEvent& event)
  229. {
  230. GUI::Frame::paint_event(event);
  231. GUI::Painter painter(*this);
  232. auto visual_beep_active = m_visual_beep_timer->is_active();
  233. painter.add_clip_rect(event.rect());
  234. Gfx::IntRect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
  235. painter.add_clip_rect(terminal_buffer_rect);
  236. if (visual_beep_active)
  237. painter.clear_rect(frame_inner_rect(), Color::Red);
  238. else
  239. painter.clear_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  240. invalidate_cursor();
  241. int rows_from_history = 0;
  242. int first_row_from_history = m_terminal.history_size();
  243. int row_with_cursor = m_terminal.cursor_row();
  244. if (m_scrollbar->value() != m_scrollbar->max()) {
  245. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  246. first_row_from_history = m_terminal.history_size() - (m_scrollbar->max() - m_scrollbar->value());
  247. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  248. }
  249. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  250. auto row_rect = this->row_rect(visual_row);
  251. if (!event.rect().contains(row_rect))
  252. continue;
  253. auto& line = m_terminal.line(first_row_from_history + visual_row);
  254. bool has_only_one_background_color = line.has_only_one_background_color();
  255. if (visual_beep_active)
  256. painter.clear_rect(row_rect, Color::Red);
  257. else if (has_only_one_background_color)
  258. painter.clear_rect(row_rect, color_from_rgb(line.attributes()[0].background_color).with_alpha(m_opacity));
  259. for (size_t column = 0; column < line.length(); ++column) {
  260. u32 code_point = line.code_point(column);
  261. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  262. && m_has_logical_focus
  263. && visual_row == row_with_cursor
  264. && column == m_terminal.cursor_column();
  265. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  266. auto attribute = line.attributes()[column];
  267. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color);
  268. auto character_rect = glyph_rect(visual_row, column);
  269. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  270. if ((!visual_beep_active && !has_only_one_background_color) || should_reverse_fill_for_cursor_or_selection) {
  271. 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));
  272. }
  273. enum class UnderlineStyle {
  274. None,
  275. Dotted,
  276. Solid,
  277. };
  278. auto underline_style = UnderlineStyle::None;
  279. if (attribute.flags & VT::Attribute::Underline) {
  280. // Content has specified underline
  281. underline_style = UnderlineStyle::Solid;
  282. } else if (!attribute.href.is_empty()) {
  283. // We're hovering a hyperlink
  284. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id)
  285. underline_style = UnderlineStyle::Solid;
  286. else
  287. underline_style = UnderlineStyle::Dotted;
  288. }
  289. if (underline_style == UnderlineStyle::Solid) {
  290. if (attribute.href_id == m_active_href_id && m_hovered_href_id == m_active_href_id)
  291. text_color = palette().active_link();
  292. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), text_color);
  293. } else if (underline_style == UnderlineStyle::Dotted) {
  294. auto dotted_line_color = text_color.darkened(0.6f);
  295. int x1 = cell_rect.bottom_left().x();
  296. int x2 = cell_rect.bottom_right().x();
  297. int y = cell_rect.bottom_left().y();
  298. for (int x = x1; x <= x2; ++x) {
  299. if ((x % 3) == 0)
  300. painter.set_pixel({ x, y }, dotted_line_color);
  301. }
  302. }
  303. if (code_point == ' ')
  304. continue;
  305. painter.draw_glyph_or_emoji(
  306. character_rect.location(),
  307. code_point,
  308. attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
  309. text_color);
  310. }
  311. }
  312. if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
  313. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  314. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  315. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  316. painter.draw_rect(cell_rect, color_from_rgb(cursor_line.attributes()[m_terminal.cursor_column()].foreground_color));
  317. }
  318. }
  319. }
  320. void TerminalWidget::set_window_progress(int value, int max)
  321. {
  322. float float_value = value;
  323. float float_max = max;
  324. float progress = (float_value / float_max) * 100.0f;
  325. window()->set_progress((int)roundf(progress));
  326. }
  327. void TerminalWidget::set_window_title(const StringView& title)
  328. {
  329. if (!Utf8View(title).validate()) {
  330. dbg() << "TerminalWidget: Attempted to set window title to invalid UTF-8 string";
  331. return;
  332. }
  333. if (on_title_change)
  334. on_title_change(title);
  335. }
  336. void TerminalWidget::invalidate_cursor()
  337. {
  338. m_terminal.invalidate_cursor();
  339. }
  340. void TerminalWidget::flush_dirty_lines()
  341. {
  342. // FIXME: Update smarter when scrolled
  343. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  344. update();
  345. m_terminal.m_need_full_flush = false;
  346. return;
  347. }
  348. Gfx::IntRect rect;
  349. for (int i = 0; i < m_terminal.rows(); ++i) {
  350. if (m_terminal.visible_line(i).is_dirty()) {
  351. rect = rect.united(row_rect(i));
  352. m_terminal.visible_line(i).set_dirty(false);
  353. }
  354. }
  355. update(rect);
  356. }
  357. void TerminalWidget::force_repaint()
  358. {
  359. m_needs_background_fill = true;
  360. update();
  361. }
  362. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  363. {
  364. relayout(event.size());
  365. }
  366. void TerminalWidget::relayout(const Gfx::IntSize& size)
  367. {
  368. if (!m_scrollbar)
  369. return;
  370. auto base_size = compute_base_size();
  371. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  372. int new_rows = (size.height() - base_size.height()) / m_line_height;
  373. m_terminal.set_size(new_columns, new_rows);
  374. Gfx::IntRect scrollbar_rect = {
  375. size.width() - m_scrollbar->width() - frame_thickness(),
  376. frame_thickness(),
  377. m_scrollbar->width(),
  378. size.height() - frame_thickness() * 2,
  379. };
  380. m_scrollbar->set_relative_rect(scrollbar_rect);
  381. m_scrollbar->set_page(new_rows);
  382. }
  383. Gfx::IntSize TerminalWidget::compute_base_size() const
  384. {
  385. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  386. int base_height = frame_thickness() * 2 + m_inset * 2;
  387. return { base_width, base_height };
  388. }
  389. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  390. {
  391. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  392. window.set_base_size(compute_base_size());
  393. }
  394. void TerminalWidget::update_cursor()
  395. {
  396. invalidate_cursor();
  397. flush_dirty_lines();
  398. }
  399. void TerminalWidget::set_opacity(u8 new_opacity)
  400. {
  401. if (m_opacity == new_opacity)
  402. return;
  403. window()->set_has_alpha_channel(new_opacity < 255);
  404. m_opacity = new_opacity;
  405. force_repaint();
  406. }
  407. VT::Position TerminalWidget::normalized_selection_start() const
  408. {
  409. if (m_selection_start < m_selection_end)
  410. return m_selection_start;
  411. return m_selection_end;
  412. }
  413. VT::Position TerminalWidget::normalized_selection_end() const
  414. {
  415. if (m_selection_start < m_selection_end)
  416. return m_selection_end;
  417. return m_selection_start;
  418. }
  419. bool TerminalWidget::has_selection() const
  420. {
  421. return m_selection_start.is_valid() && m_selection_end.is_valid();
  422. }
  423. bool TerminalWidget::selection_contains(const VT::Position& position) const
  424. {
  425. if (!has_selection())
  426. return false;
  427. if (m_rectangle_selection) {
  428. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  429. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  430. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  431. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  432. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  433. }
  434. return position >= normalized_selection_start() && position <= normalized_selection_end();
  435. }
  436. VT::Position TerminalWidget::buffer_position_at(const Gfx::IntPoint& position) const
  437. {
  438. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  439. int row = adjusted_position.y() / m_line_height;
  440. int column = adjusted_position.x() / font().glyph_width('x');
  441. if (row < 0)
  442. row = 0;
  443. if (column < 0)
  444. column = 0;
  445. if (row >= m_terminal.rows())
  446. row = m_terminal.rows() - 1;
  447. if (column >= m_terminal.columns())
  448. column = m_terminal.columns() - 1;
  449. row += m_scrollbar->value();
  450. return { row, column };
  451. }
  452. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  453. {
  454. if (event.button() == GUI::MouseButton::Left) {
  455. m_triple_click_timer.start();
  456. auto position = buffer_position_at(event.position());
  457. auto& line = m_terminal.line(position.row());
  458. bool want_whitespace = line.code_point(position.column()) == ' ';
  459. int start_column = 0;
  460. int end_column = 0;
  461. for (int column = position.column(); column >= 0 && (line.code_point(column) == ' ') == want_whitespace; --column) {
  462. start_column = column;
  463. }
  464. for (int column = position.column(); column < m_terminal.columns() && (line.code_point(column) == ' ') == want_whitespace; ++column) {
  465. end_column = column;
  466. }
  467. m_selection_start = { position.row(), start_column };
  468. m_selection_end = { position.row(), end_column };
  469. }
  470. GUI::Frame::doubleclick_event(event);
  471. }
  472. void TerminalWidget::paste()
  473. {
  474. if (m_ptm_fd == -1)
  475. return;
  476. auto text = GUI::Clipboard::the().data();
  477. if (text.is_empty())
  478. return;
  479. int nwritten = write(m_ptm_fd, text.data(), text.size());
  480. if (nwritten < 0) {
  481. perror("write");
  482. ASSERT_NOT_REACHED();
  483. }
  484. }
  485. void TerminalWidget::copy()
  486. {
  487. if (has_selection())
  488. GUI::Clipboard::the().set_plain_text(selected_text());
  489. }
  490. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  491. {
  492. if (event.button() == GUI::MouseButton::Left) {
  493. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  494. if (!m_active_href_id.is_null() && attribute.href_id == m_active_href_id) {
  495. dbg() << "Open hyperlinked URL: _" << attribute.href << "_";
  496. Desktop::Launcher::open(attribute.href);
  497. }
  498. if (!m_active_href_id.is_null()) {
  499. m_active_href = {};
  500. m_active_href_id = {};
  501. update();
  502. }
  503. }
  504. }
  505. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  506. {
  507. if (event.button() == GUI::MouseButton::Left) {
  508. m_left_mousedown_position = event.position();
  509. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  510. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  511. m_active_href = attribute.href;
  512. m_active_href_id = attribute.href_id;
  513. update();
  514. return;
  515. }
  516. m_active_href = {};
  517. m_active_href_id = {};
  518. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  519. int start_column = 0;
  520. int end_column = m_terminal.columns() - 1;
  521. auto position = buffer_position_at(event.position());
  522. m_selection_start = { position.row(), start_column };
  523. m_selection_end = { position.row(), end_column };
  524. } else {
  525. m_selection_start = buffer_position_at(event.position());
  526. m_selection_end = {};
  527. }
  528. if (m_alt_key_held)
  529. m_rectangle_selection = true;
  530. else if (m_rectangle_selection)
  531. m_rectangle_selection = false;
  532. update();
  533. }
  534. }
  535. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  536. {
  537. auto position = buffer_position_at(event.position());
  538. auto attribute = m_terminal.attribute_at(position);
  539. if (attribute.href_id != m_hovered_href_id) {
  540. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  541. m_hovered_href_id = attribute.href_id;
  542. m_hovered_href = attribute.href;
  543. } else {
  544. m_hovered_href_id = {};
  545. m_hovered_href = {};
  546. }
  547. if (!m_hovered_href.is_empty())
  548. set_override_cursor(Gfx::StandardCursor::Hand);
  549. else
  550. set_override_cursor(Gfx::StandardCursor::IBeam);
  551. update();
  552. }
  553. if (!(event.buttons() & GUI::MouseButton::Left))
  554. return;
  555. if (!m_active_href_id.is_null()) {
  556. auto diff = event.position() - m_left_mousedown_position;
  557. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  558. constexpr int drag_distance_threshold = 5;
  559. if (distance_travelled_squared <= drag_distance_threshold)
  560. return;
  561. auto drag_operation = GUI::DragOperation::construct();
  562. drag_operation->set_text(m_active_href);
  563. drag_operation->set_data("text/uri-list", m_active_href);
  564. drag_operation->exec();
  565. m_active_href = {};
  566. m_active_href_id = {};
  567. m_hovered_href = {};
  568. m_hovered_href_id = {};
  569. update();
  570. return;
  571. }
  572. auto old_selection_end = m_selection_end;
  573. m_selection_end = position;
  574. if (old_selection_end != m_selection_end)
  575. update();
  576. }
  577. void TerminalWidget::leave_event(Core::Event&)
  578. {
  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. RefPtr<GUI::Action> context_menu_default_action;
  699. // Go through the list of handlers and see if we can find a nice display name + icon for them.
  700. // Then add them to the context menu.
  701. // FIXME: Adapt this code when we actually support calling LaunchServer with a specific handler in mind.
  702. for (auto& handler : handlers) {
  703. auto af_path = String::format("/res/apps/%s.af", LexicalPath(handler).basename().characters());
  704. auto af = Core::ConfigFile::open(af_path);
  705. auto handler_name = af->read_entry("App", "Name", handler);
  706. auto handler_icon = af->read_entry("Icons", "16x16", {});
  707. auto icon = Gfx::Bitmap::load_from_file(handler_icon);
  708. auto action = GUI::Action::create(String::format("Open in %s", handler_name.characters()), move(icon), [this, handler](auto&) {
  709. Desktop::Launcher::open(m_context_menu_href, handler);
  710. });
  711. if (context_menu_default_action.is_null()) {
  712. context_menu_default_action = action;
  713. }
  714. m_context_menu_for_hyperlink->add_action(action);
  715. }
  716. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy URL", [this](auto&) {
  717. GUI::Clipboard::the().set_plain_text(m_context_menu_href);
  718. }));
  719. m_context_menu_for_hyperlink->add_separator();
  720. m_context_menu_for_hyperlink->add_action(copy_action());
  721. m_context_menu_for_hyperlink->add_action(paste_action());
  722. m_context_menu_for_hyperlink->popup(event.screen_position(), context_menu_default_action);
  723. }
  724. }
  725. void TerminalWidget::drop_event(GUI::DropEvent& event)
  726. {
  727. if (event.mime_data().has_text()) {
  728. event.accept();
  729. auto text = event.mime_data().text();
  730. write(m_ptm_fd, text.characters(), text.length());
  731. } else if (event.mime_data().has_urls()) {
  732. event.accept();
  733. auto urls = event.mime_data().urls();
  734. bool first = true;
  735. for (auto& url : event.mime_data().urls()) {
  736. if (!first) {
  737. write(m_ptm_fd, " ", 1);
  738. first = false;
  739. }
  740. if (url.protocol() == "file")
  741. write(m_ptm_fd, url.path().characters(), url.path().length());
  742. else
  743. write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
  744. }
  745. }
  746. }
  747. void TerminalWidget::did_change_font()
  748. {
  749. GUI::Frame::did_change_font();
  750. m_line_height = font().glyph_height() + m_line_spacing;
  751. // TODO: try to find a bold version of the new font (e.g. CsillaThin7x10 -> CsillaBold7x10)
  752. const Gfx::Font& bold_font = Gfx::Font::default_bold_fixed_width_font();
  753. if (bold_font.glyph_height() == font().glyph_height() && bold_font.glyph_width(' ') == font().glyph_width(' '))
  754. m_bold_font = &bold_font;
  755. else
  756. m_bold_font = font();
  757. if (!size().is_empty())
  758. relayout(size());
  759. }
  760. void TerminalWidget::clear_including_history()
  761. {
  762. m_terminal.clear_including_history();
  763. }