HexEditor.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "HexEditor.h"
  27. #include <AK/StringBuilder.h>
  28. #include <Kernel/KeyCode.h>
  29. #include <LibGfx/Palette.h>
  30. #include <LibGUI/Action.h>
  31. #include <LibGUI/Clipboard.h>
  32. #include <LibGUI/FontDatabase.h>
  33. #include <LibGUI/Menu.h>
  34. #include <LibGUI/Painter.h>
  35. #include <LibGUI/ScrollBar.h>
  36. #include <LibGUI/TextEditor.h>
  37. #include <LibGUI/Window.h>
  38. #include <ctype.h>
  39. #include <fcntl.h>
  40. #include <stdio.h>
  41. #include <unistd.h>
  42. HexEditor::HexEditor()
  43. {
  44. set_scrollbars_enabled(true);
  45. set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
  46. set_background_role(ColorRole::Base);
  47. set_foreground_role(ColorRole::BaseText);
  48. vertical_scrollbar().set_step(line_height());
  49. }
  50. HexEditor::~HexEditor()
  51. {
  52. }
  53. void HexEditor::set_readonly(bool readonly)
  54. {
  55. if (m_readonly == readonly)
  56. return;
  57. m_readonly = readonly;
  58. }
  59. void HexEditor::set_buffer(const ByteBuffer& buffer)
  60. {
  61. m_buffer = buffer;
  62. set_content_length(buffer.size());
  63. m_tracked_changes.clear();
  64. m_position = 0;
  65. m_byte_position = 0;
  66. update();
  67. update_status();
  68. }
  69. void HexEditor::fill_selection(u8 fill_byte)
  70. {
  71. if (!has_selection())
  72. return;
  73. for (int i = m_selection_start; i <= m_selection_end; i++) {
  74. m_tracked_changes.set(i, m_buffer.data()[i]);
  75. m_buffer.data()[i] = fill_byte;
  76. }
  77. update();
  78. did_change();
  79. }
  80. void HexEditor::set_position(int position)
  81. {
  82. if (position > static_cast<int>(m_buffer.size()))
  83. return;
  84. m_position = position;
  85. m_byte_position = 0;
  86. scroll_position_into_view(position);
  87. update_status();
  88. }
  89. bool HexEditor::write_to_file(const StringView& path)
  90. {
  91. if (m_buffer.is_empty())
  92. return true;
  93. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  94. if (fd < 0) {
  95. perror("open");
  96. return false;
  97. }
  98. int rc = ftruncate(fd, m_buffer.size());
  99. if (rc < 0) {
  100. perror("ftruncate");
  101. return false;
  102. }
  103. ssize_t nwritten = write(fd, m_buffer.data(), m_buffer.size());
  104. if (nwritten < 0) {
  105. perror("write");
  106. close(fd);
  107. return false;
  108. }
  109. if (static_cast<size_t>(nwritten) == m_buffer.size()) {
  110. m_tracked_changes.clear();
  111. update();
  112. }
  113. close(fd);
  114. return true;
  115. }
  116. bool HexEditor::copy_selected_hex_to_clipboard()
  117. {
  118. if (!has_selection())
  119. return false;
  120. StringBuilder output_string_builder;
  121. for (int i = m_selection_start; i <= m_selection_end; i++) {
  122. output_string_builder.appendf("%02X ", m_buffer.data()[i]);
  123. }
  124. GUI::Clipboard::the().set_data(output_string_builder.to_string());
  125. return true;
  126. }
  127. bool HexEditor::copy_selected_text_to_clipboard()
  128. {
  129. if (!has_selection())
  130. return false;
  131. StringBuilder output_string_builder;
  132. for (int i = m_selection_start; i <= m_selection_end; i++) {
  133. output_string_builder.appendf("%c", isprint(m_buffer.data()[i]) ? m_buffer[i] : '.');
  134. }
  135. GUI::Clipboard::the().set_data(output_string_builder.to_string());
  136. return true;
  137. }
  138. bool HexEditor::copy_selected_hex_to_clipboard_as_c_code()
  139. {
  140. if (!has_selection())
  141. return false;
  142. StringBuilder output_string_builder;
  143. output_string_builder.appendf("unsigned char raw_data[%d] = {\n", (m_selection_end - m_selection_start) + 1);
  144. output_string_builder.append(" ");
  145. for (int i = m_selection_start, j = 1; i <= m_selection_end; i++, j++) {
  146. output_string_builder.appendf("0x%02X", m_buffer.data()[i]);
  147. if (i != m_selection_end)
  148. output_string_builder.append(", ");
  149. if ((j % 12) == 0) {
  150. output_string_builder.append("\n");
  151. output_string_builder.append(" ");
  152. }
  153. }
  154. output_string_builder.append("\n};\n");
  155. GUI::Clipboard::the().set_data(output_string_builder.to_string());
  156. return true;
  157. }
  158. void HexEditor::set_bytes_per_row(int bytes_per_row)
  159. {
  160. m_bytes_per_row = bytes_per_row;
  161. set_content_size({ offset_margin_width() + (m_bytes_per_row * (character_width() * 3)) + 10 + (m_bytes_per_row * character_width()) + 20, total_rows() * line_height() + 10 });
  162. update();
  163. }
  164. void HexEditor::set_content_length(int length)
  165. {
  166. if (length == m_content_length)
  167. return;
  168. m_content_length = length;
  169. set_content_size({ offset_margin_width() + (m_bytes_per_row * (character_width() * 3)) + 10 + (m_bytes_per_row * character_width()) + 20, total_rows() * line_height() + 10 });
  170. }
  171. void HexEditor::mousedown_event(GUI::MouseEvent& event)
  172. {
  173. if (event.button() != GUI::MouseButton::Left) {
  174. return;
  175. }
  176. auto absolute_x = horizontal_scrollbar().value() + event.x();
  177. auto absolute_y = vertical_scrollbar().value() + event.y();
  178. auto hex_start_x = frame_thickness() + 90;
  179. auto hex_start_y = frame_thickness() + 5;
  180. auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
  181. auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
  182. auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
  183. auto text_start_y = frame_thickness() + 5;
  184. auto text_end_x = text_start_x + (bytes_per_row() * character_width());
  185. auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
  186. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  187. auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
  188. auto byte_y = (absolute_y - hex_start_y) / line_height();
  189. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  190. if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
  191. return;
  192. #ifdef HEX_DEBUG
  193. printf("HexEditor::mousedown_event(hex): offset=%d\n", offset);
  194. #endif
  195. m_edit_mode = EditMode::Hex;
  196. m_byte_position = 0;
  197. m_position = offset;
  198. m_in_drag_select = true;
  199. m_selection_start = offset;
  200. m_selection_end = -1;
  201. update();
  202. update_status();
  203. }
  204. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  205. auto byte_x = (absolute_x - text_start_x) / character_width();
  206. auto byte_y = (absolute_y - text_start_y) / line_height();
  207. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  208. if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
  209. return;
  210. #ifdef HEX_DEBUG
  211. printf("HexEditor::mousedown_event(text): offset=%d\n", offset);
  212. #endif
  213. m_position = offset;
  214. m_byte_position = 0;
  215. m_in_drag_select = true;
  216. m_selection_start = offset;
  217. m_selection_end = -1;
  218. m_edit_mode = EditMode::Text;
  219. update();
  220. update_status();
  221. }
  222. }
  223. void HexEditor::mousemove_event(GUI::MouseEvent& event)
  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() + 90;
  228. auto hex_start_y = frame_thickness() + 5;
  229. auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
  230. auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
  231. auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
  232. auto text_start_y = frame_thickness() + 5;
  233. auto text_end_x = text_start_x + (bytes_per_row() * character_width());
  234. auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
  235. window()->set_override_cursor(GUI::StandardCursor::None);
  236. if ((absolute_x >= hex_start_x && absolute_x <= hex_end_x
  237. && absolute_y >= hex_start_y && absolute_y <= hex_end_y)
  238. || (absolute_x >= text_start_x && absolute_x <= text_end_x
  239. && absolute_y >= text_start_y && absolute_y <= text_end_y)) {
  240. window()->set_override_cursor(GUI::StandardCursor::IBeam);
  241. }
  242. if (m_in_drag_select) {
  243. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  244. auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
  245. auto byte_y = (absolute_y - hex_start_y) / line_height();
  246. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  247. if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
  248. return;
  249. m_selection_end = offset;
  250. scroll_position_into_view(offset);
  251. }
  252. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  253. auto byte_x = (absolute_x - text_start_x) / character_width();
  254. auto byte_y = (absolute_y - text_start_y) / line_height();
  255. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  256. if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
  257. return;
  258. m_selection_end = offset;
  259. scroll_position_into_view(offset);
  260. }
  261. update_status();
  262. update();
  263. return;
  264. }
  265. }
  266. void HexEditor::mouseup_event(GUI::MouseEvent& event)
  267. {
  268. if (event.button() == GUI::MouseButton::Left) {
  269. if (m_in_drag_select) {
  270. if (m_selection_end == -1 || m_selection_start == -1) {
  271. m_selection_start = -1;
  272. m_selection_end = -1;
  273. } else if (m_selection_end < m_selection_start) {
  274. // lets flip these around
  275. auto start = m_selection_end;
  276. m_selection_end = m_selection_start;
  277. m_selection_start = start;
  278. }
  279. m_in_drag_select = false;
  280. }
  281. update();
  282. update_status();
  283. }
  284. }
  285. void HexEditor::scroll_position_into_view(int position)
  286. {
  287. int y = position / bytes_per_row();
  288. int x = position % bytes_per_row();
  289. Gfx::Rect rect {
  290. frame_thickness() + offset_margin_width() + (x * (character_width() * 3)) + 10,
  291. frame_thickness() + 5 + (y * line_height()),
  292. (character_width() * 3),
  293. line_height() - m_line_spacing
  294. };
  295. scroll_into_view(rect, true, true);
  296. }
  297. void HexEditor::keydown_event(GUI::KeyEvent& event)
  298. {
  299. #ifdef HEX_DEBUG
  300. printf("HexEditor::keydown_event key=%d\n", event.key());
  301. #endif
  302. if (event.key() == KeyCode::Key_Up) {
  303. if (m_position - bytes_per_row() >= 0) {
  304. m_position -= bytes_per_row();
  305. m_byte_position = 0;
  306. scroll_position_into_view(m_position);
  307. update();
  308. update_status();
  309. }
  310. return;
  311. }
  312. if (event.key() == KeyCode::Key_Down) {
  313. if (m_position + bytes_per_row() < static_cast<int>(m_buffer.size())) {
  314. m_position += bytes_per_row();
  315. m_byte_position = 0;
  316. scroll_position_into_view(m_position);
  317. update();
  318. update_status();
  319. }
  320. return;
  321. }
  322. if (event.key() == KeyCode::Key_Left) {
  323. if (m_position - 1 >= 0) {
  324. m_position--;
  325. m_byte_position = 0;
  326. scroll_position_into_view(m_position);
  327. update();
  328. update_status();
  329. }
  330. return;
  331. }
  332. if (event.key() == KeyCode::Key_Right) {
  333. if (m_position + 1 < static_cast<int>(m_buffer.size())) {
  334. m_position++;
  335. m_byte_position = 0;
  336. scroll_position_into_view(m_position);
  337. update();
  338. update_status();
  339. }
  340. return;
  341. }
  342. if (event.key() == KeyCode::Key_Backspace) {
  343. if (m_position > 0) {
  344. m_position--;
  345. m_byte_position = 0;
  346. scroll_position_into_view(m_position);
  347. update();
  348. update_status();
  349. }
  350. return;
  351. }
  352. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
  353. if (m_edit_mode == EditMode::Hex) {
  354. hex_mode_keydown_event(event);
  355. } else {
  356. text_mode_keydown_event(event);
  357. }
  358. }
  359. }
  360. void HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event)
  361. {
  362. if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
  363. if (m_buffer.is_empty())
  364. return;
  365. ASSERT(m_position >= 0);
  366. ASSERT(m_position < static_cast<int>(m_buffer.size()));
  367. // yes, this is terrible... but it works.
  368. auto value = (event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9)
  369. ? event.key() - KeyCode::Key_0
  370. : (event.key() - KeyCode::Key_A) + 0xA;
  371. if (m_byte_position == 0) {
  372. m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
  373. m_buffer.data()[m_position] = value << 4 | (m_buffer.data()[m_position] & 0xF); // shift new value left 4 bits, OR with existing last 4 bits
  374. m_byte_position++;
  375. } else {
  376. m_buffer.data()[m_position] = (m_buffer.data()[m_position] & 0xF0) | value; // save the first 4 bits, OR the new value in the last 4
  377. if (m_position + 1 < static_cast<int>(m_buffer.size()))
  378. m_position++;
  379. m_byte_position = 0;
  380. }
  381. update();
  382. update_status();
  383. did_change();
  384. }
  385. }
  386. void HexEditor::text_mode_keydown_event(GUI::KeyEvent& event)
  387. {
  388. if (m_buffer.is_empty())
  389. return;
  390. ASSERT(m_position >= 0);
  391. ASSERT(m_position < static_cast<int>(m_buffer.size()));
  392. m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
  393. m_buffer.data()[m_position] = (u8)event.text().characters()[0]; // save the first 4 bits, OR the new value in the last 4
  394. if (m_position + 1 < static_cast<int>(m_buffer.size()))
  395. m_position++;
  396. m_byte_position = 0;
  397. update();
  398. update_status();
  399. did_change();
  400. }
  401. void HexEditor::update_status()
  402. {
  403. if (on_status_change)
  404. on_status_change(m_position, m_edit_mode, m_selection_start, m_selection_end);
  405. }
  406. void HexEditor::did_change()
  407. {
  408. if (on_change)
  409. on_change();
  410. }
  411. void HexEditor::paint_event(GUI::PaintEvent& event)
  412. {
  413. GUI::Frame::paint_event(event);
  414. GUI::Painter painter(*this);
  415. painter.add_clip_rect(widget_inner_rect());
  416. painter.add_clip_rect(event.rect());
  417. painter.fill_rect(event.rect(), palette().color(background_role()));
  418. if (m_buffer.is_empty())
  419. return;
  420. painter.translate(frame_thickness(), frame_thickness());
  421. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  422. Gfx::Rect offset_clip_rect {
  423. 0,
  424. vertical_scrollbar().value(),
  425. 85,
  426. height() - height_occupied_by_horizontal_scrollbar() //(total_rows() * line_height()) + 5
  427. };
  428. painter.fill_rect(offset_clip_rect, palette().ruler());
  429. painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right(), palette().ruler_border());
  430. auto margin_and_hex_width = offset_margin_width() + (m_bytes_per_row * (character_width() * 3)) + 15;
  431. painter.draw_line({ margin_and_hex_width, 0 },
  432. { margin_and_hex_width, vertical_scrollbar().value() + (height() - height_occupied_by_horizontal_scrollbar()) },
  433. palette().ruler_border());
  434. auto view_height = (height() - height_occupied_by_horizontal_scrollbar());
  435. auto min_row = max(0, vertical_scrollbar().value() / line_height()); // if below 0 then use 0
  436. auto max_row = min(total_rows(), min_row + ceil_div(view_height, line_height())); // if above calculated rows, use calculated rows
  437. // paint offsets
  438. for (int i = min_row; i < max_row; i++) {
  439. Gfx::Rect side_offset_rect {
  440. frame_thickness() + 5,
  441. frame_thickness() + 5 + (i * line_height()),
  442. width() - width_occupied_by_vertical_scrollbar(),
  443. height() - height_occupied_by_horizontal_scrollbar()
  444. };
  445. bool is_current_line = (m_position / bytes_per_row()) == i;
  446. auto line = String::format("0x%08X", i * bytes_per_row());
  447. painter.draw_text(
  448. side_offset_rect,
  449. line,
  450. is_current_line ? Gfx::Font::default_bold_font() : font(),
  451. Gfx::TextAlignment::TopLeft,
  452. is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
  453. }
  454. for (int i = min_row; i < max_row; i++) {
  455. for (int j = 0; j < bytes_per_row(); j++) {
  456. auto byte_position = (i * bytes_per_row()) + j;
  457. if (byte_position >= static_cast<int>(m_buffer.size()))
  458. return;
  459. Color text_color = palette().color(foreground_role());
  460. if (m_tracked_changes.contains(byte_position)) {
  461. text_color = Color::Red;
  462. }
  463. auto highlight_flag = false;
  464. if (m_selection_start > -1 && m_selection_end > -1) {
  465. if (byte_position >= m_selection_start && byte_position <= m_selection_end) {
  466. highlight_flag = true;
  467. }
  468. if (byte_position >= m_selection_end && byte_position <= m_selection_start) {
  469. highlight_flag = true;
  470. }
  471. }
  472. Gfx::Rect hex_display_rect {
  473. frame_thickness() + offset_margin_width() + (j * (character_width() * 3)) + 10,
  474. frame_thickness() + 5 + (i * line_height()),
  475. (character_width() * 3),
  476. line_height() - m_line_spacing
  477. };
  478. if (highlight_flag) {
  479. painter.fill_rect(hex_display_rect, palette().selection());
  480. text_color = text_color == Color::Red ? Color::from_rgb(0xFFC0CB) : palette().selection_text();
  481. } else if (byte_position == m_position) {
  482. painter.fill_rect(hex_display_rect, palette().inactive_selection());
  483. text_color = palette().inactive_selection_text();
  484. }
  485. auto line = String::format("%02X", m_buffer[byte_position]);
  486. painter.draw_text(hex_display_rect, line, Gfx::TextAlignment::TopLeft, text_color);
  487. Gfx::Rect text_display_rect {
  488. frame_thickness() + offset_margin_width() + (bytes_per_row() * (character_width() * 3)) + (j * character_width()) + 20,
  489. frame_thickness() + 5 + (i * line_height()),
  490. character_width(),
  491. line_height() - m_line_spacing
  492. };
  493. // selection highlighting.
  494. if (highlight_flag) {
  495. painter.fill_rect(text_display_rect, palette().selection());
  496. } else if (byte_position == m_position) {
  497. painter.fill_rect(text_display_rect, palette().inactive_selection());
  498. }
  499. painter.draw_text(text_display_rect, String::format("%c", isprint(m_buffer[byte_position]) ? m_buffer[byte_position] : '.'), Gfx::TextAlignment::TopLeft, text_color);
  500. }
  501. }
  502. }
  503. void HexEditor::leave_event(Core::Event&)
  504. {
  505. ASSERT(window());
  506. window()->set_override_cursor(GUI::StandardCursor::None);
  507. }