main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 <Applications/Terminal/TerminalSettingsWindowGML.h>
  9. #include <LibConfig/Client.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/FontPicker.h>
  24. #include <LibGUI/Icon.h>
  25. #include <LibGUI/ItemListModel.h>
  26. #include <LibGUI/Menu.h>
  27. #include <LibGUI/Menubar.h>
  28. #include <LibGUI/OpacitySlider.h>
  29. #include <LibGUI/RadioButton.h>
  30. #include <LibGUI/SpinBox.h>
  31. #include <LibGUI/TextBox.h>
  32. #include <LibGUI/Widget.h>
  33. #include <LibGUI/Window.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. static void utmp_update(const char* tty, pid_t pid, bool create)
  49. {
  50. if (!tty)
  51. return;
  52. int utmpupdate_pid = fork();
  53. if (utmpupdate_pid < 0) {
  54. perror("fork");
  55. return;
  56. }
  57. if (utmpupdate_pid == 0) {
  58. // Be careful here! Because fork() only clones one thread it's
  59. // possible that we deadlock on anything involving a mutex,
  60. // including the heap! So resort to low-level APIs
  61. char pid_str[32];
  62. snprintf(pid_str, sizeof(pid_str), "%d", pid);
  63. execl("/bin/utmpupdate", "/bin/utmpupdate", "-f", "Terminal", "-p", pid_str, (create ? "-c" : "-d"), tty, nullptr);
  64. } else {
  65. wait_again:
  66. int status = 0;
  67. if (waitpid(utmpupdate_pid, &status, 0) < 0) {
  68. int err = errno;
  69. if (err == EINTR)
  70. goto wait_again;
  71. perror("waitpid");
  72. return;
  73. }
  74. if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
  75. dbgln("Terminal: utmpupdate exited with status {}", WEXITSTATUS(status));
  76. else if (WIFSIGNALED(status))
  77. dbgln("Terminal: utmpupdate exited due to unhandled signal {}", WTERMSIG(status));
  78. }
  79. }
  80. static void run_command(String command, bool keep_open)
  81. {
  82. String shell = "/bin/Shell";
  83. auto* pw = getpwuid(getuid());
  84. if (pw && pw->pw_shell) {
  85. shell = pw->pw_shell;
  86. }
  87. endpwent();
  88. const char* args[5] = { shell.characters(), nullptr, nullptr, nullptr, nullptr };
  89. if (!command.is_empty()) {
  90. int arg_index = 1;
  91. if (keep_open)
  92. args[arg_index++] = "--keep-open";
  93. args[arg_index++] = "-c";
  94. args[arg_index++] = command.characters();
  95. }
  96. const char* envs[] = { "TERM=xterm", "PAGER=more", "PATH=/usr/local/bin:/usr/bin:/bin", nullptr };
  97. int rc = execve(shell.characters(), const_cast<char**>(args), const_cast<char**>(envs));
  98. if (rc < 0) {
  99. perror("execve");
  100. exit(1);
  101. }
  102. VERIFY_NOT_REACHED();
  103. }
  104. static RefPtr<GUI::Window> create_settings_window(VT::TerminalWidget& terminal)
  105. {
  106. auto window = GUI::Window::construct();
  107. window->set_window_type(GUI::WindowType::ToolWindow);
  108. window->set_title("Terminal settings");
  109. window->set_resizable(false);
  110. window->resize(200, 240);
  111. window->center_within(*terminal.window());
  112. auto& settings = window->set_main_widget<GUI::Widget>();
  113. settings.load_from_gml(terminal_settings_window_gml);
  114. auto& beep_bell_radio = *settings.find_descendant_of_type_named<GUI::RadioButton>("beep_bell_radio");
  115. auto& visual_bell_radio = *settings.find_descendant_of_type_named<GUI::RadioButton>("visual_bell_radio");
  116. auto& no_bell_radio = *settings.find_descendant_of_type_named<GUI::RadioButton>("no_bell_radio");
  117. switch (terminal.bell_mode()) {
  118. case VT::TerminalWidget::BellMode::Visible:
  119. visual_bell_radio.set_checked(true);
  120. break;
  121. case VT::TerminalWidget::BellMode::AudibleBeep:
  122. beep_bell_radio.set_checked(true);
  123. break;
  124. case VT::TerminalWidget::BellMode::Disabled:
  125. no_bell_radio.set_checked(true);
  126. break;
  127. }
  128. beep_bell_radio.on_checked = [&terminal](bool) {
  129. terminal.set_bell_mode(VT::TerminalWidget::BellMode::AudibleBeep);
  130. };
  131. visual_bell_radio.on_checked = [&terminal](bool) {
  132. terminal.set_bell_mode(VT::TerminalWidget::BellMode::Visible);
  133. };
  134. no_bell_radio.on_checked = [&terminal](bool) {
  135. terminal.set_bell_mode(VT::TerminalWidget::BellMode::Disabled);
  136. };
  137. auto& slider = *settings.find_descendant_of_type_named<GUI::OpacitySlider>("background_opacity_slider");
  138. slider.on_change = [&terminal](int value) {
  139. terminal.set_opacity(value);
  140. };
  141. slider.set_value(terminal.opacity());
  142. auto& history_size_spinbox = *settings.find_descendant_of_type_named<GUI::SpinBox>("history_size_spinbox");
  143. history_size_spinbox.set_value(terminal.max_history_size());
  144. history_size_spinbox.on_change = [&terminal](int value) {
  145. terminal.set_max_history_size(value);
  146. };
  147. // The settings window takes a reference to this vector, so it needs to outlive this scope.
  148. // As long as we ensure that only one settings window may be open at a time (which we do),
  149. // this should cause no problems.
  150. static Vector<String> color_scheme_names;
  151. color_scheme_names.clear();
  152. Core::DirIterator iterator("/res/terminal-colors", Core::DirIterator::SkipParentAndBaseDir);
  153. while (iterator.has_next()) {
  154. auto path = iterator.next_path();
  155. color_scheme_names.append(path.replace(".ini", ""));
  156. }
  157. quick_sort(color_scheme_names);
  158. auto& color_scheme_combo = *settings.find_descendant_of_type_named<GUI::ComboBox>("color_scheme_combo");
  159. color_scheme_combo.set_only_allow_values_from_model(true);
  160. color_scheme_combo.set_model(*GUI::ItemListModel<String>::create(color_scheme_names));
  161. color_scheme_combo.set_selected_index(color_scheme_names.find_first_index(terminal.color_scheme_name()).value());
  162. color_scheme_combo.set_enabled(color_scheme_names.size() > 1);
  163. color_scheme_combo.on_change = [&](auto&, const GUI::ModelIndex& index) {
  164. terminal.set_color_scheme(index.data().as_string());
  165. };
  166. return window;
  167. }
  168. static RefPtr<GUI::Window> create_find_window(VT::TerminalWidget& terminal)
  169. {
  170. auto window = GUI::Window::construct();
  171. window->set_window_type(GUI::WindowType::ToolWindow);
  172. window->set_title("Find in Terminal");
  173. window->set_resizable(false);
  174. window->resize(300, 90);
  175. auto& search = window->set_main_widget<GUI::Widget>();
  176. search.set_fill_with_background_color(true);
  177. search.set_background_role(ColorRole::Button);
  178. search.set_layout<GUI::VerticalBoxLayout>();
  179. search.layout()->set_margins(4);
  180. auto& find = search.add<GUI::Widget>();
  181. find.set_layout<GUI::HorizontalBoxLayout>();
  182. find.layout()->set_margins(4);
  183. find.set_fixed_height(30);
  184. auto& find_textbox = find.add<GUI::TextBox>();
  185. find_textbox.set_fixed_width(230);
  186. find_textbox.set_focus(true);
  187. if (terminal.has_selection())
  188. find_textbox.set_text(terminal.selected_text().replace("\n", " ", true));
  189. auto& find_backwards = find.add<GUI::Button>();
  190. find_backwards.set_fixed_width(25);
  191. find_backwards.set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/upward-triangle.png").release_value_but_fixme_should_propagate_errors());
  192. auto& find_forwards = find.add<GUI::Button>();
  193. find_forwards.set_fixed_width(25);
  194. find_forwards.set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/downward-triangle.png").release_value_but_fixme_should_propagate_errors());
  195. find_textbox.on_return_pressed = [&]() {
  196. find_backwards.click();
  197. };
  198. find_textbox.on_shift_return_pressed = [&]() {
  199. find_forwards.click();
  200. };
  201. auto& match_case = search.add<GUI::CheckBox>("Case sensitive");
  202. auto& wrap_around = search.add<GUI::CheckBox>("Wrap around");
  203. find_backwards.on_click = [&](auto) {
  204. auto needle = find_textbox.text();
  205. if (needle.is_empty()) {
  206. return;
  207. }
  208. auto found_range = terminal.find_previous(needle, terminal.normalized_selection().start(), 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. find_forwards.on_click = [&](auto) {
  215. auto needle = find_textbox.text();
  216. if (needle.is_empty()) {
  217. return;
  218. }
  219. auto found_range = terminal.find_next(needle, terminal.normalized_selection().end(), match_case.is_checked(), wrap_around.is_checked());
  220. if (found_range.is_valid()) {
  221. terminal.scroll_to_row(found_range.start().row());
  222. terminal.set_selection(found_range);
  223. }
  224. };
  225. return window;
  226. }
  227. ErrorOr<int> serenity_main(Main::Arguments arguments)
  228. {
  229. TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix sigaction", nullptr));
  230. struct sigaction act;
  231. memset(&act, 0, sizeof(act));
  232. act.sa_flags = SA_NOCLDWAIT;
  233. act.sa_handler = SIG_IGN;
  234. TRY(Core::System::sigaction(SIGCHLD, &act, nullptr));
  235. auto app = GUI::Application::construct(arguments);
  236. TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix", nullptr));
  237. Config::pledge_domains("Terminal");
  238. const char* command_to_execute = nullptr;
  239. bool keep_open = false;
  240. Core::ArgsParser args_parser;
  241. args_parser.add_option(command_to_execute, "Execute this command inside the terminal", nullptr, 'e', "command");
  242. args_parser.add_option(keep_open, "Keep the terminal open after the command has finished executing", nullptr, 'k');
  243. args_parser.parse(arguments);
  244. if (keep_open && !command_to_execute) {
  245. warnln("Option -k can only be used in combination with -e.");
  246. return 1;
  247. }
  248. int ptm_fd;
  249. pid_t shell_pid = forkpty(&ptm_fd, nullptr, nullptr, nullptr);
  250. if (shell_pid < 0) {
  251. perror("forkpty");
  252. return 1;
  253. }
  254. if (shell_pid == 0) {
  255. close(ptm_fd);
  256. if (command_to_execute)
  257. run_command(command_to_execute, keep_open);
  258. else
  259. run_command(Config::read_string("Terminal", "Startup", "Command", ""), false);
  260. VERIFY_NOT_REACHED();
  261. }
  262. auto* pts_name = ptsname(ptm_fd);
  263. utmp_update(pts_name, shell_pid, true);
  264. auto app_icon = GUI::Icon::default_icon("app-terminal");
  265. auto window = GUI::Window::construct();
  266. window->set_title("Terminal");
  267. window->set_background_color(Color::Black);
  268. window->set_double_buffering_enabled(false);
  269. auto& terminal = window->set_main_widget<VT::TerminalWidget>(ptm_fd, true);
  270. terminal.on_command_exit = [&] {
  271. app->quit(0);
  272. };
  273. terminal.on_title_change = [&](auto title) {
  274. window->set_title(title);
  275. };
  276. terminal.on_terminal_size_change = [&](auto& size) {
  277. window->resize(size);
  278. };
  279. terminal.apply_size_increments_to_window(*window);
  280. window->set_icon(app_icon.bitmap_for_size(16));
  281. auto bell = Config::read_string("Terminal", "Window", "Bell", "Visible");
  282. if (bell == "AudibleBeep") {
  283. terminal.set_bell_mode(VT::TerminalWidget::BellMode::AudibleBeep);
  284. } else if (bell == "Disabled") {
  285. terminal.set_bell_mode(VT::TerminalWidget::BellMode::Disabled);
  286. } else {
  287. terminal.set_bell_mode(VT::TerminalWidget::BellMode::Visible);
  288. }
  289. RefPtr<GUI::Window> settings_window;
  290. RefPtr<GUI::Window> find_window;
  291. auto new_opacity = Config::read_i32("Terminal", "Window", "Opacity", 255);
  292. terminal.set_opacity(new_opacity);
  293. window->set_has_alpha_channel(new_opacity < 255);
  294. auto new_scrollback_size = Config::read_i32("Terminal", "Terminal", "MaxHistorySize", terminal.max_history_size());
  295. terminal.set_max_history_size(new_scrollback_size);
  296. 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(),
  297. [&](const GUI::Action&) {
  298. if (!settings_window)
  299. settings_window = create_settings_window(terminal);
  300. settings_window->show();
  301. settings_window->move_to_front();
  302. settings_window->on_close = [&]() {
  303. Config::write_i32("Terminal", "Window", "Opacity", terminal.opacity());
  304. Config::write_i32("Terminal", "Terminal", "MaxHistorySize", terminal.max_history_size());
  305. auto bell = terminal.bell_mode();
  306. auto bell_setting = String::empty();
  307. if (bell == VT::TerminalWidget::BellMode::AudibleBeep) {
  308. bell_setting = "AudibleBeep";
  309. } else if (bell == VT::TerminalWidget::BellMode::Disabled) {
  310. bell_setting = "Disabled";
  311. } else {
  312. bell_setting = "Visible";
  313. }
  314. Config::write_string("Terminal", "Window", "Bell", bell_setting);
  315. };
  316. });
  317. terminal.context_menu().add_separator();
  318. auto pick_font_action = GUI::Action::create("&Terminal Font...", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-font-editor.png").release_value_but_fixme_should_propagate_errors(),
  319. [&](auto&) {
  320. auto picker = GUI::FontPicker::construct(window, &terminal.font(), true);
  321. if (picker->exec() == GUI::Dialog::ExecOK) {
  322. terminal.set_font_and_resize_to_fit(*picker->font());
  323. window->resize(terminal.size());
  324. Config::write_string("Terminal", "Text", "Font", picker->font()->qualified_name());
  325. }
  326. });
  327. terminal.context_menu().add_action(pick_font_action);
  328. terminal.context_menu().add_separator();
  329. terminal.context_menu().add_action(open_settings_action);
  330. auto& file_menu = window->add_menu("&File");
  331. file_menu.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&) {
  332. Core::Process::spawn("/bin/Terminal");
  333. }));
  334. file_menu.add_action(open_settings_action);
  335. file_menu.add_separator();
  336. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  337. dbgln("Terminal: Quit menu activated!");
  338. GUI::Application::the()->quit();
  339. }));
  340. auto& edit_menu = window->add_menu("&Edit");
  341. edit_menu.add_action(terminal.copy_action());
  342. edit_menu.add_action(terminal.paste_action());
  343. edit_menu.add_separator();
  344. edit_menu.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(),
  345. [&](auto&) {
  346. if (!find_window)
  347. find_window = create_find_window(terminal);
  348. find_window->show();
  349. find_window->move_to_front();
  350. }));
  351. auto& view_menu = window->add_menu("&View");
  352. view_menu.add_action(GUI::CommonActions::make_fullscreen_action([&](auto&) {
  353. window->set_fullscreen(!window->is_fullscreen());
  354. }));
  355. view_menu.add_action(terminal.clear_including_history_action());
  356. view_menu.add_separator();
  357. view_menu.add_action(pick_font_action);
  358. auto& help_menu = window->add_menu("&Help");
  359. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  360. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/Terminal.md"), "/bin/Help");
  361. }));
  362. help_menu.add_action(GUI::CommonActions::make_about_action("Terminal", app_icon, window));
  363. window->on_close = [&]() {
  364. if (find_window)
  365. find_window->close();
  366. if (settings_window)
  367. settings_window->close();
  368. };
  369. TRY(Core::System::unveil("/res", "r"));
  370. TRY(Core::System::unveil("/bin", "r"));
  371. TRY(Core::System::unveil("/bin/Terminal", "x"));
  372. TRY(Core::System::unveil("/bin/utmpupdate", "x"));
  373. TRY(Core::System::unveil("/etc/FileIconProvider.ini", "r"));
  374. TRY(Core::System::unveil("/tmp/portal/launch", "rw"));
  375. TRY(Core::System::unveil("/tmp/portal/config", "rw"));
  376. TRY(Core::System::unveil(nullptr, nullptr));
  377. window->show();
  378. int result = app->exec();
  379. dbgln("Exiting terminal, updating utmp");
  380. utmp_update(pts_name, 0, false);
  381. return result;
  382. }