Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, 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
27#include "TerminalWidget.h"
28#include "XtermColors.h"
29#include <AK/StdLibExtras.h>
30#include <AK/String.h>
31#include <AK/StringBuilder.h>
32#include <AK/Utf8View.h>
33#include <Kernel/KeyCode.h>
34#include <LibCore/MimeData.h>
35#include <LibGUI/Action.h>
36#include <LibGUI/Application.h>
37#include <LibGUI/Clipboard.h>
38#include <LibGUI/Menu.h>
39#include <LibGUI/Painter.h>
40#include <LibGUI/ScrollBar.h>
41#include <LibGUI/Window.h>
42#include <LibGfx/Font.h>
43#include <errno.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <sys/ioctl.h>
48#include <unistd.h>
49
50//#define TERMINAL_DEBUG
51
52void TerminalWidget::set_pty_master_fd(int fd)
53{
54 m_ptm_fd = fd;
55 if (m_ptm_fd == -1) {
56 m_notifier = nullptr;
57 return;
58 }
59 m_notifier = Core::Notifier::construct(m_ptm_fd, Core::Notifier::Read);
60 m_notifier->on_ready_to_read = [this] {
61 u8 buffer[BUFSIZ];
62 ssize_t nread = read(m_ptm_fd, buffer, sizeof(buffer));
63 if (nread < 0) {
64 dbgprintf("Terminal read error: %s\n", strerror(errno));
65 perror("read(ptm)");
66 GUI::Application::the().quit(1);
67 return;
68 }
69 if (nread == 0) {
70 dbgprintf("Terminal: EOF on master pty, firing on_command_exit hook.\n");
71 if (on_command_exit)
72 on_command_exit();
73 int rc = close(m_ptm_fd);
74 if (rc < 0) {
75 perror("close");
76 }
77 set_pty_master_fd(-1);
78 return;
79 }
80 for (ssize_t i = 0; i < nread; ++i)
81 m_terminal.on_char(buffer[i]);
82 flush_dirty_lines();
83 };
84}
85
86TerminalWidget::TerminalWidget(int ptm_fd, bool automatic_size_policy, RefPtr<Core::ConfigFile> config)
87 : m_terminal(*this)
88 , m_automatic_size_policy(automatic_size_policy)
89 , m_config(move(config))
90{
91 set_pty_master_fd(ptm_fd);
92 m_cursor_blink_timer = add<Core::Timer>();
93 m_visual_beep_timer = add<Core::Timer>();
94
95 m_scrollbar = add<GUI::ScrollBar>(Orientation::Vertical);
96 m_scrollbar->set_relative_rect(0, 0, 16, 0);
97 m_scrollbar->on_change = [this](int) {
98 force_repaint();
99 };
100
101 dbgprintf("Terminal: Load config file from %s\n", m_config->file_name().characters());
102 m_cursor_blink_timer->set_interval(m_config->read_num_entry("Text",
103 "CursorBlinkInterval",
104 500));
105 m_cursor_blink_timer->on_timeout = [this] {
106 m_cursor_blink_state = !m_cursor_blink_state;
107 update_cursor();
108 };
109
110 auto font_entry = m_config->read_entry("Text", "Font", "default");
111 if (font_entry == "default")
112 set_font(Gfx::Font::default_fixed_width_font());
113 else
114 set_font(Gfx::Font::load_from_file(font_entry));
115
116 m_line_height = font().glyph_height() + m_line_spacing;
117
118 m_terminal.set_size(m_config->read_num_entry("Window", "Width", 80), m_config->read_num_entry("Window", "Height", 25));
119
120 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&) {
121 copy();
122 });
123
124 m_paste_action = GUI::Action::create("Paste", { Mod_Ctrl | Mod_Shift, Key_V }, Gfx::Bitmap::load_from_file("/res/icons/paste16.png"), [this](auto&) {
125 paste();
126 });
127}
128
129TerminalWidget::~TerminalWidget()
130{
131}
132
133static inline Color lookup_color(unsigned color)
134{
135 return Color::from_rgb(xterm_colors[color]);
136}
137
138Gfx::Rect TerminalWidget::glyph_rect(u16 row, u16 column)
139{
140 int y = row * m_line_height;
141 int x = column * font().glyph_width('x');
142 return { x + frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x'), font().glyph_height() };
143}
144
145Gfx::Rect TerminalWidget::row_rect(u16 row)
146{
147 int y = row * m_line_height;
148 Gfx::Rect rect = { frame_thickness() + m_inset, y + frame_thickness() + m_inset, font().glyph_width('x') * m_terminal.columns(), font().glyph_height() };
149 rect.inflate(0, m_line_spacing);
150 return rect;
151}
152
153void TerminalWidget::set_logical_focus(bool focus)
154{
155 m_has_logical_focus = focus;
156 if (!m_has_logical_focus) {
157 m_cursor_blink_timer->stop();
158 } else {
159 m_cursor_blink_state = true;
160 m_cursor_blink_timer->start();
161 }
162 invalidate_cursor();
163 update();
164}
165
166void TerminalWidget::focusin_event(Core::Event& event)
167{
168 set_logical_focus(true);
169 return GUI::Frame::focusin_event(event);
170}
171
172void TerminalWidget::focusout_event(Core::Event& event)
173{
174 set_logical_focus(false);
175 return GUI::Frame::focusout_event(event);
176}
177
178void TerminalWidget::event(Core::Event& event)
179{
180 if (event.type() == GUI::Event::WindowBecameActive)
181 set_logical_focus(true);
182 else if (event.type() == GUI::Event::WindowBecameInactive)
183 set_logical_focus(false);
184 return GUI::Frame::event(event);
185}
186
187void TerminalWidget::keydown_event(GUI::KeyEvent& event)
188{
189 if (m_ptm_fd == -1) {
190 event.ignore();
191 return GUI::Frame::keydown_event(event);
192 }
193
194 // Reset timer so cursor doesn't blink while typing.
195 m_cursor_blink_timer->stop();
196 m_cursor_blink_state = true;
197 m_cursor_blink_timer->start();
198
199 switch (event.key()) {
200 case KeyCode::Key_Up:
201 write(m_ptm_fd, "\033[A", 3);
202 return;
203 case KeyCode::Key_Down:
204 write(m_ptm_fd, "\033[B", 3);
205 return;
206 case KeyCode::Key_Right:
207 write(m_ptm_fd, "\033[C", 3);
208 return;
209 case KeyCode::Key_Left:
210 write(m_ptm_fd, "\033[D", 3);
211 return;
212 case KeyCode::Key_Insert:
213 write(m_ptm_fd, "\033[2~", 4);
214 return;
215 case KeyCode::Key_Delete:
216 write(m_ptm_fd, "\033[3~", 4);
217 return;
218 case KeyCode::Key_Home:
219 write(m_ptm_fd, "\033[H", 3);
220 return;
221 case KeyCode::Key_End:
222 write(m_ptm_fd, "\033[F", 3);
223 return;
224 case KeyCode::Key_PageUp:
225 if (event.modifiers() == Mod_Shift) {
226 m_scrollbar->set_value(m_scrollbar->value() - m_terminal.rows());
227 return;
228 }
229 write(m_ptm_fd, "\033[5~", 4);
230 return;
231 case KeyCode::Key_PageDown:
232 if (event.modifiers() == Mod_Shift) {
233 m_scrollbar->set_value(m_scrollbar->value() + m_terminal.rows());
234 return;
235 }
236 write(m_ptm_fd, "\033[6~", 4);
237 return;
238 case KeyCode::Key_Alt:
239 m_alt_key_held = true;
240 return;
241 default:
242 break;
243 }
244
245 // Key event was not one of the above special cases,
246 // attempt to treat it as a character...
247 char ch = !event.text().is_empty() ? event.text()[0] : 0;
248 if (ch) {
249 if (event.ctrl()) {
250 if (ch >= 'a' && ch <= 'z') {
251 ch = ch - 'a' + 1;
252 } else if (ch == '\\') {
253 ch = 0x1c;
254 }
255 }
256
257 // ALT modifier sends escape prefix
258 if (event.alt())
259 write(m_ptm_fd, "\033", 1);
260
261 //Clear the selection if we type in/behind it
262 auto future_cursor_column = (event.key() == KeyCode::Key_Backspace) ? m_terminal.cursor_column() - 1 : m_terminal.cursor_column();
263 auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
264 auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
265
266 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) {
267 m_selection_end = {};
268 update();
269 }
270
271 write(m_ptm_fd, &ch, 1);
272 }
273
274 if (event.key() != Key_Control && event.key() != Key_Alt && event.key() != Key_Shift && event.key() != Key_Logo)
275 m_scrollbar->set_value(m_scrollbar->max());
276}
277
278void TerminalWidget::keyup_event(GUI::KeyEvent& event)
279{
280 switch (event.key()) {
281 case KeyCode::Key_Alt:
282 m_alt_key_held = false;
283 return;
284 default:
285 break;
286 }
287}
288
289void TerminalWidget::paint_event(GUI::PaintEvent& event)
290{
291 GUI::Frame::paint_event(event);
292
293 GUI::Painter painter(*this);
294
295 painter.add_clip_rect(event.rect());
296
297 Gfx::Rect terminal_buffer_rect(frame_inner_rect().top_left(), { frame_inner_rect().width() - m_scrollbar->width(), frame_inner_rect().height() });
298 painter.add_clip_rect(terminal_buffer_rect);
299
300 if (m_visual_beep_timer->is_active())
301 painter.clear_rect(frame_inner_rect(), Color::Red);
302 else
303 painter.clear_rect(frame_inner_rect(), Color(Color::Black).with_alpha(m_opacity));
304 invalidate_cursor();
305
306 int rows_from_history = 0;
307 int first_row_from_history = 0;
308 int row_with_cursor = m_terminal.cursor_row();
309 if (m_scrollbar->value() != m_scrollbar->max()) {
310 rows_from_history = min((int)m_terminal.rows(), m_scrollbar->max() - m_scrollbar->value());
311 first_row_from_history = m_terminal.history().size() - (m_scrollbar->max() - m_scrollbar->value());
312 row_with_cursor = m_terminal.cursor_row() + rows_from_history;
313 }
314
315 auto line_for_visual_row = [&](u16 row) -> const VT::Terminal::Line& {
316 if (row < rows_from_history)
317 return m_terminal.history().at(first_row_from_history + row);
318 return m_terminal.line(row - rows_from_history);
319 };
320
321 for (u16 row = 0; row < m_terminal.rows(); ++row) {
322 auto row_rect = this->row_rect(row);
323 if (!event.rect().contains(row_rect))
324 continue;
325 auto& line = line_for_visual_row(row);
326 bool has_only_one_background_color = line.has_only_one_background_color();
327 if (m_visual_beep_timer->is_active())
328 painter.clear_rect(row_rect, Color::Red);
329 else if (has_only_one_background_color)
330 painter.clear_rect(row_rect, lookup_color(line.attributes[0].background_color).with_alpha(m_opacity));
331
332 // The terminal insists on thinking characters and
333 // bytes are the same thing. We want to still draw
334 // emojis in *some* way, but it won't be completely
335 // perfect. So what we do is we make multi-byte
336 // characters take up multiple columns, and render
337 // the character itself in the center of the columns
338 // its bytes take up as far as the terminal is concerned.
339
340 Utf8View utf8_view { line.text() };
341
342 for (auto it = utf8_view.begin(); it != utf8_view.end(); ++it) {
343 u32 codepoint = *it;
344 int this_char_column = utf8_view.byte_offset_of(it);
345 AK::Utf8CodepointIterator it_copy = it;
346 int next_char_column = utf8_view.byte_offset_of(++it_copy);
347
348 // Columns from this_char_column up until next_char_column
349 // are logically taken up by this (possibly multi-byte)
350 // character. Iterate over these columns and draw background
351 // for each one of them separately.
352
353 bool should_reverse_fill_for_cursor_or_selection = false;
354 VT::Attribute attribute;
355
356 for (u16 column = this_char_column; column < next_char_column; ++column) {
357 should_reverse_fill_for_cursor_or_selection |= m_cursor_blink_state
358 && m_has_logical_focus
359 && row == row_with_cursor
360 && column == m_terminal.cursor_column();
361 should_reverse_fill_for_cursor_or_selection |= selection_contains({ row, column });
362 attribute = line.attributes[column];
363 auto character_rect = glyph_rect(row, column);
364 auto cell_rect = character_rect.inflated(0, m_line_spacing);
365 if (!has_only_one_background_color || should_reverse_fill_for_cursor_or_selection) {
366 painter.clear_rect(cell_rect, lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.foreground_color : attribute.background_color).with_alpha(m_opacity));
367 }
368 if (attribute.flags & VT::Attribute::Underline)
369 painter.draw_line(cell_rect.bottom_left(), cell_rect.bottom_right(), lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color));
370 }
371
372 if (codepoint == ' ')
373 continue;
374
375 auto character_rect = glyph_rect(row, this_char_column);
376 auto num_columns = next_char_column - this_char_column;
377 character_rect.move_by((num_columns - 1) * font().glyph_width('x') / 2, 0);
378 painter.draw_glyph_or_emoji(
379 character_rect.location(),
380 codepoint,
381 attribute.flags & VT::Attribute::Bold ? bold_font() : font(),
382 lookup_color(should_reverse_fill_for_cursor_or_selection ? attribute.background_color : attribute.foreground_color));
383 }
384 }
385
386 if (!m_has_logical_focus && row_with_cursor < m_terminal.rows()) {
387 auto& cursor_line = line_for_visual_row(row_with_cursor);
388 if (m_terminal.cursor_row() < (m_terminal.rows() - rows_from_history)) {
389 auto cell_rect = glyph_rect(row_with_cursor, m_terminal.cursor_column()).inflated(0, m_line_spacing);
390 painter.draw_rect(cell_rect, lookup_color(cursor_line.attributes[m_terminal.cursor_column()].foreground_color));
391 }
392 }
393}
394
395void TerminalWidget::set_window_title(const StringView& title)
396{
397 if (on_title_change)
398 on_title_change(title);
399}
400
401void TerminalWidget::invalidate_cursor()
402{
403 m_terminal.invalidate_cursor();
404}
405
406void TerminalWidget::flush_dirty_lines()
407{
408 // FIXME: Update smarter when scrolled
409 if (m_terminal.m_need_full_flush || m_scrollbar->value() != m_scrollbar->max()) {
410 update();
411 m_terminal.m_need_full_flush = false;
412 return;
413 }
414 Gfx::Rect rect;
415 for (int i = 0; i < m_terminal.rows(); ++i) {
416 if (m_terminal.line(i).dirty) {
417 rect = rect.united(row_rect(i));
418 m_terminal.line(i).dirty = false;
419 }
420 }
421 update(rect);
422}
423
424void TerminalWidget::force_repaint()
425{
426 m_needs_background_fill = true;
427 update();
428}
429
430void TerminalWidget::resize_event(GUI::ResizeEvent& event)
431{
432 relayout(event.size());
433}
434
435void TerminalWidget::relayout(const Gfx::Size& size)
436{
437 if (!m_scrollbar)
438 return;
439
440 auto base_size = compute_base_size();
441 int new_columns = (size.width() - base_size.width()) / font().glyph_width('x');
442 int new_rows = (size.height() - base_size.height()) / m_line_height;
443 m_terminal.set_size(new_columns, new_rows);
444
445 Gfx::Rect scrollbar_rect = {
446 size.width() - m_scrollbar->width() - frame_thickness(),
447 frame_thickness(),
448 m_scrollbar->width(),
449 size.height() - frame_thickness() * 2,
450 };
451 m_scrollbar->set_relative_rect(scrollbar_rect);
452}
453
454Gfx::Size TerminalWidget::compute_base_size() const
455{
456 int base_width = frame_thickness() * 2 + m_inset * 2 + m_scrollbar->width();
457 int base_height = frame_thickness() * 2 + m_inset * 2;
458 return { base_width, base_height };
459}
460
461void TerminalWidget::apply_size_increments_to_window(GUI::Window& window)
462{
463 window.set_size_increment({ font().glyph_width('x'), m_line_height });
464 window.set_base_size(compute_base_size());
465}
466
467void TerminalWidget::update_cursor()
468{
469 invalidate_cursor();
470 flush_dirty_lines();
471}
472
473void TerminalWidget::set_opacity(u8 new_opacity)
474{
475 if (m_opacity == new_opacity)
476 return;
477
478 window()->set_has_alpha_channel(new_opacity < 255);
479 m_opacity = new_opacity;
480 force_repaint();
481}
482
483VT::Position TerminalWidget::normalized_selection_start() const
484{
485 if (m_selection_start < m_selection_end)
486 return m_selection_start;
487 return m_selection_end;
488}
489
490VT::Position TerminalWidget::normalized_selection_end() const
491{
492 if (m_selection_start < m_selection_end)
493 return m_selection_end;
494 return m_selection_start;
495}
496
497bool TerminalWidget::has_selection() const
498{
499 return m_selection_start.is_valid() && m_selection_end.is_valid();
500}
501
502bool TerminalWidget::selection_contains(const VT::Position& position) const
503{
504 if (!has_selection())
505 return false;
506
507 if (m_rectangle_selection) {
508 auto min_selection_column = min(m_selection_start.column(), m_selection_end.column());
509 auto max_selection_column = max(m_selection_start.column(), m_selection_end.column());
510 auto min_selection_row = min(m_selection_start.row(), m_selection_end.row());
511 auto max_selection_row = max(m_selection_start.row(), m_selection_end.row());
512
513 return position.column() >= min_selection_column && position.column() <= max_selection_column && position.row() >= min_selection_row && position.row() <= max_selection_row;
514 }
515
516 return position >= normalized_selection_start() && position <= normalized_selection_end();
517}
518
519VT::Position TerminalWidget::buffer_position_at(const Gfx::Point& position) const
520{
521 auto adjusted_position = position.translated(-(frame_thickness() + m_inset), -(frame_thickness() + m_inset));
522 int row = adjusted_position.y() / m_line_height;
523 int column = adjusted_position.x() / font().glyph_width('x');
524 if (row < 0)
525 row = 0;
526 if (column < 0)
527 column = 0;
528 if (row >= m_terminal.rows())
529 row = m_terminal.rows() - 1;
530 if (column >= m_terminal.columns())
531 column = m_terminal.columns() - 1;
532 return { row, column };
533}
534
535void TerminalWidget::doubleclick_event(GUI::MouseEvent& event)
536{
537 if (event.button() == GUI::MouseButton::Left) {
538 m_triple_click_timer.start();
539
540 auto position = buffer_position_at(event.position());
541 auto& line = m_terminal.line(position.row());
542 bool want_whitespace = line.characters[position.column()] == ' ';
543
544 int start_column = 0;
545 int end_column = 0;
546
547 for (int column = position.column(); column >= 0 && (line.characters[column] == ' ') == want_whitespace; --column) {
548 start_column = column;
549 }
550
551 for (int column = position.column(); column < m_terminal.columns() && (line.characters[column] == ' ') == want_whitespace; ++column) {
552 end_column = column;
553 }
554
555 m_selection_start = { position.row(), start_column };
556 m_selection_end = { position.row(), end_column };
557 }
558 GUI::Frame::doubleclick_event(event);
559}
560
561void TerminalWidget::paste()
562{
563 if (m_ptm_fd == -1)
564 return;
565 auto text = GUI::Clipboard::the().data();
566 if (text.is_empty())
567 return;
568 int nwritten = write(m_ptm_fd, text.characters(), text.length());
569 if (nwritten < 0) {
570 perror("write");
571 ASSERT_NOT_REACHED();
572 }
573}
574
575void TerminalWidget::copy()
576{
577 if (has_selection())
578 GUI::Clipboard::the().set_data(selected_text());
579}
580
581void TerminalWidget::mousedown_event(GUI::MouseEvent& event)
582{
583 if (event.button() == GUI::MouseButton::Left) {
584 if (m_triple_click_timer.is_valid() && m_triple_click_timer.elapsed() < 250) {
585 int start_column = 0;
586 int end_column = m_terminal.columns() - 1;
587
588 auto position = buffer_position_at(event.position());
589 m_selection_start = { position.row(), start_column };
590 m_selection_end = { position.row(), end_column };
591 } else {
592 m_selection_start = buffer_position_at(event.position());
593 m_selection_end = {};
594 }
595 if (m_alt_key_held)
596 m_rectangle_selection = true;
597 else if (m_rectangle_selection)
598 m_rectangle_selection = false;
599
600 update();
601 }
602}
603
604void TerminalWidget::mousemove_event(GUI::MouseEvent& event)
605{
606 if (!(event.buttons() & GUI::MouseButton::Left))
607 return;
608
609 auto old_selection_end = m_selection_end;
610 m_selection_end = buffer_position_at(event.position());
611 if (old_selection_end != m_selection_end)
612 update();
613}
614
615void TerminalWidget::mousewheel_event(GUI::MouseEvent& event)
616{
617 if (!is_scrollable())
618 return;
619 m_scrollbar->set_value(m_scrollbar->value() + event.wheel_delta());
620 GUI::Frame::mousewheel_event(event);
621}
622
623bool TerminalWidget::is_scrollable() const
624{
625 return m_scrollbar->is_scrollable();
626}
627
628String TerminalWidget::selected_text() const
629{
630 StringBuilder builder;
631 auto start = normalized_selection_start();
632 auto end = normalized_selection_end();
633
634 for (int row = start.row(); row <= end.row(); ++row) {
635 int first_column = first_selection_column_on_row(row);
636 int last_column = last_selection_column_on_row(row);
637 for (int column = first_column; column <= last_column; ++column) {
638 auto& line = m_terminal.line(row);
639 if (line.attributes[column].is_untouched()) {
640 builder.append('\n');
641 break;
642 }
643 builder.append(line.characters[column]);
644 if (column == line.m_length - 1 || (m_rectangle_selection && column == last_column)) {
645 builder.append('\n');
646 }
647 }
648 }
649
650 return builder.to_string();
651}
652
653int TerminalWidget::first_selection_column_on_row(int row) const
654{
655 return row == normalized_selection_start().row() || m_rectangle_selection ? normalized_selection_start().column() : 0;
656}
657
658int TerminalWidget::last_selection_column_on_row(int row) const
659{
660 return row == normalized_selection_end().row() || m_rectangle_selection ? normalized_selection_end().column() : m_terminal.columns() - 1;
661}
662
663void TerminalWidget::terminal_history_changed()
664{
665 bool was_max = m_scrollbar->value() == m_scrollbar->max();
666 m_scrollbar->set_max(m_terminal.history().size());
667 if (was_max)
668 m_scrollbar->set_value(m_scrollbar->max());
669 m_scrollbar->update();
670}
671
672void TerminalWidget::terminal_did_resize(u16 columns, u16 rows)
673{
674 m_pixel_width = (frame_thickness() * 2) + (m_inset * 2) + (columns * font().glyph_width('x')) + m_scrollbar->width();
675 m_pixel_height = (frame_thickness() * 2) + (m_inset * 2) + (rows * (font().glyph_height() + m_line_spacing));
676
677 if (m_automatic_size_policy) {
678 set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fixed);
679 set_preferred_size(m_pixel_width, m_pixel_height);
680 }
681
682 m_needs_background_fill = true;
683 force_repaint();
684
685 winsize ws;
686 ws.ws_row = rows;
687 ws.ws_col = columns;
688 if (m_ptm_fd != -1) {
689 int rc = ioctl(m_ptm_fd, TIOCSWINSZ, &ws);
690 ASSERT(rc == 0);
691 }
692}
693
694void TerminalWidget::beep()
695{
696 if (m_should_beep) {
697 sysbeep();
698 return;
699 }
700 m_visual_beep_timer->restart(200);
701 m_visual_beep_timer->set_single_shot(true);
702 m_visual_beep_timer->on_timeout = [this] {
703 force_repaint();
704 };
705 force_repaint();
706}
707
708void TerminalWidget::emit_char(u8 ch)
709{
710 if (write(m_ptm_fd, &ch, 1) < 0) {
711 perror("emit_char: write");
712 }
713}
714
715void TerminalWidget::context_menu_event(GUI::ContextMenuEvent& event)
716{
717 if (!m_context_menu) {
718 m_context_menu = GUI::Menu::construct();
719 m_context_menu->add_action(copy_action());
720 m_context_menu->add_action(paste_action());
721 }
722 m_context_menu->popup(event.screen_position());
723}
724
725void TerminalWidget::drop_event(GUI::DropEvent& event)
726{
727 if (event.mime_data().has_text()) {
728 event.accept();
729 auto text = event.mime_data().text();
730 write(m_ptm_fd, text.characters(), text.length());
731 } else if (event.mime_data().has_urls()) {
732 event.accept();
733 auto urls = event.mime_data().urls();
734 bool first = true;
735 for (auto& url : event.mime_data().urls()) {
736 if (!first) {
737 write(m_ptm_fd, " ", 1);
738 first = false;
739 }
740 if (url.protocol() == "file")
741 write(m_ptm_fd, url.path().characters(), url.path().length());
742 else
743 write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
744 }
745 }
746}
747
748void TerminalWidget::did_change_font()
749{
750 GUI::Frame::did_change_font();
751 m_line_height = font().glyph_height() + m_line_spacing;
752
753 // TODO: try to find a bold version of the new font (e.g. CsillaThin7x10 -> CsillaBold7x10)
754 const Gfx::Font& bold_font = Gfx::Font::default_bold_fixed_width_font();
755
756 if (bold_font.glyph_height() == font().glyph_height() && bold_font.glyph_width(' ') == font().glyph_width(' '))
757 m_bold_font = &bold_font;
758 else
759 m_bold_font = font();
760
761 if (!size().is_empty())
762 relayout(size());
763}