main.cpp 18 KB

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