TextEditorWidget.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 <LibGUI/AboutDialog.h>
  33. #include <LibGUI/Action.h>
  34. #include <LibGUI/BoxLayout.h>
  35. #include <LibGUI/Button.h>
  36. #include <LibGUI/CppSyntaxHighlighter.h>
  37. #include <LibGUI/FilePicker.h>
  38. #include <LibGUI/FontDatabase.h>
  39. #include <LibGUI/Menu.h>
  40. #include <LibGUI/MenuBar.h>
  41. #include <LibGUI/MessageBox.h>
  42. #include <LibGUI/StatusBar.h>
  43. #include <LibGUI/TextBox.h>
  44. #include <LibGUI/TextEditor.h>
  45. #include <LibGUI/ToolBar.h>
  46. #include <LibGfx/Font.h>
  47. TextEditorWidget::TextEditorWidget()
  48. {
  49. set_layout(make<GUI::VerticalBoxLayout>());
  50. layout()->set_spacing(0);
  51. auto toolbar = GUI::ToolBar::construct(this);
  52. m_editor = GUI::TextEditor::construct(GUI::TextEditor::MultiLine, this);
  53. m_editor->set_ruler_visible(true);
  54. m_editor->set_automatic_indentation_enabled(true);
  55. m_editor->set_line_wrapping_enabled(true);
  56. m_editor->on_change = [this] {
  57. // Do not mark as diry on the first change (When document is first opened.)
  58. if (m_document_opening) {
  59. m_document_opening = false;
  60. return;
  61. }
  62. bool was_dirty = m_document_dirty;
  63. m_document_dirty = true;
  64. if (!was_dirty)
  65. update_title();
  66. };
  67. m_find_replace_widget = GUI::Widget::construct(this);
  68. m_find_replace_widget->set_fill_with_background_color(true);
  69. m_find_replace_widget->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  70. m_find_replace_widget->set_preferred_size(0, 48);
  71. m_find_replace_widget->set_layout(make<GUI::VerticalBoxLayout>());
  72. m_find_replace_widget->layout()->set_margins({ 2, 2, 2, 4 });
  73. m_find_replace_widget->set_visible(false);
  74. m_find_widget = GUI::Widget::construct(m_find_replace_widget);
  75. m_find_widget->set_fill_with_background_color(true);
  76. m_find_widget->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  77. m_find_widget->set_preferred_size(0, 22);
  78. m_find_widget->set_layout(make<GUI::HorizontalBoxLayout>());
  79. m_find_widget->set_visible(false);
  80. m_replace_widget = GUI::Widget::construct(m_find_replace_widget);
  81. m_replace_widget->set_fill_with_background_color(true);
  82. m_replace_widget->set_size_policy(GUI::SizePolicy::Fill, GUI::SizePolicy::Fixed);
  83. m_replace_widget->set_preferred_size(0, 22);
  84. m_replace_widget->set_layout(make<GUI::HorizontalBoxLayout>());
  85. m_replace_widget->set_visible(false);
  86. m_find_textbox = GUI::TextBox::construct(m_find_widget);
  87. m_replace_textbox = GUI::TextBox::construct(m_replace_widget);
  88. m_find_next_action = GUI::Action::create("Find next", { Mod_Ctrl, Key_G }, [&](auto&) {
  89. auto needle = m_find_textbox->text();
  90. if (needle.is_empty()) {
  91. dbg() << "find_next(\"\")";
  92. return;
  93. }
  94. auto found_range = m_editor->document().find_next(needle, m_editor->normalized_selection().end());
  95. dbg() << "find_next(\"" << needle << "\") returned " << found_range;
  96. if (found_range.is_valid()) {
  97. m_editor->set_selection(found_range);
  98. } else {
  99. GUI::MessageBox::show(
  100. String::format("Not found: \"%s\"", needle.characters()),
  101. "Not found",
  102. GUI::MessageBox::Type::Information,
  103. GUI::MessageBox::InputType::OK, window());
  104. }
  105. });
  106. m_find_previous_action = GUI::Action::create("Find previous", { Mod_Ctrl | Mod_Shift, Key_G }, [&](auto&) {
  107. auto needle = m_find_textbox->text();
  108. if (needle.is_empty()) {
  109. dbg() << "find_prev(\"\")";
  110. return;
  111. }
  112. auto selection_start = m_editor->normalized_selection().start();
  113. if (!selection_start.is_valid())
  114. selection_start = m_editor->normalized_selection().end();
  115. auto found_range = m_editor->document().find_previous(needle, selection_start);
  116. dbg() << "find_prev(\"" << needle << "\") returned " << found_range;
  117. if (found_range.is_valid()) {
  118. m_editor->set_selection(found_range);
  119. } else {
  120. GUI::MessageBox::show(
  121. String::format("Not found: \"%s\"", needle.characters()),
  122. "Not found",
  123. GUI::MessageBox::Type::Information,
  124. GUI::MessageBox::InputType::OK, window());
  125. }
  126. });
  127. m_replace_next_action = GUI::Action::create("Replace next", { Mod_Ctrl, Key_F1 }, [&](auto&) {
  128. auto needle = m_find_textbox->text();
  129. auto substitute = m_replace_textbox->text();
  130. if (needle.is_empty())
  131. return;
  132. auto selection_start = m_editor->normalized_selection().start();
  133. if (!selection_start.is_valid())
  134. selection_start = m_editor->normalized_selection().start();
  135. auto found_range = m_editor->document().find_next(needle, selection_start);
  136. if (found_range.is_valid()) {
  137. m_editor->set_selection(found_range);
  138. m_editor->insert_at_cursor_or_replace_selection(substitute);
  139. } else {
  140. GUI::MessageBox::show(
  141. String::format("Not found: \"%s\"", needle.characters()),
  142. "Not found",
  143. GUI::MessageBox::Type::Information,
  144. GUI::MessageBox::InputType::OK, window());
  145. }
  146. });
  147. m_replace_previous_action = GUI::Action::create("Replace previous", { Mod_Ctrl | Mod_Shift, Key_F1 }, [&](auto&) {
  148. auto needle = m_find_textbox->text();
  149. auto substitute = m_replace_textbox->text();
  150. if (needle.is_empty())
  151. return;
  152. auto selection_start = m_editor->normalized_selection().start();
  153. if (!selection_start.is_valid())
  154. selection_start = m_editor->normalized_selection().start();
  155. auto found_range = m_editor->document().find_previous(needle, selection_start);
  156. if (found_range.is_valid()) {
  157. m_editor->set_selection(found_range);
  158. m_editor->insert_at_cursor_or_replace_selection(substitute);
  159. } else {
  160. GUI::MessageBox::show(
  161. String::format("Not found: \"%s\"", needle.characters()),
  162. "Not found",
  163. GUI::MessageBox::Type::Information,
  164. GUI::MessageBox::InputType::OK, window());
  165. }
  166. });
  167. m_replace_all_action = GUI::Action::create("Replace all", { Mod_Ctrl, Key_F2 }, [&](auto&) {
  168. auto needle = m_find_textbox->text();
  169. auto substitute = m_replace_textbox->text();
  170. if (needle.is_empty())
  171. return;
  172. auto found_range = m_editor->document().find_next(needle);
  173. while (found_range.is_valid()) {
  174. m_editor->set_selection(found_range);
  175. m_editor->insert_at_cursor_or_replace_selection(substitute);
  176. found_range = m_editor->document().find_next(needle);
  177. }
  178. });
  179. m_find_previous_button = GUI::Button::construct("Find previous", m_find_widget);
  180. m_find_previous_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  181. m_find_previous_button->set_preferred_size(150, 0);
  182. m_find_previous_button->set_action(*m_find_previous_action);
  183. m_find_next_button = GUI::Button::construct("Find next", m_find_widget);
  184. m_find_next_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  185. m_find_next_button->set_preferred_size(150, 0);
  186. m_find_next_button->set_action(*m_find_next_action);
  187. m_find_textbox->on_return_pressed = [this] {
  188. m_find_next_button->click();
  189. };
  190. m_find_textbox->on_escape_pressed = [this] {
  191. m_find_replace_widget->set_visible(false);
  192. m_editor->set_focus(true);
  193. };
  194. m_replace_previous_button = GUI::Button::construct("Replace previous", m_replace_widget);
  195. m_replace_previous_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  196. m_replace_previous_button->set_preferred_size(100, 0);
  197. m_replace_previous_button->set_action(*m_replace_previous_action);
  198. m_replace_next_button = GUI::Button::construct("Replace next", m_replace_widget);
  199. m_replace_next_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  200. m_replace_next_button->set_preferred_size(100, 0);
  201. m_replace_next_button->set_action(*m_replace_next_action);
  202. m_replace_all_button = GUI::Button::construct("Replace all", m_replace_widget);
  203. m_replace_all_button->set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
  204. m_replace_all_button->set_preferred_size(100, 0);
  205. m_replace_all_button->set_action(*m_replace_all_action);
  206. m_replace_textbox->on_return_pressed = [this] {
  207. m_replace_next_button->click();
  208. };
  209. m_replace_textbox->on_escape_pressed = [this] {
  210. m_find_replace_widget->set_visible(false);
  211. m_editor->set_focus(true);
  212. };
  213. 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&) {
  214. m_find_replace_widget->set_visible(true);
  215. m_find_widget->set_visible(true);
  216. m_replace_widget->set_visible(true);
  217. m_find_textbox->set_focus(true);
  218. if (m_editor->has_selection()) {
  219. auto selected_text = m_editor->document().text_in_range(m_editor->normalized_selection());
  220. m_find_textbox->set_text(selected_text);
  221. }
  222. m_find_textbox->select_all();
  223. });
  224. m_editor->add_custom_context_menu_action(*m_find_replace_action);
  225. m_editor->add_custom_context_menu_action(*m_find_next_action);
  226. m_editor->add_custom_context_menu_action(*m_find_previous_action);
  227. m_statusbar = GUI::StatusBar::construct(this);
  228. m_editor->on_cursor_change = [this] {
  229. StringBuilder builder;
  230. builder.appendf("Line: %d, Column: %d", m_editor->cursor().line() + 1, m_editor->cursor().column());
  231. m_statusbar->set_text(builder.to_string());
  232. };
  233. 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&) {
  234. if (m_document_dirty) {
  235. auto save_document_first_box = GUI::MessageBox::construct("Save Document First?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel, window());
  236. auto save_document_first_result = save_document_first_box->exec();
  237. if (save_document_first_result != GUI::Dialog::ExecResult::ExecOK)
  238. return;
  239. m_save_action->activate();
  240. }
  241. m_document_dirty = false;
  242. m_editor->set_text(StringView());
  243. set_path(FileSystemPath());
  244. update_title();
  245. });
  246. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  247. Optional<String> open_path = GUI::FilePicker::get_open_filepath();
  248. if (!open_path.has_value())
  249. return;
  250. if (m_document_dirty) {
  251. auto save_document_first_box = GUI::MessageBox::construct("Save Document First?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel, window());
  252. auto save_document_first_result = save_document_first_box->exec();
  253. if (save_document_first_result == GUI::Dialog::ExecResult::ExecOK)
  254. m_save_action->activate();
  255. }
  256. open_sesame(open_path.value());
  257. });
  258. 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&) {
  259. Optional<String> save_path = GUI::FilePicker::get_save_filepath(m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "txt" : m_extension);
  260. if (!save_path.has_value())
  261. return;
  262. if (!m_editor->write_to_file(save_path.value())) {
  263. GUI::MessageBox::show("Unable to save file.\n", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  264. return;
  265. }
  266. m_document_dirty = false;
  267. set_path(FileSystemPath(save_path.value()));
  268. dbg() << "Wrote document to " << save_path.value();
  269. });
  270. m_save_action = GUI::Action::create("Save", { Mod_Ctrl, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), [&](const GUI::Action&) {
  271. if (!m_path.is_empty()) {
  272. if (!m_editor->write_to_file(m_path)) {
  273. GUI::MessageBox::show("Unable to save file.\n", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  274. } else {
  275. m_document_dirty = false;
  276. update_title();
  277. }
  278. return;
  279. }
  280. m_save_as_action->activate();
  281. });
  282. m_line_wrapping_setting_action = GUI::Action::create("Line wrapping", [&](GUI::Action& action) {
  283. action.set_checked(!action.is_checked());
  284. m_editor->set_line_wrapping_enabled(action.is_checked());
  285. });
  286. m_line_wrapping_setting_action->set_checkable(true);
  287. m_line_wrapping_setting_action->set_checked(m_editor->is_line_wrapping_enabled());
  288. auto menubar = make<GUI::MenuBar>();
  289. auto app_menu = GUI::Menu::construct("Text Editor");
  290. app_menu->add_action(*m_new_action);
  291. app_menu->add_action(*m_open_action);
  292. app_menu->add_action(*m_save_action);
  293. app_menu->add_action(*m_save_as_action);
  294. app_menu->add_separator();
  295. app_menu->add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  296. if (!request_close())
  297. return;
  298. GUI::Application::the().quit(0);
  299. }));
  300. menubar->add_menu(move(app_menu));
  301. auto edit_menu = GUI::Menu::construct("Edit");
  302. edit_menu->add_action(m_editor->undo_action());
  303. edit_menu->add_action(m_editor->redo_action());
  304. edit_menu->add_separator();
  305. edit_menu->add_action(m_editor->cut_action());
  306. edit_menu->add_action(m_editor->copy_action());
  307. edit_menu->add_action(m_editor->paste_action());
  308. edit_menu->add_action(m_editor->delete_action());
  309. edit_menu->add_separator();
  310. edit_menu->add_action(*m_find_replace_action);
  311. edit_menu->add_action(*m_find_next_action);
  312. edit_menu->add_action(*m_find_previous_action);
  313. edit_menu->add_action(*m_replace_next_action);
  314. edit_menu->add_action(*m_replace_previous_action);
  315. edit_menu->add_action(*m_replace_all_action);
  316. menubar->add_menu(move(edit_menu));
  317. auto font_menu = GUI::Menu::construct("Font");
  318. GFontDatabase::the().for_each_fixed_width_font([&](const StringView& font_name) {
  319. font_menu->add_action(GUI::Action::create(font_name, [this](const GUI::Action& action) {
  320. m_editor->set_font(GFontDatabase::the().get_by_name(action.text()));
  321. m_editor->update();
  322. }));
  323. });
  324. auto view_menu = GUI::Menu::construct("View");
  325. view_menu->add_action(*m_line_wrapping_setting_action);
  326. view_menu->add_separator();
  327. view_menu->add_submenu(move(font_menu));
  328. menubar->add_menu(move(view_menu));
  329. auto help_menu = GUI::Menu::construct("Help");
  330. help_menu->add_action(GUI::Action::create("About", [&](const GUI::Action&) {
  331. GUI::AboutDialog::show("Text Editor", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-texteditor.png"), window());
  332. }));
  333. menubar->add_menu(move(help_menu));
  334. GUI::Application::the().set_menubar(move(menubar));
  335. toolbar->add_action(*m_new_action);
  336. toolbar->add_action(*m_open_action);
  337. toolbar->add_action(*m_save_action);
  338. toolbar->add_separator();
  339. toolbar->add_action(m_editor->cut_action());
  340. toolbar->add_action(m_editor->copy_action());
  341. toolbar->add_action(m_editor->paste_action());
  342. toolbar->add_action(m_editor->delete_action());
  343. toolbar->add_separator();
  344. toolbar->add_action(m_editor->undo_action());
  345. toolbar->add_action(m_editor->redo_action());
  346. }
  347. TextEditorWidget::~TextEditorWidget()
  348. {
  349. }
  350. void TextEditorWidget::set_path(const FileSystemPath& file)
  351. {
  352. m_path = file.string();
  353. m_name = file.title();
  354. m_extension = file.extension();
  355. if (m_extension == "cpp" || m_extension == "h")
  356. m_editor->set_syntax_highlighter(make<GUI::CppSyntaxHighlighter>());
  357. update_title();
  358. }
  359. void TextEditorWidget::update_title()
  360. {
  361. StringBuilder builder;
  362. builder.append("Text Editor: ");
  363. builder.append(m_path);
  364. if (m_document_dirty)
  365. builder.append(" (*)");
  366. window()->set_title(builder.to_string());
  367. }
  368. void TextEditorWidget::open_sesame(const String& path)
  369. {
  370. auto file = Core::File::construct(path);
  371. if (!file->open(Core::IODevice::ReadOnly)) {
  372. GUI::MessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  373. return;
  374. }
  375. m_editor->set_text(file->read_all());
  376. m_document_dirty = false;
  377. m_document_opening = true;
  378. set_path(FileSystemPath(path));
  379. m_editor->set_focus(true);
  380. }
  381. bool TextEditorWidget::request_close()
  382. {
  383. if (!m_document_dirty)
  384. return true;
  385. auto result = GUI::MessageBox::show("The document has been modified. Quit without saving?", "Quit without saving?", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel, window());
  386. return result == GUI::MessageBox::ExecOK;
  387. }
  388. void TextEditorWidget::drop_event(GUI::DropEvent& event)
  389. {
  390. event.accept();
  391. window()->move_to_front();
  392. if (event.mime_data().has_urls()) {
  393. auto urls = event.mime_data().urls();
  394. if (urls.is_empty())
  395. return;
  396. if (urls.size() > 1) {
  397. GUI::MessageBox::show("TextEditor can only open one file at a time!", "One at a time please!", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  398. return;
  399. }
  400. open_sesame(urls.first().path());
  401. }
  402. }