main.cpp 14 KB

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