Serenity Operating System
1/*
2 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/FixedArray.h>
8#include <AK/QuickSort.h>
9#include <AK/URL.h>
10#include <LibConfig/Client.h>
11#include <LibConfig/Listener.h>
12#include <LibCore/ArgsParser.h>
13#include <LibCore/DeprecatedFile.h>
14#include <LibCore/DirIterator.h>
15#include <LibCore/System.h>
16#include <LibDesktop/Launcher.h>
17#include <LibGUI/Action.h>
18#include <LibGUI/ActionGroup.h>
19#include <LibGUI/Application.h>
20#include <LibGUI/BoxLayout.h>
21#include <LibGUI/Button.h>
22#include <LibGUI/CheckBox.h>
23#include <LibGUI/ComboBox.h>
24#include <LibGUI/Event.h>
25#include <LibGUI/Icon.h>
26#include <LibGUI/ItemListModel.h>
27#include <LibGUI/Menu.h>
28#include <LibGUI/Menubar.h>
29#include <LibGUI/MessageBox.h>
30#include <LibGUI/Process.h>
31#include <LibGUI/TextBox.h>
32#include <LibGUI/Widget.h>
33#include <LibGUI/Window.h>
34#include <LibGfx/Font/FontDatabase.h>
35#include <LibGfx/Palette.h>
36#include <LibMain/Main.h>
37#include <LibVT/TerminalWidget.h>
38#include <assert.h>
39#include <errno.h>
40#include <pty.h>
41#include <pwd.h>
42#include <signal.h>
43#include <stdio.h>
44#include <stdlib.h>
45#include <string.h>
46#include <sys/ioctl.h>
47#include <sys/wait.h>
48#include <unistd.h>
49
50class TerminalChangeListener : public Config::Listener {
51public:
52 TerminalChangeListener(VT::TerminalWidget& parent_terminal)
53 : m_parent_terminal(parent_terminal)
54 {
55 }
56
57 virtual void config_bool_did_change(DeprecatedString const& domain, DeprecatedString const& group, DeprecatedString const& key, bool value) override
58 {
59 VERIFY(domain == "Terminal");
60
61 if (group == "Terminal") {
62 if (key == "ShowScrollBar")
63 m_parent_terminal.set_show_scrollbar(value);
64 else if (key == "ConfirmClose" && on_confirm_close_changed)
65 on_confirm_close_changed(value);
66 } else if (group == "Cursor" && key == "Blinking") {
67 m_parent_terminal.set_cursor_blinking(value);
68 }
69 }
70
71 virtual void config_string_did_change(DeprecatedString const& domain, DeprecatedString const& group, DeprecatedString const& key, DeprecatedString const& value) override
72 {
73 VERIFY(domain == "Terminal");
74
75 if (group == "Window" && key == "Bell") {
76 auto bell_mode = VT::TerminalWidget::BellMode::Visible;
77 if (value == "AudibleBeep")
78 bell_mode = VT::TerminalWidget::BellMode::AudibleBeep;
79 if (value == "Visible")
80 bell_mode = VT::TerminalWidget::BellMode::Visible;
81 if (value == "Disabled")
82 bell_mode = VT::TerminalWidget::BellMode::Disabled;
83 m_parent_terminal.set_bell_mode(bell_mode);
84 } else if (group == "Text" && key == "Font") {
85 auto font = Gfx::FontDatabase::the().get_by_name(value);
86 if (font.is_null())
87 font = Gfx::FontDatabase::default_fixed_width_font();
88 m_parent_terminal.set_font_and_resize_to_fit(*font);
89 m_parent_terminal.apply_size_increments_to_window(*m_parent_terminal.window());
90 m_parent_terminal.window()->resize(m_parent_terminal.size());
91 } else if (group == "Cursor" && key == "Shape") {
92 auto cursor_shape = VT::TerminalWidget::parse_cursor_shape(value).value_or(VT::CursorShape::Block);
93 m_parent_terminal.set_cursor_shape(cursor_shape);
94 }
95 }
96
97 virtual void config_i32_did_change(DeprecatedString const& domain, DeprecatedString const& group, DeprecatedString const& key, i32 value) override
98 {
99 VERIFY(domain == "Terminal");
100
101 if (group == "Terminal" && key == "MaxHistorySize") {
102 m_parent_terminal.set_max_history_size(value);
103 } else if (group == "Window" && key == "Opacity") {
104 m_parent_terminal.set_opacity(value);
105 }
106 }
107
108 Function<void(bool)> on_confirm_close_changed;
109
110private:
111 VT::TerminalWidget& m_parent_terminal;
112};
113
114static void utmp_update(DeprecatedString const& tty, pid_t pid, bool create)
115{
116 int utmpupdate_pid = fork();
117 if (utmpupdate_pid < 0) {
118 perror("fork");
119 return;
120 }
121 if (utmpupdate_pid == 0) {
122 // Be careful here! Because fork() only clones one thread it's
123 // possible that we deadlock on anything involving a mutex,
124 // including the heap! So resort to low-level APIs
125 char pid_str[32];
126 snprintf(pid_str, sizeof(pid_str), "%d", pid);
127 execl("/bin/utmpupdate", "/bin/utmpupdate", "-f", "Terminal", "-p", pid_str, (create ? "-c" : "-d"), tty.characters(), nullptr);
128 } else {
129 wait_again:
130 int status = 0;
131 if (waitpid(utmpupdate_pid, &status, 0) < 0) {
132 int err = errno;
133 if (err == EINTR)
134 goto wait_again;
135 perror("waitpid");
136 return;
137 }
138 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
139 dbgln("Terminal: utmpupdate exited with status {}", WEXITSTATUS(status));
140 else if (WIFSIGNALED(status))
141 dbgln("Terminal: utmpupdate exited due to unhandled signal {}", WTERMSIG(status));
142 }
143}
144
145static ErrorOr<void> run_command(DeprecatedString command, bool keep_open)
146{
147 DeprecatedString shell = "/bin/Shell";
148 auto* pw = getpwuid(getuid());
149 if (pw && pw->pw_shell) {
150 shell = pw->pw_shell;
151 }
152 endpwent();
153
154 Vector<StringView> arguments;
155 arguments.append(shell);
156 if (!command.is_empty()) {
157 if (keep_open)
158 arguments.append("--keep-open"sv);
159 arguments.append("-c"sv);
160 arguments.append(command);
161 }
162 auto env = TRY(FixedArray<StringView>::create({ "TERM=xterm"sv, "PAGER=more"sv, "PATH="sv DEFAULT_PATH_SV }));
163 TRY(Core::System::exec(shell, arguments, Core::System::SearchInPath::No, env.span()));
164 VERIFY_NOT_REACHED();
165}
166
167static ErrorOr<NonnullRefPtr<GUI::Window>> create_find_window(VT::TerminalWidget& terminal)
168{
169 auto window = TRY(GUI::Window::try_create(&terminal));
170 window->set_window_mode(GUI::WindowMode::RenderAbove);
171 window->set_title("Find in Terminal");
172 window->set_resizable(false);
173 window->resize(300, 90);
174
175 auto main_widget = TRY(window->set_main_widget<GUI::Widget>());
176 main_widget->set_fill_with_background_color(true);
177 main_widget->set_background_role(ColorRole::Button);
178 TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>(4));
179
180 auto find = TRY(main_widget->try_add<GUI::Widget>());
181 TRY(find->try_set_layout<GUI::HorizontalBoxLayout>(4));
182 find->set_fixed_height(30);
183
184 auto find_textbox = TRY(find->try_add<GUI::TextBox>());
185 find_textbox->set_fixed_width(230);
186 find_textbox->set_focus(true);
187 if (terminal.has_selection())
188 find_textbox->set_text(terminal.selected_text().replace("\n"sv, " "sv, ReplaceMode::All));
189 auto find_backwards = TRY(find->try_add<GUI::Button>());
190 find_backwards->set_fixed_width(25);
191 find_backwards->set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/upward-triangle.png"sv)));
192 auto find_forwards = TRY(find->try_add<GUI::Button>());
193 find_forwards->set_fixed_width(25);
194 find_forwards->set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/downward-triangle.png"sv)));
195
196 find_textbox->on_return_pressed = [find_backwards] {
197 find_backwards->click();
198 };
199
200 find_textbox->on_shift_return_pressed = [find_forwards] {
201 find_forwards->click();
202 };
203
204 auto match_case = TRY(main_widget->try_add<GUI::CheckBox>(TRY("Case sensitive"_string)));
205 auto wrap_around = TRY(main_widget->try_add<GUI::CheckBox>(TRY("Wrap around"_string)));
206
207 find_backwards->on_click = [&terminal, find_textbox, match_case, wrap_around](auto) {
208 auto needle = find_textbox->text();
209 if (needle.is_empty()) {
210 return;
211 }
212
213 auto found_range = terminal.find_previous(needle, terminal.normalized_selection().start(), match_case->is_checked(), wrap_around->is_checked());
214
215 if (found_range.is_valid()) {
216 terminal.scroll_to_row(found_range.start().row());
217 terminal.set_selection(found_range);
218 }
219 };
220 find_forwards->on_click = [&terminal, find_textbox, match_case, wrap_around](auto) {
221 auto needle = find_textbox->text();
222 if (needle.is_empty()) {
223 return;
224 }
225
226 auto found_range = terminal.find_next(needle, terminal.normalized_selection().end(), match_case->is_checked(), wrap_around->is_checked());
227
228 if (found_range.is_valid()) {
229 terminal.scroll_to_row(found_range.start().row());
230 terminal.set_selection(found_range);
231 }
232 };
233
234 return window;
235}
236
237ErrorOr<int> serenity_main(Main::Arguments arguments)
238{
239 TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix sigaction"));
240
241 struct sigaction act;
242 memset(&act, 0, sizeof(act));
243 act.sa_flags = SA_NOCLDWAIT;
244 act.sa_handler = SIG_IGN;
245
246 TRY(Core::System::sigaction(SIGCHLD, &act, nullptr));
247
248 auto app = TRY(GUI::Application::try_create(arguments));
249
250 TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix"));
251
252 Config::pledge_domain("Terminal");
253
254 StringView command_to_execute;
255 bool keep_open = false;
256
257 Core::ArgsParser args_parser;
258 args_parser.add_option(command_to_execute, "Execute this command inside the terminal", nullptr, 'e', "command");
259 args_parser.add_option(keep_open, "Keep the terminal open after the command has finished executing", nullptr, 'k');
260
261 args_parser.parse(arguments);
262
263 if (keep_open && command_to_execute.is_empty()) {
264 warnln("Option -k can only be used in combination with -e.");
265 return 1;
266 }
267
268 int ptm_fd;
269 pid_t shell_pid = forkpty(&ptm_fd, nullptr, nullptr, nullptr);
270 if (shell_pid < 0) {
271 perror("forkpty");
272 return 1;
273 }
274 if (shell_pid == 0) {
275 close(ptm_fd);
276 if (!command_to_execute.is_empty())
277 TRY(run_command(command_to_execute, keep_open));
278 else
279 TRY(run_command(Config::read_string("Terminal"sv, "Startup"sv, "Command"sv, ""sv), false));
280 VERIFY_NOT_REACHED();
281 }
282
283 auto ptsname = TRY(Core::System::ptsname(ptm_fd));
284 utmp_update(ptsname, shell_pid, true);
285
286 auto app_icon = GUI::Icon::default_icon("app-terminal"sv);
287
288 auto window = TRY(GUI::Window::try_create());
289 window->set_title("Terminal");
290 window->set_obey_widget_min_size(false);
291
292 auto terminal = TRY(window->set_main_widget<VT::TerminalWidget>(ptm_fd, true));
293 terminal->on_command_exit = [&] {
294 app->quit(0);
295 };
296 terminal->on_title_change = [&](auto title) {
297 window->set_title(title);
298 };
299 terminal->on_terminal_size_change = [&](auto size) {
300 window->resize(size);
301 };
302 terminal->apply_size_increments_to_window(*window);
303 window->set_icon(app_icon.bitmap_for_size(16));
304
305 Config::monitor_domain("Terminal");
306 auto should_confirm_close = Config::read_bool("Terminal"sv, "Terminal"sv, "ConfirmClose"sv, true);
307 TerminalChangeListener listener { terminal };
308
309 auto bell = Config::read_string("Terminal"sv, "Window"sv, "Bell"sv, "Visible"sv);
310 if (bell == "AudibleBeep") {
311 terminal->set_bell_mode(VT::TerminalWidget::BellMode::AudibleBeep);
312 } else if (bell == "Disabled") {
313 terminal->set_bell_mode(VT::TerminalWidget::BellMode::Disabled);
314 } else {
315 terminal->set_bell_mode(VT::TerminalWidget::BellMode::Visible);
316 }
317
318 auto cursor_shape = VT::TerminalWidget::parse_cursor_shape(Config::read_string("Terminal"sv, "Cursor"sv, "Shape"sv, "Block"sv)).value_or(VT::CursorShape::Block);
319 terminal->set_cursor_shape(cursor_shape);
320
321 auto cursor_blinking = Config::read_bool("Terminal"sv, "Cursor"sv, "Blinking"sv, true);
322 terminal->set_cursor_blinking(cursor_blinking);
323
324 auto find_window = TRY(create_find_window(terminal));
325
326 auto new_opacity = Config::read_i32("Terminal"sv, "Window"sv, "Opacity"sv, 255);
327 terminal->set_opacity(new_opacity);
328 window->set_has_alpha_channel(new_opacity < 255);
329
330 auto new_scrollback_size = Config::read_i32("Terminal"sv, "Terminal"sv, "MaxHistorySize"sv, terminal->max_history_size());
331 terminal->set_max_history_size(new_scrollback_size);
332
333 auto show_scroll_bar = Config::read_bool("Terminal"sv, "Terminal"sv, "ShowScrollBar"sv, true);
334 terminal->set_show_scrollbar(show_scroll_bar);
335
336 auto open_settings_action = GUI::Action::create("Terminal &Settings", TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/settings.png"sv)),
337 [&](auto&) {
338 GUI::Process::spawn_or_show_error(window, "/bin/TerminalSettings"sv);
339 });
340
341 TRY(terminal->context_menu().try_add_separator());
342 TRY(terminal->context_menu().try_add_action(open_settings_action));
343
344 auto file_menu = TRY(window->try_add_menu("&File"));
345 TRY(file_menu->try_add_action(GUI::Action::create("Open New &Terminal", { Mod_Ctrl | Mod_Shift, Key_N }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"sv)), [&](auto&) {
346 GUI::Process::spawn_or_show_error(window, "/bin/Terminal"sv);
347 })));
348
349 TRY(file_menu->try_add_action(open_settings_action));
350 TRY(file_menu->try_add_separator());
351
352 auto tty_has_foreground_process = [&] {
353 pid_t fg_pid = tcgetpgrp(ptm_fd);
354 return fg_pid != -1 && fg_pid != shell_pid;
355 };
356
357 auto shell_child_process_count = [&] {
358 Core::DirIterator iterator(DeprecatedString::formatted("/proc/{}/children", shell_pid), Core::DirIterator::Flags::SkipParentAndBaseDir);
359 int background_process_count = 0;
360 while (iterator.has_next()) {
361 ++background_process_count;
362 (void)iterator.next_path();
363 }
364 return background_process_count;
365 };
366
367 auto check_terminal_quit = [&]() -> GUI::Dialog::ExecResult {
368 if (!should_confirm_close)
369 return GUI::MessageBox::ExecResult::OK;
370 Optional<DeprecatedString> close_message;
371 if (tty_has_foreground_process()) {
372 close_message = "There is still a process running in this terminal. Closing the terminal will kill it.";
373 } else {
374 auto child_process_count = shell_child_process_count();
375 if (child_process_count > 1)
376 close_message = DeprecatedString::formatted("There are {} background processes running in this terminal. Closing the terminal may kill them.", child_process_count);
377 else if (child_process_count == 1)
378 close_message = "There is a background process running in this terminal. Closing the terminal may kill it.";
379 }
380 if (close_message.has_value())
381 return GUI::MessageBox::show(window, *close_message, "Close this terminal?"sv, GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel);
382 return GUI::MessageBox::ExecResult::OK;
383 };
384
385 TRY(file_menu->try_add_action(GUI::CommonActions::make_quit_action([&](auto&) {
386 dbgln("Terminal: Quit menu activated!");
387 if (check_terminal_quit() == GUI::MessageBox::ExecResult::OK)
388 GUI::Application::the()->quit();
389 })));
390
391 auto edit_menu = TRY(window->try_add_menu("&Edit"));
392 TRY(edit_menu->try_add_action(terminal->copy_action()));
393 TRY(edit_menu->try_add_action(terminal->paste_action()));
394 TRY(edit_menu->try_add_separator());
395 TRY(edit_menu->try_add_action(GUI::Action::create("&Find...", { Mod_Ctrl | Mod_Shift, Key_F }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv)),
396 [&](auto&) {
397 find_window->show();
398 find_window->move_to_front();
399 })));
400
401 auto view_menu = TRY(window->try_add_menu("&View"));
402 TRY(view_menu->try_add_action(GUI::CommonActions::make_fullscreen_action([&](auto&) {
403 window->set_fullscreen(!window->is_fullscreen());
404 })));
405 TRY(view_menu->try_add_action(terminal->clear_including_history_action()));
406
407 auto adjust_font_size = [&](float adjustment) {
408 auto& font = terminal->font();
409 auto new_size = max(5, font.presentation_size() + adjustment);
410 if (auto new_font = Gfx::FontDatabase::the().get(font.family(), new_size, font.weight(), font.width(), font.slope())) {
411 terminal->set_font_and_resize_to_fit(*new_font);
412 terminal->apply_size_increments_to_window(*window);
413 window->resize(terminal->size());
414 }
415 };
416
417 TRY(view_menu->try_add_separator());
418 TRY(view_menu->try_add_action(GUI::CommonActions::make_zoom_in_action([&](auto&) {
419 adjust_font_size(1);
420 })));
421 TRY(view_menu->try_add_action(GUI::CommonActions::make_zoom_out_action([&](auto&) {
422 adjust_font_size(-1);
423 })));
424
425 auto help_menu = TRY(window->try_add_menu("&Help"));
426 TRY(help_menu->try_add_action(GUI::CommonActions::make_command_palette_action(window)));
427 TRY(help_menu->try_add_action(GUI::CommonActions::make_help_action([](auto&) {
428 Desktop::Launcher::open(URL::create_with_file_scheme("/usr/share/man/man1/Terminal.md"), "/bin/Help");
429 })));
430 TRY(help_menu->try_add_action(GUI::CommonActions::make_about_action("Terminal", app_icon, window)));
431
432 window->on_close_request = [&]() -> GUI::Window::CloseRequestDecision {
433 if (check_terminal_quit() == GUI::MessageBox::ExecResult::OK)
434 return GUI::Window::CloseRequestDecision::Close;
435 return GUI::Window::CloseRequestDecision::StayOpen;
436 };
437
438 window->on_input_preemption_change = [&](bool is_preempted) {
439 terminal->set_logical_focus(!is_preempted);
440 };
441
442 TRY(Core::System::unveil("/res", "r"));
443 TRY(Core::System::unveil("/bin", "r"));
444 TRY(Core::System::unveil("/proc", "r"));
445 TRY(Core::System::unveil("/bin/Terminal", "x"));
446 TRY(Core::System::unveil("/bin/TerminalSettings", "x"));
447 TRY(Core::System::unveil("/bin/utmpupdate", "x"));
448 TRY(Core::System::unveil("/etc/FileIconProvider.ini", "r"));
449 TRY(Core::System::unveil("/tmp/session/%sid/portal/launch", "rw"));
450 TRY(Core::System::unveil("/tmp/session/%sid/portal/config", "rw"));
451 TRY(Core::System::unveil(nullptr, nullptr));
452
453 auto modified_state_check_timer = TRY(Core::Timer::create_repeating(500, [&] {
454 window->set_modified(tty_has_foreground_process() || shell_child_process_count() > 0);
455 }));
456
457 listener.on_confirm_close_changed = [&](bool confirm_close) {
458 if (confirm_close) {
459 modified_state_check_timer->start();
460 } else {
461 modified_state_check_timer->stop();
462 window->set_modified(false);
463 }
464 should_confirm_close = confirm_close;
465 };
466
467 window->show();
468 if (should_confirm_close)
469 modified_state_check_timer->start();
470 int result = app->exec();
471 dbgln("Exiting terminal, updating utmp");
472 utmp_update(ptsname, 0, false);
473 return result;
474}