TerminalWidget.cpp 24 KB

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