HexEditorWidget.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. bool has_selection = m_editor->has_selection();
  50. m_copy_hex_action->set_enabled(has_selection);
  51. m_copy_text_action->set_enabled(has_selection);
  52. m_copy_as_c_code_action->set_enabled(has_selection);
  53. m_fill_selection_action->set_enabled(has_selection);
  54. };
  55. m_editor->on_change = [this] {
  56. window()->set_modified(true);
  57. };
  58. m_search_results->set_activates_on_selection(true);
  59. m_search_results->on_activation = [this](const GUI::ModelIndex& index) {
  60. if (!index.is_valid())
  61. return;
  62. auto offset = index.data(GUI::ModelRole::Custom).to_i32();
  63. m_last_found_index = offset;
  64. m_editor->set_position(offset);
  65. m_editor->update();
  66. };
  67. 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&) {
  68. String value;
  69. if (request_close() && GUI::InputBox::show(window(), value, "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
  70. auto file_size = value.to_int();
  71. if (file_size.has_value() && file_size.value() > 0) {
  72. window()->set_modified(false);
  73. if (!m_editor->open_new_file(file_size.value())) {
  74. GUI::MessageBox::show(window(), "Entered file size is too large.", "Error", GUI::MessageBox::Type::Error);
  75. return;
  76. }
  77. set_path({});
  78. } else {
  79. GUI::MessageBox::show(window(), "Invalid file size entered.", "Error", GUI::MessageBox::Type::Error);
  80. }
  81. }
  82. });
  83. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  84. if (!request_close())
  85. return;
  86. auto response = FileSystemAccessClient::Client::the().try_open_file(window(), {}, Core::StandardPaths::home_directory(), Core::OpenMode::ReadWrite);
  87. if (response.is_error())
  88. return;
  89. open_file(response.value());
  90. });
  91. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  92. if (m_path.is_empty())
  93. return m_save_as_action->activate();
  94. if (!m_editor->save()) {
  95. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  96. } else {
  97. window()->set_modified(false);
  98. m_editor->update();
  99. }
  100. return;
  101. });
  102. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  103. auto response = FileSystemAccessClient::Client::the().try_save_file(window(), m_name, m_extension, Core::OpenMode::ReadWrite | Core::OpenMode::Truncate);
  104. if (response.is_error())
  105. return;
  106. auto file = response.release_value();
  107. if (!m_editor->save_as(file)) {
  108. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  109. return;
  110. }
  111. window()->set_modified(false);
  112. set_path(file->filename());
  113. dbgln("Wrote document to {}", file->filename());
  114. });
  115. 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&) {
  116. auto old_buffer = m_search_buffer;
  117. bool find_all = false;
  118. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecOK) {
  119. if (find_all) {
  120. auto matches = m_editor->find_all(m_search_buffer, 0);
  121. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  122. m_search_results->update();
  123. if (matches.is_empty()) {
  124. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  125. return;
  126. }
  127. 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);
  128. set_search_results_visible(true);
  129. } else {
  130. bool same_buffers = false;
  131. if (old_buffer.size() == m_search_buffer.size()) {
  132. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  133. same_buffers = true;
  134. }
  135. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  136. if (!result.has_value()) {
  137. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  138. return;
  139. }
  140. m_last_found_index = result.value();
  141. }
  142. m_editor->update();
  143. }
  144. });
  145. 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&) {
  146. int new_offset;
  147. auto result = GoToOffsetDialog::show(
  148. window(),
  149. m_goto_history,
  150. new_offset,
  151. m_editor->selection_start_offset(),
  152. m_editor->buffer_size());
  153. if (result == GUI::InputBox::ExecOK) {
  154. m_editor->highlight(new_offset, new_offset);
  155. m_editor->update();
  156. }
  157. });
  158. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  159. m_toolbar_container->set_visible(action.is_checked());
  160. Config::write_bool("HexEditor", "Layout", "ShowToolbar", action.is_checked());
  161. });
  162. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  163. set_search_results_visible(action.is_checked());
  164. });
  165. m_copy_hex_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&) {
  166. m_editor->copy_selected_hex_to_clipboard();
  167. });
  168. m_copy_hex_action->set_enabled(false);
  169. m_copy_text_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&) {
  170. m_editor->copy_selected_text_to_clipboard();
  171. });
  172. m_copy_text_action->set_enabled(false);
  173. m_copy_as_c_code_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&) {
  174. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  175. });
  176. m_copy_as_c_code_action->set_enabled(false);
  177. m_fill_selection_action = GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  178. String value;
  179. if (GUI::InputBox::show(window(), value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  180. auto fill_byte = strtol(value.characters(), nullptr, 16);
  181. m_editor->fill_selection(fill_byte);
  182. }
  183. });
  184. m_fill_selection_action->set_enabled(false);
  185. m_toolbar->add_action(*m_new_action);
  186. m_toolbar->add_action(*m_open_action);
  187. m_toolbar->add_action(*m_save_action);
  188. m_toolbar->add_separator();
  189. m_toolbar->add_action(*m_find_action);
  190. m_toolbar->add_action(*m_goto_offset_action);
  191. m_statusbar->segment(0).set_clickable(true);
  192. m_statusbar->segment(0).set_action(*m_goto_offset_action);
  193. m_editor->set_focus(true);
  194. }
  195. void HexEditorWidget::initialize_menubar(GUI::Window& window)
  196. {
  197. auto& file_menu = window.add_menu("&File");
  198. file_menu.add_action(*m_new_action);
  199. file_menu.add_action(*m_open_action);
  200. file_menu.add_action(*m_save_action);
  201. file_menu.add_action(*m_save_as_action);
  202. file_menu.add_separator();
  203. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  204. if (!request_close())
  205. return;
  206. GUI::Application::the()->quit();
  207. }));
  208. auto& edit_menu = window.add_menu("&Edit");
  209. edit_menu.add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  210. m_editor->select_all();
  211. m_editor->update();
  212. }));
  213. edit_menu.add_action(*m_fill_selection_action);
  214. edit_menu.add_separator();
  215. edit_menu.add_action(*m_copy_hex_action);
  216. edit_menu.add_action(*m_copy_text_action);
  217. edit_menu.add_action(*m_copy_as_c_code_action);
  218. edit_menu.add_separator();
  219. edit_menu.add_action(*m_find_action);
  220. 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&) {
  221. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  222. GUI::MessageBox::show(&window, "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  223. return;
  224. }
  225. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  226. if (!result.has_value()) {
  227. GUI::MessageBox::show(&window, String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  228. return;
  229. }
  230. m_editor->update();
  231. m_last_found_index = result.value();
  232. }));
  233. 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&) {
  234. int min_length = 4;
  235. auto matches = m_editor->find_all_strings(min_length);
  236. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  237. m_search_results->update();
  238. if (matches.is_empty()) {
  239. GUI::MessageBox::show(&window, "No strings found in this file", "Not found", GUI::MessageBox::Type::Warning);
  240. return;
  241. }
  242. set_search_results_visible(true);
  243. m_editor->update();
  244. }));
  245. edit_menu.add_separator();
  246. edit_menu.add_action(*m_goto_offset_action);
  247. auto& view_menu = window.add_menu("&View");
  248. auto show_toolbar = Config::read_bool("HexEditor", "Layout", "ShowToolbar", true);
  249. m_layout_toolbar_action->set_checked(show_toolbar);
  250. m_toolbar_container->set_visible(show_toolbar);
  251. view_menu.add_action(*m_layout_toolbar_action);
  252. view_menu.add_action(*m_layout_search_results_action);
  253. view_menu.add_separator();
  254. auto bytes_per_row = Config::read_i32("HexEditor", "Layout", "BytesPerRow", 16);
  255. m_editor->set_bytes_per_row(bytes_per_row);
  256. m_editor->update();
  257. m_bytes_per_row_actions.set_exclusive(true);
  258. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  259. for (int i = 8; i <= 32; i += 8) {
  260. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  261. m_editor->set_bytes_per_row(i);
  262. m_editor->update();
  263. Config::write_i32("HexEditor", "Layout", "BytesPerRow", i);
  264. });
  265. m_bytes_per_row_actions.add_action(action);
  266. bytes_per_row_menu.add_action(action);
  267. if (i == bytes_per_row)
  268. action->set_checked(true);
  269. }
  270. auto& help_menu = window.add_menu("&Help");
  271. help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), &window));
  272. }
  273. void HexEditorWidget::set_path(StringView path)
  274. {
  275. if (path.is_empty()) {
  276. m_path = {};
  277. m_name = {};
  278. m_extension = {};
  279. } else {
  280. auto lexical_path = LexicalPath(path);
  281. m_path = lexical_path.string();
  282. m_name = lexical_path.title();
  283. m_extension = lexical_path.extension();
  284. }
  285. update_title();
  286. }
  287. void HexEditorWidget::update_title()
  288. {
  289. StringBuilder builder;
  290. if (m_path.is_empty())
  291. builder.append("Untitled");
  292. else
  293. builder.append(m_path);
  294. builder.append("[*] - Hex Editor");
  295. window()->set_title(builder.to_string());
  296. }
  297. void HexEditorWidget::open_file(NonnullRefPtr<Core::File> file)
  298. {
  299. window()->set_modified(false);
  300. m_editor->open_file(file);
  301. set_path(file->filename());
  302. }
  303. bool HexEditorWidget::request_close()
  304. {
  305. if (!window()->is_modified())
  306. return true;
  307. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path);
  308. if (result == GUI::MessageBox::ExecYes) {
  309. m_save_action->activate();
  310. return !window()->is_modified();
  311. }
  312. return result == GUI::MessageBox::ExecNo;
  313. }
  314. void HexEditorWidget::set_search_results_visible(bool visible)
  315. {
  316. m_layout_search_results_action->set_checked(visible);
  317. m_search_results_container->set_visible(visible);
  318. }
  319. void HexEditorWidget::drop_event(GUI::DropEvent& event)
  320. {
  321. event.accept();
  322. if (event.mime_data().has_urls()) {
  323. auto urls = event.mime_data().urls();
  324. if (urls.is_empty())
  325. return;
  326. window()->move_to_front();
  327. // TODO: A drop event should be considered user consent for opening a file
  328. auto response = FileSystemAccessClient::Client::the().try_request_file(window(), urls.first().path(), Core::OpenMode::ReadOnly);
  329. if (response.is_error())
  330. return;
  331. open_file(response.value());
  332. }
  333. }