HexEditorWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Mustafa Quraish <mustafa@serenityos.org>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include "HexEditorWidget.h"
  9. #include "FindDialog.h"
  10. #include "GoToOffsetDialog.h"
  11. #include "SearchResultsModel.h"
  12. #include <AK/Optional.h>
  13. #include <AK/StringBuilder.h>
  14. #include <Applications/HexEditor/HexEditorWindowGML.h>
  15. #include <LibConfig/Client.h>
  16. #include <LibCore/File.h>
  17. #include <LibFileSystemAccessClient/Client.h>
  18. #include <LibGUI/Action.h>
  19. #include <LibGUI/BoxLayout.h>
  20. #include <LibGUI/Button.h>
  21. #include <LibGUI/FilePicker.h>
  22. #include <LibGUI/InputBox.h>
  23. #include <LibGUI/Menu.h>
  24. #include <LibGUI/Menubar.h>
  25. #include <LibGUI/MessageBox.h>
  26. #include <LibGUI/Model.h>
  27. #include <LibGUI/Statusbar.h>
  28. #include <LibGUI/TableView.h>
  29. #include <LibGUI/TextBox.h>
  30. #include <LibGUI/Toolbar.h>
  31. #include <LibGUI/ToolbarContainer.h>
  32. #include <string.h>
  33. REGISTER_WIDGET(HexEditor, HexEditor);
  34. HexEditorWidget::HexEditorWidget()
  35. {
  36. load_from_gml(hex_editor_window_gml);
  37. m_toolbar = *find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  38. m_toolbar_container = *find_descendant_of_type_named<GUI::ToolbarContainer>("toolbar_container");
  39. m_editor = *find_descendant_of_type_named<HexEditor>("editor");
  40. m_statusbar = *find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  41. m_search_results = *find_descendant_of_type_named<GUI::TableView>("search_results");
  42. m_search_results_container = *find_descendant_of_type_named<GUI::Widget>("search_results_container");
  43. m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
  44. m_statusbar->set_text(0, String::formatted("Offset: {:#08X}", position));
  45. m_statusbar->set_text(1, String::formatted("Edit Mode: {}", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text"));
  46. m_statusbar->set_text(2, String::formatted("Selection Start: {}", selection_start));
  47. m_statusbar->set_text(3, String::formatted("Selection End: {}", selection_end));
  48. m_statusbar->set_text(4, String::formatted("Selected Bytes: {}", m_editor->selection_size()));
  49. };
  50. m_editor->on_change = [this] {
  51. window()->set_modified(true);
  52. };
  53. m_search_results->set_activates_on_selection(true);
  54. m_search_results->on_activation = [this](const GUI::ModelIndex& index) {
  55. if (!index.is_valid())
  56. return;
  57. auto offset = index.data(GUI::ModelRole::Custom).to_i32();
  58. m_last_found_index = offset;
  59. m_editor->set_position(offset);
  60. m_editor->update();
  61. };
  62. 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](const GUI::Action&) {
  63. String value;
  64. if (request_close() && GUI::InputBox::show(window(), value, "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
  65. auto file_size = value.to_int();
  66. if (file_size.has_value() && file_size.value() > 0) {
  67. window()->set_modified(false);
  68. if (!m_editor->open_new_file(file_size.value())) {
  69. GUI::MessageBox::show(window(), "Entered file size is too large.", "Error", GUI::MessageBox::Type::Error);
  70. return;
  71. }
  72. set_path({});
  73. } else {
  74. GUI::MessageBox::show(window(), "Invalid file size entered.", "Error", GUI::MessageBox::Type::Error);
  75. }
  76. }
  77. });
  78. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  79. if (!request_close())
  80. return;
  81. auto response = FileSystemAccessClient::Client::the().try_open_file(window(), {}, Core::StandardPaths::home_directory(), Core::OpenMode::ReadWrite);
  82. if (response.is_error())
  83. return;
  84. open_file(response.value());
  85. });
  86. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  87. if (m_path.is_empty())
  88. return m_save_as_action->activate();
  89. if (!m_editor->save()) {
  90. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  91. } else {
  92. window()->set_modified(false);
  93. m_editor->update();
  94. }
  95. return;
  96. });
  97. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  98. auto response = FileSystemAccessClient::Client::the().try_save_file(window(), m_name, m_extension, Core::OpenMode::ReadWrite | Core::OpenMode::Truncate);
  99. if (response.is_error())
  100. return;
  101. auto file = response.release_value();
  102. if (!m_editor->save_as(file)) {
  103. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  104. return;
  105. }
  106. window()->set_modified(false);
  107. set_path(file->filename());
  108. dbgln("Wrote document to {}", file->filename());
  109. });
  110. m_find_action = GUI::Action::create("&Find", { Mod_Ctrl, Key_F }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find.png").release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  111. auto old_buffer = m_search_buffer;
  112. bool find_all = false;
  113. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecOK) {
  114. if (find_all) {
  115. auto matches = m_editor->find_all(m_search_buffer, 0);
  116. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  117. m_search_results->update();
  118. if (matches.is_empty()) {
  119. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  120. return;
  121. }
  122. GUI::MessageBox::show(window(), String::formatted("Found {} matches for \"{}\" in this file", matches.size(), m_search_text), String::formatted("{} matches", matches.size()), GUI::MessageBox::Type::Warning);
  123. set_search_results_visible(true);
  124. } else {
  125. bool same_buffers = false;
  126. if (old_buffer.size() == m_search_buffer.size()) {
  127. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  128. same_buffers = true;
  129. }
  130. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  131. if (!result.has_value()) {
  132. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  133. return;
  134. }
  135. m_last_found_index = result.value();
  136. }
  137. m_editor->update();
  138. }
  139. });
  140. m_goto_offset_action = GUI::Action::create("&Go to Offset ...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-to.png").release_value_but_fixme_should_propagate_errors(), [this](const GUI::Action&) {
  141. int new_offset;
  142. auto result = GoToOffsetDialog::show(
  143. window(),
  144. m_goto_history,
  145. new_offset,
  146. m_editor->selection_start_offset(),
  147. m_editor->buffer_size());
  148. if (result == GUI::InputBox::ExecOK) {
  149. m_editor->highlight(new_offset, new_offset);
  150. m_editor->update();
  151. }
  152. });
  153. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  154. m_toolbar_container->set_visible(action.is_checked());
  155. Config::write_bool("HexEditor", "Layout", "ShowToolbar", action.is_checked());
  156. });
  157. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  158. set_search_results_visible(action.is_checked());
  159. });
  160. m_toolbar->add_action(*m_new_action);
  161. m_toolbar->add_action(*m_open_action);
  162. m_toolbar->add_action(*m_save_action);
  163. m_toolbar->add_separator();
  164. m_toolbar->add_action(*m_find_action);
  165. m_toolbar->add_action(*m_goto_offset_action);
  166. m_statusbar->segment(0).set_clickable(true);
  167. m_statusbar->segment(0).set_action(*m_goto_offset_action);
  168. m_editor->set_focus(true);
  169. }
  170. void HexEditorWidget::initialize_menubar(GUI::Window& window)
  171. {
  172. auto& file_menu = window.add_menu("&File");
  173. file_menu.add_action(*m_new_action);
  174. file_menu.add_action(*m_open_action);
  175. file_menu.add_action(*m_save_action);
  176. file_menu.add_action(*m_save_as_action);
  177. file_menu.add_separator();
  178. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  179. if (!request_close())
  180. return;
  181. GUI::Application::the()->quit();
  182. }));
  183. auto& edit_menu = window.add_menu("&Edit");
  184. edit_menu.add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  185. m_editor->select_all();
  186. m_editor->update();
  187. }));
  188. edit_menu.add_action(GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  189. String value;
  190. if (GUI::InputBox::show(&window, value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  191. auto fill_byte = strtol(value.characters(), nullptr, 16);
  192. m_editor->fill_selection(fill_byte);
  193. }
  194. }));
  195. edit_menu.add_separator();
  196. edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/hex.png").release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  197. m_editor->copy_selected_hex_to_clipboard();
  198. }));
  199. edit_menu.add_action(GUI::Action::create("Copy &Text", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/edit-copy.png").release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  200. m_editor->copy_selected_text_to_clipboard();
  201. }));
  202. edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/c.png").release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  203. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  204. }));
  205. edit_menu.add_separator();
  206. edit_menu.add_action(*m_find_action);
  207. edit_menu.add_action(GUI::Action::create("Find &Next", { Mod_None, Key_F3 }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find-next.png").release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  208. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  209. GUI::MessageBox::show(&window, "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  210. return;
  211. }
  212. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  213. if (!result.has_value()) {
  214. GUI::MessageBox::show(&window, String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  215. return;
  216. }
  217. m_editor->update();
  218. m_last_found_index = result.value();
  219. }));
  220. edit_menu.add_action(GUI::Action::create("Find All &Strings", { Mod_Ctrl | Mod_Shift, Key_S }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/find.png").release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  221. int min_length = 4;
  222. auto matches = m_editor->find_all_strings(min_length);
  223. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  224. m_search_results->update();
  225. if (matches.is_empty()) {
  226. GUI::MessageBox::show(&window, "No strings found in this file", "Not found", GUI::MessageBox::Type::Warning);
  227. return;
  228. }
  229. set_search_results_visible(true);
  230. m_editor->update();
  231. }));
  232. edit_menu.add_separator();
  233. edit_menu.add_action(*m_goto_offset_action);
  234. auto& view_menu = window.add_menu("&View");
  235. auto show_toolbar = Config::read_bool("HexEditor", "Layout", "ShowToolbar", true);
  236. m_layout_toolbar_action->set_checked(show_toolbar);
  237. m_toolbar_container->set_visible(show_toolbar);
  238. view_menu.add_action(*m_layout_toolbar_action);
  239. view_menu.add_action(*m_layout_search_results_action);
  240. view_menu.add_separator();
  241. auto bytes_per_row = Config::read_i32("HexEditor", "Layout", "BytesPerRow", 16);
  242. m_editor->set_bytes_per_row(bytes_per_row);
  243. m_editor->update();
  244. m_bytes_per_row_actions.set_exclusive(true);
  245. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  246. for (int i = 8; i <= 32; i += 8) {
  247. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  248. m_editor->set_bytes_per_row(i);
  249. m_editor->update();
  250. Config::write_i32("HexEditor", "Layout", "BytesPerRow", i);
  251. });
  252. m_bytes_per_row_actions.add_action(action);
  253. bytes_per_row_menu.add_action(action);
  254. if (i == bytes_per_row)
  255. action->set_checked(true);
  256. }
  257. auto& help_menu = window.add_menu("&Help");
  258. help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), &window));
  259. }
  260. void HexEditorWidget::set_path(StringView path)
  261. {
  262. if (path.is_empty()) {
  263. m_path = {};
  264. m_name = {};
  265. m_extension = {};
  266. } else {
  267. auto lexical_path = LexicalPath(path);
  268. m_path = lexical_path.string();
  269. m_name = lexical_path.title();
  270. m_extension = lexical_path.extension();
  271. }
  272. update_title();
  273. }
  274. void HexEditorWidget::update_title()
  275. {
  276. StringBuilder builder;
  277. if (m_path.is_empty())
  278. builder.append("Untitled");
  279. else
  280. builder.append(m_path);
  281. builder.append("[*] - Hex Editor");
  282. window()->set_title(builder.to_string());
  283. }
  284. void HexEditorWidget::open_file(NonnullRefPtr<Core::File> file)
  285. {
  286. window()->set_modified(false);
  287. m_editor->open_file(file);
  288. set_path(file->filename());
  289. }
  290. bool HexEditorWidget::request_close()
  291. {
  292. if (!window()->is_modified())
  293. return true;
  294. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path);
  295. if (result == GUI::MessageBox::ExecYes) {
  296. m_save_action->activate();
  297. return !window()->is_modified();
  298. }
  299. return result == GUI::MessageBox::ExecNo;
  300. }
  301. void HexEditorWidget::set_search_results_visible(bool visible)
  302. {
  303. m_layout_search_results_action->set_checked(visible);
  304. m_search_results_container->set_visible(visible);
  305. }
  306. void HexEditorWidget::drop_event(GUI::DropEvent& event)
  307. {
  308. event.accept();
  309. if (event.mime_data().has_urls()) {
  310. auto urls = event.mime_data().urls();
  311. if (urls.is_empty())
  312. return;
  313. window()->move_to_front();
  314. // TODO: A drop event should be considered user consent for opening a file
  315. auto response = FileSystemAccessClient::Client::the().try_request_file(window(), urls.first().path(), Core::OpenMode::ReadOnly);
  316. if (response.is_error())
  317. return;
  318. open_file(response.value());
  319. }
  320. }