Fix stuff.

This commit is contained in:
Nicholas Johnson 2024-11-02 19:19:53 -04:00
parent 71d6d1ab53
commit b44521cd6f
25 changed files with 2706 additions and 1047 deletions

View File

@ -11,6 +11,8 @@ CONFIG += c++17
SOURCES += \ SOURCES += \
blockvalue.cpp \ blockvalue.cpp \
deleteruledialog.cpp \ deleteruledialog.cpp \
hexeslogger.cpp \
hexstream.cpp \
hexviewer.cpp \ hexviewer.cpp \
main.cpp \ main.cpp \
mainwindow.cpp \ mainwindow.cpp \
@ -22,6 +24,8 @@ SOURCES += \
HEADERS += \ HEADERS += \
blockvalue.h \ blockvalue.h \
deleteruledialog.h \ deleteruledialog.h \
hexeslogger.h \
hexstream.h \
hexviewer.h \ hexviewer.h \
mainwindow.h \ mainwindow.h \
rule.h \ rule.h \

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject> <!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 14.0.0, 2024-10-24T20:49:25. --> <!-- Written by QtCreator 14.0.0, 2024-10-30T21:06:26. -->
<qtcreator> <qtcreator>
<data> <data>
<variable>EnvironmentId</variable> <variable>EnvironmentId</variable>
@ -78,7 +78,7 @@
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop Qt 6.7.2 MSVC2019 64bit</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop Qt 6.7.2 MSVC2019 64bit</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop Qt 6.7.2 MSVC2019 64bit</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop Qt 6.7.2 MSVC2019 64bit</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">qt.qt6.672.win64_msvc2019_64_kit</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">qt.qt6.672.win64_msvc2019_64_kit</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value> <value type="qlonglong" key="ProjectExplorer.Target.ActiveBuildConfiguration">1</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value> <value type="qlonglong" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value> <value type="qlonglong" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0"> <valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
@ -232,7 +232,7 @@
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value> <value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseLibrarySearchPath">true</value> <value type="bool" key="RunConfiguration.UseLibrarySearchPath">true</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value> <value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
<value type="QString" key="RunConfiguration.WorkingDirectory.default">C:/Ext/Projects/Qt/Hexes/build/Desktop_Qt_6_7_2_MSVC2019_64bit-Debug</value> <value type="QString" key="RunConfiguration.WorkingDirectory.default">C:/Ext/Projects/Qt/Hexes/build/Desktop_Qt_6_7_2_MSVC2019_64bit-Release</value>
</valuemap> </valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.RunConfigurationCount">1</value> <value type="qlonglong" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap> </valuemap>

View File

@ -4,5 +4,8 @@
</qresource> </qresource>
<qresource prefix="/icons"> <qresource prefix="/icons">
<file>delete.png</file> <file>delete.png</file>
<file>skip.png</file>
<file>general.png</file>
<file>repeat.png</file>
</qresource> </qresource>
</RCC> </RCC>

View File

@ -1,32 +1,123 @@
#include "blockvalue.h" #include "blockvalue.h"
BlockValue::BlockValue(QObject *parent) /*
: QObject{parent}, * Block Value default constructor
pBlockType{BLOCK_TYPE_INT8}, */
pName{""}, BlockValue::BlockValue() {
pData{} { pName = "";
pBlockType = BLOCK_TYPE_NONE;
pData = QVariant::fromValue(0);
} }
BlockValue::BlockValue(const BlockValue &blockVal) { /*
pBlockType = blockVal.BlockType(); * Block Value copy constructor
pName = blockVal.Name(); */
pData = blockVal.Value(); BlockValue::BlockValue(const BlockValue &aBlockVal) {
pName = aBlockVal.Name();
pBlockType = aBlockVal.BlockType();
pData = aBlockVal.ToVariant();
} }
BlockValue &BlockValue::operator=(const BlockValue &blockVal) { /*
if (this == &blockVal) { * Block Value constructor w/ name
*/
BlockValue::BlockValue(const QString aName) {
pName = aName;
pBlockType = BLOCK_TYPE_NONE;
pData = QVariant::fromValue(0);
}
/*
* Block Value constructor w/ name & int8
*/
BlockValue::BlockValue(const QString aName, qint8 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_INT8;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & uint8
*/
BlockValue::BlockValue(const QString aName, quint8 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_UINT8;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & int16
*/
BlockValue::BlockValue(const QString aName, qint16 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_INT16;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & uint16
*/
BlockValue::BlockValue(const QString aName, quint16 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_UINT16;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & int32
*/
BlockValue::BlockValue(const QString aName, qint32 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_INT32;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & uint32
*/
BlockValue::BlockValue(const QString aName, quint32 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_UINT32;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & int64
*/
BlockValue::BlockValue(const QString aName, qint64 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_INT64;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value constructor w/ name & uint64
*/
BlockValue::BlockValue(const QString aName, quint64 aVal) {
pName = aName;
pBlockType = BLOCK_TYPE_UINT64;
pData = QVariant::fromValue(aVal);
}
/*
* Block Value = operator implementation
*/
BlockValue &BlockValue::operator=(const BlockValue &aBlockVal) {
if (this == &aBlockVal) {
return *this; return *this;
} }
pBlockType = blockVal.BlockType(); pBlockType = aBlockVal.BlockType();
pName = blockVal.Name(); pName = aBlockVal.Name();
pData = blockVal.Value(); pData = aBlockVal.ToVariant();
return *this; return *this;
} }
int BlockValue::ValueToInt() { /*
* Return Block Value as an integer
*/
int BlockValue::ToInt() const {
switch ((int)pBlockType) { switch ((int)pBlockType) {
case 0: // BLOCK_TYPE_INT8 case 0: // BLOCK_TYPE_INT8
return static_cast<int>(pData.value<qint8>()); return static_cast<int>(pData.value<qint8>());
@ -56,62 +147,44 @@ int BlockValue::ValueToInt() {
return -1; return -1;
} }
void BlockValue::SetName(QString name) { /*
pName = name; * Return Block Value as a string
*/
QString BlockValue::ToString() const {
return QString::number(ToInt());
} }
/*
* Set Block Value type (uint8, int16, etc)
*/
QVariant BlockValue::ToVariant() const {
return pData;
}
/*
* Set Block Value's name
*/
void BlockValue::SetName(const QString aName) {
pName = aName;
}
/*
* Returns Block Value's name
*/
QString BlockValue::Name() const { QString BlockValue::Name() const {
return pName; return pName;
} }
void BlockValue::SetBlockType(BLOCK_TYPE blockType) { /*
pBlockType = blockType; * Set Block Balue type (uint8, int16, etc)
*/
void BlockValue::SetBlockType(BLOCK_TYPE aBlockType) {
pBlockType = aBlockType;
} }
/*
* Get Block Balue type (uint8, int16, etc)
*/
BLOCK_TYPE BlockValue::BlockType() const { BLOCK_TYPE BlockValue::BlockType() const {
return pBlockType; return pBlockType;
} }
void BlockValue::SetValue(qint8 val) {
pBlockType = BLOCK_TYPE_INT8;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(quint8 val) {
pBlockType = BLOCK_TYPE_UINT8;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(qint16 val) {
pBlockType = BLOCK_TYPE_INT16;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(quint16 val) {
pBlockType = BLOCK_TYPE_UINT16;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(qint32 val) {
pBlockType = BLOCK_TYPE_INT32;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(quint32 val) {
pBlockType = BLOCK_TYPE_UINT32;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(qint64 val) {
pBlockType = BLOCK_TYPE_INT64;
pData = QVariant::fromValue(val);
}
void BlockValue::SetValue(quint64 val) {
pBlockType = BLOCK_TYPE_UINT64;
pData = QVariant::fromValue(val);
}
QVariant BlockValue::Value() const {
return pData;
}

View File

@ -4,6 +4,12 @@
#include <QObject> #include <QObject>
#include <QVariant> #include <QVariant>
/*
* BLOCK_TYPE enum
*
* Value types that the BlockVlaue class can
* ingest and convert to/from.
*/
enum BLOCK_TYPE { enum BLOCK_TYPE {
BLOCK_TYPE_NONE = 0, BLOCK_TYPE_NONE = 0,
BLOCK_TYPE_INT8 = 1, BLOCK_TYPE_INT8 = 1,
@ -16,34 +22,47 @@ enum BLOCK_TYPE {
BLOCK_TYPE_UINT64 = 8, BLOCK_TYPE_UINT64 = 8,
}; };
class BlockValue : public QObject /*
* BlockValue class
*
* Represents a variable value resulting from
* parsing a block of data from the input.
*
* Constructed preferrably with a name and value.
*/
class BlockValue
{ {
Q_OBJECT
public:
explicit BlockValue(QObject *parent = nullptr);
BlockValue(const BlockValue &blockVal);
BlockValue &operator=(const BlockValue &blockVal); public: /*** PUBLIC MEMBERS ***/
/* Block Value Constructors */
BlockValue(); // Default
BlockValue(const BlockValue &aBlockVal); // Copy
BlockValue(const QString aName); // Name
BlockValue(const QString aName, qint8 aVal); // Name + int8
BlockValue(const QString aName, quint8 aVal); // Name + uint8
BlockValue(const QString aName, qint16 aVal); // Name + int16
BlockValue(const QString aName, quint16 aVal); // Name + uint16
BlockValue(const QString aName, qint32 aVal); // Name + int32
BlockValue(const QString aName, quint32 aVal); // Name + uint32
BlockValue(const QString aName, qint64 aVal); // Name + int64
BlockValue(const QString aName, quint64 aVal); // Name + uint64
void SetName(QString name); /* Block Value Operators */
QString Name() const; BlockValue &operator=(const BlockValue &aBlockVal); // = operator
void SetBlockType(BLOCK_TYPE blockType); /* Setters and Getters */
BLOCK_TYPE BlockType() const; void SetName(const QString aName); // Set Name
QString Name() const; // Get Name
void SetBlockType(BLOCK_TYPE aBlockType); // Set Block Value Type
BLOCK_TYPE BlockType() const; // Get Block Value Type
void SetValue(qint8 val); /* Data Access Methods */
void SetValue(quint8 val); int ToInt() const; // Convert to integer
void SetValue(qint16 val); QString ToString() const; // Convert to string
void SetValue(quint16 val); QVariant ToVariant() const; // Return as raw data
void SetValue(qint32 val);
void SetValue(quint32 val);
void SetValue(qint64 val);
void SetValue(quint64 val);
QVariant Value() const; private: /*** PRIVATE MEMBERS ***/
int ValueToInt();
private:
QString pName; QString pName;
BLOCK_TYPE pBlockType; BLOCK_TYPE pBlockType;
QVariant pData; QVariant pData;

BIN
general.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

43
hexeslogger.cpp Normal file
View File

@ -0,0 +1,43 @@
#include "hexeslogger.h"
HexesLogger *HexesLogger::pInstance = nullptr;
QWidget *HexesLogger::pParent = nullptr;
void HexesLogger::MakeInstance(QWidget *aParent) {
pInstance = new HexesLogger(aParent);
}
void HexesLogger::HexesInfo(const QString pInfoMsg) {
QMessageBox::information(pParent,
HEXES_INFO_TITLE,
QString(HEXES_INFO_TEMPLATE).arg(pInfoMsg));
}
void HexesLogger::HexesError(int pErrorId, const QString pErrorMsg) {
QString errorIdString = QString::number(pErrorId);
QMessageBox::warning(pParent,
HEXES_ERROR_TITLE,
QString(HEXES_ERROR_TEMPLATE).arg(errorIdString, pErrorMsg));
}
void HexesLogger::HexesFatal(int pFatalId, const QString pFatalMsg) {
QString fatalIdString = QString::number(pFatalId);
QMessageBox::critical(pParent,
HEXES_FATAL_TITLE,
QString(HEXES_FATAL_TEMPLATE).arg(fatalIdString, pFatalMsg));
}
void HexesLogger::DeleteInstance() {
delete pInstance;
}
HexesLogger::HexesLogger(QWidget *aParent) {
pParent = aParent;
}
HexesLogger* HexesLogger::Instance() {
if (!pInstance) {
MakeInstance();
}
return pInstance;
}

32
hexeslogger.h Normal file
View File

@ -0,0 +1,32 @@
#ifndef HEXESLOGGER_H
#define HEXESLOGGER_H
#include <QWidget>
#include <QMessageBox>
const QString HEXES_INFO_TITLE = "Hexes Info Message";
const QString HEXES_ERROR_TITLE = "Hexes Error Message";
const QString HEXES_FATAL_TITLE = "Hexes Fatal Message";
const QString HEXES_INFO_TEMPLATE = "Hexes Info: %1";
const QString HEXES_ERROR_TEMPLATE = "Hexes Error [%1]: %2";
const QString HEXES_FATAL_TEMPLATE = "Hexes Fatal [%1]: %2";
class HexesLogger
{
public:
static HexesLogger* Instance();
static void DeleteInstance();
static void MakeInstance(QWidget *aParent = nullptr);
static void HexesInfo(const QString pInfoMsg);
static void HexesError(int pErrorId, const QString pErrorMsg);
static void HexesFatal(int pFatalId, const QString pFatalMsg);
private:
HexesLogger(QWidget *aParent = nullptr);
static QWidget *pParent;
static HexesLogger *pInstance;
};
#endif // HEXESLOGGER_H

142
hexstream.cpp Normal file
View File

@ -0,0 +1,142 @@
#include "hexstream.h"
HexStream::HexStream()
: QDataStream() {
}
HexStream::HexStream(QIODevice *aIODevice)
: QDataStream(aIODevice) {
}
HexStream::HexStream(QByteArray *aData, OpenMode aFlags)
: QDataStream(aData, aFlags) {
}
HexStream::HexStream(const QByteArray &aData)
: QDataStream(aData) {
}
HexStream::~HexStream() {
}
void HexStream::SetHexByteOrder(BYTE_ORDER aByteOrder) {
pByteOrder = aByteOrder;
if (aByteOrder == BYTE_ORDER_BE) {
setByteOrder(BigEndian);
} else {
setByteOrder(BigEndian);
}
}
BYTE_ORDER HexStream::HexByteOrder() {
return pByteOrder;
}
void HexStream::ParseSkip(const Rule &aRule) {
// Skip hex bytes if valid
skipRawData(aRule.Length());
}
void HexStream::ParseSkip(int aSkipLen) {
// Skip hex 'aSkipLen' bytes
skipRawData(aSkipLen);
}
BlockValue HexStream::ParseInt8(const Rule &aRule) {
qint8 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseUInt8(const Rule &aRule) {
quint8 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseInt16(const Rule &aRule) {
qint16 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseUInt16(const Rule &aRule) {
quint16 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseInt32(const Rule &aRule) {
qint32 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseUInt32(const Rule &aRule) {
quint32 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseInt64(const Rule &aRule) {
qint64 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseUInt64(const Rule &aRule) {
quint64 val;
operator >>(val);
return BlockValue(aRule.Name(), val);
}
BlockValue HexStream::ParseRule(const Rule &aRule) {
if (!aRule) {
HexesLogger::HexesError(50, "Attempted to parse null rule!");
return BlockValue("INVALID");
}
if (aRule.Name().isEmpty()) {
HexesLogger::HexesError(55, "Attempted to parse rule w/ null name!");
return BlockValue("INVALID");
}
if (aRule.Length() < 0) {
HexesLogger::HexesError(60, "Attempted to rule w/ invalid length!");
return BlockValue(aRule.Name());
}
switch ((int)aRule.Type()) {
case 1: // Skip
ParseSkip(aRule);
break;
case 2: // int8
return ParseInt8(aRule);
break;
case 3: // uint8
return ParseUInt8(aRule);
break;
case 4: // int16
return ParseInt16(aRule);
break;
case 5: // uint16
return ParseUInt16(aRule);
break;
case 6: // int32
return ParseInt32(aRule);
break;
case 7: // uint32
return ParseUInt32(aRule);
break;
case 8: // int64
return ParseInt64(aRule);
break;
case 9: // uint64
return ParseUInt64(aRule);
break;
}
return BlockValue(aRule.Name());
}

38
hexstream.h Normal file
View File

@ -0,0 +1,38 @@
#ifndef HEXSTREAM_H
#define HEXSTREAM_H
#include "rule.h"
#include "blockvalue.h"
#include "hexeslogger.h"
#include <QDataStream>
class HexStream : public QDataStream
{
public:
HexStream();
explicit HexStream(QIODevice *aIODevice);
HexStream(QByteArray *aData, OpenMode aFlags);
HexStream(const QByteArray &aData);
~HexStream();
void SetHexByteOrder(BYTE_ORDER aByteOrder);
BYTE_ORDER HexByteOrder();
void ParseSkip(const Rule &aRule);
void ParseSkip(int aSkipLen);
BlockValue ParseInt8(const Rule &aRule);
BlockValue ParseUInt8(const Rule &aRule);
BlockValue ParseInt16(const Rule &aRule);
BlockValue ParseUInt16(const Rule &aRule);
BlockValue ParseInt32(const Rule &aRule);
BlockValue ParseUInt32(const Rule &aRule);
BlockValue ParseInt64(const Rule &aRule);
BlockValue ParseUInt64(const Rule &aRule);
BlockValue ParseRule(const Rule &aRule);
private:
BYTE_ORDER pByteOrder;
};
#endif // HEXSTREAM_H

View File

@ -1,147 +1,217 @@
#include "hexviewer.h" #include "hexviewer.h"
/*
* HexViewer Constructor
*/
HexViewer::HexViewer(QWidget *parent) HexViewer::HexViewer(QWidget *parent)
: QAbstractScrollArea(parent) { : QAbstractScrollArea(parent)
pText = ""; , pText("")
pHex = ""; , pHex("")
pFileName = ""; , pFileName("")
pViewRect = QRectF(0, 0, 800, 557); , pViewRect(0, 0, 800, 557)
pBlinkTimer = new QTimer(this); , pBlinkTimer(new QTimer(this))
pRules = QQueue<Rule>(); , pRules(QQueue<Rule>())
pScrollValue = 0; , pScrollValue(0)
pVars = QMap<QString, BlockValue>(); , pVars(QMap<QString, BlockValue>())
, pFontMetrics(QFontMetrics(QFont("CommitMono", 10)))
, pFileDir("C:/"){
// Set font to monospaced option
setFont(QFont("CommitMono", 10)); setFont(QFont("CommitMono", 10));
// Initialize scroll bar and cursor timer
qRegisterMetaType<Rule>("Rule"); pInitScrollBar();
qRegisterMetaType<QQueue<Rule>>("QQueue<Rule>"); pInitCursorTimer();
//qRegisterMetaTypeStreamOperators<QQueue<Rule>>("QQueue<Rule>");
verticalScrollBar()->setSingleStep(45);
verticalScrollBar()->setPageStep(45);
connect(verticalScrollBar(), &QScrollBar::valueChanged, this, [this](int value) {
pScrollValue = value;
pSeekFile();
});
connect(pBlinkTimer, &QTimer::timeout, this, [this]() {
pCursorVisible = !pCursorVisible;
update(); // Trigger update to show/hide cursor
});
pBlinkTimer->start(500); // Blinking interval
} }
/*
* HexViewer Destructor
*/
HexViewer::~HexViewer() { HexViewer::~HexViewer() {
delete pBlinkTimer; delete pBlinkTimer;
} }
void HexViewer::SetFileName(const QString fileName) { /*
pFileName = fileName; * Scroll Bar Initialization
*/
void HexViewer::pInitScrollBar() {
verticalScrollBar()->setSingleStep(DEFAULT_SINGLE_STEP);
verticalScrollBar()->setPageStep(DEFAULT_PAGE_STEP);
connect(verticalScrollBar(), &QScrollBar::valueChanged,
this, &HexViewer::pScrollValueChanged);
}
pFile.setFileName(pFileName); /*
* Cursor Blink Timer Initialization
*/
void HexViewer::pInitCursorTimer() {
connect(pBlinkTimer, &QTimer::timeout,
this, &HexViewer::pBlinkCursor);
pBlinkTimer->start(500); // Blinking interval
}
/*
* Set filename of hex file we want to open
*/
void HexViewer::SetFileName(const QString fileName) {
if (fileName.isEmpty()) { return; }
// Set file name & open for read-only
pFile.setFileName(pFileName = fileName);
if (!pFile.open(QIODevice::ReadOnly)) { if (!pFile.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to open " << pFileName; const QString errorMsg("Failed to open " + pFileName);
} else { HexesLogger::HexesError(20, errorMsg);
qDebug() << "Opened " << pFileName; return;
} }
// Re-search the file contents to display
pSeekFile(); pSeekFile();
} }
/*
* Add a rule to our local queue
*/
void HexViewer::AddRule(const Rule rule) { void HexViewer::AddRule(const Rule rule) {
pRules.enqueue(rule); pRules.enqueue(rule);
// Refresh rules and view
emit RuleNamesChanged(RuleNames()); pRefreshRules();
RunRules();
} }
/*
* Adds multiple rules to our local queue
*/
void HexViewer::AddRules(const QVector<Rule> rules) { void HexViewer::AddRules(const QVector<Rule> rules) {
if (rules.isEmpty()) { return; }
// Add rules from incoming queue
for (int i = 0; i < rules.size(); i++) { for (int i = 0; i < rules.size(); i++) {
pRules.enqueue(rules[i]); pRules.enqueue(rules[i]);
} }
// Refresh rules and view
emit RuleNamesChanged(RuleNames()); pRefreshRules();
RunRules();
} }
/*
* Remove a rule from our local queue
*/
void HexViewer::DeleteRule(const Rule rule) { void HexViewer::DeleteRule(const Rule rule) {
if (!pRules.contains(rule)) { return; } if (!pRules.contains(rule)) { return; }
if (pRules.size() == 0) { return; } if (pRules.size() == 0) { return; }
// Search for and remove rule
for (int i = 0; i < pRules.size(); i++) { for (int i = 0; i < pRules.size(); i++) {
Rule currentRule = pRules.dequeue(); Rule currentRule = pRules.dequeue();
if (currentRule != rule) { if (currentRule != rule) {
pRules.enqueue(currentRule); pRules.enqueue(currentRule);
} }
} }
// Refresh rules and view
emit RuleNamesChanged(RuleNames()); pRefreshRules();
update();
} }
/*
* Remove a rule, by name, from our local queue
*/
void HexViewer::DeleteRuleByName(const QString ruleName) { void HexViewer::DeleteRuleByName(const QString ruleName) {
if (pRules.size() == 0) { return; } if (pRules.size() == 0) { return; }
// Search for and remove rule
for (int i = 0; i < pRules.size(); i++) { for (int i = 0; i < pRules.size(); i++) {
Rule currentRule = pRules.dequeue(); Rule currentRule = pRules.dequeue();
if (currentRule.Name() != ruleName) { if (currentRule.Name() != ruleName) {
pRules.enqueue(currentRule); pRules.enqueue(currentRule);
} }
} }
// Refresh rules and view
emit RuleNamesChanged(RuleNames()); pRefreshRules();
update();
} }
/*
* Pop/dequeue a rule from our local queue
*/
void HexViewer::PopRule() { void HexViewer::PopRule() {
if (pRules.isEmpty()) { return; } if (pRules.isEmpty()) { return; }
pRules.dequeue(); pRules.dequeue();
emit RuleNamesChanged(RuleNames()); // Refresh rules and view
update(); pRefreshRules();
} }
/*
* Clear all rules from our local queue
*/
void HexViewer::ClearRules() { void HexViewer::ClearRules() {
if (pRules.isEmpty()) { return; } if (pRules.isEmpty()) { return; }
pRules.clear(); pRules.clear();
emit RuleNamesChanged(RuleNames()); // Refresh rules and view
update(); pRefreshRules();
} }
/*
* Save rules to a Hexes Rule File (.hrf)
*/
void HexViewer::SaveRules() { void HexViewer::SaveRules() {
// Have user choose where to save the .hrf
QString filePath = QFileDialog::getSaveFileName(this, "Save Hexes Rule File", QString filePath = QFileDialog::getSaveFileName(this, "Save Hexes Rule File",
"C:/", "Rule File (*.hrf);;All Files(*.*)"); pFileDir, "Rule File (*.hrf);;All Files(*.*)");
QString tempFilePath = filePath;
pFileDir = tempFilePath.replace(tempFilePath.split('/').last(), "");
emit BaseDirChanged(pFileDir);
// Open rule file, or report error, then close
QFile ruleFile(filePath); QFile ruleFile(filePath);
if (!ruleFile.open(QIODevice::WriteOnly)) { if (!ruleFile.open(QIODevice::WriteOnly)) {
qDebug() << "Failed to save rule file!"; HexesLogger::HexesError(25, "Failed to save rule file!");
return; return;
} }
ruleFile.close(); ruleFile.close();
// Write to rule file in ini format
QSettings ruleExport(filePath, QSettings::IniFormat); QSettings ruleExport(filePath, QSettings::IniFormat);
ruleExport.setValue("rules", QVariant::fromValue(pRules)); ruleExport.setValue("rules", QVariant::fromValue(pRules));
} }
/*
* Open a Hexes Rule File (.hrf)
*/
void HexViewer::OpenRules() { void HexViewer::OpenRules() {
// Have user choose where to save the .hrf
QString filePath = QFileDialog::getOpenFileName(this, "Open Hexes Rule File", QString filePath = QFileDialog::getOpenFileName(this, "Open Hexes Rule File",
"C:/", "Rule File (*.hrf);;All Files(*.*)"); pFileDir, "Rule File (*.hrf);;All Files(*.*)");
QString tempFilePath = filePath;
pFileDir = tempFilePath.replace(tempFilePath.split('/').last(), "");
emit BaseDirChanged(pFileDir);
// Open rule file, or report error, then close
QFile ruleFile(filePath); QFile ruleFile(filePath);
if (!ruleFile.open(QIODevice::ReadOnly)) { if (!ruleFile.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to save rule file!"; HexesLogger::HexesError(30, "Failed to open rule file!");
return; return;
} }
ruleFile.close(); ruleFile.close();
// Read from rule file in ini format
QSettings ruleExport(filePath, QSettings::IniFormat); QSettings ruleExport(filePath, QSettings::IniFormat);
pRules = ruleExport.value("rules").value<QQueue<Rule>>(); pRules = ruleExport.value("rules").value<QQueue<Rule>>();
emit RuleNamesChanged(RuleNames()); // Notify & refresh rules and view
pRefreshRules();
RunRules(); emit FileOpened(filePath.split('/').last());
} }
/*
* Open a binary input file
*/
void HexViewer::OpenFile() {
// Have user choose where to save the .hrf
QString filePath = QFileDialog::getOpenFileName(this, "Open Input File",
pFileDir, "All Files(*.*)");
QString tempFilePath = filePath;
pFileDir = tempFilePath.replace(tempFilePath.split('/').last(), "");
emit BaseDirChanged(pFileDir);
SetFileName(filePath);
// Notify & refresh rules and view
pRefreshRules();
emit FileOpened(filePath);
}
/*
* Get a list of rule names from local queue
*/
QStringList HexViewer::RuleNames() { QStringList HexViewer::RuleNames() {
if (pRules.isEmpty()) { return QStringList(); }
// Create and return name list
QStringList ruleNames; QStringList ruleNames;
foreach (Rule rule, pRules) { foreach (Rule rule, pRules) {
ruleNames.append(rule.Name()); ruleNames.append(rule.Name());
@ -149,162 +219,190 @@ QStringList HexViewer::RuleNames() {
return ruleNames; return ruleNames;
} }
void HexViewer::RunRules() { /*
QDataStream inStream(QByteArray::fromHex(pHex.toUtf8())); * Re-parse rules and update the variables' values
*/
void HexViewer::ParseRules() {
// Read in hex data as a byte-stream
HexStream hexStream(QByteArray::fromHex(pHex.toUtf8()));
// Iterate through local rules
for (int i = 0; i < pRules.size(); i++) { for (int i = 0; i < pRules.size(); i++) {
Rule rule = pRules[i]; Rule &rule = pRules[i]; // Current rule
qDebug() << rule.Name();
if ((rule.Type() == TYPE_NONE) || (rule.Type() == TYPE_SKIP)) {
hexStream.ParseSkip(rule.Length() + rule.SkipOffset());
continue;
}
// Repeat rule per defined repeat count
for (int j = 0; j <= rule.RepeatCount() + rule.RepeatOffset(); j++) {
// Set byte order and execute pre-skip
hexStream.SetHexByteOrder(rule.ByteOrder());
hexStream.ParseSkip(rule.PreSkipCount() + rule.PreSkipOffset());
for (int j = 0; j <= rule.RepeatCount(); j++) { // Create parse block to get value for variable
if (rule.ByteOrder() == BYTE_ORDER_BE) { BlockValue val = hexStream.ParseRule(rule);
inStream.setByteOrder(QDataStream::BigEndian); rule.SetValue(val.ToString());
} else {
inStream.setByteOrder(QDataStream::LittleEndian);
}
QString ruleName = rule.Name().toUpper(); // Execute post-skip
hexStream.ParseSkip(rule.PostSkipCount() + rule.PostSkipOffset());
// Add a var suffix (index) if repeating
if (rule.RepeatCount() > 0) { if (rule.RepeatCount() > 0) {
ruleName += QString(" %1").arg(j); pVars[rule.Name() + QString(" %1").arg(j)] = val;
} else {
pVars[rule.Name()] = val;
} }
BlockValue val;
val.SetName(ruleName);
if (rule.PreSkipCount() > 0) {
inStream.skipRawData(rule.PreSkipCount());
}
switch ((int)rule.Type()) {
case 1: // Skip
inStream.skipRawData(rule.Length());
break;
case 2: // int8
qint8 val_8;
inStream >> val_8;
rule.SetValue(QString::number(val_8));
val.SetValue(val_8);
break;
case 3: // uint8
quint8 val_u8;
inStream >> val_u8;
rule.SetValue(QString::number(val_u8));
val.SetValue(val_u8);
break;
case 4: // int16
qint16 val_16;
inStream >> val_16;
rule.SetValue(QString::number(val_16));
val.SetValue(val_16);
break;
case 5: // uint16
quint16 val_u16;
inStream >> val_u16;
rule.SetValue(QString::number(val_u16));
val.SetValue(val_u16);
break;
case 6: // int32
qint32 val_32;
inStream >> val_32;
rule.SetValue(QString::number(val_32));
val.SetValue(val_32);
break;
case 7: // uint32
quint32 val_u32;
inStream >> val_u32;
rule.SetValue(QString::number(val_u32));
val.SetValue(val_u32);
break;
case 8: // int64
qint64 val_64;
inStream >> val_64;
rule.SetValue(QString::number(val_64));
val.SetValue(val_64);
break;
case 9: // uint64
quint64 val_u64;
inStream >> val_u64;
rule.SetValue(QString::number(val_u64));
val.SetValue(val_u64);
break;
}
if (rule.PostSkipCount() > 0) {
inStream.skipRawData(rule.PostSkipCount());
}
if ((rule.Type() != TYPE_NONE)
&& (rule.Type() != TYPE_SKIP)) {
pVars[ruleName] = val;
emit VarsChanged(pVars);
}
pRules[i] = rule;
} }
} }
emit VarsChanged(pVars);
update(); update();
} }
/*
* Return the local variable map
* - Note: May not be populated
*/
QMap<QString, BlockValue> HexViewer::GetVars() { QMap<QString, BlockValue> HexViewer::GetVars() {
return pVars; return pVars;
} }
void HexViewer::SetBaseDir(QString dir) {
pFileDir = dir;
}
/*
* Get the text representation of the data
*/
QString HexViewer::Text() { QString HexViewer::Text() {
return pText; return pText;
} }
/*
* Get the hex representation of the data
*/
QString HexViewer::Hex() { QString HexViewer::Hex() {
return pHex; return pHex;
} }
QRectF HexViewer::pCalcOffsetColumnRect() { QString HexViewer::pFormatValuesGrid(const QVector<int> &values, int width, const QFont &font, int bitSize, int& textHeight) {
return QRectF(5, 30, 80, height() - 35); if (values.isEmpty()) return "";
QFontMetrics fm(font);
QString result;
// Determine the width for the index based on the number of digits in the largest index
int maxIndexDigits = QString::number(values.size()).length();
// Determine padding width for values based on bit size (minimal necessary width)
int valuePaddingWidth = 0;
switch (bitSize) {
case 8: valuePaddingWidth = 3; break; // int8 max is 255
case 16: valuePaddingWidth = 5; break; // int16 max is 65535
case 32: valuePaddingWidth = 10; break; // int32 max is 4294967295
case 64: valuePaddingWidth = 20; break; // int64 max is very large
default: valuePaddingWidth = 10; break; // Default to int32-like width
}
// Calculate a compact maximum entry width (index + value) with minimal padding
int maxEntryWidth = fm.horizontalAdvance(QString("%1=%2 ")
.arg(values.size(), maxIndexDigits)
.arg(0, valuePaddingWidth, 10, QChar('0')));
// Determine the optimal number of entries per line based on available width
int entriesPerLine = std::max(1, width / maxEntryWidth);
// Build the grid-like output
int lineCount = 0;
for (int i = 0; i < values.size(); ++i) {
if (i > 0 && i % entriesPerLine == 0) {
result += "\n";
lineCount++;
} else if (i > 0) {
result += ", "; // Minimal spacing between entries
}
// Format each entry with a left-aligned index and right-aligned value
result += QString("%1=%2")
.arg(i + 1, maxIndexDigits, 10, QChar(' ')) // Left-pad index minimally
.arg(values[i], -valuePaddingWidth, 10, QChar(' ')); // Right-pad value minimally
}
// Account for the final line
lineCount++;
// Calculate the height of the text block
textHeight = lineCount * fm.height();
return result;
} }
/*
* Calculate the hex header rectangle
*/
QRectF HexViewer::pCalcHexHeaderRect() const { QRectF HexViewer::pCalcHexHeaderRect() const {
QRectF paintRect = pCalcPaintRect(); qreal columnWidth = viewport()->width()
- (OFFSET_HEADER_WIDTH + (3 * MAX_PADDING));
qreal hexColumnWidth = (columnWidth / 5 * 3) - 2 * MAX_PADDING;
qreal columnWidth = paintRect.right() - 125; return QRectF(OFFSET_HEADER_WIDTH + MAX_PADDING, MIN_PADDING,
qreal hexColumnWidth = (columnWidth / 5 * 3) - 15; hexColumnWidth, HEADER_HEIGHT);
return QRectF(95, 5, hexColumnWidth - 10, 15);
} }
QRectF HexViewer::pCalcTextHeaderRect() { /*
QRectF paintRect = pCalcPaintRect(); * Calculate the text header rectangle
*/
QRectF HexViewer::pCalcTextHeaderRect() const {
qreal columnWidth = viewport()->width()
- (OFFSET_HEADER_WIDTH + (3 * MAX_PADDING));
qreal hexColumnWidth = (columnWidth / 5 * 3) - MAX_PADDING;
qreal textColumnWidth = (columnWidth / 5) + MAX_PADDING;
qreal columnWidth = paintRect.right() - 125; return QRectF(OFFSET_HEADER_WIDTH + hexColumnWidth + MAX_PADDING, MIN_PADDING,
qreal hexColumnWidth = (columnWidth / 5 * 3) - 15; textColumnWidth - 2 * MAX_PADDING, MAX_PADDING);
qreal textColumnWidth = (columnWidth / 5) + 15;
return QRectF(95 + hexColumnWidth, 5, textColumnWidth - 10, 15);
} }
QRectF HexViewer::pCalcRuleHeaderRect() { /*
QRectF paintRect = pCalcPaintRect(); * Calculate the rule header rectangle
*/
QRectF HexViewer::pCalcRuleHeaderRect() const {
qreal columnWidth = viewport()->width()
- (OFFSET_HEADER_WIDTH + (3 * MAX_PADDING));
qreal hexColumnWidth = (columnWidth / 5 * 3);
qreal textColumnWidth = (columnWidth / 5) + MAX_PADDING;
qreal ruleColumnWidth = (columnWidth / 5) + MAX_PADDING;
qreal columnWidth = paintRect.right() - 125; return QRectF(OFFSET_HEADER_WIDTH + hexColumnWidth + textColumnWidth, MIN_PADDING,
ruleColumnWidth - MAX_PADDING, MAX_PADDING);
qreal hexColumnWidth = (columnWidth / 5 * 3) - 15;
qreal textColumnWidth = (columnWidth / 5) + 15;
qreal ruleColumnWidth = (columnWidth / 5) + 15;
return QRectF(95 + hexColumnWidth + textColumnWidth, 5, ruleColumnWidth - 10, 15);
} }
QRectF HexViewer::pCalcOffsetHeaderRect() { /*
return QRectF(5, 5, 80, 15); * Calculate the offset header rectangle
*/
QRectF HexViewer::pCalcOffsetHeaderRect() const {
return QRectF(MIN_PADDING, MIN_PADDING,
OFFSET_HEADER_WIDTH, HEADER_HEIGHT);
} }
/*
* Calculate the offset column rectangle
*/
QRectF HexViewer::pCalcOffsetColumnRect() const {
return QRectF(MIN_PADDING, FONT_HEIGHT + HEADER_HEIGHT,
OFFSET_HEADER_WIDTH, height() - STATUS_BAR_HEIGHT);
}
/*
* Paint the offset column
*/
void HexViewer::pPaintOffsetColumn(QPainter &painter) { void HexViewer::pPaintOffsetColumn(QPainter &painter) {
QRectF offSetColumnRect = pCalcOffsetColumnRect(); QRectF offSetColumnRect = pCalcOffsetColumnRect();
QRectF hexRect = pCalcHexRect(); QRectF hexRect = pCalcHexRect();
int charWidth = fontMetrics().horizontalAdvance('F');
int hexCharsPerLine = qCeil(hexRect.width() / charWidth) / 3;
QString offset = ""; QString offset = "";
int nextOffset = verticalScrollBar()->value(); int nextOffset = verticalScrollBar()->value();
for (int i = 0; i < qCeil(hexRect.height() / fontMetrics().height()); i++) { for (int i = 0; i < qCeil(hexRect.height() / fontMetrics().height()); i++) {
offset += QString::number(nextOffset).rightJustified(8, '0') + " "; offset += QString::number(nextOffset).rightJustified(8, '0') + " ";
nextOffset += hexCharsPerLine; nextOffset += pCalcCharCount();
} }
offset = offset.trimmed(); offset = offset.trimmed();
@ -312,16 +410,21 @@ void HexViewer::pPaintOffsetColumn(QPainter &painter) {
painter.drawText(offSetColumnRect, Qt::TextWordWrap | Qt::AlignHCenter, offset); painter.drawText(offSetColumnRect, Qt::TextWordWrap | Qt::AlignHCenter, offset);
} }
/*
* Calculate the hex content rectangle
*/
QRectF HexViewer::pCalcHexRect() const { QRectF HexViewer::pCalcHexRect() const {
QRectF paintRect = pCalcPaintRect(); qreal columnWidth = viewport()->width()
- (OFFSET_HEADER_WIDTH + (3 * MAX_PADDING));
qreal hexColumnWidth = (columnWidth / 5 * 3) - 2 * MAX_PADDING;
qreal columnWidth = paintRect.right() - 125; return QRectF(OFFSET_HEADER_WIDTH + MAX_PADDING, HEADER_HEIGHT + FONT_HEIGHT,
qreal hexColumnWidth = (columnWidth / 5 * 3) - 15; hexColumnWidth, viewport()->height());
qreal scrollHeight = paintRect.height();
return QRectF(95, 30, hexColumnWidth - 10, scrollHeight - 35);
} }
/*
* Paint the hex content
*/
void HexViewer::pPaintHex(QPainter &painter) { void HexViewer::pPaintHex(QPainter &painter) {
QRectF hexRect = pCalcHexRect(); QRectF hexRect = pCalcHexRect();
@ -329,42 +432,36 @@ void HexViewer::pPaintHex(QPainter &painter) {
painter.drawText(hexRect, Qt::TextWordWrap, pHex); painter.drawText(hexRect, Qt::TextWordWrap, pHex);
} }
/*
* Calculate the text content rect
*/
QRectF HexViewer::pCalcTextRect() const { QRectF HexViewer::pCalcTextRect() const {
QRectF paintRect = pCalcPaintRect(); qreal columnWidth = viewport()->width()
qreal columnWidth = paintRect.right() - 125; - (OFFSET_HEADER_WIDTH + (3 * MAX_PADDING));
qreal hexColumnWidth = 80 + (columnWidth / 5 * 3); qreal hexColumnWidth = (columnWidth / 5 * 3);
qreal textColumnWidth = (columnWidth / 5); qreal textColumnWidth = (columnWidth / 5) - MAX_PADDING / 2;
qreal scrollHeight = paintRect.height();
int charWidth = fontMetrics().horizontalAdvance("F");
return QRectF(hexColumnWidth, 30, textColumnWidth - charWidth, scrollHeight - 35); return QRectF(OFFSET_HEADER_WIDTH + hexColumnWidth, HEADER_HEIGHT + FONT_HEIGHT,
textColumnWidth, viewport()->height());
} }
QRectF HexViewer::pCalcRuleRect() { /*
QRectF paintRect = pCalcPaintRect(); * Calculate rule sidebar rectangle
*/
QRectF HexViewer::pCalcRuleRect() const {
qreal columnWidth = viewport()->width()
- (OFFSET_HEADER_WIDTH + (3 * MAX_PADDING));
qreal hexColumnWidth = (columnWidth / 5 * 3);
qreal textColumnWidth = (columnWidth / 5) + MAX_PADDING;
qreal ruleColumnWidth = (columnWidth / 5) + MAX_PADDING;
qreal columnWidth = paintRect.right() - 125; return QRectF(OFFSET_HEADER_WIDTH + hexColumnWidth + textColumnWidth, HEADER_HEIGHT + FONT_HEIGHT,
ruleColumnWidth, viewport()->height());
qreal hexColumnWidth = (columnWidth / 5 * 3) - 15;
qreal textColumnWidth = (columnWidth / 5) + 15;
qreal rulesColumnWidth = (columnWidth / 5) + 15;
qreal scrollHeight = pCalcContentHeight();
return QRectF(95 + hexColumnWidth + textColumnWidth, 30, rulesColumnWidth - 10, scrollHeight - 35);
} }
QString HexViewer::pInsertNewlinesAtIntervals(const QString &input, int interval) { /*
QString result = input; * Paint the text content
*/
for (int i = interval; i < result.length(); i += interval) {
result.insert(i, '\n');
i++;
}
return result;
}
void HexViewer::pPaintText(QPainter &painter) { void HexViewer::pPaintText(QPainter &painter) {
QRectF textRect = pCalcTextRect(); QRectF textRect = pCalcTextRect();
@ -372,6 +469,9 @@ void HexViewer::pPaintText(QPainter &painter) {
painter.drawText(textRect, Qt::TextWrapAnywhere, pText); painter.drawText(textRect, Qt::TextWrapAnywhere, pText);
} }
/*
* Paint a hex rule over the content
*/
void HexViewer::pPaintHexRule(QPainter &painter, int &currentXPos, void HexViewer::pPaintHexRule(QPainter &painter, int &currentXPos,
int &currentYPos, int ruleLen, bool skip) { int &currentYPos, int ruleLen, bool skip) {
int charWidth = fontMetrics().horizontalAdvance("F"); int charWidth = fontMetrics().horizontalAdvance("F");
@ -386,8 +486,8 @@ void HexViewer::pPaintHexRule(QPainter &painter, int &currentXPos,
int rectWidth = charsToDraw * 3 * charWidth; int rectWidth = charsToDraw * 3 * charWidth;
// Only draw if within the visible area vertically // Only draw if within the visible area vertically
if (adjustedYPos + fontMetrics().height() >= hexRect.top() && if (adjustedYPos >= hexRect.top() &&
adjustedYPos <= hexRect.bottom()) { adjustedYPos <= (hexRect.bottom() - fontMetrics().height())) {
QRectF skipRect(QPointF(currentXPos, adjustedYPos + 1), QRectF skipRect(QPointF(currentXPos, adjustedYPos + 1),
QSizeF(rectWidth - charWidth, fontMetrics().height() - 2)); QSizeF(rectWidth - charWidth, fontMetrics().height() - 2));
@ -412,6 +512,9 @@ void HexViewer::pPaintHexRule(QPainter &painter, int &currentXPos,
currentYPos = adjustedYPos + scrollHeight; currentYPos = adjustedYPos + scrollHeight;
} }
/*
* Paint a text rule over the content
*/
void HexViewer::pPaintTextRule(QPainter &painter, int &currentXPos, void HexViewer::pPaintTextRule(QPainter &painter, int &currentXPos,
int &currentYPos, int ruleLen, bool skip) { int &currentYPos, int ruleLen, bool skip) {
int charWidth = fontMetrics().horizontalAdvance("F"); int charWidth = fontMetrics().horizontalAdvance("F");
@ -438,8 +541,8 @@ void HexViewer::pPaintTextRule(QPainter &painter, int &currentXPos,
int rectWidth = charsToDraw * charWidth; int rectWidth = charsToDraw * charWidth;
// Only draw if within the visible area vertically // Only draw if within the visible area vertically
if (adjustedYPos + fontMetrics().height() >= textRect.top() && if (adjustedYPos >= textRect.top() &&
adjustedYPos <= textRect.bottom()) { adjustedYPos <= textRect.bottom()) {
QRectF skipRect(QPointF(currentXPos, adjustedYPos + 1), QRectF skipRect(QPointF(currentXPos, adjustedYPos + 1),
QSizeF(rectWidth, fontMetrics().height() - 2)); QSizeF(rectWidth, fontMetrics().height() - 2));
@ -464,11 +567,12 @@ void HexViewer::pPaintTextRule(QPainter &painter, int &currentXPos,
currentYPos = adjustedYPos + scrollHeight; currentYPos = adjustedYPos + scrollHeight;
} }
/*
* Seek to a new file location, process
* the contents, and update the view.
*/
void HexViewer::pSeekFile() { void HexViewer::pSeekFile() {
QRectF hexRect(pCalcHexRect()); QRectF hexRect(pCalcHexRect());
qDebug() << "hexRect width" << hexRect.width();
int dataLength = (hexRect.height() / fontMetrics().height()) * pCalcCharCount(); int dataLength = (hexRect.height() / fontMetrics().height()) * pCalcCharCount();
if (dataLength < 0) { if (dataLength < 0) {
@ -479,15 +583,34 @@ void HexViewer::pSeekFile() {
pHex = pCleanHex(data.toHex()); pHex = pCleanHex(data.toHex());
pText = QString::fromLocal8Bit(data).replace('\0', '.');//, pCalcCharCount()); pText = QString::fromLocal8Bit(data).replace('\0', '.');//, pCalcCharCount());
} else { } else {
qDebug() << QString("File '%1' not open...").arg(pFile.fileName()); //HexesLogger::HexesError(35, QString("File '%1' not open...").arg(pFile.fileName()));
return; //return;
} }
pUpdateScrollBar(); pUpdateScrollBar();
update(); update();
} }
/*
* void pRefreshRules()
*
* Notify rules have changed and update view
*/
void HexViewer::pRefreshRules() {
// Notify current rules have changed
emit RuleNamesChanged(RuleNames());
// Parse new vars and values
ParseRules();
}
/*
* void pPaintRules(QPainter &painter)
*
* Paint the hex rules to the sidebar
*/
void HexViewer::pPaintRules(QPainter &painter) { void HexViewer::pPaintRules(QPainter &painter) {
int ruleIndex = 1; int ruleIndex = 1;
bool isSkip = false;
qreal fontHeight = QFontMetrics(painter.font()).height();
QRectF rulesRect = pCalcRuleRect(); QRectF rulesRect = pCalcRuleRect();
painter.save(); painter.save();
@ -501,96 +624,85 @@ void HexViewer::pPaintRules(QPainter &painter) {
int textXPos = textRect.left(); int textXPos = textRect.left();
int textYPos = textRect.top(); int textYPos = textRect.top();
QRectF clipRect(0, rulesRect.top(), width(), rulesRect.height()); int currY = 0;
painter.setClipRect(clipRect);
QQueue<Rule> rules = QQueue<Rule>(pRules); foreach (Rule rule, pRules) {
QString typeText = "";
QString valueText = "";
int preSkipCount = rule.PreSkipCount();
int postSkipCount = rule.PostSkipCount();
QVector<int> repeatVals = QVector<int>();
foreach (Rule rule, rules) { QString ruleName = rule.Name();
QString ruleName = rule.Name().toUpper();
if (rule.RepeatCount() > 0) {
ruleName += " %1";
}
QColor ruleBackground(rule.Color());
ruleBackground.setAlpha(75);
painter.setPen(Qt::black);
painter.setBrush(ruleBackground);
valueText.clear();
for (int i = 0; i <= rule.RepeatCount(); i++) { for (int i = 0; i <= rule.RepeatCount(); i++) {
QString formattedName = ruleName; QString formattedName = rule.Name();
int preSkipCount = rule.PreSkipCount();
int postSkipCount = rule.PostSkipCount();
if (rule.RepeatCount() > 0) { if (rule.RepeatCount() > 0) {
formattedName = formattedName.arg(i + 1); formattedName = QString(rule.Name() + " %1").arg(i + 1);
} }
// Paint pre-skip
painter.setPen(QPen(rule.Color(), 1));
QString typeText = "";
QString valueText = "";
QColor ruleBackground(rule.Color());
ruleBackground.setAlpha(75);
painter.setBrush(ruleBackground);
// Draw the rule information in the rule stack on the right side
QRectF ruleBackgroundRect(rulesRect.left(), -verticalScrollBar()->value() + rulesRect.top() + 1 + (QFontMetrics(painter.font()).height() * 3) * (ruleIndex - 1),
rulesRect.width(), QFontMetrics(painter.font()).height() * 3);
QRectF ruleRect(rulesRect.left() + 1, -verticalScrollBar()->value() + rulesRect.top() + 2 + (QFontMetrics(painter.font()).height() * 3) * (ruleIndex - 1),
rulesRect.width() - 2, QFontMetrics(painter.font()).height() * 3);
painter.drawRect(ruleBackgroundRect);
if (preSkipCount > 0) { if (preSkipCount > 0) {
//typeText = QString("Skip %1 byte(s)").arg(rule.Length());
pPaintHexRule(painter, hexXPos, hexYPos, preSkipCount, true); pPaintHexRule(painter, hexXPos, hexYPos, preSkipCount, true);
pPaintTextRule(painter, textXPos, textYPos, preSkipCount, true); pPaintTextRule(painter, textXPos, textYPos, preSkipCount, true);
//isSkip = true;
} }
if (postSkipCount > 0) { // Paint skip or int
//typeText = QString("Skip %1 byte(s)").arg(rule.Length()); if (rule.Type() == TYPE_SKIP) {
pPaintHexRule(painter, hexXPos, hexYPos, postSkipCount, true);
pPaintTextRule(painter, textXPos, textYPos, postSkipCount, true);
//isSkip = true;
}
bool isSkip = false;
switch ((int)rule.Type()) {
case 1: // TYPE_SKIP
typeText = QString("Skip %1 byte(s)").arg(rule.Length());
pPaintHexRule(painter, hexXPos, hexYPos, rule.Length(), true); pPaintHexRule(painter, hexXPos, hexYPos, rule.Length(), true);
pPaintTextRule(painter, textXPos, textYPos, rule.Length(), true); pPaintTextRule(painter, textXPos, textYPos, rule.Length(), true);
isSkip = true; isSkip = true;
break; } else {
typeText = QString("%1-BIT %2 INTEGER").arg(rule.Length() * 8)
case 2: // TYPE_INT_8 .arg(rule.Type() % 2 == 0 ? "" : "US");
case 3: // TYPE_UINT_8 valueText += pVars[formattedName].ToString() + "\n";
case 4: // TYPE_INT_16 if (rule.RepeatCount() > 0) {
case 5: // TYPE_UINT_16 repeatVals.push_back(pVars[formattedName].ToInt());
case 6: // TYPE_INT_32 }
case 7: // TYPE_UINT_32
case 8: // TYPE_INT_64
case 9: // TYPE_UINT_64
typeText = QString("%1-BIT %2 INTEGER").arg(rule.Length() * 8).arg(rule.Type() % 2 == 0 ? "" : "US");
valueText = pVars[formattedName].Value().toString();
pPaintHexRule(painter, hexXPos, hexYPos, rule.Length()); pPaintHexRule(painter, hexXPos, hexYPos, rule.Length());
pPaintTextRule(painter, textXPos, textYPos, rule.Length()); pPaintTextRule(painter, textXPos, textYPos, rule.Length());
break;
default:
typeText = "UH-OH";
break;
} }
// Paint post-skip
painter.setPen(Qt::black); if (postSkipCount > 0) {
QString paddedIndex = QString::number(ruleIndex).rightJustified(2, '0'); pPaintHexRule(painter, hexXPos, hexYPos, postSkipCount, true);
QString ruleText = QString("%1. %2\n%3\n%4\n").arg(paddedIndex, formattedName, pPaintTextRule(painter, textXPos, textYPos, postSkipCount, true);
typeText, valueText);
painter.drawText(ruleRect, Qt::TextWrapAnywhere, ruleText);
QString ruleByteOrder = QString(rule.ByteOrder() == BYTE_ORDER_BE ? "BE" : "LE") + "\n\n";
if (!isSkip) {
painter.drawText(ruleRect, Qt::AlignRight, ruleByteOrder);
} }
ruleIndex++;
} }
if (!isSkip) {
int blockHeight;
if (repeatVals.size() > 0) {
valueText = pFormatValuesGrid(repeatVals, rulesRect.width(), painter.font(), rule.Length() * 8, blockHeight);
}
qreal ruleHeight;
if (rule.RepeatCount() == 0) {
ruleHeight = fontHeight * 2;
} else {
ruleHeight = fontHeight * 2 + blockHeight;
}
QRectF ruleRect(rulesRect.left() + 1, -verticalScrollBar()->value() + rulesRect.top() + 2 + currY,
rulesRect.width() - 2, ruleHeight);
QString paddedIndex = QString::number(ruleIndex).rightJustified(2, '0');
QString ruleText = QString("%1. %2\n%3\n%4\n").arg(paddedIndex, ruleName,
typeText, valueText);
QString ruleByteOrder = QString(rule.ByteOrder() == BYTE_ORDER_BE ? "BE" : "LE") + "\n\n";
painter.drawText(ruleRect, Qt::TextWrapAnywhere, ruleText);
painter.drawText(ruleRect, Qt::AlignRight, ruleByteOrder);
QRectF ruleBackgroundRect(rulesRect.left(), -verticalScrollBar()->value() + rulesRect.top() + 1 + currY,
rulesRect.width(), ruleHeight);
painter.drawRect(ruleBackgroundRect);
ruleIndex++;
currY += ruleHeight;
}
isSkip = false;
} }
painter.restore(); painter.restore();
} }
@ -628,7 +740,7 @@ void HexViewer::pPaintHeaders(QPainter &painter) {
void HexViewer::paintEvent(QPaintEvent *event) { void HexViewer::paintEvent(QPaintEvent *event) {
QPainter painter(viewport()); QPainter painter(viewport());
if (!painter.isActive()) { if (!painter.isActive()) {
qWarning() << "QPainter is not active"; HexesLogger::HexesError(45, "QPainter is not active!");
return; return;
} }
if (event->rect().isEmpty()) { return; } if (event->rect().isEmpty()) { return; }
@ -640,24 +752,22 @@ void HexViewer::paintEvent(QPaintEvent *event) {
pPaintText(painter); pPaintText(painter);
pPaintRules(painter); pPaintRules(painter);
if (pCursorVisible) { // if (pCursorVisible) {
QPoint cursorPos = pCalcCursorPosition(); // QPoint cursorPos = pCalcCursorPosition();
QFontMetrics fm(font()); // int cursorHeight = pFontMetrics.height();
int cursorHeight = fm.height();
painter.drawLine(cursorPos.x(), cursorPos.y(), cursorPos.x(), cursorPos.y() + cursorHeight); // painter.drawLine(cursorPos.x(), cursorPos.y(), cursorPos.x(), cursorPos.y() + cursorHeight);
} // }
if (pSelectionStart >= 0 && pSelectionEnd >= pSelectionStart) { // if (pSelectionStart >= 0 && pSelectionEnd >= pSelectionStart) {
if (pSelectionStart >= 0 && pSelectionEnd >= pSelectionStart) { // if (pSelectionStart >= 0 && pSelectionEnd >= pSelectionStart) {
QFontMetrics fm(font()); // int startX = pFontMetrics.horizontalAdvance(pText.left(pSelectionStart));
int startX = fm.horizontalAdvance(pText.left(pSelectionStart)); // int endX = pFontMetrics.horizontalAdvance(pText.left(pSelectionEnd));
int endX = fm.horizontalAdvance(pText.left(pSelectionEnd)); // int height = pFontMetrics.height();
int height = fm.height();
painter.fillRect(QRect(startX, 0, endX - startX, height), QColor(0, 120, 215, 100)); // Semi-transparent blue // painter.fillRect(QRect(startX, 0, endX - startX, height), QColor(0, 120, 215, 100)); // Semi-transparent blue
} // }
} // }
} }
void HexViewer::showEvent(QShowEvent *event) { void HexViewer::showEvent(QShowEvent *event) {
@ -670,6 +780,16 @@ QSize HexViewer::sizeHint() const {
return pCalcPaintRect().size().toSize(); return pCalcPaintRect().size().toSize();
} }
void HexViewer::pScrollValueChanged(int value) {
pScrollValue = value;
pSeekFile();
}
void HexViewer::pBlinkCursor() {
pCursorVisible = !pCursorVisible;
update();
}
void HexViewer::resizeEvent(QResizeEvent *event) { void HexViewer::resizeEvent(QResizeEvent *event) {
QAbstractScrollArea::resizeEvent(event); QAbstractScrollArea::resizeEvent(event);
@ -727,7 +847,7 @@ int HexViewer::pCalcLineCount() const {
return pText.length() / pCalcCharCount(); return pText.length() / pCalcCharCount();
} }
QPoint HexViewer::pCalcCursorPosition() { QPoint HexViewer::pCalcCursorPosition() const {
int lineHeight = fontMetrics().height(); int lineHeight = fontMetrics().height();
int line = pCalcCursorLine(); int line = pCalcCursorLine();
@ -747,7 +867,7 @@ QRectF HexViewer::pCalcPaintRect() const {
return pViewRect; return pViewRect;
} }
int HexViewer::pCalcCursorLine() { int HexViewer::pCalcCursorLine() const {
qreal columnWidth = rect().right() - 90 - verticalScrollBar()->width(); qreal columnWidth = rect().right() - 90 - verticalScrollBar()->width();
qreal scrollHeight = verticalScrollBar()->height(); qreal scrollHeight = verticalScrollBar()->height();
qreal hexColumnWidth = (columnWidth / 4 * 3) - 15; qreal hexColumnWidth = (columnWidth / 4 * 3) - 15;

View File

@ -3,6 +3,8 @@
#include "rule.h" #include "rule.h"
#include "blockvalue.h" #include "blockvalue.h"
#include "hexstream.h"
#include "hexeslogger.h"
#include <QAbstractScrollArea> #include <QAbstractScrollArea>
#include <QPainter> #include <QPainter>
@ -16,6 +18,16 @@
#include <QSettings> #include <QSettings>
#include <QMetaType> #include <QMetaType>
const int DEFAULT_SINGLE_STEP = 45;
const int DEFAULT_PAGE_STEP = 45;
const int OFFSET_HEADER_WIDTH = 80;
const int MIN_PADDING = 5;
const int MAX_PADDING = 15;
const int HEADER_HEIGHT = 15;
const int STATUS_BAR_HEIGHT = 35;
const int FONT_HEIGHT = 15;
class HexViewer : public QAbstractScrollArea class HexViewer : public QAbstractScrollArea
{ {
Q_OBJECT Q_OBJECT
@ -27,16 +39,20 @@ public:
void SetFileName(const QString fileName); void SetFileName(const QString fileName);
QStringList RuleNames(); QStringList RuleNames();
void RunRules(); void ParseRules();
void DeclareVar(); void DeclareVar();
void SetVar(QString varName, QVariant value); void SetVar(QString varName, QVariant value);
QVariant GetVar(QString varName); QVariant GetVar(QString varName);
QMap<QString, BlockValue> GetVars(); QMap<QString, BlockValue> GetVars();
void SetBaseDir(QString dir);
QString Text(); QString Text();
QString Hex(); QString Hex();
QString pFormatValuesGrid(const QVector<int>& values, int width, const QFont& font, int bitSize, int &textHeight);
public slots: public slots:
void AddRule(const Rule rule); void AddRule(const Rule rule);
void AddRules(const QVector<Rule> rules); void AddRules(const QVector<Rule> rules);
@ -47,6 +63,7 @@ public slots:
void SaveRules(); void SaveRules();
void OpenRules(); void OpenRules();
void OpenFile();
protected: protected:
void resizeEvent(QResizeEvent *event) override; void resizeEvent(QResizeEvent *event) override;
@ -58,9 +75,15 @@ protected:
QSize sizeHint() const override; QSize sizeHint() const override;
private slots:
void pScrollValueChanged(int value);
void pBlinkCursor();
signals: signals:
void RuleNamesChanged(QStringList ruleNames); void RuleNamesChanged(QStringList ruleNames);
void VarsChanged(QMap<QString, BlockValue> vars); void VarsChanged(QMap<QString, BlockValue> vars);
void FileOpened(const QString aFileName);
void BaseDirChanged(QString dir);
private: private:
QString pFileName; QString pFileName;
@ -69,6 +92,8 @@ private:
QRectF pViewRect; QRectF pViewRect;
QFile pFile; QFile pFile;
QMap<QString, BlockValue> pVars; QMap<QString, BlockValue> pVars;
QFontMetrics pFontMetrics;
QString pFileDir;
int pScrollValue; int pScrollValue;
int pCursorPosition; // Cursor position in the text int pCursorPosition; // Cursor position in the text
@ -78,39 +103,55 @@ private:
QTimer *pBlinkTimer; // Timer for blinking cursor QTimer *pBlinkTimer; // Timer for blinking cursor
QQueue<Rule> pRules; QQueue<Rule> pRules;
// Init, update, & utility functions
void pInitCursorTimer();
void pInitScrollBar();
void pUpdateScrollBar();
QString pCleanHex(const QString &text); QString pCleanHex(const QString &text);
QString pStringToHex(const QString &text); QString pStringToHex(const QString &text);
void pUpdateScrollBar(); void pSeekFile();
void pRefreshRules();
// Cursor functions
void pPaintCursor(QPainter &painter); void pPaintCursor(QPainter &painter);
int pCalcCursorLine() const;
QPoint pCalcCursorPosition() const;
// Selection functions
void pPaintSelection(QPainter &painter); void pPaintSelection(QPainter &painter);
// Header functions
void pPaintHeaders(QPainter &painter); void pPaintHeaders(QPainter &painter);
QRectF pCalcHexHeaderRect() const;
QRectF pCalcOffsetHeaderRect() const;
QRectF pCalcRuleHeaderRect() const;
QRectF pCalcTextHeaderRect() const;
// Hex content functions
void pPaintHex(QPainter &painter); void pPaintHex(QPainter &painter);
QRectF pCalcHexRect() const;
// Text content functions
void pPaintText(QPainter &painter); void pPaintText(QPainter &painter);
QRectF pCalcTextRect() const;
// Offset functions
void pPaintOffsetColumn(QPainter &painter); void pPaintOffsetColumn(QPainter &painter);
QRectF pCalcOffsetColumnRect() const;
// Rule functions
void pPaintRules(QPainter &painter); void pPaintRules(QPainter &painter);
QRectF pCalcRuleRect() const;
void pPaintHexRule(QPainter &painter, int &currentXPos, void pPaintHexRule(QPainter &painter, int &currentXPos,
int &currentYPos, int ruleLen, bool skip = false); int &currentYPos, int ruleLen, bool skip = false);
void pPaintTextRule(QPainter &painter, int &currentXPos, void pPaintTextRule(QPainter &painter, int &currentXPos,
int &currentYPos, int ruleLen, bool skip = false); int &currentYPos, int ruleLen, bool skip = false);
void pSeekFile(); // Other calculations
QRectF pCalcPaintRect() const;
int pCalcContentHeight() const; int pCalcContentHeight() const;
int pCalcCharCount() const; int pCalcCharCount() const;
int pCalcLineCount() const; int pCalcLineCount() const;
QRectF pCalcPaintRect() const;
QRectF pCalcTextRect() const;
QRectF pCalcHexRect() const;
QRectF pCalcHexHeaderRect() const;
int pCalcCursorLine();
QPoint pCalcCursorPosition();
QRectF pCalcOffsetColumnRect();
QRectF pCalcOffsetHeaderRect();
QRectF pCalcRuleHeaderRect();
QRectF pCalcTextHeaderRect();
QRectF pCalcRuleRect();
QString pInsertNewlinesAtIntervals(const QString &input, int interval);
}; };
#endif // HEXVIEWER_H #endif // HEXVIEWER_H

View File

@ -2,9 +2,38 @@
#include <QApplication> #include <QApplication>
class Rule;
void HexesLogOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
}
}
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
qInstallMessageHandler(HexesLogOutput);
QApplication a(argc, argv); QApplication a(argc, argv);
qRegisterMetaType<Rule>("Rule");
qRegisterMetaType<QQueue<Rule>>("QQueue<Rule>");
MainWindow w; MainWindow w;
w.show(); w.show();
return a.exec(); return a.exec();

View File

@ -1,16 +1,21 @@
#include "mainwindow.h" #include "mainwindow.h"
#include "ui_mainwindow.h" #include "ui_mainwindow.h"
#include <QMetaType>
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
, ui(new Ui::MainWindow) { , ui(new Ui::MainWindow) {
HexesLogger::MakeInstance(this);
ui->setupUi(this); ui->setupUi(this);
pSettingsName = "mainwindow.ini";
pRecentFiles = QStringList();
pActions = QVector<QAction*>();
pBaseDir = "C:/";
pViewer = new HexViewer(this); pViewer = new HexViewer(this);
setCentralWidget(pViewer); setCentralWidget(pViewer);
pViewer->SetFileName("C:/Ext/Projects/Qt/Hexes/nazi_zombie_factory_patch.zone"); //pViewer->SetFileName("C:/Ext/Projects/Qt/Hexes/nazi_zombie_factory_patch.zone");
//ui->statusbar->showMessage(QString("File Size: %1 bytes").arg(data.size())); //ui->statusbar->showMessage(QString("File Size: %1 bytes").arg(data.size()));
@ -22,6 +27,11 @@ MainWindow::MainWindow(QWidget *parent)
connect(pViewer, &HexViewer::RuleNamesChanged, pRuleDialog, &RuleDialog::SetRuleNames); connect(pViewer, &HexViewer::RuleNamesChanged, pRuleDialog, &RuleDialog::SetRuleNames);
connect(pViewer, &HexViewer::VarsChanged, pRuleDialog, &RuleDialog::SetVars); connect(pViewer, &HexViewer::VarsChanged, pRuleDialog, &RuleDialog::SetVars);
connect(pViewer, &HexViewer::BaseDirChanged, pRuleDialog, &RuleDialog::SetBaseDir);
connect(pRuleDialog, &RuleDialog::BaseDirChanged, pViewer, &HexViewer::SetBaseDir);
connect(pViewer, &HexViewer::BaseDirChanged, this, &MainWindow::pSetBaseDir);
connect(pRuleDialog, &RuleDialog::BaseDirChanged, this, &MainWindow::pSetBaseDir);
pDelRuleDialog = new DeleteRuleDialog(this); pDelRuleDialog = new DeleteRuleDialog(this);
pDelRuleDialog->SetRuleNames(pViewer->RuleNames()); pDelRuleDialog->SetRuleNames(pViewer->RuleNames());
connect(pViewer, &HexViewer::RuleNamesChanged, pDelRuleDialog, &DeleteRuleDialog::SetRuleNames); connect(pViewer, &HexViewer::RuleNamesChanged, pDelRuleDialog, &DeleteRuleDialog::SetRuleNames);
@ -30,12 +40,99 @@ MainWindow::MainWindow(QWidget *parent)
connect(ui->actionClear_Rules, &QAction::triggered, pViewer, &HexViewer::ClearRules); connect(ui->actionClear_Rules, &QAction::triggered, pViewer, &HexViewer::ClearRules);
connect(ui->actionPop_Rule, &QAction::triggered, pViewer, &HexViewer::PopRule); connect(ui->actionPop_Rule, &QAction::triggered, pViewer, &HexViewer::PopRule);
connect(ui->actionRun_Rules, &QAction::triggered, pViewer, &HexViewer::RunRules); connect(ui->actionRun_Rules, &QAction::triggered, pViewer, &HexViewer::ParseRules);
connect(ui->actionSave, &QAction::triggered, pViewer, &HexViewer::SaveRules); connect(ui->actionOpen, &QAction::triggered, pViewer, &HexViewer::OpenFile);
connect(ui->actionOpen, &QAction::triggered, pViewer, &HexViewer::OpenRules); connect(ui->actionSave_Rule_File, &QAction::triggered, pViewer, &HexViewer::SaveRules);
connect(ui->actionOpen_Rule_File, &QAction::triggered, pViewer, &HexViewer::OpenRules);
connect(pViewer, &HexViewer::FileOpened, this, &MainWindow::pAddRecentFile);
connect(ui->actionExit, &QAction::triggered, this, &MainWindow::close);
QSettings HexesSettings(pSettingsName, QSettings::IniFormat);
if (HexesSettings.contains("file/basedir")) {
pBaseDir = HexesSettings.value("file/basedir").toString();
pViewer->SetBaseDir(pBaseDir);
pRuleDialog->SetBaseDir(pBaseDir);
}
}
void MainWindow::pClearActions() {
for (int i = 0; i < pActions.size(); i++) {
delete pActions[i];
}
pActions.clear();
}
void MainWindow::pSetBaseDir(QString baseDir) {
pBaseDir = baseDir;
}
void MainWindow::showEvent(QShowEvent *event) {
QMainWindow::showEvent(event);
pInitializeRecentFiles();
}
void MainWindow::pClearRecentFiles() {
QMenu *recentFileMenu = ui->menuRecent_Files;
recentFileMenu->clear();
pRecentFiles.clear();
pClearActions();
pActions << new QAction("Clear Recents...", recentFileMenu);
recentFileMenu->addAction(pActions.last());
connect(pActions.last(), &QAction::triggered, this, &MainWindow::pClearRecentFiles);
}
void MainWindow::pAddRecentFile(QString fileName) {
setWindowTitle(QString("Hexes - %1").arg(fileName));
QMenu *recentFileMenu = ui->menuRecent_Files;
recentFileMenu->clear();
pRecentFiles.push_back(fileName);
if (pRecentFiles.size() > 5) {
pRecentFiles.pop_front();
}
QVector<QAction*> pActions;
for (int i = 0; i < pRecentFiles.size(); i++) {
QString recentFileName = pRecentFiles[i];
pActions << new QAction(recentFileName, recentFileMenu);
}
recentFileMenu->addActions(pActions);
}
void MainWindow::pInitializeRecentFiles() {
pClearActions();
QMenu *recentFileMenu = ui->menuRecent_Files;
QSettings HexesSettings(pSettingsName, QSettings::IniFormat);
if (HexesSettings.contains("menu/recentfiles")) {
pRecentFiles = HexesSettings.value("menu/recentfiles").toStringList();
for (int i = 0; i < pRecentFiles.size(); i++) {
QString recentFileName = pRecentFiles[i];
pActions << new QAction(recentFileName, recentFileMenu);
recentFileMenu->addAction(pActions.last());
connect(pActions.last(), &QAction::triggered, this, [&]() {
pViewer->SetFileName(recentFileName);
});
}
recentFileMenu->addSeparator();
pActions << new QAction("Clear Recents...", recentFileMenu);
recentFileMenu->addAction(pActions.last());
connect(pActions.last(), &QAction::triggered, this, &MainWindow::pClearRecentFiles);
}
} }
MainWindow::~MainWindow() { MainWindow::~MainWindow() {
QSettings HexesSettings(pSettingsName, QSettings::IniFormat);
HexesSettings.setValue("menu/recentfiles", QVariant::fromValue(pRecentFiles));
HexesSettings.setValue("file/basedir", QVariant::fromValue(pBaseDir));
pClearActions();
HexesLogger::DeleteInstance();
delete ui; delete ui;
delete pViewer; delete pViewer;
delete pRuleDialog; delete pRuleDialog;

View File

@ -4,12 +4,14 @@
#include "hexviewer.h" #include "hexviewer.h"
#include "ruledialog.h" #include "ruledialog.h"
#include "deleteruledialog.h" #include "deleteruledialog.h"
#include "hexeslogger.h"
#include <QMainWindow> #include <QMainWindow>
#include <QFile> #include <QFile>
#include <QDebug> #include <QDebug>
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QDockWidget> #include <QDockWidget>
#include <QMetaType>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; } namespace Ui { class MainWindow; }
@ -23,10 +25,26 @@ public:
MainWindow(QWidget *parent = nullptr); MainWindow(QWidget *parent = nullptr);
~MainWindow(); ~MainWindow();
void AddRecentFile(const QString fileName);
private slots:
void pInitializeRecentFiles();
void pAddRecentFile(QString fileName);
void pClearRecentFiles();
void pClearActions();
void pSetBaseDir(QString baseDir);
protected:
void showEvent(QShowEvent* event) override;
private: private:
Ui::MainWindow *ui; Ui::MainWindow *ui;
HexViewer *pViewer; HexViewer *pViewer;
RuleDialog *pRuleDialog; RuleDialog *pRuleDialog;
DeleteRuleDialog *pDelRuleDialog; DeleteRuleDialog *pDelRuleDialog;
QString pSettingsName;
QStringList pRecentFiles;
QVector<QAction*> pActions;
QString pBaseDir;
}; };
#endif // MAINWINDOW_H #endif // MAINWINDOW_H

View File

@ -33,15 +33,26 @@
<property name="title"> <property name="title">
<string>File</string> <string>File</string>
</property> </property>
<widget class="QMenu" name="menuRecent_Files">
<property name="title">
<string>Recent Files</string>
</property>
<addaction name="separator"/>
<addaction name="actionClear_Recents_2"/>
</widget>
<addaction name="actionNew"/> <addaction name="actionNew"/>
<addaction name="actionOpen"/> <addaction name="actionOpen"/>
<addaction name="actionClose"/> <addaction name="actionClose"/>
<addaction name="actionSave"/> <addaction name="separator"/>
<addaction name="actionSave_Rule_File"/>
<addaction name="actionSave_As"/> <addaction name="actionSave_As"/>
<addaction name="actionOpen_Rule_File"/>
<addaction name="separator"/> <addaction name="separator"/>
<addaction name="actionSave_all"/> <addaction name="actionSave_all"/>
<addaction name="actionClose_all"/> <addaction name="actionClose_all"/>
<addaction name="separator"/> <addaction name="separator"/>
<addaction name="menuRecent_Files"/>
<addaction name="separator"/>
<addaction name="actionExit"/> <addaction name="actionExit"/>
</widget> </widget>
<widget class="QMenu" name="menuRule"> <widget class="QMenu" name="menuRule">
@ -215,6 +226,55 @@
</font> </font>
</property> </property>
</action> </action>
<action name="actionRecentFiles">
<property name="text">
<string>RecentFiles</string>
</property>
</action>
<action name="actionClear_Recents">
<property name="text">
<string>Clear Recents</string>
</property>
<property name="font">
<font>
<family>CommitMono</family>
<pointsize>7</pointsize>
</font>
</property>
</action>
<action name="actionOpen_Rule_File">
<property name="text">
<string>Open Rule File</string>
</property>
<property name="font">
<font>
<family>CommitMono</family>
<pointsize>8</pointsize>
</font>
</property>
</action>
<action name="actionSave_Rule_File">
<property name="text">
<string>Save Rule File</string>
</property>
<property name="font">
<font>
<family>CommitMono</family>
<pointsize>8</pointsize>
</font>
</property>
</action>
<action name="actionClear_Recents_2">
<property name="text">
<string>Clear Recents</string>
</property>
<property name="font">
<font>
<family>CommitMono</family>
<pointsize>8</pointsize>
</font>
</property>
</action>
</widget> </widget>
<resources/> <resources/>
<connections/> <connections/>

Binary file not shown.

BIN
repeat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 954 B

View File

@ -11,6 +11,10 @@ Rule::Rule() {
pRepeatCount = 0; pRepeatCount = 0;
pPreSkipCount = 0; pPreSkipCount = 0;
pPostSkipCount = 0; pPostSkipCount = 0;
pRepeatOffset = 0;
pSkipOffset = 0;
pPreSkipOffset = 0;
pPostSkipOffset = 0;
} }
Rule::Rule(const Rule &rule) { Rule::Rule(const Rule &rule) {
@ -24,6 +28,10 @@ Rule::Rule(const Rule &rule) {
pRepeatCount = rule.RepeatCount(); pRepeatCount = rule.RepeatCount();
pPreSkipCount = rule.PreSkipCount(); pPreSkipCount = rule.PreSkipCount();
pPostSkipCount = rule.PostSkipCount(); pPostSkipCount = rule.PostSkipCount();
pRepeatOffset = rule.RepeatOffset();
pSkipOffset = rule.SkipOffset();
pPreSkipOffset = rule.PreSkipOffset();
pPostSkipOffset = rule.PostSkipOffset();
} }
Rule &Rule::operator=(const Rule &rule) { Rule &Rule::operator=(const Rule &rule) {
@ -41,10 +49,29 @@ Rule &Rule::operator=(const Rule &rule) {
pRepeatCount = rule.RepeatCount(); pRepeatCount = rule.RepeatCount();
pPreSkipCount = rule.PreSkipCount(); pPreSkipCount = rule.PreSkipCount();
pPostSkipCount = rule.PostSkipCount(); pPostSkipCount = rule.PostSkipCount();
pRepeatOffset = rule.RepeatOffset();
pSkipOffset = rule.SkipOffset();
pPreSkipOffset = rule.PreSkipOffset();
pPostSkipOffset = rule.PostSkipOffset();
return *this; return *this;
} }
bool Rule::operator!() const {
bool nameNull = pName.isEmpty();
bool typeNull = pType == TYPE_NONE;
bool propsNull = pProps.isEmpty();
bool byteOrderNull = pByteOrder == BYTE_ORDER_NONE;
bool lengthNull = pLength < 0;
bool valueNull = pValue.isLower() || pValue.isEmpty();
bool repeatNull = pRepeatCount < 0;
bool preSkipNull = pPreSkipCount < 0;
bool postSkipNull = pPostSkipCount < 0;
return nameNull && typeNull && propsNull &&
byteOrderNull && lengthNull && valueNull &&
repeatNull && preSkipNull && postSkipNull;
}
bool Rule::operator==(const Rule &rule) const { bool Rule::operator==(const Rule &rule) const {
bool nameMatch = pName == rule.Name(); bool nameMatch = pName == rule.Name();
bool typeMatch = pType == rule.Type(); bool typeMatch = pType == rule.Type();
@ -65,7 +92,7 @@ bool Rule::operator!=(const Rule &rule) const {
} }
void Rule::SetName(const QString name) { void Rule::SetName(const QString name) {
pName = name; pName = name.toUpper();
} }
QString Rule::Name() const { QString Rule::Name() const {
@ -137,6 +164,7 @@ int Rule::RepeatCount() const {
} }
void Rule::SetPreSkipCount(int preSkipCount) { void Rule::SetPreSkipCount(int preSkipCount) {
if (pPreSkipCount < 0) { return; }
pPreSkipCount = preSkipCount; pPreSkipCount = preSkipCount;
} }
@ -152,6 +180,38 @@ int Rule::PostSkipCount() const {
return pPostSkipCount; return pPostSkipCount;
} }
void Rule::SetRepeatOffset(int repeatOffset) {
pRepeatOffset = repeatOffset;
}
int Rule::RepeatOffset() const {
return pRepeatOffset;
}
void Rule::SetSkipOffset(int skipOffset) {
pSkipOffset = skipOffset;
}
int Rule::SkipOffset() const {
return pSkipOffset;
}
void Rule::SetPreSkipOffset(int preSkipOffset) {
pPreSkipOffset = preSkipOffset;
}
int Rule::PreSkipOffset() const {
return pPreSkipOffset;
}
void Rule::SetPostSkipOffset(int postSkipOffset) {
pPostSkipOffset = postSkipOffset;
}
int Rule::PostSkipOffset() const {
return pPostSkipOffset;
}
QColor Rule::pGenerateColor() { QColor Rule::pGenerateColor() {
QRandomGenerator64 *globalRand = QRandomGenerator64::global(); QRandomGenerator64 *globalRand = QRandomGenerator64::global();
double rRand = globalRand->generateDouble(); double rRand = globalRand->generateDouble();

80
rule.h
View File

@ -35,6 +35,7 @@ public:
Rule(const Rule &rule); Rule(const Rule &rule);
Rule &operator=(const Rule &rule); Rule &operator=(const Rule &rule);
bool operator!() const;
bool operator==(const Rule& rule) const; bool operator==(const Rule& rule) const;
bool operator!=(const Rule& rule) const; bool operator!=(const Rule& rule) const;
@ -46,6 +47,13 @@ public:
arch << rule.ByteOrder(); arch << rule.ByteOrder();
arch << rule.Length(); arch << rule.Length();
arch << rule.Value(); arch << rule.Value();
arch << rule.PreSkipCount();
arch << rule.RepeatCount();
arch << rule.PostSkipCount();
arch << rule.SkipOffset();
arch << rule.RepeatOffset();
arch << rule.PreSkipOffset();
arch << rule.PostSkipOffset();
return arch; return arch;
} }
friend QDataStream &operator>>(QDataStream &arch, Rule &rule) { friend QDataStream &operator>>(QDataStream &arch, Rule &rule) {
@ -56,31 +64,75 @@ public:
BYTE_ORDER ruleByteOrder = BYTE_ORDER_NONE; BYTE_ORDER ruleByteOrder = BYTE_ORDER_NONE;
int ruleLength = 0; int ruleLength = 0;
QString ruleValue = ""; QString ruleValue = "";
int preSkipCount = 0;
int repeatCount = 0;
int postSkipCount = 0;
int repeatOffset;
int skipOffset;
int preSkipOffset;
int postSkipOffset;
arch >> ruleName; arch >> ruleName;
rule.SetName(ruleName); rule.SetName(ruleName);
arch >> ruleType; arch >> ruleType;
rule.SetType(ruleType); rule.SetType(ruleType);
arch >> ruleProps; arch >> ruleProps;
rule.SetProperties(ruleProps); rule.SetProperties(ruleProps);
arch >> ruleColor; arch >> ruleColor;
rule.SetColor(ruleColor); rule.SetColor(ruleColor);
arch >> ruleByteOrder; arch >> ruleByteOrder;
rule.SetByteOrder(ruleByteOrder); rule.SetByteOrder(ruleByteOrder);
arch >> ruleLength; arch >> ruleLength;
rule.SetLength(ruleLength); rule.SetLength(ruleLength);
arch >> ruleValue; arch >> ruleValue;
rule.SetValue(ruleValue); rule.SetValue(ruleValue);
arch >> preSkipCount;
rule.SetPreSkipCount(preSkipCount);
arch >> repeatCount;
rule.SetRepeatCount(repeatCount);
arch >> postSkipCount;
rule.SetPostSkipCount(postSkipCount);
arch >> repeatOffset;
rule.SetRepeatOffset(repeatOffset);
arch >> skipOffset;
rule.SetSkipOffset(skipOffset);
arch >> preSkipOffset;
rule.SetPreSkipOffset(preSkipOffset);
arch >> postSkipOffset;
rule.SetPostSkipOffset(postSkipOffset);
return arch; return arch;
} }
operator QString() const {
return QString("Rule: %1\n"
"-Type: %2\n"
"-Color: %4\n"
"-ByteOrder: %5\n"
"-Length: %6\n"
"-Value: %7\n"
"-PreSkipCount: %8\n"
"-RepeatCount: %9\n"
"-PostSkipCount: %10\n"
"-SkipOffset: %11\n"
"-RepeatOffset: %12\n"
"-PreSkipOffset: %13\n"
"-PostSkipOffset: %14\n")
.arg(pName)
.arg(pType)
.arg(pColor.name())
.arg(pByteOrder)
.arg(pLength)
.arg(pValue)
.arg(pPreSkipCount)
.arg(pRepeatCount)
.arg(pPostSkipCount)
.arg(pSkipOffset)
.arg(pRepeatOffset)
.arg(pPreSkipOffset)
.arg(pPostSkipOffset);
}
void SetName(const QString name); void SetName(const QString name);
QString Name() const; QString Name() const;
@ -114,6 +166,18 @@ public:
void SetPostSkipCount(int postSkipCount); void SetPostSkipCount(int postSkipCount);
int PostSkipCount() const; int PostSkipCount() const;
void SetRepeatOffset(int repeatOffset);
int RepeatOffset() const;
void SetSkipOffset(int skipOffset);
int SkipOffset() const;
void SetPreSkipOffset(int preSkipOffset);
int PreSkipOffset() const;
void SetPostSkipOffset(int postSkipOffset);
int PostSkipOffset() const;
private: private:
QString pName; QString pName;
RULE_TYPE pType; RULE_TYPE pType;
@ -125,6 +189,10 @@ private:
int pRepeatCount; int pRepeatCount;
int pPreSkipCount; int pPreSkipCount;
int pPostSkipCount; int pPostSkipCount;
int pRepeatOffset;
int pSkipOffset;
int pPreSkipOffset;
int pPostSkipOffset;
QColor pGenerateColor(); QColor pGenerateColor();
int pGetTypeLength(RULE_TYPE ruleType); int pGetTypeLength(RULE_TYPE ruleType);

View File

@ -9,12 +9,42 @@ RuleDialog::RuleDialog(QWidget *parent) :
pRuleNames = QStringList(); pRuleNames = QStringList();
pVars = QMap<QString, BlockValue>(); pVars = QMap<QString, BlockValue>();
pDefaultRuleCount = 1; pDefaultRuleCount = 1;
pRules = QVector<Rule>(); pRules = QQueue<Rule>();
pSnippetDir = "C:/";
pHideLayout(ui->layout_Skip); ui->toolBox->setCurrentIndex(0);
ui->groupBox_2->hide();
ui->groupBox_PreSkip->hide(); ui->groupBox_SkipOptions->hide();
ui->groupBox_PostSkip->hide(); pHideLayout(ui->layout_ByteOrder);
ui->label_Pre_SkipOffset->hide();
ui->spinBox_Pre_Offset->hide();
ui->label_SkipOffset->hide();
ui->spinBox_Skip_Offset->hide();
ui->label_Post_SkipOffset->hide();
ui->spinBox_Post_Offset->hide();
ui->label_RepeatOffset->hide();
ui->spinBox_Repeat_Offset->hide();
connect(ui->checkBox_PreSkip_Offset, &QCheckBox::toggled, this, [this](bool toggled) {
ui->label_Pre_SkipOffset->setVisible(toggled);
ui->spinBox_Pre_Offset->setVisible(toggled);
});
connect(ui->checkBox_Skip_Offset, &QCheckBox::toggled, this, [this](bool toggled) {
ui->label_SkipOffset->setVisible(toggled);
ui->spinBox_Skip_Offset->setVisible(toggled);
});
connect(ui->checkBox_PostSkip_Offset, &QCheckBox::toggled, this, [this](bool toggled) {
ui->label_Post_SkipOffset->setVisible(toggled);
ui->spinBox_Post_Offset->setVisible(toggled);
});
connect(ui->checkBox_Repeat_Offset, &QCheckBox::toggled, this, [this](bool toggled) {
ui->label_RepeatOffset->setVisible(toggled);
ui->spinBox_Repeat_Offset->setVisible(toggled);
});
connect(ui->verticalScrollBar, &QScrollBar::valueChanged, ui->widget_RulePreview, &RulePreview::SetScrollValue); connect(ui->verticalScrollBar, &QScrollBar::valueChanged, ui->widget_RulePreview, &RulePreview::SetScrollValue);
connect(ui->widget_RulePreview, &RulePreview::ScrollMaxChanged, ui->verticalScrollBar, &QScrollBar::setMaximum); connect(ui->widget_RulePreview, &RulePreview::ScrollMaxChanged, ui->verticalScrollBar, &QScrollBar::setMaximum);
@ -27,13 +57,18 @@ RuleDialog::RuleDialog(QWidget *parent) :
connect(ui->pushButton_Save, &QPushButton::clicked, this, &RuleDialog::pSaveRules); connect(ui->pushButton_Save, &QPushButton::clicked, this, &RuleDialog::pSaveRules);
connect(ui->comboBox_Type, &QComboBox::currentIndexChanged, this, &RuleDialog::pTypeChanged); connect(ui->comboBox_Type, &QComboBox::currentIndexChanged, this, &RuleDialog::pTypeChanged);
connect(ui->pushButton_Import, &QPushButton::clicked, this, &RuleDialog::pImportSnippet);
connect(ui->pushButton_Export, &QPushButton::clicked, this, &RuleDialog::pExportSnippet);
connect(this, &RuleDialog::RulesChanged, ui->widget_RulePreview, &RulePreview::SetRules); connect(this, &RuleDialog::RulesChanged, ui->widget_RulePreview, &RulePreview::SetRules);
connect(ui->groupBox_RepeatRule, &QGroupBox::toggled, this, &RuleDialog::pRepeatToggled); ui->comboBox_Repeat_Vars->hide();
connect(ui->radioButton_Repeat_PrevVar, &QRadioButton::toggled, this, &RuleDialog::pRepeat_PrevVarToggled);
connect(ui->radioButton_Repeat_StaticVal, &QRadioButton::toggled, this, &RuleDialog::pRepeat_StaticValToggled);
ui->comboBox_Vars->hide(); ui->comboBox_Skip_Vars->hide();
connect(ui->radioButton_PrevVar, &QRadioButton::toggled, this, &RuleDialog::pPrevVarToggled); connect(ui->radioButton_Skip_PrevVar, &QRadioButton::toggled, this, &RuleDialog::pSkip_PrevVarToggled);
connect(ui->radioButton_StaticVal, &QRadioButton::toggled, this, &RuleDialog::pStaticValToggled); connect(ui->radioButton_Skip_StaticVal, &QRadioButton::toggled, this, &RuleDialog::pSkip_StaticValToggled);
ui->comboBox_Pre_Vars->hide(); ui->comboBox_Pre_Vars->hide();
connect(ui->radioButton_Pre_StaticVal, &QRadioButton::toggled, this, &RuleDialog::pPre_StaticValToggled); connect(ui->radioButton_Pre_StaticVal, &QRadioButton::toggled, this, &RuleDialog::pPre_StaticValToggled);
@ -49,97 +84,100 @@ RuleDialog::~RuleDialog() {
} }
void RuleDialog::pQueueRule() { void RuleDialog::pQueueRule() {
int index = ui->comboBox_Type->currentIndex(); QString name = ui->lineEdit_Name->text();
RULE_TYPE type = (RULE_TYPE)index; if (name == "") { return; }
if (type == TYPE_NONE) { return; }
int repeatCount = 0; RULE_TYPE type = (RULE_TYPE)ui->comboBox_Type->currentIndex();
int preSkip = 0;
int postSkip = 0; Rule rule;
if (ui->groupBox_RepeatRule->isChecked()) { rule.SetName(name);
if (ui->radioButton_PrevVar->isChecked()) { rule.SetType(type);
QString itemText = ui->comboBox_Vars->currentText();
if (type == TYPE_NONE) {
return;
} else if (type == TYPE_SKIP) {
if (ui->radioButton_Skip_PrevVar->isChecked()) {
QString itemText = ui->comboBox_Skip_Vars->currentText();
const QString leadingNumber = itemText.split('.').first() + "."; const QString leadingNumber = itemText.split('.').first() + ".";
const QString varText = itemText.replace(leadingNumber, "") const QString varText = itemText.replace(leadingNumber, "")
.split('(').first().trimmed(); .split('(').first().trimmed();
BlockValue blockVal = pVars[varText]; BlockValue blockVal = pVars[varText];
repeatCount = blockVal.ValueToInt(); rule.SetLength(blockVal.ToInt());
} else if (ui->radioButton_StaticVal->isChecked()) { } else if (ui->radioButton_Skip_StaticVal->isChecked()) {
repeatCount = ui->spinBox_2->value(); rule.SetLength(ui->spinBox_Skip_StaticVal->value());
} }
} }
QString name = ui->lineEdit_Name->text();
if (name == "") { return; } if (ui->radioButton_Repeat_StaticVal->isChecked()) {
rule.SetRepeatCount(ui->spinBox_Repeat_StaticVal->value());
} else {
QString itemText = ui->comboBox_Repeat_Vars->currentText();
const QString leadingNumber = itemText.split('.').first() + ".";
const QString varText = itemText.replace(leadingNumber, "")
.split('(').first().trimmed();
BlockValue blockVal = pVars[varText];
rule.SetRepeatCount(blockVal.ToInt());
}
if (ui->groupBox_PreSkip->isChecked()) { if (ui->groupBox_PreSkip->isChecked()) {
if (ui->radioButton_Pre_StaticVal->isChecked()) { if (ui->radioButton_Pre_StaticVal->isChecked()) {
preSkip = ui->spinBox_Pre_StaticVal->value(); rule.SetPreSkipCount(ui->spinBox_Pre_StaticVal->value());
} else { } else {
QString itemText = ui->comboBox_Pre_Vars->currentText(); QString itemText = ui->comboBox_Pre_Vars->currentText();
const QString leadingNumber = itemText.split('.').first() + "."; const QString leadingNumber = itemText.split('.').first() + ".";
const QString varText = itemText.replace(leadingNumber, "") const QString varText = itemText.replace(leadingNumber, "")
.split('(').first().trimmed(); .split('(').first().trimmed();
BlockValue blockVal = pVars[varText]; BlockValue blockVal = pVars[varText];
preSkip = blockVal.ValueToInt(); rule.SetPreSkipCount(blockVal.ToInt());
} }
} }
if (ui->groupBox_PostSkip->isChecked()) { if (ui->groupBox_PostSkip->isChecked()) {
if (ui->radioButton_Post_StaticVal->isChecked()) { if (ui->radioButton_Post_StaticVal->isChecked()) {
postSkip = ui->spinBox_Post_StaticVal->value(); rule.SetPostSkipCount(ui->spinBox_Post_StaticVal->value());
} else { } else {
QString itemText = ui->comboBox_Post_Vars->currentText(); QString itemText = ui->comboBox_Post_Vars->currentText();
const QString leadingNumber = itemText.split('.').first() + "."; const QString leadingNumber = itemText.split('.').first() + ".";
const QString varText = itemText.replace(leadingNumber, "") const QString varText = itemText.replace(leadingNumber, "")
.split('(').first().trimmed(); .split('(').first().trimmed();
BlockValue blockVal = pVars[varText]; BlockValue blockVal = pVars[varText];
postSkip = blockVal.ValueToInt(); rule.SetPostSkipCount(blockVal.ToInt());
} }
} }
QString ruleName = name;
BYTE_ORDER byteOrder = BYTE_ORDER_NONE;
if (ui->radioButton_BE->isChecked()) { if (ui->radioButton_BE->isChecked()) {
byteOrder = BYTE_ORDER_BE; rule.SetByteOrder(BYTE_ORDER_BE);
} else { } else {
byteOrder = BYTE_ORDER_LE; rule.SetByteOrder(BYTE_ORDER_LE);
} }
Rule rule; rule.SetSkipOffset(ui->spinBox_Skip_Offset->value());
rule.SetName(ruleName); rule.SetPreSkipOffset(ui->spinBox_Pre_Offset->value());
rule.SetType(type); rule.SetPostSkipOffset(ui->spinBox_Post_Offset->value());
rule.SetByteOrder(byteOrder); rule.SetRepeatOffset(ui->spinBox_Repeat_Offset->value());
rule.SetRepeatCount(repeatCount);
rule.SetPreSkipCount(preSkip);
rule.SetPostSkipCount(postSkip);
if (index == 1) { // skip pRules.enqueue(rule);
rule.SetLength(ui->spinBox->value()); ui->widget_RulePreview->SetRules(pRules.toList());
}
pRules.push_back(rule);
ui->widget_RulePreview->SetRules(pRules);
} }
void RuleDialog::pSaveRules() { void RuleDialog::pSaveRules() {
emit RulesChanged(pRules); emit RulesChanged(pRules.toList());
close(); close();
} }
void RuleDialog::pClearRules() { void RuleDialog::pClearRules() {
pRules.clear(); pRules.clear();
ui->widget_RulePreview->SetRules(pRules); ui->widget_RulePreview->SetRules(pRules.toList());
} }
void RuleDialog::pPopFirstRule() { void RuleDialog::pPopFirstRule() {
pRules.pop_front(); pRules.pop_front();
ui->widget_RulePreview->SetRules(pRules); ui->widget_RulePreview->SetRules(pRules.toList());
} }
void RuleDialog::pPopLastRule() { void RuleDialog::pPopLastRule() {
pRules.pop_back(); pRules.pop_back();
ui->widget_RulePreview->SetRules(pRules); ui->widget_RulePreview->SetRules(pRules.toList());
} }
void RuleDialog::pCancelDialog() { void RuleDialog::pCancelDialog() {
@ -147,6 +185,70 @@ void RuleDialog::pCancelDialog() {
close(); close();
} }
void RuleDialog::pImportSnippet() {
QStringList filters;
filters.append("Rule File (*.hrs)");
filters.append("All Files(*.*)");
QFileDialog importDialog(this);
importDialog.setWindowTitle("Open Hexes Rule Snippet");
importDialog.setFileMode(QFileDialog::ExistingFile);
importDialog.setDirectory(pSnippetDir);
importDialog.setAcceptMode(QFileDialog::AcceptOpen);
importDialog.setNameFilters(filters);
if (importDialog.exec() != QDialog::Accepted) {
qDebug() << "Open snippet dialog was not accepted!";
return;
}
QString snippetPath = importDialog.selectedFiles().first();
QString tempSnippetPath = snippetPath;
pSnippetDir = tempSnippetPath.replace(tempSnippetPath.split('/').last(), "");
emit BaseDirChanged(pSnippetDir);
QFile snippetFile(snippetPath);
if (!snippetFile.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to open snippet file!";
return;
}
snippetFile.close();
QSettings snippetImport(snippetPath, QSettings::IniFormat);
pRules = snippetImport.value("rules").value<QQueue<Rule>>();
ui->widget_RulePreview->SetRules(pRules.toList());
}
void RuleDialog::pExportSnippet() {
QStringList filters;
filters.append("Rule File (*.hrs)");
filters.append("All Files(*.*)");
QFileDialog exportDialog(this);
exportDialog.setWindowTitle("Save Hexes Rule Snippet");
exportDialog.setDirectory(pSnippetDir);
exportDialog.setAcceptMode(QFileDialog::AcceptSave);
exportDialog.setNameFilters(filters);
if (exportDialog.exec() != QDialog::Accepted) {
qDebug() << "Save snippet dialog was not accepted!";
return;
}
QString snippetPath = exportDialog.selectedFiles().first();
QString tempSnippetPath = snippetPath;
pSnippetDir = tempSnippetPath.replace(tempSnippetPath.split('/').last(), "");
emit BaseDirChanged(pSnippetDir);
QFile snippetFile(snippetPath);
if (!snippetFile.open(QIODevice::WriteOnly)) {
qDebug() << "Failed to save snippet file!";
return;
}
snippetFile.close();
QSettings snippetExport(snippetPath, QSettings::IniFormat);
snippetExport.setValue("rules", QVariant::fromValue(pRules));
}
void RuleDialog::pHideLayout(QLayout* layout) { void RuleDialog::pHideLayout(QLayout* layout) {
if (!layout) if (!layout)
return; return;
@ -171,16 +273,17 @@ void RuleDialog::pShowLayout(QLayout* layout) {
} }
} }
void RuleDialog::pTypeChanged(int index) { void RuleDialog::pTypeChanged(int index) {
pHideLayout(ui->layout_Skip); ui->groupBox_SkipOptions->hide();
pShowLayout(ui->layout_ByteOrder); pShowLayout(ui->layout_ByteOrder);
switch (index) { switch (index) {
case 0: // none case 0: // none
ui->groupBox_SkipOptions->hide();
pHideLayout(ui->layout_ByteOrder);
break; break;
case 1: // skip case 1: // skip
pShowLayout(ui->layout_Skip); ui->groupBox_SkipOptions->show();
pHideLayout(ui->layout_ByteOrder); pHideLayout(ui->layout_ByteOrder);
break; break;
case 2: // int8 [1] case 2: // int8 [1]
@ -202,19 +305,24 @@ void RuleDialog::pTypeChanged(int index) {
} }
} }
void RuleDialog::pRepeatToggled(bool toggled) { void RuleDialog::pSkip_PrevVarToggled(bool toggled) {
ui->groupBox_PreSkip->setVisible(toggled); ui->comboBox_Skip_Vars->setVisible(toggled);
ui->groupBox_PostSkip->setVisible(toggled); ui->spinBox_Skip_StaticVal->setVisible(!toggled);
} }
void RuleDialog::pPrevVarToggled(bool toggled) { void RuleDialog::pSkip_StaticValToggled(bool toggled) {
ui->comboBox_Vars->setVisible(toggled); ui->comboBox_Skip_Vars->setVisible(!toggled);
ui->spinBox_2->setVisible(!toggled); ui->spinBox_Skip_StaticVal->setVisible(toggled);
} }
void RuleDialog::pStaticValToggled(bool toggled) { void RuleDialog::pRepeat_PrevVarToggled(bool toggled) {
ui->comboBox_Vars->setVisible(!toggled); ui->comboBox_Repeat_Vars->setVisible(toggled);
ui->spinBox_2->setVisible(toggled); ui->spinBox_Repeat_StaticVal->setVisible(!toggled);
}
void RuleDialog::pRepeat_StaticValToggled(bool toggled) {
ui->comboBox_Repeat_Vars->setVisible(!toggled);
ui->spinBox_Repeat_StaticVal->setVisible(toggled);
} }
void RuleDialog::pPre_PrevVarToggled(bool toggled) { void RuleDialog::pPre_PrevVarToggled(bool toggled) {
@ -238,21 +346,50 @@ void RuleDialog::pPost_StaticValToggled(bool toggled) {
} }
void RuleDialog::closeEvent(QCloseEvent *event) { void RuleDialog::closeEvent(QCloseEvent *event) {
pDefaultRuleCount++; ui->toolBox->setCurrentIndex(0);
if (pRuleNames.contains(QString("RULE %1").arg(pDefaultRuleCount))) {
pDefaultRuleCount++;
}
const QString defaultName = QString("RULE %1").arg(pDefaultRuleCount); const QString defaultName = QString("RULE %1").arg(pDefaultRuleCount);
ui->lineEdit_Name->setText(defaultName); ui->lineEdit_Name->setText(defaultName);
ui->comboBox_Type->setCurrentIndex(0); ui->comboBox_Type->setCurrentIndex(0);
ui->radioButton_LE->setChecked(true); ui->radioButton_LE->setChecked(true);
ui->spinBox->setValue(1);
ui->radioButton_StaticVal->setChecked(true); ui->spinBox_Skip_StaticVal->setValue(1);
ui->spinBox_2->setValue(1); ui->checkBox_Skip_Offset->setChecked(false);
ui->comboBox_Vars->setCurrentIndex(0); ui->label_SkipOffset->hide();
ui->spinBox_Skip_Offset->hide();
ui->radioButton_Skip_StaticVal->setChecked(true);
ui->spinBox_Skip_StaticVal->setValue(0);
ui->comboBox_Skip_Vars->setCurrentIndex(0);
ui->groupBox_PreSkip->setChecked(false);
ui->checkBox_PreSkip_Offset->setChecked(false);
ui->radioButton_Pre_StaticVal->setChecked(true);
ui->spinBox_Pre_StaticVal->show();
ui->comboBox_Pre_Vars->hide();
ui->spinBox_Pre_Offset->setValue(0);
ui->spinBox_Pre_StaticVal->setValue(0);
ui->groupBox_PostSkip->setChecked(false);
ui->checkBox_PostSkip_Offset->setChecked(false);
ui->radioButton_Post_StaticVal->setChecked(true);
ui->spinBox_Post_StaticVal->show();
ui->comboBox_Post_Vars->hide();
ui->spinBox_Post_Offset->setValue(0);
ui->spinBox_Post_StaticVal->setValue(0);
ui->radioButton_Repeat_StaticVal->setChecked(true);
ui->checkBox_Repeat_Offset->setChecked(false);
ui->label_RepeatOffset->hide();
ui->spinBox_Repeat_Offset->hide();
ui->spinBox_Repeat_StaticVal->setValue(0);
pRules.clear(); pRules.clear();
ui->widget_RulePreview->SetRules(pRules); ui->widget_RulePreview->SetRules(pRules.toList());
QDialog::closeEvent(event); QDialog::closeEvent(event);
} }
@ -265,17 +402,24 @@ void RuleDialog::SetRule(const Rule rule) {
ui->lineEdit_Name->setText(rule.Name()); ui->lineEdit_Name->setText(rule.Name());
if (rule.Type() == TYPE_SKIP) { if (rule.Type() == TYPE_SKIP) {
ui->spinBox->setValue(rule.Length()); ui->spinBox_Skip_StaticVal->setValue(rule.Length());
} }
} }
void RuleDialog::SetBaseDir(QString dir) {
pSnippetDir = dir;
}
void RuleDialog::SetRuleNames(QStringList ruleNames) { void RuleDialog::SetRuleNames(QStringList ruleNames) {
pRuleNames = ruleNames; pRuleNames = ruleNames;
} }
void RuleDialog::SetVars(QMap<QString, BlockValue> vars) { void RuleDialog::SetVars(QMap<QString, BlockValue> vars) {
ui->comboBox_Vars->clear(); ui->comboBox_Repeat_Vars->clear();
ui->comboBox_Vars->addItem("Select Variable"); ui->comboBox_Repeat_Vars->addItem("Select Variable");
ui->comboBox_Skip_Vars->clear();
ui->comboBox_Skip_Vars->addItem("Select Variable");
ui->comboBox_Pre_Vars->clear(); ui->comboBox_Pre_Vars->clear();
ui->comboBox_Pre_Vars->addItem("Select Variable"); ui->comboBox_Pre_Vars->addItem("Select Variable");
@ -289,8 +433,9 @@ void RuleDialog::SetVars(QMap<QString, BlockValue> vars) {
QString varName = (QString)key; QString varName = (QString)key;
BlockValue varVal = (BlockValue)value; BlockValue varVal = (BlockValue)value;
QString itemName = QString("%1. %2 (%3)") QString itemName = QString("%1. %2 (%3)")
.arg(QString::number(i), varName, varVal.Value().toString()); .arg(QString::number(i), varName, varVal.ToVariant().toString());
ui->comboBox_Vars->addItem(itemName); ui->comboBox_Repeat_Vars->addItem(itemName);
ui->comboBox_Skip_Vars->addItem(itemName);
ui->comboBox_Pre_Vars->addItem(itemName); ui->comboBox_Pre_Vars->addItem(itemName);
ui->comboBox_Post_Vars->addItem(itemName); ui->comboBox_Post_Vars->addItem(itemName);
} }

View File

@ -23,6 +23,8 @@ public:
Rule GetRule(); Rule GetRule();
void SetRule(const Rule rule); void SetRule(const Rule rule);
void SetBaseDir(QString dir);
void SetRuleNames(QStringList ruleNames); void SetRuleNames(QStringList ruleNames);
void SetVars(QMap<QString, BlockValue> vars); void SetVars(QMap<QString, BlockValue> vars);
@ -33,18 +35,22 @@ private slots:
void pPopFirstRule(); void pPopFirstRule();
void pPopLastRule(); void pPopLastRule();
void pCancelDialog(); void pCancelDialog();
void pImportSnippet();
void pExportSnippet();
void pTypeChanged(int index); void pTypeChanged(int index);
void pRepeatToggled(bool toggled); void pSkip_PrevVarToggled(bool toggled);
void pPrevVarToggled(bool toggled); void pSkip_StaticValToggled(bool toggled);
void pStaticValToggled(bool toggled);
void pPre_PrevVarToggled(bool toggled); void pPre_PrevVarToggled(bool toggled);
void pPre_StaticValToggled(bool toggled); void pPre_StaticValToggled(bool toggled);
void pPost_PrevVarToggled(bool toggled); void pPost_PrevVarToggled(bool toggled);
void pPost_StaticValToggled(bool toggled); void pPost_StaticValToggled(bool toggled);
void pRepeat_PrevVarToggled(bool toggled);
void pRepeat_StaticValToggled(bool toggled);
signals: signals:
void RuleChanged(Rule rule); void RuleChanged(Rule rule);
void RulesChanged(QVector<Rule> rules); void RulesChanged(QVector<Rule> rules);
void BaseDirChanged(QString dir);
protected: protected:
void closeEvent(QCloseEvent *event) override; void closeEvent(QCloseEvent *event) override;
@ -55,7 +61,8 @@ private:
QStringList pRuleNames; QStringList pRuleNames;
QMap<QString, BlockValue> pVars; QMap<QString, BlockValue> pVars;
int pDefaultRuleCount; int pDefaultRuleCount;
QVector<Rule> pRules; QQueue<Rule> pRules;
QString pSnippetDir;
void pHideLayout(QLayout *layout); void pHideLayout(QLayout *layout);
void pShowLayout(QLayout *layout); void pShowLayout(QLayout *layout);

File diff suppressed because it is too large Load Diff

View File

@ -72,8 +72,9 @@ void RulePreview::paintEvent(QPaintEvent *event) {
int ruleIndex = 1; int ruleIndex = 1;
QRectF rulesRect = event->rect(); QRectF rulesRect = event->rect();
painter.setBrush(Qt::white); painter.setBrush(QColor(45, 45, 45));
painter.drawRect(rulesRect); painter.setPen(QPen(QColor(60, 60, 60), 2));
painter.drawRoundedRect(rulesRect, 8, 8);
painter.setFont(QFont("CommitMono", 7)); painter.setFont(QFont("CommitMono", 7));
@ -88,12 +89,13 @@ void RulePreview::paintEvent(QPaintEvent *event) {
QColor ruleBackground(rule.Color()); QColor ruleBackground(rule.Color());
ruleBackground.setAlpha(75); ruleBackground.setAlpha(75);
painter.setBrush(ruleBackground); painter.setBrush(ruleBackground);
int offset = ruleIndex * 5;
// Draw the rule information in the rule stack on the right side // Draw the rule information in the rule stack on the right side
QRectF ruleBackgroundRect(rulesRect.left(), -pScrollValue + rulesRect.top() + 1 + (QFontMetrics(painter.font()).height() * 3) * (ruleIndex - 1), QRectF ruleBackgroundRect(rulesRect.left() + 10, offset - pScrollValue + rulesRect.top() + 11 + (QFontMetrics(painter.font()).height() * 3) * (ruleIndex - 1),
rulesRect.width(), QFontMetrics(painter.font()).height() * 3); rulesRect.width() - 20, QFontMetrics(painter.font()).height() * 3);
QRectF ruleRect(rulesRect.left() + 1, -pScrollValue + rulesRect.top() + 2 + (QFontMetrics(painter.font()).height() * 3) * (ruleIndex - 1), QRectF ruleRect(rulesRect.left() + 11, offset - pScrollValue + rulesRect.top() + 12 + (QFontMetrics(painter.font()).height() * 3) * (ruleIndex - 1),
rulesRect.width() - 2, QFontMetrics(painter.font()).height() * 3); rulesRect.width() - 22, QFontMetrics(painter.font()).height() * 3);
painter.drawRect(ruleBackgroundRect); painter.drawRect(ruleBackgroundRect);
pScrollMax = qMax(pScrollMax, (int)ruleRect.bottom()); pScrollMax = qMax(pScrollMax, (int)ruleRect.bottom());
@ -119,7 +121,7 @@ void RulePreview::paintEvent(QPaintEvent *event) {
break; break;
} }
painter.setPen(Qt::black); painter.setPen(Qt::white);
QString paddedIndex = QString::number(ruleIndex).rightJustified(2, '0'); QString paddedIndex = QString::number(ruleIndex).rightJustified(2, '0');
QString ruleName = rule.Name().toUpper(); QString ruleName = rule.Name().toUpper();
@ -129,7 +131,6 @@ void RulePreview::paintEvent(QPaintEvent *event) {
if (!isSkip) { if (!isSkip) {
painter.drawText(ruleRect, Qt::AlignRight, ruleByteOrder); painter.drawText(ruleRect, Qt::AlignRight, ruleByteOrder);
} }
ruleIndex++; ruleIndex++;
} }
emit ScrollMaxChanged(qMax(0, static_cast<int>(pScrollMax - rulesRect.height()))); emit ScrollMaxChanged(qMax(0, static_cast<int>(pScrollMax - rulesRect.height())));

BIN
skip.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 807 B