diff options
| author | Josh Ferrell <josh@vector35.com> | 2024-05-09 22:53:01 -0400 |
|---|---|---|
| committer | Josh Ferrell <josh@vector35.com> | 2024-05-14 15:11:16 -0400 |
| commit | 08c5286c19fd78fa9d3b9f469a639c7a1013f22e (patch) | |
| tree | 9f8c4dca8a387431d3c9b2209bcdf88f8dfc832a | |
| parent | cb407be11b08c1c427fcf33a49974155e522e14a (diff) | |
History widget
| -rw-r--r-- | binaryninjaapi.h | 43 | ||||
| -rw-r--r-- | binaryninjacore.h | 3 | ||||
| -rw-r--r-- | binaryview.cpp | 33 | ||||
| -rw-r--r-- | python/binaryview.py | 32 | ||||
| -rw-r--r-- | python/filemetadata.py | 37 | ||||
| -rw-r--r-- | python/undo.py | 81 | ||||
| -rw-r--r-- | ui/historyview.h | 92 | ||||
| -rw-r--r-- | ui/notificationsdispatcher.h | 7 | ||||
| -rw-r--r-- | ui/render.h | 10 |
9 files changed, 310 insertions, 28 deletions
diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 791acf07..f3ee14ed 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -3139,6 +3139,10 @@ namespace BinaryNinja { static void TypeArchiveConnectedCallback(void* ctxt, BNBinaryView* data, BNTypeArchive* archive); static void TypeArchiveDisconnectedCallback(void* ctxt, BNBinaryView* data, BNTypeArchive* archive); + static void UndoEntryAddedCallback(void* ctxt, BNBinaryView* data, BNUndoEntry* entry); + static void UndoEntryTakenCallback(void* ctxt, BNBinaryView* data, BNUndoEntry* entry); + static void RedoEntryTakenCallback(void* ctxt, BNBinaryView* data, BNUndoEntry* entry); + public: enum NotificationType : uint64_t @@ -3192,6 +3196,9 @@ namespace BinaryNinja { TypeArchiveDetached = 1ULL << 46, TypeArchiveConnected = 1ULL << 47, TypeArchiveDisconnected = 1ULL << 48, + UndoEntryAdded = 1ULL << 49, + UndoEntryTaken = 1ULL << 50, + RedoEntryTaken = 1ULL << 51, BinaryDataUpdates = DataWritten | DataInserted | DataRemoved, FunctionLifetime = FunctionAdded | FunctionRemoved, @@ -3214,7 +3221,8 @@ namespace BinaryNinja { ExternalLibraryUpdates = ExternalLibraryLifetime | ExternalLibraryUpdated, ExternalLocationLifetime = ExternalLocationAdded | ExternalLocationRemoved, ExternalLocationUpdates = ExternalLocationLifetime | ExternalLocationUpdated, - TypeArchiveUpdates = TypeArchiveAttached | TypeArchiveDetached | TypeArchiveConnected | TypeArchiveDisconnected + TypeArchiveUpdates = TypeArchiveAttached | TypeArchiveDetached | TypeArchiveConnected | TypeArchiveDisconnected, + UndoUpdates = UndoEntryAdded | UndoEntryTaken | RedoEntryTaken }; using NotificationTypes = uint64_t; @@ -3587,6 +3595,39 @@ namespace BinaryNinja { (void)data; (void)archive; } + + /*! This notification is posted whenever an entry is added to undo history + + \param data BinaryView the action was taken on + \param entry UndoEntry + */ + virtual void OnUndoEntryAdded(BinaryView* data, UndoEntry* entry) + { + (void)data; + (void)entry; + } + + /*! This notification is posted whenever an action is undone + + \param data BinaryView the action was taken on + \param entry UndoEntry that was undone + */ + virtual void OnUndoEntryTaken(BinaryView* data, UndoEntry* entry) + { + (void)data; + (void)entry; + } + + /*! This notification is posted whenever an action is redone + + \param data BinaryView the action was taken on + \param entry UndoEntry that was redone + */ + virtual void OnRedoEntryTaken(BinaryView* data, UndoEntry* entry) + { + (void)data; + (void)entry; + } }; /*! diff --git a/binaryninjacore.h b/binaryninjacore.h index 04612d43..f6900c43 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -1568,6 +1568,9 @@ extern "C" void (*typeArchiveDetached)(void* ctxt, BNBinaryView* view, const char* id, const char* path); void (*typeArchiveConnected)(void* ctxt, BNBinaryView* view, BNTypeArchive* archive); void (*typeArchiveDisconnected)(void* ctxt, BNBinaryView* view, BNTypeArchive* archive); + void (*undoEntryAdded)(void* ctxt, BNBinaryView* view, BNUndoEntry* entry); + void (*undoEntryTaken)(void* ctxt, BNBinaryView* view, BNUndoEntry* entry); + void (*redoEntryTaken)(void* ctxt, BNBinaryView* view, BNUndoEntry* entry); } BNBinaryDataNotification; typedef struct BNProjectNotification diff --git a/binaryview.cpp b/binaryview.cpp index 51ee2ee9..6bb485d2 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -496,6 +496,33 @@ void BinaryDataNotification::TypeArchiveDisconnectedCallback(void* ctxt, BNBinar } +void BinaryDataNotification::UndoEntryAddedCallback(void* ctxt, BNBinaryView* data, BNUndoEntry* entry) +{ + BinaryDataNotification* notify = (BinaryDataNotification*)ctxt; + Ref<BinaryView> view = new BinaryView(BNNewViewReference(data)); + Ref<UndoEntry> apiEntry = new UndoEntry(BNNewUndoEntryReference(entry)); + notify->OnUndoEntryAdded(view, apiEntry); +} + + +void BinaryDataNotification::UndoEntryTakenCallback(void* ctxt, BNBinaryView* data, BNUndoEntry* entry) +{ + BinaryDataNotification* notify = (BinaryDataNotification*)ctxt; + Ref<BinaryView> view = new BinaryView(BNNewViewReference(data)); + Ref<UndoEntry> apiEntry = new UndoEntry(BNNewUndoEntryReference(entry)); + notify->OnUndoEntryTaken(view, apiEntry); +} + + +void BinaryDataNotification::RedoEntryTakenCallback(void* ctxt, BNBinaryView* data, BNUndoEntry* entry) +{ + BinaryDataNotification* notify = (BinaryDataNotification*)ctxt; + Ref<BinaryView> view = new BinaryView(BNNewViewReference(data)); + Ref<UndoEntry> apiEntry = new UndoEntry(BNNewUndoEntryReference(entry)); + notify->OnRedoEntryTaken(view, apiEntry); +} + + BinaryDataNotification::BinaryDataNotification() { m_callbacks.context = this; @@ -548,6 +575,9 @@ BinaryDataNotification::BinaryDataNotification() m_callbacks.typeArchiveDetached = TypeArchiveDetachedCallback; m_callbacks.typeArchiveConnected = TypeArchiveConnectedCallback; m_callbacks.typeArchiveDisconnected = TypeArchiveDisconnectedCallback; + m_callbacks.undoEntryAdded = UndoEntryAddedCallback; + m_callbacks.undoEntryTaken = UndoEntryTakenCallback; + m_callbacks.redoEntryTaken = RedoEntryTakenCallback; } @@ -603,6 +633,9 @@ BinaryDataNotification::BinaryDataNotification(NotificationTypes notifications) m_callbacks.typeArchiveDetached = (notifications & NotificationType::TypeArchiveDetached) ? TypeArchiveDetachedCallback : nullptr; m_callbacks.typeArchiveConnected = (notifications & NotificationType::TypeArchiveConnected) ? TypeArchiveConnectedCallback : nullptr; m_callbacks.typeArchiveDisconnected = (notifications & NotificationType::TypeArchiveDisconnected) ? TypeArchiveDisconnectedCallback : nullptr; + m_callbacks.undoEntryAdded = (notifications & NotificationType::UndoEntryAdded) ? UndoEntryAddedCallback : nullptr; + m_callbacks.undoEntryTaken = (notifications & NotificationType::UndoEntryTaken) ? UndoEntryTakenCallback : nullptr; + m_callbacks.redoEntryTaken = (notifications & NotificationType::RedoEntryTaken) ? RedoEntryTakenCallback : nullptr; } diff --git a/python/binaryview.py b/python/binaryview.py index 68eedc54..dee0375e 100644 --- a/python/binaryview.py +++ b/python/binaryview.py @@ -79,6 +79,7 @@ from . import deprecation from . import typecontainer from . import externallibrary from . import project +from . import undo PathType = Union[str, os.PathLike] @@ -667,6 +668,10 @@ class BinaryDataNotificationCallbacks: self._cb.typeArchiveDetached = self._cb.typeArchiveDetached.__class__(self._type_archive_detached) self._cb.typeArchiveConnected = self._cb.typeArchiveConnected.__class__(self._type_archive_connected) self._cb.typeArchiveDisconnected = self._cb.typeArchiveDisconnected.__class__(self._type_archive_disconnected) + + self._cb.undoEntryAdded = self._cb.undoEntryAdded.__class__(self._undo_entry_added) + self._cb.undoEntryTaken = self._cb.undoEntryTaken.__class__(self._undo_entry_taken) + self._cb.redoEntryTaken = self._cb.redoEntryTaken.__class__(self._redo_entry_taken) else: if notify.notifications & NotificationType.NotificationBarrier: self._cb.notificationBarrier = self._cb.notificationBarrier.__class__(self._notification_barrier) @@ -756,6 +761,13 @@ class BinaryDataNotificationCallbacks: if notify.notifications & NotificationType.TypeArchiveDisconnected: self._cb.typeArchiveDisconnected = self._cb.typeArchiveDisconnected.__class__(self._type_archive_disconnected) + if notify.notifications & NotificationType.UndoEntryAdded: + self._cb.undoEntryAdded = self._cb.undoEntryAdded.__class__(self._undo_entry_added) + if notify.notifications & NotificationType.UndoEntryTaken: + self._cb.undoEntryTaken = self._cb.undoEntryTaken.__class__(self._undo_entry_taken) + if notify.notifications & NotificationType.RedoEntryTaken: + self._cb.redoEntryTaken = self._cb.redoEntryTaken.__class__(self._redo_entry_taken) + def _register(self) -> None: core.BNRegisterDataNotification(self._view.handle, self._cb) @@ -1152,6 +1164,26 @@ class BinaryDataNotificationCallbacks: except: log_error(traceback.format_exc()) + def _undo_entry_added(self, ctxt, view: core.BNBinaryView, archive: core.BNUndoEntry): + try: + py_entry = undo.UndoEntry(handle=core.BNNewUndoEntryReference(archive)) + self._notify.undo_entry_added(self._view, py_entry) + except: + log_error(traceback.format_exc()) + + def _undo_entry_taken(self, ctxt, view: core.BNBinaryView, archive: core.BNUndoEntry): + try: + py_entry = undo.UndoEntry(handle=core.BNNewUndoEntryReference(archive)) + self._notify.undo_entry_taken(self._view, py_entry) + except: + log_error(traceback.format_exc()) + + def _redo_entry_taken(self, ctxt, view: core.BNBinaryView, archive: core.BNUndoEntry): + try: + py_entry = undo.UndoEntry(handle=core.BNNewUndoEntryReference(archive)) + self._notify.redo_entry_taken(self._view, py_entry) + except: + log_error(traceback.format_exc()) @property def view(self) -> 'BinaryView': diff --git a/python/filemetadata.py b/python/filemetadata.py index e0222fd2..a78f548b 100644 --- a/python/filemetadata.py +++ b/python/filemetadata.py @@ -32,6 +32,7 @@ from . import binaryview from . import database from . import deprecation from . import project +from . import undo ProgressFuncType = Callable[[int, int], bool] ViewName = str @@ -139,7 +140,6 @@ class FileMetadata: self._nav: Optional[NavigationHandler] = None assert _handle is not None self.handle = _handle - self._previous_undos = [] def __repr__(self): return f"<FileMetadata: {self.filename}>" @@ -384,7 +384,6 @@ class FileMetadata: >>> """ id = core.BNBeginUndoActions(self.handle, anonymous_allowed) - self._previous_undos.append(id) return id def commit_undo_actions(self, id: Optional[str] = None) -> None: @@ -516,6 +515,40 @@ class FileMetadata: """ core.BNRedo(self.handle) + @property + def undo_entries(self) -> List['undo.UndoEntry']: + count = ctypes.c_ulonglong() + + entries = core.BNGetUndoEntries(self.handle, count) + assert entries is not None, "core.BNGetUndoEntries returned None" + + result = [] + try: + for i in range(0, count.value): + tag_handle = core.BNNewUndoEntryReference(entries[i]) + assert tag_handle is not None, "core.BNNewUndoEntryReference returned None" + result.append(undo.UndoEntry(tag_handle)) + return result + finally: + core.BNFreeUndoEntryList(entries, count.value) + + @property + def redo_entries(self) -> List['undo.UndoEntry']: + count = ctypes.c_ulonglong() + + entries = core.BNGetRedoEntries(self.handle, count) + assert entries is not None, "core.BNGetRedoEntries returned None" + + result = [] + try: + for i in range(0, count.value): + tag_handle = core.BNNewUndoEntryReference(entries[i]) + assert tag_handle is not None, "core.BNNewUndoEntryReference returned None" + result.append(undo.UndoEntry(tag_handle)) + return result + finally: + core.BNFreeUndoEntryList(entries, count.value) + def navigate(self, view: ViewName, offset: int) -> bool: """ ``navigate`` navigates the UI to the specified virtual address diff --git a/python/undo.py b/python/undo.py new file mode 100644 index 00000000..4a0a7124 --- /dev/null +++ b/python/undo.py @@ -0,0 +1,81 @@ +# Copyright (c) 2015-2024 Vector 35 Inc +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. + + +import ctypes +from typing import List + +from . import _binaryninjacore as core + + +class UndoAction: + """ + Class representing an action in an UndoEntry + """ + def __init__(self, handle: core.BNUndoActionHandle): + self._handle = handle + + def __del__(self): + if core is not None: + core.BNFreeUndoAction(self._handle) + + def __repr__(self) -> str: + return f"<UndoAction: {self}>" + + def __str__(self): + return self.summary_text + + @property + def summary_text(self) -> str: + return core.BNUndoActionGetSummaryText(self._handle) # type: ignore + +class UndoEntry: + """ + Class representing an entry in undo/redo history + """ + def __init__(self, handle: core.BNUndoEntryHandle): + self._handle = handle + + def __del__(self): + if core is not None: + core.BNFreeUndoEntry(self._handle) + + @property + def actions(self) -> List[UndoAction]: + """ + Get the list of actions in this entry + + :return: List of UndoAction in this UndoEntry + """ + + count = ctypes.c_size_t() + value = core.BNUndoEntryGetActions(self._handle, count) + if value is None: + raise Exception("Failed to get list undo actions") + result = [] + try: + for i in range(count.value): + folder_handle = core.BNNewUndoActionReference(value[i]) + if folder_handle is None: + raise Exception("core.BNNewUndoActionReference returned None") + result.append(UndoAction(folder_handle)) + return result + finally: + core.BNFreeUndoActionList(value, count.value) diff --git a/ui/historyview.h b/ui/historyview.h index 06f6561d..4f747fa3 100644 --- a/ui/historyview.h +++ b/ui/historyview.h @@ -1,44 +1,98 @@ #pragma once -#include "filter.h" +#include "render.h" #include "sidebarwidget.h" +#include <qlistview.h> #include <qsortfilterproxymodel.h> #include <qstandarditemmodel.h> -#include <qtreeview.h> +#include <qstyleditemdelegate.h> -class BINARYNINJAUIAPI HistorySidebarWidget : public SidebarWidget, public FilterTarget +enum class HistoryOption +{ + ShowDates, +}; + + +class BINARYNINJAUIAPI HistoryEntryItemModel : public QAbstractItemModel, public BinaryNinja::BinaryDataNotification, public UIContextNotification +{ + std::vector<UndoEntryRef> m_undoEntries; + std::vector<UndoEntryRef> m_redoEntries; + + FileMetadataRef m_file; + BinaryViewRef m_data; + std::unordered_set<HistoryOption> m_options; + QSettings m_settings; + + UndoEntryRef entryForRow(int row) const; + + QString getSettingKeyForOption(HistoryOption option) const; + + virtual void OnUndoEntryAdded(BinaryNinja::BinaryView* data, BinaryNinja::UndoEntry* entry) override; + virtual void OnUndoEntryTaken(BinaryNinja::BinaryView* data, BinaryNinja::UndoEntry* entry) override; + virtual void OnRedoEntryTaken(BinaryNinja::BinaryView* data, BinaryNinja::UndoEntry* entry) override; + + virtual void OnAfterSaveFile(UIContext* context, FileContext* file, ViewFrame* frame) override; + + void hardReload(); + + public: + HistoryEntryItemModel(QWidget* parent, BinaryViewRef data); + ~HistoryEntryItemModel(); + + virtual QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + virtual QModelIndex parent(const QModelIndex& child) const override; + + virtual int rowCount(const QModelIndex& parent = QModelIndex()) const override; + virtual int columnCount(const QModelIndex& parent = QModelIndex()) const override; + + virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + void toggleOption(HistoryOption option); + bool isOptionSet(HistoryOption option); +}; + + +class BINARYNINJAUIAPI HistoryEntryItemDelegate : public QStyledItemDelegate { Q_OBJECT - QTreeView* m_tree; - QStandardItemModel* m_model; - QSortFilterProxyModel* m_proxyModel; + + QFont m_font; + int m_baseline, m_charWidth, m_charHeight, m_charOffset; + + RenderContext m_render; + + public: + HistoryEntryItemDelegate(QWidget* parent = nullptr); + + void updateFonts(); + + virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; +}; + + +class BINARYNINJAUIAPI HistorySidebarWidget : public SidebarWidget +{ + Q_OBJECT + QListView* m_entryList; + HistoryEntryItemModel* m_model; + HistoryEntryItemDelegate* m_itemDelegate; QWidget* m_header; - FilteredView* m_libFilter; BinaryViewRef m_data; - ContextMenuManager* m_contextMenuManager; - Menu m_contextMenu; bool m_updating = false; - - std::unordered_map<std::string, QPersistentModelIndex> m_idIndices; - - virtual void scrollToFirstItem() override; - virtual void scrollToCurrentItem() override; - virtual void selectFirstItem() override; - virtual void activateFirstItem() override; - virtual void setFilter(const std::string& filter) override; + bool m_atBottom = true; virtual void contextMenuEvent(QContextMenuEvent*) override; void itemDoubleClicked(const QModelIndex& index); + void scrollBarValueChanged(int value); void scrollBarRangeChanged(int min, int max); - void populateTree(); + void resetToSelectedEntry(std::function<bool(size_t, size_t)> progress); public: HistorySidebarWidget(BinaryViewRef data); - + ~HistorySidebarWidget(); void notifyFontChanged() override; QWidget* headerWidget() override { return m_header; } }; diff --git a/ui/notificationsdispatcher.h b/ui/notificationsdispatcher.h index a65e2dac..f3b3a7bd 100644 --- a/ui/notificationsdispatcher.h +++ b/ui/notificationsdispatcher.h @@ -127,7 +127,7 @@ private: std::unique_ptr<SymbolInfo> m_symbolInfo; std::variant<std::monostate, BinaryDataChangeInfo, FunctionRef, BinaryNinja::DataVariable, TagTypeRef, BinaryNinja::TagReference, StringInfo, TypeChangeInfo, SegmentRef, SectionRef, ComponentInfo, - ExternalLibraryRef, ExternalLocationRef, TypeArchiveInfo, TypeArchiveRef> m_object; + ExternalLibraryRef, ExternalLocationRef, TypeArchiveInfo, TypeArchiveRef, UndoEntryRef> m_object; public: NotificationEvent(NotificationType source): m_source(source) { } @@ -146,6 +146,7 @@ public: NotificationEvent(NotificationType source, BinaryNinja::ExternalLocation* location): m_source(source), m_object(location) { } NotificationEvent(NotificationType source, TypeArchiveInfo&& typeArchiveInfo): m_source(source), m_object(std::move(typeArchiveInfo)) { } NotificationEvent(NotificationType source, BinaryNinja::TypeArchive* archive): m_source(source), m_object(archive) { } + NotificationEvent(NotificationType source, BinaryNinja::UndoEntry* entry): m_source(source), m_object(entry) { } void cacheSymbolInfo(); SymbolInfo* getSymbolInfo() const { return m_symbolInfo.get(); } @@ -297,6 +298,10 @@ public: void OnTypeArchiveDetached(BinaryNinja::BinaryView* data, const std::string& id, const std::string& path) override; void OnTypeArchiveConnected(BinaryNinja::BinaryView* data, BinaryNinja::TypeArchive* archive) override; void OnTypeArchiveDisconnected(BinaryNinja::BinaryView* data, BinaryNinja::TypeArchive* archive) override; + + void OnUndoEntryAdded(BinaryNinja::BinaryView* data, BinaryNinja::UndoEntry* entry) override; + void OnUndoEntryTaken(BinaryNinja::BinaryView* data, BinaryNinja::UndoEntry* entry) override; + void OnRedoEntryTaken(BinaryNinja::BinaryView* data, BinaryNinja::UndoEntry* entry) override; }; diff --git a/ui/render.h b/ui/render.h index 8dc0d158..39393e4c 100644 --- a/ui/render.h +++ b/ui/render.h @@ -112,7 +112,7 @@ class BINARYNINJAUIAPI RenderContext size_t tokenIndex, const std::vector<BinaryNinja::InstructionTextToken>& tokens); HighlightTokenState getHighlightTokenForTextToken(const BinaryNinja::InstructionTextToken& token); - void drawText(QPainter& p, int x, int y, QColor color, const QString& text); + void drawText(QPainter& p, int x, int y, QColor color, const QString& text) const; void drawUnderlinedText(QPainter& p, int x, int y, QColor color, const QString& text); void drawSeparatorLine(QPainter& p, QColor top, QColor bottom, QColor line, const QRect& rect); @@ -120,14 +120,14 @@ class BINARYNINJAUIAPI RenderContext void drawLinearDisassemblyLineBackground( QPainter& p, BNLinearDisassemblyLineType type, const QRect& rect, const QRect& dirtyRect, int gutterWidth); - void drawDisassemblyLine(QPainter& p, int left, int top, + int drawDisassemblyLine(QPainter& p, int left, int top, const std::vector<BinaryNinja::InstructionTextToken>& tokens, HighlightTokenState& highlight, - bool highlightOnly = false); + bool highlightOnly = false) const; void drawHexEditorLine(QPainter& p, int left, int top, const HexEditorHighlightState& highlight, BinaryViewRef view, uint64_t lineStartAddr, size_t cols, size_t firstCol, size_t count, bool cursorVisible, bool cursorAscii, size_t cursorPos, bool byteCursor); - QFont getFont() { return m_fontParams.getFont(); } - QFont getEmojiFont() { return m_fontParams.getEmojiFont(); } + QFont getFont() const { return m_fontParams.getFont(); } + QFont getEmojiFont() const { return m_fontParams.getEmojiFont(); } void setFont(const QFont& font); }; |
