HexEditorWidget.cpp 15 KB

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