MainWidget.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "MainWidget.h"
  7. #include <AK/Optional.h>
  8. #include <AK/StringBuilder.h>
  9. #include <AK/URL.h>
  10. #include <Applications/TextEditor/TextEditorWindowGML.h>
  11. #include <LibConfig/Client.h>
  12. #include <LibCore/File.h>
  13. #include <LibCpp/SyntaxHighlighter.h>
  14. #include <LibDesktop/Launcher.h>
  15. #include <LibGUI/Action.h>
  16. #include <LibGUI/BoxLayout.h>
  17. #include <LibGUI/Button.h>
  18. #include <LibGUI/CheckBox.h>
  19. #include <LibGUI/FilePicker.h>
  20. #include <LibGUI/FontPicker.h>
  21. #include <LibGUI/GMLSyntaxHighlighter.h>
  22. #include <LibGUI/GroupBox.h>
  23. #include <LibGUI/INISyntaxHighlighter.h>
  24. #include <LibGUI/Menu.h>
  25. #include <LibGUI/Menubar.h>
  26. #include <LibGUI/MessageBox.h>
  27. #include <LibGUI/RegularEditingEngine.h>
  28. #include <LibGUI/Statusbar.h>
  29. #include <LibGUI/TextBox.h>
  30. #include <LibGUI/TextEditor.h>
  31. #include <LibGUI/Toolbar.h>
  32. #include <LibGUI/ToolbarContainer.h>
  33. #include <LibGUI/VimEditingEngine.h>
  34. #include <LibGfx/Font.h>
  35. #include <LibGfx/Painter.h>
  36. #include <LibJS/SyntaxHighlighter.h>
  37. #include <LibMarkdown/Document.h>
  38. #include <LibSQL/AST/SyntaxHighlighter.h>
  39. #include <LibWeb/HTML/SyntaxHighlighter/SyntaxHighlighter.h>
  40. #include <LibWeb/OutOfProcessWebView.h>
  41. #include <Shell/SyntaxHighlighter.h>
  42. namespace TextEditor {
  43. MainWidget::MainWidget()
  44. {
  45. load_from_gml(text_editor_window_gml);
  46. m_toolbar = *find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  47. m_toolbar_container = *find_descendant_of_type_named<GUI::ToolbarContainer>("toolbar_container");
  48. m_editor = *find_descendant_of_type_named<GUI::TextEditor>("editor");
  49. m_editor->set_ruler_visible(true);
  50. m_editor->set_automatic_indentation_enabled(true);
  51. m_editor->set_editing_engine(make<GUI::RegularEditingEngine>());
  52. m_editor->on_change = [this] {
  53. update_preview();
  54. };
  55. m_editor->on_modified_change = [this](bool modified) {
  56. window()->set_modified(modified);
  57. };
  58. m_find_replace_widget = *find_descendant_of_type_named<GUI::GroupBox>("find_replace_widget");
  59. m_find_widget = *find_descendant_of_type_named<GUI::Widget>("find_widget");
  60. m_replace_widget = *find_descendant_of_type_named<GUI::Widget>("replace_widget");
  61. m_find_textbox = *find_descendant_of_type_named<GUI::TextBox>("find_textbox");
  62. m_find_textbox->set_placeholder("Find");
  63. m_replace_textbox = *find_descendant_of_type_named<GUI::TextBox>("replace_textbox");
  64. m_replace_textbox->set_placeholder("Replace");
  65. m_match_case_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("match_case_checkbox");
  66. m_match_case_checkbox->on_checked = [this](auto is_checked) {
  67. m_match_case = is_checked;
  68. };
  69. m_match_case_checkbox->set_checked(true);
  70. m_regex_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("regex_checkbox");
  71. m_regex_checkbox->on_checked = [this](auto is_checked) {
  72. m_use_regex = is_checked;
  73. };
  74. m_regex_checkbox->set_checked(false);
  75. m_wrap_around_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("wrap_around_checkbox");
  76. m_wrap_around_checkbox->on_checked = [this](auto is_checked) {
  77. m_should_wrap = is_checked;
  78. };
  79. m_wrap_around_checkbox->set_checked(true);
  80. m_find_next_action = GUI::Action::create("Find &Next", { Mod_Ctrl, Key_G }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find-next.png"), [&](auto&) {
  81. auto needle = m_find_textbox->text();
  82. if (needle.is_empty())
  83. return;
  84. if (m_use_regex)
  85. m_editor->document().update_regex_matches(needle);
  86. auto found_range = m_editor->document().find_next(needle, m_editor->normalized_selection().end(), m_should_wrap ? GUI::TextDocument::SearchShouldWrap::Yes : GUI::TextDocument::SearchShouldWrap::No, m_use_regex, m_match_case);
  87. dbgln("find_next('{}') returned {}", needle, found_range);
  88. if (found_range.is_valid()) {
  89. m_editor->set_selection(found_range);
  90. } else {
  91. GUI::MessageBox::show(window(),
  92. String::formatted("Not found: \"{}\"", needle),
  93. "Not found",
  94. GUI::MessageBox::Type::Information);
  95. }
  96. });
  97. m_find_previous_action = GUI::Action::create("Find Pr&evious", { Mod_Ctrl | Mod_Shift, Key_G }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find-previous.png"), [&](auto&) {
  98. auto needle = m_find_textbox->text();
  99. if (needle.is_empty())
  100. return;
  101. if (m_use_regex)
  102. m_editor->document().update_regex_matches(needle);
  103. auto selection_start = m_editor->normalized_selection().start();
  104. if (!selection_start.is_valid())
  105. selection_start = m_editor->normalized_selection().end();
  106. auto found_range = m_editor->document().find_previous(needle, selection_start, m_should_wrap ? GUI::TextDocument::SearchShouldWrap::Yes : GUI::TextDocument::SearchShouldWrap::No, m_use_regex, m_match_case);
  107. dbgln("find_prev(\"{}\") returned {}", needle, found_range);
  108. if (found_range.is_valid()) {
  109. m_editor->set_selection(found_range);
  110. } else {
  111. GUI::MessageBox::show(window(),
  112. String::formatted("Not found: \"{}\"", needle),
  113. "Not found",
  114. GUI::MessageBox::Type::Information);
  115. }
  116. });
  117. m_replace_action = GUI::Action::create("Rep&lace", { Mod_Ctrl, Key_F1 }, [&](auto&) {
  118. auto needle = m_find_textbox->text();
  119. auto substitute = m_replace_textbox->text();
  120. if (needle.is_empty())
  121. return;
  122. if (m_use_regex)
  123. m_editor->document().update_regex_matches(needle);
  124. auto found_range = m_editor->document().find_next(needle, m_editor->normalized_selection().start(), m_should_wrap ? GUI::TextDocument::SearchShouldWrap::Yes : GUI::TextDocument::SearchShouldWrap::No, m_use_regex, m_match_case);
  125. if (found_range.is_valid()) {
  126. m_editor->set_selection(found_range);
  127. m_editor->insert_at_cursor_or_replace_selection(substitute);
  128. } else {
  129. GUI::MessageBox::show(window(),
  130. String::formatted("Not found: \"{}\"", needle),
  131. "Not found",
  132. GUI::MessageBox::Type::Information);
  133. }
  134. });
  135. m_replace_all_action = GUI::Action::create("Replace &All", { Mod_Ctrl, Key_F2 }, [&](auto&) {
  136. auto needle = m_find_textbox->text();
  137. auto substitute = m_replace_textbox->text();
  138. if (needle.is_empty())
  139. return;
  140. if (m_use_regex)
  141. m_editor->document().update_regex_matches(needle);
  142. auto found_range = m_editor->document().find_next(needle, {}, GUI::TextDocument::SearchShouldWrap::Yes, m_use_regex, m_match_case);
  143. while (found_range.is_valid()) {
  144. m_editor->set_selection(found_range);
  145. m_editor->insert_at_cursor_or_replace_selection(substitute);
  146. found_range = m_editor->document().find_next(needle, {}, GUI::TextDocument::SearchShouldWrap::Yes, m_use_regex, m_match_case);
  147. }
  148. });
  149. m_find_previous_button = *find_descendant_of_type_named<GUI::Button>("find_previous_button");
  150. m_find_previous_button->set_action(*m_find_previous_action);
  151. m_find_previous_button->set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find-previous.png"));
  152. m_find_next_button = *find_descendant_of_type_named<GUI::Button>("find_next_button");
  153. m_find_next_button->set_action(*m_find_next_action);
  154. m_find_next_button->set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find-next.png"));
  155. m_find_textbox->on_return_pressed = [this] {
  156. m_find_next_button->click();
  157. };
  158. m_find_textbox->on_escape_pressed = [this] {
  159. m_find_replace_widget->set_visible(false);
  160. m_editor->set_focus(true);
  161. };
  162. m_replace_button = *find_descendant_of_type_named<GUI::Button>("replace_button");
  163. m_replace_button->set_action(*m_replace_action);
  164. m_replace_all_button = *find_descendant_of_type_named<GUI::Button>("replace_all_button");
  165. m_replace_all_button->set_action(*m_replace_all_action);
  166. m_replace_textbox->on_return_pressed = [this] {
  167. m_replace_button->click();
  168. };
  169. m_replace_textbox->on_escape_pressed = [this] {
  170. m_find_replace_widget->set_visible(false);
  171. m_editor->set_focus(true);
  172. };
  173. m_vim_emulation_setting_action = GUI::Action::create_checkable("&Vim Emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [&](auto& action) {
  174. if (action.is_checked())
  175. m_editor->set_editing_engine(make<GUI::VimEditingEngine>());
  176. else
  177. m_editor->set_editing_engine(make<GUI::RegularEditingEngine>());
  178. });
  179. m_vim_emulation_setting_action->set_checked(false);
  180. m_find_replace_action = GUI::Action::create("&Find/Replace...", { Mod_Ctrl, Key_F }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find.png"), [this](auto&) {
  181. m_find_replace_widget->set_visible(true);
  182. m_find_widget->set_visible(true);
  183. m_replace_widget->set_visible(true);
  184. m_find_textbox->set_focus(true);
  185. if (m_editor->has_selection()) {
  186. auto selected_text = m_editor->document().text_in_range(m_editor->normalized_selection());
  187. m_find_textbox->set_text(selected_text);
  188. }
  189. m_find_textbox->select_all();
  190. });
  191. m_editor->add_custom_context_menu_action(*m_find_replace_action);
  192. m_editor->add_custom_context_menu_action(*m_find_next_action);
  193. m_editor->add_custom_context_menu_action(*m_find_previous_action);
  194. m_statusbar = *find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  195. GUI::Application::the()->on_action_enter = [this](GUI::Action& action) {
  196. auto text = action.status_tip();
  197. if (text.is_empty())
  198. text = Gfx::parse_ampersand_string(action.text());
  199. m_statusbar->set_override_text(move(text));
  200. };
  201. GUI::Application::the()->on_action_leave = [this](GUI::Action&) {
  202. m_statusbar->set_override_text({});
  203. };
  204. m_editor->on_cursor_change = [this] { update_statusbar(); };
  205. m_editor->on_selection_change = [this] { update_statusbar(); };
  206. m_new_action = GUI::Action::create("&New", { Mod_Ctrl, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/new.png"), [this](GUI::Action const&) {
  207. if (editor().document().is_modified()) {
  208. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  209. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  210. m_save_action->activate();
  211. if (save_document_first_result != GUI::Dialog::ExecResult::ExecNo && editor().document().is_modified())
  212. return;
  213. }
  214. m_editor->set_text(StringView());
  215. set_path({});
  216. update_title();
  217. });
  218. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  219. auto response = FileSystemAccessClient::Client::the().open_file(window()->window_id());
  220. if (response.error != 0) {
  221. if (response.error != -1)
  222. GUI::MessageBox::show_error(window(), String::formatted("Opening \"{}\" failed: {}", *response.chosen_file, strerror(response.error)));
  223. return;
  224. }
  225. if (editor().document().is_modified()) {
  226. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  227. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  228. m_save_action->activate();
  229. if (save_document_first_result != GUI::Dialog::ExecResult::ExecNo && editor().document().is_modified())
  230. return;
  231. }
  232. read_file_and_close(*response.fd, *response.chosen_file);
  233. });
  234. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  235. auto response = FileSystemAccessClient::Client::the().save_file(window()->window_id(), m_name, m_extension);
  236. if (response.error != 0) {
  237. if (response.error != -1)
  238. GUI::MessageBox::show_error(window(), String::formatted("Saving \"{}\" failed: {}", *response.chosen_file, strerror(response.error)));
  239. return;
  240. }
  241. if (!m_editor->write_to_file_and_close(*response.fd)) {
  242. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  243. return;
  244. }
  245. // FIXME: It would be cool if this would propagate from GUI::TextDocument somehow.
  246. window()->set_modified(false);
  247. set_path(*response.chosen_file);
  248. dbgln("Wrote document to {}", *response.chosen_file);
  249. });
  250. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  251. if (!m_path.is_empty()) {
  252. auto response = FileSystemAccessClient::Client::the().request_file(window()->window_id(), m_path, Core::OpenMode::Truncate | Core::OpenMode::WriteOnly);
  253. if (response.error != 0) {
  254. if (response.error != -1)
  255. GUI::MessageBox::show_error(window(), String::formatted("Unable to save file: {}", strerror(response.error)));
  256. return;
  257. }
  258. int fd = *response.fd;
  259. if (!m_editor->write_to_file_and_close(fd)) {
  260. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  261. } else {
  262. // FIXME: It would be cool if this would propagate from GUI::TextDocument somehow.
  263. window()->set_modified(false);
  264. update_title();
  265. }
  266. return;
  267. }
  268. m_save_as_action->activate();
  269. });
  270. m_toolbar->add_action(*m_new_action);
  271. m_toolbar->add_action(*m_open_action);
  272. m_toolbar->add_action(*m_save_action);
  273. m_toolbar->add_separator();
  274. m_toolbar->add_action(m_editor->cut_action());
  275. m_toolbar->add_action(m_editor->copy_action());
  276. m_toolbar->add_action(m_editor->paste_action());
  277. m_toolbar->add_action(m_editor->delete_action());
  278. m_toolbar->add_separator();
  279. m_toolbar->add_action(m_editor->undo_action());
  280. m_toolbar->add_action(m_editor->redo_action());
  281. }
  282. MainWidget::~MainWidget()
  283. {
  284. }
  285. Web::OutOfProcessWebView& MainWidget::ensure_web_view()
  286. {
  287. if (!m_page_view) {
  288. auto& web_view_container = *find_descendant_of_type_named<GUI::Widget>("web_view_container");
  289. m_page_view = web_view_container.add<Web::OutOfProcessWebView>();
  290. m_page_view->on_link_hover = [this](auto& url) {
  291. if (url.is_valid())
  292. m_statusbar->set_text(url.to_string());
  293. else
  294. update_statusbar();
  295. };
  296. m_page_view->on_link_click = [&](auto& url, auto&, unsigned) {
  297. if (!Desktop::Launcher::open(url)) {
  298. GUI::MessageBox::show(
  299. window(),
  300. String::formatted("The link to '{}' could not be opened.", url),
  301. "Failed to open link",
  302. GUI::MessageBox::Type::Error);
  303. }
  304. };
  305. }
  306. return *m_page_view;
  307. }
  308. void MainWidget::initialize_menubar(GUI::Window& window)
  309. {
  310. auto& file_menu = window.add_menu("&File");
  311. file_menu.add_action(*m_new_action);
  312. file_menu.add_action(*m_open_action);
  313. file_menu.add_action(*m_save_action);
  314. file_menu.add_action(*m_save_as_action);
  315. file_menu.add_separator();
  316. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  317. if (!request_close())
  318. return;
  319. GUI::Application::the()->quit();
  320. }));
  321. auto& edit_menu = window.add_menu("&Edit");
  322. edit_menu.add_action(m_editor->undo_action());
  323. edit_menu.add_action(m_editor->redo_action());
  324. edit_menu.add_separator();
  325. edit_menu.add_action(m_editor->cut_action());
  326. edit_menu.add_action(m_editor->copy_action());
  327. edit_menu.add_action(m_editor->paste_action());
  328. edit_menu.add_action(m_editor->delete_action());
  329. edit_menu.add_separator();
  330. edit_menu.add_action(*m_vim_emulation_setting_action);
  331. edit_menu.add_separator();
  332. edit_menu.add_action(*m_find_replace_action);
  333. edit_menu.add_action(*m_find_next_action);
  334. edit_menu.add_action(*m_find_previous_action);
  335. edit_menu.add_action(*m_replace_action);
  336. edit_menu.add_action(*m_replace_all_action);
  337. m_no_preview_action = GUI::Action::create_checkable(
  338. "&No Preview", [this](auto&) {
  339. set_preview_mode(PreviewMode::None);
  340. });
  341. m_markdown_preview_action = GUI::Action::create_checkable(
  342. "&Markdown Preview", [this](auto&) {
  343. set_preview_mode(PreviewMode::Markdown);
  344. },
  345. this);
  346. m_html_preview_action = GUI::Action::create_checkable(
  347. "&HTML Preview", [this](auto&) {
  348. set_preview_mode(PreviewMode::HTML);
  349. },
  350. this);
  351. m_preview_actions.add_action(*m_no_preview_action);
  352. m_preview_actions.add_action(*m_markdown_preview_action);
  353. m_preview_actions.add_action(*m_html_preview_action);
  354. m_preview_actions.set_exclusive(true);
  355. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  356. action.is_checked() ? m_toolbar_container->set_visible(true) : m_toolbar_container->set_visible(false);
  357. Config::write_bool("TextEditor", "Layout", "ShowToolbar", action.is_checked());
  358. });
  359. auto show_toolbar = Config::read_bool("TextEditor", "Layout", "ShowToolbar", true);
  360. m_layout_toolbar_action->set_checked(show_toolbar);
  361. m_toolbar_container->set_visible(show_toolbar);
  362. m_layout_statusbar_action = GUI::Action::create_checkable("&Status Bar", [&](auto& action) {
  363. action.is_checked() ? m_statusbar->set_visible(true) : m_statusbar->set_visible(false);
  364. Config::write_bool("TextEditor", "Layout", "ShowStatusbar", action.is_checked());
  365. });
  366. auto show_statusbar = Config::read_bool("TextEditor", "Layout", "ShowStatusbar", true);
  367. m_layout_statusbar_action->set_checked(show_statusbar);
  368. m_statusbar->set_visible(show_statusbar);
  369. m_layout_ruler_action = GUI::Action::create_checkable("Ruler", [&](auto& action) {
  370. action.is_checked() ? m_editor->set_ruler_visible(true) : m_editor->set_ruler_visible(false);
  371. Config::write_bool("TextEditor", "Layout", "ShowRuler", action.is_checked());
  372. });
  373. auto show_ruler = Config::read_bool("TextEditor", "Layout", "ShowRuler", true);
  374. m_layout_ruler_action->set_checked(show_ruler);
  375. m_editor->set_ruler_visible(show_ruler);
  376. auto& view_menu = window.add_menu("&View");
  377. auto& layout_menu = view_menu.add_submenu("&Layout");
  378. layout_menu.add_action(*m_layout_toolbar_action);
  379. layout_menu.add_action(*m_layout_statusbar_action);
  380. layout_menu.add_action(*m_layout_ruler_action);
  381. view_menu.add_separator();
  382. view_menu.add_action(GUI::Action::create("Editor &Font...", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-font-editor.png"),
  383. [&](auto&) {
  384. auto picker = GUI::FontPicker::construct(&window, &m_editor->font(), false);
  385. if (picker->exec() == GUI::Dialog::ExecOK) {
  386. dbgln("setting font {}", picker->font()->qualified_name());
  387. m_editor->set_font(picker->font());
  388. }
  389. }));
  390. view_menu.add_separator();
  391. m_wrapping_mode_actions.set_exclusive(true);
  392. auto& wrapping_mode_menu = view_menu.add_submenu("&Wrapping Mode");
  393. m_no_wrapping_action = GUI::Action::create_checkable("&No Wrapping", [&](auto&) {
  394. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  395. });
  396. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap &Anywhere", [&](auto&) {
  397. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  398. });
  399. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at &Words", [&](auto&) {
  400. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  401. });
  402. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  403. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  404. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  405. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  406. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  407. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  408. m_no_wrapping_action->set_checked(true);
  409. view_menu.add_separator();
  410. m_soft_tab_width_actions.set_exclusive(true);
  411. auto& soft_tab_width_menu = view_menu.add_submenu("&Tab Width");
  412. m_soft_tab_1_width_action = GUI::Action::create_checkable("1", [&](auto&) {
  413. m_editor->set_soft_tab_width(1);
  414. });
  415. m_soft_tab_2_width_action = GUI::Action::create_checkable("2", [&](auto&) {
  416. m_editor->set_soft_tab_width(2);
  417. });
  418. m_soft_tab_4_width_action = GUI::Action::create_checkable("4", [&](auto&) {
  419. m_editor->set_soft_tab_width(4);
  420. });
  421. m_soft_tab_8_width_action = GUI::Action::create_checkable("8", [&](auto&) {
  422. m_editor->set_soft_tab_width(8);
  423. });
  424. m_soft_tab_16_width_action = GUI::Action::create_checkable("16", [&](auto&) {
  425. m_editor->set_soft_tab_width(16);
  426. });
  427. m_soft_tab_width_actions.add_action(*m_soft_tab_1_width_action);
  428. m_soft_tab_width_actions.add_action(*m_soft_tab_2_width_action);
  429. m_soft_tab_width_actions.add_action(*m_soft_tab_4_width_action);
  430. m_soft_tab_width_actions.add_action(*m_soft_tab_8_width_action);
  431. m_soft_tab_width_actions.add_action(*m_soft_tab_16_width_action);
  432. soft_tab_width_menu.add_action(*m_soft_tab_1_width_action);
  433. soft_tab_width_menu.add_action(*m_soft_tab_2_width_action);
  434. soft_tab_width_menu.add_action(*m_soft_tab_4_width_action);
  435. soft_tab_width_menu.add_action(*m_soft_tab_8_width_action);
  436. soft_tab_width_menu.add_action(*m_soft_tab_16_width_action);
  437. m_soft_tab_4_width_action->set_checked(true);
  438. view_menu.add_separator();
  439. m_visualize_trailing_whitespace_action = GUI::Action::create_checkable("&Visualize Trailing Whitespace", [&](auto&) {
  440. m_editor->set_visualize_trailing_whitespace(m_visualize_trailing_whitespace_action->is_checked());
  441. });
  442. m_visualize_leading_whitespace_action = GUI::Action::create_checkable("Visualize &Leading Whitespace", [&](auto&) {
  443. m_editor->set_visualize_leading_whitespace(m_visualize_leading_whitespace_action->is_checked());
  444. });
  445. m_visualize_trailing_whitespace_action->set_checked(true);
  446. view_menu.add_action(*m_visualize_trailing_whitespace_action);
  447. view_menu.add_action(*m_visualize_leading_whitespace_action);
  448. view_menu.add_separator();
  449. view_menu.add_action(*m_no_preview_action);
  450. view_menu.add_action(*m_markdown_preview_action);
  451. view_menu.add_action(*m_html_preview_action);
  452. m_no_preview_action->set_checked(true);
  453. view_menu.add_separator();
  454. syntax_actions.set_exclusive(true);
  455. auto& syntax_menu = view_menu.add_submenu("&Syntax");
  456. m_plain_text_highlight = GUI::Action::create_checkable("&Plain Text", [&](auto&) {
  457. m_editor->set_syntax_highlighter({});
  458. m_editor->update();
  459. });
  460. m_plain_text_highlight->set_checked(true);
  461. syntax_actions.add_action(*m_plain_text_highlight);
  462. syntax_menu.add_action(*m_plain_text_highlight);
  463. m_cpp_highlight = GUI::Action::create_checkable("&C++", [&](auto&) {
  464. m_editor->set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  465. m_editor->update();
  466. });
  467. syntax_actions.add_action(*m_cpp_highlight);
  468. syntax_menu.add_action(*m_cpp_highlight);
  469. m_js_highlight = GUI::Action::create_checkable("&JavaScript", [&](auto&) {
  470. m_editor->set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  471. m_editor->update();
  472. });
  473. syntax_actions.add_action(*m_js_highlight);
  474. syntax_menu.add_action(*m_js_highlight);
  475. m_html_highlight = GUI::Action::create_checkable("&HTML File", [&](auto&) {
  476. m_editor->set_syntax_highlighter(make<Web::HTML::SyntaxHighlighter>());
  477. m_editor->update();
  478. });
  479. syntax_actions.add_action(*m_html_highlight);
  480. syntax_menu.add_action(*m_html_highlight);
  481. m_gml_highlight = GUI::Action::create_checkable("&GML", [&](auto&) {
  482. m_editor->set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  483. m_editor->update();
  484. });
  485. syntax_actions.add_action(*m_gml_highlight);
  486. syntax_menu.add_action(*m_gml_highlight);
  487. m_ini_highlight = GUI::Action::create_checkable("&INI File", [&](auto&) {
  488. m_editor->set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  489. m_editor->update();
  490. });
  491. syntax_actions.add_action(*m_ini_highlight);
  492. syntax_menu.add_action(*m_ini_highlight);
  493. m_shell_highlight = GUI::Action::create_checkable("&Shell File", [&](auto&) {
  494. m_editor->set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  495. m_editor->update();
  496. });
  497. syntax_actions.add_action(*m_shell_highlight);
  498. syntax_menu.add_action(*m_shell_highlight);
  499. m_sql_highlight = GUI::Action::create_checkable("S&QL File", [&](auto&) {
  500. m_editor->set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
  501. m_editor->update();
  502. });
  503. syntax_actions.add_action(*m_sql_highlight);
  504. syntax_menu.add_action(*m_sql_highlight);
  505. auto& help_menu = window.add_menu("&Help");
  506. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  507. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/TextEditor.md"), "/bin/Help");
  508. }));
  509. help_menu.add_action(GUI::CommonActions::make_about_action("Text Editor", GUI::Icon::default_icon("app-text-editor"), &window));
  510. }
  511. void MainWidget::set_path(StringView const& path)
  512. {
  513. if (path.is_empty()) {
  514. m_path = {};
  515. m_name = {};
  516. m_extension = {};
  517. } else {
  518. auto lexical_path = LexicalPath(path);
  519. m_path = lexical_path.string();
  520. m_name = lexical_path.title();
  521. m_extension = lexical_path.extension();
  522. }
  523. if (m_extension == "c" || m_extension == "cc" || m_extension == "cxx" || m_extension == "cpp" || m_extension == "c++"
  524. || m_extension == "h" || m_extension == "hh" || m_extension == "hxx" || m_extension == "hpp" || m_extension == "h++") {
  525. m_cpp_highlight->activate();
  526. } else if (m_extension == "js" || m_extension == "mjs" || m_extension == "json") {
  527. m_js_highlight->activate();
  528. } else if (m_extension == "gml") {
  529. m_gml_highlight->activate();
  530. } else if (m_extension == "ini") {
  531. m_ini_highlight->activate();
  532. } else if (m_extension == "sh" || m_extension == "bash") {
  533. m_shell_highlight->activate();
  534. } else if (m_extension == "sql") {
  535. m_sql_highlight->activate();
  536. } else if (m_extension == "html" || m_extension == "htm") {
  537. m_html_highlight->activate();
  538. } else {
  539. m_plain_text_highlight->activate();
  540. }
  541. if (m_auto_detect_preview_mode) {
  542. if (m_extension == "md")
  543. set_preview_mode(PreviewMode::Markdown);
  544. else if (m_extension == "html" || m_extension == "htm")
  545. set_preview_mode(PreviewMode::HTML);
  546. else
  547. set_preview_mode(PreviewMode::None);
  548. }
  549. update_title();
  550. }
  551. void MainWidget::update_title()
  552. {
  553. StringBuilder builder;
  554. if (m_path.is_empty())
  555. builder.append("Untitled");
  556. else
  557. builder.append(m_path);
  558. builder.append("[*] - Text Editor");
  559. window()->set_title(builder.to_string());
  560. }
  561. bool MainWidget::read_file_and_close(int fd, String const& path)
  562. {
  563. VERIFY(path.starts_with("/"sv));
  564. auto file = Core::File::construct();
  565. if (!file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::Yes) && file->error() != ENOENT) {
  566. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  567. return false;
  568. }
  569. if (file->is_device()) {
  570. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: Can't open device files", path), "Error", GUI::MessageBox::Type::Error);
  571. return false;
  572. }
  573. if (file->is_directory()) {
  574. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: Can't open directories", path), "Error", GUI::MessageBox::Type::Error);
  575. return false;
  576. }
  577. m_editor->set_text(file->read_all());
  578. set_path(path);
  579. m_editor->set_focus(true);
  580. return true;
  581. }
  582. void MainWidget::open_nonexistent_file(String const& path)
  583. {
  584. m_editor->set_text({});
  585. set_path(path);
  586. m_editor->set_focus(true);
  587. }
  588. bool MainWidget::request_close()
  589. {
  590. if (!editor().document().is_modified())
  591. return true;
  592. auto result = GUI::MessageBox::show(window(), "The document has been modified. Would you like to save?", "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  593. if (result == GUI::MessageBox::ExecYes) {
  594. m_save_action->activate();
  595. if (editor().document().is_modified())
  596. return false;
  597. return true;
  598. }
  599. if (result == GUI::MessageBox::ExecNo)
  600. return true;
  601. return false;
  602. }
  603. void MainWidget::drop_event(GUI::DropEvent& event)
  604. {
  605. event.accept();
  606. window()->move_to_front();
  607. if (event.mime_data().has_urls()) {
  608. auto urls = event.mime_data().urls();
  609. if (urls.is_empty())
  610. return;
  611. if (urls.size() > 1) {
  612. GUI::MessageBox::show(window(), "TextEditor can only open one file at a time!", "One at a time please!", GUI::MessageBox::Type::Error);
  613. return;
  614. }
  615. // TODO: A drop event should be considered user consent for opening a file
  616. auto file_response = FileSystemAccessClient::Client::the().request_file(window()->window_id(), urls.first().path(), Core::OpenMode::ReadOnly);
  617. if (file_response.error != 0)
  618. return;
  619. read_file_and_close(*file_response.fd, urls.first().path());
  620. }
  621. }
  622. void MainWidget::set_web_view_visible(bool visible)
  623. {
  624. if (!visible && !m_page_view)
  625. return;
  626. ensure_web_view();
  627. auto& web_view_container = *find_descendant_of_type_named<GUI::Widget>("web_view_container");
  628. web_view_container.set_visible(visible);
  629. }
  630. void MainWidget::set_preview_mode(PreviewMode mode)
  631. {
  632. if (m_preview_mode == mode)
  633. return;
  634. m_preview_mode = mode;
  635. if (m_preview_mode == PreviewMode::HTML) {
  636. m_html_preview_action->set_checked(true);
  637. set_web_view_visible(true);
  638. update_html_preview();
  639. } else if (m_preview_mode == PreviewMode::Markdown) {
  640. m_markdown_preview_action->set_checked(true);
  641. set_web_view_visible(true);
  642. update_markdown_preview();
  643. } else {
  644. m_no_preview_action->set_checked(true);
  645. m_editor->set_fixed_width(-1);
  646. set_web_view_visible(false);
  647. }
  648. }
  649. void MainWidget::update_preview()
  650. {
  651. switch (m_preview_mode) {
  652. case PreviewMode::Markdown:
  653. update_markdown_preview();
  654. break;
  655. case PreviewMode::HTML:
  656. update_html_preview();
  657. break;
  658. default:
  659. break;
  660. }
  661. }
  662. void MainWidget::update_markdown_preview()
  663. {
  664. auto document = Markdown::Document::parse(m_editor->text());
  665. if (document) {
  666. auto html = document->render_to_html();
  667. auto current_scroll_pos = m_page_view->visible_content_rect();
  668. m_page_view->load_html(html, URL::create_with_file_protocol(m_path));
  669. m_page_view->scroll_into_view(current_scroll_pos, true, true);
  670. }
  671. }
  672. void MainWidget::update_html_preview()
  673. {
  674. auto current_scroll_pos = m_page_view->visible_content_rect();
  675. m_page_view->load_html(m_editor->text(), URL::create_with_file_protocol(m_path));
  676. m_page_view->scroll_into_view(current_scroll_pos, true, true);
  677. }
  678. void MainWidget::update_statusbar()
  679. {
  680. StringBuilder builder;
  681. builder.appendff("Line: {}, Column: {}", m_editor->cursor().line() + 1, m_editor->cursor().column());
  682. if (m_editor->has_selection()) {
  683. String selected_text = m_editor->selected_text();
  684. auto word_count = m_editor->number_of_selected_words();
  685. builder.appendff(" Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  686. }
  687. m_statusbar->set_text(builder.to_string());
  688. }
  689. }