MainWidget.cpp 32 KB

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