TextEditorWidget.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. /*
  2. * Copyright (c) 2018-2020, 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 <LibJS/SyntaxHighlighter.h>
  61. #include <LibMarkdown/Document.h>
  62. #include <LibWeb/OutOfProcessWebView.h>
  63. #include <Shell/SyntaxHighlighter.h>
  64. TextEditorWidget::TextEditorWidget()
  65. {
  66. load_from_gml(text_editor_window_gml);
  67. m_config = Core::ConfigFile::get_for_app("TextEditor");
  68. m_toolbar = *find_descendant_of_type_named<GUI::ToolBar>("toolbar");
  69. m_toolbar_container = *find_descendant_of_type_named<GUI::ToolBarContainer>("toolbar_container");
  70. m_editor = *find_descendant_of_type_named<GUI::TextEditor>("editor");
  71. m_editor->set_ruler_visible(true);
  72. m_editor->set_automatic_indentation_enabled(true);
  73. m_editor->set_editing_engine(make<GUI::RegularEditingEngine>());
  74. m_editor->on_change = [this] {
  75. update_preview();
  76. // Do not mark as dirty on the first change (When document is first opened.)
  77. if (m_document_opening) {
  78. m_document_opening = false;
  79. return;
  80. }
  81. bool was_dirty = m_document_dirty;
  82. m_document_dirty = true;
  83. if (!was_dirty)
  84. update_title();
  85. };
  86. m_page_view = *find_descendant_of_type_named<Web::OutOfProcessWebView>("webview");
  87. m_page_view->on_link_hover = [this](auto& url) {
  88. if (url.is_valid())
  89. m_statusbar->set_text(url.to_string());
  90. else
  91. update_statusbar();
  92. };
  93. m_page_view->on_link_click = [&](auto& url, auto&, unsigned) {
  94. if (!Desktop::Launcher::open(url)) {
  95. GUI::MessageBox::show(
  96. window(),
  97. String::formatted("The link to '{}' could not be opened.", url),
  98. "Failed to open link",
  99. GUI::MessageBox::Type::Error);
  100. }
  101. };
  102. m_find_replace_widget = *find_descendant_of_type_named<GUI::GroupBox>("find_replace_widget");
  103. m_find_widget = *find_descendant_of_type_named<GUI::Widget>("find_widget");
  104. m_replace_widget = *find_descendant_of_type_named<GUI::Widget>("replace_widget");
  105. m_find_textbox = *find_descendant_of_type_named<GUI::TextBox>("find_textbox");
  106. m_find_textbox->set_placeholder("Find");
  107. m_replace_textbox = *find_descendant_of_type_named<GUI::TextBox>("replace_textbox");
  108. m_replace_textbox->set_placeholder("Replace");
  109. m_match_case_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("match_case_checkbox");
  110. m_match_case_checkbox->on_checked = [this] {
  111. m_match_case = m_match_case_checkbox->is_checked();
  112. };
  113. m_match_case_checkbox->set_checked(true);
  114. m_regex_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("regex_checkbox");
  115. m_regex_checkbox->on_checked = [this] {
  116. m_use_regex = m_regex_checkbox->is_checked();
  117. };
  118. m_regex_checkbox->set_checked(false);
  119. m_wrap_around_checkbox = *find_descendant_of_type_named<GUI::CheckBox>("wrap_around_checkbox");
  120. m_wrap_around_checkbox->on_checked = [this] {
  121. m_should_wrap = m_wrap_around_checkbox->is_checked();
  122. };
  123. m_wrap_around_checkbox->set_checked(true);
  124. 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&) {
  125. auto needle = m_find_textbox->text();
  126. if (needle.is_empty())
  127. return;
  128. if (m_use_regex)
  129. m_editor->document().update_regex_matches(needle);
  130. 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);
  131. dbgln("find_next('{}') returned {}", needle, found_range);
  132. if (found_range.is_valid()) {
  133. m_editor->set_selection(found_range);
  134. } else {
  135. GUI::MessageBox::show(window(),
  136. String::formatted("Not found: \"{}\"", needle),
  137. "Not found",
  138. GUI::MessageBox::Type::Information);
  139. }
  140. });
  141. 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&) {
  142. auto needle = m_find_textbox->text();
  143. if (needle.is_empty())
  144. return;
  145. if (m_use_regex)
  146. m_editor->document().update_regex_matches(needle);
  147. auto selection_start = m_editor->normalized_selection().start();
  148. if (!selection_start.is_valid())
  149. selection_start = m_editor->normalized_selection().end();
  150. 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);
  151. dbgln("find_prev(\"{}\") returned {}", needle, found_range);
  152. if (found_range.is_valid()) {
  153. m_editor->set_selection(found_range);
  154. } else {
  155. GUI::MessageBox::show(window(),
  156. String::formatted("Not found: \"{}\"", needle),
  157. "Not found",
  158. GUI::MessageBox::Type::Information);
  159. }
  160. });
  161. m_replace_action = GUI::Action::create("Replace", { Mod_Ctrl, Key_F1 }, [&](auto&) {
  162. auto needle = m_find_textbox->text();
  163. auto substitute = m_replace_textbox->text();
  164. if (needle.is_empty())
  165. return;
  166. if (m_use_regex)
  167. m_editor->document().update_regex_matches(needle);
  168. 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);
  169. if (found_range.is_valid()) {
  170. m_editor->set_selection(found_range);
  171. m_editor->insert_at_cursor_or_replace_selection(substitute);
  172. } else {
  173. GUI::MessageBox::show(window(),
  174. String::formatted("Not found: \"{}\"", needle),
  175. "Not found",
  176. GUI::MessageBox::Type::Information);
  177. }
  178. });
  179. m_replace_all_action = GUI::Action::create("Replace all", { Mod_Ctrl, Key_F2 }, [&](auto&) {
  180. auto needle = m_find_textbox->text();
  181. auto substitute = m_replace_textbox->text();
  182. if (needle.is_empty())
  183. return;
  184. if (m_use_regex)
  185. m_editor->document().update_regex_matches(needle);
  186. auto found_range = m_editor->document().find_next(needle, {}, GUI::TextDocument::SearchShouldWrap::Yes, m_use_regex, m_match_case);
  187. while (found_range.is_valid()) {
  188. m_editor->set_selection(found_range);
  189. m_editor->insert_at_cursor_or_replace_selection(substitute);
  190. found_range = m_editor->document().find_next(needle, {}, GUI::TextDocument::SearchShouldWrap::Yes, m_use_regex, m_match_case);
  191. }
  192. });
  193. m_find_previous_button = *find_descendant_of_type_named<GUI::Button>("find_previous_button");
  194. m_find_previous_button->set_action(*m_find_previous_action);
  195. m_find_previous_button->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/find-previous.png"));
  196. m_find_next_button = *find_descendant_of_type_named<GUI::Button>("find_next_button");
  197. m_find_next_button->set_action(*m_find_next_action);
  198. m_find_next_button->set_icon(Gfx::Bitmap::load_from_file("/res/icons/16x16/find-next.png"));
  199. m_find_textbox->on_return_pressed = [this] {
  200. m_find_next_button->click();
  201. };
  202. m_find_textbox->on_escape_pressed = [this] {
  203. m_find_replace_widget->set_visible(false);
  204. m_editor->set_focus(true);
  205. };
  206. m_replace_button = *find_descendant_of_type_named<GUI::Button>("replace_button");
  207. m_replace_button->set_action(*m_replace_action);
  208. m_replace_all_button = *find_descendant_of_type_named<GUI::Button>("replace_all_button");
  209. m_replace_all_button->set_action(*m_replace_all_action);
  210. m_replace_textbox->on_return_pressed = [this] {
  211. m_replace_button->click();
  212. };
  213. m_replace_textbox->on_escape_pressed = [this] {
  214. m_find_replace_widget->set_visible(false);
  215. m_editor->set_focus(true);
  216. };
  217. m_vim_emulation_setting_action = GUI::Action::create_checkable("Vim emulation", { Mod_Ctrl | Mod_Shift | Mod_Alt, Key_V }, [&](auto& action) {
  218. if (action.is_checked())
  219. m_editor->set_editing_engine(make<GUI::VimEditingEngine>());
  220. else
  221. m_editor->set_editing_engine(make<GUI::RegularEditingEngine>());
  222. });
  223. m_vim_emulation_setting_action->set_checked(false);
  224. 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&) {
  225. m_find_replace_widget->set_visible(true);
  226. m_find_widget->set_visible(true);
  227. m_replace_widget->set_visible(true);
  228. m_find_textbox->set_focus(true);
  229. if (m_editor->has_selection()) {
  230. auto selected_text = m_editor->document().text_in_range(m_editor->normalized_selection());
  231. m_find_textbox->set_text(selected_text);
  232. }
  233. m_find_textbox->select_all();
  234. });
  235. m_editor->add_custom_context_menu_action(*m_find_replace_action);
  236. m_editor->add_custom_context_menu_action(*m_find_next_action);
  237. m_editor->add_custom_context_menu_action(*m_find_previous_action);
  238. m_statusbar = *find_descendant_of_type_named<GUI::StatusBar>("statusbar");
  239. m_editor->on_cursor_change = [this] { update_statusbar(); };
  240. m_editor->on_selection_change = [this] { update_statusbar(); };
  241. 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&) {
  242. if (m_document_dirty) {
  243. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  244. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  245. m_save_action->activate();
  246. if (save_document_first_result == GUI::Dialog::ExecResult::ExecCancel)
  247. return;
  248. }
  249. m_document_dirty = false;
  250. m_editor->set_text(StringView());
  251. set_path(LexicalPath());
  252. update_title();
  253. });
  254. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  255. Optional<String> open_path = GUI::FilePicker::get_open_filepath(window());
  256. if (!open_path.has_value())
  257. return;
  258. if (m_document_dirty) {
  259. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  260. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  261. m_save_action->activate();
  262. if (save_document_first_result == GUI::Dialog::ExecResult::ExecCancel)
  263. return;
  264. }
  265. open_file(open_path.value());
  266. });
  267. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  268. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(), m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "txt" : m_extension);
  269. if (!save_path.has_value())
  270. return;
  271. if (!m_editor->write_to_file(save_path.value())) {
  272. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  273. return;
  274. }
  275. m_document_dirty = false;
  276. set_path(LexicalPath(save_path.value()));
  277. dbgln("Wrote document to {}", save_path.value());
  278. });
  279. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  280. if (!m_path.is_empty()) {
  281. if (!m_editor->write_to_file(m_path)) {
  282. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  283. } else {
  284. m_document_dirty = false;
  285. update_title();
  286. }
  287. return;
  288. }
  289. m_save_as_action->activate();
  290. });
  291. m_toolbar->add_action(*m_new_action);
  292. m_toolbar->add_action(*m_open_action);
  293. m_toolbar->add_action(*m_save_action);
  294. m_toolbar->add_separator();
  295. m_toolbar->add_action(m_editor->cut_action());
  296. m_toolbar->add_action(m_editor->copy_action());
  297. m_toolbar->add_action(m_editor->paste_action());
  298. m_toolbar->add_action(m_editor->delete_action());
  299. m_toolbar->add_separator();
  300. m_toolbar->add_action(m_editor->undo_action());
  301. m_toolbar->add_action(m_editor->redo_action());
  302. }
  303. TextEditorWidget::~TextEditorWidget()
  304. {
  305. }
  306. void TextEditorWidget::initialize_menubar(GUI::MenuBar& menubar)
  307. {
  308. auto& app_menu = menubar.add_menu("Text Editor");
  309. app_menu.add_action(*m_new_action);
  310. app_menu.add_action(*m_open_action);
  311. app_menu.add_action(*m_save_action);
  312. app_menu.add_action(*m_save_as_action);
  313. app_menu.add_separator();
  314. app_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  315. if (!request_close())
  316. return;
  317. GUI::Application::the()->quit();
  318. }));
  319. auto& edit_menu = menubar.add_menu("Edit");
  320. edit_menu.add_action(m_editor->undo_action());
  321. edit_menu.add_action(m_editor->redo_action());
  322. edit_menu.add_separator();
  323. edit_menu.add_action(m_editor->cut_action());
  324. edit_menu.add_action(m_editor->copy_action());
  325. edit_menu.add_action(m_editor->paste_action());
  326. edit_menu.add_action(m_editor->delete_action());
  327. edit_menu.add_separator();
  328. edit_menu.add_action(*m_vim_emulation_setting_action);
  329. edit_menu.add_separator();
  330. edit_menu.add_action(*m_find_replace_action);
  331. edit_menu.add_action(*m_find_next_action);
  332. edit_menu.add_action(*m_find_previous_action);
  333. edit_menu.add_action(*m_replace_action);
  334. edit_menu.add_action(*m_replace_all_action);
  335. m_no_preview_action = GUI::Action::create_checkable(
  336. "No preview", [this](auto&) {
  337. set_preview_mode(PreviewMode::None);
  338. });
  339. m_markdown_preview_action = GUI::Action::create_checkable(
  340. "Markdown preview", [this](auto&) {
  341. set_preview_mode(PreviewMode::Markdown);
  342. },
  343. this);
  344. m_html_preview_action = GUI::Action::create_checkable(
  345. "HTML preview", [this](auto&) {
  346. set_preview_mode(PreviewMode::HTML);
  347. },
  348. this);
  349. m_preview_actions.add_action(*m_no_preview_action);
  350. m_preview_actions.add_action(*m_markdown_preview_action);
  351. m_preview_actions.add_action(*m_html_preview_action);
  352. m_preview_actions.set_exclusive(true);
  353. m_layout_toolbar_action = GUI::Action::create_checkable("Toolbar", [&](auto& action) {
  354. action.is_checked() ? m_toolbar_container->set_visible(true) : m_toolbar_container->set_visible(false);
  355. m_config->write_bool_entry("Layout", "ShowToolbar", action.is_checked());
  356. m_config->sync();
  357. });
  358. auto show_toolbar = m_config->read_bool_entry("Layout", "ShowToolbar", true);
  359. m_layout_toolbar_action->set_checked(show_toolbar);
  360. m_toolbar_container->set_visible(show_toolbar);
  361. m_layout_statusbar_action = GUI::Action::create_checkable("Status bar", [&](auto& action) {
  362. action.is_checked() ? m_statusbar->set_visible(true) : m_statusbar->set_visible(false);
  363. m_config->write_bool_entry("Layout", "ShowStatusBar", action.is_checked());
  364. m_config->sync();
  365. });
  366. auto show_statusbar = m_config->read_bool_entry("Layout", "ShowStatusBar", true);
  367. m_layout_statusbar_action->set_checked(show_statusbar);
  368. m_statusbar->set_visible(show_statusbar);
  369. m_layout_ruler_action = GUI::Action::create_checkable("Ruler", [&](auto& action) {
  370. action.is_checked() ? m_editor->set_ruler_visible(true) : m_editor->set_ruler_visible(false);
  371. m_config->write_bool_entry("Layout", "ShowRuler", action.is_checked());
  372. m_config->sync();
  373. });
  374. auto show_ruler = m_config->read_bool_entry("Layout", "ShowRuler", true);
  375. m_layout_ruler_action->set_checked(show_ruler);
  376. m_editor->set_ruler_visible(show_ruler);
  377. auto& view_menu = menubar.add_menu("View");
  378. auto& layout_menu = view_menu.add_submenu("Layout");
  379. layout_menu.add_action(*m_layout_toolbar_action);
  380. layout_menu.add_action(*m_layout_statusbar_action);
  381. layout_menu.add_action(*m_layout_ruler_action);
  382. view_menu.add_separator();
  383. view_menu.add_action(GUI::Action::create("Editor font...", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-font-editor.png"),
  384. [&](auto&) {
  385. auto picker = GUI::FontPicker::construct(window(), &m_editor->font(), false);
  386. if (picker->exec() == GUI::Dialog::ExecOK) {
  387. dbgln("setting font {}", picker->font()->qualified_name());
  388. m_editor->set_font(picker->font());
  389. }
  390. }));
  391. view_menu.add_separator();
  392. m_wrapping_mode_actions.set_exclusive(true);
  393. auto& wrapping_mode_menu = view_menu.add_submenu("Wrapping mode");
  394. m_no_wrapping_action = GUI::Action::create_checkable("No wrapping", [&](auto&) {
  395. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  396. });
  397. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap anywhere", [&](auto&) {
  398. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  399. });
  400. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at words", [&](auto&) {
  401. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  402. });
  403. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  404. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  405. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  406. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  407. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  408. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  409. m_no_wrapping_action->set_checked(true);
  410. view_menu.add_separator();
  411. view_menu.add_action(*m_no_preview_action);
  412. view_menu.add_action(*m_markdown_preview_action);
  413. view_menu.add_action(*m_html_preview_action);
  414. m_no_preview_action->set_checked(true);
  415. view_menu.add_separator();
  416. syntax_actions.set_exclusive(true);
  417. auto& syntax_menu = view_menu.add_submenu("Syntax");
  418. m_plain_text_highlight = GUI::Action::create_checkable("Plain text", [&](auto&) {
  419. m_editor->set_syntax_highlighter({});
  420. m_editor->update();
  421. });
  422. m_plain_text_highlight->set_checked(true);
  423. syntax_actions.add_action(*m_plain_text_highlight);
  424. syntax_menu.add_action(*m_plain_text_highlight);
  425. m_cpp_highlight = GUI::Action::create_checkable("C++", [&](auto&) {
  426. m_editor->set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  427. m_editor->update();
  428. });
  429. syntax_actions.add_action(*m_cpp_highlight);
  430. syntax_menu.add_action(*m_cpp_highlight);
  431. m_js_highlight = GUI::Action::create_checkable("JavaScript", [&](auto&) {
  432. m_editor->set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  433. m_editor->update();
  434. });
  435. syntax_actions.add_action(*m_js_highlight);
  436. syntax_menu.add_action(*m_js_highlight);
  437. m_gml_highlight = GUI::Action::create_checkable("GML", [&](auto&) {
  438. m_editor->set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  439. m_editor->update();
  440. });
  441. syntax_actions.add_action(*m_gml_highlight);
  442. syntax_menu.add_action(*m_gml_highlight);
  443. m_ini_highlight = GUI::Action::create_checkable("INI File", [&](auto&) {
  444. m_editor->set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  445. m_editor->update();
  446. });
  447. syntax_actions.add_action(*m_ini_highlight);
  448. syntax_menu.add_action(*m_ini_highlight);
  449. m_shell_highlight = GUI::Action::create_checkable("Shell File", [&](auto&) {
  450. m_editor->set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  451. m_editor->update();
  452. });
  453. syntax_actions.add_action(*m_shell_highlight);
  454. syntax_menu.add_action(*m_shell_highlight);
  455. auto& help_menu = menubar.add_menu("Help");
  456. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  457. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/TextEditor.md"), "/bin/Help");
  458. }));
  459. help_menu.add_action(GUI::CommonActions::make_about_action("Text Editor", GUI::Icon::default_icon("app-text-editor"), window()));
  460. }
  461. void TextEditorWidget::set_path(const LexicalPath& lexical_path)
  462. {
  463. m_path = lexical_path.string();
  464. m_name = lexical_path.title();
  465. m_extension = lexical_path.extension();
  466. if (m_extension == "c" || m_extension == "cc" || m_extension == "cxx" || m_extension == "cpp" || m_extension == "h") {
  467. m_cpp_highlight->activate();
  468. } else if (m_extension == "js" || m_extension == "json") {
  469. m_js_highlight->activate();
  470. } else if (m_extension == "gml") {
  471. m_gml_highlight->activate();
  472. } else if (m_extension == "ini") {
  473. m_ini_highlight->activate();
  474. } else {
  475. m_plain_text_highlight->activate();
  476. }
  477. if (m_auto_detect_preview_mode) {
  478. if (m_extension == "md")
  479. set_preview_mode(PreviewMode::Markdown);
  480. else if (m_extension == "html")
  481. set_preview_mode(PreviewMode::HTML);
  482. else
  483. set_preview_mode(PreviewMode::None);
  484. }
  485. update_title();
  486. }
  487. void TextEditorWidget::update_title()
  488. {
  489. StringBuilder builder;
  490. if (m_path.is_empty())
  491. builder.append("Untitled");
  492. else
  493. builder.append(m_path);
  494. if (m_document_dirty)
  495. builder.append(" (*)");
  496. builder.append(" - Text Editor");
  497. window()->set_title(builder.to_string());
  498. }
  499. void TextEditorWidget::open_file(const String& path)
  500. {
  501. auto file = Core::File::construct(path);
  502. if (!file->open(Core::IODevice::ReadOnly) && file->error() != ENOENT) {
  503. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  504. return;
  505. }
  506. m_editor->set_text(file->read_all());
  507. m_document_dirty = false;
  508. m_document_opening = true;
  509. set_path(LexicalPath(path));
  510. m_editor->set_focus(true);
  511. }
  512. bool TextEditorWidget::request_close()
  513. {
  514. if (!m_document_dirty)
  515. return true;
  516. 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);
  517. if (result == GUI::MessageBox::ExecYes) {
  518. m_save_action->activate();
  519. return true;
  520. }
  521. if (result == GUI::MessageBox::ExecNo)
  522. return true;
  523. return false;
  524. }
  525. void TextEditorWidget::drop_event(GUI::DropEvent& event)
  526. {
  527. event.accept();
  528. window()->move_to_front();
  529. if (event.mime_data().has_urls()) {
  530. auto urls = event.mime_data().urls();
  531. if (urls.is_empty())
  532. return;
  533. if (urls.size() > 1) {
  534. GUI::MessageBox::show(window(), "TextEditor can only open one file at a time!", "One at a time please!", GUI::MessageBox::Type::Error);
  535. return;
  536. }
  537. open_file(urls.first().path());
  538. }
  539. }
  540. void TextEditorWidget::set_preview_mode(PreviewMode mode)
  541. {
  542. if (m_preview_mode == mode)
  543. return;
  544. m_preview_mode = mode;
  545. if (m_preview_mode == PreviewMode::HTML) {
  546. m_html_preview_action->set_checked(true);
  547. m_page_view->set_visible(true);
  548. update_html_preview();
  549. } else if (m_preview_mode == PreviewMode::Markdown) {
  550. m_markdown_preview_action->set_checked(true);
  551. m_page_view->set_visible(true);
  552. update_markdown_preview();
  553. } else {
  554. m_no_preview_action->set_checked(true);
  555. m_page_view->set_visible(false);
  556. }
  557. }
  558. void TextEditorWidget::update_preview()
  559. {
  560. switch (m_preview_mode) {
  561. case PreviewMode::Markdown:
  562. update_markdown_preview();
  563. break;
  564. case PreviewMode::HTML:
  565. update_html_preview();
  566. break;
  567. default:
  568. break;
  569. }
  570. }
  571. void TextEditorWidget::update_markdown_preview()
  572. {
  573. auto document = Markdown::Document::parse(m_editor->text());
  574. if (document) {
  575. auto html = document->render_to_html();
  576. auto current_scroll_pos = m_page_view->visible_content_rect();
  577. m_page_view->load_html(html, URL::create_with_file_protocol(m_path));
  578. m_page_view->scroll_into_view(current_scroll_pos, true, true);
  579. }
  580. }
  581. void TextEditorWidget::update_html_preview()
  582. {
  583. auto current_scroll_pos = m_page_view->visible_content_rect();
  584. m_page_view->load_html(m_editor->text(), URL::create_with_file_protocol(m_path));
  585. m_page_view->scroll_into_view(current_scroll_pos, true, true);
  586. }
  587. void TextEditorWidget::update_statusbar()
  588. {
  589. StringBuilder builder;
  590. builder.appendff("Line: {}, Column: {}", m_editor->cursor().line() + 1, m_editor->cursor().column());
  591. if (m_editor->has_selection()) {
  592. int word_count = 0;
  593. bool in_word = false;
  594. String selected_text = m_editor->selected_text();
  595. for (char c : selected_text) {
  596. if (in_word && isspace(c)) {
  597. in_word = false;
  598. word_count++;
  599. continue;
  600. }
  601. if (!in_word && !isspace(c))
  602. in_word = true;
  603. }
  604. if (in_word)
  605. word_count++;
  606. builder.appendff(" Selected: {} {} ({} {})", selected_text.length(), selected_text.length() == 1 ? "character" : "characters", word_count, word_count != 1 ? "words" : "word");
  607. }
  608. m_statusbar->set_text(builder.to_string());
  609. }