TerminalWidget.cpp 18 KB

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