TextEditorWidget.cpp 30 KB

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