main.cpp 17 KB

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