MainWidget.cpp 35 KB

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