HexEditorWidget.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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/CFile.h>
  30. #include <LibDraw/PNGLoader.h>
  31. #include <LibGUI/GAboutDialog.h>
  32. #include <LibGUI/GAction.h>
  33. #include <LibGUI/GBoxLayout.h>
  34. #include <LibGUI/GButton.h>
  35. #include <LibGUI/GFilePicker.h>
  36. #include <LibGUI/GFontDatabase.h>
  37. #include <LibGUI/GInputBox.h>
  38. #include <LibGUI/GMenuBar.h>
  39. #include <LibGUI/GMessageBox.h>
  40. #include <LibGUI/GStatusBar.h>
  41. #include <LibGUI/GTextBox.h>
  42. #include <LibGUI/GTextEditor.h>
  43. #include <LibGUI/GToolBar.h>
  44. #include <stdio.h>
  45. HexEditorWidget::HexEditorWidget()
  46. {
  47. set_layout(make<GUI::VBoxLayout>());
  48. layout()->set_spacing(0);
  49. m_editor = HexEditor::construct(this);
  50. m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
  51. m_statusbar->set_text(0, String::format("Offset: %8X", position));
  52. m_statusbar->set_text(1, String::format("Edit Mode: %s", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text"));
  53. m_statusbar->set_text(2, String::format("Selection Start: %d", selection_start));
  54. m_statusbar->set_text(3, String::format("Selection End: %d", selection_end));
  55. m_statusbar->set_text(4, String::format("Selected Bytes: %d", (selection_end - selection_start) + 1));
  56. };
  57. m_editor->on_change = [this] {
  58. bool was_dirty = m_document_dirty;
  59. m_document_dirty = true;
  60. if (!was_dirty)
  61. update_title();
  62. };
  63. m_statusbar = GUI::StatusBar::construct(5, this);
  64. 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&) {
  65. if (m_document_dirty) {
  66. auto save_document_first_box = GUI::MessageBox::construct("Save Document First?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel, window());
  67. auto save_document_first_result = save_document_first_box->exec();
  68. if (save_document_first_result != GUI::Dialog::ExecResult::ExecOK)
  69. return;
  70. m_save_action->activate();
  71. }
  72. auto input_box = GUI::InputBox::construct("Enter new file size:", "New file size", this);
  73. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  74. auto valid = false;
  75. auto file_size = input_box->text_value().to_int(valid);
  76. if (valid && file_size > 0) {
  77. m_document_dirty = false;
  78. m_editor->set_buffer(ByteBuffer::create_zeroed(file_size));
  79. set_path(FileSystemPath());
  80. update_title();
  81. } else {
  82. GUI::MessageBox::show("Invalid file size entered.", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  83. }
  84. }
  85. });
  86. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  87. Optional<String> open_path = GUI::FilePicker::get_open_filepath();
  88. if (!open_path.has_value())
  89. return;
  90. open_file(open_path.value());
  91. });
  92. m_save_action = GUI::Action::create("Save", { Mod_Ctrl, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), [&](const GUI::Action&) {
  93. if (!m_path.is_empty()) {
  94. if (!m_editor->write_to_file(m_path)) {
  95. GUI::MessageBox::show("Unable to save file.\n", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  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::Action::create("Save as...", { Mod_Ctrl | Mod_Shift, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), [this](const GUI::Action&) {
  105. Optional<String> save_path = GUI::FilePicker::get_save_filepath(m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "bin" : m_extension);
  106. if (!save_path.has_value())
  107. return;
  108. if (!m_editor->write_to_file(save_path.value())) {
  109. GUI::MessageBox::show("Unable to save file.\n", "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  110. return;
  111. }
  112. m_document_dirty = false;
  113. set_path(FileSystemPath(save_path.value()));
  114. dbg() << "Wrote document to " << save_path.value();
  115. });
  116. auto menubar = make<GUI::MenuBar>();
  117. auto app_menu = GUI::Menu::construct("Hex Editor");
  118. app_menu->add_action(*m_new_action);
  119. app_menu->add_action(*m_open_action);
  120. app_menu->add_action(*m_save_action);
  121. app_menu->add_action(*m_save_as_action);
  122. app_menu->add_separator();
  123. app_menu->add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  124. if (!request_close())
  125. return;
  126. GUI::Application::the().quit(0);
  127. }));
  128. menubar->add_menu(move(app_menu));
  129. auto bytes_per_row_menu = GUI::Menu::construct("Bytes Per Row");
  130. for (int i = 8; i <= 32; i += 8) {
  131. bytes_per_row_menu->add_action(GUI::Action::create(String::number(i), [this, i](auto&) {
  132. m_editor->set_bytes_per_row(i);
  133. m_editor->update();
  134. }));
  135. }
  136. 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&) {
  137. auto input_box = GUI::InputBox::construct("Enter Decimal offset:", "Go To", this);
  138. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  139. auto valid = false;
  140. auto new_offset = input_box->text_value().to_int(valid);
  141. if (valid) {
  142. m_editor->set_position(new_offset);
  143. }
  144. }
  145. });
  146. 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&) {
  147. auto input_box = GUI::InputBox::construct("Enter Hex offset:", "Go To", this);
  148. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  149. auto new_offset = strtol(input_box->text_value().characters(), nullptr, 16);
  150. m_editor->set_position(new_offset);
  151. }
  152. });
  153. auto edit_menu = GUI::Menu::construct("Edit");
  154. edit_menu->add_action(GUI::Action::create("Fill selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  155. auto input_box = GUI::InputBox::construct("Fill byte (hex):", "Fill Selection", this);
  156. if (input_box->exec() == GUI::InputBox::ExecOK && !input_box->text_value().is_empty()) {
  157. auto fill_byte = strtol(input_box->text_value().characters(), nullptr, 16);
  158. m_editor->fill_selection(fill_byte);
  159. }
  160. }));
  161. edit_menu->add_separator();
  162. edit_menu->add_action(*m_goto_decimal_offset_action);
  163. edit_menu->add_action(*m_goto_hex_offset_action);
  164. edit_menu->add_separator();
  165. edit_menu->add_action(GUI::Action::create("Copy Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
  166. m_editor->copy_selected_hex_to_clipboard();
  167. }));
  168. edit_menu->add_action(GUI::Action::create("Copy Text", { Mod_Ctrl | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  169. m_editor->copy_selected_text_to_clipboard();
  170. }));
  171. edit_menu->add_separator();
  172. edit_menu->add_action(GUI::Action::create("Copy As C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
  173. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  174. }));
  175. menubar->add_menu(move(edit_menu));
  176. auto view_menu = GUI::Menu::construct("View");
  177. view_menu->add_submenu(move(bytes_per_row_menu));
  178. menubar->add_menu(move(view_menu));
  179. auto help_menu = GUI::Menu::construct("Help");
  180. help_menu->add_action(GUI::Action::create("About", [&](const GUI::Action&) {
  181. GUI::AboutDialog::show("Hex Editor", Gfx::load_png("/res/icons/32x32/app-hexeditor.png"), window());
  182. }));
  183. menubar->add_menu(move(help_menu));
  184. GUI::Application::the().set_menubar(move(menubar));
  185. m_editor->set_focus(true);
  186. }
  187. HexEditorWidget::~HexEditorWidget()
  188. {
  189. }
  190. void HexEditorWidget::set_path(const FileSystemPath& file)
  191. {
  192. m_path = file.string();
  193. m_name = file.title();
  194. m_extension = file.extension();
  195. update_title();
  196. }
  197. void HexEditorWidget::update_title()
  198. {
  199. StringBuilder builder;
  200. builder.append("Hex Editor: ");
  201. builder.append(m_path);
  202. if (m_document_dirty)
  203. builder.append(" (*)");
  204. window()->set_title(builder.to_string());
  205. }
  206. void HexEditorWidget::open_file(const String& path)
  207. {
  208. auto file = Core::File::construct(path);
  209. if (!file->open(Core::IODevice::ReadOnly)) {
  210. GUI::MessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK, window());
  211. return;
  212. }
  213. m_document_dirty = false;
  214. 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.
  215. set_path(FileSystemPath(path));
  216. }
  217. bool HexEditorWidget::request_close()
  218. {
  219. if (!m_document_dirty)
  220. return true;
  221. 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());
  222. return result == GUI::MessageBox::ExecOK;
  223. }