Ver código fonte

HexEditor: Initial application release

The very first release of the Hex Editor for Serenity.
Brandon Scott 5 anos atrás
pai
commit
48ef1d1bd1

+ 488 - 0
Applications/HexEditor/HexEditor.cpp

@@ -0,0 +1,488 @@
+#include "HexEditor.h"
+#include <AK/StringBuilder.h>
+#include <Kernel/KeyCode.h>
+#include <LibGUI/GAction.h>
+#include <LibGUI/GClipboard.h>
+#include <LibGUI/GFontDatabase.h>
+#include <LibGUI/GMenu.h>
+#include <LibGUI/GPainter.h>
+#include <LibGUI/GScrollBar.h>
+#include <LibGUI/GTextEditor.h>
+#include <LibGUI/GWindow.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+
+HexEditor::HexEditor(GWidget* parent)
+    : GScrollableWidget(parent)
+{
+    set_frame_shape(FrameShape::Container);
+    set_frame_shadow(FrameShadow::Sunken);
+    set_frame_thickness(2);
+    set_scrollbars_enabled(true);
+    set_font(GFontDatabase::the().get_by_name("Csilla Thin"));
+    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());
+    update();
+    update_status();
+}
+
+void HexEditor::set_position(int position)
+{
+    if (position > m_buffer.size())
+        return;
+
+    m_position = position;
+    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 (nwritten == m_buffer.size()) {
+        m_tracked_changes.clear();
+        update();
+    }
+
+    close(fd);
+    return true;
+}
+
+bool HexEditor::copy_selected_hex_to_clipboard()
+{
+    if(m_selection_start == -1 || m_selection_end == -1 || (m_selection_end - m_selection_start) < 0 || m_buffer.is_empty())
+        return false;
+
+    StringBuilder output_string_builder;
+    for(int i = m_selection_start; i < m_selection_end; i++)
+    {
+        output_string_builder.appendf("%02X ", m_buffer.data()[i]);
+    }
+
+    GClipboard::the().set_data(output_string_builder.to_string());
+    return true;
+}
+
+bool HexEditor::copy_selected_text_to_clipboard()
+{
+    if(m_selection_start == -1 || m_selection_end == -1 || (m_selection_end - m_selection_start) < 0)
+        return false;
+
+    StringBuilder output_string_builder;
+    for(int i = m_selection_start; i < m_selection_end; i++)
+    {
+        output_string_builder.appendf("%c", isprint(m_buffer.data()[i]) ? m_buffer[i] : '.');
+    }
+
+    GClipboard::the().set_data(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(GMouseEvent& event)
+{
+    if (event.button() != GMouseButton::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 > m_buffer.size())
+            return;
+
+#ifdef HEX_DEBUG
+        printf("HexEditor::mousedown_event(hex): offset=%d\n", 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 = -1;
+        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 > m_buffer.size())
+            return;
+
+#ifdef HEX_DEBUG
+        printf("HexEditor::mousedown_event(text): offset=%d\n", offset);
+#endif
+
+        m_position = offset;
+        m_byte_position = 0;
+        m_in_drag_select = true;
+        m_selection_start = offset;
+        m_selection_end = -1;
+        m_edit_mode = EditMode::Text;
+        update();
+        update_status();
+    }
+}
+
+void HexEditor::mousemove_event(GMouseEvent& 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());
+
+    window()->set_override_cursor(GStandardCursor::None);
+    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)) {
+        window()->set_override_cursor(GStandardCursor::IBeam);
+    }
+
+    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 > 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 > m_buffer.size())
+                return;
+
+            m_selection_end = offset;
+            scroll_position_into_view(offset);
+        }
+        update_status();
+        update();
+        return;
+    }
+}
+
+void HexEditor::mouseup_event(GMouseEvent& event)
+{
+    if (event.button() == GMouseButton::Left) {
+        if (m_in_drag_select) {
+            if (m_selection_end == -1 || m_selection_start == m_selection_end || m_selection_start > m_selection_end) {
+                m_selection_start = -1;
+                m_selection_end = -1;
+            }
+            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();
+    Rect 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(GKeyEvent& event)
+{
+#ifdef HEX_DEBUG
+    printf("HexEditor::keydown_event key=%d\n", event.key());
+#endif
+
+    if (event.key() == KeyCode::Key_Up) {
+        if (m_position - bytes_per_row() >= 0) {
+            m_position -= bytes_per_row();
+            scroll_position_into_view(m_position);
+            update();
+            update_status();
+        }
+        return;
+    }
+
+    if (event.key() == KeyCode::Key_Down) {
+        if (m_position + bytes_per_row() < m_buffer.size()) {
+            m_position += bytes_per_row();
+            scroll_position_into_view(m_position);
+            update();
+            update_status();
+        }
+        return;
+    }
+
+    if (event.key() == KeyCode::Key_Left) {
+        if (m_position - 1 >= 0) {
+            m_position--;
+            scroll_position_into_view(m_position);
+            update();
+            update_status();
+        }
+        return;
+    }
+
+    if (event.key() == KeyCode::Key_Right) {
+        if (m_position + 1 < m_buffer.size()) {
+            m_position++;
+            scroll_position_into_view(m_position);
+            update();
+            update_status();
+        }
+        return;
+    }
+
+    if (event.key() == KeyCode::Key_Backspace) {
+        if (m_position > 0) {
+            m_position--;
+            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(GKeyEvent& event)
+{
+    if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) {
+
+        // 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
+            m_position++;
+            m_byte_position = 0;
+        }
+
+        update();
+        update_status();
+        did_change();
+    }
+}
+
+void HexEditor::text_mode_keydown_event(GKeyEvent& event)
+{
+    m_tracked_changes.set(m_position, m_buffer.data()[m_position]);
+    m_buffer.data()[m_position] = (u8)event.text().characters()[0]; // save the first 4 bits, OR the new value in the last 4
+    m_position++;
+    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(GPaintEvent& event)
+{
+    GFrame::paint_event(event);
+
+    GPainter painter(*this);
+    painter.add_clip_rect(widget_inner_rect());
+    painter.add_clip_rect(event.rect());
+    painter.fill_rect(event.rect(), Color::White);
+
+    if (m_buffer.is_empty())
+        return;
+
+    painter.translate(frame_thickness(), frame_thickness());
+    painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
+
+    Rect 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, Color::WarmGray);
+    painter.draw_line(offset_clip_rect.top_right(), offset_clip_rect.bottom_right(), Color::DarkGray);
+
+    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()) },
+        Color::LightGray);
+
+    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++) {
+        Rect side_offset_rect {
+            frame_thickness() + 5,
+            frame_thickness() + 5 + (i * line_height()),
+            width() - width_occupied_by_vertical_scrollbar(),
+            height() - height_occupied_by_horizontal_scrollbar()
+        };
+
+        auto line = String::format("0x%08X", i * bytes_per_row());
+        painter.draw_text(side_offset_rect, line);
+    }
+
+    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 >= m_buffer.size())
+                return;
+
+            Color text_color = Color::Black;
+            if (m_tracked_changes.contains(byte_position)) {
+                text_color = Color::Red;
+            }
+
+            Color highlight_color = Color::from_rgb(0x84351a);
+
+            Rect 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 (byte_position >= m_selection_start && byte_position <= m_selection_end) {
+                painter.fill_rect(hex_display_rect, highlight_color);
+                text_color = text_color == Color::Red ? Color::from_rgb(0xFFC0CB) : Color::White;
+            } else if (byte_position == m_position) {
+                painter.fill_rect(hex_display_rect, Color::from_rgb(0xCCCCCC));
+            }
+
+            auto line = String::format("%02X", m_buffer[byte_position]);
+            painter.draw_text(hex_display_rect, line, TextAlignment::TopLeft, text_color);
+
+            Rect 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 (byte_position >= m_selection_start && byte_position <= m_selection_end) {
+                painter.fill_rect(text_display_rect, highlight_color);
+            } else if (byte_position == m_position) {
+                painter.fill_rect(text_display_rect, Color::from_rgb(0xCCCCCC));
+            }
+
+            painter.draw_text(text_display_rect, String::format("%c", isprint(m_buffer[byte_position]) ? m_buffer[byte_position] : '.'), TextAlignment::TopLeft, text_color);
+        }
+    }
+}
+
+void HexEditor::leave_event(CEvent&)
+{
+    ASSERT(window());
+    window()->set_override_cursor(GStandardCursor::None);
+}

+ 77 - 0
Applications/HexEditor/HexEditor.h

@@ -0,0 +1,77 @@
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/HashMap.h>
+#include <AK/NonnullOwnPtrVector.h>
+#include <AK/NonnullRefPtrVector.h>
+#include <AK/StdLibExtras.h>
+#include <LibDraw/TextAlignment.h>
+#include <LibGUI/GScrollableWidget.h>
+
+class HexEditor : public GScrollableWidget {
+    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&);
+    bool write_to_file(const StringView& path);
+
+    bool copy_selected_text_to_clipboard();
+    bool copy_selected_hex_to_clipboard();
+
+    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(GWidget* parent);
+
+    virtual void paint_event(GPaintEvent&) override;
+    virtual void mousedown_event(GMouseEvent&) override;
+    virtual void mouseup_event(GMouseEvent&) override;
+    virtual void mousemove_event(GMouseEvent&) override;
+    virtual void keydown_event(GKeyEvent&) override;
+    virtual bool accepts_focus() const override { return true; }
+    virtual void leave_event(CEvent&) 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 { -1 };
+    int m_selection_end { -1 };
+    int m_hover_pos { -1 };
+    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(GKeyEvent&);
+    void text_mode_keydown_event(GKeyEvent&);
+
+    void set_content_length(int); // I might make this public if I add fetching data on demand.
+    void update_status();
+    void did_change();
+};

+ 183 - 0
Applications/HexEditor/HexEditorWidget.cpp

@@ -0,0 +1,183 @@
+#include "HexEditorWidget.h"
+#include <AK/Optional.h>
+#include <AK/StringBuilder.h>
+#include <LibCore/CFile.h>
+#include <LibDraw/PNGLoader.h>
+#include <LibGUI/GAboutDialog.h>
+#include <LibGUI/GAction.h>
+#include <LibGUI/GBoxLayout.h>
+#include <LibGUI/GButton.h>
+#include <LibGUI/GFilePicker.h>
+#include <LibGUI/GFontDatabase.h>
+#include <LibGUI/GInputBox.h>
+#include <LibGUI/GMenuBar.h>
+#include <LibGUI/GMessageBox.h>
+#include <LibGUI/GStatusBar.h>
+#include <LibGUI/GTextBox.h>
+#include <LibGUI/GTextEditor.h>
+#include <LibGUI/GToolBar.h>
+#include <stdio.h>
+
+HexEditorWidget::HexEditorWidget()
+{
+    set_layout(make<GBoxLayout>(Orientation::Vertical));
+    layout()->set_spacing(0);
+
+    m_editor = HexEditor::construct(this);
+
+    m_editor->on_status_change = [this](int position, HexEditor::EditMode edit_mode, int selection_start, int selection_end) {
+        m_statusbar->set_text(String::format("Offset: %8X, Edit Mode: %s, Selection Start: %d, Selection End: %d, Selected Bytes: %d",
+            position,
+            edit_mode == HexEditor::EditMode::Hex ? "Hex" : "Text",
+            selection_start,
+            selection_end,
+            (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 = GStatusBar::construct(this);
+
+    m_open_action = GCommonActions::make_open_action([this](auto&) {
+        Optional<String> open_path = GFilePicker::get_open_filepath();
+
+        if (!open_path.has_value())
+            return;
+
+        open_file(open_path.value());
+    });
+
+    m_save_action = GAction::create("Save", { Mod_Ctrl, Key_S }, GraphicsBitmap::load_from_file("/res/icons/16x16/save.png"), [&](const GAction&) {
+        if (!m_path.is_empty()) {
+            if (!m_editor->write_to_file(m_path)) {
+                GMessageBox::show("Unable to save file.\n", "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
+            } else {
+                m_document_dirty = false;
+                update_title();
+            }
+            return;
+        }
+
+        m_save_as_action->activate();
+    });
+
+    m_save_as_action = GAction::create("Save as...", { Mod_None, Key_F12 }, GraphicsBitmap::load_from_file("/res/icons/16x16/save.png"), [this](const GAction&) {
+        Optional<String> save_path = GFilePicker::get_save_filepath(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())) {
+            GMessageBox::show("Unable to save file.\n", "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
+            return;
+        }
+
+        m_document_dirty = false;
+        set_path(FileSystemPath(save_path.value()));
+        dbg() << "Wrote document to " << save_path.value();
+    });
+
+    auto menubar = make<GMenuBar>();
+    auto app_menu = make<GMenu>("Hex Editor");
+    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(GCommonActions::make_quit_action([this](auto&) {
+        if (!request_close())
+            return;
+        GApplication::the().quit(0);
+    }));
+    menubar->add_menu(move(app_menu));
+
+    auto bytes_per_row_menu = make<GMenu>("Bytes Per Row");
+    for (int i = 8; i <= 32; i += 8) {
+        bytes_per_row_menu->add_action(GAction::create(String::number(i), [this, i](auto&) {
+            m_editor->set_bytes_per_row(i);
+            m_editor->update();
+        }));
+    }
+
+    m_goto_action = GAction::create("Go To...", GraphicsBitmap::load_from_file("/res/icons/16x16/go-forward.png"), [this](const GAction&) {
+        auto input_box = GInputBox::construct("Enter offset:", "Go To", this);
+        if (input_box->exec() == GInputBox::ExecOK && !input_box->text_value().is_empty()) {
+            auto valid = false;
+            auto new_offset = input_box->text_value().to_int(valid);
+            if (valid) {
+                m_editor->set_position(new_offset);
+            }
+        }
+    });
+
+    auto edit_menu = make<GMenu>("Edit");
+    edit_menu->add_action(*m_goto_action);
+    edit_menu->add_separator();
+    edit_menu->add_action(GAction::create("Copy Hex", [&](const GAction&) {
+        m_editor->copy_selected_hex_to_clipboard();
+    }));
+    edit_menu->add_action(GAction::create("Copy Text", [&](const GAction&) {
+        m_editor->copy_selected_text_to_clipboard();
+    }));
+    menubar->add_menu(move(edit_menu));
+
+    auto view_menu = make<GMenu>("View");
+    view_menu->add_submenu(move(bytes_per_row_menu));
+    menubar->add_menu(move(view_menu));
+
+    auto help_menu = make<GMenu>("Help");
+    help_menu->add_action(GAction::create("About", [&](const GAction&) {
+        GAboutDialog::show("Hex Editor", load_png("/res/icons/32x32/app-hexeditor.png"), window());
+    }));
+    menubar->add_menu(move(help_menu));
+
+    GApplication::the().set_menubar(move(menubar));
+
+    m_editor->set_focus(true);
+}
+
+HexEditorWidget::~HexEditorWidget()
+{
+}
+
+void HexEditorWidget::set_path(const FileSystemPath& file)
+{
+    m_path = file.string();
+    m_name = file.title();
+    m_extension = file.extension();
+    update_title();
+}
+
+void HexEditorWidget::update_title()
+{
+    StringBuilder builder;
+    builder.append("Hex Editor: ");
+    builder.append(m_path);
+    if (m_document_dirty)
+        builder.append(" (*)");
+    window()->set_title(builder.to_string());
+}
+
+void HexEditorWidget::open_file(const String& path)
+{
+    auto file = CFile::construct(path);
+    if (!file->open(CIODevice::ReadOnly)) {
+        GMessageBox::show(String::format("Opening \"%s\" failed: %s", path.characters(), strerror(errno)), "Error", GMessageBox::Type::Error, GMessageBox::InputType::OK, window());
+        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(FileSystemPath(path));
+}
+
+bool HexEditorWidget::request_close()
+{
+    if (!m_document_dirty)
+        return true;
+    auto result = GMessageBox::show("The file has been modified. Quit without saving?", "Quit without saving?", GMessageBox::Type::Warning, GMessageBox::InputType::OKCancel, window());
+    return result == GMessageBox::ExecOK;
+}

+ 39 - 0
Applications/HexEditor/HexEditorWidget.h

@@ -0,0 +1,39 @@
+#pragma once
+
+#include "HexEditor.h"
+#include <AK/FileSystemPath.h>
+#include <AK/Function.h>
+#include <LibGUI/GApplication.h>
+#include <LibGUI/GTextEditor.h>
+#include <LibGUI/GWidget.h>
+#include <LibGUI/GWindow.h>
+
+class HexEditor;
+class GStatusBar;
+
+class HexEditorWidget final : public GWidget {
+    C_OBJECT(HexEditorWidget)
+public:
+    virtual ~HexEditorWidget() override;
+    void open_file(const String& path);
+    bool request_close();
+
+private:
+    HexEditorWidget();
+    void set_path(const FileSystemPath& file);
+    void update_title();
+
+    RefPtr<HexEditor> m_editor;
+    String m_path;
+    String m_name;
+    String m_extension;
+    RefPtr<GAction> m_new_action;
+    RefPtr<GAction> m_open_action;
+    RefPtr<GAction> m_save_action;
+    RefPtr<GAction> m_save_as_action;
+    RefPtr<GAction> m_goto_action;
+
+    RefPtr<GStatusBar> m_statusbar;
+
+    bool m_document_dirty { false };
+};

+ 10 - 0
Applications/HexEditor/Makefile

@@ -0,0 +1,10 @@
+include ../../Makefile.common
+
+OBJS = \
+	HexEditor.o \
+    HexEditorWidget.o \
+    main.o 
+
+APP = HexEditor
+
+include ../Makefile.common

+ 28 - 0
Applications/HexEditor/main.cpp

@@ -0,0 +1,28 @@
+#include "HexEditorWidget.h"
+#include <LibDraw/PNGLoader.h>
+
+int main(int argc, char** argv)
+{
+    GApplication app(argc, argv);
+
+    auto window = GWindow::construct();
+    window->set_title("Hex Editor");
+    window->set_rect(20, 200, 640, 400);
+
+    auto hex_editor_widget = HexEditorWidget::construct();
+    window->set_main_widget(hex_editor_widget);
+
+    window->on_close_request = [&]() -> GWindow::CloseRequestDecision {
+        if (hex_editor_widget->request_close())
+            return GWindow::CloseRequestDecision::Close;
+        return GWindow::CloseRequestDecision::StayOpen;
+    };
+
+    if (argc >= 2)
+        hex_editor_widget->open_file(argv[1]);
+
+    window->show();
+    window->set_icon(load_png("/res/icons/16x16/app-hexeditor.png"));
+
+    return app.exec();
+}

BIN
Base/res/icons/16x16/app-hexeditor.png


BIN
Base/res/icons/32x32/app-hexeditor.png


+ 2 - 0
Kernel/build-root-filesystem.sh

@@ -79,6 +79,7 @@ cp ../Applications/SystemMonitor/SystemMonitor mnt/bin/SystemMonitor
 cp ../Applications/Taskbar/Taskbar mnt/bin/Taskbar
 cp ../Applications/Terminal/Terminal mnt/bin/Terminal
 cp ../Applications/TextEditor/TextEditor mnt/bin/TextEditor
+cp ../Applications/HexEditor/HexEditor mnt/bin/HexEditor
 cp ../Applications/PaintBrush/PaintBrush mnt/bin/PaintBrush
 cp ../Applications/QuickShow/QuickShow mnt/bin/QuickShow
 cp ../Applications/Piano/Piano mnt/bin/Piano
@@ -121,6 +122,7 @@ ln -s Taskbar mnt/bin/tb
 ln -s VisualBuilder mnt/bin/vb
 ln -s WidgetGallery mnt/bin/wg
 ln -s TextEditor mnt/bin/te
+ln -s HexEditor mnt/bin/he
 ln -s PaintBrush mnt/bin/pb
 ln -s QuickShow mnt/bin/qs
 ln -s Piano mnt/bin/pi

+ 1 - 0
Kernel/makeall.sh

@@ -57,6 +57,7 @@ build_targets="$build_targets ../Applications/SystemMonitor"
 build_targets="$build_targets ../Applications/Taskbar"
 build_targets="$build_targets ../Applications/Terminal"
 build_targets="$build_targets ../Applications/TextEditor"
+build_targets="$build_targets ../Applications/HexEditor"
 build_targets="$build_targets ../Applications/SoundPlayer"
 build_targets="$build_targets ../Applications/Welcome"
 build_targets="$build_targets ../Applications/Help"