TextEditorWidget.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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_cursor_position();
  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_cursor_position(); };
  240. 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&) {
  241. if (m_document_dirty) {
  242. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  243. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  244. m_save_action->activate();
  245. if (save_document_first_result == GUI::Dialog::ExecResult::ExecCancel)
  246. return;
  247. }
  248. m_document_dirty = false;
  249. m_editor->set_text(StringView());
  250. set_path(LexicalPath());
  251. update_title();
  252. });
  253. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  254. Optional<String> open_path = GUI::FilePicker::get_open_filepath(window());
  255. if (!open_path.has_value())
  256. return;
  257. if (m_document_dirty) {
  258. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  259. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  260. m_save_action->activate();
  261. if (save_document_first_result == GUI::Dialog::ExecResult::ExecCancel)
  262. return;
  263. }
  264. open_file(open_path.value());
  265. });
  266. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  267. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(), m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "txt" : m_extension);
  268. if (!save_path.has_value())
  269. return;
  270. if (!m_editor->write_to_file(save_path.value())) {
  271. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  272. return;
  273. }
  274. m_document_dirty = false;
  275. set_path(LexicalPath(save_path.value()));
  276. dbgln("Wrote document to {}", save_path.value());
  277. });
  278. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  279. if (!m_path.is_empty()) {
  280. if (!m_editor->write_to_file(m_path)) {
  281. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  282. } else {
  283. m_document_dirty = false;
  284. update_title();
  285. }
  286. return;
  287. }
  288. m_save_as_action->activate();
  289. });
  290. m_toolbar->add_action(*m_new_action);
  291. m_toolbar->add_action(*m_open_action);
  292. m_toolbar->add_action(*m_save_action);
  293. m_toolbar->add_separator();
  294. m_toolbar->add_action(m_editor->cut_action());
  295. m_toolbar->add_action(m_editor->copy_action());
  296. m_toolbar->add_action(m_editor->paste_action());
  297. m_toolbar->add_action(m_editor->delete_action());
  298. m_toolbar->add_separator();
  299. m_toolbar->add_action(m_editor->undo_action());
  300. m_toolbar->add_action(m_editor->redo_action());
  301. }
  302. TextEditorWidget::~TextEditorWidget()
  303. {
  304. }
  305. void TextEditorWidget::initialize_menubar(GUI::MenuBar& menubar)
  306. {
  307. auto& app_menu = menubar.add_menu("Text Editor");
  308. app_menu.add_action(*m_new_action);
  309. app_menu.add_action(*m_open_action);
  310. app_menu.add_action(*m_save_action);
  311. app_menu.add_action(*m_save_as_action);
  312. app_menu.add_separator();
  313. app_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  314. if (!request_close())
  315. return;
  316. GUI::Application::the()->quit();
  317. }));
  318. auto& edit_menu = menubar.add_menu("Edit");
  319. edit_menu.add_action(m_editor->undo_action());
  320. edit_menu.add_action(m_editor->redo_action());
  321. edit_menu.add_separator();
  322. edit_menu.add_action(m_editor->cut_action());
  323. edit_menu.add_action(m_editor->copy_action());
  324. edit_menu.add_action(m_editor->paste_action());
  325. edit_menu.add_action(m_editor->delete_action());
  326. edit_menu.add_separator();
  327. edit_menu.add_action(*m_vim_emulation_setting_action);
  328. edit_menu.add_separator();
  329. edit_menu.add_action(*m_find_replace_action);
  330. edit_menu.add_action(*m_find_next_action);
  331. edit_menu.add_action(*m_find_previous_action);
  332. edit_menu.add_action(*m_replace_action);
  333. edit_menu.add_action(*m_replace_all_action);
  334. m_no_preview_action = GUI::Action::create_checkable(
  335. "No preview", [this](auto&) {
  336. set_preview_mode(PreviewMode::None);
  337. });
  338. m_markdown_preview_action = GUI::Action::create_checkable(
  339. "Markdown preview", [this](auto&) {
  340. set_preview_mode(PreviewMode::Markdown);
  341. },
  342. this);
  343. m_html_preview_action = GUI::Action::create_checkable(
  344. "HTML preview", [this](auto&) {
  345. set_preview_mode(PreviewMode::HTML);
  346. },
  347. this);
  348. m_preview_actions.add_action(*m_no_preview_action);
  349. m_preview_actions.add_action(*m_markdown_preview_action);
  350. m_preview_actions.add_action(*m_html_preview_action);
  351. m_preview_actions.set_exclusive(true);
  352. m_layout_toolbar_action = GUI::Action::create_checkable("Toolbar", [&](auto& action) {
  353. action.is_checked() ? m_toolbar_container->set_visible(true) : m_toolbar_container->set_visible(false);
  354. m_config->write_bool_entry("Layout", "ShowToolbar", action.is_checked());
  355. m_config->sync();
  356. });
  357. auto show_toolbar = m_config->read_bool_entry("Layout", "ShowToolbar", true);
  358. m_layout_toolbar_action->set_checked(show_toolbar);
  359. m_toolbar_container->set_visible(show_toolbar);
  360. m_layout_statusbar_action = GUI::Action::create_checkable("Status bar", [&](auto& action) {
  361. action.is_checked() ? m_statusbar->set_visible(true) : m_statusbar->set_visible(false);
  362. m_config->write_bool_entry("Layout", "ShowStatusBar", action.is_checked());
  363. m_config->sync();
  364. });
  365. auto show_statusbar = m_config->read_bool_entry("Layout", "ShowStatusBar", true);
  366. m_layout_statusbar_action->set_checked(show_statusbar);
  367. m_statusbar->set_visible(show_statusbar);
  368. m_layout_ruler_action = GUI::Action::create_checkable("Ruler", [&](auto& action) {
  369. action.is_checked() ? m_editor->set_ruler_visible(true) : m_editor->set_ruler_visible(false);
  370. m_config->write_bool_entry("Layout", "ShowRuler", action.is_checked());
  371. m_config->sync();
  372. });
  373. auto show_ruler = m_config->read_bool_entry("Layout", "ShowRuler", true);
  374. m_layout_ruler_action->set_checked(show_ruler);
  375. m_editor->set_ruler_visible(show_ruler);
  376. auto& view_menu = menubar.add_menu("View");
  377. auto& layout_menu = view_menu.add_submenu("Layout");
  378. layout_menu.add_action(*m_layout_toolbar_action);
  379. layout_menu.add_action(*m_layout_statusbar_action);
  380. layout_menu.add_action(*m_layout_ruler_action);
  381. view_menu.add_separator();
  382. view_menu.add_action(GUI::Action::create("Editor font...", Gfx::Bitmap::load_from_file("/res/icons/16x16/app-font-editor.png"),
  383. [&](auto&) {
  384. auto picker = GUI::FontPicker::construct(window(), &m_editor->font(), false);
  385. if (picker->exec() == GUI::Dialog::ExecOK) {
  386. dbgln("setting font {}", picker->font()->qualified_name());
  387. m_editor->set_font(picker->font());
  388. }
  389. }));
  390. view_menu.add_separator();
  391. m_wrapping_mode_actions.set_exclusive(true);
  392. auto& wrapping_mode_menu = view_menu.add_submenu("Wrapping mode");
  393. m_no_wrapping_action = GUI::Action::create_checkable("No wrapping", [&](auto&) {
  394. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
  395. });
  396. m_wrap_anywhere_action = GUI::Action::create_checkable("Wrap anywhere", [&](auto&) {
  397. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAnywhere);
  398. });
  399. m_wrap_at_words_action = GUI::Action::create_checkable("Wrap at words", [&](auto&) {
  400. m_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::WrapAtWords);
  401. });
  402. m_wrapping_mode_actions.add_action(*m_no_wrapping_action);
  403. m_wrapping_mode_actions.add_action(*m_wrap_anywhere_action);
  404. m_wrapping_mode_actions.add_action(*m_wrap_at_words_action);
  405. wrapping_mode_menu.add_action(*m_no_wrapping_action);
  406. wrapping_mode_menu.add_action(*m_wrap_anywhere_action);
  407. wrapping_mode_menu.add_action(*m_wrap_at_words_action);
  408. m_no_wrapping_action->set_checked(true);
  409. view_menu.add_separator();
  410. view_menu.add_action(*m_no_preview_action);
  411. view_menu.add_action(*m_markdown_preview_action);
  412. view_menu.add_action(*m_html_preview_action);
  413. m_no_preview_action->set_checked(true);
  414. view_menu.add_separator();
  415. syntax_actions.set_exclusive(true);
  416. auto& syntax_menu = view_menu.add_submenu("Syntax");
  417. m_plain_text_highlight = GUI::Action::create_checkable("Plain text", [&](auto&) {
  418. m_editor->set_syntax_highlighter({});
  419. m_editor->update();
  420. });
  421. m_plain_text_highlight->set_checked(true);
  422. syntax_actions.add_action(*m_plain_text_highlight);
  423. syntax_menu.add_action(*m_plain_text_highlight);
  424. m_cpp_highlight = GUI::Action::create_checkable("C++", [&](auto&) {
  425. m_editor->set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  426. m_editor->update();
  427. });
  428. syntax_actions.add_action(*m_cpp_highlight);
  429. syntax_menu.add_action(*m_cpp_highlight);
  430. m_js_highlight = GUI::Action::create_checkable("JavaScript", [&](auto&) {
  431. m_editor->set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  432. m_editor->update();
  433. });
  434. syntax_actions.add_action(*m_js_highlight);
  435. syntax_menu.add_action(*m_js_highlight);
  436. m_gml_highlight = GUI::Action::create_checkable("GML", [&](auto&) {
  437. m_editor->set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  438. m_editor->update();
  439. });
  440. syntax_actions.add_action(*m_gml_highlight);
  441. syntax_menu.add_action(*m_gml_highlight);
  442. m_ini_highlight = GUI::Action::create_checkable("INI File", [&](auto&) {
  443. m_editor->set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  444. m_editor->update();
  445. });
  446. syntax_actions.add_action(*m_ini_highlight);
  447. syntax_menu.add_action(*m_ini_highlight);
  448. m_shell_highlight = GUI::Action::create_checkable("Shell File", [&](auto&) {
  449. m_editor->set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  450. m_editor->update();
  451. });
  452. syntax_actions.add_action(*m_shell_highlight);
  453. syntax_menu.add_action(*m_shell_highlight);
  454. auto& help_menu = menubar.add_menu("Help");
  455. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  456. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/TextEditor.md"), "/bin/Help");
  457. }));
  458. help_menu.add_action(GUI::CommonActions::make_about_action("Text Editor", GUI::Icon::default_icon("app-text-editor"), window()));
  459. }
  460. void TextEditorWidget::set_path(const LexicalPath& lexical_path)
  461. {
  462. m_path = lexical_path.string();
  463. m_name = lexical_path.title();
  464. m_extension = lexical_path.extension();
  465. if (m_extension == "c" || m_extension == "cc" || m_extension == "cxx" || m_extension == "cpp" || m_extension == "h") {
  466. m_cpp_highlight->activate();
  467. } else if (m_extension == "js" || m_extension == "json") {
  468. m_js_highlight->activate();
  469. } else if (m_extension == "gml") {
  470. m_gml_highlight->activate();
  471. } else if (m_extension == "ini") {
  472. m_ini_highlight->activate();
  473. } else {
  474. m_plain_text_highlight->activate();
  475. }
  476. if (m_auto_detect_preview_mode) {
  477. if (m_extension == "md")
  478. set_preview_mode(PreviewMode::Markdown);
  479. else if (m_extension == "html")
  480. set_preview_mode(PreviewMode::HTML);
  481. else
  482. set_preview_mode(PreviewMode::None);
  483. }
  484. update_title();
  485. }
  486. void TextEditorWidget::update_title()
  487. {
  488. StringBuilder builder;
  489. if (m_path.is_empty())
  490. builder.append("Untitled");
  491. else
  492. builder.append(m_path);
  493. if (m_document_dirty)
  494. builder.append(" (*)");
  495. builder.append(" - Text Editor");
  496. window()->set_title(builder.to_string());
  497. }
  498. void TextEditorWidget::open_file(const String& path)
  499. {
  500. auto file = Core::File::construct(path);
  501. if (!file->open(Core::IODevice::ReadOnly) && file->error() != ENOENT) {
  502. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  503. return;
  504. }
  505. m_editor->set_text(file->read_all());
  506. m_document_dirty = false;
  507. m_document_opening = true;
  508. set_path(LexicalPath(path));
  509. m_editor->set_focus(true);
  510. }
  511. bool TextEditorWidget::request_close()
  512. {
  513. if (!m_document_dirty)
  514. return true;
  515. 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);
  516. if (result == GUI::MessageBox::ExecYes) {
  517. m_save_action->activate();
  518. return true;
  519. }
  520. if (result == GUI::MessageBox::ExecNo)
  521. return true;
  522. return false;
  523. }
  524. void TextEditorWidget::drop_event(GUI::DropEvent& event)
  525. {
  526. event.accept();
  527. window()->move_to_front();
  528. if (event.mime_data().has_urls()) {
  529. auto urls = event.mime_data().urls();
  530. if (urls.is_empty())
  531. return;
  532. if (urls.size() > 1) {
  533. GUI::MessageBox::show(window(), "TextEditor can only open one file at a time!", "One at a time please!", GUI::MessageBox::Type::Error);
  534. return;
  535. }
  536. open_file(urls.first().path());
  537. }
  538. }
  539. void TextEditorWidget::set_preview_mode(PreviewMode mode)
  540. {
  541. if (m_preview_mode == mode)
  542. return;
  543. m_preview_mode = mode;
  544. if (m_preview_mode == PreviewMode::HTML) {
  545. m_html_preview_action->set_checked(true);
  546. m_page_view->set_visible(true);
  547. update_html_preview();
  548. } else if (m_preview_mode == PreviewMode::Markdown) {
  549. m_markdown_preview_action->set_checked(true);
  550. m_page_view->set_visible(true);
  551. update_markdown_preview();
  552. } else {
  553. m_no_preview_action->set_checked(true);
  554. m_page_view->set_visible(false);
  555. }
  556. }
  557. void TextEditorWidget::update_preview()
  558. {
  559. switch (m_preview_mode) {
  560. case PreviewMode::Markdown:
  561. update_markdown_preview();
  562. break;
  563. case PreviewMode::HTML:
  564. update_html_preview();
  565. break;
  566. default:
  567. break;
  568. }
  569. }
  570. void TextEditorWidget::update_markdown_preview()
  571. {
  572. auto document = Markdown::Document::parse(m_editor->text());
  573. if (document) {
  574. auto html = document->render_to_html();
  575. auto current_scroll_pos = m_page_view->visible_content_rect();
  576. m_page_view->load_html(html, URL::create_with_file_protocol(m_path));
  577. m_page_view->scroll_into_view(current_scroll_pos, true, true);
  578. }
  579. }
  580. void TextEditorWidget::update_html_preview()
  581. {
  582. auto current_scroll_pos = m_page_view->visible_content_rect();
  583. m_page_view->load_html(m_editor->text(), URL::create_with_file_protocol(m_path));
  584. m_page_view->scroll_into_view(current_scroll_pos, true, true);
  585. }
  586. void TextEditorWidget::update_statusbar_cursor_position()
  587. {
  588. StringBuilder builder;
  589. builder.appendff("Line: {}, Column: {}", m_editor->cursor().line() + 1, m_editor->cursor().column());
  590. m_statusbar->set_text(builder.to_string());
  591. }