TerminalWidget.cpp 27 KB

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