HexEditorWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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: {}", m_editor->selection_size()));
  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. String value;
  67. if (request_close() && GUI::InputBox::show(window(), value, "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
  68. auto file_size = value.to_int();
  69. if (file_size.has_value() && file_size.value() > 0) {
  70. m_document_dirty = false;
  71. m_editor->set_buffer(ByteBuffer::create_zeroed(file_size.value()));
  72. set_path({});
  73. update_title();
  74. } else {
  75. GUI::MessageBox::show(window(), "Invalid file size entered.", "Error", GUI::MessageBox::Type::Error);
  76. }
  77. }
  78. });
  79. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  80. Optional<String> open_path = GUI::FilePicker::get_open_filepath(window());
  81. if (!open_path.has_value())
  82. return;
  83. if (m_document_dirty) {
  84. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  85. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  86. m_save_action->activate();
  87. if (save_document_first_result != GUI::Dialog::ExecResult::ExecNo && m_document_dirty)
  88. return;
  89. }
  90. open_file(open_path.value());
  91. });
  92. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  93. if (!m_path.is_empty()) {
  94. if (!m_editor->write_to_file(m_path)) {
  95. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  96. } else {
  97. m_document_dirty = false;
  98. update_title();
  99. }
  100. return;
  101. }
  102. m_save_as_action->activate();
  103. });
  104. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  105. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(), m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "bin" : m_extension);
  106. if (!save_path.has_value()) {
  107. dbgln("GUI::FilePicker: Cancel button clicked");
  108. return;
  109. }
  110. if (!m_editor->write_to_file(save_path.value())) {
  111. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  112. return;
  113. }
  114. m_document_dirty = false;
  115. set_path(save_path.value());
  116. dbgln("Wrote document to {}", save_path.value());
  117. });
  118. m_find_action = GUI::Action::create("&Find", { Mod_Ctrl, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](const GUI::Action&) {
  119. auto old_buffer = m_search_buffer;
  120. bool find_all = false;
  121. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecOK) {
  122. if (find_all) {
  123. auto matches = m_editor->find_all(m_search_buffer, 0);
  124. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  125. m_search_results->update();
  126. if (matches.is_empty()) {
  127. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  128. return;
  129. }
  130. 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);
  131. set_search_results_visible(true);
  132. } else {
  133. bool same_buffers = false;
  134. if (old_buffer.size() == m_search_buffer.size()) {
  135. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  136. same_buffers = true;
  137. }
  138. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  139. if (result == -1) {
  140. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  141. return;
  142. }
  143. m_last_found_index = result;
  144. }
  145. m_editor->update();
  146. }
  147. });
  148. 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&) {
  149. int new_offset;
  150. auto result = GoToOffsetDialog::show(
  151. window(),
  152. m_goto_history,
  153. new_offset,
  154. m_editor->selection_start_offset(),
  155. m_editor->buffer_size());
  156. if (result == GUI::InputBox::ExecOK) {
  157. m_editor->highlight(new_offset, new_offset);
  158. m_editor->update();
  159. }
  160. });
  161. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  162. m_toolbar_container->set_visible(action.is_checked());
  163. m_config->write_bool_entry("Layout", "ShowToolbar", action.is_checked());
  164. m_config->sync();
  165. });
  166. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  167. set_search_results_visible(action.is_checked());
  168. });
  169. m_toolbar->add_action(*m_new_action);
  170. m_toolbar->add_action(*m_open_action);
  171. m_toolbar->add_action(*m_save_action);
  172. m_toolbar->add_separator();
  173. m_toolbar->add_action(*m_find_action);
  174. m_toolbar->add_action(*m_goto_offset_action);
  175. m_editor->set_focus(true);
  176. }
  177. HexEditorWidget::~HexEditorWidget()
  178. {
  179. }
  180. void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar)
  181. {
  182. auto& file_menu = menubar.add_menu("&File");
  183. file_menu.add_action(*m_new_action);
  184. file_menu.add_action(*m_open_action);
  185. file_menu.add_action(*m_save_action);
  186. file_menu.add_action(*m_save_as_action);
  187. file_menu.add_separator();
  188. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  189. if (!request_close())
  190. return;
  191. GUI::Application::the()->quit();
  192. }));
  193. auto& edit_menu = menubar.add_menu("&Edit");
  194. edit_menu.add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  195. m_editor->select_all();
  196. m_editor->update();
  197. }));
  198. edit_menu.add_action(GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  199. String value;
  200. if (GUI::InputBox::show(window(), value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  201. auto fill_byte = strtol(value.characters(), nullptr, 16);
  202. m_editor->fill_selection(fill_byte);
  203. }
  204. }));
  205. edit_menu.add_separator();
  206. edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  207. m_editor->copy_selected_hex_to_clipboard();
  208. }));
  209. 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&) {
  210. m_editor->copy_selected_text_to_clipboard();
  211. }));
  212. edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  213. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  214. }));
  215. edit_menu.add_separator();
  216. edit_menu.add_action(*m_find_action);
  217. 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&) {
  218. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  219. GUI::MessageBox::show(window(), "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  220. return;
  221. }
  222. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  223. if (!result) {
  224. GUI::MessageBox::show(window(), String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  225. return;
  226. }
  227. m_editor->update();
  228. m_last_found_index = result;
  229. }));
  230. 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&) {
  231. int min_length = 4;
  232. auto matches = m_editor->find_all_strings(min_length);
  233. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  234. m_search_results->update();
  235. if (matches.is_empty()) {
  236. GUI::MessageBox::show(window(), "No strings found in this file", "Not found", GUI::MessageBox::Type::Warning);
  237. return;
  238. }
  239. set_search_results_visible(true);
  240. m_editor->update();
  241. }));
  242. edit_menu.add_separator();
  243. edit_menu.add_action(*m_goto_offset_action);
  244. auto& view_menu = menubar.add_menu("&View");
  245. auto show_toolbar = m_config->read_bool_entry("Layout", "ShowToolbar", true);
  246. m_layout_toolbar_action->set_checked(show_toolbar);
  247. m_toolbar_container->set_visible(show_toolbar);
  248. view_menu.add_action(*m_layout_toolbar_action);
  249. view_menu.add_action(*m_layout_search_results_action);
  250. view_menu.add_separator();
  251. auto bytes_per_row = m_config->read_num_entry("Layout", "BytesPerRow", 16);
  252. m_editor->set_bytes_per_row(bytes_per_row);
  253. m_editor->update();
  254. m_bytes_per_row_actions.set_exclusive(true);
  255. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  256. for (int i = 8; i <= 32; i += 8) {
  257. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  258. m_editor->set_bytes_per_row(i);
  259. m_editor->update();
  260. m_config->write_num_entry("Layout", "BytesPerRow", i);
  261. m_config->sync();
  262. });
  263. m_bytes_per_row_actions.add_action(action);
  264. bytes_per_row_menu.add_action(action);
  265. if (i == bytes_per_row)
  266. action->set_checked(true);
  267. }
  268. auto& help_menu = menubar.add_menu("&Help");
  269. help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), window()));
  270. }
  271. void HexEditorWidget::set_path(StringView const& path)
  272. {
  273. if (path.is_empty()) {
  274. m_path = {};
  275. m_name = {};
  276. m_extension = {};
  277. } else {
  278. auto lexical_path = LexicalPath(path);
  279. m_path = lexical_path.string();
  280. m_name = lexical_path.title();
  281. m_extension = lexical_path.extension();
  282. }
  283. update_title();
  284. }
  285. void HexEditorWidget::update_title()
  286. {
  287. StringBuilder builder;
  288. if (m_path.is_empty())
  289. builder.append("Untitled");
  290. else
  291. builder.append(m_path);
  292. if (m_document_dirty)
  293. builder.append(" (*)");
  294. builder.append(" - Hex Editor");
  295. window()->set_title(builder.to_string());
  296. }
  297. void HexEditorWidget::open_file(const String& path)
  298. {
  299. auto file = Core::File::construct(path);
  300. if (!file->open(Core::OpenMode::ReadOnly)) {
  301. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  302. return;
  303. }
  304. m_document_dirty = false;
  305. 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.
  306. set_path(path);
  307. }
  308. bool HexEditorWidget::request_close()
  309. {
  310. if (!m_document_dirty)
  311. return true;
  312. auto result = GUI::MessageBox::show(window(), "The file has been modified. Save before closing?", "Save changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  313. if (result == GUI::MessageBox::ExecCancel)
  314. return false;
  315. if (result == GUI::MessageBox::ExecYes) {
  316. m_save_action->activate();
  317. return m_document_dirty == false;
  318. }
  319. return true;
  320. }
  321. void HexEditorWidget::set_search_results_visible(bool visible)
  322. {
  323. m_layout_search_results_action->set_checked(visible);
  324. m_search_results_container->set_visible(visible);
  325. }