TerminalWidget.cpp 31 KB

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