TerminalWidget.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. /*
  2. * Copyright (c) 2018-2021, 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 <AK/LexicalPath.h>
  28. #include <AK/StdLibExtras.h>
  29. #include <AK/String.h>
  30. #include <AK/StringBuilder.h>
  31. #include <AK/TemporaryChange.h>
  32. #include <AK/Utf32View.h>
  33. #include <AK/Utf8View.h>
  34. #include <LibCore/ConfigFile.h>
  35. #include <LibCore/MimeData.h>
  36. #include <LibDesktop/AppFile.h>
  37. #include <LibDesktop/Launcher.h>
  38. #include <LibGUI/Action.h>
  39. #include <LibGUI/Application.h>
  40. #include <LibGUI/Clipboard.h>
  41. #include <LibGUI/DragOperation.h>
  42. #include <LibGUI/Icon.h>
  43. #include <LibGUI/Menu.h>
  44. #include <LibGUI/Painter.h>
  45. #include <LibGUI/ScrollBar.h>
  46. #include <LibGUI/Window.h>
  47. #include <LibGfx/Font.h>
  48. #include <LibGfx/FontDatabase.h>
  49. #include <LibGfx/Palette.h>
  50. #include <LibGfx/StylePainter.h>
  51. #include <ctype.h>
  52. #include <errno.h>
  53. #include <math.h>
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <sys/ioctl.h>
  58. #include <unistd.h>
  59. namespace VT {
  60. void TerminalWidget::set_pty_master_fd(int fd)
  61. {
  62. m_ptm_fd = fd;
  63. if (m_ptm_fd == -1) {
  64. m_notifier = nullptr;
  65. return;
  66. }
  67. m_notifier = Core::Notifier::construct(m_ptm_fd, Core::Notifier::Read);
  68. m_notifier->on_ready_to_read = [this] {
  69. u8 buffer[BUFSIZ];
  70. ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
  71. if (nread < 0) {
  72. dbgln("Terminal read error: {}", strerror(errno));
  73. perror("read(ptm)");
  74. GUI::Application::the()->quit(1);
  75. return;
  76. }
  77. if (nread == 0) {
  78. dbgln("TerminalWidget: EOF on master pty, firing on_command_exit hook.");
  79. if (on_command_exit)
  80. on_command_exit();
  81. int rc = close(m_ptm_fd);
  82. if (rc < 0) {
  83. perror("close");
  84. }
  85. set_pty_master_fd(-1);
  86. return;
  87. }
  88. for (ssize_t i = 0; i < nread; ++i)
  89. m_terminal.on_input(buffer[i]);
  90. flush_dirty_lines();
  91. };
  92. }
  93. TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Core::ConfigFile> config)
  94. : m_terminal(*this)
  95. , m_automatic_size_policy(automatic_size_policy)
  96. , m_config(move(config))
  97. {
  98. set_override_cursor(Gfx::StandardCursor::IBeam);
  99. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  100. set_accepts_emoji_input(true);
  101. set_pty_master_fd(ptm_fd);
  102. m_cursor_blink_timer = add<Core::Timer>();
  103. m_visual_beep_timer = add<Core::Timer>();
  104. m_auto_scroll_timer = add<Core::Timer>();
  105. m_scrollbar = add<GUI::ScrollBar>(Orientation::Vertical);
  106. m_scrollbar->set_relative_rect(0, 0, 16, 0);
  107. m_scrollbar->on_change = [this](int) {
  108. update();
  109. };
  110. dbgln("Load config file from {}", m_config->file_name());
  111. m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
  112. "CursorBlinkInterval",
  113. 500));
  114. m_cursor_blink_timer->on_timeout = [this] {
  115. m_cursor_blink_state = !m_cursor_blink_state;
  116. update_cursor();
  117. };
  118. m_auto_scroll_timer->set_interval(50);
  119. m_auto_scroll_timer->on_timeout = [this] {
  120. if (m_auto_scroll_direction != AutoScrollDirection::None) {
  121. int scroll_amount = m_auto_scroll_direction == AutoScrollDirection::Up ? -1 : 1;
  122. m_scrollbar->set_value(m_scrollbar->value() + scroll_amount);
  123. }
  124. };
  125. m_auto_scroll_timer->start();
  126. auto font_entry = m_config->read_entry("Text", "Font", "default");
  127. if (font_entry == "default")
  128. set_font(Gfx::FontDatabase::default_fixed_width_font());
  129. else
  130. set_font(Gfx::FontDatabase::the().get_by_name(font_entry));
  131. m_line_height = font().glyph_height() + m_line_spacing;
  132. m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
  133. m_copy_action = GUI::Action::create("Copy", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [this](auto&) {
  134. copy();
  135. });
  136. m_copy_action->set_swallow_key_event_when_disabled(true);
  137. m_paste_action = GUI::Action::create("Paste", { Mod_Ctrl | Mod_Shift, Key_V }, Gfx::Bitmap::load_from_file("/res/icons/16x16/paste.png"), [this](auto&) {
  138. paste();
  139. });
  140. m_paste_action->set_swallow_key_event_when_disabled(true);
  141. m_clear_including_history_action = GUI::Action::create("Clear including history", { Mod_Ctrl | Mod_Shift, Key_K }, [this](auto&) {
  142. clear_including_history();
  143. });
  144. m_context_menu = GUI::Menu::construct();
  145. m_context_menu->add_action(copy_action());
  146. m_context_menu->add_action(paste_action());
  147. m_context_menu->add_separator();
  148. m_context_menu->add_action(clear_including_history_action());
  149. GUI::Clipboard::the().on_change = [this](const String&) {
  150. update_paste_action();
  151. };
  152. update_copy_action();
  153. update_paste_action();
  154. }
  155. TerminalWidget::~TerminalWidget()
  156. {
  157. }
  158. static inline Color color_from_rgb(unsigned color)
  159. {
  160. return Color::from_rgb(color);
  161. }
  162. Gfx::IntRect TerminalWidget::glyph_rect(u16 row, u16 column)
  163. {
  164. int y = row * m_line_height;
  165. int x = column * font().glyph_width('x');
  166. return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
  167. }
  168. Gfx::IntRect TerminalWidget::row_rect(u16 row)
  169. {
  170. int y = row * m_line_height;
  171. Gfx::IntRect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
  172. rect.inflate(0, m_line_spacing);
  173. return rect;
  174. }
  175. void TerminalWidget::set_logical_focus(bool focus)
  176. {
  177. m_has_logical_focus = focus;
  178. if (!m_has_logical_focus) {
  179. m_cursor_blink_timer->stop();
  180. } else {
  181. m_cursor_blink_state = true;
  182. m_cursor_blink_timer->start();
  183. }
  184. m_auto_scroll_direction = AutoScrollDirection::None;
  185. invalidate_cursor();
  186. update();
  187. }
  188. void TerminalWidget::focusin_event(GUI::FocusEvent& event)
  189. {
  190. set_logical_focus(true);
  191. return GUI::Frame::focusin_event(event);
  192. }
  193. void TerminalWidget::focusout_event(GUI::FocusEvent& event)
  194. {
  195. set_logical_focus(false);
  196. return GUI::Frame::focusout_event(event);
  197. }
  198. void TerminalWidget::event(Core::Event& event)
  199. {
  200. if (event.type() == GUI::Event::WindowBecameActive)
  201. set_logical_focus(true);
  202. else if (event.type() == GUI::Event::WindowBecameInactive)
  203. set_logical_focus(false);
  204. return GUI::Frame::event(event);
  205. }
  206. void TerminalWidget::keydown_event(GUI::KeyEvent& event)
  207. {
  208. if (m_ptm_fd == -1) {
  209. event.ignore();
  210. return GUI::Frame::keydown_event(event);
  211. }
  212. // Reset timer so cursor doesn't blink while typing.
  213. m_cursor_blink_timer->stop();
  214. m_cursor_blink_state = true;
  215. m_cursor_blink_timer->start();
  216. if (event.key() == KeyCode::Key_PageUp && event.modifiers() == Mod_Shift) {
  217. m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
  218. return;
  219. }
  220. if (event.key() == KeyCode::Key_PageDown && event.modifiers() == Mod_Shift) {
  221. m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
  222. return;
  223. }
  224. if (event.key() == KeyCode::Key_Alt) {
  225. m_alt_key_held = true;
  226. return;
  227. }
  228. // Clear the selection if we type in/behind it.
  229. auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
  230. auto min_selection_row = min(m_selection.start().row(), m_selection.end().row());
  231. auto max_selection_row = max(m_selection.start().row(), m_selection.end().row());
  232. 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) {
  233. m_selection.set_end({});
  234. update_copy_action();
  235. update();
  236. }
  237. m_terminal.handle_key_press(event.key(), event.code_point(), event.modifiers());
  238. if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_LeftShift && event.key() != Key_RightShift && event.key() != Key_Super)
  239. scroll_to_bottom();
  240. }
  241. void TerminalWidget::keyup_event(GUI::KeyEvent& event)
  242. {
  243. switch (event.key()) {
  244. case KeyCode::Key_Alt:
  245. m_alt_key_held = false;
  246. return;
  247. default:
  248. break;
  249. }
  250. }
  251. void TerminalWidget::paint_event(GUI::PaintEvent& event)
  252. {
  253. GUI::Frame::paint_event(event);
  254. GUI::Painter painter(*this);
  255. auto visual_beep_active = m_visual_beep_timer->is_active();
  256. painter.add_clip_rect(event.rect());
  257. Gfx::IntRect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
  258. painter.add_clip_rect(terminal_buffer_rect);
  259. if (visual_beep_active)
  260. painter.clear_rect(frame_inner_rect(), Color::Red);
  261. else
  262. painter.clear_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
  263. invalidate_cursor();
  264. int rows_from_history = 0;
  265. int first_row_from_history = m_terminal.history_size();
  266. int row_with_cursor = m_terminal.cursor_row();
  267. if (m_scrollbar->value() != m_scrollbar->max()) {
  268. rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
  269. first_row_from_history = m_terminal.history_size() - (m_scrollbar->max() - m_scrollbar->value());
  270. row_with_cursor = m_terminal.cursor_row() + rows_from_history;
  271. }
  272. // Pass: Compute the rect(s) of the currently hovered link, if any.
  273. Vector<Gfx::IntRect> hovered_href_rects;
  274. if (!m_hovered_href_id.is_null()) {
  275. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  276. auto& line = m_terminal.line(first_row_from_history + visual_row);
  277. for (size_t column = 0; column < line.length(); ++column) {
  278. if (m_hovered_href_id == line.attribute_at(column).href_id) {
  279. bool merged_with_existing_rect = false;
  280. auto glyph_rect = this->glyph_rect(visual_row, column);
  281. for (auto& rect : hovered_href_rects) {
  282. if (rect.inflated(1, 1).intersects(glyph_rect)) {
  283. rect = rect.united(glyph_rect);
  284. merged_with_existing_rect = true;
  285. break;
  286. }
  287. }
  288. if (!merged_with_existing_rect)
  289. hovered_href_rects.append(glyph_rect);
  290. }
  291. }
  292. }
  293. }
  294. // Pass: Paint background & text decorations.
  295. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  296. auto row_rect = this->row_rect(visual_row);
  297. if (!event.rect().contains(row_rect))
  298. continue;
  299. auto& line = m_terminal.line(first_row_from_history + visual_row);
  300. bool has_only_one_background_color = line.has_only_one_background_color();
  301. if (visual_beep_active)
  302. painter.clear_rect(row_rect, Color::Red);
  303. else if (has_only_one_background_color)
  304. painter.clear_rect(row_rect, color_from_rgb(line.attribute_at(0).effective_background_color()).with_alpha(m_opacity));
  305. for (size_t column = 0; column < line.length(); ++column) {
  306. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  307. && m_has_logical_focus
  308. && visual_row == row_with_cursor
  309. && column == m_terminal.cursor_column();
  310. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  311. auto attribute = line.attribute_at(column);
  312. auto character_rect = glyph_rect(visual_row, column);
  313. auto cell_rect = character_rect.inflated(0, m_line_spacing);
  314. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color());
  315. if ((!visual_beep_active && !has_only_one_background_color) || should_reverse_fill_for_cursor_or_selection)
  316. painter.clear_rect(cell_rect, color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_foreground_color() : attribute.effective_background_color()));
  317. enum class UnderlineStyle {
  318. None,
  319. Dotted,
  320. Solid,
  321. };
  322. auto underline_style = UnderlineStyle::None;
  323. if (attribute.flags & VT::Attribute::Underline) {
  324. // Content has specified underline
  325. underline_style = UnderlineStyle::Solid;
  326. } else if (!attribute.href.is_empty()) {
  327. // We're hovering a hyperlink
  328. if (m_hovered_href_id == attribute.href_id || m_active_href_id == attribute.href_id)
  329. underline_style = UnderlineStyle::Solid;
  330. else
  331. underline_style = UnderlineStyle::Dotted;
  332. }
  333. if (underline_style == UnderlineStyle::Solid) {
  334. if (attribute.href_id == m_active_href_id && m_hovered_href_id == m_active_href_id)
  335. text_color = palette().active_link();
  336. painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), text_color);
  337. } else if (underline_style == UnderlineStyle::Dotted) {
  338. auto dotted_line_color = text_color.darkened(0.6f);
  339. int x1 = cell_rect.bottom_left().x();
  340. int x2 = cell_rect.bottom_right().x();
  341. int y = cell_rect.bottom_left().y();
  342. for (int x = x1; x <= x2; ++x) {
  343. if ((x % 3) == 0)
  344. painter.set_pixel({ x, y }, dotted_line_color);
  345. }
  346. }
  347. }
  348. }
  349. // Paint the hovered link rects, if any.
  350. for (auto rect : hovered_href_rects) {
  351. rect.inflate(6, 6);
  352. painter.fill_rect(rect, palette().base());
  353. painter.draw_rect(rect.inflated(2, 2).intersected(frame_inner_rect()), palette().base_text());
  354. }
  355. // Pass: Paint foreground (text).
  356. for (u16 visual_row = 0; visual_row < m_terminal.rows(); ++visual_row) {
  357. auto row_rect = this->row_rect(visual_row);
  358. if (!event.rect().contains(row_rect))
  359. continue;
  360. auto& line = m_terminal.line(first_row_from_history + visual_row);
  361. for (size_t column = 0; column < line.length(); ++column) {
  362. auto attribute = line.attribute_at(column);
  363. bool should_reverse_fill_for_cursor_or_selection = m_cursor_blink_state
  364. && m_has_logical_focus
  365. && visual_row == row_with_cursor
  366. && column == m_terminal.cursor_column();
  367. should_reverse_fill_for_cursor_or_selection |= selection_contains({ first_row_from_history + visual_row, (int)column });
  368. auto text_color = color_from_rgb(should_reverse_fill_for_cursor_or_selection ? attribute.effective_background_color() : attribute.effective_foreground_color());
  369. u32 code_point = line.code_point(column);
  370. if (code_point == ' ')
  371. continue;
  372. auto character_rect = glyph_rect(visual_row, column);
  373. if (!m_hovered_href_id.is_null() && attribute.href_id == m_hovered_href_id) {
  374. text_color = palette().base_text();
  375. }
  376. painter.draw_glyph_or_emoji(
  377. character_rect.location(),
  378. code_point,
  379. attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
  380. text_color);
  381. }
  382. }
  383. // Draw cursor.
  384. if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
  385. auto& cursor_line = m_terminal.line(first_row_from_history + row_with_cursor);
  386. if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
  387. auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
  388. painter.draw_rect(cell_rect, color_from_rgb(cursor_line.attribute_at(m_terminal.cursor_column()).effective_foreground_color()));
  389. }
  390. }
  391. }
  392. void TerminalWidget::set_window_progress(int value, int max)
  393. {
  394. float float_value = value;
  395. float float_max = max;
  396. float progress = (float_value / float_max) * 100.0f;
  397. window()->set_progress((int)roundf(progress));
  398. }
  399. void TerminalWidget::set_window_title(const StringView& title)
  400. {
  401. if (!Utf8View(title).validate()) {
  402. dbgln("TerminalWidget: Attempted to set window title to invalid UTF-8 string");
  403. return;
  404. }
  405. if (on_title_change)
  406. on_title_change(title);
  407. }
  408. void TerminalWidget::invalidate_cursor()
  409. {
  410. m_terminal.invalidate_cursor();
  411. }
  412. void TerminalWidget::flush_dirty_lines()
  413. {
  414. // FIXME: Update smarter when scrolled
  415. if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
  416. update();
  417. m_terminal.m_need_full_flush = false;
  418. return;
  419. }
  420. Gfx::IntRect rect;
  421. for (int i = 0; i < m_terminal.rows(); ++i) {
  422. if (m_terminal.visible_line(i).is_dirty()) {
  423. rect = rect.united(row_rect(i));
  424. m_terminal.visible_line(i).set_dirty(false);
  425. }
  426. }
  427. update(rect);
  428. }
  429. void TerminalWidget::resize_event(GUI::ResizeEvent& event)
  430. {
  431. relayout(event.size());
  432. }
  433. void TerminalWidget::relayout(const Gfx::IntSize& size)
  434. {
  435. if (!m_scrollbar)
  436. return;
  437. TemporaryChange change(m_in_relayout, true);
  438. auto base_size = compute_base_size();
  439. int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
  440. int new_rows = (size.height() - base_size.height()) / m_line_height;
  441. m_terminal.set_size(new_columns, new_rows);
  442. Gfx::IntRect scrollbar_rect = {
  443. size.width() - m_scrollbar->width() - frame_thickness(),
  444. frame_thickness(),
  445. m_scrollbar->width(),
  446. size.height() - frame_thickness() * 2,
  447. };
  448. m_scrollbar->set_relative_rect(scrollbar_rect);
  449. m_scrollbar->set_page_step(new_rows);
  450. }
  451. Gfx::IntSize TerminalWidget::compute_base_size() const
  452. {
  453. int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
  454. int base_height = frame_thickness() * 2 + m_inset * 2;
  455. return { base_width, base_height };
  456. }
  457. void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
  458. {
  459. window.set_size_increment({ font().glyph_width('x'), m_line_height });
  460. window.set_base_size(compute_base_size());
  461. }
  462. void TerminalWidget::update_cursor()
  463. {
  464. invalidate_cursor();
  465. flush_dirty_lines();
  466. }
  467. void TerminalWidget::set_opacity(u8 new_opacity)
  468. {
  469. if (m_opacity == new_opacity)
  470. return;
  471. window()->set_has_alpha_channel(new_opacity < 255);
  472. m_opacity = new_opacity;
  473. update();
  474. }
  475. bool TerminalWidget::has_selection() const
  476. {
  477. return m_selection.is_valid();
  478. }
  479. void TerminalWidget::set_selection(const VT::Range& selection)
  480. {
  481. m_selection = selection;
  482. update_copy_action();
  483. update();
  484. }
  485. bool TerminalWidget::selection_contains(const VT::Position& position) const
  486. {
  487. if (!has_selection())
  488. return false;
  489. if (m_rectangle_selection) {
  490. auto m_selection_start = m_selection.start();
  491. auto m_selection_end = m_selection.end();
  492. auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
  493. auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
  494. auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
  495. auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
  496. return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
  497. }
  498. auto normalized_selection = m_selection.normalized();
  499. return position >= normalized_selection.start() && position <= normalized_selection.end();
  500. }
  501. VT::Position TerminalWidget::buffer_position_at(const Gfx::IntPoint& position) const
  502. {
  503. auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  504. int row = adjusted_position.y() / m_line_height;
  505. int column = adjusted_position.x() / font().glyph_width('x');
  506. if (row < 0)
  507. row = 0;
  508. if (column < 0)
  509. column = 0;
  510. if (row >= m_terminal.rows())
  511. row = m_terminal.rows() - 1;
  512. if (column >= m_terminal.columns())
  513. column = m_terminal.columns() - 1;
  514. row += m_scrollbar->value();
  515. return { row, column };
  516. }
  517. u32 TerminalWidget::code_point_at(const VT::Position& position) const
  518. {
  519. VERIFY(position.is_valid());
  520. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  521. auto& line = m_terminal.line(position.row());
  522. if (static_cast<size_t>(position.column()) == line.length())
  523. return '\n';
  524. return line.code_point(position.column());
  525. }
  526. VT::Position TerminalWidget::next_position_after(const VT::Position& position, bool should_wrap) const
  527. {
  528. VERIFY(position.is_valid());
  529. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  530. auto& line = m_terminal.line(position.row());
  531. if (static_cast<size_t>(position.column()) == line.length()) {
  532. if (static_cast<size_t>(position.row()) == m_terminal.line_count() - 1) {
  533. if (should_wrap)
  534. return { 0, 0 };
  535. return {};
  536. }
  537. return { position.row() + 1, 0 };
  538. }
  539. return { position.row(), position.column() + 1 };
  540. }
  541. VT::Position TerminalWidget::previous_position_before(const VT::Position& position, bool should_wrap) const
  542. {
  543. VERIFY(position.row() >= 0 && static_cast<size_t>(position.row()) < m_terminal.line_count());
  544. if (position.column() == 0) {
  545. if (position.row() == 0) {
  546. if (should_wrap) {
  547. auto& last_line = m_terminal.line(m_terminal.line_count() - 1);
  548. return { static_cast<int>(m_terminal.line_count() - 1), static_cast<int>(last_line.length()) };
  549. }
  550. return {};
  551. }
  552. auto& prev_line = m_terminal.line(position.row() - 1);
  553. return { position.row() - 1, static_cast<int>(prev_line.length()) };
  554. }
  555. return { position.row(), position.column() - 1 };
  556. }
  557. static u32 to_lowercase_code_point(u32 code_point)
  558. {
  559. // FIXME: this only handles ascii characters, but handling unicode lowercasing seems like a mess
  560. if (code_point < 128)
  561. return tolower(code_point);
  562. return code_point;
  563. }
  564. VT::Range TerminalWidget::find_next(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  565. {
  566. if (needle.is_empty())
  567. return {};
  568. VT::Position position = start.is_valid() ? start : VT::Position(0, 0);
  569. VT::Position original_position = position;
  570. VT::Position start_of_potential_match;
  571. size_t needle_index = 0;
  572. do {
  573. auto ch = code_point_at(position);
  574. // FIXME: This is not the right way to use a Unicode needle!
  575. auto needle_ch = (u32)needle[needle_index];
  576. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  577. if (needle_index == 0)
  578. start_of_potential_match = position;
  579. ++needle_index;
  580. if (needle_index >= needle.length())
  581. return { start_of_potential_match, position };
  582. } else {
  583. if (needle_index > 0)
  584. position = start_of_potential_match;
  585. needle_index = 0;
  586. }
  587. position = next_position_after(position, should_wrap);
  588. } while (position.is_valid() && position != original_position);
  589. return {};
  590. }
  591. VT::Range TerminalWidget::find_previous(const StringView& needle, const VT::Position& start, bool case_sensitivity, bool should_wrap)
  592. {
  593. if (needle.is_empty())
  594. return {};
  595. VT::Position position = start.is_valid() ? start : VT::Position(m_terminal.line_count() - 1, m_terminal.line(m_terminal.line_count() - 1).length() - 1);
  596. VT::Position original_position = position;
  597. VT::Position end_of_potential_match;
  598. size_t needle_index = needle.length() - 1;
  599. do {
  600. auto ch = code_point_at(position);
  601. // FIXME: This is not the right way to use a Unicode needle!
  602. auto needle_ch = (u32)needle[needle_index];
  603. if (case_sensitivity ? ch == needle_ch : to_lowercase_code_point(ch) == to_lowercase_code_point(needle_ch)) {
  604. if (needle_index == needle.length() - 1)
  605. end_of_potential_match = position;
  606. if (needle_index == 0)
  607. return { position, end_of_potential_match };
  608. --needle_index;
  609. } else {
  610. if (needle_index < needle.length() - 1)
  611. position = end_of_potential_match;
  612. needle_index = needle.length() - 1;
  613. }
  614. position = previous_position_before(position, should_wrap);
  615. } while (position.is_valid() && position != original_position);
  616. return {};
  617. }
  618. void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
  619. {
  620. if (event.button() == GUI::MouseButton::Left) {
  621. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  622. if (!attribute.href_id.is_null()) {
  623. dbgln("Open hyperlinked URL: '{}'", attribute.href);
  624. Desktop::Launcher::open(attribute.href);
  625. return;
  626. }
  627. m_triple_click_timer.start();
  628. auto position = buffer_position_at(event.position());
  629. auto& line = m_terminal.line(position.row());
  630. bool want_whitespace = line.code_point(position.column()) == ' ';
  631. int start_column = 0;
  632. int end_column = 0;
  633. for (int column = position.column(); column >= 0 && (line.code_point(column) == ' ') == want_whitespace; --column) {
  634. start_column = column;
  635. }
  636. for (int column = position.column(); column < m_terminal.columns() && (line.code_point(column) == ' ') == want_whitespace; ++column) {
  637. end_column = column;
  638. }
  639. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  640. update_copy_action();
  641. }
  642. GUI::Frame::doubleclick_event(event);
  643. }
  644. void TerminalWidget::paste()
  645. {
  646. if (m_ptm_fd == -1)
  647. return;
  648. auto mime_type = GUI::Clipboard::the().mime_type();
  649. if (!mime_type.starts_with("text/"))
  650. return;
  651. auto text = GUI::Clipboard::the().data();
  652. if (text.is_empty())
  653. return;
  654. int nwritten = write(m_ptm_fd, text.data(), text.size());
  655. if (nwritten < 0) {
  656. perror("write");
  657. VERIFY_NOT_REACHED();
  658. }
  659. }
  660. void TerminalWidget::copy()
  661. {
  662. if (has_selection())
  663. GUI::Clipboard::the().set_plain_text(selected_text());
  664. }
  665. void TerminalWidget::mouseup_event(GUI::MouseEvent& event)
  666. {
  667. if (event.button() == GUI::MouseButton::Left) {
  668. if (!m_active_href_id.is_null()) {
  669. m_active_href = {};
  670. m_active_href_id = {};
  671. update();
  672. }
  673. m_auto_scroll_direction = AutoScrollDirection::None;
  674. }
  675. }
  676. void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
  677. {
  678. if (event.button() == GUI::MouseButton::Left) {
  679. m_left_mousedown_position = event.position();
  680. auto attribute = m_terminal.attribute_at(buffer_position_at(event.position()));
  681. if (!(event.modifiers() & Mod_Shift) && !attribute.href.is_empty()) {
  682. m_active_href = attribute.href;
  683. m_active_href_id = attribute.href_id;
  684. update();
  685. return;
  686. }
  687. m_active_href = {};
  688. m_active_href_id = {};
  689. if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
  690. int start_column = 0;
  691. int end_column = m_terminal.columns() - 1;
  692. auto position = buffer_position_at(event.position());
  693. m_selection.set({ position.row(), start_column }, { position.row(), end_column });
  694. } else {
  695. m_selection.set(buffer_position_at(event.position()), {});
  696. }
  697. if (m_alt_key_held)
  698. m_rectangle_selection = true;
  699. else if (m_rectangle_selection)
  700. m_rectangle_selection = false;
  701. update_copy_action();
  702. update();
  703. }
  704. }
  705. void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
  706. {
  707. auto position = buffer_position_at(event.position());
  708. auto attribute = m_terminal.attribute_at(position);
  709. if (attribute.href_id != m_hovered_href_id) {
  710. if (m_active_href_id.is_null() || m_active_href_id == attribute.href_id) {
  711. m_hovered_href_id = attribute.href_id;
  712. m_hovered_href = attribute.href;
  713. } else {
  714. m_hovered_href_id = {};
  715. m_hovered_href = {};
  716. }
  717. set_tooltip(m_hovered_href);
  718. show_or_hide_tooltip();
  719. if (!m_hovered_href.is_empty())
  720. set_override_cursor(Gfx::StandardCursor::Arrow);
  721. else
  722. set_override_cursor(Gfx::StandardCursor::IBeam);
  723. update();
  724. }
  725. if (!(event.buttons() & GUI::MouseButton::Left))
  726. return;
  727. if (!m_active_href_id.is_null()) {
  728. auto diff = event.position() - m_left_mousedown_position;
  729. auto distance_travelled_squared = diff.x() * diff.x() + diff.y() * diff.y();
  730. constexpr int drag_distance_threshold = 5;
  731. if (distance_travelled_squared <= drag_distance_threshold)
  732. return;
  733. auto drag_operation = GUI::DragOperation::construct();
  734. drag_operation->set_text(m_active_href);
  735. drag_operation->set_data("text/uri-list", m_active_href);
  736. drag_operation->exec();
  737. m_active_href = {};
  738. m_active_href_id = {};
  739. m_hovered_href = {};
  740. m_hovered_href_id = {};
  741. update();
  742. return;
  743. }
  744. auto adjusted_position = event.position().translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
  745. if (adjusted_position.y() < 0)
  746. m_auto_scroll_direction = AutoScrollDirection::Up;
  747. else if (adjusted_position.y() > m_terminal.rows() * m_line_height)
  748. m_auto_scroll_direction = AutoScrollDirection::Down;
  749. else
  750. m_auto_scroll_direction = AutoScrollDirection::None;
  751. VT::Position old_selection_end = m_selection.end();
  752. m_selection.set_end(position);
  753. if (old_selection_end != m_selection.end()) {
  754. update_copy_action();
  755. update();
  756. }
  757. }
  758. void TerminalWidget::leave_event(Core::Event&)
  759. {
  760. bool should_update = !m_hovered_href.is_empty();
  761. m_hovered_href = {};
  762. m_hovered_href_id = {};
  763. set_tooltip(m_hovered_href);
  764. set_override_cursor(Gfx::StandardCursor::IBeam);
  765. if (should_update)
  766. update();
  767. }
  768. void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
  769. {
  770. if (!is_scrollable())
  771. return;
  772. m_auto_scroll_direction = AutoScrollDirection::None;
  773. m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta() * scroll_length());
  774. GUI::Frame::mousewheel_event(event);
  775. }
  776. bool TerminalWidget::is_scrollable() const
  777. {
  778. return m_scrollbar->is_scrollable();
  779. }
  780. int TerminalWidget::scroll_length() const
  781. {
  782. return m_scrollbar->step();
  783. }
  784. String TerminalWidget::selected_text() const
  785. {
  786. StringBuilder builder;
  787. auto normalized_selection = m_selection.normalized();
  788. auto start = normalized_selection.start();
  789. auto end = normalized_selection.end();
  790. for (int row = start.row(); row <= end.row(); ++row) {
  791. int first_column = first_selection_column_on_row(row);
  792. int last_column = last_selection_column_on_row(row);
  793. for (int column = first_column; column <= last_column; ++column) {
  794. auto& line = m_terminal.line(row);
  795. if (line.attribute_at(column).is_untouched()) {
  796. builder.append('\n');
  797. break;
  798. }
  799. // FIXME: This is a bit hackish.
  800. u32 code_point = line.code_point(column);
  801. builder.append(Utf32View(&code_point, 1));
  802. if (column == static_cast<int>(line.length()) - 1 || (m_rectangle_selection && column == last_column)) {
  803. builder.append('\n');
  804. }
  805. }
  806. }
  807. return builder.to_string();
  808. }
  809. int TerminalWidget::first_selection_column_on_row(int row) const
  810. {
  811. auto normalized_selection_start = m_selection.normalized().start();
  812. return row == normalized_selection_start.row() || m_rectangle_selection ? normalized_selection_start.column() : 0;
  813. }
  814. int TerminalWidget::last_selection_column_on_row(int row) const
  815. {
  816. auto normalized_selection_end = m_selection.normalized().end();
  817. return row == normalized_selection_end.row() || m_rectangle_selection ? normalized_selection_end.column() : m_terminal.columns() - 1;
  818. }
  819. void TerminalWidget::terminal_history_changed()
  820. {
  821. bool was_max = m_scrollbar->value() == m_scrollbar->max();
  822. m_scrollbar->set_max(m_terminal.history_size());
  823. if (was_max)
  824. m_scrollbar->set_value(m_scrollbar->max());
  825. m_scrollbar->update();
  826. }
  827. void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
  828. {
  829. auto pixel_size = widget_size_for_font(font());
  830. m_pixel_width = pixel_size.width();
  831. m_pixel_height = pixel_size.height();
  832. if (!m_in_relayout) {
  833. if (on_terminal_size_change)
  834. on_terminal_size_change(Gfx::IntSize { m_pixel_width, m_pixel_height });
  835. }
  836. if (m_automatic_size_policy) {
  837. set_fixed_size(m_pixel_width, m_pixel_height);
  838. }
  839. update();
  840. winsize ws;
  841. ws.ws_row = rows;
  842. ws.ws_col = columns;
  843. if (m_ptm_fd != -1) {
  844. if (ioctl(m_ptm_fd, TIOCSWINSZ, &ws) < 0) {
  845. // This can happen if we resize just as the shell exits.
  846. dbgln("Notifying the pseudo-terminal about a size change failed.");
  847. }
  848. }
  849. }
  850. void TerminalWidget::beep()
  851. {
  852. if (m_bell_mode == BellMode::Disabled) {
  853. return;
  854. }
  855. if (m_bell_mode == BellMode::AudibleBeep) {
  856. sysbeep();
  857. return;
  858. }
  859. m_visual_beep_timer->restart(200);
  860. m_visual_beep_timer->set_single_shot(true);
  861. m_visual_beep_timer->on_timeout = [this] {
  862. update();
  863. };
  864. update();
  865. }
  866. void TerminalWidget::emit(const u8* data, size_t size)
  867. {
  868. if (write(m_ptm_fd, data, size) < 0) {
  869. perror("TerminalWidget::emit: write");
  870. }
  871. }
  872. void TerminalWidget::context_menu_event(GUI::ContextMenuEvent& event)
  873. {
  874. if (m_hovered_href_id.is_null()) {
  875. m_context_menu->popup(event.screen_position());
  876. } else {
  877. m_context_menu_href = m_hovered_href;
  878. // Ask LaunchServer for a list of programs that can handle the right-clicked URL.
  879. auto handlers = Desktop::Launcher::get_handlers_for_url(m_hovered_href);
  880. if (handlers.is_empty()) {
  881. m_context_menu->popup(event.screen_position());
  882. return;
  883. }
  884. m_context_menu_for_hyperlink = GUI::Menu::construct();
  885. RefPtr<GUI::Action> context_menu_default_action;
  886. // Go through the list of handlers and see if we can find a nice display name + icon for them.
  887. // Then add them to the context menu.
  888. // FIXME: Adapt this code when we actually support calling LaunchServer with a specific handler in mind.
  889. for (auto& handler : handlers) {
  890. auto af = Desktop::AppFile::get_for_app(LexicalPath(handler).basename());
  891. if (!af->is_valid())
  892. continue;
  893. auto action = GUI::Action::create(String::formatted("Open in {}", af->name()), af->icon().bitmap_for_size(16), [this, handler](auto&) {
  894. Desktop::Launcher::open(m_context_menu_href, handler);
  895. });
  896. if (context_menu_default_action.is_null()) {
  897. context_menu_default_action = action;
  898. }
  899. m_context_menu_for_hyperlink->add_action(action);
  900. }
  901. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy URL", [this](auto&) {
  902. GUI::Clipboard::the().set_plain_text(m_context_menu_href);
  903. }));
  904. m_context_menu_for_hyperlink->add_action(GUI::Action::create("Copy name", [&](auto&) {
  905. // file://courage/home/anon/something -> /home/anon/something
  906. auto path = URL(m_context_menu_href).path();
  907. // /home/anon/something -> something
  908. auto name = LexicalPath(path).basename();
  909. GUI::Clipboard::the().set_plain_text(name);
  910. }));
  911. m_context_menu_for_hyperlink->add_separator();
  912. m_context_menu_for_hyperlink->add_action(copy_action());
  913. m_context_menu_for_hyperlink->add_action(paste_action());
  914. m_context_menu_for_hyperlink->popup(event.screen_position(), context_menu_default_action);
  915. }
  916. }
  917. void TerminalWidget::drop_event(GUI::DropEvent& event)
  918. {
  919. if (event.mime_data().has_text()) {
  920. event.accept();
  921. auto text = event.mime_data().text();
  922. write(m_ptm_fd, text.characters(), text.length());
  923. } else if (event.mime_data().has_urls()) {
  924. event.accept();
  925. auto urls = event.mime_data().urls();
  926. bool first = true;
  927. for (auto& url : event.mime_data().urls()) {
  928. if (!first) {
  929. write(m_ptm_fd, " ", 1);
  930. first = false;
  931. }
  932. if (url.protocol() == "file")
  933. write(m_ptm_fd, url.path().characters(), url.path().length());
  934. else
  935. write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
  936. }
  937. }
  938. }
  939. void TerminalWidget::did_change_font()
  940. {
  941. GUI::Frame::did_change_font();
  942. m_line_height = font().glyph_height() + m_line_spacing;
  943. // TODO: try to find a bold version of the new font (e.g. CsillaThin7x10 -> CsillaBold7x10)
  944. const Gfx::Font& bold_font = Gfx::FontDatabase::default_bold_fixed_width_font();
  945. if (bold_font.glyph_height() == font().glyph_height() && bold_font.glyph_width(' ') == font().glyph_width(' '))
  946. m_bold_font = &bold_font;
  947. else
  948. m_bold_font = font();
  949. if (!size().is_empty())
  950. relayout(size());
  951. }
  952. void TerminalWidget::clear_including_history()
  953. {
  954. m_terminal.clear_including_history();
  955. }
  956. void TerminalWidget::scroll_to_bottom()
  957. {
  958. m_scrollbar->set_value(m_scrollbar->max());
  959. }
  960. void TerminalWidget::scroll_to_row(int row)
  961. {
  962. m_scrollbar->set_value(row);
  963. }
  964. void TerminalWidget::update_copy_action()
  965. {
  966. m_copy_action->set_enabled(has_selection());
  967. }
  968. void TerminalWidget::update_paste_action()
  969. {
  970. m_paste_action->set_enabled(GUI::Clipboard::the().mime_type().starts_with("text/") && !GUI::Clipboard::the().data().is_empty());
  971. }
  972. Gfx::IntSize TerminalWidget::widget_size_for_font(const Gfx::Font& font) const
  973. {
  974. return {
  975. (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.columns() * font.glyph_width('x')) + m_scrollbar->width(),
  976. (frame_thickness() * 2) + (m_inset * 2) + (m_terminal.rows() * (font.glyph_height() + m_line_spacing))
  977. };
  978. }
  979. void TerminalWidget::set_font_and_resize_to_fit(const Gfx::Font& font)
  980. {
  981. set_font(font);
  982. resize(widget_size_for_font(font));
  983. }
  984. }