TerminalWidget.cpp 30 KB

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