HexEditorWidget.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include "HexEditorWidget.h"
  10. #include "FindDialog.h"
  11. #include "GoToOffsetDialog.h"
  12. #include "SearchResultsModel.h"
  13. #include "ValueInspectorModel.h"
  14. #include <AK/Forward.h>
  15. #include <AK/Optional.h>
  16. #include <AK/StringBuilder.h>
  17. #include <Applications/HexEditor/HexEditorWindowGML.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/Statusbar.h>
  31. #include <LibGUI/TableView.h>
  32. #include <LibGUI/TextBox.h>
  33. #include <LibGUI/Toolbar.h>
  34. #include <LibGUI/ToolbarContainer.h>
  35. #include <LibTextCodec/Decoder.h>
  36. #include <string.h>
  37. REGISTER_WIDGET(HexEditor, HexEditor);
  38. HexEditorWidget::HexEditorWidget()
  39. {
  40. load_from_gml(hex_editor_window_gml).release_value_but_fixme_should_propagate_errors();
  41. m_toolbar = *find_descendant_of_type_named<GUI::Toolbar>("toolbar");
  42. m_toolbar_container = *find_descendant_of_type_named<GUI::ToolbarContainer>("toolbar_container");
  43. m_editor = *find_descendant_of_type_named<HexEditor>("editor");
  44. m_statusbar = *find_descendant_of_type_named<GUI::Statusbar>("statusbar");
  45. m_search_results = *find_descendant_of_type_named<GUI::TableView>("search_results");
  46. m_search_results_container = *find_descendant_of_type_named<GUI::Widget>("search_results_container");
  47. m_side_panel_container = *find_descendant_of_type_named<GUI::Widget>("side_panel_container");
  48. m_value_inspector_container = *find_descendant_of_type_named<GUI::Widget>("value_inspector_container");
  49. m_value_inspector = *find_descendant_of_type_named<GUI::TableView>("value_inspector");
  50. m_value_inspector->on_activation = [this](GUI::ModelIndex const& index) {
  51. if (!index.is_valid())
  52. return;
  53. m_selecting_from_inspector = true;
  54. m_editor->set_selection(m_editor->selection_start_offset(), index.data(GUI::ModelRole::Custom).to_integer<size_t>());
  55. m_editor->update();
  56. };
  57. m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
  58. m_statusbar->set_text(0, String::formatted("Offset: {:#08X}", position).release_value_but_fixme_should_propagate_errors());
  59. m_statusbar->set_text(1, String::formatted("Edit Mode: {}", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text").release_value_but_fixme_should_propagate_errors());
  60. m_statusbar->set_text(2, String::formatted("Selection Start: {}", selection_start).release_value_but_fixme_should_propagate_errors());
  61. m_statusbar->set_text(3, String::formatted("Selection End: {}", selection_end).release_value_but_fixme_should_propagate_errors());
  62. m_statusbar->set_text(4, String::formatted("Selected Bytes: {}", m_editor->selection_size()).release_value_but_fixme_should_propagate_errors());
  63. bool has_selection = m_editor->has_selection();
  64. m_copy_hex_action->set_enabled(has_selection);
  65. m_copy_text_action->set_enabled(has_selection);
  66. m_copy_as_c_code_action->set_enabled(has_selection);
  67. m_fill_selection_action->set_enabled(has_selection);
  68. if (m_value_inspector_container->is_visible() && !m_selecting_from_inspector) {
  69. update_inspector_values(selection_start);
  70. }
  71. m_selecting_from_inspector = false;
  72. };
  73. m_editor->on_change = [this](bool is_document_dirty) {
  74. window()->set_modified(is_document_dirty);
  75. };
  76. m_editor->undo_stack().on_state_change = [this] {
  77. m_undo_action->set_enabled(m_editor->undo_stack().can_undo());
  78. m_redo_action->set_enabled(m_editor->undo_stack().can_redo());
  79. };
  80. m_search_results->set_activates_on_selection(true);
  81. m_search_results->on_activation = [this](const GUI::ModelIndex& index) {
  82. if (!index.is_valid())
  83. return;
  84. auto offset = index.data(GUI::ModelRole::Custom).to_i32();
  85. m_last_found_index = offset;
  86. m_editor->set_position(offset);
  87. m_editor->update();
  88. };
  89. 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&) {
  90. String value;
  91. if (request_close() && GUI::InputBox::show(window(), value, "Enter a size:"sv, "New File"sv, GUI::InputType::NonemptyText) == GUI::InputBox::ExecResult::OK) {
  92. auto file_size = AK::StringUtils::convert_to_uint(value);
  93. if (!file_size.has_value()) {
  94. GUI::MessageBox::show(window(), "Invalid file size entered."sv, "Error"sv, GUI::MessageBox::Type::Error);
  95. return;
  96. }
  97. if (auto error = m_editor->open_new_file(file_size.value()); error.is_error()) {
  98. GUI::MessageBox::show(window(), DeprecatedString::formatted("Unable to open new file: {}"sv, error.error()), "Error"sv, GUI::MessageBox::Type::Error);
  99. return;
  100. }
  101. set_path({});
  102. window()->set_modified(false);
  103. }
  104. });
  105. m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
  106. if (!request_close())
  107. return;
  108. auto response = FileSystemAccessClient::Client::the().open_file(window(), { .requested_access = Core::File::OpenMode::ReadWrite });
  109. if (response.is_error())
  110. return;
  111. open_file(response.value().filename(), response.value().release_stream());
  112. });
  113. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  114. if (m_path.is_empty())
  115. return m_save_as_action->activate();
  116. if (auto result = m_editor->save(); result.is_error()) {
  117. GUI::MessageBox::show(window(), DeprecatedString::formatted("Unable to save file: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  118. } else {
  119. window()->set_modified(false);
  120. m_editor->update();
  121. }
  122. return;
  123. });
  124. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  125. auto response = FileSystemAccessClient::Client::the().save_file(window(), m_name, m_extension, Core::File::OpenMode::ReadWrite | Core::File::OpenMode::Truncate);
  126. if (response.is_error())
  127. return;
  128. auto file = response.release_value();
  129. if (auto result = m_editor->save_as(file.release_stream()); result.is_error()) {
  130. GUI::MessageBox::show(window(), DeprecatedString::formatted("Unable to save file: {}\n"sv, result.error()), "Error"sv, GUI::MessageBox::Type::Error);
  131. return;
  132. }
  133. window()->set_modified(false);
  134. set_path(file.filename());
  135. dbgln("Wrote document to {}", file.filename());
  136. });
  137. m_undo_action = GUI::CommonActions::make_undo_action([&](auto&) {
  138. m_editor->undo();
  139. });
  140. m_undo_action->set_enabled(false);
  141. m_redo_action = GUI::CommonActions::make_redo_action([&](auto&) {
  142. m_editor->redo();
  143. });
  144. m_redo_action->set_enabled(false);
  145. 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&) {
  146. auto old_buffer = m_search_buffer;
  147. bool find_all = false;
  148. if (FindDialog::show(window(), m_search_text, m_search_buffer, find_all) == GUI::InputBox::ExecResult::OK) {
  149. if (find_all) {
  150. auto matches = m_editor->find_all(m_search_buffer, 0);
  151. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  152. m_search_results->update();
  153. if (matches.is_empty()) {
  154. GUI::MessageBox::show(window(), DeprecatedString::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not Found"sv, GUI::MessageBox::Type::Warning);
  155. return;
  156. }
  157. GUI::MessageBox::show(window(), DeprecatedString::formatted("Found {} matches for \"{}\" in this file", matches.size(), m_search_text), DeprecatedString::formatted("{} Matches", matches.size()), GUI::MessageBox::Type::Warning);
  158. set_search_results_visible(true);
  159. } else {
  160. bool same_buffers = false;
  161. if (old_buffer.size() == m_search_buffer.size()) {
  162. if (memcmp(old_buffer.data(), m_search_buffer.data(), old_buffer.size()) == 0)
  163. same_buffers = true;
  164. }
  165. auto result = m_editor->find_and_highlight(m_search_buffer, same_buffers ? last_found_index() : 0);
  166. if (!result.has_value()) {
  167. GUI::MessageBox::show(window(), DeprecatedString::formatted("Pattern \"{}\" not found in this file", m_search_text), "Not Found"sv, GUI::MessageBox::Type::Warning);
  168. return;
  169. }
  170. m_last_found_index = result.value();
  171. }
  172. m_editor->update();
  173. }
  174. });
  175. 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&) {
  176. int new_offset;
  177. auto result = GoToOffsetDialog::show(
  178. window(),
  179. m_goto_history,
  180. new_offset,
  181. m_editor->selection_start_offset(),
  182. m_editor->buffer_size());
  183. if (result == GUI::InputBox::ExecResult::OK) {
  184. m_editor->highlight(new_offset, new_offset);
  185. m_editor->update();
  186. }
  187. });
  188. m_layout_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
  189. m_toolbar_container->set_visible(action.is_checked());
  190. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowToolbar"sv, action.is_checked());
  191. });
  192. m_layout_search_results_action = GUI::Action::create_checkable("&Search Results", [&](auto& action) {
  193. set_search_results_visible(action.is_checked());
  194. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowSearchResults"sv, action.is_checked());
  195. });
  196. 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&) {
  197. m_editor->copy_selected_hex_to_clipboard();
  198. });
  199. m_copy_hex_action->set_enabled(false);
  200. 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&) {
  201. m_editor->copy_selected_text_to_clipboard();
  202. });
  203. m_copy_text_action->set_enabled(false);
  204. 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&) {
  205. m_editor->copy_selected_hex_to_clipboard_as_c_code();
  206. });
  207. m_copy_as_c_code_action->set_enabled(false);
  208. m_fill_selection_action = GUI::Action::create("Fill &Selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
  209. String value;
  210. if (GUI::InputBox::show(window(), value, "Fill byte (hex):"sv, "Fill Selection"sv, GUI::InputType::NonemptyText) == GUI::InputBox::ExecResult::OK) {
  211. auto fill_byte = strtol(value.bytes_as_string_view().characters_without_null_termination(), nullptr, 16);
  212. auto result = m_editor->fill_selection(fill_byte);
  213. if (result.is_error())
  214. GUI::MessageBox::show_error(window(), DeprecatedString::formatted("{}", result.error()));
  215. }
  216. });
  217. m_fill_selection_action->set_enabled(false);
  218. m_layout_value_inspector_action = GUI::Action::create_checkable("&Value Inspector", [&](auto& action) {
  219. set_value_inspector_visible(action.is_checked());
  220. Config::write_bool("HexEditor"sv, "Layout"sv, "ShowValueInspector"sv, action.is_checked());
  221. });
  222. m_toolbar->add_action(*m_new_action);
  223. m_toolbar->add_action(*m_open_action);
  224. m_toolbar->add_action(*m_save_action);
  225. m_toolbar->add_separator();
  226. m_toolbar->add_action(*m_undo_action);
  227. m_toolbar->add_action(*m_redo_action);
  228. m_toolbar->add_separator();
  229. m_toolbar->add_action(*m_find_action);
  230. m_toolbar->add_action(*m_goto_offset_action);
  231. m_statusbar->segment(0).set_clickable(true);
  232. m_statusbar->segment(0).set_action(*m_goto_offset_action);
  233. m_editor->set_focus(true);
  234. GUI::Application::the()->on_action_enter = [this](GUI::Action& action) {
  235. m_statusbar->set_override_text(action.status_tip());
  236. };
  237. GUI::Application::the()->on_action_leave = [this](GUI::Action&) {
  238. m_statusbar->set_override_text({});
  239. };
  240. }
  241. void HexEditorWidget::update_inspector_values(size_t position)
  242. {
  243. // build out primitive types like u8, i8, u16, etc
  244. size_t byte_read_count = 0;
  245. u64 unsigned_64_bit_int = 0;
  246. for (int i = 0; i < 8; ++i) {
  247. Optional<u8> read_result = m_editor->get_byte(position + i);
  248. u8 current_byte = 0;
  249. if (!read_result.has_value())
  250. break;
  251. current_byte = read_result.release_value();
  252. if (m_value_inspector_little_endian)
  253. unsigned_64_bit_int = ((u64)current_byte << (8 * byte_read_count)) + unsigned_64_bit_int;
  254. else
  255. unsigned_64_bit_int = (unsigned_64_bit_int << 8) + current_byte;
  256. ++byte_read_count;
  257. }
  258. if (!m_value_inspector_little_endian) {
  259. // if we didn't read far enough, lets finish shifting the bytes so the code below works
  260. size_t bytes_left_to_read = 8 - byte_read_count;
  261. unsigned_64_bit_int = (unsigned_64_bit_int << (8 * bytes_left_to_read));
  262. }
  263. // Populate the model
  264. NonnullRefPtr<ValueInspectorModel> value_inspector_model = make_ref_counted<ValueInspectorModel>(m_value_inspector_little_endian);
  265. if (byte_read_count >= 1) {
  266. u8 unsigned_byte_value = 0;
  267. if (m_value_inspector_little_endian)
  268. unsigned_byte_value = (unsigned_64_bit_int & 0xFF);
  269. else
  270. unsigned_byte_value = (unsigned_64_bit_int >> (64 - 8)) & 0xFF;
  271. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedByte, String::number(static_cast<i8>(unsigned_byte_value)));
  272. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedByte, String::number(unsigned_byte_value));
  273. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::ASCII, String::formatted("{:c}", static_cast<char>(unsigned_byte_value)));
  274. } else {
  275. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedByte, ""_string);
  276. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedByte, ""_string);
  277. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::ASCII, ""_string);
  278. }
  279. if (byte_read_count >= 2) {
  280. u16 unsigned_short_value = 0;
  281. if (m_value_inspector_little_endian)
  282. unsigned_short_value = (unsigned_64_bit_int & 0xFFFF);
  283. else
  284. unsigned_short_value = (unsigned_64_bit_int >> (64 - 16)) & 0xFFFF;
  285. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedShort, String::number(static_cast<i16>(unsigned_short_value)));
  286. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedShort, String::number(unsigned_short_value));
  287. } else {
  288. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedShort, ""_string);
  289. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedShort, ""_string);
  290. }
  291. if (byte_read_count >= 4) {
  292. u32 unsigned_int_value = 0;
  293. if (m_value_inspector_little_endian)
  294. unsigned_int_value = (unsigned_64_bit_int & 0xFFFFFFFF);
  295. else
  296. unsigned_int_value = (unsigned_64_bit_int >> 32) & 0xFFFFFFFF;
  297. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedInt, String::number(static_cast<i32>(unsigned_int_value)));
  298. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedInt, String::number(unsigned_int_value));
  299. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Float, String::number(bit_cast<float>(unsigned_int_value)));
  300. } else {
  301. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedInt, ""_string);
  302. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedInt, ""_string);
  303. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Float, ""_string);
  304. }
  305. if (byte_read_count >= 8) {
  306. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedLong, String::number(static_cast<i64>(unsigned_64_bit_int)));
  307. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedLong, String::number(unsigned_64_bit_int));
  308. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Double, String::number(bit_cast<double>(unsigned_64_bit_int)));
  309. } else {
  310. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::SignedLong, ""_string);
  311. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UnsignedLong, ""_string);
  312. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::Double, ""_string);
  313. }
  314. // FIXME: This probably doesn't honour endianness correctly.
  315. Utf8View utf8_view { ReadonlyBytes { reinterpret_cast<u8 const*>(&unsigned_64_bit_int), 4 } };
  316. size_t valid_bytes;
  317. utf8_view.validate(valid_bytes);
  318. if (valid_bytes == 0)
  319. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8, ""_string);
  320. else {
  321. auto utf8 = String::from_utf8(utf8_view.unicode_substring_view(0, 1).as_string());
  322. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8, move(utf8));
  323. }
  324. if (byte_read_count % 2 == 0) {
  325. Utf16View utf16_view { ReadonlySpan<u16> { reinterpret_cast<u16 const*>(&unsigned_64_bit_int), 4 } };
  326. size_t valid_code_units;
  327. utf16_view.validate(valid_code_units);
  328. if (valid_code_units == 0)
  329. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16, ""_string);
  330. else
  331. 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());
  332. } else {
  333. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16, ""_string);
  334. }
  335. auto selected_bytes = m_editor->get_selected_bytes();
  336. auto ascii_string = String::from_utf8(ReadonlyBytes { selected_bytes });
  337. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::ASCIIString, move(ascii_string));
  338. Utf8View utf8_string_view { ReadonlyBytes { selected_bytes } };
  339. utf8_string_view.validate(valid_bytes);
  340. if (valid_bytes == 0)
  341. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8String, ""_string);
  342. else
  343. // FIXME: replace control chars with something else - we don't want line breaks here ;)
  344. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF8String, String::from_utf8(utf8_string_view.as_string()));
  345. // FIXME: Parse as other values like Timestamp etc
  346. auto decoder = TextCodec::decoder_for(m_value_inspector_little_endian ? "utf-16le"sv : "utf-16be"sv);
  347. ErrorOr<String> utf16_string = decoder->to_utf8(StringView(selected_bytes.span()));
  348. value_inspector_model->set_parsed_value(ValueInspectorModel::ValueType::UTF16String, move(utf16_string));
  349. m_value_inspector->set_model(value_inspector_model);
  350. m_value_inspector->update();
  351. }
  352. ErrorOr<void> HexEditorWidget::initialize_menubar(GUI::Window& window)
  353. {
  354. auto file_menu = window.add_menu("&File"_string);
  355. file_menu->add_action(*m_new_action);
  356. file_menu->add_action(*m_open_action);
  357. file_menu->add_action(*m_save_action);
  358. file_menu->add_action(*m_save_as_action);
  359. file_menu->add_separator();
  360. file_menu->add_recent_files_list([&](auto& action) {
  361. auto path = action.text();
  362. auto response = FileSystemAccessClient::Client::the().request_file_read_only_approved(&window, path);
  363. if (response.is_error())
  364. return;
  365. auto file = response.release_value();
  366. open_file(file.filename(), file.release_stream());
  367. });
  368. file_menu->add_action(GUI::CommonActions::make_quit_action([this](auto&) {
  369. if (!request_close())
  370. return;
  371. GUI::Application::the()->quit();
  372. }));
  373. auto edit_menu = window.add_menu("&Edit"_string);
  374. edit_menu->add_action(*m_undo_action);
  375. edit_menu->add_action(*m_redo_action);
  376. edit_menu->add_separator();
  377. edit_menu->add_action(GUI::CommonActions::make_select_all_action([this](auto&) {
  378. m_editor->select_all();
  379. m_editor->update();
  380. }));
  381. edit_menu->add_action(*m_fill_selection_action);
  382. edit_menu->add_separator();
  383. edit_menu->add_action(*m_copy_hex_action);
  384. edit_menu->add_action(*m_copy_text_action);
  385. edit_menu->add_action(*m_copy_as_c_code_action);
  386. edit_menu->add_separator();
  387. edit_menu->add_action(*m_find_action);
  388. 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&) {
  389. if (m_search_text.is_empty() || m_search_buffer.is_empty()) {
  390. GUI::MessageBox::show(&window, "Nothing to search for"sv, "Not Found"sv, GUI::MessageBox::Type::Warning);
  391. return;
  392. }
  393. auto result = m_editor->find_and_highlight(m_search_buffer, last_found_index());
  394. if (!result.has_value()) {
  395. GUI::MessageBox::show(&window, DeprecatedString::formatted("No more matches for \"{}\" found in this file", m_search_text), "Not Found"sv, GUI::MessageBox::Type::Warning);
  396. return;
  397. }
  398. m_editor->update();
  399. m_last_found_index = result.value();
  400. }));
  401. 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&) {
  402. int min_length = 4;
  403. auto matches = m_editor->find_all_strings(min_length);
  404. m_search_results->set_model(*new SearchResultsModel(move(matches)));
  405. m_search_results->update();
  406. if (matches.is_empty()) {
  407. GUI::MessageBox::show(&window, "No strings found in this file"sv, "Not Found"sv, GUI::MessageBox::Type::Warning);
  408. return;
  409. }
  410. set_search_results_visible(true);
  411. m_editor->update();
  412. }));
  413. edit_menu->add_separator();
  414. edit_menu->add_action(*m_goto_offset_action);
  415. auto view_menu = window.add_menu("&View"_string);
  416. auto show_toolbar = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowToolbar"sv, true);
  417. m_layout_toolbar_action->set_checked(show_toolbar);
  418. m_toolbar_container->set_visible(show_toolbar);
  419. auto show_search_results = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowSearchResults"sv, false);
  420. set_search_results_visible(show_search_results);
  421. auto show_value_inspector = Config::read_bool("HexEditor"sv, "Layout"sv, "ShowValueInspector"sv, false);
  422. set_value_inspector_visible(show_value_inspector);
  423. view_menu->add_action(*m_layout_toolbar_action);
  424. view_menu->add_action(*m_layout_search_results_action);
  425. view_menu->add_action(*m_layout_value_inspector_action);
  426. view_menu->add_separator();
  427. auto bytes_per_row = Config::read_i32("HexEditor"sv, "Layout"sv, "BytesPerRow"sv, 16);
  428. m_editor->set_bytes_per_row(bytes_per_row);
  429. m_editor->update();
  430. m_bytes_per_row_actions.set_exclusive(true);
  431. auto bytes_per_row_menu = view_menu->add_submenu("Bytes per &Row"_string);
  432. for (int i = 8; i <= 32; i += 8) {
  433. auto action = GUI::Action::create_checkable(DeprecatedString::number(i), [this, i](auto&) {
  434. m_editor->set_bytes_per_row(i);
  435. m_editor->update();
  436. Config::write_i32("HexEditor"sv, "Layout"sv, "BytesPerRow"sv, i);
  437. });
  438. m_bytes_per_row_actions.add_action(action);
  439. bytes_per_row_menu->add_action(action);
  440. if (i == bytes_per_row)
  441. action->set_checked(true);
  442. }
  443. m_value_inspector_mode_actions.set_exclusive(true);
  444. auto inspector_mode_menu = view_menu->add_submenu("Value Inspector &Mode"_string);
  445. auto little_endian_mode = GUI::Action::create_checkable("&Little Endian", [&](auto& action) {
  446. m_value_inspector_little_endian = action.is_checked();
  447. update_inspector_values(m_editor->selection_start_offset());
  448. Config::write_bool("HexEditor"sv, "Layout"sv, "UseLittleEndianInValueInspector"sv, m_value_inspector_little_endian);
  449. });
  450. m_value_inspector_mode_actions.add_action(little_endian_mode);
  451. inspector_mode_menu->add_action(little_endian_mode);
  452. auto big_endian_mode = GUI::Action::create_checkable("&Big Endian", [this](auto& action) {
  453. m_value_inspector_little_endian = !action.is_checked();
  454. update_inspector_values(m_editor->selection_start_offset());
  455. Config::write_bool("HexEditor"sv, "Layout"sv, "UseLittleEndianInValueInspector"sv, m_value_inspector_little_endian);
  456. });
  457. m_value_inspector_mode_actions.add_action(big_endian_mode);
  458. inspector_mode_menu->add_action(big_endian_mode);
  459. auto use_little_endian = Config::read_bool("HexEditor"sv, "Layout"sv, "UseLittleEndianInValueInspector"sv, true);
  460. m_value_inspector_little_endian = use_little_endian;
  461. little_endian_mode->set_checked(use_little_endian);
  462. big_endian_mode->set_checked(!use_little_endian);
  463. auto help_menu = window.add_menu("&Help"_string);
  464. help_menu->add_action(GUI::CommonActions::make_command_palette_action(&window));
  465. help_menu->add_action(GUI::CommonActions::make_help_action([](auto&) {
  466. Desktop::Launcher::open(URL::create_with_file_scheme("/usr/share/man/man1/Applications/HexEditor.md"), "/bin/Help");
  467. }));
  468. help_menu->add_action(GUI::CommonActions::make_about_action("Hex Editor"_string, GUI::Icon::default_icon("app-hex-editor"sv), &window));
  469. return {};
  470. }
  471. void HexEditorWidget::set_path(StringView path)
  472. {
  473. if (path.is_empty()) {
  474. m_path = {};
  475. m_name = {};
  476. m_extension = {};
  477. } else {
  478. auto lexical_path = LexicalPath(path);
  479. m_path = lexical_path.string();
  480. m_name = lexical_path.title();
  481. m_extension = lexical_path.extension();
  482. }
  483. update_title();
  484. }
  485. void HexEditorWidget::update_title()
  486. {
  487. StringBuilder builder;
  488. if (m_path.is_empty())
  489. builder.append("Untitled"sv);
  490. else
  491. builder.append(m_path);
  492. builder.append("[*] - Hex Editor"sv);
  493. window()->set_title(builder.to_deprecated_string());
  494. }
  495. void HexEditorWidget::open_file(String const& filename, NonnullOwnPtr<Core::File> file)
  496. {
  497. window()->set_modified(false);
  498. m_editor->open_file(move(file));
  499. set_path(filename.to_deprecated_string());
  500. GUI::Application::the()->set_most_recently_open_file(filename);
  501. }
  502. bool HexEditorWidget::request_close()
  503. {
  504. if (!window()->is_modified())
  505. return true;
  506. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path);
  507. if (result == GUI::MessageBox::ExecResult::Yes) {
  508. m_save_action->activate();
  509. return !window()->is_modified();
  510. }
  511. return result == GUI::MessageBox::ExecResult::No;
  512. }
  513. void HexEditorWidget::set_search_results_visible(bool visible)
  514. {
  515. m_layout_search_results_action->set_checked(visible);
  516. m_search_results_container->set_visible(visible);
  517. // Ensure side panel container is visible if either search result or value inspector are turned on
  518. m_side_panel_container->set_visible(visible || m_value_inspector_container->is_visible());
  519. }
  520. void HexEditorWidget::set_value_inspector_visible(bool visible)
  521. {
  522. if (visible)
  523. update_inspector_values(m_editor->selection_start_offset());
  524. m_layout_value_inspector_action->set_checked(visible);
  525. m_value_inspector_container->set_visible(visible);
  526. // Ensure side panel container is visible if either search result or value inspector are turned on
  527. m_side_panel_container->set_visible(visible || m_search_results_container->is_visible());
  528. }
  529. void HexEditorWidget::drag_enter_event(GUI::DragEvent& event)
  530. {
  531. auto const& mime_types = event.mime_types();
  532. if (mime_types.contains_slow("text/uri-list"))
  533. event.accept();
  534. }
  535. void HexEditorWidget::drop_event(GUI::DropEvent& event)
  536. {
  537. event.accept();
  538. if (event.mime_data().has_urls()) {
  539. auto urls = event.mime_data().urls();
  540. if (urls.is_empty())
  541. return;
  542. window()->move_to_front();
  543. if (!request_close())
  544. return;
  545. // TODO: A drop event should be considered user consent for opening a file
  546. auto response = FileSystemAccessClient::Client::the().request_file(window(), urls.first().serialize_path(), Core::File::OpenMode::Read);
  547. if (response.is_error())
  548. return;
  549. open_file(response.value().filename(), response.value().release_stream());
  550. }
  551. }