TextEditorWidget.cpp 25 KB

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