HexEditorWidget.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "HexEditorWidget.h"
  27. #include <AK/Optional.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibCore/File.h>
  30. #include <LibGUI/AboutDialog.h>
  31. #include <LibGUI/Action.h>
  32. #include <LibGUI/BoxLayout.h>
  33. #include <LibGUI/Button.h>
  34. #include <LibGUI/FilePicker.h>
  35. #include <LibGUI/FontDatabase.h>
  36. #include <LibGUI/InputBox.h>
  37. #include <LibGUI/Menu.h>
  38. #include <LibGUI/MenuBar.h>
  39. #include <LibGUI/MessageBox.h>
  40. #include <LibGUI/StatusBar.h>
  41. #include <LibGUI/TextBox.h>
  42. #include <LibGUI/TextEditor.h>
  43. #include <LibGUI/ToolBar.h>
  44. #include <stdio.h>
  45. #include <string.h>
  46. HexEditorWidget::HexEditorWidget()
  47. {
  48. set_fill_with_background_color(true);
  49. set_layout<GUI::VerticalBoxLayout>();
  50. layout()->set_spacing(2);
  51. m_editor = add<HexEditor>();
  52. m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
  53. m_statusbar->set_text(0, String::format("Offset: %8X", position));
  54. m_statusbar->set_text(1, String::format("Edit Mode: %s", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text"));
  55. m_statusbar->set_text(2, String::format("Selection Start: %d", selection_start));
  56. m_statusbar->set_text(3, String::format("Selection End: %d", selection_end));
  57. m_statusbar->set_text(4, String::format("Selected Bytes: %d", (selection_end - selection_start) + 1));
  58. };
  59. m_editor->on_change = [this] {
  60. bool was_dirty = m_document_dirty;
  61. m_document_dirty = true;
  62. if (!was_dirty)
  63. update_title();
  64. };
  65. m_statusbar = add<GUI::StatusBar>(5);
  66. 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&) {
  67. if (m_document_dirty) {
  68. auto save_document_first_box = GUI::MessageBox::construct("Save Document First?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel, window());
  69. auto save_document_first_result = save_document_first_box->exec();
  70. if (save_document_first_result != GUI::Dialog::ExecResult::ExecOK)
  71. return;
  72. m_save_action->activate();
  73. }
  74. auto input_box = GUI::InputBox::construct("Enter new file size:", "New file size", window());
  75. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  76. auto valid = false;
  77. auto file_size = input_box->text_value().to_int(valid);
  78. if (valid && file_size > 0) {
  79. m_document_dirty = false;
  80. m_editor->set_buffer(ByteBuffer::create_zeroed(file_size));
  81. set_path(FileSystemPath());
  82. update_title();
  83. } else {
  84. GUI::MessageBox::show("Invalid file size entered.", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  85. }
  86. }
  87. });
  88. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  89. Optional<String> open_path = GUI::FilePicker::get_open_filepath();
  90. if (!open_path.has_value())
  91. return;
  92. open_file(open_path.value());
  93. });
  94. m_save_action = GUI::Action::create("Save", { Mod_Ctrl, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), [&](const GUI::Action&) {
  95. if (!m_path.is_empty()) {
  96. if (!m_editor->write_to_file(m_path)) {
  97. GUI::MessageBox::show("Unable to save file.\n", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  98. } else {
  99. m_document_dirty = false;
  100. update_title();
  101. }
  102. return;
  103. }
  104. m_save_as_action->activate();
  105. });
  106. m_save_as_action = GUI::Action::create("Save as...", { Mod_Ctrl | Mod_Shift, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), [this](const GUI::Action&) {
  107. Optional<String> save_path = GUI::FilePicker::get_save_filepath(m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "bin" : m_extension);
  108. if (!save_path.has_value())
  109. return;
  110. if (!m_editor->write_to_file(save_path.value())) {
  111. GUI::MessageBox::show("Unable to save file.\n", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  112. return;
  113. }
  114. m_document_dirty = false;
  115. set_path(FileSystemPath(save_path.value()));
  116. dbg() << "Wrote document to " << save_path.value();
  117. });
  118. auto menubar = GUI::MenuBar::construct();
  119. auto& app_menu = menubar->add_menu("Hex Editor");
  120. app_menu.add_action(*m_new_action);
  121. app_menu.add_action(*m_open_action);
  122. app_menu.add_action(*m_save_action);
  123. app_menu.add_action(*m_save_as_action);
  124. app_menu.add_separator();
  125. app_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  126. if (!request_close())
  127. return;
  128. GUI::Application::the().quit(0);
  129. }));
  130. 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&) {
  131. auto input_box = GUI::InputBox::construct("Enter Decimal offset:", "Go To", window());
  132. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  133. auto valid = false;
  134. auto new_offset = input_box->text_value().to_int(valid);
  135. if (valid) {
  136. m_editor->set_position(new_offset);
  137. }
  138. }
  139. });
  140. 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&) {
  141. auto input_box = GUI::InputBox::construct("Enter Hex offset:", "Go To", window());
  142. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  143. auto new_offset = strtol(input_box->text_value().characters(), nullptr, 16);
  144. m_editor->set_position(new_offset);
  145. }
  146. });
  147. auto& edit_menu = menubar->add_menu("Edit");
  148. edit_menu.add_action(GUI::Action::create("Fill selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  149. auto input_box = GUI::InputBox::construct("Fill byte (hex):", "Fill Selection", window());
  150. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  151. auto fill_byte = strtol(input_box->text_value().characters(), nullptr, 16);
  152. m_editor->fill_selection(fill_byte);
  153. }
  154. }));
  155. edit_menu.add_separator();
  156. edit_menu.add_action(*m_goto_decimal_offset_action);
  157. edit_menu.add_action(*m_goto_hex_offset_action);
  158. edit_menu.add_separator();
  159. edit_menu.add_action(GUI::Action::create("Copy Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  160. m_editor->copy_selected_hex_to_clipboard();
  161. }));
  162. edit_menu.add_action(GUI::Action::create("Copy Text", { Mod_Ctrl | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  163. m_editor->copy_selected_text_to_clipboard();
  164. }));
  165. edit_menu.add_separator();
  166. edit_menu.add_action(GUI::Action::create("Copy As C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  167. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  168. }));
  169. auto& view_menu = menubar->add_menu("View");
  170. auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per row");
  171. for (int i = 8; i <= 32; i += 8) {
  172. bytes_per_row_menu.add_action(GUI::Action::create(String::number(i), [this, i](auto&) {
  173. m_editor->set_bytes_per_row(i);
  174. m_editor->update();
  175. }));
  176. }
  177. auto& help_menu = menubar->add_menu("Help");
  178. help_menu.add_action(GUI::Action::create("About", [&](auto&) {
  179. GUI::AboutDialog::show("Hex Editor", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-hexeditor.png"), window());
  180. }));
  181. GUI::Application::the().set_menubar(move(menubar));
  182. m_editor->set_focus(true);
  183. }
  184. HexEditorWidget::~HexEditorWidget()
  185. {
  186. }
  187. void HexEditorWidget::set_path(const FileSystemPath& file)
  188. {
  189. m_path = file.string();
  190. m_name = file.title();
  191. m_extension = file.extension();
  192. update_title();
  193. }
  194. void HexEditorWidget::update_title()
  195. {
  196. StringBuilder builder;
  197. builder.append(m_path);
  198. if (m_document_dirty)
  199. builder.append(" (*)");
  200. builder.append(" - Hex Editor");
  201. window()->set_title(builder.to_string());
  202. }
  203. void HexEditorWidget::open_file(const String& path)
  204. {
  205. auto file = Core::File::construct(path);
  206. if (!file->open(Core::IODevice::ReadOnly)) {
  207. GUI::MessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  208. return;
  209. }
  210. m_document_dirty = false;
  211. 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.
  212. set_path(FileSystemPath(path));
  213. }
  214. bool HexEditorWidget::request_close()
  215. {
  216. if (!m_document_dirty)
  217. return true;
  218. auto result = GUI::MessageBox::show("The file has been modified. Quit without saving?", "Quit without saving?", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel, window());
  219. return result == GUI::MessageBox::ExecOK;
  220. }