MainWidget.cpp 36 KB

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