1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-28 08:07:44 +00:00

Applications: Move to Userland/Applications/

This commit is contained in:
Andreas Kling 2021-01-12 12:05:23 +01:00
parent aa939c4b4b
commit dc28c07fa5
287 changed files with 1 additions and 1 deletions

View file

@ -0,0 +1,8 @@
set(SOURCES
HexEditor.cpp
HexEditorWidget.cpp
main.cpp
)
serenity_app(HexEditor ICON app-hexeditor)
target_link_libraries(HexEditor LibGUI)

View file

@ -0,0 +1,583 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HexEditor.h"
#include <AK/StringBuilder.h>
#include <LibGUI/Action.h>
#include <LibGUI/Clipboard.h>
#include <LibGUI/Menu.h>
#include <LibGUI/Painter.h>
#include <LibGUI/ScrollBar.h>
#include <LibGUI/TextEditor.h>
#include <LibGUI/Window.h>
#include <LibGfx/FontDatabase.h>
#include <LibGfx/Palette.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
HexEditor::HexEditor()
{
set_focus_policy(GUI::FocusPolicy::StrongFocus);
set_scrollbars_enabled(true);
set_font(Gfx::FontDatabase::default_fixed_width_font());
set_background_role(ColorRole::Base);
set_foreground_role(ColorRole::BaseText);
vertical_scrollbar().set_step(line_height());
}
HexEditor::~HexEditor()
{
}
void HexEditor::set_readonly(bool readonly)
{
if (m_readonly == readonly)
return;
m_readonly = readonly;
}
void HexEditor::set_buffer(const ByteBuffer& buffer)
{
m_buffer = buffer;
set_content_length(buffer.size());
m_tracked_changes.clear();
m_position = 0;
m_byte_position = 0;
update();
update_status();
}
void HexEditor::fill_selection(u8 fill_byte)
{
if (!has_selection())
return;
for (int i = m_selection_start; i <= m_selection_end; i++) {
m_tracked_changes.set(i, m_buffer.data()[i]);
m_buffer.data()[i] = fill_byte;
}
update();
did_change();
}
void HexEditor::set_position(int position)
{
if (position > static_cast<int>(m_buffer.size()))
return;
m_position = position;
m_byte_position = 0;
scroll_position_into_view(position);
update_status();
}
bool HexEditor::write_to_file(const StringView& path)
{
if (m_buffer.is_empty())
return true;
int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
perror("open");
return false;
}
int rc = ftruncate(fd, m_buffer.size());
if (rc < 0) {
perror("ftruncate");
return false;
}
ssize_t nwritten = write(fd, m_buffer.data(), m_buffer.size());
if (nwritten < 0) {
perror("write");
close(fd);
return false;
}
if (static_cast<size_t>(nwritten) == m_buffer.size()) {
m_tracked_changes.clear();
update();
}
close(fd);
return true;
}
bool HexEditor::copy_selected_hex_to_clipboard()
{
if (!has_selection())
return false;
StringBuilder output_string_builder;
for (int i = m_selection_start; i <= m_selection_end; i++)
output_string_builder.appendff("{:02X} ", m_buffer.data()[i]);
GUI::Clipboard::the().set_plain_text(output_string_builder.to_string());
return true;
}
bool HexEditor::copy_selected_text_to_clipboard()
{
if (!has_selection())
return false;
StringBuilder output_string_builder;
for (int i = m_selection_start; i <= m_selection_end; i++)
output_string_builder.append(isprint(m_buffer.data()[i]) ? m_buffer[i] : '.');
GUI::Clipboard::the().set_plain_text(output_string_builder.to_string());
return true;
}
bool HexEditor::copy_selected_hex_to_clipboard_as_c_code()
{
if (!has_selection())
return false;
StringBuilder output_string_builder;
output_string_builder.appendff("unsigned char raw_data[{}] = {{\n", (m_selection_end - m_selection_start) + 1);
output_string_builder.append(" ");
for (int i = m_selection_start, j = 1; i <= m_selection_end; i++, j++) {
output_string_builder.appendff("{:#02X}", m_buffer.data()[i]);
if (i != m_selection_end)
output_string_builder.append(", ");
if ((j % 12) == 0) {
output_string_builder.append("\n");
output_string_builder.append(" ");
}
}
output_string_builder.append("\n};\n");
GUI::Clipboard::the().set_plain_text(output_string_builder.to_string());
return true;
}
void HexEditor::set_bytes_per_row(int bytes_per_row)
{
m_bytes_per_row = bytes_per_row;
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 });
update();
}
void HexEditor::set_content_length(int length)
{
if (length == m_content_length)
return;
m_content_length = length;
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 });
}
void HexEditor::mousedown_event(GUI::MouseEvent& event)
{
if (event.button() != GUI::MouseButton::Left) {
return;
}
auto absolute_x = horizontal_scrollbar().value() + event.x();
auto absolute_y = vertical_scrollbar().value() + event.y();
auto hex_start_x = frame_thickness() + 90;
auto hex_start_y = frame_thickness() + 5;
auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
auto text_start_y = frame_thickness() + 5;
auto text_end_x = text_start_x + (bytes_per_row() * character_width());
auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
auto byte_y = (absolute_y - hex_start_y) / line_height();
auto offset = (byte_y * m_bytes_per_row) + byte_x;
if (offset < 0 || offset >= static_cast<int>(m_buffer.size()))
return;
#ifdef HEX_DEBUG
outln("HexEditor::mousedown_event(hex): offset={}", offset);
#endif
m_edit_mode = EditMode::Hex;
m_byte_position = 0;
m_position = offset;
m_in_drag_select = true;
m_selection_start = offset;
m_selection_end = offset;
update();
update_status();
}
if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
auto byte_x = (absolute_x - text_start_x) / character_width();
auto byte_y = (absolute_y - text_start_y) / line_height();
auto offset = (byte_y * m_bytes_per_row) + byte_x;
if (offset < 0 || offset >= static_cast<int>(m_buffer.size()))
return;
#ifdef HEX_DEBUG
outln("HexEditor::mousedown_event(text): offset={}", offset);
#endif
m_position = offset;
m_byte_position = 0;
m_in_drag_select = true;
m_selection_start = offset;
m_selection_end = offset;
m_edit_mode = EditMode::Text;
update();
update_status();
}
}
void HexEditor::mousemove_event(GUI::MouseEvent& event)
{
auto absolute_x = horizontal_scrollbar().value() + event.x();
auto absolute_y = vertical_scrollbar().value() + event.y();
auto hex_start_x = frame_thickness() + 90;
auto hex_start_y = frame_thickness() + 5;
auto hex_end_x = hex_start_x + (bytes_per_row() * (character_width() * 3));
auto hex_end_y = hex_start_y + 5 + (total_rows() * line_height());
auto text_start_x = frame_thickness() + 100 + (bytes_per_row() * (character_width() * 3));
auto text_start_y = frame_thickness() + 5;
auto text_end_x = text_start_x + (bytes_per_row() * character_width());
auto text_end_y = text_start_y + 5 + (total_rows() * line_height());
if ((absolute_x >= hex_start_x && absolute_x <= hex_end_x
&& absolute_y >= hex_start_y && absolute_y <= hex_end_y)
|| (absolute_x >= text_start_x && absolute_x <= text_end_x
&& absolute_y >= text_start_y && absolute_y <= text_end_y)) {
set_override_cursor(Gfx::StandardCursor::IBeam);
} else {
set_override_cursor(Gfx::StandardCursor::None);
}
if (m_in_drag_select) {
if (absolute_x >= hex_start_x && absolute_x <= hex_end_x && absolute_y >= hex_start_y && absolute_y <= hex_end_y) {
auto byte_x = (absolute_x - hex_start_x) / (character_width() * 3);
auto byte_y = (absolute_y - hex_start_y) / line_height();
auto offset = (byte_y * m_bytes_per_row) + byte_x;
if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
return;
m_selection_end = offset;
scroll_position_into_view(offset);
}
if (absolute_x >= text_start_x && absolute_x <= text_end_x && absolute_y >= text_start_y && absolute_y <= text_end_y) {
auto byte_x = (absolute_x - text_start_x) / character_width();
auto byte_y = (absolute_y - text_start_y) / line_height();
auto offset = (byte_y * m_bytes_per_row) + byte_x;
if (offset < 0 || offset > static_cast<int>(m_buffer.size()))
return;
m_selection_end = offset;
scroll_position_into_view(offset);
}
update_status();
update();
return;
}
}
void HexEditor::mouseup_event(GUI::MouseEvent& event)
{
if (event.button() == GUI::MouseButton::Left) {
if (m_in_drag_select) {
if (m_selection_end < m_selection_start) {
// lets flip these around
auto start = m_selection_end;
m_selection_end = m_selection_start;
m_selection_start = start;
}
m_in_drag_select = false;
}
update();
update_status();
}
}
void HexEditor::scroll_position_into_view(int position)
{
int y = position / bytes_per_row();
int x = position % bytes_per_row();
Gfx::IntRect rect {
frame_thickness() + offset_margin_width() + (x * (character_width() * 3)) + 10,
frame_thickness() + 5 + (y * line_height()),
(character_width() * 3),
line_height() - m_line_spacing
};
scroll_into_view(rect, true, true);
}
void HexEditor::keydown_event(GUI::KeyEvent& event)
{
#ifdef HEX_DEBUG
outln("HexEditor::keydown_event key={}", static_cast<u8>(event.key()));
#endif
if (event.key() == KeyCode::Key_Up) {
if (m_position - bytes_per_row() >= 0) {
m_position -= bytes_per_row();
m_byte_position = 0;
scroll_position_into_view(m_position);
update();
update_status();
}
return;
}
if (event.key() == KeyCode::Key_Down) {
if (m_position + bytes_per_row() < static_cast<int>(m_buffer.size())) {
m_position += bytes_per_row();
m_byte_position = 0;
scroll_position_into_view(m_position);
update();
update_status();
}
return;
}
if (event.key() == KeyCode::Key_Left) {
if (m_position - 1 >= 0) {
m_position--;
m_byte_position = 0;
scroll_position_into_view(m_position);
update();
update_status();
}
return;
}
if (event.key() == KeyCode::Key_Right) {
if (m_position + 1 < static_cast<int>(m_buffer.size())) {
m_position++;
m_byte_position = 0;
scroll_position_into_view(m_position);
update();
update_status();
}
return;
}
if (event.key() == KeyCode::Key_Backspace) {
if (m_position > 0) {
m_position--;
m_byte_position = 0;
scroll_position_into_view(m_position);
update();
update_status();
}
return;
}
if (!is_readonly() && !event.ctrl() && !event.alt() && !event.text().is_empty()) {
if (m_edit_mode == EditMode::Hex) {
hex_mode_keydown_event(event);
} else {
text_mode_keydown_event(event);
}
}
}
void HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event)
{
if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
if (m_buffer.is_empty())
return;
ASSERT(m_position >= 0);
ASSERT(m_position < static_cast<int>(m_buffer.size()));
// yes, this is terrible... but it works.
auto value = (event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9)
? event.key() - KeyCode::Key_0
: (event.key() - KeyCode::Key_A) + 0xA;
if (m_byte_position == 0) {
m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
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
m_byte_position++;
} else {
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
if (m_position + 1 < static_cast<int>(m_buffer.size()))
m_position++;
m_byte_position = 0;
}
update();
update_status();
did_change();
}
}
void HexEditor::text_mode_keydown_event(GUI::KeyEvent& event)
{
if (m_buffer.is_empty())
return;
ASSERT(m_position >= 0);
ASSERT(m_position < static_cast<int>(m_buffer.size()));
if (event.code_point() == 0) // This is a control key
return;
m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
m_buffer.data()[m_position] = event.code_point();
if (m_position + 1 < static_cast<int>(m_buffer.size()))
m_position++;
m_byte_position = 0;
update();
update_status();
did_change();
}
void HexEditor::update_status()
{
if (on_status_change)
on_status_change(m_position, m_edit_mode, m_selection_start, m_selection_end);
}
void HexEditor::did_change()
{
if (on_change)
on_change();
}
void HexEditor::paint_event(GUI::PaintEvent& event)
{
GUI::Frame::paint_event(event);
GUI::Painter painter(*this);
painter.add_clip_rect(widget_inner_rect());
painter.add_clip_rect(event.rect());
painter.fill_rect(event.rect(), palette().color(background_role()));
if (m_buffer.is_empty())
return;
painter.translate(frame_thickness(), frame_thickness());
painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
Gfx::IntRect offset_clip_rect {
0,
vertical_scrollbar().value(),
85,
height() - height_occupied_by_horizontal_scrollbar() //(total_rows() * line_height()) + 5
};
painter.fill_rect(offset_clip_rect, palette().ruler());
painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right(), palette().ruler_border());
auto margin_and_hex_width = offset_margin_width() + (m_bytes_per_row * (character_width() * 3)) + 15;
painter.draw_line({ margin_and_hex_width, 0 },
{ margin_and_hex_width, vertical_scrollbar().value() + (height() - height_occupied_by_horizontal_scrollbar()) },
palette().ruler_border());
auto view_height = (height() - height_occupied_by_horizontal_scrollbar());
auto min_row = max(0, vertical_scrollbar().value() / line_height()); // if below 0 then use 0
auto max_row = min(total_rows(), min_row + ceil_div(view_height, line_height())); // if above calculated rows, use calculated rows
// paint offsets
for (int i = min_row; i < max_row; i++) {
Gfx::IntRect side_offset_rect {
frame_thickness() + 5,
frame_thickness() + 5 + (i * line_height()),
width() - width_occupied_by_vertical_scrollbar(),
height() - height_occupied_by_horizontal_scrollbar()
};
bool is_current_line = (m_position / bytes_per_row()) == i;
auto line = String::formatted("{:#08X}", i * bytes_per_row());
painter.draw_text(
side_offset_rect,
line,
is_current_line ? Gfx::FontDatabase::default_bold_font() : font(),
Gfx::TextAlignment::TopLeft,
is_current_line ? palette().ruler_active_text() : palette().ruler_inactive_text());
}
for (int i = min_row; i < max_row; i++) {
for (int j = 0; j < bytes_per_row(); j++) {
auto byte_position = (i * bytes_per_row()) + j;
if (byte_position >= static_cast<int>(m_buffer.size()))
return;
Color text_color = palette().color(foreground_role());
if (m_tracked_changes.contains(byte_position)) {
text_color = Color::Red;
}
auto highlight_flag = false;
if (m_selection_start > -1 && m_selection_end > -1) {
if (byte_position >= m_selection_start && byte_position <= m_selection_end) {
highlight_flag = true;
}
if (byte_position >= m_selection_end && byte_position <= m_selection_start) {
highlight_flag = true;
}
}
Gfx::IntRect hex_display_rect {
frame_thickness() + offset_margin_width() + (j * (character_width() * 3)) + 10,
frame_thickness() + 5 + (i * line_height()),
(character_width() * 3),
line_height() - m_line_spacing
};
if (highlight_flag) {
painter.fill_rect(hex_display_rect, palette().selection());
text_color = text_color == Color::Red ? Color::from_rgb(0xFFC0CB) : palette().selection_text();
} else if (byte_position == m_position) {
painter.fill_rect(hex_display_rect, palette().inactive_selection());
text_color = palette().inactive_selection_text();
}
auto line = String::formatted("{:02X}", m_buffer[byte_position]);
painter.draw_text(hex_display_rect, line, Gfx::TextAlignment::TopLeft, text_color);
Gfx::IntRect text_display_rect {
frame_thickness() + offset_margin_width() + (bytes_per_row() * (character_width() * 3)) + (j * character_width()) + 20,
frame_thickness() + 5 + (i * line_height()),
character_width(),
line_height() - m_line_spacing
};
// selection highlighting.
if (highlight_flag) {
painter.fill_rect(text_display_rect, palette().selection());
} else if (byte_position == m_position) {
painter.fill_rect(text_display_rect, palette().inactive_selection());
}
painter.draw_text(text_display_rect, String::formatted("{:c}", isprint(m_buffer[byte_position]) ? m_buffer[byte_position] : '.'), Gfx::TextAlignment::TopLeft, text_color);
}
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <AK/ByteBuffer.h>
#include <AK/Function.h>
#include <AK/HashMap.h>
#include <AK/NonnullOwnPtrVector.h>
#include <AK/NonnullRefPtrVector.h>
#include <AK/StdLibExtras.h>
#include <LibGUI/ScrollableWidget.h>
#include <LibGfx/Font.h>
#include <LibGfx/TextAlignment.h>
class HexEditor : public GUI::ScrollableWidget {
C_OBJECT(HexEditor)
public:
enum EditMode {
Hex,
Text
};
virtual ~HexEditor() override;
bool is_readonly() const { return m_readonly; }
void set_readonly(bool);
void set_buffer(const ByteBuffer&);
void fill_selection(u8 fill_byte);
bool write_to_file(const StringView& path);
bool has_selection() const { return !(m_selection_start == -1 || m_selection_end == -1 || (m_selection_end - m_selection_start) < 0 || m_buffer.is_empty()); }
bool copy_selected_text_to_clipboard();
bool copy_selected_hex_to_clipboard();
bool copy_selected_hex_to_clipboard_as_c_code();
int bytes_per_row() const { return m_bytes_per_row; }
void set_bytes_per_row(int);
void set_position(int position);
Function<void(int, EditMode, int, int)> on_status_change; // position, edit mode, selection start, selection end
Function<void()> on_change;
protected:
HexEditor();
virtual void paint_event(GUI::PaintEvent&) override;
virtual void mousedown_event(GUI::MouseEvent&) override;
virtual void mouseup_event(GUI::MouseEvent&) override;
virtual void mousemove_event(GUI::MouseEvent&) override;
virtual void keydown_event(GUI::KeyEvent&) override;
private:
bool m_readonly { false };
int m_line_spacing { 4 };
int m_content_length { 0 };
int m_bytes_per_row { 16 };
ByteBuffer m_buffer;
bool m_in_drag_select { false };
int m_selection_start { 0 };
int m_selection_end { 0 };
HashMap<int, u8> m_tracked_changes;
int m_position { 0 };
int m_byte_position { 0 }; // 0 or 1
EditMode m_edit_mode { Hex };
void scroll_position_into_view(int position);
int total_rows() const { return ceil_div(m_content_length, m_bytes_per_row); }
int line_height() const { return font().glyph_height() + m_line_spacing; }
int character_width() const { return font().glyph_width('W'); }
int offset_margin_width() const { return 80; }
void hex_mode_keydown_event(GUI::KeyEvent&);
void text_mode_keydown_event(GUI::KeyEvent&);
void set_content_length(int); // I might make this public if I add fetching data on demand.
void update_status();
void did_change();
};

View file

@ -0,0 +1,241 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HexEditorWidget.h"
#include <AK/Optional.h>
#include <AK/StringBuilder.h>
#include <LibCore/File.h>
#include <LibGUI/Action.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/FilePicker.h>
#include <LibGUI/InputBox.h>
#include <LibGUI/Menu.h>
#include <LibGUI/MenuBar.h>
#include <LibGUI/MessageBox.h>
#include <LibGUI/StatusBar.h>
#include <LibGUI/TextBox.h>
#include <LibGUI/TextEditor.h>
#include <LibGUI/ToolBar.h>
#include <stdio.h>
#include <string.h>
HexEditorWidget::HexEditorWidget()
{
set_fill_with_background_color(true);
set_layout<GUI::VerticalBoxLayout>();
layout()->set_spacing(2);
m_editor = add<HexEditor>();
m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
m_statusbar->set_text(0, String::formatted("Offset: {:#08X}", position));
m_statusbar->set_text(1, String::formatted("Edit Mode: {}", edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text"));
m_statusbar->set_text(2, String::formatted("Selection Start: {}", selection_start));
m_statusbar->set_text(3, String::formatted("Selection End: {}", selection_end));
m_statusbar->set_text(4, String::formatted("Selected Bytes: {}", abs(selection_end - selection_start) + 1));
};
m_editor->on_change = [this] {
bool was_dirty = m_document_dirty;
m_document_dirty = true;
if (!was_dirty)
update_title();
};
m_statusbar = add<GUI::StatusBar>(5);
m_new_action = GUI::Action::create("New", { Mod_Ctrl, Key_N }, Gfx::Bitmap::load_from_file("/res/icons/16x16/new.png"), [this](const GUI::Action&) {
if (m_document_dirty) {
if (GUI::MessageBox::show(window(), "Save changes to current file first?", "Warning", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel) != GUI::Dialog::ExecResult::ExecOK)
return;
m_save_action->activate();
}
String value;
if (GUI::InputBox::show(value, window(), "Enter new file size:", "New file size") == GUI::InputBox::ExecOK && !value.is_empty()) {
auto file_size = value.to_int();
if (file_size.has_value() && file_size.value() > 0) {
m_document_dirty = false;
m_editor->set_buffer(ByteBuffer::create_zeroed(file_size.value()));
set_path(LexicalPath());
update_title();
} else {
GUI::MessageBox::show(window(), "Invalid file size entered.", "Error", GUI::MessageBox::Type::Error);
}
}
});
m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
Optional<String> open_path = GUI::FilePicker::get_open_filepath(window());
if (!open_path.has_value())
return;
open_file(open_path.value());
});
m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
if (!m_path.is_empty()) {
if (!m_editor->write_to_file(m_path)) {
GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
} else {
m_document_dirty = false;
update_title();
}
return;
}
m_save_as_action->activate();
});
m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(), m_name.is_null() ? "Untitled" : m_name, m_extension.is_null() ? "bin" : m_extension);
if (!save_path.has_value())
return;
if (!m_editor->write_to_file(save_path.value())) {
GUI::MessageBox::show(window(), "Unable to save file.\n", "Error", GUI::MessageBox::Type::Error);
return;
}
m_document_dirty = false;
set_path(LexicalPath(save_path.value()));
dbgln("Wrote document to {}", save_path.value());
});
auto menubar = GUI::MenuBar::construct();
auto& app_menu = menubar->add_menu("Hex Editor");
app_menu.add_action(*m_new_action);
app_menu.add_action(*m_open_action);
app_menu.add_action(*m_save_action);
app_menu.add_action(*m_save_as_action);
app_menu.add_separator();
app_menu.add_action(GUI::CommonActions::make_quit_action([this](auto&) {
if (!request_close())
return;
GUI::Application::the()->quit();
}));
m_goto_decimal_offset_action = GUI::Action::create("Go To Offset (Decimal)...", { Mod_Ctrl | Mod_Shift, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) {
String value;
if (GUI::InputBox::show(value, window(), "Enter Decimal offset:", "Go To") == GUI::InputBox::ExecOK && !value.is_empty()) {
auto new_offset = value.to_int();
if (new_offset.has_value())
m_editor->set_position(new_offset.value());
}
});
m_goto_hex_offset_action = GUI::Action::create("Go To Offset (Hex)...", { Mod_Ctrl, Key_G }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GUI::Action&) {
String value;
if (GUI::InputBox::show(value, window(), "Enter Hex offset:", "Go To") == GUI::InputBox::ExecOK && !value.is_empty()) {
auto new_offset = strtol(value.characters(), nullptr, 16);
m_editor->set_position(new_offset);
}
});
auto& edit_menu = menubar->add_menu("Edit");
edit_menu.add_action(GUI::Action::create("Fill selection...", { Mod_Ctrl, Key_B }, [&](const GUI::Action&) {
String value;
if (GUI::InputBox::show(value, window(), "Fill byte (hex):", "Fill Selection") == GUI::InputBox::ExecOK && !value.is_empty()) {
auto fill_byte = strtol(value.characters(), nullptr, 16);
m_editor->fill_selection(fill_byte);
}
}));
edit_menu.add_separator();
edit_menu.add_action(*m_goto_decimal_offset_action);
edit_menu.add_action(*m_goto_hex_offset_action);
edit_menu.add_separator();
edit_menu.add_action(GUI::Action::create("Copy Hex", { Mod_Ctrl, Key_C }, [&](const GUI::Action&) {
m_editor->copy_selected_hex_to_clipboard();
}));
edit_menu.add_action(GUI::Action::create("Copy Text", { Mod_Ctrl | Mod_Shift, Key_C }, [&](const GUI::Action&) {
m_editor->copy_selected_text_to_clipboard();
}));
edit_menu.add_separator();
edit_menu.add_action(GUI::Action::create("Copy As C Code", { Mod_Alt | Mod_Shift, Key_C }, [&](const GUI::Action&) {
m_editor->copy_selected_hex_to_clipboard_as_c_code();
}));
auto& view_menu = menubar->add_menu("View");
auto& bytes_per_row_menu = view_menu.add_submenu("Bytes per row");
for (int i = 8; i <= 32; i += 8) {
bytes_per_row_menu.add_action(GUI::Action::create(String::number(i), [this, i](auto&) {
m_editor->set_bytes_per_row(i);
m_editor->update();
}));
}
auto& help_menu = menubar->add_menu("Help");
help_menu.add_action(GUI::CommonActions::make_about_action("Hex Editor", GUI::Icon::default_icon("Hex Editor"), window()));
GUI::Application::the()->set_menubar(move(menubar));
m_editor->set_focus(true);
}
HexEditorWidget::~HexEditorWidget()
{
}
void HexEditorWidget::set_path(const LexicalPath& lexical_path)
{
m_path = lexical_path.string();
m_name = lexical_path.title();
m_extension = lexical_path.extension();
update_title();
}
void HexEditorWidget::update_title()
{
StringBuilder builder;
builder.append(m_path);
if (m_document_dirty)
builder.append(" (*)");
builder.append(" - Hex Editor");
window()->set_title(builder.to_string());
}
void HexEditorWidget::open_file(const String& path)
{
auto file = Core::File::construct(path);
if (!file->open(Core::IODevice::ReadOnly)) {
GUI::MessageBox::show(window(), String::formatted("Opening \"{}\" failed: {}", path, strerror(errno)), "Error", GUI::MessageBox::Type::Error);
return;
}
m_document_dirty = false;
m_editor->set_buffer(file->read_all()); // FIXME: On really huge files, this is never going to work. Should really create a framework to fetch data from the file on-demand.
set_path(LexicalPath(path));
}
bool HexEditorWidget::request_close()
{
if (!m_document_dirty)
return true;
auto result = GUI::MessageBox::show(window(), "The file has been modified. Quit without saving?", "Quit without saving?", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::OKCancel);
return result == GUI::MessageBox::ExecOK;
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "HexEditor.h"
#include <AK/Function.h>
#include <AK/LexicalPath.h>
#include <LibGUI/Application.h>
#include <LibGUI/TextEditor.h>
#include <LibGUI/Widget.h>
#include <LibGUI/Window.h>
class HexEditor;
class HexEditorWidget final : public GUI::Widget {
C_OBJECT(HexEditorWidget)
public:
virtual ~HexEditorWidget() override;
void open_file(const String& path);
bool request_close();
private:
HexEditorWidget();
void set_path(const LexicalPath& file);
void update_title();
RefPtr<HexEditor> m_editor;
String m_path;
String m_name;
String m_extension;
RefPtr<GUI::Action> m_new_action;
RefPtr<GUI::Action> m_open_action;
RefPtr<GUI::Action> m_save_action;
RefPtr<GUI::Action> m_save_as_action;
RefPtr<GUI::Action> m_goto_decimal_offset_action;
RefPtr<GUI::Action> m_goto_hex_offset_action;
RefPtr<GUI::StatusBar> m_statusbar;
bool m_document_dirty { false };
};

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HexEditorWidget.h"
#include <LibGUI/Icon.h>
#include <LibGfx/Bitmap.h>
#include <stdio.h>
int main(int argc, char** argv)
{
if (pledge("stdio shared_buffer accept rpath unix cpath wpath fattr thread", nullptr) < 0) {
perror("pledge");
return 1;
}
auto app = GUI::Application::construct(argc, argv);
if (pledge("stdio shared_buffer accept rpath cpath wpath thread", nullptr) < 0) {
perror("pledge");
return 1;
}
auto app_icon = GUI::Icon::default_icon("app-hexeditor");
auto window = GUI::Window::construct();
window->set_title("Hex Editor");
window->resize(640, 400);
auto& hex_editor_widget = window->set_main_widget<HexEditorWidget>();
window->on_close_request = [&]() -> GUI::Window::CloseRequestDecision {
if (hex_editor_widget.request_close())
return GUI::Window::CloseRequestDecision::Close;
return GUI::Window::CloseRequestDecision::StayOpen;
};
window->show();
window->set_icon(app_icon.bitmap_for_size(16));
if (argc >= 2)
hex_editor_widget.open_file(argv[1]);
return app->exec();
}