main.cpp 19 KB

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