HexEditorWidget.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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/TextEditor.h>
  28. #include <LibGUI/Toolbar.h>
  29. #include <LibGUI/ToolbarContainer.h>
  30. #include <stdio.h>
  31. #include <string.h>
  32. REGISTER_WIDGET(HexEditor, HexEditor);
  33. HexEditorWidget::HexEditorWidget()
  34. {
  35. load_from_gml(hex_editor_window_gml);
  36. m_config = Core::ConfigFile::get_for_app("HexEditor");
  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: {}", abs(selection_end - selection_start)));
  49. };
  50. m_editor->on_change = [this] {
  51. bool was_dirty = m_document_dirty;
  52. m_document_dirty = true;
  53. if (!was_dirty)
  54. update_title();
  55. };
  56. m_search_results->set_activates_on_selection(true);
  57. m_search_results->on_activation = [this](const GUI::ModelIndex& index) {
  58. if (!index.is_valid())
  59. return;
  60. auto offset = index.data(GUI::ModelRole::Custom).to_i32();
  61. m_last_found_index = offset;
  62. m_editor->set_position(offset);
  63. m_editor->update();
  64. };
  65. 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&) {
  66. if (m_document_dirty) {
  67. if (GUI::MessageBox::show(window(), "Save changes to current file first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel) != GUI::Dialog::ExecResult::ExecOK)
  68. return;
  69. m_save_action->activate();
  70. }
  71. String value;
  72. if (GUI::InputBox::show(window(), value, "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
  73. auto file_size = value.to_int();
  74. if (file_size.has_value() && file_size.value() > 0) {
  75. m_document_dirty = false;
  76. m_editor->set_buffer(ByteBuffer::create_zeroed(file_size.value()));
  77. set_path(LexicalPath());
  78. update_title();
  79. } else {
  80. GUI::MessageBox::show(window(), "Invalid file size entered.", "Error", GUI::MessageBox::Type::Error);
  81. }
  82. }
  83. });
  84. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  85. Optional<String> open_path = GUI::FilePicker::get_open_filepath(window());
  86. if (!open_path.has_value())
  87. return;
  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. return;
  106. if (!m_editor->write_to_file(save_path.value())) {
  107. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  108. return;
  109. }
  110. m_document_dirty = false;
  111. set_path(LexicalPath(save_path.value()));
  112. dbgln("Wrote document to {}", save_path.value());
  113. });
  114. m_find_action = GUI::Action::create("&Find", { Mod_Ctrl, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](const GUI::Action&) {
  115. auto old_buffer = m_search_buffer;
  116. bool find_all = false;
  117. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecOK) {
  118. if (find_all) {
  119. auto matches = m_editor->find_all(m_search_buffer, 0);
  120. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  121. m_search_results->update();
  122. if (matches.is_empty()) {
  123. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  124. return;
  125. }
  126. 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);
  127. set_search_results_visible(true);
  128. } else {
  129. bool same_buffers = false;
  130. if (old_buffer.size() == m_search_buffer.size()) {
  131. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  132. same_buffers = true;
  133. }
  134. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  135. if (result == -1) {
  136. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  137. return;
  138. }
  139. m_last_found_index = result;
  140. }
  141. m_editor->update();
  142. }
  143. });
  144. m_goto_offset_action = GUI::Action::create("&Go to Offset ...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-to.png"), [this](const GUI::Action&) {
  145. int new_offset;
  146. auto result = GoToOffsetDialog::show(
  147. window(),
  148. m_goto_history,
  149. new_offset,
  150. m_editor->selection_start_offset(),
  151. m_editor->buffer_size());
  152. if (result == GUI::InputBox::ExecOK) {
  153. m_editor->highlight(new_offset, new_offset);
  154. m_editor->update();
  155. }
  156. });
  157. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  158. m_toolbar_container->set_visible(action.is_checked());
  159. m_config->write_bool_entry("Layout", "ShowToolbar", action.is_checked());
  160. m_config->sync();
  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_toolbar->add_action(*m_new_action);
  166. m_toolbar->add_action(*m_open_action);
  167. m_toolbar->add_action(*m_save_action);
  168. m_toolbar->add_separator();
  169. m_toolbar->add_action(*m_find_action);
  170. m_toolbar->add_action(*m_goto_offset_action);
  171. m_editor->set_focus(true);
  172. }
  173. HexEditorWidget::~HexEditorWidget()
  174. {
  175. }
  176. void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar)
  177. {
  178. auto& file_menu = menubar.add_menu("&File");
  179. file_menu.add_action(*m_new_action);
  180. file_menu.add_action(*m_open_action);
  181. file_menu.add_action(*m_save_action);
  182. file_menu.add_action(*m_save_as_action);
  183. file_menu.add_separator();
  184. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  185. if (!request_close())
  186. return;
  187. GUI::Application::the()->quit();
  188. }));
  189. auto& edit_menu = menubar.add_menu("&Edit");
  190. edit_menu.add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  191. m_editor->select_all();
  192. m_editor->update();
  193. }));
  194. edit_menu.add_action(GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  195. String value;
  196. if (GUI::InputBox::show(window(), value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  197. auto fill_byte = strtol(value.characters(), nullptr, 16);
  198. m_editor->fill_selection(fill_byte);
  199. }
  200. }));
  201. edit_menu.add_separator();
  202. edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  203. m_editor->copy_selected_hex_to_clipboard();
  204. }));
  205. edit_menu.add_action(GUI::Action::create("Copy &Text", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), [&](const GUI::Action&) {
  206. m_editor->copy_selected_text_to_clipboard();
  207. }));
  208. edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  209. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  210. }));
  211. edit_menu.add_separator();
  212. edit_menu.add_action(*m_find_action);
  213. edit_menu.add_action(GUI::Action::create("Find &Next", { Mod_None, Key_F3 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find-next.png"), [&](const GUI::Action&) {
  214. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  215. GUI::MessageBox::show(window(), "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  216. return;
  217. }
  218. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  219. if (!result) {
  220. GUI::MessageBox::show(window(), String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  221. return;
  222. }
  223. m_editor->update();
  224. m_last_found_index = result;
  225. }));
  226. edit_menu.add_action(GUI::Action::create("Find All &Strings", { Mod_Ctrl | Mod_Shift, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](const GUI::Action&) {
  227. int min_length = 4;
  228. auto matches = m_editor->find_all_strings(min_length);
  229. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  230. m_search_results->update();
  231. if (matches.is_empty()) {
  232. GUI::MessageBox::show(window(), "No strings found in this file", "Not found", GUI::MessageBox::Type::Warning);
  233. return;
  234. }
  235. set_search_results_visible(true);
  236. m_editor->update();
  237. }));
  238. edit_menu.add_separator();
  239. edit_menu.add_action(*m_goto_offset_action);
  240. auto& view_menu = menubar.add_menu("&View");
  241. auto show_toolbar = m_config->read_bool_entry("Layout", "ShowToolbar", true);
  242. m_layout_toolbar_action->set_checked(show_toolbar);
  243. m_toolbar_container->set_visible(show_toolbar);
  244. view_menu.add_action(*m_layout_toolbar_action);
  245. view_menu.add_action(*m_layout_search_results_action);
  246. view_menu.add_separator();
  247. auto bytes_per_row = m_config->read_num_entry("Layout", "BytesPerRow", 16);
  248. m_editor->set_bytes_per_row(bytes_per_row);
  249. m_editor->update();
  250. m_bytes_per_row_actions.set_exclusive(true);
  251. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  252. for (int i = 8; i <= 32; i += 8) {
  253. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  254. m_editor->set_bytes_per_row(i);
  255. m_editor->update();
  256. m_config->write_num_entry("Layout", "BytesPerRow", i);
  257. m_config->sync();
  258. });
  259. m_bytes_per_row_actions.add_action(action);
  260. bytes_per_row_menu.add_action(action);
  261. if (i == bytes_per_row)
  262. action->set_checked(true);
  263. }
  264. auto& help_menu = menubar.add_menu("&Help");
  265. help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), window()));
  266. }
  267. void HexEditorWidget::set_path(const LexicalPath& lexical_path)
  268. {
  269. m_path = lexical_path.string();
  270. m_name = lexical_path.title();
  271. m_extension = lexical_path.extension();
  272. update_title();
  273. }
  274. void HexEditorWidget::update_title()
  275. {
  276. StringBuilder builder;
  277. builder.append(m_path);
  278. if (m_document_dirty)
  279. builder.append(" (*)");
  280. builder.append(" - Hex Editor");
  281. window()->set_title(builder.to_string());
  282. }
  283. void HexEditorWidget::open_file(const String& path)
  284. {
  285. auto file = Core::File::construct(path);
  286. if (!file->open(Core::OpenMode::ReadOnly)) {
  287. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  288. return;
  289. }
  290. m_document_dirty = false;
  291. 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.
  292. set_path(LexicalPath(path));
  293. }
  294. bool HexEditorWidget::request_close()
  295. {
  296. if (!m_document_dirty)
  297. return true;
  298. auto result = GUI::MessageBox::show(window(), "The file has been modified. Quit without saving?", "Quit without saving?", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel);
  299. return result == GUI::MessageBox::ExecOK;
  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. }