HexEditorWidget.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Mustafa Quraish <mustafa@serenityos.org>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. * Copyright (c) 2022, Timothy Slater <tslater2006@gmail.com>
  6. * Copyright (c) 2024, Sam Atkins <atkinssj@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "HexEditorWidget.h"
  11. #include "FindDialog.h"
  12. #include "GoToOffsetDialog.h"
  13. #include "SearchResultsModel.h"
  14. #include "ValueInspectorModel.h"
  15. #include <AK/Forward.h>
  16. #include <AK/Optional.h>
  17. #include <AK/StringBuilder.h>
  18. #include <LibConfig/Client.h>
  19. #include <LibDesktop/Launcher.h>
  20. #include <LibFileSystemAccessClient/Client.h>
  21. #include <LibGUI/Action.h>
  22. #include <LibGUI/BoxLayout.h>
  23. #include <LibGUI/Button.h>
  24. #include <LibGUI/FilePicker.h>
  25. #include <LibGUI/InputBox.h>
  26. #include <LibGUI/Menu.h>
  27. #include <LibGUI/Menubar.h>
  28. #include <LibGUI/MessageBox.h>
  29. #include <LibGUI/Model.h>
  30. #include <LibGUI/SortingProxyModel.h>
  31. #include <LibGUI/Statusbar.h>
  32. #include <LibGUI/TableView.h>
  33. #include <LibGUI/TextBox.h>
  34. #include <LibGUI/Toolbar.h>
  35. #include <LibGUI/ToolbarContainer.h>
  36. #include <LibTextCodec/Decoder.h>
  37. #include <string.h>
  38. namespace HexEditor {
  39. ErrorOr<NonnullRefPtr<HexEditorWidget>> HexEditorWidget::create()
  40. {
  41. auto widget = TRY(try_create());
  42. TRY(widget->setup());
  43. return widget;
  44. }
  45. ErrorOr<void> HexEditorWidget::setup()
  46. {
  47. m_toolbar = *find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  48. m_toolbar_container = *find_descendant_of_type_named<GUI::ToolbarContainer>("toolbar_container");
  49. m_editor = *find_descendant_of_type_named<::HexEditor::HexEditor>("editor");
  50. m_statusbar = *find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  51. m_annotations = *find_descendant_of_type_named<GUI::TableView>("annotations");
  52. m_annotations_container = *find_descendant_of_type_named<GUI::Widget>("annotations_container");
  53. m_search_results = *find_descendant_of_type_named<GUI::TableView>("search_results");
  54. m_search_results_container = *find_descendant_of_type_named<GUI::Widget>("search_results_container");
  55. m_side_panel_container = *find_descendant_of_type_named<GUI::Widget>("side_panel_container");
  56. m_value_inspector_container = *find_descendant_of_type_named<GUI::Widget>("value_inspector_container");
  57. m_value_inspector = *find_descendant_of_type_named<GUI::TableView>("value_inspector");
  58. m_value_inspector->on_activation = [this](GUI::ModelIndex const& index) {
  59. if (!index.is_valid())
  60. return;
  61. m_selecting_from_inspector = true;
  62. m_editor->set_selection(m_editor->selection_start_offset(), index.data(GUI::ModelRole::Custom).to_integer<size_t>());
  63. m_editor->update();
  64. };
  65. m_editor->on_status_change = [this](int position, HexEditor::HexEditor::EditMode edit_mode, auto selection) {
  66. m_statusbar->set_text(0, String::formatted("Offset: {:#08X}", position).release_value_but_fixme_should_propagate_errors());
  67. m_statusbar->set_text(1, String::formatted("Edit Mode: {}", edit_mode == HexEditor::HexEditor::EditMode::Hex ? "Hex" : "Text").release_value_but_fixme_should_propagate_errors());
  68. m_statusbar->set_text(2, String::formatted("Selection Start: {}", selection.start).release_value_but_fixme_should_propagate_errors());
  69. m_statusbar->set_text(3, String::formatted("Selection End: {}", selection.end).release_value_but_fixme_should_propagate_errors());
  70. m_statusbar->set_text(4, String::formatted("Selected Bytes: {}", selection.size()).release_value_but_fixme_should_propagate_errors());
  71. bool has_selection = m_editor->has_selection();
  72. m_copy_hex_action->set_enabled(has_selection);
  73. m_copy_text_action->set_enabled(has_selection);
  74. m_copy_as_c_code_action->set_enabled(has_selection);
  75. m_fill_selection_action->set_enabled(has_selection);
  76. if (m_value_inspector_container->is_visible() && !m_selecting_from_inspector) {
  77. update_inspector_values(selection.start);
  78. }
  79. m_selecting_from_inspector = false;
  80. };
  81. m_editor->on_change = [this](bool is_document_dirty) {
  82. window()->set_modified(is_document_dirty);
  83. };
  84. m_editor->undo_stack().on_state_change = [this] {
  85. m_undo_action->set_enabled(m_editor->undo_stack().can_undo());
  86. m_redo_action->set_enabled(m_editor->undo_stack().can_redo());
  87. };
  88. initialize_annotations_model();
  89. m_annotations->set_activates_on_selection(true);
  90. m_annotations->on_activation = [this](GUI::ModelIndex const& index) {
  91. if (!index.is_valid())
  92. return;
  93. auto start_offset = m_annotations->model()->data(index, (GUI::ModelRole)AnnotationsModel::CustomRole::StartOffset).to_integer<size_t>();
  94. m_editor->set_position(start_offset);
  95. m_editor->update();
  96. };
  97. m_search_results->set_activates_on_selection(true);
  98. m_search_results->on_activation = [this](const GUI::ModelIndex& index) {
  99. if (!index.is_valid())
  100. return;
  101. auto offset = index.data(GUI::ModelRole::Custom).to_i32();
  102. m_last_found_index = offset;
  103. m_editor->set_position(offset);
  104. m_editor->update();
  105. };
  106. m_new_action = GUI::Action::create("New...", { Mod_Ctrl, Key_N }, Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"sv).release_value_but_fixme_should_propagate_errors(), [this](const GUI::Action&) {
  107. String value;
  108. if (request_close() && GUI::InputBox::show(window(), value, "Enter a size:"sv, "New File"sv, GUI::InputType::NonemptyText) == GUI::InputBox::ExecResult::OK) {
  109. auto file_size = AK::StringUtils::convert_to_uint(value);
  110. if (!file_size.has_value()) {
  111. GUI::MessageBox::show(window(), "Invalid file size entered."sv, "Error"sv, GUI::MessageBox::Type::Error);
  112. return;
  113. }
  114. if (auto error = m_editor->open_new_file(file_size.value()); error.is_error()) {
  115. GUI::MessageBox::show(window(), ByteString::formatted("Unable to open new file: {}"sv, error.error()), "Error"sv, GUI::MessageBox::Type::Error);
  116. return;
  117. }
  118. set_path({});
  119. initialize_annotations_model();
  120. window()->set_modified(false);
  121. }
  122. });
  123. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  124. if (!request_close())
  125. return;
  126. auto response = FileSystemAccessClient::Client::the().open_file(window(), { .requested_access = Core::File::OpenMode::ReadWrite });
  127. if (response.is_error())
  128. return;
  129. open_file(response.value().filename(), response.value().release_stream());
  130. });
  131. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  132. if (m_path.is_empty())
  133. return m_save_as_action->activate();
  134. if (auto result = m_editor->save(); result.is_error()) {
  135. GUI::MessageBox::show(window(), ByteString::formatted("Unable to save file: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  136. } else {
  137. window()->set_modified(false);
  138. m_editor->update();
  139. }
  140. return;
  141. });
  142. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  143. auto response = FileSystemAccessClient::Client::the().save_file(window(), m_name, m_extension, Core::File::OpenMode::ReadWrite | Core::File::OpenMode::Truncate);
  144. if (response.is_error())
  145. return;
  146. auto file = response.release_value();
  147. if (auto result = m_editor->save_as(file.release_stream()); result.is_error()) {
  148. GUI::MessageBox::show(window(), ByteString::formatted("Unable to save file: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  149. return;
  150. }
  151. window()->set_modified(false);
  152. set_path(file.filename());
  153. dbgln("Wrote document to {}", file.filename());
  154. });
  155. m_open_annotations_action = GUI::Action::create("Load Annotations...", Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"sv).release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  156. auto response = FileSystemAccessClient::Client::the().open_file(window(),
  157. { .window_title = "Load annotations file"sv,
  158. .requested_access = Core::File::OpenMode::Read,
  159. .allowed_file_types = { { GUI::FileTypeFilter { "Annotations files", { { "annotations" } } }, GUI::FileTypeFilter::all_files() } } });
  160. if (response.is_error())
  161. return;
  162. auto result = m_editor->document().annotations().load_from_file(response.value().stream());
  163. if (result.is_error()) {
  164. GUI::MessageBox::show(window(), ByteString::formatted("Unable to load annotations: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  165. return;
  166. }
  167. m_annotations_path = response.value().filename();
  168. });
  169. m_open_annotations_action->set_status_tip("Load annotations from a file"_string);
  170. m_save_annotations_action = GUI::Action::create("Save Annotations", Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"sv).release_value_but_fixme_should_propagate_errors(), [&](auto&) {
  171. if (m_annotations_path.is_empty())
  172. return m_save_annotations_as_action->activate();
  173. auto response = FileSystemAccessClient::Client::the().request_file(window(), m_annotations_path, Core::File::OpenMode::Write | Core::File::OpenMode::Truncate);
  174. if (response.is_error())
  175. return;
  176. auto file = response.release_value();
  177. if (auto result = m_editor->document().annotations().save_to_file(file.stream()); result.is_error()) {
  178. GUI::MessageBox::show(window(), ByteString::formatted("Unable to save annotations file: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  179. }
  180. });
  181. m_save_annotations_action->set_status_tip("Save annotations to a file"_string);
  182. m_save_annotations_as_action = GUI::Action::create("Save Annotations As...", Gfx::Bitmap::load_from_file("/res/icons/16x16/save-as.png"sv).release_value_but_fixme_should_propagate_errors(), [&](auto&) {
  183. auto response = FileSystemAccessClient::Client::the().save_file(window(), m_name, "annotations"sv, Core::File::OpenMode::Write | Core::File::OpenMode::Truncate);
  184. if (response.is_error())
  185. return;
  186. auto file = response.release_value();
  187. if (auto result = m_editor->document().annotations().save_to_file(file.stream()); result.is_error()) {
  188. GUI::MessageBox::show(window(), ByteString::formatted("Unable to save annotations file: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  189. }
  190. });
  191. m_save_annotations_as_action->set_status_tip("Save annotations to a file with a new name"_string);
  192. m_undo_action = GUI::CommonActions::make_undo_action([&](auto&) {
  193. m_editor->undo();
  194. });
  195. m_undo_action->set_enabled(false);
  196. m_redo_action = GUI::CommonActions::make_redo_action([&](auto&) {
  197. m_editor->redo();
  198. });
  199. m_redo_action->set_enabled(false);
  200. m_find_action = GUI::Action::create("&Find...", { Mod_Ctrl, Key_F }, Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv).release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  201. auto old_buffer = m_search_buffer;
  202. bool find_all = false;
  203. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecResult::OK) {
  204. if (find_all) {
  205. auto matches = m_editor->find_all(m_search_buffer, 0);
  206. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  207. m_search_results->update();
  208. if (matches.is_empty()) {
  209. GUI::MessageBox::show(window(), ByteString::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not Found"sv, GUI::MessageBox::Type::Warning);
  210. return;
  211. }
  212. GUI::MessageBox::show(window(), ByteString::formatted("Found {} matches for \"{}\" in this file", matches.size(), m_search_text), ByteString::formatted("{} Matches", matches.size()), GUI::MessageBox::Type::Warning);
  213. set_search_results_visible(true);
  214. } else {
  215. bool same_buffers = false;
  216. if (old_buffer.size() == m_search_buffer.size()) {
  217. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  218. same_buffers = true;
  219. }
  220. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  221. if (!result.has_value()) {
  222. GUI::MessageBox::show(window(), ByteString::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not Found"sv, GUI::MessageBox::Type::Warning);
  223. return;
  224. }
  225. m_last_found_index = result.value();
  226. }
  227. m_editor->update();
  228. }
  229. });
  230. m_goto_offset_action = GUI::Action::create("&Go to Offset...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-to.png"sv).release_value_but_fixme_should_propagate_errors(), [this](const GUI::Action&) {
  231. int new_offset;
  232. auto result = GoToOffsetDialog::show(
  233. window(),
  234. m_goto_history,
  235. new_offset,
  236. m_editor->selection_start_offset(),
  237. m_editor->buffer_size());
  238. if (result == GUI::InputBox::ExecResult::OK) {
  239. m_editor->highlight(new_offset, new_offset);
  240. m_editor->update();
  241. }
  242. });
  243. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  244. m_toolbar_container->set_visible(action.is_checked());
  245. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowToolbar"sv, action.is_checked());
  246. });
  247. m_layout_annotations_action = GUI::Action::create_checkable("&Annotations", [&](auto& action) {
  248. set_annotations_visible(action.is_checked());
  249. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowAnnotations"sv, action.is_checked());
  250. });
  251. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  252. set_search_results_visible(action.is_checked());
  253. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowSearchResults"sv, action.is_checked());
  254. });
  255. m_copy_hex_action = GUI::Action::create("Copy &Hex", { Mod_Ctrl, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/hex.png"sv).release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  256. m_editor->copy_selected_hex_to_clipboard();
  257. });
  258. m_copy_hex_action->set_enabled(false);
  259. m_copy_text_action = GUI::Action::create("Copy &Text", { Mod_Ctrl | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"sv).release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  260. m_editor->copy_selected_text_to_clipboard();
  261. });
  262. m_copy_text_action->set_enabled(false);
  263. m_copy_as_c_code_action = GUI::Action::create("Copy as &C Code", { Mod_Alt | Mod_Shift, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/c.png"sv).release_value_but_fixme_should_propagate_errors(), [&](const GUI::Action&) {
  264. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  265. });
  266. m_copy_as_c_code_action->set_enabled(false);
  267. m_fill_selection_action = GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  268. String value;
  269. if (GUI::InputBox::show(window(), value, "Fill byte (hex):"sv, "Fill Selection"sv, GUI::InputType::NonemptyText) == GUI::InputBox::ExecResult::OK) {
  270. auto fill_byte = strtol(value.bytes_as_string_view().characters_without_null_termination(), nullptr, 16);
  271. auto result = m_editor->fill_selection(fill_byte);
  272. if (result.is_error())
  273. GUI::MessageBox::show_error(window(), ByteString::formatted("{}", result.error()));
  274. }
  275. });
  276. m_fill_selection_action->set_enabled(false);
  277. m_layout_value_inspector_action = GUI::Action::create_checkable("&Value Inspector", [&](auto& action) {
  278. set_value_inspector_visible(action.is_checked());
  279. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowValueInspector"sv, action.is_checked());
  280. });
  281. m_toolbar->add_action(*m_new_action);
  282. m_toolbar->add_action(*m_open_action);
  283. m_toolbar->add_action(*m_save_action);
  284. m_toolbar->add_separator();
  285. m_toolbar->add_action(*m_undo_action);
  286. m_toolbar->add_action(*m_redo_action);
  287. m_toolbar->add_separator();
  288. m_toolbar->add_action(*m_find_action);
  289. m_toolbar->add_action(*m_goto_offset_action);
  290. m_statusbar->segment(0).set_clickable(true);
  291. m_statusbar->segment(0).set_action(*m_goto_offset_action);
  292. m_editor->set_focus(true);
  293. GUI::Application::the()->on_action_enter = [this](GUI::Action& action) {
  294. m_statusbar->set_override_text(action.status_tip());
  295. };
  296. GUI::Application::the()->on_action_leave = [this](GUI::Action&) {
  297. m_statusbar->set_override_text({});
  298. };
  299. return {};
  300. }
  301. void HexEditorWidget::update_inspector_values(size_t position)
  302. {
  303. // build out primitive types like u8, i8, u16, etc
  304. size_t byte_read_count = 0;
  305. u64 unsigned_64_bit_int = 0;
  306. for (int i = 0; i < 8; ++i) {
  307. Optional<u8> read_result = m_editor->get_byte(position + i);
  308. u8 current_byte = 0;
  309. if (!read_result.has_value())
  310. break;
  311. current_byte = read_result.release_value();
  312. if (m_value_inspector_little_endian)
  313. unsigned_64_bit_int = ((u64)current_byte << (8 * byte_read_count)) + unsigned_64_bit_int;
  314. else
  315. unsigned_64_bit_int = (unsigned_64_bit_int << 8) + current_byte;
  316. ++byte_read_count;
  317. }
  318. if (!m_value_inspector_little_endian) {
  319. // if we didn't read far enough, lets finish shifting the bytes so the code below works
  320. size_t bytes_left_to_read = 8 - byte_read_count;
  321. unsigned_64_bit_int = (unsigned_64_bit_int << (8 * bytes_left_to_read));
  322. }
  323. // Populate the model
  324. NonnullRefPtr<ValueInspectorModel> value_inspector_model = make_ref_counted<ValueInspectorModel>(m_value_inspector_little_endian);
  325. if (byte_read_count >= 1) {
  326. u8 unsigned_byte_value = 0;
  327. if (m_value_inspector_little_endian)
  328. unsigned_byte_value = (unsigned_64_bit_int & 0xFF);
  329. else
  330. unsigned_byte_value = (unsigned_64_bit_int >> (64 - 8)) & 0xFF;
  331. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedByte, String::number(static_cast<i8>(unsigned_byte_value)));
  332. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedByte, String::number(unsigned_byte_value));
  333. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::ASCII, String::formatted("{:c}", static_cast<char>(unsigned_byte_value)));
  334. } else {
  335. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedByte, ""_string);
  336. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedByte, ""_string);
  337. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::ASCII, ""_string);
  338. }
  339. if (byte_read_count >= 2) {
  340. u16 unsigned_short_value = 0;
  341. if (m_value_inspector_little_endian)
  342. unsigned_short_value = (unsigned_64_bit_int & 0xFFFF);
  343. else
  344. unsigned_short_value = (unsigned_64_bit_int >> (64 - 16)) & 0xFFFF;
  345. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedShort, String::number(static_cast<i16>(unsigned_short_value)));
  346. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedShort, String::number(unsigned_short_value));
  347. } else {
  348. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedShort, ""_string);
  349. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedShort, ""_string);
  350. }
  351. if (byte_read_count >= 4) {
  352. u32 unsigned_int_value = 0;
  353. if (m_value_inspector_little_endian)
  354. unsigned_int_value = (unsigned_64_bit_int & 0xFFFFFFFF);
  355. else
  356. unsigned_int_value = (unsigned_64_bit_int >> 32) & 0xFFFFFFFF;
  357. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedInt, String::number(static_cast<i32>(unsigned_int_value)));
  358. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedInt, String::number(unsigned_int_value));
  359. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Float, String::number(bit_cast<float>(unsigned_int_value)));
  360. } else {
  361. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedInt, ""_string);
  362. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedInt, ""_string);
  363. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Float, ""_string);
  364. }
  365. if (byte_read_count >= 8) {
  366. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedLong, String::number(static_cast<i64>(unsigned_64_bit_int)));
  367. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedLong, String::number(unsigned_64_bit_int));
  368. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Double, String::number(bit_cast<double>(unsigned_64_bit_int)));
  369. } else {
  370. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedLong, ""_string);
  371. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedLong, ""_string);
  372. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Double, ""_string);
  373. }
  374. // FIXME: This probably doesn't honour endianness correctly.
  375. Utf8View utf8_view { ReadonlyBytes { reinterpret_cast<u8 const*>(&unsigned_64_bit_int), 4 } };
  376. size_t valid_bytes;
  377. utf8_view.validate(valid_bytes);
  378. if (valid_bytes == 0)
  379. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8, ""_string);
  380. else {
  381. auto utf8 = String::from_utf8(utf8_view.unicode_substring_view(0, 1).as_string());
  382. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8, move(utf8));
  383. }
  384. if (byte_read_count % 2 == 0) {
  385. Utf16View utf16_view { ReadonlySpan<u16> { reinterpret_cast<u16 const*>(&unsigned_64_bit_int), 4 } };
  386. size_t valid_code_units;
  387. utf16_view.validate(valid_code_units);
  388. if (valid_code_units == 0)
  389. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16, ""_string);
  390. else
  391. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16, utf16_view.unicode_substring_view(0, 1).to_utf8().release_value_but_fixme_should_propagate_errors());
  392. } else {
  393. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16, ""_string);
  394. }
  395. auto selected_bytes = m_editor->get_selected_bytes();
  396. auto ascii_string = String::from_utf8(ReadonlyBytes { selected_bytes });
  397. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::ASCIIString, move(ascii_string));
  398. Utf8View utf8_string_view { ReadonlyBytes { selected_bytes } };
  399. utf8_string_view.validate(valid_bytes);
  400. if (valid_bytes == 0)
  401. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8String, ""_string);
  402. else
  403. // FIXME: replace control chars with something else - we don't want line breaks here ;)
  404. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8String, String::from_utf8(utf8_string_view.as_string()));
  405. // FIXME: Parse as other values like Timestamp etc
  406. auto decoder = TextCodec::decoder_for(m_value_inspector_little_endian ? "utf-16le"sv : "utf-16be"sv);
  407. ErrorOr<String> utf16_string = decoder->to_utf8(StringView(selected_bytes.span()));
  408. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16String, move(utf16_string));
  409. m_value_inspector->set_model(value_inspector_model);
  410. m_value_inspector->update();
  411. }
  412. ErrorOr<void> HexEditorWidget::initialize_menubar(GUI::Window& window)
  413. {
  414. auto file_menu = window.add_menu("&File"_string);
  415. file_menu->add_action(*m_new_action);
  416. file_menu->add_action(*m_open_action);
  417. file_menu->add_action(*m_save_action);
  418. file_menu->add_action(*m_save_as_action);
  419. file_menu->add_separator();
  420. file_menu->add_action(*m_open_annotations_action);
  421. file_menu->add_action(*m_save_annotations_action);
  422. file_menu->add_action(*m_save_annotations_as_action);
  423. file_menu->add_separator();
  424. file_menu->add_recent_files_list([&](auto& action) {
  425. auto path = action.text();
  426. auto response = FileSystemAccessClient::Client::the().request_file_read_only_approved(&window, path);
  427. if (response.is_error())
  428. return;
  429. auto file = response.release_value();
  430. open_file(file.filename(), file.release_stream());
  431. });
  432. file_menu->add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  433. if (!request_close())
  434. return;
  435. GUI::Application::the()->quit();
  436. }));
  437. auto edit_menu = window.add_menu("&Edit"_string);
  438. edit_menu->add_action(*m_undo_action);
  439. edit_menu->add_action(*m_redo_action);
  440. edit_menu->add_separator();
  441. edit_menu->add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  442. m_editor->select_all();
  443. m_editor->update();
  444. }));
  445. edit_menu->add_action(*m_fill_selection_action);
  446. edit_menu->add_separator();
  447. edit_menu->add_action(GUI::Action::create(
  448. "Add Annotation",
  449. Gfx::Bitmap::load_from_file("/res/icons/16x16/annotation-add.png"sv).release_value_but_fixme_should_propagate_errors(),
  450. [this](GUI::Action&) { m_editor->show_create_annotation_dialog(); },
  451. this));
  452. edit_menu->add_separator();
  453. edit_menu->add_action(*m_copy_hex_action);
  454. edit_menu->add_action(*m_copy_text_action);
  455. edit_menu->add_action(*m_copy_as_c_code_action);
  456. edit_menu->add_separator();
  457. edit_menu->add_action(*m_find_action);
  458. edit_menu->add_action(GUI::Action::create("Find &Next", { Mod_None, Key_F3 }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find-next.png"sv)), [&](const GUI::Action&) {
  459. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  460. GUI::MessageBox::show(&window, "Nothing to search for"sv, "Not Found"sv, GUI::MessageBox::Type::Warning);
  461. return;
  462. }
  463. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  464. if (!result.has_value()) {
  465. GUI::MessageBox::show(&window, ByteString::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not Found"sv, GUI::MessageBox::Type::Warning);
  466. return;
  467. }
  468. m_editor->update();
  469. m_last_found_index = result.value();
  470. }));
  471. edit_menu->add_action(GUI::Action::create("Find All &Strings", { Mod_Ctrl | Mod_Shift, Key_F }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv)), [&](const GUI::Action&) {
  472. int min_length = 4;
  473. auto matches = m_editor->find_all_strings(min_length);
  474. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  475. m_search_results->update();
  476. if (matches.is_empty()) {
  477. GUI::MessageBox::show(&window, "No strings found in this file"sv, "Not Found"sv, GUI::MessageBox::Type::Warning);
  478. return;
  479. }
  480. set_search_results_visible(true);
  481. m_editor->update();
  482. }));
  483. edit_menu->add_separator();
  484. edit_menu->add_action(*m_goto_offset_action);
  485. auto view_menu = window.add_menu("&View"_string);
  486. auto show_toolbar = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowToolbar"sv, true);
  487. m_layout_toolbar_action->set_checked(show_toolbar);
  488. m_toolbar_container->set_visible(show_toolbar);
  489. auto show_annotations = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowAnnotations"sv, false);
  490. set_annotations_visible(show_annotations);
  491. auto show_search_results = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowSearchResults"sv, false);
  492. set_search_results_visible(show_search_results);
  493. auto show_value_inspector = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowValueInspector"sv, false);
  494. set_value_inspector_visible(show_value_inspector);
  495. view_menu->add_action(*m_layout_toolbar_action);
  496. view_menu->add_action(*m_layout_annotations_action);
  497. view_menu->add_action(*m_layout_search_results_action);
  498. view_menu->add_action(*m_layout_value_inspector_action);
  499. view_menu->add_separator();
  500. auto bytes_per_row = Config::read_i32("HexEditor"sv, "Layout"sv, "BytesPerRow"sv, 16);
  501. m_editor->set_bytes_per_row(bytes_per_row);
  502. m_editor->update();
  503. m_bytes_per_row_actions.set_exclusive(true);
  504. auto bytes_per_row_menu = view_menu->add_submenu("Bytes per &Row"_string);
  505. for (int i = 8; i <= 32; i += 8) {
  506. auto action = GUI::Action::create_checkable(ByteString::number(i), [this, i](auto&) {
  507. m_editor->set_bytes_per_row(i);
  508. m_editor->update();
  509. Config::write_i32("HexEditor"sv, "Layout"sv, "BytesPerRow"sv, i);
  510. });
  511. m_bytes_per_row_actions.add_action(action);
  512. bytes_per_row_menu->add_action(action);
  513. if (i == bytes_per_row)
  514. action->set_checked(true);
  515. }
  516. m_value_inspector_mode_actions.set_exclusive(true);
  517. auto inspector_mode_menu = view_menu->add_submenu("Value Inspector &Mode"_string);
  518. auto little_endian_mode = GUI::Action::create_checkable("&Little Endian", [&](auto& action) {
  519. m_value_inspector_little_endian = action.is_checked();
  520. update_inspector_values(m_editor->selection_start_offset());
  521. Config::write_bool("HexEditor"sv, "Layout"sv, "UseLittleEndianInValueInspector"sv, m_value_inspector_little_endian);
  522. });
  523. m_value_inspector_mode_actions.add_action(little_endian_mode);
  524. inspector_mode_menu->add_action(little_endian_mode);
  525. auto big_endian_mode = GUI::Action::create_checkable("&Big Endian", [this](auto& action) {
  526. m_value_inspector_little_endian = !action.is_checked();
  527. update_inspector_values(m_editor->selection_start_offset());
  528. Config::write_bool("HexEditor"sv, "Layout"sv, "UseLittleEndianInValueInspector"sv, m_value_inspector_little_endian);
  529. });
  530. m_value_inspector_mode_actions.add_action(big_endian_mode);
  531. inspector_mode_menu->add_action(big_endian_mode);
  532. auto use_little_endian = Config::read_bool("HexEditor"sv, "Layout"sv, "UseLittleEndianInValueInspector"sv, true);
  533. m_value_inspector_little_endian = use_little_endian;
  534. little_endian_mode->set_checked(use_little_endian);
  535. big_endian_mode->set_checked(!use_little_endian);
  536. view_menu->add_separator();
  537. view_menu->add_action(GUI::CommonActions::make_fullscreen_action([&](auto&) {
  538. window.set_fullscreen(!window.is_fullscreen());
  539. }));
  540. auto help_menu = window.add_menu("&Help"_string);
  541. help_menu->add_action(GUI::CommonActions::make_command_palette_action(&window));
  542. help_menu->add_action(GUI::CommonActions::make_help_action([](auto&) {
  543. Desktop::Launcher::open(URL::create_with_file_scheme("/usr/share/man/man1/Applications/HexEditor.md"), "/bin/Help");
  544. }));
  545. help_menu->add_action(GUI::CommonActions::make_about_action("Hex Editor"_string, GUI::Icon::default_icon("app-hex-editor"sv), &window));
  546. return {};
  547. }
  548. void HexEditorWidget::set_path(StringView path)
  549. {
  550. if (path.is_empty()) {
  551. m_path = {};
  552. m_name = {};
  553. m_extension = {};
  554. } else {
  555. auto lexical_path = LexicalPath(path);
  556. m_path = lexical_path.string();
  557. m_name = lexical_path.title();
  558. m_extension = lexical_path.extension();
  559. }
  560. update_title();
  561. }
  562. void HexEditorWidget::update_title()
  563. {
  564. StringBuilder builder;
  565. if (m_path.is_empty())
  566. builder.append("Untitled"sv);
  567. else
  568. builder.append(m_path);
  569. builder.append("[*] - Hex Editor"sv);
  570. window()->set_title(builder.to_byte_string());
  571. }
  572. void HexEditorWidget::open_file(ByteString const& filename, NonnullOwnPtr<Core::File> file)
  573. {
  574. window()->set_modified(false);
  575. m_editor->open_file(move(file));
  576. set_path(filename);
  577. initialize_annotations_model();
  578. m_annotations_path = "";
  579. GUI::Application::the()->set_most_recently_open_file(filename);
  580. }
  581. void HexEditorWidget::open_annotations_file(StringView filename)
  582. {
  583. auto response = FileSystemAccessClient::Client::the().request_file_read_only_approved(window(), filename);
  584. if (response.is_error())
  585. return;
  586. auto result = m_editor->document().annotations().load_from_file(response.value().stream());
  587. if (result.is_error()) {
  588. GUI::MessageBox::show(window(), ByteString::formatted("Unable to load annotations: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  589. return;
  590. }
  591. m_annotations_path = filename;
  592. }
  593. bool HexEditorWidget::request_close()
  594. {
  595. if (!window()->is_modified())
  596. return true;
  597. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path);
  598. if (result == GUI::MessageBox::ExecResult::Yes) {
  599. m_save_action->activate();
  600. return !window()->is_modified();
  601. }
  602. return result == GUI::MessageBox::ExecResult::No;
  603. }
  604. void HexEditorWidget::update_side_panel_visibility()
  605. {
  606. m_side_panel_container->set_visible(
  607. m_annotations_container->is_visible()
  608. || m_search_results_container->is_visible()
  609. || m_value_inspector_container->is_visible());
  610. }
  611. void HexEditorWidget::set_annotations_visible(bool visible)
  612. {
  613. m_layout_annotations_action->set_checked(visible);
  614. m_annotations_container->set_visible(visible);
  615. update_side_panel_visibility();
  616. }
  617. void HexEditorWidget::initialize_annotations_model()
  618. {
  619. auto sorting_model = MUST(GUI::SortingProxyModel::create(m_editor->document().annotations()));
  620. sorting_model->set_sort_role((GUI::ModelRole)AnnotationsModel::CustomRole::StartOffset);
  621. sorting_model->sort(AnnotationsModel::Column::Start, GUI::SortOrder::Ascending);
  622. m_annotations->set_model(sorting_model);
  623. }
  624. void HexEditorWidget::set_search_results_visible(bool visible)
  625. {
  626. m_layout_search_results_action->set_checked(visible);
  627. m_search_results_container->set_visible(visible);
  628. update_side_panel_visibility();
  629. }
  630. void HexEditorWidget::set_value_inspector_visible(bool visible)
  631. {
  632. if (visible)
  633. update_inspector_values(m_editor->selection_start_offset());
  634. m_layout_value_inspector_action->set_checked(visible);
  635. m_value_inspector_container->set_visible(visible);
  636. update_side_panel_visibility();
  637. }
  638. void HexEditorWidget::drag_enter_event(GUI::DragEvent& event)
  639. {
  640. auto const& mime_types = event.mime_types();
  641. if (mime_types.contains_slow("text/uri-list"sv))
  642. event.accept();
  643. }
  644. void HexEditorWidget::drop_event(GUI::DropEvent& event)
  645. {
  646. event.accept();
  647. if (event.mime_data().has_urls()) {
  648. auto urls = event.mime_data().urls();
  649. if (urls.is_empty())
  650. return;
  651. window()->move_to_front();
  652. if (!request_close())
  653. return;
  654. // TODO: A drop event should be considered user consent for opening a file
  655. auto response = FileSystemAccessClient::Client::the().request_file(window(), urls.first().serialize_path(), Core::File::OpenMode::Read);
  656. if (response.is_error())
  657. return;
  658. open_file(response.value().filename(), response.value().release_stream());
  659. }
  660. }
  661. }