HexEditorWidget.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 <AK/Optional.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/File.h>
  11. #include <LibGUI/Action.h>
  12. #include <LibGUI/BoxLayout.h>
  13. #include <LibGUI/Button.h>
  14. #include <LibGUI/FilePicker.h>
  15. #include <LibGUI/InputBox.h>
  16. #include <LibGUI/Menu.h>
  17. #include <LibGUI/Menubar.h>
  18. #include <LibGUI/MessageBox.h>
  19. #include <LibGUI/Statusbar.h>
  20. #include <LibGUI/TextBox.h>
  21. #include <LibGUI/TextEditor.h>
  22. #include <LibGUI/Toolbar.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. HexEditorWidget::HexEditorWidget()
  26. {
  27. set_fill_with_background_color(true);
  28. set_layout<GUI::VerticalBoxLayout>();
  29. layout()->set_spacing(2);
  30. m_editor = add<HexEditor>();
  31. m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
  32. m_statusbar->set_text(0, String::formatted("Offset: {:#08X}", position));
  33. m_statusbar->set_text(1, String::formatted("Edit Mode: {}", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text"));
  34. m_statusbar->set_text(2, String::formatted("Selection Start: {}", selection_start));
  35. m_statusbar->set_text(3, String::formatted("Selection End: {}", selection_end));
  36. m_statusbar->set_text(4, String::formatted("Selected Bytes: {}", abs(selection_end - selection_start) + 1));
  37. };
  38. m_editor->on_change = [this] {
  39. bool was_dirty = m_document_dirty;
  40. m_document_dirty = true;
  41. if (!was_dirty)
  42. update_title();
  43. };
  44. m_statusbar = add<GUI::Statusbar>(5);
  45. 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&) {
  46. if (m_document_dirty) {
  47. if (GUI::MessageBox::show(window(), "Save changes to current file first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel) != GUI::Dialog::ExecResult::ExecOK)
  48. return;
  49. m_save_action->activate();
  50. }
  51. String value;
  52. if (GUI::InputBox::show(window(), value, "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
  53. auto file_size = value.to_int();
  54. if (file_size.has_value() && file_size.value() > 0) {
  55. m_document_dirty = false;
  56. m_editor->set_buffer(ByteBuffer::create_zeroed(file_size.value()));
  57. set_path(LexicalPath());
  58. update_title();
  59. } else {
  60. GUI::MessageBox::show(window(), "Invalid file size entered.", "Error", GUI::MessageBox::Type::Error);
  61. }
  62. }
  63. });
  64. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  65. Optional<String> open_path = GUI::FilePicker::get_open_filepath(window());
  66. if (!open_path.has_value())
  67. return;
  68. open_file(open_path.value());
  69. });
  70. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  71. if (!m_path.is_empty()) {
  72. if (!m_editor->write_to_file(m_path)) {
  73. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  74. } else {
  75. m_document_dirty = false;
  76. update_title();
  77. }
  78. return;
  79. }
  80. m_save_as_action->activate();
  81. });
  82. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  83. Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(), m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "bin" : m_extension);
  84. if (!save_path.has_value())
  85. return;
  86. if (!m_editor->write_to_file(save_path.value())) {
  87. GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
  88. return;
  89. }
  90. m_document_dirty = false;
  91. set_path(LexicalPath(save_path.value()));
  92. dbgln("Wrote document to {}", save_path.value());
  93. });
  94. m_editor->set_focus(true);
  95. }
  96. HexEditorWidget::~HexEditorWidget()
  97. {
  98. }
  99. void HexEditorWidget::initialize_menubar(GUI::Menubar& menubar)
  100. {
  101. auto& file_menu = menubar.add_menu("&File");
  102. file_menu.add_action(*m_new_action);
  103. file_menu.add_action(*m_open_action);
  104. file_menu.add_action(*m_save_action);
  105. file_menu.add_action(*m_save_as_action);
  106. file_menu.add_separator();
  107. file_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  108. if (!request_close())
  109. return;
  110. GUI::Application::the()->quit();
  111. }));
  112. m_goto_decimal_offset_action = GUI::Action::create("Go to Offset (&Decimal)...", { Mod_Ctrl | Mod_Shift, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) {
  113. String value;
  114. if (GUI::InputBox::show(window(), value, "Enter decimal offset:", "Go to Offset") == GUI::InputBox::ExecOK && !value.is_empty()) {
  115. auto new_offset = value.to_int();
  116. if (new_offset.has_value())
  117. m_editor->set_position(new_offset.value());
  118. }
  119. });
  120. m_goto_hex_offset_action = GUI::Action::create("Go to Offset (&Hex)...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) {
  121. String value;
  122. if (GUI::InputBox::show(window(), value, "Enter hexadecimal offset:", "Go to Offset") == GUI::InputBox::ExecOK && !value.is_empty()) {
  123. auto new_offset = strtol(value.characters(), nullptr, 16);
  124. m_editor->set_position(new_offset);
  125. }
  126. });
  127. auto& edit_menu = menubar.add_menu("&Edit");
  128. edit_menu.add_action(GUI::Action::create("&Fill Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  129. String value;
  130. if (GUI::InputBox::show(window(), value, "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
  131. auto fill_byte = strtol(value.characters(), nullptr, 16);
  132. m_editor->fill_selection(fill_byte);
  133. }
  134. }));
  135. edit_menu.add_separator();
  136. edit_menu.add_action(*m_goto_decimal_offset_action);
  137. edit_menu.add_action(*m_goto_hex_offset_action);
  138. edit_menu.add_separator();
  139. edit_menu.add_action(GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  140. m_editor->copy_selected_hex_to_clipboard();
  141. }));
  142. 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&) {
  143. m_editor->copy_selected_text_to_clipboard();
  144. }));
  145. edit_menu.add_action(GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  146. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  147. }));
  148. edit_menu.add_separator();
  149. edit_menu.add_action(GUI::Action::create("&Find", { Mod_Ctrl, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"), [&](const GUI::Action&) {
  150. auto old_buffer = m_search_buffer.isolated_copy();
  151. if (FindDialog::show(window(), m_search_text, m_search_buffer) == GUI::InputBox::ExecOK) {
  152. bool same_buffers = false;
  153. if (old_buffer.size() == m_search_buffer.size()) {
  154. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  155. same_buffers = true;
  156. }
  157. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  158. if (result == -1) {
  159. GUI::MessageBox::show(window(), String::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  160. return;
  161. }
  162. m_last_found_index = result;
  163. }
  164. }));
  165. 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&) {
  166. if (m_search_text.is_empty() || m_search_buffer.is_empty() || m_search_buffer.is_null()) {
  167. GUI::MessageBox::show(window(), "Nothing to search for", "Not found", GUI::MessageBox::Type::Warning);
  168. return;
  169. }
  170. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  171. if (!result) {
  172. GUI::MessageBox::show(window(), String::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not found", GUI::MessageBox::Type::Warning);
  173. return;
  174. }
  175. m_editor->update();
  176. m_last_found_index = result;
  177. }));
  178. auto& view_menu = menubar.add_menu("&View");
  179. m_bytes_per_row_actions.set_exclusive(true);
  180. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per &Row");
  181. for (int i = 8; i <= 32; i += 8) {
  182. auto action = GUI::Action::create_checkable(String::number(i), [this, i](auto&) {
  183. m_editor->set_bytes_per_row(i);
  184. m_editor->update();
  185. });
  186. m_bytes_per_row_actions.add_action(action);
  187. bytes_per_row_menu.add_action(action);
  188. if (i == 16)
  189. action->set_checked(true);
  190. }
  191. auto& help_menu = menubar.add_menu("&Help");
  192. help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("app-hex-editor"), window()));
  193. }
  194. void HexEditorWidget::set_path(const LexicalPath& lexical_path)
  195. {
  196. m_path = lexical_path.string();
  197. m_name = lexical_path.title();
  198. m_extension = lexical_path.extension();
  199. update_title();
  200. }
  201. void HexEditorWidget::update_title()
  202. {
  203. StringBuilder builder;
  204. builder.append(m_path);
  205. if (m_document_dirty)
  206. builder.append(" (*)");
  207. builder.append(" - Hex Editor");
  208. window()->set_title(builder.to_string());
  209. }
  210. void HexEditorWidget::open_file(const String& path)
  211. {
  212. auto file = Core::File::construct(path);
  213. if (!file->open(Core::IODevice::ReadOnly)) {
  214. GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
  215. return;
  216. }
  217. m_document_dirty = false;
  218. 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.
  219. set_path(LexicalPath(path));
  220. }
  221. bool HexEditorWidget::request_close()
  222. {
  223. if (!m_document_dirty)
  224. return true;
  225. 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);
  226. return result == GUI::MessageBox::ExecOK;
  227. }