HexEditorWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Mustafa Quraish <mustafa@cs.toronto.edu>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "HexEditorWidget.h"
  8. #include "FindDialog.h"
  9. #include "GoToOffsetDialog.h"
  10. #include "SearchResultsModel.h"
  11. #include <AK/Optional.h>
  12. #include <AK/StringBuilder.h>
  13. #include <Applications/HexEditor/HexEditorWindowGML.h>
  14. #include <LibConfig/Client.h>
  15. #include <LibCore/File.h>
  16. #include <LibGUI/Action.h>
  17. #include <LibGUI/BoxLayout.h>
  18. #include <LibGUI/Button.h>
  19. #include <LibGUI/FilePicker.h>
  20. #include <LibGUI/InputBox.h>
  21. #include <LibGUI/Menu.h>
  22. #include <LibGUI/Menubar.h>
  23. #include <LibGUI/MessageBox.h>
  24. #include <LibGUI/Model.h>
  25. #include <LibGUI/Statusbar.h>
  26. #include <LibGUI/TableView.h>
  27. #include <LibGUI/TextBox.h>
  28. #include <LibGUI/Toolbar.h>
  29. #include <LibGUI/ToolbarContainer.h>
  30. #include <string.h>
  31. REGISTER_WIDGET(HexEditor, HexEditor);
  32. HexEditorWidget::HexEditorWidget()
  33. {
  34. load_from_gml(hex_editor_window_gml);
  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. Config::write_bool("HexEditor", "Layout", "ShowToolbar", action.is_checked());
  162. });
  163. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  164. set_search_results_visible(action.is_checked());
  165. });
  166. m_toolbar->add_action(*m_new_action);
  167. m_toolbar->add_action(*m_open_action);
  168. m_toolbar->add_action(*m_save_action);
  169. m_toolbar->add_separator();
  170. m_toolbar->add_action(*m_find_action);
  171. m_toolbar->add_action(*m_goto_offset_action);
  172. m_editor->set_focus(true);
  173. }
  174. HexEditorWidget::~HexEditorWidget()
  175. {
  176. }
  177. void HexEditorWidget::initialize_menubar(GUI::Window& window)
  178. {
  179. auto& file_menu = window.add_menu("&File");
  180. file_menu.add_action(*m_new_action);
  181. file_menu.add_action(*m_open_action);
  182. file_menu.add_action(*m_save_action);
  183. file_menu.add_action(*m_save_as_action);
  184. file_menu.add_separator();
  185. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  186. if (!request_close())
  187. return;
  188. GUI::Application::the()->quit();
  189. }));
  190. auto& edit_menu = window.add_menu("&Edit");
  191. edit_menu.add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  192. m_editor->select_all();
  193. m_editor->update();
  194. }));
  195. edit_menu.add_action(GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  196. String value;
  197. if (GUI::InputBox::show(&window, value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  198. auto fill_byte = strtol(value.characters(), nullptr, 16);
  199. m_editor->fill_selection(fill_byte);
  200. }
  201. }));
  202. edit_menu.add_separator();
  203. edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  204. m_editor->copy_selected_hex_to_clipboard();
  205. }));
  206. 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&) {
  207. m_editor->copy_selected_text_to_clipboard();
  208. }));
  209. edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  210. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  211. }));
  212. edit_menu.add_separator();
  213. edit_menu.add_action(*m_find_action);
  214. 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&) {
  215. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  216. GUI::MessageBox::show(&window, "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  217. return;
  218. }
  219. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  220. if (!result) {
  221. GUI::MessageBox::show(&window, String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  222. return;
  223. }
  224. m_editor->update();
  225. m_last_found_index = result;
  226. }));
  227. 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&) {
  228. int min_length = 4;
  229. auto matches = m_editor->find_all_strings(min_length);
  230. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  231. m_search_results->update();
  232. if (matches.is_empty()) {
  233. GUI::MessageBox::show(&window, "No strings found in this file", "Not found", GUI::MessageBox::Type::Warning);
  234. return;
  235. }
  236. set_search_results_visible(true);
  237. m_editor->update();
  238. }));
  239. edit_menu.add_separator();
  240. edit_menu.add_action(*m_goto_offset_action);
  241. auto& view_menu = window.add_menu("&View");
  242. auto show_toolbar = Config::read_bool("HexEditor", "Layout", "ShowToolbar", true);
  243. m_layout_toolbar_action->set_checked(show_toolbar);
  244. m_toolbar_container->set_visible(show_toolbar);
  245. view_menu.add_action(*m_layout_toolbar_action);
  246. view_menu.add_action(*m_layout_search_results_action);
  247. view_menu.add_separator();
  248. auto bytes_per_row = Config::read_i32("HexEditor", "Layout", "BytesPerRow", 16);
  249. m_editor->set_bytes_per_row(bytes_per_row);
  250. m_editor->update();
  251. m_bytes_per_row_actions.set_exclusive(true);
  252. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  253. for (int i = 8; i <= 32; i += 8) {
  254. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  255. m_editor->set_bytes_per_row(i);
  256. m_editor->update();
  257. Config::write_i32("HexEditor", "Layout", "BytesPerRow", i);
  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 = window.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(StringView const& path)
  268. {
  269. if (path.is_empty()) {
  270. m_path = {};
  271. m_name = {};
  272. m_extension = {};
  273. } else {
  274. auto lexical_path = LexicalPath(path);
  275. m_path = lexical_path.string();
  276. m_name = lexical_path.title();
  277. m_extension = lexical_path.extension();
  278. }
  279. update_title();
  280. }
  281. void HexEditorWidget::update_title()
  282. {
  283. StringBuilder builder;
  284. if (m_path.is_empty())
  285. builder.append("Untitled");
  286. else
  287. builder.append(m_path);
  288. if (m_document_dirty)
  289. builder.append(" (*)");
  290. builder.append(" - Hex Editor");
  291. window()->set_title(builder.to_string());
  292. }
  293. void HexEditorWidget::open_file(const String& path)
  294. {
  295. auto file = Core::File::construct(path);
  296. if (!file->open(Core::OpenMode::ReadOnly)) {
  297. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  298. return;
  299. }
  300. m_document_dirty = false;
  301. 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.
  302. set_path(path);
  303. }
  304. bool HexEditorWidget::request_close()
  305. {
  306. if (!m_document_dirty)
  307. return true;
  308. auto result = GUI::MessageBox::show(window(), "The file has been modified. Save before closing?", "Save changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  309. if (result == GUI::MessageBox::ExecCancel)
  310. return false;
  311. if (result == GUI::MessageBox::ExecYes) {
  312. m_save_action->activate();
  313. return m_document_dirty == false;
  314. }
  315. return true;
  316. }
  317. void HexEditorWidget::set_search_results_visible(bool visible)
  318. {
  319. m_layout_search_results_action->set_checked(visible);
  320. m_search_results_container->set_visible(visible);
  321. }
  322. void HexEditorWidget::drop_event(GUI::DropEvent& event)
  323. {
  324. event.accept();
  325. if (event.mime_data().has_urls()) {
  326. auto urls = event.mime_data().urls();
  327. if (urls.is_empty())
  328. return;
  329. window()->move_to_front();
  330. open_file(urls.first().path());
  331. }
  332. }