HexEditor.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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 "HexEditor.h"
  10. #include "SearchResultsModel.h"
  11. #include <AK/Debug.h>
  12. #include <AK/DeprecatedString.h>
  13. #include <AK/Format.h>
  14. #include <AK/ScopeGuard.h>
  15. #include <AK/StringBuilder.h>
  16. #include <LibGUI/Action.h>
  17. #include <LibGUI/Clipboard.h>
  18. #include <LibGUI/Menu.h>
  19. #include <LibGUI/MessageBox.h>
  20. #include <LibGUI/Painter.h>
  21. #include <LibGUI/Scrollbar.h>
  22. #include <LibGUI/TextEditor.h>
  23. #include <LibGUI/Window.h>
  24. #include <LibGfx/Font/FontDatabase.h>
  25. #include <LibGfx/Palette.h>
  26. #include <ctype.h>
  27. #include <fcntl.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <unistd.h>
  31. HexEditor::HexEditor()
  32. : m_document(make<HexDocumentMemory>(ByteBuffer::create_zeroed(0).release_value_but_fixme_should_propagate_errors()))
  33. {
  34. set_should_hide_unnecessary_scrollbars(true);
  35. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  36. set_scrollbars_enabled(true);
  37. set_font(Gfx::FontDatabase::default_fixed_width_font());
  38. set_background_role(ColorRole::Base);
  39. set_foreground_role(ColorRole::BaseText);
  40. vertical_scrollbar().set_step(line_height());
  41. m_blink_timer = Core::Timer::create_repeating(500, [this]() {
  42. m_cursor_blink_active = !m_cursor_blink_active;
  43. update();
  44. }).release_value_but_fixme_should_propagate_errors();
  45. m_blink_timer->start();
  46. }
  47. ErrorOr<void> HexEditor::open_new_file(size_t size)
  48. {
  49. m_document = make<HexDocumentMemory>(TRY(ByteBuffer::create_zeroed(size)));
  50. set_content_length(m_document->size());
  51. m_position = 0;
  52. m_cursor_at_low_nibble = false;
  53. m_selection_start = 0;
  54. m_selection_end = 0;
  55. scroll_position_into_view(m_position);
  56. update();
  57. update_status();
  58. return {};
  59. }
  60. void HexEditor::open_file(NonnullOwnPtr<Core::File> file)
  61. {
  62. m_document = HexDocumentFile::create(move(file)).release_value_but_fixme_should_propagate_errors();
  63. set_content_length(m_document->size());
  64. m_position = 0;
  65. m_cursor_at_low_nibble = false;
  66. m_selection_start = 0;
  67. m_selection_end = 0;
  68. scroll_position_into_view(m_position);
  69. update();
  70. update_status();
  71. }
  72. ErrorOr<void> HexEditor::fill_selection(u8 fill_byte)
  73. {
  74. if (!has_selection())
  75. return {};
  76. ByteBuffer old_values;
  77. ByteBuffer new_values;
  78. size_t length = m_selection_end - m_selection_start;
  79. new_values.resize(length);
  80. old_values.resize(length);
  81. for (size_t i = 0; i < length; i++) {
  82. size_t position = m_selection_start + i;
  83. old_values[i] = m_document->get(position).value;
  84. new_values[i] = fill_byte;
  85. m_document->set(position, fill_byte);
  86. }
  87. auto result = did_complete_action(m_selection_start, move(old_values), move(new_values));
  88. if (result.is_error()) {
  89. for (size_t i = 0; i < length; i++) {
  90. size_t position = m_selection_start + i;
  91. m_document->set(position, old_values[i]);
  92. }
  93. return result;
  94. }
  95. update();
  96. did_change();
  97. return {};
  98. }
  99. void HexEditor::set_position(size_t position)
  100. {
  101. if (position > m_document->size())
  102. return;
  103. m_position = position;
  104. m_cursor_at_low_nibble = false;
  105. reset_cursor_blink_state();
  106. scroll_position_into_view(position);
  107. update_status();
  108. }
  109. void HexEditor::set_selection(size_t position, size_t length)
  110. {
  111. if (position > m_document->size() || position + length > m_document->size())
  112. return;
  113. m_position = position;
  114. m_cursor_at_low_nibble = false;
  115. m_selection_start = position;
  116. m_selection_end = position + length;
  117. reset_cursor_blink_state();
  118. scroll_position_into_view(position);
  119. update_status();
  120. }
  121. ErrorOr<void> HexEditor::save_as(NonnullOwnPtr<Core::File> new_file)
  122. {
  123. if (m_document->type() == HexDocument::Type::File) {
  124. auto& file_document = static_cast<HexDocumentFile&>(*m_document);
  125. TRY(file_document.write_to_file(*new_file));
  126. TRY(file_document.set_file(move(new_file)));
  127. } else {
  128. auto& memory_document = static_cast<HexDocumentMemory&>(*m_document);
  129. TRY(memory_document.write_to_file(*new_file));
  130. m_document = HexDocumentFile::create(move(new_file)).release_value_but_fixme_should_propagate_errors();
  131. }
  132. update();
  133. return {};
  134. }
  135. ErrorOr<void> HexEditor::save()
  136. {
  137. if (m_document->type() != HexDocument::Type::File)
  138. return Error::from_string_literal("Unable to save from a memory document");
  139. TRY(static_cast<HexDocumentFile*>(m_document.ptr())->write_to_file());
  140. return {};
  141. }
  142. size_t HexEditor::selection_size()
  143. {
  144. if (!has_selection())
  145. return 0;
  146. return m_selection_end - m_selection_start;
  147. }
  148. bool HexEditor::copy_selected_hex_to_clipboard()
  149. {
  150. if (!has_selection())
  151. return false;
  152. StringBuilder output_string_builder;
  153. for (size_t i = m_selection_start; i < m_selection_end; i++)
  154. output_string_builder.appendff("{:02X} ", m_document->get(i).value);
  155. GUI::Clipboard::the().set_plain_text(output_string_builder.to_deprecated_string());
  156. return true;
  157. }
  158. bool HexEditor::copy_selected_text_to_clipboard()
  159. {
  160. if (!has_selection())
  161. return false;
  162. StringBuilder output_string_builder;
  163. for (size_t i = m_selection_start; i < m_selection_end; i++)
  164. output_string_builder.append(isprint(m_document->get(i).value) ? m_document->get(i).value : '.');
  165. GUI::Clipboard::the().set_plain_text(output_string_builder.to_deprecated_string());
  166. return true;
  167. }
  168. bool HexEditor::copy_selected_hex_to_clipboard_as_c_code()
  169. {
  170. if (!has_selection())
  171. return false;
  172. StringBuilder output_string_builder;
  173. output_string_builder.appendff("unsigned char raw_data[{}] = {{\n", m_selection_end - m_selection_start);
  174. output_string_builder.append(" "sv);
  175. for (size_t i = m_selection_start, j = 1; i < m_selection_end; i++, j++) {
  176. output_string_builder.appendff("{:#02X}", m_document->get(i).value);
  177. if (i >= m_selection_end - 1)
  178. continue;
  179. if ((j % 12) == 0)
  180. output_string_builder.append(",\n "sv);
  181. else
  182. output_string_builder.append(", "sv);
  183. }
  184. output_string_builder.append("\n};\n"sv);
  185. GUI::Clipboard::the().set_plain_text(output_string_builder.to_deprecated_string());
  186. return true;
  187. }
  188. void HexEditor::set_bytes_per_row(size_t bytes_per_row)
  189. {
  190. m_bytes_per_row = bytes_per_row;
  191. auto newWidth = offset_margin_width() + (m_bytes_per_row * cell_width()) + 2 * m_padding + (m_bytes_per_row * character_width()) + 4 * m_padding;
  192. auto newHeight = total_rows() * line_height() + 2 * m_padding;
  193. set_content_size({ static_cast<int>(newWidth), static_cast<int>(newHeight) });
  194. update();
  195. }
  196. void HexEditor::set_content_length(size_t length)
  197. {
  198. if (length == m_content_length)
  199. return;
  200. m_content_length = length;
  201. auto newWidth = offset_margin_width() + (m_bytes_per_row * cell_width()) + 2 * m_padding + (m_bytes_per_row * character_width()) + 4 * m_padding;
  202. auto newHeight = total_rows() * line_height() + 2 * m_padding;
  203. set_content_size({ static_cast<int>(newWidth), static_cast<int>(newHeight) });
  204. }
  205. Optional<u8> HexEditor::get_byte(size_t position)
  206. {
  207. if (position < m_document->size())
  208. return m_document->get(position).value;
  209. return {};
  210. }
  211. ByteBuffer HexEditor::get_selected_bytes()
  212. {
  213. auto num_selected_bytes = m_selection_end - m_selection_start;
  214. ByteBuffer data;
  215. data.ensure_capacity(num_selected_bytes);
  216. for (size_t i = m_selection_start; i < m_selection_end; i++)
  217. data.append(m_document->get(i).value);
  218. return data;
  219. }
  220. void HexEditor::mousedown_event(GUI::MouseEvent& event)
  221. {
  222. if (event.button() != GUI::MouseButton::Primary) {
  223. return;
  224. }
  225. auto absolute_x = horizontal_scrollbar().value() + event.x();
  226. auto absolute_y = vertical_scrollbar().value() + event.y();
  227. auto hex_start_x = frame_thickness() + m_address_bar_width;
  228. auto hex_start_y = frame_thickness() + m_padding;
  229. auto hex_end_x = static_cast<int>(hex_start_x + bytes_per_row() * cell_width());
  230. auto hex_end_y = static_cast<int>(hex_start_y + m_padding + total_rows() * line_height());
  231. auto text_start_x = static_cast<int>(frame_thickness() + m_address_bar_width + 2 * m_padding + bytes_per_row() * cell_width());
  232. auto text_start_y = frame_thickness() + m_padding;
  233. auto text_end_x = static_cast<int>(text_start_x + bytes_per_row() * character_width());
  234. auto text_end_y = static_cast<int>(text_start_y + m_padding + total_rows() * line_height());
  235. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  236. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  237. return;
  238. auto byte_x = (absolute_x - hex_start_x) / cell_width();
  239. auto byte_y = (absolute_y - hex_start_y) / line_height();
  240. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  241. if (offset >= m_document->size())
  242. return;
  243. dbgln_if(HEX_DEBUG, "HexEditor::mousedown_event(hex): offset={}", offset);
  244. m_edit_mode = EditMode::Hex;
  245. m_cursor_at_low_nibble = false;
  246. m_position = offset;
  247. m_in_drag_select = true;
  248. m_selection_start = offset;
  249. m_selection_end = offset;
  250. update();
  251. update_status();
  252. }
  253. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  254. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  255. return;
  256. auto byte_x = (absolute_x - text_start_x) / character_width();
  257. auto byte_y = (absolute_y - text_start_y) / line_height();
  258. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  259. if (offset >= m_document->size())
  260. return;
  261. dbgln_if(HEX_DEBUG, "HexEditor::mousedown_event(text): offset={}", offset);
  262. m_position = offset;
  263. m_cursor_at_low_nibble = false;
  264. m_in_drag_select = true;
  265. m_selection_start = offset;
  266. m_selection_end = offset;
  267. m_edit_mode = EditMode::Text;
  268. update();
  269. update_status();
  270. }
  271. }
  272. void HexEditor::mousemove_event(GUI::MouseEvent& event)
  273. {
  274. auto absolute_x = horizontal_scrollbar().value() + event.x();
  275. auto absolute_y = vertical_scrollbar().value() + event.y();
  276. auto hex_start_x = frame_thickness() + m_address_bar_width;
  277. auto hex_start_y = frame_thickness() + m_padding;
  278. auto hex_end_x = static_cast<int>(hex_start_x + bytes_per_row() * cell_width());
  279. auto hex_end_y = static_cast<int>(hex_start_y + m_padding + total_rows() * line_height());
  280. auto text_start_x = static_cast<int>(frame_thickness() + m_address_bar_width + 2 * m_padding + bytes_per_row() * cell_width());
  281. auto text_start_y = frame_thickness() + m_padding;
  282. auto text_end_x = static_cast<int>(text_start_x + bytes_per_row() * character_width());
  283. auto text_end_y = static_cast<int>(text_start_y + m_padding + total_rows() * line_height());
  284. if ((absolute_x >= hex_start_x && absolute_x <= hex_end_x
  285. && absolute_y >= hex_start_y && absolute_y <= hex_end_y)
  286. || (absolute_x >= text_start_x && absolute_x <= text_end_x
  287. && absolute_y >= text_start_y && absolute_y <= text_end_y)) {
  288. set_override_cursor(Gfx::StandardCursor::IBeam);
  289. } else {
  290. set_override_cursor(Gfx::StandardCursor::None);
  291. }
  292. if (m_in_drag_select) {
  293. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  294. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  295. return;
  296. auto byte_x = (absolute_x - hex_start_x) / cell_width();
  297. auto byte_y = (absolute_y - hex_start_y) / line_height();
  298. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  299. if (offset > m_document->size())
  300. return;
  301. m_selection_end = offset;
  302. m_position = offset;
  303. scroll_position_into_view(offset);
  304. }
  305. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  306. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  307. return;
  308. auto byte_x = (absolute_x - text_start_x) / character_width();
  309. auto byte_y = (absolute_y - text_start_y) / line_height();
  310. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  311. if (offset > m_document->size())
  312. return;
  313. m_selection_end = offset;
  314. m_position = offset;
  315. scroll_position_into_view(offset);
  316. }
  317. update_status();
  318. update();
  319. return;
  320. }
  321. }
  322. void HexEditor::mouseup_event(GUI::MouseEvent& event)
  323. {
  324. if (event.button() == GUI::MouseButton::Primary) {
  325. if (m_in_drag_select) {
  326. if (m_selection_end < m_selection_start) {
  327. // lets flip these around
  328. auto start = m_selection_end;
  329. m_selection_end = m_selection_start;
  330. m_selection_start = start;
  331. }
  332. m_in_drag_select = false;
  333. }
  334. update();
  335. update_status();
  336. }
  337. }
  338. void HexEditor::scroll_position_into_view(size_t position)
  339. {
  340. size_t y = position / bytes_per_row();
  341. size_t x = position % bytes_per_row();
  342. Gfx::IntRect rect {
  343. static_cast<int>(frame_thickness() + offset_margin_width() + x * cell_width() + 2 * m_padding),
  344. static_cast<int>(frame_thickness() + m_padding + y * line_height()),
  345. static_cast<int>(cell_width()),
  346. static_cast<int>(line_height() - m_line_spacing)
  347. };
  348. scroll_into_view(rect, true, true);
  349. }
  350. void HexEditor::keydown_event(GUI::KeyEvent& event)
  351. {
  352. dbgln_if(HEX_DEBUG, "HexEditor::keydown_event key={}", static_cast<u8>(event.key()));
  353. auto move_and_update_cursor_by = [&](i64 cursor_location_change) {
  354. size_t new_position = m_position + cursor_location_change;
  355. if (event.modifiers() & Mod_Shift) {
  356. size_t selection_pivot = m_position == m_selection_end ? m_selection_start : m_selection_end;
  357. m_position = new_position;
  358. m_selection_start = selection_pivot;
  359. m_selection_end = m_position;
  360. if (m_selection_start > m_selection_end)
  361. swap(m_selection_start, m_selection_end);
  362. } else
  363. m_selection_start = m_selection_end = m_position = new_position;
  364. m_cursor_at_low_nibble = false;
  365. reset_cursor_blink_state();
  366. scroll_position_into_view(m_position);
  367. update();
  368. update_status();
  369. };
  370. if (event.key() == KeyCode::Key_Up) {
  371. if (m_position >= bytes_per_row())
  372. move_and_update_cursor_by(-bytes_per_row());
  373. return;
  374. }
  375. if (event.key() == KeyCode::Key_Down) {
  376. if (m_position + bytes_per_row() < m_document->size())
  377. move_and_update_cursor_by(bytes_per_row());
  378. return;
  379. }
  380. if (event.key() == KeyCode::Key_Left) {
  381. if (m_position >= 1)
  382. move_and_update_cursor_by(-1);
  383. return;
  384. }
  385. if (event.key() == KeyCode::Key_Right) {
  386. if (m_position + 1 < m_document->size())
  387. move_and_update_cursor_by(1);
  388. return;
  389. }
  390. if (event.key() == KeyCode::Key_Backspace) {
  391. if (m_position > 0)
  392. move_and_update_cursor_by(-1);
  393. return;
  394. }
  395. if (event.key() == KeyCode::Key_PageUp) {
  396. auto cursor_location_change = min(bytes_per_row() * floor(visible_content_rect().height() / line_height()), m_position);
  397. if (cursor_location_change > 0)
  398. move_and_update_cursor_by(-cursor_location_change);
  399. return;
  400. }
  401. if (event.key() == KeyCode::Key_PageDown) {
  402. auto cursor_location_change = min(bytes_per_row() * floor(visible_content_rect().height() / line_height()), m_document->size() - m_position);
  403. if (cursor_location_change > 0)
  404. move_and_update_cursor_by(cursor_location_change);
  405. return;
  406. }
  407. if (!event.ctrl() && !event.alt() && !event.text().is_empty()) {
  408. ErrorOr<void> result;
  409. if (m_edit_mode == EditMode::Hex) {
  410. result = hex_mode_keydown_event(event);
  411. } else {
  412. result = text_mode_keydown_event(event);
  413. }
  414. if (result.is_error())
  415. GUI::MessageBox::show_error(window(), DeprecatedString::formatted("{}", result.error()));
  416. }
  417. event.ignore();
  418. }
  419. ErrorOr<void> HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event)
  420. {
  421. if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
  422. if (m_document->size() == 0)
  423. return {};
  424. VERIFY(m_position <= m_document->size());
  425. auto old_value = m_document->get(m_position).value;
  426. // yes, this is terrible... but it works.
  427. auto value = (event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9)
  428. ? event.key() - KeyCode::Key_0
  429. : (event.key() - KeyCode::Key_A) + 0xA;
  430. if (!m_cursor_at_low_nibble) {
  431. u8 existing_change = m_document->get(m_position).value;
  432. u8 new_value = value << 4 | (existing_change & 0xF); // shift new value left 4 bits, OR with existing last 4 bits
  433. m_document->set(m_position, new_value);
  434. auto result = did_complete_action(m_position, old_value, new_value);
  435. if (result.is_error()) {
  436. m_document->set(m_position, old_value);
  437. return result;
  438. }
  439. m_cursor_at_low_nibble = true;
  440. } else {
  441. u8 new_value = (m_document->get(m_position).value & 0xF0) | value; // save the first 4 bits, OR the new value in the last 4
  442. m_document->set(m_position, new_value);
  443. auto result = did_complete_action(m_position, old_value, new_value);
  444. if (result.is_error()) {
  445. m_document->set(m_position, old_value);
  446. return result;
  447. }
  448. if (m_position + 1 < m_document->size())
  449. m_position++;
  450. m_cursor_at_low_nibble = false;
  451. }
  452. reset_cursor_blink_state();
  453. update();
  454. update_status();
  455. did_change();
  456. }
  457. return {};
  458. }
  459. ErrorOr<void> HexEditor::text_mode_keydown_event(GUI::KeyEvent& event)
  460. {
  461. if (m_document->size() == 0)
  462. return {};
  463. VERIFY(m_position < m_document->size());
  464. if (event.code_point() == 0) // This is a control key
  465. return {};
  466. auto old_value = m_document->get(m_position).value;
  467. auto new_value = event.code_point();
  468. m_document->set(m_position, new_value);
  469. TRY(did_complete_action(m_position, old_value, new_value));
  470. if (m_position + 1 < m_document->size())
  471. m_position++;
  472. m_cursor_at_low_nibble = false;
  473. reset_cursor_blink_state();
  474. update();
  475. update_status();
  476. did_change();
  477. return {};
  478. }
  479. void HexEditor::update_status()
  480. {
  481. if (on_status_change)
  482. on_status_change(m_position, m_edit_mode, m_selection_start, m_selection_end);
  483. }
  484. void HexEditor::did_change()
  485. {
  486. if (on_change)
  487. on_change(m_document->is_dirty());
  488. }
  489. void HexEditor::paint_event(GUI::PaintEvent& event)
  490. {
  491. GUI::Frame::paint_event(event);
  492. GUI::Painter painter(*this);
  493. painter.add_clip_rect(widget_inner_rect());
  494. painter.add_clip_rect(event.rect());
  495. painter.fill_rect(event.rect(), palette().color(background_role()));
  496. if (m_document->size() == 0)
  497. return;
  498. painter.translate(frame_thickness(), frame_thickness());
  499. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  500. Gfx::IntRect offset_clip_rect {
  501. 0,
  502. vertical_scrollbar().value(),
  503. m_address_bar_width - m_padding,
  504. height() - height_occupied_by_horizontal_scrollbar() //(total_rows() * line_height()) + 5
  505. };
  506. painter.fill_rect(offset_clip_rect, palette().ruler());
  507. painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right().translated(-1), palette().ruler_border());
  508. auto margin_and_hex_width = static_cast<int>(offset_margin_width() + m_bytes_per_row * cell_width() + 3 * m_padding);
  509. painter.draw_line({ margin_and_hex_width, 0 },
  510. { margin_and_hex_width, vertical_scrollbar().value() + (height() - height_occupied_by_horizontal_scrollbar()) },
  511. palette().ruler_border());
  512. size_t view_height = (height() - height_occupied_by_horizontal_scrollbar());
  513. size_t min_row = max(0, vertical_scrollbar().value() / line_height()); // if below 0 then use 0
  514. size_t max_row = min(total_rows(), min_row + ceil_div(view_height, line_height())); // if above calculated rows, use calculated rows
  515. // paint offsets
  516. for (size_t i = min_row; i < max_row; i++) {
  517. Gfx::IntRect side_offset_rect {
  518. frame_thickness() + m_padding,
  519. static_cast<int>(frame_thickness() + m_padding + i * line_height()),
  520. width() - width_occupied_by_vertical_scrollbar(),
  521. height() - height_occupied_by_horizontal_scrollbar()
  522. };
  523. bool is_current_line = (m_position / bytes_per_row()) == i;
  524. auto line = DeprecatedString::formatted("{:#08X}", i * bytes_per_row());
  525. painter.draw_text(
  526. side_offset_rect,
  527. line,
  528. is_current_line ? font().bold_variant() : font(),
  529. Gfx::TextAlignment::TopLeft,
  530. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  531. }
  532. for (size_t i = min_row; i < max_row; i++) {
  533. for (size_t j = 0; j < bytes_per_row(); j++) {
  534. auto byte_position = (i * bytes_per_row()) + j;
  535. if (byte_position >= m_document->size())
  536. return;
  537. bool const edited_flag = m_document->get(byte_position).modified;
  538. bool const selection_inbetween_start_end = byte_position >= m_selection_start && byte_position < m_selection_end;
  539. bool const selection_inbetween_end_start = byte_position >= m_selection_end && byte_position < m_selection_start;
  540. bool const highlight_flag = selection_inbetween_start_end || selection_inbetween_end_start;
  541. Gfx::IntRect hex_display_rect {
  542. frame_thickness() + offset_margin_width() + j * cell_width() + 2 * m_padding,
  543. frame_thickness() + m_padding + i * line_height(),
  544. cell_width(),
  545. line_height() - m_line_spacing
  546. };
  547. Gfx::IntRect background_rect {
  548. frame_thickness() + offset_margin_width() + j * cell_width() + 1 * m_padding,
  549. frame_thickness() + m_line_spacing / 2 + i * line_height(),
  550. cell_width(),
  551. line_height()
  552. };
  553. const u8 cell_value = m_document->get(byte_position).value;
  554. auto line = DeprecatedString::formatted("{:02X}", cell_value);
  555. Gfx::Color background_color = palette().color(background_role());
  556. Gfx::Color text_color = [&]() -> Gfx::Color {
  557. if (edited_flag)
  558. return Color::Red;
  559. if (cell_value == 0x00)
  560. return palette().color(ColorRole::PlaceholderText);
  561. return palette().color(foreground_role());
  562. }();
  563. if (highlight_flag) {
  564. background_color = edited_flag ? palette().selection().inverted() : palette().selection();
  565. text_color = edited_flag ? palette().selection_text().inverted() : palette().selection_text();
  566. } else if (byte_position == m_position && m_edit_mode == EditMode::Text) {
  567. background_color = palette().inactive_selection();
  568. text_color = palette().inactive_selection_text();
  569. }
  570. painter.fill_rect(background_rect, background_color);
  571. painter.draw_text(hex_display_rect, line, Gfx::TextAlignment::TopLeft, text_color);
  572. if (m_edit_mode == EditMode::Hex) {
  573. if (byte_position == m_position && m_cursor_blink_active) {
  574. Gfx::IntRect cursor_position_rect {
  575. static_cast<int>(hex_display_rect.left() + m_cursor_at_low_nibble * character_width()),
  576. hex_display_rect.top(),
  577. 2,
  578. hex_display_rect.height()
  579. };
  580. painter.fill_rect(cursor_position_rect, palette().text_cursor());
  581. }
  582. }
  583. Gfx::IntRect text_display_rect {
  584. frame_thickness() + offset_margin_width() + bytes_per_row() * cell_width() + j * character_width() + 4 * m_padding,
  585. frame_thickness() + m_padding + i * line_height(),
  586. character_width(),
  587. line_height() - m_line_spacing
  588. };
  589. Gfx::IntRect text_background_rect {
  590. frame_thickness() + offset_margin_width() + bytes_per_row() * cell_width() + j * character_width() + 4 * m_padding,
  591. frame_thickness() + m_line_spacing / 2 + i * line_height(),
  592. character_width(),
  593. line_height()
  594. };
  595. background_color = palette().color(background_role());
  596. text_color = [&]() -> Gfx::Color {
  597. if (edited_flag)
  598. return Color::Red;
  599. if (cell_value == 0x00)
  600. return palette().color(ColorRole::PlaceholderText);
  601. return palette().color(foreground_role());
  602. }();
  603. if (highlight_flag) {
  604. background_color = edited_flag ? palette().selection().inverted() : palette().selection();
  605. text_color = edited_flag ? palette().selection_text().inverted() : palette().selection_text();
  606. } else if (byte_position == m_position && m_edit_mode == EditMode::Hex) {
  607. background_color = palette().inactive_selection();
  608. text_color = palette().inactive_selection_text();
  609. }
  610. painter.fill_rect(text_background_rect, background_color);
  611. painter.draw_text(text_display_rect, DeprecatedString::formatted("{:c}", isprint(cell_value) ? cell_value : '.'), Gfx::TextAlignment::TopLeft, text_color);
  612. if (m_edit_mode == EditMode::Text) {
  613. if (byte_position == m_position && m_cursor_blink_active) {
  614. Gfx::IntRect cursor_position_rect {
  615. text_display_rect.left(), text_display_rect.top(), 2, text_display_rect.height()
  616. };
  617. painter.fill_rect(cursor_position_rect, palette().text_cursor());
  618. }
  619. }
  620. }
  621. }
  622. }
  623. void HexEditor::select_all()
  624. {
  625. highlight(0, m_document->size());
  626. set_position(0);
  627. }
  628. void HexEditor::highlight(size_t start, size_t end)
  629. {
  630. m_selection_start = start;
  631. m_selection_end = end;
  632. set_position(start);
  633. }
  634. Optional<size_t> HexEditor::find_and_highlight(ByteBuffer& needle, size_t start)
  635. {
  636. auto end_of_match = find(needle, start);
  637. if (end_of_match.has_value()) {
  638. highlight(end_of_match.value() - needle.size(), end_of_match.value());
  639. }
  640. return end_of_match;
  641. }
  642. Optional<size_t> HexEditor::find(ByteBuffer& needle, size_t start)
  643. {
  644. if (m_document->size() == 0)
  645. return {};
  646. for (size_t i = start; i < m_document->size(); i++) {
  647. if (m_document->get(i).value == *needle.data()) {
  648. bool found = true;
  649. for (size_t j = 1; j < needle.size(); j++) {
  650. if (m_document->get(i + j).value != needle.data()[j]) {
  651. found = false;
  652. break;
  653. }
  654. }
  655. if (found) {
  656. auto end_of_match = i + needle.size();
  657. return end_of_match;
  658. }
  659. }
  660. }
  661. return {};
  662. }
  663. Vector<Match> HexEditor::find_all(ByteBuffer& needle, size_t start)
  664. {
  665. if (m_document->size() == 0 || needle.size() == 0)
  666. return {};
  667. Vector<Match> matches;
  668. size_t i = start;
  669. for (; i < m_document->size(); i++) {
  670. if (m_document->get(i).value == *needle.data()) {
  671. bool found = true;
  672. for (size_t j = 1; j < needle.size(); j++) {
  673. if (m_document->get(i + j).value != needle.data()[j]) {
  674. found = false;
  675. break;
  676. }
  677. }
  678. if (found) {
  679. matches.append({ i, DeprecatedString::formatted("{}", StringView { needle }.to_deprecated_string().characters()) });
  680. i += needle.size() - 1;
  681. }
  682. }
  683. }
  684. if (matches.is_empty())
  685. return {};
  686. auto first_match = matches.at(0);
  687. highlight(first_match.offset, first_match.offset + first_match.value.length());
  688. return matches;
  689. }
  690. Vector<Match> HexEditor::find_all_strings(size_t min_length)
  691. {
  692. if (m_document->size() == 0)
  693. return {};
  694. Vector<Match> matches;
  695. bool found_string = false;
  696. size_t offset = 0;
  697. StringBuilder builder;
  698. for (size_t i = 0; i < m_document->size(); i++) {
  699. char c = m_document->get(i).value;
  700. if (isprint(c)) {
  701. if (!found_string) {
  702. offset = i;
  703. found_string = true;
  704. }
  705. builder.append(c);
  706. } else {
  707. if (builder.length() >= min_length)
  708. matches.append({ offset, builder.to_deprecated_string() });
  709. builder.clear();
  710. found_string = false;
  711. }
  712. }
  713. if (matches.is_empty())
  714. return {};
  715. auto first_match = matches.at(0);
  716. highlight(first_match.offset, first_match.offset + first_match.value.length());
  717. return matches;
  718. }
  719. void HexEditor::reset_cursor_blink_state()
  720. {
  721. m_cursor_blink_active = true;
  722. m_blink_timer->restart();
  723. }
  724. ErrorOr<void> HexEditor::did_complete_action(size_t position, u8 old_value, u8 new_value)
  725. {
  726. if (old_value == new_value)
  727. return {};
  728. auto command = make<HexDocumentUndoCommand>(m_document->make_weak_ptr(), position);
  729. // We know this won't allocate because the buffers start empty
  730. MUST(command->try_add_changed_byte(old_value, new_value));
  731. TRY(m_undo_stack.try_push(move(command)));
  732. return {};
  733. }
  734. ErrorOr<void> HexEditor::did_complete_action(size_t position, ByteBuffer&& old_values, ByteBuffer&& new_values)
  735. {
  736. auto command = make<HexDocumentUndoCommand>(m_document->make_weak_ptr(), position);
  737. TRY(command->try_add_changed_bytes(move(old_values), move(new_values)));
  738. TRY(m_undo_stack.try_push(move(command)));
  739. return {};
  740. }
  741. bool HexEditor::undo()
  742. {
  743. if (!m_undo_stack.can_undo())
  744. return false;
  745. m_undo_stack.undo();
  746. reset_cursor_blink_state();
  747. update();
  748. update_status();
  749. did_change();
  750. return true;
  751. }
  752. bool HexEditor::redo()
  753. {
  754. if (!m_undo_stack.can_redo())
  755. return false;
  756. m_undo_stack.redo();
  757. reset_cursor_blink_state();
  758. update();
  759. update_status();
  760. did_change();
  761. return true;
  762. }
  763. GUI::UndoStack& HexEditor::undo_stack()
  764. {
  765. return m_undo_stack;
  766. }