TerminalWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. write(m_ptm_fd, &ch, 1);
  158. }
  159. }
  160. void TerminalWidget::paint_event(GPaintEvent& event)
  161. {
  162. GFrame::paint_event(event);
  163. GPainter painter(*this);
  164. painter.add_clip_rect(event.rect());
  165. if (m_visual_beep_timer.is_active())
  166. painter.fill_rect(frame_inner_rect(), Color::Red);
  167. else
  168. painter.fill_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  169. invalidate_cursor();
  170. int rows_from_history = 0;
  171. int first_row_from_history = 0;
  172. int row_with_cursor = m_terminal.cursor_row();
  173. if (m_scrollbar->value() != m_scrollbar->max()) {
  174. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  175. first_row_from_history = m_terminal.history().size() - (m_scrollbar->max() - m_scrollbar->value());
  176. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  177. }
  178. auto line_for_visual_row = [&](u16 row) -> const VT::Terminal::Line& {
  179. if (row < rows_from_history)
  180. return m_terminal.history().at(first_row_from_history + row);
  181. return m_terminal.line(row - rows_from_history);
  182. };
  183. for (u16 row = 0; row < m_terminal.rows(); ++row) {
  184. auto row_rect = this->row_rect(row);
  185. if (!event.rect().contains(row_rect))
  186. continue;
  187. auto& line = line_for_visual_row(row);
  188. bool has_only_one_background_color = line.has_only_one_background_color();
  189. if (m_visual_beep_timer.is_active())
  190. painter.fill_rect(row_rect, Color::Red);
  191. else if (has_only_one_background_color)
  192. painter.fill_rect(row_rect, lookup_color(line.attributes[0].background_color).with_alpha(m_opacity));
  193. for (u16 column = 0; column < m_terminal.columns(); ++column) {
  194. char ch = line.characters[column];
  195. bool should_reverse_fill_for_cursor_or_selection = (m_cursor_blink_state && m_in_active_window && row == row_with_cursor && column == m_terminal.cursor_column())
  196. || selection_contains({ row, column });
  197. auto& attribute = line.attributes[column];
  198. auto character_rect = glyph_rect(row, column);
  199. if (!has_only_one_background_color || should_reverse_fill_for_cursor_or_selection) {
  200. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  201. painter.fill_rect(cell_rect, lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.foreground_color : attribute.background_color).with_alpha(m_opacity));
  202. }
  203. if (ch == ' ')
  204. continue;
  205. painter.draw_glyph(
  206. character_rect.location(),
  207. ch,
  208. attribute.flags & VT::Attribute::Bold ? Font::default_bold_fixed_width_font() : font(),
  209. lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color));
  210. }
  211. }
  212. if (!m_in_active_window && row_with_cursor < m_terminal.rows()) {
  213. auto& cursor_line = line_for_visual_row(row_with_cursor);
  214. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  215. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  216. painter.draw_rect(cell_rect, lookup_color(cursor_line.attributes[m_terminal.cursor_column()].foreground_color));
  217. }
  218. }
  219. }
  220. void TerminalWidget::set_window_title(const StringView& title)
  221. {
  222. auto* w = window();
  223. if (!w)
  224. return;
  225. w->set_title(title);
  226. }
  227. void TerminalWidget::invalidate_cursor()
  228. {
  229. m_terminal.invalidate_cursor();
  230. }
  231. void TerminalWidget::flush_dirty_lines()
  232. {
  233. // FIXME: Update smarter when scrolled
  234. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  235. update();
  236. m_terminal.m_need_full_flush = false;
  237. return;
  238. }
  239. Rect rect;
  240. for (int i = 0; i < m_terminal.rows(); ++i) {
  241. if (m_terminal.line(i).dirty) {
  242. rect = rect.united(row_rect(i));
  243. m_terminal.line(i).dirty = false;
  244. }
  245. }
  246. update(rect);
  247. }
  248. void TerminalWidget::force_repaint()
  249. {
  250. m_needs_background_fill = true;
  251. update();
  252. }
  253. void TerminalWidget::resize_event(GResizeEvent& event)
  254. {
  255. auto base_size = compute_base_size();
  256. int new_columns = (event.size().width() - base_size.width()) / font().glyph_width('x');
  257. int new_rows = (event.size().height() - base_size.height()) / m_line_height;
  258. m_terminal.set_size(new_columns, new_rows);
  259. Rect scrollbar_rect = {
  260. event.size().width() - m_scrollbar->width() - frame_thickness(),
  261. frame_thickness(),
  262. m_scrollbar->width(),
  263. event.size().height() - frame_thickness() * 2,
  264. };
  265. m_scrollbar->set_relative_rect(scrollbar_rect);
  266. }
  267. Size TerminalWidget::compute_base_size() const
  268. {
  269. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  270. int base_height = frame_thickness() * 2 + m_inset * 2;
  271. return { base_width, base_height };
  272. }
  273. void TerminalWidget::apply_size_increments_to_window(GWindow& window)
  274. {
  275. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  276. window.set_base_size(compute_base_size());
  277. }
  278. void TerminalWidget::update_cursor()
  279. {
  280. invalidate_cursor();
  281. flush_dirty_lines();
  282. }
  283. void TerminalWidget::set_opacity(u8 new_opacity)
  284. {
  285. if (m_opacity == new_opacity)
  286. return;
  287. window()->set_has_alpha_channel(new_opacity < 255);
  288. m_opacity = new_opacity;
  289. force_repaint();
  290. }
  291. VT::Position TerminalWidget::normalized_selection_start() const
  292. {
  293. if (m_selection_start < m_selection_end)
  294. return m_selection_start;
  295. return m_selection_end;
  296. }
  297. VT::Position TerminalWidget::normalized_selection_end() const
  298. {
  299. if (m_selection_start < m_selection_end)
  300. return m_selection_end;
  301. return m_selection_start;
  302. }
  303. bool TerminalWidget::has_selection() const
  304. {
  305. return m_selection_start.is_valid() && m_selection_end.is_valid();
  306. }
  307. bool TerminalWidget::selection_contains(const VT::Position& position) const
  308. {
  309. if (!has_selection())
  310. return false;
  311. return position >= normalized_selection_start() && position <= normalized_selection_end();
  312. }
  313. VT::Position TerminalWidget::buffer_position_at(const Point& position) const
  314. {
  315. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  316. int row = adjusted_position.y() / m_line_height;
  317. int column = adjusted_position.x() / font().glyph_width('x');
  318. if (row < 0)
  319. row = 0;
  320. if (column < 0)
  321. column = 0;
  322. if (row >= m_terminal.rows())
  323. row = m_terminal.rows() - 1;
  324. if (column >= m_terminal.columns())
  325. column = m_terminal.columns() - 1;
  326. return { row, column };
  327. }
  328. void TerminalWidget::mousedown_event(GMouseEvent& event)
  329. {
  330. if (event.button() == GMouseButton::Left) {
  331. m_selection_start = buffer_position_at(event.position());
  332. m_selection_end = {};
  333. update();
  334. } else if (event.button() == GMouseButton::Right) {
  335. auto text = GClipboard::the().data();
  336. if (text.is_empty())
  337. return;
  338. int nwritten = write(m_ptm_fd, text.characters(), text.length());
  339. if (nwritten < 0) {
  340. perror("write");
  341. ASSERT_NOT_REACHED();
  342. }
  343. }
  344. }
  345. void TerminalWidget::mousemove_event(GMouseEvent& event)
  346. {
  347. if (!(event.buttons() & GMouseButton::Left))
  348. return;
  349. auto old_selection_end = m_selection_end;
  350. m_selection_end = buffer_position_at(event.position());
  351. if (old_selection_end != m_selection_end)
  352. update();
  353. }
  354. void TerminalWidget::mouseup_event(GMouseEvent& event)
  355. {
  356. if (event.button() != GMouseButton::Left)
  357. return;
  358. if (!has_selection())
  359. return;
  360. GClipboard::the().set_data(selected_text());
  361. }
  362. String TerminalWidget::selected_text() const
  363. {
  364. StringBuilder builder;
  365. auto start = normalized_selection_start();
  366. auto end = normalized_selection_end();
  367. for (int row = start.row(); row <= end.row(); ++row) {
  368. int first_column = row == start.row() ? start.column() : 0;
  369. int last_column = row == end.row() ? end.column() : m_terminal.columns() - 1;
  370. for (int column = first_column; column <= last_column; ++column) {
  371. auto& line = m_terminal.line(row);
  372. if (line.attributes[column].is_untouched()) {
  373. builder.append('\n');
  374. break;
  375. }
  376. builder.append(line.characters[column]);
  377. if (column == line.m_length - 1) {
  378. builder.append('\n');
  379. }
  380. }
  381. }
  382. return builder.to_string();
  383. }
  384. void TerminalWidget::terminal_history_changed()
  385. {
  386. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  387. m_scrollbar->set_max(m_terminal.history().size());
  388. if (was_max)
  389. m_scrollbar->set_value(m_scrollbar->max());
  390. m_scrollbar->update();
  391. }
  392. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  393. {
  394. m_pixel_width = (frame_thickness() * 2) + (m_inset * 2) + (columns * font().glyph_width('x'));
  395. m_pixel_height = (frame_thickness() * 2) + (m_inset * 2) + (rows * (font().glyph_height() + m_line_spacing)) - m_line_spacing;
  396. set_size_policy(SizePolicy::Fixed, SizePolicy::Fixed);
  397. set_preferred_size(m_pixel_width, m_pixel_height);
  398. m_needs_background_fill = true;
  399. force_repaint();
  400. winsize ws;
  401. ws.ws_row = rows;
  402. ws.ws_col = columns;
  403. int rc = ioctl(m_ptm_fd, TIOCSWINSZ, &ws);
  404. ASSERT(rc == 0);
  405. }
  406. void TerminalWidget::beep()
  407. {
  408. if (m_should_beep) {
  409. sysbeep();
  410. return;
  411. }
  412. m_visual_beep_timer.restart(200);
  413. m_visual_beep_timer.set_single_shot(true);
  414. m_visual_beep_timer.on_timeout = [this] {
  415. force_repaint();
  416. };
  417. force_repaint();
  418. }