TerminalWidget.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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/StdLibExtras.h>
  29. #include <AK/String.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/Utf8View.h>
  32. #include <Kernel/KeyCode.h>
  33. #include <LibCore/MimeData.h>
  34. #include <LibDesktop/Launcher.h>
  35. #include <LibGUI/Action.h>
  36. #include <LibGUI/Application.h>
  37. #include <LibGUI/Clipboard.h>
  38. #include <LibGUI/DragOperation.h>
  39. #include <LibGUI/Menu.h>
  40. #include <LibGUI/Painter.h>
  41. #include <LibGUI/ScrollBar.h>
  42. #include <LibGUI/Window.h>
  43. #include <LibGfx/Font.h>
  44. #include <LibGfx/Palette.h>
  45. #include <errno.h>
  46. #include <stdio.h>
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <sys/ioctl.h>
  50. #include <unistd.h>
  51. //#define TERMINAL_DEBUG
  52. void TerminalWidget::set_pty_master_fd(int fd)
  53. {
  54. m_ptm_fd = fd;
  55. if (m_ptm_fd == -1) {
  56. m_notifier = nullptr;
  57. return;
  58. }
  59. m_notifier = Core::Notifier::construct(m_ptm_fd, Core::Notifier::Read);
  60. m_notifier->on_ready_to_read = [this] {
  61. u8 buffer[BUFSIZ];
  62. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  63. if (nread < 0) {
  64. dbgprintf("Terminal read error: %s\n", strerror(errno));
  65. perror("read(ptm)");
  66. GUI::Application::the().quit(1);
  67. return;
  68. }
  69. if (nread == 0) {
  70. dbgprintf("Terminal: EOF on master pty, firing on_command_exit hook.\n");
  71. if (on_command_exit)
  72. on_command_exit();
  73. int rc = close(m_ptm_fd);
  74. if (rc < 0) {
  75. perror("close");
  76. }
  77. set_pty_master_fd(-1);
  78. return;
  79. }
  80. for (ssize_t i = 0; i < nread; ++i)
  81. m_terminal.on_char(buffer[i]);
  82. flush_dirty_lines();
  83. };
  84. }
  85. TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Core::ConfigFile> config)
  86. : m_terminal(*this)
  87. , m_automatic_size_policy(automatic_size_policy)
  88. , m_config(move(config))
  89. {
  90. set_pty_master_fd(ptm_fd);
  91. m_cursor_blink_timer = add<Core::Timer>();
  92. m_visual_beep_timer = add<Core::Timer>();
  93. m_scrollbar = add<GUI::ScrollBar>(Orientation::Vertical);
  94. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  95. m_scrollbar->on_change = [this](int) {
  96. force_repaint();
  97. };
  98. dbgprintf("Terminal: Load config file from %s\n", m_config->file_name().characters());
  99. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  100. "CursorBlinkInterval",
  101. 500));
  102. m_cursor_blink_timer->on_timeout = [this] {
  103. m_cursor_blink_state = !m_cursor_blink_state;
  104. update_cursor();
  105. };
  106. auto font_entry = m_config->read_entry("Text", "Font", "default");
  107. if (font_entry == "default")
  108. set_font(Gfx::Font::default_fixed_width_font());
  109. else
  110. set_font(Gfx::Font::load_from_file(font_entry));
  111. m_line_height = font().glyph_height() + m_line_spacing;
  112. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  113. 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&) {
  114. copy();
  115. });
  116. m_paste_action = GUI::Action::create("Paste", { Mod_Ctrl | Mod_Shift, Key_V }, Gfx::Bitmap::load_from_file("/res/icons/paste16.png"), [this](auto&) {
  117. paste();
  118. });
  119. m_context_menu = GUI::Menu::construct();
  120. m_context_menu->add_action(copy_action());
  121. m_context_menu->add_action(paste_action());
  122. m_context_menu_for_hyperlink = GUI::Menu::construct();
  123. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Open URL", [this](auto&) {
  124. Desktop::Launcher::open(m_context_menu_href);
  125. }));
  126. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy URL", [this](auto&) {
  127. GUI::Clipboard::the().set_data(m_context_menu_href);
  128. }));
  129. m_context_menu_for_hyperlink->add_separator();
  130. m_context_menu_for_hyperlink->add_action(copy_action());
  131. m_context_menu_for_hyperlink->add_action(paste_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::Rect 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::Rect TerminalWidget::row_rect(u16 row)
  147. {
  148. int y = row * m_line_height;
  149. Gfx::Rect 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(Core::Event& event)
  166. {
  167. set_logical_focus(true);
  168. return GUI::Frame::focusin_event(event);
  169. }
  170. void TerminalWidget::focusout_event(Core::Event& 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. auto ctrl_held = !!(event.modifiers() & Mod_Ctrl);
  194. switch (event.key()) {
  195. case KeyCode::Key_Up:
  196. write(m_ptm_fd, ctrl_held ? "\033[OA" : "\033[A", 3 + ctrl_held);
  197. return;
  198. case KeyCode::Key_Down:
  199. write(m_ptm_fd, ctrl_held ? "\033[OB" : "\033[B", 3 + ctrl_held);
  200. return;
  201. case KeyCode::Key_Right:
  202. write(m_ptm_fd, ctrl_held ? "\033[OC" : "\033[C", 3 + ctrl_held);
  203. return;
  204. case KeyCode::Key_Left:
  205. write(m_ptm_fd, ctrl_held ? "\033[OD" : "\033[D", 3 + ctrl_held);
  206. return;
  207. case KeyCode::Key_Insert:
  208. write(m_ptm_fd, "\033[2~", 4);
  209. return;
  210. case KeyCode::Key_Delete:
  211. write(m_ptm_fd, "\033[3~", 4);
  212. return;
  213. case KeyCode::Key_Home:
  214. write(m_ptm_fd, "\033[H", 3);
  215. return;
  216. case KeyCode::Key_End:
  217. write(m_ptm_fd, "\033[F", 3);
  218. return;
  219. case KeyCode::Key_PageUp:
  220. if (event.modifiers() == Mod_Shift) {
  221. m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
  222. return;
  223. }
  224. write(m_ptm_fd, "\033[5~", 4);
  225. return;
  226. case KeyCode::Key_PageDown:
  227. if (event.modifiers() == Mod_Shift) {
  228. m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
  229. return;
  230. }
  231. write(m_ptm_fd, "\033[6~", 4);
  232. return;
  233. case KeyCode::Key_Alt:
  234. m_alt_key_held = true;
  235. return;
  236. default:
  237. break;
  238. }
  239. if (event.shift() && event.key() == KeyCode::Key_Tab) {
  240. write(m_ptm_fd, "\033[Z", 3);
  241. return;
  242. }
  243. // Key event was not one of the above special cases,
  244. // attempt to treat it as a character...
  245. char ch = !event.text().is_empty() ? event.text()[0] : 0;
  246. if (ch) {
  247. if (event.ctrl()) {
  248. if (ch >= 'a' && ch <= 'z') {
  249. ch = ch - 'a' + 1;
  250. } else if (ch == '\\') {
  251. ch = 0x1c;
  252. }
  253. }
  254. // ALT modifier sends escape prefix
  255. if (event.alt())
  256. write(m_ptm_fd, "\033", 1);
  257. //Clear the selection if we type in/behind it
  258. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  259. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  260. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  261. 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) {
  262. m_selection_end = {};
  263. update();
  264. }
  265. write(m_ptm_fd, &ch, 1);
  266. }
  267. if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_Shift && event.key() != Key_Logo)
  268. m_scrollbar->set_value(m_scrollbar->max());
  269. }
  270. void TerminalWidget::keyup_event(GUI::KeyEvent& event)
  271. {
  272. switch (event.key()) {
  273. case KeyCode::Key_Alt:
  274. m_alt_key_held = false;
  275. return;
  276. default:
  277. break;
  278. }
  279. }
  280. void TerminalWidget::paint_event(GUI::PaintEvent& event)
  281. {
  282. GUI::Frame::paint_event(event);
  283. GUI::Painter painter(*this);
  284. painter.add_clip_rect(event.rect());
  285. Gfx::Rect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
  286. painter.add_clip_rect(terminal_buffer_rect);
  287. if (m_visual_beep_timer->is_active())
  288. painter.clear_rect(frame_inner_rect(), Color::Red);
  289. else
  290. painter.clear_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  291. invalidate_cursor();
  292. int rows_from_history = 0;
  293. int first_row_from_history = m_terminal.history().size();
  294. int row_with_cursor = m_terminal.cursor_row();
  295. if (m_scrollbar->value() != m_scrollbar->max()) {
  296. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  297. first_row_from_history = m_terminal.history().size() - (m_scrollbar->max() - m_scrollbar->value());
  298. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  299. }
  300. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  301. auto row_rect = this->row_rect(visual_row);
  302. if (!event.rect().contains(row_rect))
  303. continue;
  304. auto& line = m_terminal.line(first_row_from_history + visual_row);
  305. bool has_only_one_background_color = line.has_only_one_background_color();
  306. if (m_visual_beep_timer->is_active())
  307. painter.clear_rect(row_rect, Color::Red);
  308. else if (has_only_one_background_color)
  309. painter.clear_rect(row_rect, color_from_rgb(line.attributes[0].background_color).with_alpha(m_opacity));
  310. // The terminal insists on thinking characters and
  311. // bytes are the same thing. We want to still draw
  312. // emojis in *some* way, but it won't be completely
  313. // perfect. So what we do is we make multi-byte
  314. // characters take up multiple columns, and render
  315. // the character itself in the center of the columns
  316. // its bytes take up as far as the terminal is concerned.
  317. Utf8View utf8_view { line.text() };
  318. for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
  319. u32 codepoint = *it;
  320. int this_char_column = utf8_view.byte_offset_of(it);
  321. AK::Utf8CodepointIterator it_copy = it;
  322. int next_char_column = utf8_view.byte_offset_of(++it_copy);
  323. // Columns from this_char_column up until next_char_column
  324. // are logically taken up by this (possibly multi-byte)
  325. // character. Iterate over these columns and draw background
  326. // for each one of them separately.
  327. bool should_reverse_fill_for_cursor_or_selection = false;
  328. VT::Attribute attribute;
  329. Color text_color;
  330. for (u16 column = this_char_column; column < next_char_column; ++column) {
  331. should_reverse_fill_for_cursor_or_selection |= m_cursor_blink_state
  332. && m_has_logical_focus
  333. && visual_row == row_with_cursor
  334. && column == m_terminal.cursor_column();
  335. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, column });
  336. attribute = line.attributes[column];
  337. text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color);
  338. auto character_rect = glyph_rect(visual_row, column);
  339. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  340. if (!has_only_one_background_color || should_reverse_fill_for_cursor_or_selection) {
  341. 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));
  342. }
  343. enum class UnderlineStyle {
  344. None,
  345. Dotted,
  346. Solid,
  347. };
  348. auto underline_style = UnderlineStyle::None;
  349. if (attribute.flags & VT::Attribute::Underline) {
  350. // Content has specified underline
  351. underline_style = UnderlineStyle::Solid;
  352. } else if (!attribute.href.is_empty()) {
  353. // We're hovering a hyperlink
  354. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id)
  355. underline_style = UnderlineStyle::Solid;
  356. else
  357. underline_style = UnderlineStyle::Dotted;
  358. }
  359. if (underline_style == UnderlineStyle::Solid) {
  360. if (attribute.href_id == m_active_href_id && m_hovered_href_id == m_active_href_id)
  361. text_color = palette().active_link();
  362. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), text_color);
  363. } else if (underline_style == UnderlineStyle::Dotted) {
  364. auto dotted_line_color = text_color.darkened(0.6f);
  365. int x1 = cell_rect.bottom_left().x();
  366. int x2 = cell_rect.bottom_right().x();
  367. int y = cell_rect.bottom_left().y();
  368. for (int x = x1; x <= x2; ++x) {
  369. if ((x % 3) == 0)
  370. painter.set_pixel({ x, y }, dotted_line_color);
  371. }
  372. }
  373. }
  374. if (codepoint == ' ')
  375. continue;
  376. auto character_rect = glyph_rect(visual_row, this_char_column);
  377. auto num_columns = next_char_column - this_char_column;
  378. character_rect.move_by((num_columns - 1) * font().glyph_width('x') / 2, 0);
  379. painter.draw_glyph_or_emoji(
  380. character_rect.location(),
  381. codepoint,
  382. attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
  383. text_color);
  384. }
  385. }
  386. if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
  387. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  388. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  389. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  390. painter.draw_rect(cell_rect, color_from_rgb(cursor_line.attributes[m_terminal.cursor_column()].foreground_color));
  391. }
  392. }
  393. }
  394. void TerminalWidget::set_window_title(const StringView& title)
  395. {
  396. if (on_title_change)
  397. on_title_change(title);
  398. }
  399. void TerminalWidget::invalidate_cursor()
  400. {
  401. m_terminal.invalidate_cursor();
  402. }
  403. void TerminalWidget::flush_dirty_lines()
  404. {
  405. // FIXME: Update smarter when scrolled
  406. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  407. update();
  408. m_terminal.m_need_full_flush = false;
  409. return;
  410. }
  411. Gfx::Rect rect;
  412. for (int i = 0; i < m_terminal.rows(); ++i) {
  413. if (m_terminal.line(i).dirty) {
  414. rect = rect.united(row_rect(i));
  415. m_terminal.line(i).dirty = false;
  416. }
  417. }
  418. update(rect);
  419. }
  420. void TerminalWidget::force_repaint()
  421. {
  422. m_needs_background_fill = true;
  423. update();
  424. }
  425. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  426. {
  427. relayout(event.size());
  428. }
  429. void TerminalWidget::relayout(const Gfx::Size& size)
  430. {
  431. if (!m_scrollbar)
  432. return;
  433. auto base_size = compute_base_size();
  434. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  435. int new_rows = (size.height() - base_size.height()) / m_line_height;
  436. m_terminal.set_size(new_columns, new_rows);
  437. Gfx::Rect scrollbar_rect = {
  438. size.width() - m_scrollbar->width() - frame_thickness(),
  439. frame_thickness(),
  440. m_scrollbar->width(),
  441. size.height() - frame_thickness() * 2,
  442. };
  443. m_scrollbar->set_relative_rect(scrollbar_rect);
  444. }
  445. Gfx::Size TerminalWidget::compute_base_size() const
  446. {
  447. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  448. int base_height = frame_thickness() * 2 + m_inset * 2;
  449. return { base_width, base_height };
  450. }
  451. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  452. {
  453. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  454. window.set_base_size(compute_base_size());
  455. }
  456. void TerminalWidget::update_cursor()
  457. {
  458. invalidate_cursor();
  459. flush_dirty_lines();
  460. }
  461. void TerminalWidget::set_opacity(u8 new_opacity)
  462. {
  463. if (m_opacity == new_opacity)
  464. return;
  465. window()->set_has_alpha_channel(new_opacity < 255);
  466. m_opacity = new_opacity;
  467. force_repaint();
  468. }
  469. VT::Position TerminalWidget::normalized_selection_start() const
  470. {
  471. if (m_selection_start < m_selection_end)
  472. return m_selection_start;
  473. return m_selection_end;
  474. }
  475. VT::Position TerminalWidget::normalized_selection_end() const
  476. {
  477. if (m_selection_start < m_selection_end)
  478. return m_selection_end;
  479. return m_selection_start;
  480. }
  481. bool TerminalWidget::has_selection() const
  482. {
  483. return m_selection_start.is_valid() && m_selection_end.is_valid();
  484. }
  485. bool TerminalWidget::selection_contains(const VT::Position& position) const
  486. {
  487. if (!has_selection())
  488. return false;
  489. if (m_rectangle_selection) {
  490. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  491. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  492. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  493. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  494. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  495. }
  496. return position >= normalized_selection_start() && position <= normalized_selection_end();
  497. }
  498. VT::Position TerminalWidget::buffer_position_at(const Gfx::Point& position) const
  499. {
  500. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  501. int row = adjusted_position.y() / m_line_height;
  502. int column = adjusted_position.x() / font().glyph_width('x');
  503. if (row < 0)
  504. row = 0;
  505. if (column < 0)
  506. column = 0;
  507. if (row >= m_terminal.rows())
  508. row = m_terminal.rows() - 1;
  509. if (column >= m_terminal.columns())
  510. column = m_terminal.columns() - 1;
  511. row += m_scrollbar->value();
  512. return { row, column };
  513. }
  514. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  515. {
  516. if (event.button() == GUI::MouseButton::Left) {
  517. m_triple_click_timer.start();
  518. auto position = buffer_position_at(event.position());
  519. auto& line = m_terminal.line(position.row());
  520. bool want_whitespace = line.characters[position.column()] == ' ';
  521. int start_column = 0;
  522. int end_column = 0;
  523. for (int column = position.column(); column >= 0 && (line.characters[column] == ' ') == want_whitespace; --column) {
  524. start_column = column;
  525. }
  526. for (int column = position.column(); column < m_terminal.columns() && (line.characters[column] == ' ') == want_whitespace; ++column) {
  527. end_column = column;
  528. }
  529. m_selection_start = { position.row(), start_column };
  530. m_selection_end = { position.row(), end_column };
  531. }
  532. GUI::Frame::doubleclick_event(event);
  533. }
  534. void TerminalWidget::paste()
  535. {
  536. if (m_ptm_fd == -1)
  537. return;
  538. auto text = GUI::Clipboard::the().data();
  539. if (text.is_empty())
  540. return;
  541. int nwritten = write(m_ptm_fd, text.characters(), text.length());
  542. if (nwritten < 0) {
  543. perror("write");
  544. ASSERT_NOT_REACHED();
  545. }
  546. }
  547. void TerminalWidget::copy()
  548. {
  549. if (has_selection())
  550. GUI::Clipboard::the().set_data(selected_text());
  551. }
  552. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  553. {
  554. if (event.button() == GUI::MouseButton::Left) {
  555. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  556. if (!m_active_href_id.is_null() && attribute.href_id == m_active_href_id) {
  557. dbg() << "Open hyperlinked URL: _" << attribute.href << "_";
  558. Desktop::Launcher::open(attribute.href);
  559. }
  560. if (!m_active_href_id.is_null()) {
  561. m_active_href = {};
  562. m_active_href_id = {};
  563. update();
  564. }
  565. }
  566. }
  567. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  568. {
  569. if (event.button() == GUI::MouseButton::Left) {
  570. m_left_mousedown_position = event.position();
  571. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  572. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  573. m_active_href = attribute.href;
  574. m_active_href_id = attribute.href_id;
  575. update();
  576. return;
  577. }
  578. m_active_href = {};
  579. m_active_href_id = {};
  580. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  581. int start_column = 0;
  582. int end_column = m_terminal.columns() - 1;
  583. auto position = buffer_position_at(event.position());
  584. m_selection_start = { position.row(), start_column };
  585. m_selection_end = { position.row(), end_column };
  586. } else {
  587. m_selection_start = buffer_position_at(event.position());
  588. m_selection_end = {};
  589. }
  590. if (m_alt_key_held)
  591. m_rectangle_selection = true;
  592. else if (m_rectangle_selection)
  593. m_rectangle_selection = false;
  594. update();
  595. }
  596. }
  597. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  598. {
  599. auto position = buffer_position_at(event.position());
  600. auto attribute = m_terminal.attribute_at(position);
  601. if (attribute.href_id != m_hovered_href_id) {
  602. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  603. m_hovered_href_id = attribute.href_id;
  604. m_hovered_href = attribute.href;
  605. } else {
  606. m_hovered_href_id = {};
  607. m_hovered_href = {};
  608. }
  609. if (!m_hovered_href.is_empty())
  610. window()->set_override_cursor(GUI::StandardCursor::Hand);
  611. else
  612. window()->set_override_cursor(GUI::StandardCursor::None);
  613. update();
  614. }
  615. if (!(event.buttons() & GUI::MouseButton::Left))
  616. return;
  617. if (!m_active_href_id.is_null()) {
  618. auto diff = event.position() - m_left_mousedown_position;
  619. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  620. constexpr int drag_distance_threshold = 5;
  621. if (distance_travelled_squared <= drag_distance_threshold)
  622. return;
  623. auto drag_operation = GUI::DragOperation::construct();
  624. drag_operation->set_text(m_active_href);
  625. drag_operation->set_data("text/uri-list", m_active_href);
  626. drag_operation->exec();
  627. m_active_href = {};
  628. m_active_href_id = {};
  629. update();
  630. return;
  631. }
  632. auto old_selection_end = m_selection_end;
  633. m_selection_end = position;
  634. if (old_selection_end != m_selection_end)
  635. update();
  636. }
  637. void TerminalWidget::leave_event(Core::Event&)
  638. {
  639. window()->set_override_cursor(GUI::StandardCursor::None);
  640. bool should_update = !m_hovered_href.is_empty();
  641. m_hovered_href = {};
  642. m_hovered_href_id = {};
  643. if (should_update)
  644. update();
  645. }
  646. void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
  647. {
  648. if (!is_scrollable())
  649. return;
  650. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta());
  651. GUI::Frame::mousewheel_event(event);
  652. }
  653. bool TerminalWidget::is_scrollable() const
  654. {
  655. return m_scrollbar->is_scrollable();
  656. }
  657. String TerminalWidget::selected_text() const
  658. {
  659. StringBuilder builder;
  660. auto start = normalized_selection_start();
  661. auto end = normalized_selection_end();
  662. for (int row = start.row(); row <= end.row(); ++row) {
  663. int first_column = first_selection_column_on_row(row);
  664. int last_column = last_selection_column_on_row(row);
  665. for (int column = first_column; column <= last_column; ++column) {
  666. auto& line = m_terminal.line(row);
  667. if (line.attributes[column].is_untouched()) {
  668. builder.append('\n');
  669. break;
  670. }
  671. builder.append(line.characters[column]);
  672. if (column == line.m_length - 1 || (m_rectangle_selection && column == last_column)) {
  673. builder.append('\n');
  674. }
  675. }
  676. }
  677. return builder.to_string();
  678. }
  679. int TerminalWidget::first_selection_column_on_row(int row) const
  680. {
  681. return row == normalized_selection_start().row() || m_rectangle_selection ? normalized_selection_start().column() : 0;
  682. }
  683. int TerminalWidget::last_selection_column_on_row(int row) const
  684. {
  685. return row == normalized_selection_end().row() || m_rectangle_selection ? normalized_selection_end().column() : m_terminal.columns() - 1;
  686. }
  687. void TerminalWidget::terminal_history_changed()
  688. {
  689. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  690. m_scrollbar->set_max(m_terminal.history().size());
  691. if (was_max)
  692. m_scrollbar->set_value(m_scrollbar->max());
  693. m_scrollbar->update();
  694. }
  695. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  696. {
  697. m_pixel_width = (frame_thickness() * 2) + (m_inset * 2) + (columns * font().glyph_width('x')) + m_scrollbar->width();
  698. m_pixel_height = (frame_thickness() * 2) + (m_inset * 2) + (rows * (font().glyph_height() + m_line_spacing));
  699. if (m_automatic_size_policy) {
  700. set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed);
  701. set_preferred_size(m_pixel_width, m_pixel_height);
  702. }
  703. m_needs_background_fill = true;
  704. force_repaint();
  705. winsize ws;
  706. ws.ws_row = rows;
  707. ws.ws_col = columns;
  708. if (m_ptm_fd != -1) {
  709. int rc = ioctl(m_ptm_fd, TIOCSWINSZ, &ws);
  710. ASSERT(rc == 0);
  711. }
  712. }
  713. void TerminalWidget::beep()
  714. {
  715. if (m_should_beep) {
  716. sysbeep();
  717. return;
  718. }
  719. m_visual_beep_timer->restart(200);
  720. m_visual_beep_timer->set_single_shot(true);
  721. m_visual_beep_timer->on_timeout = [this] {
  722. force_repaint();
  723. };
  724. force_repaint();
  725. }
  726. void TerminalWidget::emit(const u8* data, size_t size)
  727. {
  728. if (write(m_ptm_fd, data, size) < 0) {
  729. perror("TerminalWidget::emit: write");
  730. }
  731. }
  732. void TerminalWidget::context_menu_event(GUI::ContextMenuEvent& event)
  733. {
  734. if (m_hovered_href_id.is_null()) {
  735. m_context_menu->popup(event.screen_position());
  736. } else {
  737. m_context_menu_href = m_hovered_href;
  738. m_context_menu_for_hyperlink->popup(event.screen_position());
  739. }
  740. }
  741. void TerminalWidget::drop_event(GUI::DropEvent& event)
  742. {
  743. if (event.mime_data().has_text()) {
  744. event.accept();
  745. auto text = event.mime_data().text();
  746. write(m_ptm_fd, text.characters(), text.length());
  747. } else if (event.mime_data().has_urls()) {
  748. event.accept();
  749. auto urls = event.mime_data().urls();
  750. bool first = true;
  751. for (auto& url : event.mime_data().urls()) {
  752. if (!first) {
  753. write(m_ptm_fd, " ", 1);
  754. first = false;
  755. }
  756. if (url.protocol() == "file")
  757. write(m_ptm_fd, url.path().characters(), url.path().length());
  758. else
  759. write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
  760. }
  761. }
  762. }
  763. void TerminalWidget::did_change_font()
  764. {
  765. GUI::Frame::did_change_font();
  766. m_line_height = font().glyph_height() + m_line_spacing;
  767. // TODO: try to find a bold version of the new font (e.g. CsillaThin7x10 -> CsillaBold7x10)
  768. const Gfx::Font& bold_font = Gfx::Font::default_bold_fixed_width_font();
  769. if (bold_font.glyph_height() == font().glyph_height() && bold_font.glyph_width(' ') == font().glyph_width(' '))
  770. m_bold_font = &bold_font;
  771. else
  772. m_bold_font = font();
  773. if (!size().is_empty())
  774. relayout(size());
  775. }