HexEditor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 <LibDraw/Palette.h>
  30. #include <LibGUI/GAction.h>
  31. #include <LibGUI/GClipboard.h>
  32. #include <LibGUI/GFontDatabase.h>
  33. #include <LibGUI/GMenu.h>
  34. #include <LibGUI/GPainter.h>
  35. #include <LibGUI/GScrollBar.h>
  36. #include <LibGUI/GTextEditor.h>
  37. #include <LibGUI/GWindow.h>
  38. #include <ctype.h>
  39. #include <fcntl.h>
  40. #include <stdio.h>
  41. #include <unistd.h>
  42. HexEditor::HexEditor(GWidget* parent)
  43. : GScrollableWidget(parent)
  44. {
  45. set_frame_shape(FrameShape::Container);
  46. set_frame_shadow(FrameShadow::Sunken);
  47. set_frame_thickness(2);
  48. set_scrollbars_enabled(true);
  49. set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
  50. vertical_scrollbar().set_step(line_height());
  51. }
  52. HexEditor::~HexEditor()
  53. {
  54. }
  55. void HexEditor::set_readonly(bool readonly)
  56. {
  57. if (m_readonly == readonly)
  58. return;
  59. m_readonly = readonly;
  60. }
  61. void HexEditor::set_buffer(const ByteBuffer& buffer)
  62. {
  63. m_buffer = buffer;
  64. set_content_length(buffer.size());
  65. update();
  66. update_status();
  67. }
  68. void HexEditor::fill_selection(u8 fill_byte)
  69. {
  70. if (!has_selection())
  71. return;
  72. for (int i = m_selection_start; i <= m_selection_end; i++) {
  73. m_tracked_changes.set(i, m_buffer.data()[i]);
  74. m_buffer.data()[i] = fill_byte;
  75. }
  76. update();
  77. did_change();
  78. }
  79. void HexEditor::set_position(int position)
  80. {
  81. if (position > m_buffer.size())
  82. return;
  83. m_position = position;
  84. m_byte_position = 0;
  85. scroll_position_into_view(position);
  86. update_status();
  87. }
  88. bool HexEditor::write_to_file(const StringView& path)
  89. {
  90. if (m_buffer.is_empty())
  91. return true;
  92. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  93. if (fd < 0) {
  94. perror("open");
  95. return false;
  96. }
  97. int rc = ftruncate(fd, m_buffer.size());
  98. if (rc < 0) {
  99. perror("ftruncate");
  100. return false;
  101. }
  102. ssize_t nwritten = write(fd, m_buffer.data(), m_buffer.size());
  103. if (nwritten < 0) {
  104. perror("write");
  105. close(fd);
  106. return false;
  107. }
  108. if (nwritten == m_buffer.size()) {
  109. m_tracked_changes.clear();
  110. update();
  111. }
  112. close(fd);
  113. return true;
  114. }
  115. bool HexEditor::copy_selected_hex_to_clipboard()
  116. {
  117. if (!has_selection())
  118. return false;
  119. StringBuilder output_string_builder;
  120. for (int i = m_selection_start; i <= m_selection_end; i++) {
  121. output_string_builder.appendf("%02X ", m_buffer.data()[i]);
  122. }
  123. GClipboard::the().set_data(output_string_builder.to_string());
  124. return true;
  125. }
  126. bool HexEditor::copy_selected_text_to_clipboard()
  127. {
  128. if (!has_selection())
  129. return false;
  130. StringBuilder output_string_builder;
  131. for (int i = m_selection_start; i <= m_selection_end; i++) {
  132. output_string_builder.appendf("%c", isprint(m_buffer.data()[i]) ? m_buffer[i] : '.');
  133. }
  134. GClipboard::the().set_data(output_string_builder.to_string());
  135. return true;
  136. }
  137. bool HexEditor::copy_selected_hex_to_clipboard_as_c_code()
  138. {
  139. if (!has_selection())
  140. return false;
  141. StringBuilder output_string_builder;
  142. output_string_builder.appendf("unsigned char raw_data[%d] = {\n", (m_selection_end - m_selection_start) + 1);
  143. output_string_builder.append(" ");
  144. for (int i = m_selection_start, j = 1; i <= m_selection_end; i++, j++) {
  145. output_string_builder.appendf("0x%02X", m_buffer.data()[i]);
  146. if (i != m_selection_end)
  147. output_string_builder.append(", ");
  148. if ((j % 12) == 0) {
  149. output_string_builder.append("\n");
  150. output_string_builder.append(" ");
  151. }
  152. }
  153. output_string_builder.append("\n};\n");
  154. GClipboard::the().set_data(output_string_builder.to_string());
  155. return true;
  156. }
  157. void HexEditor::set_bytes_per_row(int bytes_per_row)
  158. {
  159. m_bytes_per_row = bytes_per_row;
  160. 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 });
  161. update();
  162. }
  163. void HexEditor::set_content_length(int length)
  164. {
  165. if (length == m_content_length)
  166. return;
  167. m_content_length = length;
  168. 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 });
  169. }
  170. void HexEditor::mousedown_event(GMouseEvent& event)
  171. {
  172. if (event.button() != GMouseButton::Left) {
  173. return;
  174. }
  175. auto absolute_x = horizontal_scrollbar().value() + event.x();
  176. auto absolute_y = vertical_scrollbar().value() + event.y();
  177. auto hex_start_x = frame_thickness() + 90;
  178. auto hex_start_y = frame_thickness() + 5;
  179. auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
  180. auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
  181. auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
  182. auto text_start_y = frame_thickness() + 5;
  183. auto text_end_x = text_start_x + (bytes_per_row() * character_width());
  184. auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
  185. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  186. auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
  187. auto byte_y = (absolute_y - hex_start_y) / line_height();
  188. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  189. if (offset < 0 || offset > m_buffer.size())
  190. return;
  191. #ifdef HEX_DEBUG
  192. printf("HexEditor::mousedown_event(hex): offset=%d\n", offset);
  193. #endif
  194. m_edit_mode = EditMode::Hex;
  195. m_byte_position = 0;
  196. m_position = offset;
  197. m_in_drag_select = true;
  198. m_selection_start = offset;
  199. m_selection_end = -1;
  200. update();
  201. update_status();
  202. }
  203. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  204. auto byte_x = (absolute_x - text_start_x) / character_width();
  205. auto byte_y = (absolute_y - text_start_y) / line_height();
  206. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  207. if (offset < 0 || offset > m_buffer.size())
  208. return;
  209. #ifdef HEX_DEBUG
  210. printf("HexEditor::mousedown_event(text): offset=%d\n", offset);
  211. #endif
  212. m_position = offset;
  213. m_byte_position = 0;
  214. m_in_drag_select = true;
  215. m_selection_start = offset;
  216. m_selection_end = -1;
  217. m_edit_mode = EditMode::Text;
  218. update();
  219. update_status();
  220. }
  221. }
  222. void HexEditor::mousemove_event(GMouseEvent& event)
  223. {
  224. auto absolute_x = horizontal_scrollbar().value() + event.x();
  225. auto absolute_y = vertical_scrollbar().value() + event.y();
  226. auto hex_start_x = frame_thickness() + 90;
  227. auto hex_start_y = frame_thickness() + 5;
  228. auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
  229. auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
  230. auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
  231. auto text_start_y = frame_thickness() + 5;
  232. auto text_end_x = text_start_x + (bytes_per_row() * character_width());
  233. auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
  234. window()->set_override_cursor(GStandardCursor::None);
  235. if ((absolute_x >= hex_start_x && absolute_x <= hex_end_x
  236. && absolute_y >= hex_start_y && absolute_y <= hex_end_y)
  237. || (absolute_x >= text_start_x && absolute_x <= text_end_x
  238. && absolute_y >= text_start_y && absolute_y <= text_end_y)) {
  239. window()->set_override_cursor(GStandardCursor::IBeam);
  240. }
  241. if (m_in_drag_select) {
  242. if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
  243. auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
  244. auto byte_y = (absolute_y - hex_start_y) / line_height();
  245. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  246. if (offset < 0 || offset > m_buffer.size())
  247. return;
  248. m_selection_end = offset;
  249. scroll_position_into_view(offset);
  250. }
  251. if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
  252. auto byte_x = (absolute_x - text_start_x) / character_width();
  253. auto byte_y = (absolute_y - text_start_y) / line_height();
  254. auto offset = (byte_y * m_bytes_per_row) + byte_x;
  255. if (offset < 0 || offset > m_buffer.size())
  256. return;
  257. m_selection_end = offset;
  258. scroll_position_into_view(offset);
  259. }
  260. update_status();
  261. update();
  262. return;
  263. }
  264. }
  265. void HexEditor::mouseup_event(GMouseEvent& event)
  266. {
  267. if (event.button() == GMouseButton::Left) {
  268. if (m_in_drag_select) {
  269. if (m_selection_end == -1 || m_selection_start == -1) {
  270. m_selection_start = -1;
  271. m_selection_end = -1;
  272. } else if (m_selection_end < m_selection_start) {
  273. // lets flip these around
  274. auto start = m_selection_end;
  275. m_selection_end = m_selection_start;
  276. m_selection_start = start;
  277. }
  278. m_in_drag_select = false;
  279. }
  280. update();
  281. update_status();
  282. }
  283. }
  284. void HexEditor::scroll_position_into_view(int position)
  285. {
  286. int y = position / bytes_per_row();
  287. int x = position % bytes_per_row();
  288. Rect rect {
  289. frame_thickness() + offset_margin_width() + (x * (character_width() * 3)) + 10,
  290. frame_thickness() + 5 + (y * line_height()),
  291. (character_width() * 3),
  292. line_height() - m_line_spacing
  293. };
  294. scroll_into_view(rect, true, true);
  295. }
  296. void HexEditor::keydown_event(GKeyEvent& event)
  297. {
  298. #ifdef HEX_DEBUG
  299. printf("HexEditor::keydown_event key=%d\n", event.key());
  300. #endif
  301. if (event.key() == KeyCode::Key_Up) {
  302. if (m_position - bytes_per_row() >= 0) {
  303. m_position -= bytes_per_row();
  304. m_byte_position = 0;
  305. scroll_position_into_view(m_position);
  306. update();
  307. update_status();
  308. }
  309. return;
  310. }
  311. if (event.key() == KeyCode::Key_Down) {
  312. if (m_position + bytes_per_row() < m_buffer.size()) {
  313. m_position += bytes_per_row();
  314. m_byte_position = 0;
  315. scroll_position_into_view(m_position);
  316. update();
  317. update_status();
  318. }
  319. return;
  320. }
  321. if (event.key() == KeyCode::Key_Left) {
  322. if (m_position - 1 >= 0) {
  323. m_position--;
  324. m_byte_position = 0;
  325. scroll_position_into_view(m_position);
  326. update();
  327. update_status();
  328. }
  329. return;
  330. }
  331. if (event.key() == KeyCode::Key_Right) {
  332. if (m_position + 1 < m_buffer.size()) {
  333. m_position++;
  334. m_byte_position = 0;
  335. scroll_position_into_view(m_position);
  336. update();
  337. update_status();
  338. }
  339. return;
  340. }
  341. if (event.key() == KeyCode::Key_Backspace) {
  342. if (m_position > 0) {
  343. m_position--;
  344. m_byte_position = 0;
  345. scroll_position_into_view(m_position);
  346. update();
  347. update_status();
  348. }
  349. return;
  350. }
  351. if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
  352. if (m_edit_mode == EditMode::Hex) {
  353. hex_mode_keydown_event(event);
  354. } else {
  355. text_mode_keydown_event(event);
  356. }
  357. }
  358. }
  359. void HexEditor::hex_mode_keydown_event(GKeyEvent& event)
  360. {
  361. if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
  362. // yes, this is terrible... but it works.
  363. auto value = (event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9)
  364. ? event.key() - KeyCode::Key_0
  365. : (event.key() - KeyCode::Key_A) + 0xA;
  366. if (m_byte_position == 0) {
  367. m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
  368. 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
  369. m_byte_position++;
  370. } else {
  371. 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
  372. m_position++;
  373. m_byte_position = 0;
  374. }
  375. update();
  376. update_status();
  377. did_change();
  378. }
  379. }
  380. void HexEditor::text_mode_keydown_event(GKeyEvent& event)
  381. {
  382. m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
  383. m_buffer.data()[m_position] = (u8)event.text().characters()[0]; // save the first 4 bits, OR the new value in the last 4
  384. m_position++;
  385. m_byte_position = 0;
  386. update();
  387. update_status();
  388. did_change();
  389. }
  390. void HexEditor::update_status()
  391. {
  392. if (on_status_change)
  393. on_status_change(m_position, m_edit_mode, m_selection_start, m_selection_end);
  394. }
  395. void HexEditor::did_change()
  396. {
  397. if (on_change)
  398. on_change();
  399. }
  400. void HexEditor::paint_event(GPaintEvent& event)
  401. {
  402. GFrame::paint_event(event);
  403. GPainter painter(*this);
  404. painter.add_clip_rect(widget_inner_rect());
  405. painter.add_clip_rect(event.rect());
  406. painter.fill_rect(event.rect(), Color::White);
  407. if (m_buffer.is_empty())
  408. return;
  409. painter.translate(frame_thickness(), frame_thickness());
  410. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  411. Rect offset_clip_rect {
  412. 0,
  413. vertical_scrollbar().value(),
  414. 85,
  415. height() - height_occupied_by_horizontal_scrollbar() //(total_rows() * line_height()) + 5
  416. };
  417. painter.fill_rect(offset_clip_rect, Color::WarmGray);
  418. painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right(), Color::DarkGray);
  419. auto margin_and_hex_width = offset_margin_width() + (m_bytes_per_row * (character_width() * 3)) + 15;
  420. painter.draw_line({ margin_and_hex_width, 0 },
  421. { margin_and_hex_width, vertical_scrollbar().value() + (height() - height_occupied_by_horizontal_scrollbar()) },
  422. Color::LightGray);
  423. auto view_height = (height() - height_occupied_by_horizontal_scrollbar());
  424. auto min_row = max(0, vertical_scrollbar().value() / line_height()); // if below 0 then use 0
  425. auto max_row = min(total_rows(), min_row + ceil_div(view_height, line_height())); // if above calculated rows, use calculated rows
  426. // paint offsets
  427. for (int i = min_row; i < max_row; i++) {
  428. Rect side_offset_rect {
  429. frame_thickness() + 5,
  430. frame_thickness() + 5 + (i * line_height()),
  431. width() - width_occupied_by_vertical_scrollbar(),
  432. height() - height_occupied_by_horizontal_scrollbar()
  433. };
  434. auto line = String::format("0x%08X", i * bytes_per_row());
  435. painter.draw_text(side_offset_rect, line);
  436. }
  437. for (int i = min_row; i < max_row; i++) {
  438. for (int j = 0; j < bytes_per_row(); j++) {
  439. auto byte_position = (i * bytes_per_row()) + j;
  440. if (byte_position >= m_buffer.size())
  441. return;
  442. Color text_color = Color::Black;
  443. if (m_tracked_changes.contains(byte_position)) {
  444. text_color = Color::Red;
  445. }
  446. Color highlight_color = palette().selection();
  447. auto highlight_flag = false;
  448. if (m_selection_start > -1 && m_selection_end > -1) {
  449. if (byte_position >= m_selection_start && byte_position <= m_selection_end) {
  450. highlight_flag = true;
  451. }
  452. if (byte_position >= m_selection_end && byte_position <= m_selection_start) {
  453. highlight_flag = true;
  454. }
  455. }
  456. Rect hex_display_rect {
  457. frame_thickness() + offset_margin_width() + (j * (character_width() * 3)) + 10,
  458. frame_thickness() + 5 + (i * line_height()),
  459. (character_width() * 3),
  460. line_height() - m_line_spacing
  461. };
  462. if (highlight_flag) {
  463. painter.fill_rect(hex_display_rect, highlight_color);
  464. text_color = text_color == Color::Red ? Color::from_rgb(0xFFC0CB) : Color::White;
  465. } else if (byte_position == m_position) {
  466. painter.fill_rect(hex_display_rect, Color::from_rgb(0xCCCCCC));
  467. }
  468. auto line = String::format("%02X", m_buffer[byte_position]);
  469. painter.draw_text(hex_display_rect, line, TextAlignment::TopLeft, text_color);
  470. Rect text_display_rect {
  471. frame_thickness() + offset_margin_width() + (bytes_per_row() * (character_width() * 3)) + (j * character_width()) + 20,
  472. frame_thickness() + 5 + (i * line_height()),
  473. character_width(),
  474. line_height() - m_line_spacing
  475. };
  476. // selection highlighting.
  477. if (highlight_flag) {
  478. painter.fill_rect(text_display_rect, highlight_color);
  479. } else if (byte_position == m_position) {
  480. painter.fill_rect(text_display_rect, Color::from_rgb(0xCCCCCC));
  481. }
  482. painter.draw_text(text_display_rect, String::format("%c", isprint(m_buffer[byte_position]) ? m_buffer[byte_position] : '.'), TextAlignment::TopLeft, text_color);
  483. }
  484. }
  485. }
  486. void HexEditor::leave_event(Core::Event&)
  487. {
  488. ASSERT(window());
  489. window()->set_override_cursor(GStandardCursor::None);
  490. }