main.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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/TypedTransfer.h>
  9. #include <AK/URL.h>
  10. #include <LibConfig/Client.h>
  11. #include <LibConfig/Listener.h>
  12. #include <LibCore/Account.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/Directory.h>
  15. #include <LibCore/System.h>
  16. #include <LibDesktop/Launcher.h>
  17. #include <LibFileSystem/FileSystem.h>
  18. #include <LibGUI/Action.h>
  19. #include <LibGUI/ActionGroup.h>
  20. #include <LibGUI/Application.h>
  21. #include <LibGUI/BoxLayout.h>
  22. #include <LibGUI/Button.h>
  23. #include <LibGUI/CheckBox.h>
  24. #include <LibGUI/ComboBox.h>
  25. #include <LibGUI/Event.h>
  26. #include <LibGUI/Icon.h>
  27. #include <LibGUI/ItemListModel.h>
  28. #include <LibGUI/Menu.h>
  29. #include <LibGUI/Menubar.h>
  30. #include <LibGUI/MessageBox.h>
  31. #include <LibGUI/Process.h>
  32. #include <LibGUI/TextBox.h>
  33. #include <LibGUI/Widget.h>
  34. #include <LibGUI/Window.h>
  35. #include <LibGfx/Font/FontDatabase.h>
  36. #include <LibGfx/Palette.h>
  37. #include <LibMain/Main.h>
  38. #include <LibVT/TerminalWidget.h>
  39. #include <pty.h>
  40. class TerminalChangeListener : public Config::Listener {
  41. public:
  42. TerminalChangeListener(VT::TerminalWidget& parent_terminal)
  43. : m_parent_terminal(parent_terminal)
  44. {
  45. }
  46. virtual void config_bool_did_change(StringView domain, StringView group, StringView key, bool value) override
  47. {
  48. VERIFY(domain == "Terminal");
  49. if (group == "Terminal") {
  50. if (key == "ShowScrollBar")
  51. m_parent_terminal.set_show_scrollbar(value);
  52. else if (key == "ConfirmClose" && on_confirm_close_changed)
  53. on_confirm_close_changed(value);
  54. } else if (group == "Cursor" && key == "Blinking") {
  55. m_parent_terminal.set_cursor_blinking(value);
  56. }
  57. }
  58. virtual void config_string_did_change(StringView domain, StringView group, StringView key, StringView value) override
  59. {
  60. VERIFY(domain == "Terminal");
  61. if (group == "Window" && key == "Bell") {
  62. auto bell_mode = VT::TerminalWidget::BellMode::Visible;
  63. if (value == "AudibleBeep")
  64. bell_mode = VT::TerminalWidget::BellMode::AudibleBeep;
  65. if (value == "Visible")
  66. bell_mode = VT::TerminalWidget::BellMode::Visible;
  67. if (value == "Disabled")
  68. bell_mode = VT::TerminalWidget::BellMode::Disabled;
  69. m_parent_terminal.set_bell_mode(bell_mode);
  70. } else if (group == "Text" && key == "Font") {
  71. auto font = Gfx::FontDatabase::the().get_by_name(value);
  72. if (font.is_null())
  73. font = Gfx::FontDatabase::default_fixed_width_font();
  74. m_parent_terminal.set_font_and_resize_to_fit(*font);
  75. m_parent_terminal.apply_size_increments_to_window(*m_parent_terminal.window());
  76. m_parent_terminal.window()->resize(m_parent_terminal.size());
  77. } else if (group == "Cursor" && key == "Shape") {
  78. auto cursor_shape = VT::TerminalWidget::parse_cursor_shape(value).value_or(VT::CursorShape::Block);
  79. m_parent_terminal.set_cursor_shape(cursor_shape);
  80. }
  81. }
  82. virtual void config_i32_did_change(StringView domain, StringView group, StringView 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. Function<void(bool)> on_confirm_close_changed;
  92. private:
  93. VT::TerminalWidget& m_parent_terminal;
  94. };
  95. static ErrorOr<void> utmp_update(StringView tty, pid_t pid, bool create)
  96. {
  97. auto pid_string = TRY(String::number(pid));
  98. Array utmp_update_command {
  99. "-f"sv,
  100. "Terminal"sv,
  101. "-p"sv,
  102. pid_string.bytes_as_string_view(),
  103. (create ? "-c"sv : "-d"sv),
  104. tty,
  105. };
  106. auto utmpupdate_pid = TRY(Core::Process::spawn("/bin/utmpupdate"sv, utmp_update_command, {}, Core::Process::KeepAsChild::Yes));
  107. Core::System::WaitPidResult status;
  108. auto wait_successful = false;
  109. while (!wait_successful) {
  110. auto result = Core::System::waitpid(utmpupdate_pid, 0);
  111. if (result.is_error() && result.error().code() != EINTR) {
  112. return result.release_error();
  113. } else if (!result.is_error()) {
  114. status = result.release_value();
  115. wait_successful = true;
  116. }
  117. }
  118. if (WIFEXITED(status.status) && WEXITSTATUS(status.status) != 0)
  119. dbgln("Terminal: utmpupdate exited with status {}", WEXITSTATUS(status.status));
  120. else if (WIFSIGNALED(status.status))
  121. dbgln("Terminal: utmpupdate exited due to unhandled signal {}", WTERMSIG(status.status));
  122. return {};
  123. }
  124. static ErrorOr<void> run_command(StringView command, bool keep_open)
  125. {
  126. auto shell = TRY(String::from_byte_string(TRY(Core::Account::self(Core::Account::Read::PasswdOnly)).shell()));
  127. if (shell.is_empty())
  128. shell = "/bin/Shell"_string;
  129. Vector<StringView> arguments;
  130. arguments.append(shell);
  131. if (!command.is_empty()) {
  132. if (keep_open)
  133. arguments.append("--keep-open"sv);
  134. arguments.append("-c"sv);
  135. arguments.append(command);
  136. }
  137. auto env = TRY(FixedArray<StringView>::create({ "TERM=xterm"sv, "PAGER=more"sv, "PATH="sv DEFAULT_PATH_SV }));
  138. TRY(Core::System::exec(shell, arguments, Core::System::SearchInPath::No, env.span()));
  139. VERIFY_NOT_REACHED();
  140. }
  141. static ErrorOr<NonnullRefPtr<GUI::Window>> create_find_window(VT::TerminalWidget& terminal)
  142. {
  143. auto window = GUI::Window::construct(&terminal);
  144. window->set_window_mode(GUI::WindowMode::RenderAbove);
  145. window->set_title("Find in Terminal");
  146. window->set_resizable(false);
  147. window->resize(300, 90);
  148. auto main_widget = window->set_main_widget<GUI::Widget>();
  149. main_widget->set_fill_with_background_color(true);
  150. main_widget->set_background_role(ColorRole::Button);
  151. main_widget->set_layout<GUI::VerticalBoxLayout>(4);
  152. auto& find = main_widget->add<GUI::Widget>();
  153. find.set_layout<GUI::HorizontalBoxLayout>(4);
  154. find.set_fixed_height(30);
  155. auto& find_textbox = find.add<GUI::TextBox>();
  156. find_textbox.set_fixed_width(230);
  157. find_textbox.set_focus(true);
  158. if (terminal.has_selection())
  159. find_textbox.set_text(terminal.selected_text().replace("\n"sv, " "sv, ReplaceMode::All));
  160. auto& find_backwards = find.add<GUI::Button>();
  161. find_backwards.set_fixed_width(25);
  162. find_backwards.set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/upward-triangle.png"sv)));
  163. auto& find_forwards = find.add<GUI::Button>();
  164. find_forwards.set_fixed_width(25);
  165. find_forwards.set_icon(TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/downward-triangle.png"sv)));
  166. find_textbox.on_return_pressed = [&find_backwards] {
  167. find_backwards.click();
  168. };
  169. find_textbox.on_shift_return_pressed = [&find_forwards] {
  170. find_forwards.click();
  171. };
  172. auto& match_case = main_widget->add<GUI::CheckBox>("Case sensitive"_string);
  173. auto& wrap_around = main_widget->add<GUI::CheckBox>("Wrap around"_string);
  174. find_backwards.on_click = [&terminal, &find_textbox, &match_case, &wrap_around](auto) {
  175. auto needle = find_textbox.text();
  176. if (needle.is_empty()) {
  177. return;
  178. }
  179. auto found_range = terminal.find_previous(needle, terminal.normalized_selection().start(), match_case.is_checked(), wrap_around.is_checked());
  180. if (found_range.is_valid()) {
  181. terminal.scroll_to_row(found_range.start().row());
  182. terminal.set_selection(found_range);
  183. }
  184. };
  185. find_forwards.on_click = [&terminal, &find_textbox, &match_case, &wrap_around](auto) {
  186. auto needle = find_textbox.text();
  187. if (needle.is_empty()) {
  188. return;
  189. }
  190. auto found_range = terminal.find_next(needle, terminal.normalized_selection().end(), 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. return window;
  197. }
  198. ErrorOr<int> serenity_main(Main::Arguments arguments)
  199. {
  200. TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix sigaction"));
  201. struct sigaction act;
  202. act.sa_mask = 0;
  203. // Do not trust that both function pointers overlap.
  204. act.sa_sigaction = nullptr;
  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::create(arguments));
  209. TRY(Core::System::pledge("stdio tty rpath cpath wpath recvfd sendfd proc exec unix"));
  210. Config::pledge_domain("Terminal");
  211. StringView command_to_execute;
  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.is_empty()) {
  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. return Error::from_errno(errno);
  225. // We're the child process; run the startup command.
  226. if (shell_pid == 0) {
  227. if (!command_to_execute.is_empty())
  228. TRY(run_command(command_to_execute, keep_open));
  229. else
  230. TRY(run_command(Config::read_string("Terminal"sv, "Startup"sv, "Command"sv, ""sv), false));
  231. VERIFY_NOT_REACHED();
  232. }
  233. auto ptsname = TRY(Core::System::ptsname(ptm_fd));
  234. TRY(utmp_update(ptsname, shell_pid, true));
  235. auto app_icon = GUI::Icon::default_icon("app-terminal"sv);
  236. auto window = GUI::Window::construct();
  237. window->set_title("Terminal");
  238. window->set_obey_widget_min_size(false);
  239. auto terminal = window->set_main_widget<VT::TerminalWidget>(ptm_fd, true);
  240. terminal->set_startup_process_id(shell_pid);
  241. terminal->on_command_exit = [&] {
  242. app->quit(0);
  243. };
  244. terminal->on_title_change = [&](auto title) {
  245. window->set_title(title);
  246. };
  247. terminal->on_terminal_size_change = [&](auto size) {
  248. window->resize(size);
  249. };
  250. terminal->apply_size_increments_to_window(*window);
  251. window->set_icon(app_icon.bitmap_for_size(16));
  252. Config::monitor_domain("Terminal");
  253. auto should_confirm_close = Config::read_bool("Terminal"sv, "Terminal"sv, "ConfirmClose"sv, true);
  254. TerminalChangeListener listener { terminal };
  255. auto bell = Config::read_string("Terminal"sv, "Window"sv, "Bell"sv, "Visible"sv);
  256. if (bell == "AudibleBeep") {
  257. terminal->set_bell_mode(VT::TerminalWidget::BellMode::AudibleBeep);
  258. } else if (bell == "Disabled") {
  259. terminal->set_bell_mode(VT::TerminalWidget::BellMode::Disabled);
  260. } else {
  261. terminal->set_bell_mode(VT::TerminalWidget::BellMode::Visible);
  262. }
  263. auto automark = Config::read_string("Terminal"sv, "Terminal"sv, "AutoMark"sv, "MarkInteractiveShellPrompt"sv);
  264. if (automark == "MarkNothing") {
  265. terminal->set_auto_mark_mode(VT::TerminalWidget::AutoMarkMode::MarkNothing);
  266. } else {
  267. terminal->set_auto_mark_mode(VT::TerminalWidget::AutoMarkMode::MarkInteractiveShellPrompt);
  268. }
  269. auto cursor_shape = VT::TerminalWidget::parse_cursor_shape(Config::read_string("Terminal"sv, "Cursor"sv, "Shape"sv, "Block"sv)).value_or(VT::CursorShape::Block);
  270. terminal->set_cursor_shape(cursor_shape);
  271. auto cursor_blinking = Config::read_bool("Terminal"sv, "Cursor"sv, "Blinking"sv, true);
  272. terminal->set_cursor_blinking(cursor_blinking);
  273. auto find_window = TRY(create_find_window(terminal));
  274. auto new_opacity = Config::read_i32("Terminal"sv, "Window"sv, "Opacity"sv, 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"sv, "Terminal"sv, "MaxHistorySize"sv, terminal->max_history_size());
  278. terminal->set_max_history_size(new_scrollback_size);
  279. auto show_scroll_bar = Config::read_bool("Terminal"sv, "Terminal"sv, "ShowScrollBar"sv, true);
  280. terminal->set_show_scrollbar(show_scroll_bar);
  281. auto open_settings_action = GUI::Action::create("Terminal &Settings", TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/settings.png"sv)),
  282. [&](auto&) {
  283. GUI::Process::spawn_or_show_error(window, "/bin/TerminalSettings"sv);
  284. });
  285. terminal->context_menu().add_separator();
  286. terminal->context_menu().add_action(open_settings_action);
  287. auto file_menu = window->add_menu("&File"_string);
  288. file_menu->add_action(GUI::Action::create("Open New &Terminal", { Mod_Ctrl | Mod_Shift, Key_N }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-terminal.png"sv)), [&](auto&) {
  289. GUI::Process::spawn_or_show_error(window, "/bin/Terminal"sv);
  290. }));
  291. file_menu->add_action(open_settings_action);
  292. file_menu->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. int background_process_count = 0;
  299. Core::Directory::for_each_entry(String::formatted("/proc/{}/children", shell_pid).release_value_but_fixme_should_propagate_errors(), Core::DirIterator::Flags::SkipParentAndBaseDir, [&](auto&, auto&) {
  300. ++background_process_count;
  301. return IterationDecision::Continue;
  302. }).release_value_but_fixme_should_propagate_errors();
  303. return background_process_count;
  304. };
  305. auto check_terminal_quit = [&]() -> GUI::Dialog::ExecResult {
  306. if (!should_confirm_close)
  307. return GUI::MessageBox::ExecResult::OK;
  308. Optional<String> close_message;
  309. auto title = "Running Process"sv;
  310. if (tty_has_foreground_process()) {
  311. close_message = "Close Terminal and kill its foreground process?"_string;
  312. } else {
  313. auto child_process_count = shell_child_process_count();
  314. if (child_process_count > 1) {
  315. title = "Running Processes"sv;
  316. close_message = String::formatted("Close Terminal and kill its {} background processes?", child_process_count).release_value_but_fixme_should_propagate_errors();
  317. } else if (child_process_count == 1) {
  318. close_message = "Close Terminal and kill its background process?"_string;
  319. }
  320. }
  321. if (close_message.has_value())
  322. return GUI::MessageBox::show(window, *close_message, title, GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel);
  323. return GUI::MessageBox::ExecResult::OK;
  324. };
  325. file_menu->add_action(GUI::CommonActions::make_quit_action([&](auto&) {
  326. dbgln("Terminal: Quit menu activated!");
  327. if (check_terminal_quit() == GUI::MessageBox::ExecResult::OK)
  328. GUI::Application::the()->quit();
  329. }));
  330. auto edit_menu = window->add_menu("&Edit"_string);
  331. edit_menu->add_action(terminal->copy_action());
  332. edit_menu->add_action(terminal->paste_action());
  333. edit_menu->add_separator();
  334. edit_menu->add_action(GUI::Action::create("&Find...", { Mod_Ctrl | Mod_Shift, Key_F }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv)),
  335. [&](auto&) {
  336. find_window->show();
  337. find_window->move_to_front();
  338. }));
  339. auto view_menu = window->add_menu("&View"_string);
  340. view_menu->add_action(GUI::CommonActions::make_fullscreen_action([&](auto&) {
  341. window->set_fullscreen(!window->is_fullscreen());
  342. }));
  343. view_menu->add_action(terminal->clear_including_history_action());
  344. view_menu->add_action(terminal->clear_to_previous_mark_action());
  345. auto adjust_font_size = [&](float adjustment, Gfx::Font::AllowInexactSizeMatch preference) {
  346. auto& font = terminal->font();
  347. auto new_size = max(5, font.presentation_size() + adjustment);
  348. if (auto new_font = Gfx::FontDatabase::the().get(font.family(), new_size, font.weight(), font.width(), font.slope(), preference)) {
  349. terminal->set_font_and_resize_to_fit(*new_font);
  350. terminal->apply_size_increments_to_window(*window);
  351. window->resize(terminal->size());
  352. }
  353. };
  354. view_menu->add_separator();
  355. view_menu->add_action(GUI::CommonActions::make_zoom_in_action([&](auto&) {
  356. adjust_font_size(1, Gfx::Font::AllowInexactSizeMatch::Larger);
  357. }));
  358. view_menu->add_action(GUI::CommonActions::make_zoom_out_action([&](auto&) {
  359. adjust_font_size(-1, Gfx::Font::AllowInexactSizeMatch::Smaller);
  360. }));
  361. auto help_menu = window->add_menu("&Help"_string);
  362. help_menu->add_action(GUI::CommonActions::make_command_palette_action(window));
  363. help_menu->add_action(GUI::CommonActions::make_help_action([](auto&) {
  364. Desktop::Launcher::open(URL::create_with_file_scheme("/usr/share/man/man1/Applications/Terminal.md"), "/bin/Help");
  365. }));
  366. help_menu->add_action(GUI::CommonActions::make_about_action("Terminal"_string, app_icon, window));
  367. window->on_close_request = [&]() -> GUI::Window::CloseRequestDecision {
  368. if (check_terminal_quit() == GUI::MessageBox::ExecResult::OK)
  369. return GUI::Window::CloseRequestDecision::Close;
  370. return GUI::Window::CloseRequestDecision::StayOpen;
  371. };
  372. window->on_input_preemption_change = [&](bool is_preempted) {
  373. terminal->set_logical_focus(!is_preempted);
  374. };
  375. TRY(Core::System::unveil("/res", "r"));
  376. TRY(Core::System::unveil("/bin", "r"));
  377. TRY(Core::System::unveil("/proc", "r"));
  378. TRY(Core::System::unveil("/bin/Terminal", "x"));
  379. TRY(Core::System::unveil("/bin/TerminalSettings", "x"));
  380. TRY(Core::System::unveil("/bin/utmpupdate", "x"));
  381. TRY(Core::System::unveil("/etc/FileIconProvider.ini", "r"));
  382. TRY(Core::System::unveil("/tmp/session/%sid/portal/launch", "rw"));
  383. TRY(Core::System::unveil("/tmp/session/%sid/portal/config", "rw"));
  384. TRY(Core::System::unveil(nullptr, nullptr));
  385. auto modified_state_check_timer = TRY(Core::Timer::create_repeating(500, [&] {
  386. window->set_modified(tty_has_foreground_process() || shell_child_process_count() > 0);
  387. }));
  388. listener.on_confirm_close_changed = [&](bool confirm_close) {
  389. if (confirm_close) {
  390. modified_state_check_timer->start();
  391. } else {
  392. modified_state_check_timer->stop();
  393. window->set_modified(false);
  394. }
  395. should_confirm_close = confirm_close;
  396. };
  397. window->show();
  398. if (should_confirm_close)
  399. modified_state_check_timer->start();
  400. int result = app->exec();
  401. dbgln("Exiting terminal, updating utmp");
  402. TRY(utmp_update(ptsname, 0, false));
  403. return result;
  404. }