main.cpp 19 KB

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