main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/URL.h>
  8. #include <LibConfig/Client.h>
  9. #include <LibConfig/Listener.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/DirIterator.h>
  12. #include <LibCore/Process.h>
  13. #include <LibCore/System.h>
  14. #include <LibDesktop/Launcher.h>
  15. #include <LibGUI/Action.h>
  16. #include <LibGUI/ActionGroup.h>
  17. #include <LibGUI/Application.h>
  18. #include <LibGUI/BoxLayout.h>
  19. #include <LibGUI/Button.h>
  20. #include <LibGUI/CheckBox.h>
  21. #include <LibGUI/ComboBox.h>
  22. #include <LibGUI/Event.h>
  23. #include <LibGUI/Icon.h>
  24. #include <LibGUI/ItemListModel.h>
  25. #include <LibGUI/Menu.h>
  26. #include <LibGUI/Menubar.h>
  27. #include <LibGUI/TextBox.h>
  28. #include <LibGUI/Widget.h>
  29. #include <LibGUI/Window.h>
  30. #include <LibGfx/Font/FontDatabase.h>
  31. #include <LibGfx/Palette.h>
  32. #include <LibMain/Main.h>
  33. #include <LibVT/TerminalWidget.h>
  34. #include <assert.h>
  35. #include <errno.h>
  36. #include <pty.h>
  37. #include <pwd.h>
  38. #include <signal.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <string.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/wait.h>
  44. #include <unistd.h>
  45. class TerminalChangeListener : public Config::Listener {
  46. public:
  47. TerminalChangeListener(VT::TerminalWidget& parent_terminal)
  48. : m_parent_terminal(parent_terminal)
  49. {
  50. }
  51. virtual void config_bool_did_change(String const& domain, String const& group, String const& key, bool value) override
  52. {
  53. VERIFY(domain == "Terminal");
  54. if (group == "Terminal" && key == "ShowScrollBar") {
  55. m_parent_terminal.set_show_scrollbar(value);
  56. }
  57. }
  58. virtual void config_string_did_change(String const& domain, String const& group, String const& key, String const& value) override
  59. {
  60. VERIFY(domain == "Terminal");
  61. if (group == "Window") {
  62. if (key == "Bell") {
  63. auto bell_mode = VT::TerminalWidget::BellMode::Visible;
  64. if (value == "AudibleBeep")
  65. bell_mode = VT::TerminalWidget::BellMode::AudibleBeep;
  66. if (value == "Visible")
  67. bell_mode = VT::TerminalWidget::BellMode::Visible;
  68. if (value == "Disabled")
  69. bell_mode = VT::TerminalWidget::BellMode::Disabled;
  70. m_parent_terminal.set_bell_mode(bell_mode);
  71. } else if (key == "ColorScheme") {
  72. m_parent_terminal.set_color_scheme(value);
  73. }
  74. } else if (group == "Text" && key == "Font") {
  75. auto font = Gfx::FontDatabase::the().get_by_name(value);
  76. if (font.is_null())
  77. font = Gfx::FontDatabase::default_fixed_width_font();
  78. m_parent_terminal.set_font_and_resize_to_fit(*font);
  79. m_parent_terminal.window()->resize(m_parent_terminal.size());
  80. }
  81. }
  82. virtual void config_i32_did_change(String const& domain, String const& group, String const& key, i32 value) override
  83. {
  84. VERIFY(domain == "Terminal");
  85. if (group == "Terminal" && key == "MaxHistorySize") {
  86. m_parent_terminal.set_max_history_size(value);
  87. } else if (group == "Window" && key == "Opacity") {
  88. m_parent_terminal.set_opacity(value);
  89. }
  90. }
  91. private:
  92. VT::TerminalWidget& m_parent_terminal;
  93. };
  94. static void utmp_update(String const& tty, pid_t pid, bool create)
  95. {
  96. int utmpupdate_pid = fork();
  97. if (utmpupdate_pid < 0) {
  98. perror("fork");
  99. return;
  100. }
  101. if (utmpupdate_pid == 0) {
  102. // Be careful here! Because fork() only clones one thread it's
  103. // possible that we deadlock on anything involving a mutex,
  104. // including the heap! So resort to low-level APIs
  105. char pid_str[32];
  106. snprintf(pid_str, sizeof(pid_str), "%d", pid);
  107. execl("/bin/utmpupdate", "/bin/utmpupdate", "-f", "Terminal", "-p", pid_str, (create ? "-c" : "-d"), tty.characters(), nullptr);
  108. } else {
  109. wait_again:
  110. int status = 0;
  111. if (waitpid(utmpupdate_pid, &status, 0) < 0) {
  112. int err = errno;
  113. if (err == EINTR)
  114. goto wait_again;
  115. perror("waitpid");
  116. return;
  117. }
  118. if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
  119. dbgln("Terminal: utmpupdate exited with status {}", WEXITSTATUS(status));
  120. else if (WIFSIGNALED(status))
  121. dbgln("Terminal: utmpupdate exited due to unhandled signal {}", WTERMSIG(status));
  122. }
  123. }
  124. static void run_command(String command, bool keep_open)
  125. {
  126. String shell = "/bin/Shell";
  127. auto* pw = getpwuid(getuid());
  128. if (pw && pw->pw_shell) {
  129. shell = pw->pw_shell;
  130. }
  131. endpwent();
  132. char const* args[5] = { shell.characters(), nullptr, nullptr, nullptr, nullptr };
  133. if (!command.is_empty()) {
  134. int arg_index = 1;
  135. if (keep_open)
  136. args[arg_index++] = "--keep-open";
  137. args[arg_index++] = "-c";
  138. args[arg_index++] = command.characters();
  139. }
  140. char const* envs[] = { "TERM=xterm", "PAGER=more", "PATH=/usr/local/bin:/usr/bin:/bin", nullptr };
  141. int rc = execve(shell.characters(), const_cast<char**>(args), const_cast<char**>(envs));
  142. if (rc < 0) {
  143. perror("execve");
  144. exit(1);
  145. }
  146. VERIFY_NOT_REACHED();
  147. }
  148. static ErrorOr<NonnullRefPtr<GUI::Window>> create_find_window(VT::TerminalWidget& terminal)
  149. {
  150. auto window = TRY(GUI::Window::try_create());
  151. window->set_window_type(GUI::WindowType::ToolWindow);
  152. window->set_title("Find in Terminal");
  153. window->set_resizable(false);
  154. window->resize(300, 90);
  155. auto main_widget = TRY(window->try_set_main_widget<GUI::Widget>());
  156. main_widget->set_fill_with_background_color(true);
  157. main_widget->set_background_role(ColorRole::Button);
  158. (void)TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>());
  159. main_widget->layout()->set_margins(4);
  160. auto find = TRY(main_widget->try_add<GUI::Widget>());
  161. (void)TRY(find->try_set_layout<GUI::HorizontalBoxLayout>());
  162. find->layout()->set_margins(4);
  163. find->set_fixed_height(30);
  164. auto find_textbox = TRY(find->try_add<GUI::TextBox>());
  165. find_textbox->set_fixed_width(230);
  166. find_textbox->set_focus(true);
  167. if (terminal.has_selection())
  168. find_textbox->set_text(terminal.selected_text().replace("\n", " ", true));
  169. auto find_backwards = TRY(find->try_add<GUI::Button>());
  170. find_backwards->set_fixed_width(25);
  171. find_backwards->set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/upward-triangle.png").release_value_but_fixme_should_propagate_errors());
  172. auto find_forwards = TRY(find->try_add<GUI::Button>());
  173. find_forwards->set_fixed_width(25);
  174. find_forwards->set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/downward-triangle.png").release_value_but_fixme_should_propagate_errors());
  175. find_textbox->on_return_pressed = [find_backwards]() mutable {
  176. find_backwards->click();
  177. };
  178. find_textbox->on_shift_return_pressed = [find_forwards]() mutable {
  179. find_forwards->click();
  180. };
  181. auto match_case = TRY(main_widget->try_add<GUI::CheckBox>("Case sensitive"));
  182. auto wrap_around = TRY(main_widget->try_add<GUI::CheckBox>("Wrap around"));
  183. find_backwards->on_click = [&terminal, find_textbox, match_case, wrap_around](auto) mutable {
  184. auto needle = find_textbox->text();
  185. if (needle.is_empty()) {
  186. return;
  187. }
  188. auto found_range = terminal.find_previous(needle, terminal.normalized_selection().start(), match_case->is_checked(), wrap_around->is_checked());
  189. if (found_range.is_valid()) {
  190. terminal.scroll_to_row(found_range.start().row());
  191. terminal.set_selection(found_range);
  192. }
  193. };
  194. find_forwards->on_click = [&terminal, find_textbox, match_case, wrap_around](auto) {
  195. auto needle = find_textbox->text();
  196. if (needle.is_empty()) {
  197. return;
  198. }
  199. auto found_range = terminal.find_next(needle, terminal.normalized_selection().end(), match_case->is_checked(), wrap_around->is_checked());
  200. if (found_range.is_valid()) {
  201. terminal.scroll_to_row(found_range.start().row());
  202. terminal.set_selection(found_range);
  203. }
  204. };
  205. return window;
  206. }
  207. ErrorOr<int> serenity_main(Main::Arguments arguments)
  208. {
  209. TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix sigaction"));
  210. struct sigaction act;
  211. memset(&act, 0, sizeof(act));
  212. act.sa_flags = SA_NOCLDWAIT;
  213. act.sa_handler = SIG_IGN;
  214. TRY(Core::System::sigaction(SIGCHLD, &act, nullptr));
  215. auto app = TRY(GUI::Application::try_create(arguments));
  216. TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix"));
  217. Config::pledge_domain("Terminal");
  218. char const* command_to_execute = nullptr;
  219. bool keep_open = false;
  220. Core::ArgsParser args_parser;
  221. args_parser.add_option(command_to_execute, "Execute this command inside the terminal", nullptr, 'e', "command");
  222. args_parser.add_option(keep_open, "Keep the terminal open after the command has finished executing", nullptr, 'k');
  223. args_parser.parse(arguments);
  224. if (keep_open && !command_to_execute) {
  225. warnln("Option -k can only be used in combination with -e.");
  226. return 1;
  227. }
  228. int ptm_fd;
  229. pid_t shell_pid = forkpty(&ptm_fd, nullptr, nullptr, nullptr);
  230. if (shell_pid < 0) {
  231. perror("forkpty");
  232. return 1;
  233. }
  234. if (shell_pid == 0) {
  235. close(ptm_fd);
  236. if (command_to_execute)
  237. run_command(command_to_execute, keep_open);
  238. else
  239. run_command(Config::read_string("Terminal", "Startup", "Command", ""), false);
  240. VERIFY_NOT_REACHED();
  241. }
  242. auto ptsname = TRY(Core::System::ptsname(ptm_fd));
  243. utmp_update(ptsname, shell_pid, true);
  244. auto app_icon = GUI::Icon::default_icon("app-terminal");
  245. auto window = TRY(GUI::Window::try_create());
  246. window->set_title("Terminal");
  247. window->set_double_buffering_enabled(false);
  248. auto terminal = TRY(window->try_set_main_widget<VT::TerminalWidget>(ptm_fd, true));
  249. terminal->on_command_exit = [&] {
  250. app->quit(0);
  251. };
  252. terminal->on_title_change = [&](auto title) {
  253. window->set_title(title);
  254. };
  255. terminal->on_terminal_size_change = [&](auto& size) {
  256. window->resize(size);
  257. };
  258. terminal->apply_size_increments_to_window(*window);
  259. window->set_icon(app_icon.bitmap_for_size(16));
  260. Config::monitor_domain("Terminal");
  261. TerminalChangeListener listener { terminal };
  262. auto bell = Config::read_string("Terminal", "Window", "Bell", "Visible");
  263. if (bell == "AudibleBeep") {
  264. terminal->set_bell_mode(VT::TerminalWidget::BellMode::AudibleBeep);
  265. } else if (bell == "Disabled") {
  266. terminal->set_bell_mode(VT::TerminalWidget::BellMode::Disabled);
  267. } else {
  268. terminal->set_bell_mode(VT::TerminalWidget::BellMode::Visible);
  269. }
  270. auto find_window = TRY(create_find_window(terminal));
  271. auto new_opacity = Config::read_i32("Terminal", "Window", "Opacity", 255);
  272. terminal->set_opacity(new_opacity);
  273. window->set_has_alpha_channel(new_opacity < 255);
  274. auto new_scrollback_size = Config::read_i32("Terminal", "Terminal", "MaxHistorySize", terminal->max_history_size());
  275. terminal->set_max_history_size(new_scrollback_size);
  276. auto show_scroll_bar = Config::read_bool("Terminal", "Terminal", "ShowScrollBar", true);
  277. terminal->set_show_scrollbar(show_scroll_bar);
  278. 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(),
  279. [&](auto&) {
  280. Core::Process::spawn("/bin/TerminalSettings");
  281. });
  282. TRY(terminal->context_menu().try_add_separator());
  283. TRY(terminal->context_menu().try_add_action(open_settings_action));
  284. auto file_menu = TRY(window->try_add_menu("&File"));
  285. 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&) {
  286. Core::Process::spawn("/bin/Terminal");
  287. })));
  288. TRY(file_menu->try_add_action(open_settings_action));
  289. TRY(file_menu->try_add_separator());
  290. TRY(file_menu->try_add_action(GUI::CommonActions::make_quit_action([](auto&) {
  291. dbgln("Terminal: Quit menu activated!");
  292. GUI::Application::the()->quit();
  293. })));
  294. auto edit_menu = TRY(window->try_add_menu("&Edit"));
  295. TRY(edit_menu->try_add_action(terminal->copy_action()));
  296. TRY(edit_menu->try_add_action(terminal->paste_action()));
  297. TRY(edit_menu->try_add_separator());
  298. 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(),
  299. [&](auto&) {
  300. find_window->show();
  301. find_window->move_to_front();
  302. })));
  303. auto view_menu = TRY(window->try_add_menu("&View"));
  304. TRY(view_menu->try_add_action(GUI::CommonActions::make_fullscreen_action([&](auto&) {
  305. window->set_fullscreen(!window->is_fullscreen());
  306. })));
  307. TRY(view_menu->try_add_action(terminal->clear_including_history_action()));
  308. auto help_menu = TRY(window->try_add_menu("&Help"));
  309. TRY(help_menu->try_add_action(GUI::CommonActions::make_help_action([](auto&) {
  310. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/Terminal.md"), "/bin/Help");
  311. })));
  312. TRY(help_menu->try_add_action(GUI::CommonActions::make_about_action("Terminal", app_icon, window)));
  313. window->on_close = [&]() {
  314. find_window->close();
  315. };
  316. TRY(Core::System::unveil("/res", "r"));
  317. TRY(Core::System::unveil("/bin", "r"));
  318. TRY(Core::System::unveil("/bin/Terminal", "x"));
  319. TRY(Core::System::unveil("/bin/TerminalSettings", "x"));
  320. TRY(Core::System::unveil("/bin/utmpupdate", "x"));
  321. TRY(Core::System::unveil("/etc/FileIconProvider.ini", "r"));
  322. TRY(Core::System::unveil("/tmp/portal/launch", "rw"));
  323. TRY(Core::System::unveil("/tmp/portal/config", "rw"));
  324. TRY(Core::System::unveil(nullptr, nullptr));
  325. window->show();
  326. int result = app->exec();
  327. dbgln("Exiting terminal, updating utmp");
  328. utmp_update(ptsname, 0, false);
  329. return result;
  330. }