MainWidget.cpp 29 KB

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