HexEditorWidget.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 <LibFileSystemAccessClient/Client.h>
  17. #include <LibGUI/Action.h>
  18. #include <LibGUI/BoxLayout.h>
  19. #include <LibGUI/Button.h>
  20. #include <LibGUI/FilePicker.h>
  21. #include <LibGUI/InputBox.h>
  22. #include <LibGUI/Menu.h>
  23. #include <LibGUI/Menubar.h>
  24. #include <LibGUI/MessageBox.h>
  25. #include <LibGUI/Model.h>
  26. #include <LibGUI/Statusbar.h>
  27. #include <LibGUI/TableView.h>
  28. #include <LibGUI/TextBox.h>
  29. #include <LibGUI/Toolbar.h>
  30. #include <LibGUI/ToolbarContainer.h>
  31. #include <string.h>
  32. REGISTER_WIDGET(HexEditor, HexEditor);
  33. HexEditorWidget::HexEditorWidget()
  34. {
  35. load_from_gml(hex_editor_window_gml);
  36. m_toolbar = *find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  37. m_toolbar_container = *find_descendant_of_type_named<GUI::ToolbarContainer>("toolbar_container");
  38. m_editor = *find_descendant_of_type_named<HexEditor>("editor");
  39. m_statusbar = *find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  40. m_search_results = *find_descendant_of_type_named<GUI::TableView>("search_results");
  41. m_search_results_container = *find_descendant_of_type_named<GUI::Widget>("search_results_container");
  42. m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
  43. m_statusbar->set_text(0, String::formatted("Offset: {:#08X}", position));
  44. m_statusbar->set_text(1, String::formatted("Edit Mode: {}", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text"));
  45. m_statusbar->set_text(2, String::formatted("Selection Start: {}", selection_start));
  46. m_statusbar->set_text(3, String::formatted("Selection End: {}", selection_end));
  47. m_statusbar->set_text(4, String::formatted("Selected Bytes: {}", m_editor->selection_size()));
  48. };
  49. m_editor->on_change = [this] {
  50. bool was_dirty = m_document_dirty;
  51. m_document_dirty = true;
  52. if (!was_dirty)
  53. update_title();
  54. };
  55. m_search_results->set_activates_on_selection(true);
  56. m_search_results->on_activation = [this](const GUI::ModelIndex& index) {
  57. if (!index.is_valid())
  58. return;
  59. auto offset = index.data(GUI::ModelRole::Custom).to_i32();
  60. m_last_found_index = offset;
  61. m_editor->set_position(offset);
  62. m_editor->update();
  63. };
  64. 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&) {
  65. String value;
  66. if (request_close() && GUI::InputBox::show(window(), value, "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
  67. auto file_size = value.to_int();
  68. if (file_size.has_value() && file_size.value() > 0) {
  69. m_document_dirty = false;
  70. auto buffer_result = ByteBuffer::create_zeroed(file_size.value());
  71. if (!buffer_result.has_value()) {
  72. GUI::MessageBox::show(window(), "Entered file size is too large.", "Error", GUI::MessageBox::Type::Error);
  73. return;
  74. }
  75. m_editor->set_buffer(buffer_result.release_value());
  76. set_path({});
  77. update_title();
  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. auto response = FileSystemAccessClient::Client::the().open_file(window()->window_id());
  85. if (response.error != 0) {
  86. if (response.error != -1)
  87. GUI::MessageBox::show_error(window(), String::formatted("Opening \"{}\" failed: {}", *response.chosen_file, strerror(response.error)));
  88. return;
  89. }
  90. if (m_document_dirty) {
  91. auto save_document_first_result = GUI::MessageBox::show(window(), "Save changes to current document first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  92. if (save_document_first_result == GUI::Dialog::ExecResult::ExecYes)
  93. m_save_action->activate();
  94. if (save_document_first_result != GUI::Dialog::ExecResult::ExecNo && m_document_dirty)
  95. return;
  96. }
  97. open_file(*response.fd, *response.chosen_file);
  98. });
  99. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  100. if (m_path.is_empty())
  101. return m_save_as_action->activate();
  102. auto response = FileSystemAccessClient::Client::the().request_file(window()->window_id(), m_path, Core::OpenMode::Truncate | Core::OpenMode::WriteOnly);
  103. if (response.error != 0) {
  104. if (response.error != -1)
  105. GUI::MessageBox::show_error(window(), String::formatted("Unable to save file: {}", strerror(response.error)));
  106. return;
  107. }
  108. if (!m_editor->write_to_file(*response.fd)) {
  109. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  110. } else {
  111. m_document_dirty = false;
  112. update_title();
  113. }
  114. return;
  115. });
  116. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  117. auto response = FileSystemAccessClient::Client::the().save_file(window()->window_id(), m_name, m_extension);
  118. if (response.error != 0) {
  119. if (response.error != -1)
  120. GUI::MessageBox::show_error(window(), String::formatted("Saving \"{}\" failed: {}", *response.chosen_file, strerror(response.error)));
  121. return;
  122. }
  123. if (!m_editor->write_to_file(*response.fd)) {
  124. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  125. return;
  126. }
  127. m_document_dirty = false;
  128. set_path(*response.chosen_file);
  129. dbgln("Wrote document to {}", *response.chosen_file);
  130. });
  131. 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&) {
  132. auto old_buffer = m_search_buffer;
  133. bool find_all = false;
  134. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecOK) {
  135. if (find_all) {
  136. auto matches = m_editor->find_all(m_search_buffer, 0);
  137. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  138. m_search_results->update();
  139. if (matches.is_empty()) {
  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. 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);
  144. set_search_results_visible(true);
  145. } else {
  146. bool same_buffers = false;
  147. if (old_buffer.size() == m_search_buffer.size()) {
  148. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  149. same_buffers = true;
  150. }
  151. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  152. if (result == -1) {
  153. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  154. return;
  155. }
  156. m_last_found_index = result;
  157. }
  158. m_editor->update();
  159. }
  160. });
  161. 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&) {
  162. int new_offset;
  163. auto result = GoToOffsetDialog::show(
  164. window(),
  165. m_goto_history,
  166. new_offset,
  167. m_editor->selection_start_offset(),
  168. m_editor->buffer_size());
  169. if (result == GUI::InputBox::ExecOK) {
  170. m_editor->highlight(new_offset, new_offset);
  171. m_editor->update();
  172. }
  173. });
  174. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  175. m_toolbar_container->set_visible(action.is_checked());
  176. Config::write_bool("HexEditor", "Layout", "ShowToolbar", action.is_checked());
  177. });
  178. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  179. set_search_results_visible(action.is_checked());
  180. });
  181. m_toolbar->add_action(*m_new_action);
  182. m_toolbar->add_action(*m_open_action);
  183. m_toolbar->add_action(*m_save_action);
  184. m_toolbar->add_separator();
  185. m_toolbar->add_action(*m_find_action);
  186. m_toolbar->add_action(*m_goto_offset_action);
  187. m_editor->set_focus(true);
  188. }
  189. HexEditorWidget::~HexEditorWidget()
  190. {
  191. }
  192. void HexEditorWidget::initialize_menubar(GUI::Window& window)
  193. {
  194. auto& file_menu = window.add_menu("&File");
  195. file_menu.add_action(*m_new_action);
  196. file_menu.add_action(*m_open_action);
  197. file_menu.add_action(*m_save_action);
  198. file_menu.add_action(*m_save_as_action);
  199. file_menu.add_separator();
  200. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  201. if (!request_close())
  202. return;
  203. GUI::Application::the()->quit();
  204. }));
  205. auto& edit_menu = window.add_menu("&Edit");
  206. edit_menu.add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  207. m_editor->select_all();
  208. m_editor->update();
  209. }));
  210. edit_menu.add_action(GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  211. String value;
  212. if (GUI::InputBox::show(&window, value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  213. auto fill_byte = strtol(value.characters(), nullptr, 16);
  214. m_editor->fill_selection(fill_byte);
  215. }
  216. }));
  217. edit_menu.add_separator();
  218. edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  219. m_editor->copy_selected_hex_to_clipboard();
  220. }));
  221. 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&) {
  222. m_editor->copy_selected_text_to_clipboard();
  223. }));
  224. edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  225. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  226. }));
  227. edit_menu.add_separator();
  228. edit_menu.add_action(*m_find_action);
  229. 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&) {
  230. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  231. GUI::MessageBox::show(&window, "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  232. return;
  233. }
  234. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  235. if (!result) {
  236. GUI::MessageBox::show(&window, String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  237. return;
  238. }
  239. m_editor->update();
  240. m_last_found_index = result;
  241. }));
  242. 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&) {
  243. int min_length = 4;
  244. auto matches = m_editor->find_all_strings(min_length);
  245. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  246. m_search_results->update();
  247. if (matches.is_empty()) {
  248. GUI::MessageBox::show(&window, "No strings found in this file", "Not found", GUI::MessageBox::Type::Warning);
  249. return;
  250. }
  251. set_search_results_visible(true);
  252. m_editor->update();
  253. }));
  254. edit_menu.add_separator();
  255. edit_menu.add_action(*m_goto_offset_action);
  256. auto& view_menu = window.add_menu("&View");
  257. auto show_toolbar = Config::read_bool("HexEditor", "Layout", "ShowToolbar", true);
  258. m_layout_toolbar_action->set_checked(show_toolbar);
  259. m_toolbar_container->set_visible(show_toolbar);
  260. view_menu.add_action(*m_layout_toolbar_action);
  261. view_menu.add_action(*m_layout_search_results_action);
  262. view_menu.add_separator();
  263. auto bytes_per_row = Config::read_i32("HexEditor", "Layout", "BytesPerRow", 16);
  264. m_editor->set_bytes_per_row(bytes_per_row);
  265. m_editor->update();
  266. m_bytes_per_row_actions.set_exclusive(true);
  267. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  268. for (int i = 8; i <= 32; i += 8) {
  269. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  270. m_editor->set_bytes_per_row(i);
  271. m_editor->update();
  272. Config::write_i32("HexEditor", "Layout", "BytesPerRow", i);
  273. });
  274. m_bytes_per_row_actions.add_action(action);
  275. bytes_per_row_menu.add_action(action);
  276. if (i == bytes_per_row)
  277. action->set_checked(true);
  278. }
  279. auto& help_menu = window.add_menu("&Help");
  280. help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), &window));
  281. }
  282. void HexEditorWidget::set_path(StringView const& path)
  283. {
  284. if (path.is_empty()) {
  285. m_path = {};
  286. m_name = {};
  287. m_extension = {};
  288. } else {
  289. auto lexical_path = LexicalPath(path);
  290. m_path = lexical_path.string();
  291. m_name = lexical_path.title();
  292. m_extension = lexical_path.extension();
  293. }
  294. update_title();
  295. }
  296. void HexEditorWidget::update_title()
  297. {
  298. StringBuilder builder;
  299. if (m_path.is_empty())
  300. builder.append("Untitled");
  301. else
  302. builder.append(m_path);
  303. if (m_document_dirty)
  304. builder.append(" (*)");
  305. builder.append(" - Hex Editor");
  306. window()->set_title(builder.to_string());
  307. }
  308. void HexEditorWidget::open_file(int fd, String const& path)
  309. {
  310. VERIFY(path.starts_with("/"sv));
  311. auto file = Core::File::construct();
  312. if (!file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::Yes) && file->error() != ENOENT) {
  313. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  314. return;
  315. }
  316. if (file->is_device()) {
  317. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: Can't open device files", path), "Error", GUI::MessageBox::Type::Error);
  318. return;
  319. }
  320. if (file->is_directory()) {
  321. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: Can't open directories", path), "Error", GUI::MessageBox::Type::Error);
  322. return;
  323. }
  324. m_document_dirty = false;
  325. 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.
  326. set_path(path);
  327. }
  328. bool HexEditorWidget::request_close()
  329. {
  330. if (!m_document_dirty)
  331. return true;
  332. auto result = GUI::MessageBox::show(window(), "The file has been modified. Save before closing?", "Save changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
  333. if (result == GUI::MessageBox::ExecCancel)
  334. return false;
  335. if (result == GUI::MessageBox::ExecYes) {
  336. m_save_action->activate();
  337. return m_document_dirty == false;
  338. }
  339. return true;
  340. }
  341. void HexEditorWidget::set_search_results_visible(bool visible)
  342. {
  343. m_layout_search_results_action->set_checked(visible);
  344. m_search_results_container->set_visible(visible);
  345. }
  346. void HexEditorWidget::drop_event(GUI::DropEvent& event)
  347. {
  348. event.accept();
  349. if (event.mime_data().has_urls()) {
  350. auto urls = event.mime_data().urls();
  351. if (urls.is_empty())
  352. return;
  353. window()->move_to_front();
  354. // TODO: A drop event should be considered user consent for opening a file
  355. auto file_response = FileSystemAccessClient::Client::the().request_file(window()->window_id(), urls.first().path(), Core::OpenMode::ReadOnly);
  356. if (file_response.error != 0)
  357. return;
  358. open_file(*file_response.fd, urls.first().path());
  359. }
  360. }