TerminalWidget.cpp 25 KB

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