TextEditorWidget.cpp 24 KB

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