HexEditor.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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::Stream::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::Stream::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. 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. void HexEditor::mousedown_event(GUI::MouseEvent& event)
  212. {
  213. if (event.button() != GUI::MouseButton::Primary) {
  214. return;
  215. }
  216. auto absolute_x = horizontal_scrollbar().value() + event.x();
  217. auto absolute_y = vertical_scrollbar().value() + event.y();
  218. auto hex_start_x = frame_thickness() + m_address_bar_width;
  219. auto hex_start_y = frame_thickness() + m_padding;
  220. auto hex_end_x = static_cast<int>(hex_start_x + bytes_per_row() * cell_width());
  221. auto hex_end_y = static_cast<int>(hex_start_y + m_padding + total_rows() * line_height());
  222. auto text_start_x = static_cast<int>(frame_thickness() + m_address_bar_width + 2 * m_padding + bytes_per_row() * cell_width());
  223. auto text_start_y = frame_thickness() + m_padding;
  224. auto text_end_x = static_cast<int>(text_start_x + bytes_per_row() * character_width());
  225. auto text_end_y = static_cast<int>(text_start_y + m_padding + total_rows() * line_height());
  226. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  227. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  228. return;
  229. auto byte_x = (absolute_x - hex_start_x) / cell_width();
  230. auto byte_y = (absolute_y - hex_start_y) / line_height();
  231. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  232. if (offset >= m_document->size())
  233. return;
  234. dbgln_if(HEX_DEBUG, "HexEditor::mousedown_event(hex): offset={}", offset);
  235. m_edit_mode = EditMode::Hex;
  236. m_cursor_at_low_nibble = false;
  237. m_position = offset;
  238. m_in_drag_select = true;
  239. m_selection_start = offset;
  240. m_selection_end = offset;
  241. update();
  242. update_status();
  243. }
  244. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  245. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  246. return;
  247. auto byte_x = (absolute_x - text_start_x) / character_width();
  248. auto byte_y = (absolute_y - text_start_y) / line_height();
  249. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  250. if (offset >= m_document->size())
  251. return;
  252. dbgln_if(HEX_DEBUG, "HexEditor::mousedown_event(text): offset={}", offset);
  253. m_position = offset;
  254. m_cursor_at_low_nibble = false;
  255. m_in_drag_select = true;
  256. m_selection_start = offset;
  257. m_selection_end = offset;
  258. m_edit_mode = EditMode::Text;
  259. update();
  260. update_status();
  261. }
  262. }
  263. void HexEditor::mousemove_event(GUI::MouseEvent& event)
  264. {
  265. auto absolute_x = horizontal_scrollbar().value() + event.x();
  266. auto absolute_y = vertical_scrollbar().value() + event.y();
  267. auto hex_start_x = frame_thickness() + m_address_bar_width;
  268. auto hex_start_y = frame_thickness() + m_padding;
  269. auto hex_end_x = static_cast<int>(hex_start_x + bytes_per_row() * cell_width());
  270. auto hex_end_y = static_cast<int>(hex_start_y + m_padding + total_rows() * line_height());
  271. auto text_start_x = static_cast<int>(frame_thickness() + m_address_bar_width + 2 * m_padding + bytes_per_row() * cell_width());
  272. auto text_start_y = frame_thickness() + m_padding;
  273. auto text_end_x = static_cast<int>(text_start_x + bytes_per_row() * character_width());
  274. auto text_end_y = static_cast<int>(text_start_y + m_padding + total_rows() * line_height());
  275. if ((absolute_x >= hex_start_x && absolute_x <= hex_end_x
  276. && absolute_y >= hex_start_y && absolute_y <= hex_end_y)
  277. || (absolute_x >= text_start_x && absolute_x <= text_end_x
  278. && absolute_y >= text_start_y && absolute_y <= text_end_y)) {
  279. set_override_cursor(Gfx::StandardCursor::IBeam);
  280. } else {
  281. set_override_cursor(Gfx::StandardCursor::None);
  282. }
  283. if (m_in_drag_select) {
  284. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  285. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  286. return;
  287. auto byte_x = (absolute_x - hex_start_x) / cell_width();
  288. auto byte_y = (absolute_y - hex_start_y) / line_height();
  289. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  290. if (offset > m_document->size())
  291. return;
  292. m_selection_end = offset;
  293. m_position = offset;
  294. scroll_position_into_view(offset);
  295. }
  296. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  297. if (absolute_x < hex_start_x || absolute_y < hex_start_y)
  298. return;
  299. auto byte_x = (absolute_x - text_start_x) / character_width();
  300. auto byte_y = (absolute_y - text_start_y) / line_height();
  301. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  302. if (offset > m_document->size())
  303. return;
  304. m_selection_end = offset;
  305. m_position = offset;
  306. scroll_position_into_view(offset);
  307. }
  308. update_status();
  309. update();
  310. return;
  311. }
  312. }
  313. void HexEditor::mouseup_event(GUI::MouseEvent& event)
  314. {
  315. if (event.button() == GUI::MouseButton::Primary) {
  316. if (m_in_drag_select) {
  317. if (m_selection_end < m_selection_start) {
  318. // lets flip these around
  319. auto start = m_selection_end;
  320. m_selection_end = m_selection_start;
  321. m_selection_start = start;
  322. }
  323. m_in_drag_select = false;
  324. }
  325. update();
  326. update_status();
  327. }
  328. }
  329. void HexEditor::scroll_position_into_view(size_t position)
  330. {
  331. size_t y = position / bytes_per_row();
  332. size_t x = position % bytes_per_row();
  333. Gfx::IntRect rect {
  334. static_cast<int>(frame_thickness() + offset_margin_width() + x * cell_width() + 2 * m_padding),
  335. static_cast<int>(frame_thickness() + m_padding + y * line_height()),
  336. static_cast<int>(cell_width()),
  337. static_cast<int>(line_height() - m_line_spacing)
  338. };
  339. scroll_into_view(rect, true, true);
  340. }
  341. void HexEditor::keydown_event(GUI::KeyEvent& event)
  342. {
  343. dbgln_if(HEX_DEBUG, "HexEditor::keydown_event key={}", static_cast<u8>(event.key()));
  344. auto move_and_update_cursor_by = [&](i64 cursor_location_change) {
  345. size_t new_position = m_position + cursor_location_change;
  346. if (event.modifiers() & Mod_Shift) {
  347. size_t selection_pivot = m_position == m_selection_end ? m_selection_start : m_selection_end;
  348. m_position = new_position;
  349. m_selection_start = selection_pivot;
  350. m_selection_end = m_position;
  351. if (m_selection_start > m_selection_end)
  352. swap(m_selection_start, m_selection_end);
  353. } else
  354. m_selection_start = m_selection_end = m_position = new_position;
  355. m_cursor_at_low_nibble = false;
  356. reset_cursor_blink_state();
  357. scroll_position_into_view(m_position);
  358. update();
  359. update_status();
  360. };
  361. if (event.key() == KeyCode::Key_Up) {
  362. if (m_position >= bytes_per_row())
  363. move_and_update_cursor_by(-bytes_per_row());
  364. return;
  365. }
  366. if (event.key() == KeyCode::Key_Down) {
  367. if (m_position + bytes_per_row() < m_document->size())
  368. move_and_update_cursor_by(bytes_per_row());
  369. return;
  370. }
  371. if (event.key() == KeyCode::Key_Left) {
  372. if (m_position >= 1)
  373. move_and_update_cursor_by(-1);
  374. return;
  375. }
  376. if (event.key() == KeyCode::Key_Right) {
  377. if (m_position + 1 < m_document->size())
  378. move_and_update_cursor_by(1);
  379. return;
  380. }
  381. if (event.key() == KeyCode::Key_Backspace) {
  382. if (m_position > 0)
  383. move_and_update_cursor_by(-1);
  384. return;
  385. }
  386. if (event.key() == KeyCode::Key_PageUp) {
  387. auto cursor_location_change = min(bytes_per_row() * floor(visible_content_rect().height() / line_height()), m_position);
  388. if (cursor_location_change > 0)
  389. move_and_update_cursor_by(-cursor_location_change);
  390. return;
  391. }
  392. if (event.key() == KeyCode::Key_PageDown) {
  393. auto cursor_location_change = min(bytes_per_row() * floor(visible_content_rect().height() / line_height()), m_document->size() - m_position);
  394. if (cursor_location_change > 0)
  395. move_and_update_cursor_by(cursor_location_change);
  396. return;
  397. }
  398. if (!event.ctrl() && !event.alt() && !event.text().is_empty()) {
  399. ErrorOr<void> result;
  400. if (m_edit_mode == EditMode::Hex) {
  401. result = hex_mode_keydown_event(event);
  402. } else {
  403. result = text_mode_keydown_event(event);
  404. }
  405. if (result.is_error())
  406. GUI::MessageBox::show_error(window(), DeprecatedString::formatted("{}", result.error()));
  407. }
  408. event.ignore();
  409. }
  410. ErrorOr<void> HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event)
  411. {
  412. if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
  413. if (m_document->size() == 0)
  414. return {};
  415. VERIFY(m_position <= m_document->size());
  416. auto old_value = m_document->get(m_position).value;
  417. // yes, this is terrible... but it works.
  418. auto value = (event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9)
  419. ? event.key() - KeyCode::Key_0
  420. : (event.key() - KeyCode::Key_A) + 0xA;
  421. if (!m_cursor_at_low_nibble) {
  422. u8 existing_change = m_document->get(m_position).value;
  423. u8 new_value = value << 4 | (existing_change & 0xF); // shift new value left 4 bits, OR with existing last 4 bits
  424. m_document->set(m_position, new_value);
  425. auto result = did_complete_action(m_position, old_value, new_value);
  426. if (result.is_error()) {
  427. m_document->set(m_position, old_value);
  428. return result;
  429. }
  430. m_cursor_at_low_nibble = true;
  431. } else {
  432. u8 new_value = (m_document->get(m_position).value & 0xF0) | value; // save the first 4 bits, OR the new value in the last 4
  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. if (m_position + 1 < m_document->size())
  440. m_position++;
  441. m_cursor_at_low_nibble = false;
  442. }
  443. reset_cursor_blink_state();
  444. update();
  445. update_status();
  446. did_change();
  447. }
  448. return {};
  449. }
  450. ErrorOr<void> HexEditor::text_mode_keydown_event(GUI::KeyEvent& event)
  451. {
  452. if (m_document->size() == 0)
  453. return {};
  454. VERIFY(m_position < m_document->size());
  455. if (event.code_point() == 0) // This is a control key
  456. return {};
  457. auto old_value = m_document->get(m_position).value;
  458. auto new_value = event.code_point();
  459. m_document->set(m_position, new_value);
  460. TRY(did_complete_action(m_position, old_value, new_value));
  461. if (m_position + 1 < m_document->size())
  462. m_position++;
  463. m_cursor_at_low_nibble = false;
  464. reset_cursor_blink_state();
  465. update();
  466. update_status();
  467. did_change();
  468. return {};
  469. }
  470. void HexEditor::update_status()
  471. {
  472. if (on_status_change)
  473. on_status_change(m_position, m_edit_mode, m_selection_start, m_selection_end);
  474. }
  475. void HexEditor::did_change()
  476. {
  477. if (on_change)
  478. on_change(m_document->is_dirty());
  479. }
  480. void HexEditor::paint_event(GUI::PaintEvent& event)
  481. {
  482. GUI::Frame::paint_event(event);
  483. GUI::Painter painter(*this);
  484. painter.add_clip_rect(widget_inner_rect());
  485. painter.add_clip_rect(event.rect());
  486. painter.fill_rect(event.rect(), palette().color(background_role()));
  487. if (m_document->size() == 0)
  488. return;
  489. painter.translate(frame_thickness(), frame_thickness());
  490. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  491. Gfx::IntRect offset_clip_rect {
  492. 0,
  493. vertical_scrollbar().value(),
  494. m_address_bar_width - m_padding,
  495. height() - height_occupied_by_horizontal_scrollbar() //(total_rows() * line_height()) + 5
  496. };
  497. painter.fill_rect(offset_clip_rect, palette().ruler());
  498. painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right(), palette().ruler_border());
  499. auto margin_and_hex_width = static_cast<int>(offset_margin_width() + m_bytes_per_row * cell_width() + 3 * m_padding);
  500. painter.draw_line({ margin_and_hex_width, 0 },
  501. { margin_and_hex_width, vertical_scrollbar().value() + (height() - height_occupied_by_horizontal_scrollbar()) },
  502. palette().ruler_border());
  503. size_t view_height = (height() - height_occupied_by_horizontal_scrollbar());
  504. size_t min_row = max(0, vertical_scrollbar().value() / line_height()); // if below 0 then use 0
  505. size_t max_row = min(total_rows(), min_row + ceil_div(view_height, line_height())); // if above calculated rows, use calculated rows
  506. // paint offsets
  507. for (size_t i = min_row; i < max_row; i++) {
  508. Gfx::IntRect side_offset_rect {
  509. frame_thickness() + m_padding,
  510. static_cast<int>(frame_thickness() + m_padding + i * line_height()),
  511. width() - width_occupied_by_vertical_scrollbar(),
  512. height() - height_occupied_by_horizontal_scrollbar()
  513. };
  514. bool is_current_line = (m_position / bytes_per_row()) == i;
  515. auto line = DeprecatedString::formatted("{:#08X}", i * bytes_per_row());
  516. painter.draw_text(
  517. side_offset_rect,
  518. line,
  519. is_current_line ? font().bold_variant() : font(),
  520. Gfx::TextAlignment::TopLeft,
  521. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  522. }
  523. for (size_t i = min_row; i < max_row; i++) {
  524. for (size_t j = 0; j < bytes_per_row(); j++) {
  525. auto byte_position = (i * bytes_per_row()) + j;
  526. if (byte_position >= m_document->size())
  527. return;
  528. bool const edited_flag = m_document->get(byte_position).modified;
  529. bool const selection_inbetween_start_end = byte_position >= m_selection_start && byte_position < m_selection_end;
  530. bool const selection_inbetween_end_start = byte_position >= m_selection_end && byte_position < m_selection_start;
  531. bool const highlight_flag = selection_inbetween_start_end || selection_inbetween_end_start;
  532. Gfx::IntRect hex_display_rect {
  533. frame_thickness() + offset_margin_width() + j * cell_width() + 2 * m_padding,
  534. frame_thickness() + m_padding + i * line_height(),
  535. cell_width(),
  536. line_height() - m_line_spacing
  537. };
  538. Gfx::IntRect background_rect {
  539. frame_thickness() + offset_margin_width() + j * cell_width() + 1 * m_padding,
  540. frame_thickness() + m_line_spacing / 2 + i * line_height(),
  541. cell_width(),
  542. line_height()
  543. };
  544. const u8 cell_value = m_document->get(byte_position).value;
  545. auto line = DeprecatedString::formatted("{:02X}", cell_value);
  546. Gfx::Color background_color = palette().color(background_role());
  547. Gfx::Color text_color = [&]() -> Gfx::Color {
  548. if (edited_flag)
  549. return Color::Red;
  550. if (cell_value == 0x00)
  551. return palette().color(ColorRole::PlaceholderText);
  552. return palette().color(foreground_role());
  553. }();
  554. if (highlight_flag) {
  555. background_color = edited_flag ? palette().selection().inverted() : palette().selection();
  556. text_color = edited_flag ? palette().selection_text().inverted() : palette().selection_text();
  557. } else if (byte_position == m_position && m_edit_mode == EditMode::Text) {
  558. background_color = palette().inactive_selection();
  559. text_color = palette().inactive_selection_text();
  560. }
  561. painter.fill_rect(background_rect, background_color);
  562. painter.draw_text(hex_display_rect, line, Gfx::TextAlignment::TopLeft, text_color);
  563. if (m_edit_mode == EditMode::Hex) {
  564. if (byte_position == m_position && m_cursor_blink_active) {
  565. Gfx::IntRect cursor_position_rect {
  566. static_cast<int>(hex_display_rect.left() + m_cursor_at_low_nibble * character_width()),
  567. hex_display_rect.top(),
  568. 2,
  569. hex_display_rect.height()
  570. };
  571. painter.fill_rect(cursor_position_rect, palette().text_cursor());
  572. }
  573. }
  574. Gfx::IntRect text_display_rect {
  575. frame_thickness() + offset_margin_width() + bytes_per_row() * cell_width() + j * character_width() + 4 * m_padding,
  576. frame_thickness() + m_padding + i * line_height(),
  577. character_width(),
  578. line_height() - m_line_spacing
  579. };
  580. Gfx::IntRect text_background_rect {
  581. frame_thickness() + offset_margin_width() + bytes_per_row() * cell_width() + j * character_width() + 4 * m_padding,
  582. frame_thickness() + m_line_spacing / 2 + i * line_height(),
  583. character_width(),
  584. line_height()
  585. };
  586. background_color = palette().color(background_role());
  587. text_color = [&]() -> Gfx::Color {
  588. if (edited_flag)
  589. return Color::Red;
  590. if (cell_value == 0x00)
  591. return palette().color(ColorRole::PlaceholderText);
  592. return palette().color(foreground_role());
  593. }();
  594. if (highlight_flag) {
  595. background_color = edited_flag ? palette().selection().inverted() : palette().selection();
  596. text_color = edited_flag ? palette().selection_text().inverted() : palette().selection_text();
  597. } else if (byte_position == m_position && m_edit_mode == EditMode::Hex) {
  598. background_color = palette().inactive_selection();
  599. text_color = palette().inactive_selection_text();
  600. }
  601. painter.fill_rect(text_background_rect, background_color);
  602. painter.draw_text(text_display_rect, DeprecatedString::formatted("{:c}", isprint(cell_value) ? cell_value : '.'), Gfx::TextAlignment::TopLeft, text_color);
  603. if (m_edit_mode == EditMode::Text) {
  604. if (byte_position == m_position && m_cursor_blink_active) {
  605. Gfx::IntRect cursor_position_rect {
  606. text_display_rect.left(), text_display_rect.top(), 2, text_display_rect.height()
  607. };
  608. painter.fill_rect(cursor_position_rect, palette().text_cursor());
  609. }
  610. }
  611. }
  612. }
  613. }
  614. void HexEditor::select_all()
  615. {
  616. highlight(0, m_document->size());
  617. set_position(0);
  618. }
  619. void HexEditor::highlight(size_t start, size_t end)
  620. {
  621. m_selection_start = start;
  622. m_selection_end = end;
  623. set_position(start);
  624. }
  625. Optional<size_t> HexEditor::find_and_highlight(ByteBuffer& needle, size_t start)
  626. {
  627. auto end_of_match = find(needle, start);
  628. if (end_of_match.has_value()) {
  629. highlight(end_of_match.value() - needle.size(), end_of_match.value());
  630. }
  631. return end_of_match;
  632. }
  633. Optional<size_t> HexEditor::find(ByteBuffer& needle, size_t start)
  634. {
  635. if (m_document->size() == 0)
  636. return {};
  637. for (size_t i = start; i < m_document->size(); i++) {
  638. if (m_document->get(i).value == *needle.data()) {
  639. bool found = true;
  640. for (size_t j = 1; j < needle.size(); j++) {
  641. if (m_document->get(i + j).value != needle.data()[j]) {
  642. found = false;
  643. break;
  644. }
  645. }
  646. if (found) {
  647. auto end_of_match = i + needle.size();
  648. return end_of_match;
  649. }
  650. }
  651. }
  652. return {};
  653. }
  654. Vector<Match> HexEditor::find_all(ByteBuffer& needle, size_t start)
  655. {
  656. if (m_document->size() == 0 || needle.size() == 0)
  657. return {};
  658. Vector<Match> matches;
  659. size_t i = start;
  660. for (; i < m_document->size(); i++) {
  661. if (m_document->get(i).value == *needle.data()) {
  662. bool found = true;
  663. for (size_t j = 1; j < needle.size(); j++) {
  664. if (m_document->get(i + j).value != needle.data()[j]) {
  665. found = false;
  666. break;
  667. }
  668. }
  669. if (found) {
  670. matches.append({ i, DeprecatedString::formatted("{}", StringView { needle }.to_deprecated_string().characters()) });
  671. i += needle.size() - 1;
  672. }
  673. }
  674. }
  675. if (matches.is_empty())
  676. return {};
  677. auto first_match = matches.at(0);
  678. highlight(first_match.offset, first_match.offset + first_match.value.length());
  679. return matches;
  680. }
  681. Vector<Match> HexEditor::find_all_strings(size_t min_length)
  682. {
  683. if (m_document->size() == 0)
  684. return {};
  685. Vector<Match> matches;
  686. bool found_string = false;
  687. size_t offset = 0;
  688. StringBuilder builder;
  689. for (size_t i = 0; i < m_document->size(); i++) {
  690. char c = m_document->get(i).value;
  691. if (isprint(c)) {
  692. if (!found_string) {
  693. offset = i;
  694. found_string = true;
  695. }
  696. builder.append(c);
  697. } else {
  698. if (builder.length() >= min_length)
  699. matches.append({ offset, builder.to_deprecated_string() });
  700. builder.clear();
  701. found_string = false;
  702. }
  703. }
  704. if (matches.is_empty())
  705. return {};
  706. auto first_match = matches.at(0);
  707. highlight(first_match.offset, first_match.offset + first_match.value.length());
  708. return matches;
  709. }
  710. void HexEditor::reset_cursor_blink_state()
  711. {
  712. m_cursor_blink_active = true;
  713. m_blink_timer->restart();
  714. }
  715. ErrorOr<void> HexEditor::did_complete_action(size_t position, u8 old_value, u8 new_value)
  716. {
  717. if (old_value == new_value)
  718. return {};
  719. auto command = make<HexDocumentUndoCommand>(m_document->make_weak_ptr(), position);
  720. // We know this won't allocate because the buffers start empty
  721. MUST(command->try_add_changed_byte(old_value, new_value));
  722. TRY(m_undo_stack.try_push(move(command)));
  723. return {};
  724. }
  725. ErrorOr<void> HexEditor::did_complete_action(size_t position, ByteBuffer&& old_values, ByteBuffer&& new_values)
  726. {
  727. auto command = make<HexDocumentUndoCommand>(m_document->make_weak_ptr(), position);
  728. TRY(command->try_add_changed_bytes(move(old_values), move(new_values)));
  729. TRY(m_undo_stack.try_push(move(command)));
  730. return {};
  731. }
  732. bool HexEditor::undo()
  733. {
  734. if (!m_undo_stack.can_undo())
  735. return false;
  736. m_undo_stack.undo();
  737. reset_cursor_blink_state();
  738. update();
  739. update_status();
  740. did_change();
  741. return true;
  742. }
  743. bool HexEditor::redo()
  744. {
  745. if (!m_undo_stack.can_redo())
  746. return false;
  747. m_undo_stack.redo();
  748. reset_cursor_blink_state();
  749. update();
  750. update_status();
  751. did_change();
  752. return true;
  753. }
  754. GUI::UndoStack& HexEditor::undo_stack()
  755. {
  756. return m_undo_stack;
  757. }