Serenity Operating System
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
27#include "HexEditor.h"
28#include <AK/StringBuilder.h>
29#include <Kernel/KeyCode.h>
30#include <LibGfx/Palette.h>
31#include <LibGUI/Action.h>
32#include <LibGUI/Clipboard.h>
33#include <LibGUI/FontDatabase.h>
34#include <LibGUI/Menu.h>
35#include <LibGUI/Painter.h>
36#include <LibGUI/ScrollBar.h>
37#include <LibGUI/TextEditor.h>
38#include <LibGUI/Window.h>
39#include <ctype.h>
40#include <fcntl.h>
41#include <stdio.h>
42#include <unistd.h>
43
44HexEditor::HexEditor()
45{
46 set_scrollbars_enabled(true);
47 set_font(GUI::FontDatabase::the().get_by_name("Csilla Thin"));
48 set_background_role(ColorRole::Base);
49 set_foreground_role(ColorRole::BaseText);
50 vertical_scrollbar().set_step(line_height());
51}
52
53HexEditor::~HexEditor()
54{
55}
56
57void HexEditor::set_readonly(bool readonly)
58{
59 if (m_readonly == readonly)
60 return;
61 m_readonly = readonly;
62}
63
64void HexEditor::set_buffer(const ByteBuffer& buffer)
65{
66 m_buffer = buffer;
67 set_content_length(buffer.size());
68 m_tracked_changes.clear();
69 m_position = 0;
70 m_byte_position = 0;
71 update();
72 update_status();
73}
74
75void HexEditor::fill_selection(u8 fill_byte)
76{
77 if (!has_selection())
78 return;
79
80 for (int i = m_selection_start; i <= m_selection_end; i++) {
81 m_tracked_changes.set(i, m_buffer.data()[i]);
82 m_buffer.data()[i] = fill_byte;
83 }
84
85 update();
86 did_change();
87}
88
89void HexEditor::set_position(int position)
90{
91 if (position > static_cast<int>(m_buffer.size()))
92 return;
93
94 m_position = position;
95 m_byte_position = 0;
96 scroll_position_into_view(position);
97 update_status();
98}
99
100bool HexEditor::write_to_file(const StringView& path)
101{
102 if (m_buffer.is_empty())
103 return true;
104
105 int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
106 if (fd < 0) {
107 perror("open");
108 return false;
109 }
110
111 int rc = ftruncate(fd, m_buffer.size());
112 if (rc < 0) {
113 perror("ftruncate");
114 return false;
115 }
116
117 ssize_t nwritten = write(fd, m_buffer.data(), m_buffer.size());
118 if (nwritten < 0) {
119 perror("write");
120 close(fd);
121 return false;
122 }
123
124 if (static_cast<size_t>(nwritten) == m_buffer.size()) {
125 m_tracked_changes.clear();
126 update();
127 }
128
129 close(fd);
130 return true;
131}
132
133bool HexEditor::copy_selected_hex_to_clipboard()
134{
135 if (!has_selection())
136 return false;
137
138 StringBuilder output_string_builder;
139 for (int i = m_selection_start; i <= m_selection_end; i++) {
140 output_string_builder.appendf("%02X ", m_buffer.data()[i]);
141 }
142
143 GUI::Clipboard::the().set_data(output_string_builder.to_string());
144 return true;
145}
146
147bool HexEditor::copy_selected_text_to_clipboard()
148{
149 if (!has_selection())
150 return false;
151
152 StringBuilder output_string_builder;
153 for (int i = m_selection_start; i <= m_selection_end; i++) {
154 output_string_builder.appendf("%c", isprint(m_buffer.data()[i]) ? m_buffer[i] : '.');
155 }
156
157 GUI::Clipboard::the().set_data(output_string_builder.to_string());
158 return true;
159}
160
161bool HexEditor::copy_selected_hex_to_clipboard_as_c_code()
162{
163 if (!has_selection())
164 return false;
165
166 StringBuilder output_string_builder;
167 output_string_builder.appendf("unsigned char raw_data[%d] = {\n", (m_selection_end - m_selection_start) + 1);
168 output_string_builder.append(" ");
169 for (int i = m_selection_start, j = 1; i <= m_selection_end; i++, j++) {
170 output_string_builder.appendf("0x%02X", m_buffer.data()[i]);
171 if (i != m_selection_end)
172 output_string_builder.append(", ");
173 if ((j % 12) == 0) {
174 output_string_builder.append("\n");
175 output_string_builder.append(" ");
176 }
177 }
178 output_string_builder.append("\n};\n");
179
180 GUI::Clipboard::the().set_data(output_string_builder.to_string());
181 return true;
182}
183
184void HexEditor::set_bytes_per_row(int bytes_per_row)
185{
186 m_bytes_per_row = bytes_per_row;
187 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 });
188 update();
189}
190
191void HexEditor::set_content_length(int length)
192{
193 if (length == m_content_length)
194 return;
195 m_content_length = length;
196 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 });
197}
198
199void HexEditor::mousedown_event(GUI::MouseEvent& event)
200{
201 if (event.button() != GUI::MouseButton::Left) {
202 return;
203 }
204
205 auto absolute_x = horizontal_scrollbar().value() + event.x();
206 auto absolute_y = vertical_scrollbar().value() + event.y();
207
208 auto hex_start_x = frame_thickness() + 90;
209 auto hex_start_y = frame_thickness() + 5;
210 auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
211 auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
212
213 auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
214 auto text_start_y = frame_thickness() + 5;
215 auto text_end_x = text_start_x + (bytes_per_row() * character_width());
216 auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
217
218 if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
219 auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
220 auto byte_y = (absolute_y - hex_start_y) / line_height();
221 auto offset = (byte_y * m_bytes_per_row) + byte_x;
222
223 if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
224 return;
225
226#ifdef HEX_DEBUG
227 printf("HexEditor::mousedown_event(hex): offset=%d\n", offset);
228#endif
229
230 m_edit_mode = EditMode::Hex;
231 m_byte_position = 0;
232 m_position = offset;
233 m_in_drag_select = true;
234 m_selection_start = offset;
235 m_selection_end = -1;
236 update();
237 update_status();
238 }
239
240 if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
241 auto byte_x = (absolute_x - text_start_x) / character_width();
242 auto byte_y = (absolute_y - text_start_y) / line_height();
243 auto offset = (byte_y * m_bytes_per_row) + byte_x;
244
245 if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
246 return;
247
248#ifdef HEX_DEBUG
249 printf("HexEditor::mousedown_event(text): offset=%d\n", offset);
250#endif
251
252 m_position = offset;
253 m_byte_position = 0;
254 m_in_drag_select = true;
255 m_selection_start = offset;
256 m_selection_end = -1;
257 m_edit_mode = EditMode::Text;
258 update();
259 update_status();
260 }
261}
262
263void 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
268 auto hex_start_x = frame_thickness() + 90;
269 auto hex_start_y = frame_thickness() + 5;
270 auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
271 auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
272
273 auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
274 auto text_start_y = frame_thickness() + 5;
275 auto text_end_x = text_start_x + (bytes_per_row() * character_width());
276 auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
277
278 window()->set_override_cursor(GUI::StandardCursor::None);
279 if ((absolute_x >= hex_start_x && absolute_x <= hex_end_x
280 && absolute_y >= hex_start_y && absolute_y <= hex_end_y)
281 || (absolute_x >= text_start_x && absolute_x <= text_end_x
282 && absolute_y >= text_start_y && absolute_y <= text_end_y)) {
283 window()->set_override_cursor(GUI::StandardCursor::IBeam);
284 }
285
286 if (m_in_drag_select) {
287 if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
288 auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
289 auto byte_y = (absolute_y - hex_start_y) / line_height();
290 auto offset = (byte_y * m_bytes_per_row) + byte_x;
291
292 if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
293 return;
294
295 m_selection_end = offset;
296 scroll_position_into_view(offset);
297 }
298
299 if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
300 auto byte_x = (absolute_x - text_start_x) / character_width();
301 auto byte_y = (absolute_y - text_start_y) / line_height();
302 auto offset = (byte_y * m_bytes_per_row) + byte_x;
303 if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
304 return;
305
306 m_selection_end = offset;
307 scroll_position_into_view(offset);
308 }
309 update_status();
310 update();
311 return;
312 }
313}
314
315void HexEditor::mouseup_event(GUI::MouseEvent& event)
316{
317 if (event.button() == GUI::MouseButton::Left) {
318 if (m_in_drag_select) {
319 if (m_selection_end == -1 || m_selection_start == -1) {
320 m_selection_start = -1;
321 m_selection_end = -1;
322 } else if (m_selection_end < m_selection_start) {
323 // lets flip these around
324 auto start = m_selection_end;
325 m_selection_end = m_selection_start;
326 m_selection_start = start;
327 }
328 m_in_drag_select = false;
329 }
330 update();
331 update_status();
332 }
333}
334
335void HexEditor::scroll_position_into_view(int position)
336{
337 int y = position / bytes_per_row();
338 int x = position % bytes_per_row();
339 Gfx::Rect rect {
340 frame_thickness() + offset_margin_width() + (x * (character_width() * 3)) + 10,
341 frame_thickness() + 5 + (y * line_height()),
342 (character_width() * 3),
343 line_height() - m_line_spacing
344 };
345 scroll_into_view(rect, true, true);
346}
347
348void HexEditor::keydown_event(GUI::KeyEvent& event)
349{
350#ifdef HEX_DEBUG
351 printf("HexEditor::keydown_event key=%d\n", event.key());
352#endif
353
354 if (event.key() == KeyCode::Key_Up) {
355 if (m_position - bytes_per_row() >= 0) {
356 m_position -= bytes_per_row();
357 m_byte_position = 0;
358 scroll_position_into_view(m_position);
359 update();
360 update_status();
361 }
362 return;
363 }
364
365 if (event.key() == KeyCode::Key_Down) {
366 if (m_position + bytes_per_row() < static_cast<int>(m_buffer.size())) {
367 m_position += bytes_per_row();
368 m_byte_position = 0;
369 scroll_position_into_view(m_position);
370 update();
371 update_status();
372 }
373 return;
374 }
375
376 if (event.key() == KeyCode::Key_Left) {
377 if (m_position - 1 >= 0) {
378 m_position--;
379 m_byte_position = 0;
380 scroll_position_into_view(m_position);
381 update();
382 update_status();
383 }
384 return;
385 }
386
387 if (event.key() == KeyCode::Key_Right) {
388 if (m_position + 1 < static_cast<int>(m_buffer.size())) {
389 m_position++;
390 m_byte_position = 0;
391 scroll_position_into_view(m_position);
392 update();
393 update_status();
394 }
395 return;
396 }
397
398 if (event.key() == KeyCode::Key_Backspace) {
399 if (m_position > 0) {
400 m_position--;
401 m_byte_position = 0;
402 scroll_position_into_view(m_position);
403 update();
404 update_status();
405 }
406 return;
407 }
408
409 if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
410 if (m_edit_mode == EditMode::Hex) {
411 hex_mode_keydown_event(event);
412 } else {
413 text_mode_keydown_event(event);
414 }
415 }
416}
417
418void HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event)
419{
420 if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
421 if (m_buffer.is_empty())
422 return;
423 ASSERT(m_position >= 0);
424 ASSERT(m_position < static_cast<int>(m_buffer.size()));
425
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
431 if (m_byte_position == 0) {
432 m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
433 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
434 m_byte_position++;
435 } else {
436 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
437 if (m_position + 1 < static_cast<int>(m_buffer.size()))
438 m_position++;
439 m_byte_position = 0;
440 }
441
442 update();
443 update_status();
444 did_change();
445 }
446}
447
448void HexEditor::text_mode_keydown_event(GUI::KeyEvent& event)
449{
450 if (m_buffer.is_empty())
451 return;
452 ASSERT(m_position >= 0);
453 ASSERT(m_position < static_cast<int>(m_buffer.size()));
454
455 m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
456 m_buffer.data()[m_position] = (u8)event.text().characters()[0]; // save the first 4 bits, OR the new value in the last 4
457 if (m_position + 1 < static_cast<int>(m_buffer.size()))
458 m_position++;
459 m_byte_position = 0;
460
461 update();
462 update_status();
463 did_change();
464}
465
466void HexEditor::update_status()
467{
468 if (on_status_change)
469 on_status_change(m_position, m_edit_mode, m_selection_start, m_selection_end);
470}
471
472void HexEditor::did_change()
473{
474 if (on_change)
475 on_change();
476}
477
478void HexEditor::paint_event(GUI::PaintEvent& event)
479{
480 GUI::Frame::paint_event(event);
481
482 GUI::Painter painter(*this);
483 painter.add_clip_rect(widget_inner_rect());
484 painter.add_clip_rect(event.rect());
485 painter.fill_rect(event.rect(), palette().color(background_role()));
486
487 if (m_buffer.is_empty())
488 return;
489
490 painter.translate(frame_thickness(), frame_thickness());
491 painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
492
493 Gfx::Rect offset_clip_rect {
494 0,
495 vertical_scrollbar().value(),
496 85,
497 height() - height_occupied_by_horizontal_scrollbar() //(total_rows() * line_height()) + 5
498 };
499 painter.fill_rect(offset_clip_rect, palette().ruler());
500 painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right(), palette().ruler_border());
501
502 auto margin_and_hex_width = offset_margin_width() + (m_bytes_per_row * (character_width() * 3)) + 15;
503 painter.draw_line({ margin_and_hex_width, 0 },
504 { margin_and_hex_width, vertical_scrollbar().value() + (height() - height_occupied_by_horizontal_scrollbar()) },
505 palette().ruler_border());
506
507 auto view_height = (height() - height_occupied_by_horizontal_scrollbar());
508 auto min_row = max(0, vertical_scrollbar().value() / line_height()); // if below 0 then use 0
509 auto max_row = min(total_rows(), min_row + ceil_div(view_height, line_height())); // if above calculated rows, use calculated rows
510
511 // paint offsets
512 for (int i = min_row; i < max_row; i++) {
513 Gfx::Rect side_offset_rect {
514 frame_thickness() + 5,
515 frame_thickness() + 5 + (i * line_height()),
516 width() - width_occupied_by_vertical_scrollbar(),
517 height() - height_occupied_by_horizontal_scrollbar()
518 };
519
520 bool is_current_line = (m_position / bytes_per_row()) == i;
521 auto line = String::format("0x%08X", i * bytes_per_row());
522 painter.draw_text(
523 side_offset_rect,
524 line,
525 is_current_line ? Gfx::Font::default_bold_font() : font(),
526 Gfx::TextAlignment::TopLeft,
527 is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
528 }
529
530 for (int i = min_row; i < max_row; i++) {
531 for (int j = 0; j < bytes_per_row(); j++) {
532 auto byte_position = (i * bytes_per_row()) + j;
533 if (byte_position >= static_cast<int>(m_buffer.size()))
534 return;
535
536 Color text_color = palette().color(foreground_role());
537 if (m_tracked_changes.contains(byte_position)) {
538 text_color = Color::Red;
539 }
540
541 auto highlight_flag = false;
542 if (m_selection_start > -1 && m_selection_end > -1) {
543 if (byte_position >= m_selection_start && byte_position <= m_selection_end) {
544 highlight_flag = true;
545 }
546 if (byte_position >= m_selection_end && byte_position <= m_selection_start) {
547 highlight_flag = true;
548 }
549 }
550
551 Gfx::Rect hex_display_rect {
552 frame_thickness() + offset_margin_width() + (j * (character_width() * 3)) + 10,
553 frame_thickness() + 5 + (i * line_height()),
554 (character_width() * 3),
555 line_height() - m_line_spacing
556 };
557 if (highlight_flag) {
558 painter.fill_rect(hex_display_rect, palette().selection());
559 text_color = text_color == Color::Red ? Color::from_rgb(0xFFC0CB) : palette().selection_text();
560 } else if (byte_position == m_position) {
561 painter.fill_rect(hex_display_rect, palette().inactive_selection());
562 text_color = palette().inactive_selection_text();
563 }
564
565 auto line = String::format("%02X", m_buffer[byte_position]);
566 painter.draw_text(hex_display_rect, line, Gfx::TextAlignment::TopLeft, text_color);
567
568 Gfx::Rect text_display_rect {
569 frame_thickness() + offset_margin_width() + (bytes_per_row() * (character_width() * 3)) + (j * character_width()) + 20,
570 frame_thickness() + 5 + (i * line_height()),
571 character_width(),
572 line_height() - m_line_spacing
573 };
574 // selection highlighting.
575 if (highlight_flag) {
576 painter.fill_rect(text_display_rect, palette().selection());
577 } else if (byte_position == m_position) {
578 painter.fill_rect(text_display_rect, palette().inactive_selection());
579 }
580
581 painter.draw_text(text_display_rect, String::format("%c", isprint(m_buffer[byte_position]) ? m_buffer[byte_position] : '.'), Gfx::TextAlignment::TopLeft, text_color);
582 }
583 }
584}
585
586void HexEditor::leave_event(Core::Event&)
587{
588 ASSERT(window());
589 window()->set_override_cursor(GUI::StandardCursor::None);
590}