TerminalWidget.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. #include "TerminalWidget.h"
  2. #include "XtermColors.h"
  3. #include <AK/String.h>
  4. #include <AK/StdLibExtras.h>
  5. #include <AK/StringBuilder.h>
  6. #include <Kernel/KeyCode.h>
  7. #include <LibDraw/Font.h>
  8. #include <LibGUI/GApplication.h>
  9. #include <LibGUI/GClipboard.h>
  10. #include <LibGUI/GPainter.h>
  11. #include <LibGUI/GScrollBar.h>
  12. #include <LibGUI/GWindow.h>
  13. #include <errno.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <sys/ioctl.h>
  18. #include <unistd.h>
  19. //#define TERMINAL_DEBUG
  20. TerminalWidget::TerminalWidget(int ptm_fd, RefPtr<CConfigFile> config)
  21. : m_terminal(*this)
  22. , m_ptm_fd(ptm_fd)
  23. , m_notifier(CNotifier::construct(ptm_fd, CNotifier::Read))
  24. , m_config(move(config))
  25. {
  26. m_cursor_blink_timer = CTimer::construct();
  27. m_visual_beep_timer = CTimer::construct();
  28. set_frame_shape(FrameShape::Container);
  29. set_frame_shadow(FrameShadow::Sunken);
  30. set_frame_thickness(2);
  31. m_scrollbar = GScrollBar::construct(Orientation::Vertical, this);
  32. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  33. m_scrollbar->on_change = [this](int) {
  34. force_repaint();
  35. };
  36. dbgprintf("Terminal: Load config file from %s\n", m_config->file_name().characters());
  37. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  38. "CursorBlinkInterval",
  39. 500));
  40. m_cursor_blink_timer->on_timeout = [this] {
  41. m_cursor_blink_state = !m_cursor_blink_state;
  42. update_cursor();
  43. };
  44. auto font_entry = m_config->read_entry("Text", "Font", "default");
  45. if (font_entry == "default")
  46. set_font(Font::default_fixed_width_font());
  47. else
  48. set_font(Font::load_from_file(font_entry));
  49. m_notifier->on_ready_to_read = [this] {
  50. u8 buffer[BUFSIZ];
  51. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  52. if (nread < 0) {
  53. dbgprintf("Terminal read error: %s\n", strerror(errno));
  54. perror("read(ptm)");
  55. GApplication::the().quit(1);
  56. return;
  57. }
  58. if (nread == 0) {
  59. dbgprintf("Terminal: EOF on master pty, closing.\n");
  60. GApplication::the().quit(0);
  61. return;
  62. }
  63. for (ssize_t i = 0; i < nread; ++i)
  64. m_terminal.on_char(buffer[i]);
  65. flush_dirty_lines();
  66. };
  67. m_line_height = font().glyph_height() + m_line_spacing;
  68. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  69. }
  70. TerminalWidget::~TerminalWidget()
  71. {
  72. }
  73. static inline Color lookup_color(unsigned color)
  74. {
  75. return Color::from_rgb(xterm_colors[color]);
  76. }
  77. Rect TerminalWidget::glyph_rect(u16 row, u16 column)
  78. {
  79. int y = row * m_line_height;
  80. int x = column * font().glyph_width('x');
  81. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  82. }
  83. Rect TerminalWidget::row_rect(u16 row)
  84. {
  85. int y = row * m_line_height;
  86. Rect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  87. rect.inflate(0, m_line_spacing);
  88. return rect;
  89. }
  90. void TerminalWidget::event(CEvent& event)
  91. {
  92. if (event.type() == GEvent::WindowBecameActive || event.type() == GEvent::WindowBecameInactive) {
  93. m_in_active_window = event.type() == GEvent::WindowBecameActive;
  94. if (!m_in_active_window) {
  95. m_cursor_blink_timer->stop();
  96. } else {
  97. m_cursor_blink_state = true;
  98. m_cursor_blink_timer->start();
  99. }
  100. invalidate_cursor();
  101. update();
  102. }
  103. return GWidget::event(event);
  104. }
  105. void TerminalWidget::keydown_event(GKeyEvent& event)
  106. {
  107. // Reset timer so cursor doesn't blink while typing.
  108. m_cursor_blink_timer->stop();
  109. m_cursor_blink_state = true;
  110. m_cursor_blink_timer->start();
  111. switch (event.key()) {
  112. case KeyCode::Key_Up:
  113. write(m_ptm_fd, "\033[A", 3);
  114. return;
  115. case KeyCode::Key_Down:
  116. write(m_ptm_fd, "\033[B", 3);
  117. return;
  118. case KeyCode::Key_Right:
  119. write(m_ptm_fd, "\033[C", 3);
  120. return;
  121. case KeyCode::Key_Left:
  122. write(m_ptm_fd, "\033[D", 3);
  123. return;
  124. case KeyCode::Key_Insert:
  125. write(m_ptm_fd, "\033[2~", 4);
  126. return;
  127. case KeyCode::Key_Delete:
  128. write(m_ptm_fd, "\033[3~", 4);
  129. return;
  130. case KeyCode::Key_Home:
  131. write(m_ptm_fd, "\033[H", 3);
  132. return;
  133. case KeyCode::Key_End:
  134. write(m_ptm_fd, "\033[F", 3);
  135. return;
  136. case KeyCode::Key_PageUp:
  137. write(m_ptm_fd, "\033[5~", 4);
  138. return;
  139. case KeyCode::Key_PageDown:
  140. write(m_ptm_fd, "\033[6~", 4);
  141. return;
  142. default:
  143. break;
  144. }
  145. // Key event was not one of the above special cases,
  146. // attempt to treat it as a character...
  147. char ch = !event.text().is_empty() ? event.text()[0] : 0;
  148. if (ch) {
  149. if (event.ctrl()) {
  150. if (ch >= 'a' && ch <= 'z') {
  151. ch = ch - 'a' + 1;
  152. } else if (ch == '\\') {
  153. ch = 0x1c;
  154. }
  155. }
  156. // ALT modifier sends escape prefix
  157. if (event.alt())
  158. write(m_ptm_fd, "\033", 1);
  159. //Clear the selection if we type in/behind it
  160. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  161. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  162. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  163. 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) {
  164. m_selection_end = {};
  165. update();
  166. }
  167. write(m_ptm_fd, &ch, 1);
  168. }
  169. m_scrollbar->set_value(m_scrollbar->max());
  170. }
  171. void TerminalWidget::paint_event(GPaintEvent& event)
  172. {
  173. GFrame::paint_event(event);
  174. GPainter painter(*this);
  175. painter.add_clip_rect(event.rect());
  176. if (m_visual_beep_timer->is_active())
  177. painter.fill_rect(frame_inner_rect(), Color::Red);
  178. else
  179. painter.fill_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  180. invalidate_cursor();
  181. int rows_from_history = 0;
  182. int first_row_from_history = 0;
  183. int row_with_cursor = m_terminal.cursor_row();
  184. if (m_scrollbar->value() != m_scrollbar->max()) {
  185. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  186. first_row_from_history = m_terminal.history().size() - (m_scrollbar->max() - m_scrollbar->value());
  187. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  188. }
  189. auto line_for_visual_row = [&](u16 row) -> const VT::Terminal::Line& {
  190. if (row < rows_from_history)
  191. return m_terminal.history().at(first_row_from_history + row);
  192. return m_terminal.line(row - rows_from_history);
  193. };
  194. for (u16 row = 0; row < m_terminal.rows(); ++row) {
  195. auto row_rect = this->row_rect(row);
  196. if (!event.rect().contains(row_rect))
  197. continue;
  198. auto& line = line_for_visual_row(row);
  199. bool has_only_one_background_color = line.has_only_one_background_color();
  200. if (m_visual_beep_timer->is_active())
  201. painter.fill_rect(row_rect, Color::Red);
  202. else if (has_only_one_background_color)
  203. painter.fill_rect(row_rect, lookup_color(line.attributes[0].background_color).with_alpha(m_opacity));
  204. // The terminal insists on thinking characters and
  205. // bytes are the same thing. We want to still draw
  206. // emojis in *some* way, but it won't be completely
  207. // perfect. So what we do is we make multi-byte
  208. // characters take up multiple columns, and render
  209. // the character itself in the center of the columns
  210. // its bytes take up as far as the terminal is concerned.
  211. ASSERT(line.text().length() == m_terminal.columns());
  212. Utf8View utf8_view { line.text() };
  213. for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
  214. u32 codepoint = *it;
  215. int this_char_column = utf8_view.byte_offset_of(it);
  216. AK::Utf8CodepointIterator it_copy = it;
  217. int next_char_column = utf8_view.byte_offset_of(++it_copy);
  218. // Columns from this_char_column up until next_char_column
  219. // are logically taken up by this (possibly multi-byte)
  220. // character. Iterate over these columns and draw background
  221. // for each one of them separately.
  222. bool should_reverse_fill_for_cursor_or_selection = false;
  223. VT::Attribute attribute;
  224. for (u16 column = this_char_column; column < next_char_column; ++column) {
  225. should_reverse_fill_for_cursor_or_selection |=
  226. m_cursor_blink_state
  227. && m_in_active_window
  228. && row == row_with_cursor
  229. && column == m_terminal.cursor_column();
  230. should_reverse_fill_for_cursor_or_selection |= selection_contains({ row, column });
  231. attribute = line.attributes[column];
  232. auto character_rect = glyph_rect(row, column);
  233. if (!has_only_one_background_color || should_reverse_fill_for_cursor_or_selection) {
  234. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  235. painter.fill_rect(cell_rect, lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.foreground_color : attribute.background_color).with_alpha(m_opacity));
  236. }
  237. }
  238. if (codepoint == ' ')
  239. continue;
  240. auto character_rect = glyph_rect(row, this_char_column);
  241. auto num_columns = next_char_column - this_char_column;
  242. character_rect.move_by((num_columns - 1) * font().glyph_width('x') / 2, 0);
  243. painter.draw_glyph_or_emoji(
  244. character_rect.location(),
  245. codepoint,
  246. attribute.flags & VT::Attribute::Bold ? Font::default_bold_fixed_width_font() : font(),
  247. lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color));
  248. }
  249. }
  250. if (!m_in_active_window && row_with_cursor < m_terminal.rows()) {
  251. auto& cursor_line = line_for_visual_row(row_with_cursor);
  252. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  253. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  254. painter.draw_rect(cell_rect, lookup_color(cursor_line.attributes[m_terminal.cursor_column()].foreground_color));
  255. }
  256. }
  257. }
  258. void TerminalWidget::set_window_title(const StringView& title)
  259. {
  260. auto* w = window();
  261. if (!w)
  262. return;
  263. w->set_title(title);
  264. }
  265. void TerminalWidget::invalidate_cursor()
  266. {
  267. m_terminal.invalidate_cursor();
  268. }
  269. void TerminalWidget::flush_dirty_lines()
  270. {
  271. // FIXME: Update smarter when scrolled
  272. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  273. update();
  274. m_terminal.m_need_full_flush = false;
  275. return;
  276. }
  277. Rect rect;
  278. for (int i = 0; i < m_terminal.rows(); ++i) {
  279. if (m_terminal.line(i).dirty) {
  280. rect = rect.united(row_rect(i));
  281. m_terminal.line(i).dirty = false;
  282. }
  283. }
  284. update(rect);
  285. }
  286. void TerminalWidget::force_repaint()
  287. {
  288. m_needs_background_fill = true;
  289. update();
  290. }
  291. void TerminalWidget::resize_event(GResizeEvent& event)
  292. {
  293. auto base_size = compute_base_size();
  294. int new_columns = (event.size().width() - base_size.width()) / font().glyph_width('x');
  295. int new_rows = (event.size().height() - base_size.height()) / m_line_height;
  296. m_terminal.set_size(new_columns, new_rows);
  297. Rect scrollbar_rect = {
  298. event.size().width() - m_scrollbar->width() - frame_thickness(),
  299. frame_thickness(),
  300. m_scrollbar->width(),
  301. event.size().height() - frame_thickness() * 2,
  302. };
  303. m_scrollbar->set_relative_rect(scrollbar_rect);
  304. }
  305. Size TerminalWidget::compute_base_size() const
  306. {
  307. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  308. int base_height = frame_thickness() * 2 + m_inset * 2;
  309. return { base_width, base_height };
  310. }
  311. void TerminalWidget::apply_size_increments_to_window(GWindow& window)
  312. {
  313. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  314. window.set_base_size(compute_base_size());
  315. }
  316. void TerminalWidget::update_cursor()
  317. {
  318. invalidate_cursor();
  319. flush_dirty_lines();
  320. }
  321. void TerminalWidget::set_opacity(u8 new_opacity)
  322. {
  323. if (m_opacity == new_opacity)
  324. return;
  325. window()->set_has_alpha_channel(new_opacity < 255);
  326. m_opacity = new_opacity;
  327. force_repaint();
  328. }
  329. VT::Position TerminalWidget::normalized_selection_start() const
  330. {
  331. if (m_selection_start < m_selection_end)
  332. return m_selection_start;
  333. return m_selection_end;
  334. }
  335. VT::Position TerminalWidget::normalized_selection_end() const
  336. {
  337. if (m_selection_start < m_selection_end)
  338. return m_selection_end;
  339. return m_selection_start;
  340. }
  341. bool TerminalWidget::has_selection() const
  342. {
  343. return m_selection_start.is_valid() && m_selection_end.is_valid();
  344. }
  345. bool TerminalWidget::selection_contains(const VT::Position& position) const
  346. {
  347. if (!has_selection())
  348. return false;
  349. return position >= normalized_selection_start() && position <= normalized_selection_end();
  350. }
  351. VT::Position TerminalWidget::buffer_position_at(const Point& position) const
  352. {
  353. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  354. int row = adjusted_position.y() / m_line_height;
  355. int column = adjusted_position.x() / font().glyph_width('x');
  356. if (row < 0)
  357. row = 0;
  358. if (column < 0)
  359. column = 0;
  360. if (row >= m_terminal.rows())
  361. row = m_terminal.rows() - 1;
  362. if (column >= m_terminal.columns())
  363. column = m_terminal.columns() - 1;
  364. return { row, column };
  365. }
  366. void TerminalWidget::doubleclick_event(GMouseEvent& event)
  367. {
  368. if (event.button() == GMouseButton::Left) {
  369. auto position = buffer_position_at(event.position());
  370. auto& line = m_terminal.line(position.row());
  371. bool want_whitespace = line.characters[position.column()] == ' ';
  372. int start_column = 0;
  373. int end_column = 0;
  374. for (int column = position.column(); column >= 0 && (line.characters[column] == ' ') == want_whitespace; --column) {
  375. start_column = column;
  376. }
  377. for (int column = position.column(); column < m_terminal.columns() && (line.characters[column] == ' ') == want_whitespace; ++column) {
  378. end_column = column;
  379. }
  380. m_selection_start = { position.row(), start_column };
  381. m_selection_end = { position.row(), end_column };
  382. if (has_selection())
  383. GClipboard::the().set_data(selected_text());
  384. }
  385. GFrame::doubleclick_event(event);
  386. }
  387. void TerminalWidget::mousedown_event(GMouseEvent& event)
  388. {
  389. if (event.button() == GMouseButton::Left) {
  390. m_selection_start = buffer_position_at(event.position());
  391. m_selection_end = {};
  392. update();
  393. } else if (event.button() == GMouseButton::Right) {
  394. auto text = GClipboard::the().data();
  395. if (text.is_empty())
  396. return;
  397. int nwritten = write(m_ptm_fd, text.characters(), text.length());
  398. if (nwritten < 0) {
  399. perror("write");
  400. ASSERT_NOT_REACHED();
  401. }
  402. }
  403. }
  404. void TerminalWidget::mousemove_event(GMouseEvent& event)
  405. {
  406. if (!(event.buttons() & GMouseButton::Left))
  407. return;
  408. auto old_selection_end = m_selection_end;
  409. m_selection_end = buffer_position_at(event.position());
  410. if (old_selection_end != m_selection_end)
  411. update();
  412. }
  413. void TerminalWidget::mouseup_event(GMouseEvent& event)
  414. {
  415. if (event.button() != GMouseButton::Left)
  416. return;
  417. if (!has_selection())
  418. return;
  419. GClipboard::the().set_data(selected_text());
  420. }
  421. void TerminalWidget::mousewheel_event(GMouseEvent& event)
  422. {
  423. if (!is_scrollable())
  424. return;
  425. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta());
  426. GFrame::mousewheel_event(event);
  427. }
  428. bool TerminalWidget::is_scrollable() const
  429. {
  430. return m_scrollbar->is_scrollable();
  431. }
  432. String TerminalWidget::selected_text() const
  433. {
  434. StringBuilder builder;
  435. auto start = normalized_selection_start();
  436. auto end = normalized_selection_end();
  437. for (int row = start.row(); row <= end.row(); ++row) {
  438. int first_column = first_selection_column_on_row(row);
  439. int last_column = last_selection_column_on_row(row);
  440. for (int column = first_column; column <= last_column; ++column) {
  441. auto& line = m_terminal.line(row);
  442. if (line.attributes[column].is_untouched()) {
  443. builder.append('\n');
  444. break;
  445. }
  446. builder.append(line.characters[column]);
  447. if (column == line.m_length - 1) {
  448. builder.append('\n');
  449. }
  450. }
  451. }
  452. return builder.to_string();
  453. }
  454. int TerminalWidget::first_selection_column_on_row(int row) const
  455. {
  456. return row == normalized_selection_start().row() ? normalized_selection_start().column() : 0;
  457. }
  458. int TerminalWidget::last_selection_column_on_row(int row) const
  459. {
  460. return row == normalized_selection_end().row() ? normalized_selection_end().column() : m_terminal.columns() - 1;
  461. }
  462. void TerminalWidget::terminal_history_changed()
  463. {
  464. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  465. m_scrollbar->set_max(m_terminal.history().size());
  466. if (was_max)
  467. m_scrollbar->set_value(m_scrollbar->max());
  468. m_scrollbar->update();
  469. }
  470. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  471. {
  472. m_pixel_width = (frame_thickness() * 2) + (m_inset * 2) + (columns * font().glyph_width('x'));
  473. m_pixel_height = (frame_thickness() * 2) + (m_inset * 2) + (rows * (font().glyph_height() + m_line_spacing)) - m_line_spacing;
  474. set_size_policy(SizePolicy::Fixed, SizePolicy::Fixed);
  475. set_preferred_size(m_pixel_width, m_pixel_height);
  476. m_needs_background_fill = true;
  477. force_repaint();
  478. winsize ws;
  479. ws.ws_row = rows;
  480. ws.ws_col = columns;
  481. int rc = ioctl(m_ptm_fd, TIOCSWINSZ, &ws);
  482. ASSERT(rc == 0);
  483. }
  484. void TerminalWidget::beep()
  485. {
  486. if (m_should_beep) {
  487. sysbeep();
  488. return;
  489. }
  490. m_visual_beep_timer->restart(200);
  491. m_visual_beep_timer->set_single_shot(true);
  492. m_visual_beep_timer->on_timeout = [this] {
  493. force_repaint();
  494. };
  495. force_repaint();
  496. }