TerminalWidget.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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/GWindow.h>
  12. #include <errno.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <sys/ioctl.h>
  17. #include <unistd.h>
  18. //#define TERMINAL_DEBUG
  19. TerminalWidget::TerminalWidget(int ptm_fd, RefPtr<CConfigFile> config)
  20. : m_terminal(*this)
  21. , m_ptm_fd(ptm_fd)
  22. , m_notifier(ptm_fd, CNotifier::Read)
  23. , m_config(move(config))
  24. {
  25. set_frame_shape(FrameShape::Container);
  26. set_frame_shadow(FrameShadow::Sunken);
  27. set_frame_thickness(2);
  28. dbgprintf("Terminal: Load config file from %s\n", m_config->file_name().characters());
  29. m_cursor_blink_timer.set_interval(m_config->read_num_entry("Text",
  30. "CursorBlinkInterval",
  31. 500));
  32. m_cursor_blink_timer.on_timeout = [this] {
  33. m_cursor_blink_state = !m_cursor_blink_state;
  34. update_cursor();
  35. };
  36. auto font_entry = m_config->read_entry("Text", "Font", "default");
  37. if (font_entry == "default")
  38. set_font(Font::default_fixed_width_font());
  39. else
  40. set_font(Font::load_from_file(font_entry));
  41. m_notifier.on_ready_to_read = [this] {
  42. u8 buffer[BUFSIZ];
  43. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  44. if (nread < 0) {
  45. dbgprintf("Terminal read error: %s\n", strerror(errno));
  46. perror("read(ptm)");
  47. GApplication::the().quit(1);
  48. return;
  49. }
  50. if (nread == 0) {
  51. dbgprintf("Terminal: EOF on master pty, closing.\n");
  52. GApplication::the().quit(0);
  53. return;
  54. }
  55. for (ssize_t i = 0; i < nread; ++i)
  56. m_terminal.on_char(buffer[i]);
  57. flush_dirty_lines();
  58. };
  59. m_line_height = font().glyph_height() + m_line_spacing;
  60. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  61. }
  62. TerminalWidget::~TerminalWidget()
  63. {
  64. }
  65. static inline Color lookup_color(unsigned color)
  66. {
  67. return Color::from_rgb(xterm_colors[color]);
  68. }
  69. Rect TerminalWidget::glyph_rect(u16 row, u16 column)
  70. {
  71. int y = row * m_line_height;
  72. int x = column * font().glyph_width('x');
  73. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  74. }
  75. Rect TerminalWidget::row_rect(u16 row)
  76. {
  77. int y = row * m_line_height;
  78. Rect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  79. rect.inflate(0, m_line_spacing);
  80. return rect;
  81. }
  82. void TerminalWidget::event(CEvent& event)
  83. {
  84. if (event.type() == GEvent::WindowBecameActive || event.type() == GEvent::WindowBecameInactive) {
  85. m_in_active_window = event.type() == GEvent::WindowBecameActive;
  86. if (!m_in_active_window) {
  87. m_cursor_blink_timer.stop();
  88. } else {
  89. m_cursor_blink_state = true;
  90. m_cursor_blink_timer.start();
  91. }
  92. invalidate_cursor();
  93. update();
  94. }
  95. return GWidget::event(event);
  96. }
  97. void TerminalWidget::keydown_event(GKeyEvent& event)
  98. {
  99. // Reset timer so cursor doesn't blink while typing.
  100. m_cursor_blink_timer.stop();
  101. m_cursor_blink_state = true;
  102. m_cursor_blink_timer.start();
  103. switch (event.key()) {
  104. case KeyCode::Key_Up:
  105. write(m_ptm_fd, "\033[A", 3);
  106. return;
  107. case KeyCode::Key_Down:
  108. write(m_ptm_fd, "\033[B", 3);
  109. return;
  110. case KeyCode::Key_Right:
  111. write(m_ptm_fd, "\033[C", 3);
  112. return;
  113. case KeyCode::Key_Left:
  114. write(m_ptm_fd, "\033[D", 3);
  115. return;
  116. case KeyCode::Key_Insert:
  117. write(m_ptm_fd, "\033[2~", 4);
  118. return;
  119. case KeyCode::Key_Delete:
  120. write(m_ptm_fd, "\033[3~", 4);
  121. return;
  122. case KeyCode::Key_Home:
  123. write(m_ptm_fd, "\033[H", 3);
  124. return;
  125. case KeyCode::Key_End:
  126. write(m_ptm_fd, "\033[F", 3);
  127. return;
  128. case KeyCode::Key_PageUp:
  129. write(m_ptm_fd, "\033[5~", 4);
  130. return;
  131. case KeyCode::Key_PageDown:
  132. write(m_ptm_fd, "\033[6~", 4);
  133. return;
  134. default:
  135. break;
  136. }
  137. // Key event was not one of the above special cases,
  138. // attempt to treat it as a character...
  139. char ch = !event.text().is_empty() ? event.text()[0] : 0;
  140. if (ch) {
  141. if (event.ctrl()) {
  142. if (ch >= 'a' && ch <= 'z') {
  143. ch = ch - 'a' + 1;
  144. } else if (ch == '\\') {
  145. ch = 0x1c;
  146. }
  147. }
  148. // ALT modifier sends escape prefix
  149. if (event.alt())
  150. write(m_ptm_fd, "\033", 1);
  151. write(m_ptm_fd, &ch, 1);
  152. }
  153. }
  154. void TerminalWidget::paint_event(GPaintEvent& event)
  155. {
  156. GFrame::paint_event(event);
  157. GPainter painter(*this);
  158. painter.add_clip_rect(event.rect());
  159. if (m_visual_beep_timer.is_active())
  160. painter.fill_rect(frame_inner_rect(), Color::Red);
  161. else
  162. painter.fill_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  163. invalidate_cursor();
  164. for (u16 row = 0; row < m_terminal.rows(); ++row) {
  165. auto row_rect = this->row_rect(row);
  166. if (!event.rect().contains(row_rect))
  167. continue;
  168. auto& line = m_terminal.line(row);
  169. bool has_only_one_background_color = line.has_only_one_background_color();
  170. if (m_visual_beep_timer.is_active())
  171. painter.fill_rect(row_rect, Color::Red);
  172. else if (has_only_one_background_color)
  173. painter.fill_rect(row_rect, lookup_color(line.attributes[0].background_color).with_alpha(m_opacity));
  174. for (u16 column = 0; column < m_terminal.columns(); ++column) {
  175. char ch = line.characters[column];
  176. bool should_reverse_fill_for_cursor_or_selection = (m_cursor_blink_state && m_in_active_window && row == m_terminal.cursor_row() && column == m_terminal.cursor_column())
  177. || selection_contains({ row, column });
  178. auto& attribute = line.attributes[column];
  179. auto character_rect = glyph_rect(row, column);
  180. if (!has_only_one_background_color || should_reverse_fill_for_cursor_or_selection) {
  181. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  182. painter.fill_rect(cell_rect, lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.foreground_color : attribute.background_color).with_alpha(m_opacity));
  183. }
  184. if (ch == ' ')
  185. continue;
  186. painter.draw_glyph(
  187. character_rect.location(),
  188. ch,
  189. attribute.flags & VT::Attribute::Bold ? Font::default_bold_fixed_width_font() : font(),
  190. lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color));
  191. }
  192. }
  193. if (!m_in_active_window) {
  194. auto cell_rect = glyph_rect(m_terminal.cursor_row(), m_terminal.cursor_column()).inflated(0, m_line_spacing);
  195. painter.draw_rect(cell_rect, lookup_color(m_terminal.line(m_terminal.cursor_row()).attributes[m_terminal.cursor_column()].foreground_color));
  196. }
  197. }
  198. void TerminalWidget::set_window_title(const StringView& title)
  199. {
  200. auto* w = window();
  201. if (!w)
  202. return;
  203. w->set_title(title);
  204. }
  205. void TerminalWidget::invalidate_cursor()
  206. {
  207. m_terminal.invalidate_cursor();
  208. }
  209. void TerminalWidget::flush_dirty_lines()
  210. {
  211. if (m_terminal.m_need_full_flush) {
  212. update();
  213. m_terminal.m_need_full_flush = false;
  214. return;
  215. }
  216. Rect rect;
  217. for (int i = 0; i < m_terminal.rows(); ++i) {
  218. if (m_terminal.line(i).dirty) {
  219. rect = rect.united(row_rect(i));
  220. m_terminal.line(i).dirty = false;
  221. }
  222. }
  223. update(rect);
  224. }
  225. void TerminalWidget::force_repaint()
  226. {
  227. m_needs_background_fill = true;
  228. update();
  229. }
  230. void TerminalWidget::resize_event(GResizeEvent& event)
  231. {
  232. int new_columns = (event.size().width() - frame_thickness() * 2 - m_inset * 2) / font().glyph_width('x');
  233. int new_rows = (event.size().height() - frame_thickness() * 2 - m_inset * 2) / m_line_height;
  234. m_terminal.set_size(new_columns, new_rows);
  235. }
  236. void TerminalWidget::apply_size_increments_to_window(GWindow& window)
  237. {
  238. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  239. window.set_base_size({ frame_thickness() * 2 + m_inset * 2, frame_thickness() * 2 + m_inset * 2 });
  240. }
  241. void TerminalWidget::update_cursor()
  242. {
  243. invalidate_cursor();
  244. flush_dirty_lines();
  245. }
  246. void TerminalWidget::set_opacity(u8 new_opacity)
  247. {
  248. if (m_opacity == new_opacity)
  249. return;
  250. window()->set_has_alpha_channel(new_opacity < 255);
  251. m_opacity = new_opacity;
  252. force_repaint();
  253. }
  254. VT::Position TerminalWidget::normalized_selection_start() const
  255. {
  256. if (m_selection_start < m_selection_end)
  257. return m_selection_start;
  258. return m_selection_end;
  259. }
  260. VT::Position TerminalWidget::normalized_selection_end() const
  261. {
  262. if (m_selection_start < m_selection_end)
  263. return m_selection_end;
  264. return m_selection_start;
  265. }
  266. bool TerminalWidget::has_selection() const
  267. {
  268. return m_selection_start.is_valid() && m_selection_end.is_valid();
  269. }
  270. bool TerminalWidget::selection_contains(const VT::Position& position) const
  271. {
  272. if (!has_selection())
  273. return false;
  274. return position >= normalized_selection_start() && position <= normalized_selection_end();
  275. }
  276. VT::Position TerminalWidget::buffer_position_at(const Point& position) const
  277. {
  278. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  279. int row = adjusted_position.y() / m_line_height;
  280. int column = adjusted_position.x() / font().glyph_width('x');
  281. if (row < 0)
  282. row = 0;
  283. if (column < 0)
  284. column = 0;
  285. if (row >= m_terminal.rows())
  286. row = m_terminal.rows() - 1;
  287. if (column >= m_terminal.columns())
  288. column = m_terminal.columns() - 1;
  289. return { row, column };
  290. }
  291. void TerminalWidget::mousedown_event(GMouseEvent& event)
  292. {
  293. if (event.button() == GMouseButton::Left) {
  294. m_selection_start = buffer_position_at(event.position());
  295. m_selection_end = {};
  296. update();
  297. } else if (event.button() == GMouseButton::Right) {
  298. auto text = GClipboard::the().data();
  299. if (text.is_empty())
  300. return;
  301. int nwritten = write(m_ptm_fd, text.characters(), text.length());
  302. if (nwritten < 0) {
  303. perror("write");
  304. ASSERT_NOT_REACHED();
  305. }
  306. }
  307. }
  308. void TerminalWidget::mousemove_event(GMouseEvent& event)
  309. {
  310. if (!(event.buttons() & GMouseButton::Left))
  311. return;
  312. auto old_selection_end = m_selection_end;
  313. m_selection_end = buffer_position_at(event.position());
  314. if (old_selection_end != m_selection_end)
  315. update();
  316. }
  317. void TerminalWidget::mouseup_event(GMouseEvent& event)
  318. {
  319. if (event.button() != GMouseButton::Left)
  320. return;
  321. if (!has_selection())
  322. return;
  323. GClipboard::the().set_data(selected_text());
  324. }
  325. String TerminalWidget::selected_text() const
  326. {
  327. StringBuilder builder;
  328. auto start = normalized_selection_start();
  329. auto end = normalized_selection_end();
  330. for (int row = start.row(); row <= end.row(); ++row) {
  331. int first_column = row == start.row() ? start.column() : 0;
  332. int last_column = row == end.row() ? end.column() : m_terminal.columns() - 1;
  333. for (int column = first_column; column <= last_column; ++column) {
  334. auto& line = m_terminal.line(row);
  335. if (line.attributes[column].is_untouched()) {
  336. builder.append('\n');
  337. break;
  338. }
  339. builder.append(line.characters[column]);
  340. if (column == line.m_length - 1) {
  341. builder.append('\n');
  342. }
  343. }
  344. }
  345. return builder.to_string();
  346. }
  347. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  348. {
  349. m_pixel_width = (frame_thickness() * 2) + (m_inset * 2) + (columns * font().glyph_width('x'));
  350. m_pixel_height = (frame_thickness() * 2) + (m_inset * 2) + (rows * (font().glyph_height() + m_line_spacing)) - m_line_spacing;
  351. set_size_policy(SizePolicy::Fixed, SizePolicy::Fixed);
  352. set_preferred_size(m_pixel_width, m_pixel_height);
  353. m_needs_background_fill = true;
  354. force_repaint();
  355. winsize ws;
  356. ws.ws_row = rows;
  357. ws.ws_col = columns;
  358. int rc = ioctl(m_ptm_fd, TIOCSWINSZ, &ws);
  359. ASSERT(rc == 0);
  360. }
  361. void TerminalWidget::beep()
  362. {
  363. if (m_should_beep) {
  364. sysbeep();
  365. return;
  366. }
  367. m_visual_beep_timer.restart(200);
  368. m_visual_beep_timer.set_single_shot(true);
  369. m_visual_beep_timer.on_timeout = [this] {
  370. force_repaint();
  371. };
  372. force_repaint();
  373. }