diff --git a/designer/QHexEditPlugin.cpp b/designer/QHexEditPlugin.cpp index 61d206c..5b26321 100644 --- a/designer/QHexEditPlugin.cpp +++ b/designer/QHexEditPlugin.cpp @@ -21,12 +21,12 @@ #include -QHexEditPlugin::QHexEditPlugin(QObject * parent) : QObject(parent) +QHexEditPlugin::QHexEditPlugin(QObject *parent) + : QObject(parent) { initialized = false; } - bool QHexEditPlugin::isContainer() const { return false; @@ -45,23 +45,23 @@ QIcon QHexEditPlugin::icon() const QString QHexEditPlugin::domXml() const { return "\n" - " \n" - " \n" - " \n" - " 0\n" - " 0\n" - " 100\n" - " 100\n" - " \n" - " \n" - " \n" - " QHexEditWidget\n" - " \n" - " \n" - " QHexEdit widget allow to edit the data in hex view.\n" - " \n" - " \n" - "\n"; + " \n" + " \n" + " \n" + " 0\n" + " 0\n" + " 100\n" + " 100\n" + " \n" + " \n" + " \n" + " QHexEditWidget\n" + " \n" + " \n" + " QHexEdit widget allow to edit the data in hex view.\n" + " \n" + " \n" + "\n"; } QString QHexEditPlugin::group() const @@ -89,7 +89,7 @@ QString QHexEditPlugin::whatsThis() const return ""; } -QWidget * QHexEditPlugin::createWidget(QWidget *parent) +QWidget *QHexEditPlugin::createWidget(QWidget *parent) { return new QHexEdit(parent); } @@ -102,6 +102,6 @@ void QHexEditPlugin::initialize(QDesignerFormEditorInterface * /*core*/) initialized = true; } -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(QHexEditPlugin, QHexEditPlugin) #endif diff --git a/designer/QHexEditPlugin.h b/designer/QHexEditPlugin.h index 5ca81e1..8571ae4 100644 --- a/designer/QHexEditPlugin.h +++ b/designer/QHexEditPlugin.h @@ -21,7 +21,7 @@ #include -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include #else #include @@ -31,12 +31,12 @@ class QHexEditPlugin : public QObject, public QDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "com.qt-project.Qt.QHexEditPlugin") #endif public: - QHexEditPlugin(QObject * parent = 0); + QHexEditPlugin(QObject *parent = 0); bool isContainer() const; bool isInitialized() const; @@ -52,7 +52,6 @@ class QHexEditPlugin : public QObject, public QDesignerCustomWidgetInterface private: bool initialized; - }; #endif diff --git a/example/main.cpp b/example/main.cpp index 525b489..4b09867 100644 --- a/example/main.cpp +++ b/example/main.cpp @@ -21,9 +21,9 @@ #include #include #include +#include #include #include -#include #include "mainwindow.h" @@ -33,18 +33,15 @@ struct ParsedOptions QString file = ""; }; -struct CommandLineParseResult { - enum class Status { - Ok, - Error, - VersionRequested, - HelpRequested - }; +struct CommandLineParseResult +{ + enum class Status { Ok, Error, VersionRequested, HelpRequested }; Status statusCode = Status::Ok; std::optional errorString = std::nullopt; }; -CommandLineParseResult parseCommandLine(QCommandLineParser &parser, ParsedOptions *query) { +CommandLineParseResult parseCommandLine(QCommandLineParser &parser, ParsedOptions *query) +{ using Status = CommandLineParseResult::Status; const QCommandLineOption helpOption = parser.addHelpOption(); @@ -52,23 +49,23 @@ CommandLineParseResult parseCommandLine(QCommandLineParser &parser, ParsedOption parser.addPositionalArgument("file", "File to open"); if (!parser.parse(QCoreApplication::arguments())) - return { Status::Error, parser.errorText() }; + return {Status::Error, parser.errorText()}; if (parser.isSet(versionOption)) - return { Status::VersionRequested }; + return {Status::VersionRequested}; if (parser.isSet(helpOption)) - return { Status::HelpRequested }; + return {Status::HelpRequested}; const QStringList positionalArguments = parser.positionalArguments(); if (!positionalArguments.isEmpty()) { if (positionalArguments.size() > 1) - return { Status::Error, "Several 'name' arguments specified." }; + return {Status::Error, "Several 'name' arguments specified."}; query->hasFile = true; query->file = positionalArguments.first(); } - return { Status::Ok }; + return {Status::Ok}; } int main(int argc, char *argv[]) @@ -87,11 +84,11 @@ int main(int argc, char *argv[]) QTranslator translator_qt; - #if QT_VERSION < 0x060000 +#if QT_VERSION < 0x060000 QString path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); - #else +#else QString path = QLibraryInfo::path(QLibraryInfo::TranslationsPath); - #endif +#endif if (translator_qt.load(QLocale(), "qt", "_", path)) QCoreApplication::installTranslator(&translator_qt); @@ -106,22 +103,22 @@ int main(int argc, char *argv[]) CommandLineParseResult parseResult = parseCommandLine(parser, &query); switch (parseResult.statusCode) { - case Status::Ok: - break; - - case Status::Error: - std::fputs(qPrintable(parseResult.errorString.value_or("Unknown error occurred")), stderr); - std::fputs("\n\n", stderr); - std::fputs(qPrintable(parser.helpText()), stderr); - return 1; - - case Status::VersionRequested: - parser.showVersion(); - return 0; - - case Status::HelpRequested: - parser.showHelp(); - return 0; + case Status::Ok: + break; + + case Status::Error: + std::fputs(qPrintable(parseResult.errorString.value_or("Unknown error occurred")), stderr); + std::fputs("\n\n", stderr); + std::fputs(qPrintable(parser.helpText()), stderr); + return 1; + + case Status::VersionRequested: + parser.showVersion(); + return 0; + + case Status::HelpRequested: + parser.showHelp(); + return 0; } if (query.hasFile) diff --git a/example/mainwindow.cpp b/example/mainwindow.cpp index 1de791b..04af7a7 100644 --- a/example/mainwindow.cpp +++ b/example/mainwindow.cpp @@ -16,19 +16,19 @@ * License along with this library; if not, see * https://www.gnu.org/licenses/ */ -#include -#include -#include -#include -#include #include -#include -#include +#include #include -#include #include #include +#include +#include +#include +#include +#include +#include #include +#include #include "mainwindow.h" @@ -37,7 +37,7 @@ /*****************************************************************************/ MainWindow::MainWindow() { - setAcceptDrops( true ); + setAcceptDrops(true); init(); setCurrentFile(""); } @@ -49,42 +49,38 @@ void MainWindow::closeEvent(QCloseEvent *event) { writeSettings(); - if (isModified) - { + if (isModified) { QMessageBox msgBox; msgBox.setText(tr("The file has been modified.")); msgBox.setInformativeText(tr("Do you want to save your changes?")); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Save); switch (msgBox.exec()) { - case QMessageBox::Save: - save(); - event->accept(); - break; - case QMessageBox::Discard: - event->accept(); - break; - default: - event->ignore(); - break; + case QMessageBox::Save: + save(); + event->accept(); + break; + case QMessageBox::Discard: + event->accept(); + break; + default: + event->ignore(); + break; } } else { event->accept(); } } - void MainWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasUrls()) event->accept(); } - void MainWindow::dropEvent(QDropEvent *event) { - if (event->mimeData()->hasUrls()) - { + if (event->mimeData()->hasUrls()) { QList urls = event->mimeData()->urls(); QString filePath = urls.at(0).toLocalFile(); loadFile(filePath); @@ -97,8 +93,7 @@ void MainWindow::dropEvent(QDropEvent *event) /*****************************************************************************/ void MainWindow::about() { - QMessageBox::about(this, tr("About QHexEdit"), - tr("The QHexEdit example is a short Demo of the QHexEdit Widget.")); + QMessageBox::about(this, tr("About QHexEdit"), tr("The QHexEdit example is a short Demo of the QHexEdit Widget.")); } void MainWindow::dataChanged() @@ -137,8 +132,7 @@ bool MainWindow::save() bool MainWindow::saveAs() { - QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), - curFile); + QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curFile); if (fileName.isEmpty()) return false; @@ -148,14 +142,10 @@ bool MainWindow::saveAs() void MainWindow::saveSelectionToReadableFile() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save To Readable File")); - if (!fileName.isEmpty()) - { + if (!fileName.isEmpty()) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("QHexEdit"), - tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + QMessageBox::warning(this, tr("QHexEdit"), tr("Cannot write file %1:\n%2.").arg(fileName).arg(file.errorString())); return; } @@ -170,14 +160,10 @@ void MainWindow::saveSelectionToReadableFile() void MainWindow::saveToReadableFile() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save To Readable File")); - if (!fileName.isEmpty()) - { + if (!fileName.isEmpty()) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { - QMessageBox::warning(this, tr("QHexEdit"), - tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + QMessageBox::warning(this, tr("QHexEdit"), tr("Cannot write file %1:\n%2.").arg(fileName).arg(file.errorString())); return; } @@ -390,10 +376,7 @@ void MainWindow::loadFile(const QString &fileName) { file.setFileName(fileName); if (!hexEdit->setData(file)) { - QMessageBox::warning(this, tr("QHexEdit"), - tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())); + QMessageBox::warning(this, tr("QHexEdit"), tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString())); return; } setCurrentFile(fileName); @@ -443,8 +426,7 @@ bool MainWindow::saveFile(const QString &fileName) bool ok = hexEdit->write(file); if (QFile::exists(fileName)) ok = QFile::remove(fileName); - if (ok) - { + if (ok) { file.setFileName(tmpFileName); ok = file.copy(fileName); if (ok) { @@ -456,9 +438,7 @@ bool MainWindow::saveFile(const QString &fileName) QApplication::restoreOverrideCursor(); if (!ok) { - QMessageBox::warning(this, tr("QHexEdit"), - tr("Cannot write file %1.") - .arg(fileName)); + QMessageBox::warning(this, tr("QHexEdit"), tr("Cannot write file %1.").arg(fileName)); return false; } diff --git a/example/optionsdialog.cpp b/example/optionsdialog.cpp index 8ca4010..6cb920b 100644 --- a/example/optionsdialog.cpp +++ b/example/optionsdialog.cpp @@ -24,9 +24,9 @@ #include "optionsdialog.h" #include "ui_optionsdialog.h" -OptionsDialog::OptionsDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::OptionsDialog) +OptionsDialog::OptionsDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::OptionsDialog) { ui->setupUi(this); @@ -128,14 +128,13 @@ void OptionsDialog::on_cbPalette_currentIndexChanged(int index) { QSettings settings; settings.setValue("Theme", index); - - switch (index) - { - case 1: - qApp->setPalette(_darkMode); - break; - default: - qApp->setPalette(_defaultMode); - break; + + switch (index) { + case 1: + qApp->setPalette(_darkMode); + break; + default: + qApp->setPalette(_defaultMode); + break; } } \ No newline at end of file diff --git a/example/optionsdialog.h b/example/optionsdialog.h index d78e517..fbc1fec 100644 --- a/example/optionsdialog.h +++ b/example/optionsdialog.h @@ -19,13 +19,13 @@ #ifndef OPTIONSDIALOG_H #define OPTIONSDIALOG_H -#include #include +#include #include "../src/qhexedit.h" namespace Ui { - class OptionsDialog; +class OptionsDialog; } class OptionsDialog : public QDialog diff --git a/example/searchdialog.cpp b/example/searchdialog.cpp index f86aa1d..7959474 100644 --- a/example/searchdialog.cpp +++ b/example/searchdialog.cpp @@ -21,17 +21,17 @@ #include -SearchDialog::SearchDialog(QHexEdit *hexEdit, QWidget *parent) : - QDialog(parent), - ui(new Ui::SearchDialog) +SearchDialog::SearchDialog(QHexEdit *hexEdit, QWidget *parent) + : QDialog(parent) + , ui(new Ui::SearchDialog) { - ui->setupUi(this); - _hexEdit = hexEdit; + ui->setupUi(this); + _hexEdit = hexEdit; } SearchDialog::~SearchDialog() { - delete ui; + delete ui; } qint64 SearchDialog::findNext() @@ -40,8 +40,7 @@ qint64 SearchDialog::findNext() _findBa = getContent(ui->cbFindFormat->currentIndex(), ui->cbFind->currentText()); qint64 idx = -1; - if (_findBa.length() > 0) - { + if (_findBa.length() > 0) { if (ui->cbBackwards->isChecked()) idx = _hexEdit->lastIndexOf(_findBa, from); else @@ -58,8 +57,7 @@ void SearchDialog::on_pbFind_clicked() void SearchDialog::on_pbReplace_clicked() { int idx = findNext(); - if (idx >= 0) - { + if (idx >= 0) { QByteArray replaceBa = getContent(ui->cbReplaceFormat->currentIndex(), ui->cbReplace->currentText()); replaceOccurrence(idx, replaceBa); } @@ -71,11 +69,9 @@ void SearchDialog::on_pbReplaceAll_clicked() int idx = 0; int goOn = QMessageBox::Yes; - while ((idx >= 0) && (goOn == QMessageBox::Yes)) - { + while ((idx >= 0) && (goOn == QMessageBox::Yes)) { idx = findNext(); - if (idx >= 0) - { + if (idx >= 0) { QByteArray replaceBa = getContent(ui->cbReplaceFormat->currentIndex(), ui->cbReplace->currentText()); int result = replaceOccurrence(idx, replaceBa); @@ -91,18 +87,16 @@ void SearchDialog::on_pbReplaceAll_clicked() QMessageBox::information(this, tr("QHexEdit"), QString(tr("%1 occurrences replaced.")).arg(replaceCounter)); } - QByteArray SearchDialog::getContent(int comboIndex, const QString &input) { QByteArray findBa; - switch (comboIndex) - { - case 0: // hex - findBa = QByteArray::fromHex(input.toLatin1()); - break; - case 1: // text - findBa = input.toUtf8(); - break; + switch (comboIndex) { + case 0: // hex + findBa = QByteArray::fromHex(input.toLatin1()); + break; + case 1: // text + findBa = input.toUtf8(); + break; } return findBa; } @@ -110,22 +104,15 @@ QByteArray SearchDialog::getContent(int comboIndex, const QString &input) qint64 SearchDialog::replaceOccurrence(qint64 idx, const QByteArray &replaceBa) { int result = QMessageBox::Yes; - if (replaceBa.length() >= 0) - { - if (ui->cbPrompt->isChecked()) - { - result = QMessageBox::question(this, tr("QHexEdit"), - tr("Replace occurrence?"), - QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); + if (replaceBa.length() >= 0) { + if (ui->cbPrompt->isChecked()) { + result = QMessageBox::question(this, tr("QHexEdit"), tr("Replace occurrence?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); - if (result == QMessageBox::Yes) - { + if (result == QMessageBox::Yes) { _hexEdit->replace(idx, replaceBa.length(), replaceBa); _hexEdit->update(); } - } - else - { + } else { _hexEdit->replace(idx, _findBa.length(), replaceBa); } } diff --git a/example/searchdialog.h b/example/searchdialog.h index d124ee8..af27f69 100644 --- a/example/searchdialog.h +++ b/example/searchdialog.h @@ -19,12 +19,12 @@ #ifndef SEARCHDIALOG_H #define SEARCHDIALOG_H +#include "../src/qhexedit.h" #include #include -#include "../src/qhexedit.h" namespace Ui { - class SearchDialog; +class SearchDialog; } class SearchDialog : public QDialog diff --git a/src/chunks.cpp b/src/chunks.cpp index 40847dd..f0c8ae8 100644 --- a/src/chunks.cpp +++ b/src/chunks.cpp @@ -28,13 +28,15 @@ // ***************************************** Constructors and file settings -Chunks::Chunks(QObject *parent): QObject(parent) +Chunks::Chunks(QObject *parent) + : QObject(parent) { QBuffer *buf = new QBuffer(this); setIODevice(*buf); } -Chunks::Chunks(QIODevice &ioDevice, QObject *parent): QObject(parent) +Chunks::Chunks(QIODevice &ioDevice, QObject *parent) + : QObject(parent) { setIODevice(ioDevice); } @@ -43,12 +45,11 @@ bool Chunks::setIODevice(QIODevice &ioDevice) { _ioDevice = &ioDevice; bool ok = _ioDevice->open(QIODevice::ReadOnly); - if (ok) // Try to open IODevice + if (ok) // Try to open IODevice { _size = _ioDevice->size(); _ioDevice->close(); - } - else // Fallback is an empty buffer + } else // Fallback is an empty buffer { QBuffer *buf = new QBuffer(this); _ioDevice = buf; @@ -59,7 +60,6 @@ bool Chunks::setIODevice(QIODevice &ioDevice) return ok; } - // ***************************************** Getting data out of Chunks QByteArray Chunks::data(qint64 pos, qint64 maxSize, QByteArray *highlighted) const @@ -79,18 +79,15 @@ QByteArray Chunks::data(qint64 pos, qint64 maxSize, QByteArray *highlighted) con if (maxSize < 0) maxSize = _size; - else - if ((pos + maxSize) > _size) - maxSize = _size - pos; + else if ((pos + maxSize) > _size) + maxSize = _size - pos; _ioDevice->open(QIODevice::ReadOnly); - while (maxSize > 0) - { + while (maxSize > 0) { chunk.absPos = LLONG_MAX; bool chunksLoopOngoing = true; - while ((chunkIdx < _chunks.count()) && chunksLoopOngoing) - { + while ((chunkIdx < _chunks.count()) && chunksLoopOngoing) { // In this section, we track changes before our required data and // we take the editdet data, if availible. ioDelta is a difference // counter to justify the read pointer to the original data, if @@ -99,31 +96,26 @@ QByteArray Chunks::data(qint64 pos, qint64 maxSize, QByteArray *highlighted) con chunk = _chunks[chunkIdx]; if (chunk.absPos > pos) chunksLoopOngoing = false; - else - { + else { chunkIdx += 1; qint64 count; qint64 chunkOfs = pos - chunk.absPos; - if (maxSize > ((qint64)chunk.data.size() - chunkOfs)) - { - count = (qint64)chunk.data.size() - chunkOfs; + if (maxSize > ((qint64) chunk.data.size() - chunkOfs)) { + count = (qint64) chunk.data.size() - chunkOfs; ioDelta += CHUNK_SIZE - chunk.data.size(); - } - else + } else count = maxSize; - if (count > 0) - { - buffer += chunk.data.mid(chunkOfs, (int)count); + if (count > 0) { + buffer += chunk.data.mid(chunkOfs, (int) count); maxSize -= count; pos += count; if (highlighted) - *highlighted += chunk.dataChanged.mid(chunkOfs, (int)count); + *highlighted += chunk.dataChanged.mid(chunkOfs, (int) count); } } } - if ((maxSize > 0) && (pos < chunk.absPos)) - { + if ((maxSize > 0) && (pos < chunk.absPos)) { // In this section, we read data from the original source. This only will // happen, whe no copied data is available @@ -152,10 +144,8 @@ bool Chunks::write(QIODevice &iODevice, qint64 pos, qint64 count) const if (count == -1) count = _size; bool ok = iODevice.open(QIODevice::WriteOnly); - if (ok) - { - for (qint64 idx=pos; idx < count; idx += BUFFER_SIZE) - { + if (ok) { + for (qint64 idx = pos; idx < count; idx += BUFFER_SIZE) { QByteArray ba = data(idx, BUFFER_SIZE); iODevice.write(ba); } @@ -164,7 +154,6 @@ bool Chunks::write(QIODevice &iODevice, qint64 pos, qint64 count) const return ok; } - // ***************************************** Set and get highlighting infos void Chunks::setDataChanged(qint64 pos, bool dataChanged) @@ -173,22 +162,19 @@ void Chunks::setDataChanged(qint64 pos, bool dataChanged) return; int chunkIdx = getChunkIndex(pos); qint64 posInBa = pos - _chunks[chunkIdx].absPos; - _chunks[chunkIdx].dataChanged[(int)posInBa] = char(dataChanged); + _chunks[chunkIdx].dataChanged[(int) posInBa] = char(dataChanged); } bool Chunks::dataChanged(qint64 pos) const { - foreach (Chunk chunk, _chunks) - { - if (pos >= chunk.absPos && pos < (chunk.absPos + chunk.dataChanged.size())) - { + foreach (Chunk chunk, _chunks) { + if (pos >= chunk.absPos && pos < (chunk.absPos + chunk.dataChanged.size())) { return bool(chunk.dataChanged.at(pos - chunk.absPos)); } } return false; } - // ***************************************** Search API qint64 Chunks::indexOf(const QByteArray &ba, qint64 from) const @@ -196,12 +182,11 @@ qint64 Chunks::indexOf(const QByteArray &ba, qint64 from) const qint64 result = -1; QByteArray buffer; - for (qint64 pos=from; (pos < _size) && (result < 0); pos += BUFFER_SIZE) - { + for (qint64 pos = from; (pos < _size) && (result < 0); pos += BUFFER_SIZE) { buffer = data(pos, BUFFER_SIZE + ba.size() - 1); int findPos = buffer.indexOf(ba); if (findPos >= 0) - result = pos + (qint64)findPos; + result = pos + (qint64) findPos; } return result; } @@ -211,20 +196,18 @@ qint64 Chunks::lastIndexOf(const QByteArray &ba, qint64 from) const qint64 result = -1; QByteArray buffer; - for (qint64 pos=from; (pos > 0) && (result < 0); pos -= BUFFER_SIZE) - { - qint64 sPos = pos - BUFFER_SIZE - (qint64)ba.size() + 1; + for (qint64 pos = from; (pos > 0) && (result < 0); pos -= BUFFER_SIZE) { + qint64 sPos = pos - BUFFER_SIZE - (qint64) ba.size() + 1; if (sPos < 0) sPos = 0; buffer = data(sPos, pos - sPos); int findPos = buffer.lastIndexOf(ba); if (findPos >= 0) - result = sPos + (qint64)findPos; + result = sPos + (qint64) findPos; } return result; } - // ***************************************** Char manipulations bool Chunks::insert(qint64 pos, char b) @@ -233,13 +216,13 @@ bool Chunks::insert(qint64 pos, char b) return false; int chunkIdx; if (pos == _size) - chunkIdx = getChunkIndex(pos-1); + chunkIdx = getChunkIndex(pos - 1); else chunkIdx = getChunkIndex(pos); qint64 posInBa = pos - _chunks[chunkIdx].absPos; _chunks[chunkIdx].data.insert(posInBa, b); _chunks[chunkIdx].dataChanged.insert(posInBa, char(1)); - for (int idx=chunkIdx+1; idx < _chunks.size(); idx++) + for (int idx = chunkIdx + 1; idx < _chunks.size(); idx++) _chunks[idx].absPos += 1; _size += 1; _pos = pos; @@ -252,8 +235,8 @@ bool Chunks::overwrite(qint64 pos, char b) return false; int chunkIdx = getChunkIndex(pos); qint64 posInBa = pos - _chunks[chunkIdx].absPos; - _chunks[chunkIdx].data[(int)posInBa] = b; - _chunks[chunkIdx].dataChanged[(int)posInBa] = char(1); + _chunks[chunkIdx].data[(int) posInBa] = b; + _chunks[chunkIdx].dataChanged[(int) posInBa] = char(1); _pos = pos; return true; } @@ -266,14 +249,13 @@ bool Chunks::removeAt(qint64 pos) qint64 posInBa = pos - _chunks[chunkIdx].absPos; _chunks[chunkIdx].data.remove(posInBa, 1); _chunks[chunkIdx].dataChanged.remove(posInBa, 1); - for (int idx=chunkIdx+1; idx < _chunks.size(); idx++) + for (int idx = chunkIdx + 1; idx < _chunks.size(); idx++) _chunks[idx].absPos -= 1; _size -= 1; _pos = pos; return true; } - // ***************************************** Utility functions char Chunks::operator[](qint64 pos) const @@ -301,17 +283,13 @@ int Chunks::getChunkIndex(qint64 absPos) const int insertIdx = 0; qint64 ioDelta = 0; - - for (int idx=0; idx < _chunks.size(); idx++) - { + for (int idx = 0; idx < _chunks.size(); idx++) { Chunk chunk = _chunks[idx]; - if ((absPos >= chunk.absPos) && (absPos < (chunk.absPos + chunk.data.size()))) - { + if ((absPos >= chunk.absPos) && (absPos < (chunk.absPos + chunk.data.size()))) { foundIdx = idx; break; } - if (absPos < chunk.absPos) - { + if (absPos < chunk.absPos) { insertIdx = idx; break; } @@ -319,8 +297,7 @@ int Chunks::getChunkIndex(qint64 absPos) const insertIdx = idx + 1; } - if (foundIdx == -1) - { + if (foundIdx == -1) { Chunk newChunk; qint64 readAbsPos = absPos - ioDelta; qint64 readPos = (readAbsPos & READ_CHUNK_MASK); @@ -336,7 +313,6 @@ int Chunks::getChunkIndex(qint64 absPos) const return foundIdx; } - #ifdef MODUL_TEST int Chunks::chunkSize() { diff --git a/src/chunks.h b/src/chunks.h index 1291328..17446a9 100644 --- a/src/chunks.h +++ b/src/chunks.h @@ -44,9 +44,9 @@ struct Chunk qint64 absPos; }; -class Chunks: public QObject +class Chunks : public QObject { -Q_OBJECT + Q_OBJECT public: // Constructors and file settings explicit Chunks(QObject *parent); @@ -54,8 +54,8 @@ Q_OBJECT bool setIODevice(QIODevice &ioDevice); // Getting data out of Chunks - QByteArray data(qint64 pos=0, qint64 count=-1, QByteArray *highlighted=0) const; - bool write(QIODevice &iODevice, qint64 pos=0, qint64 count=-1) const; + QByteArray data(qint64 pos = 0, qint64 count = -1, QByteArray *highlighted = 0) const; + bool write(QIODevice &iODevice, qint64 pos = 0, qint64 count = -1) const; // Set and get highlighting infos void setDataChanged(qint64 pos, bool dataChanged); @@ -75,11 +75,10 @@ Q_OBJECT qint64 pos() const; qint64 size() const; - private: int getChunkIndex(qint64 absPos) const; - QIODevice * _ioDevice; + QIODevice *_ioDevice; qint64 _pos; qint64 _size; mutable QList _chunks; diff --git a/src/color_manager.cpp b/src/color_manager.cpp index a148409..74a46d7 100644 --- a/src/color_manager.cpp +++ b/src/color_manager.cpp @@ -20,10 +20,10 @@ #include #include -#include #include +#include -ColoredArea::ColoredArea() +ColoredArea::ColoredArea() { _posStart = 0; _posEnd = 0; @@ -98,13 +98,12 @@ void ColoredArea::setRange(qint64 posStart, qint64 posEnd) _posEnd = posEnd; } -void ColoredArea::clear() +void ColoredArea::clear() { _posStart = 0; _posEnd = 0; } - /********************************************* */ ColorManager::ColorManager() @@ -126,20 +125,16 @@ void ColorManager::setPalette(const QPalette &palette) ColoredArea ColorManager::markedArea(qint64 pos, Area area, Chunks *chunks) const { // prio 1 selection - if (pos >= _selection.posStart() && pos < _selection.posEnd()) - { + if (pos >= _selection.posStart() && pos < _selection.posEnd()) { return _selection; } // prio 2 highlighting (changed data) - if (chunks->dataChanged(pos)) - { + if (chunks->dataChanged(pos)) { return _highlighting; } // prio 3 user defined areas - foreach (ColoredArea area, _userAreas) - { - if (pos >= area.posStart() && pos < area.posEnd()) - { + foreach (ColoredArea area, _userAreas) { + if (pos >= area.posStart() && pos < area.posEnd()) { return area; } } @@ -150,15 +145,15 @@ ColoredArea ColorManager::markedArea(qint64 pos, Area area, Chunks *chunks) cons const ColoredArea &ColorManager::notMarked(Area area) const { switch (area) { - case Area::Address: - return _address; - break; - case Area::Ascii: - return _ascii; - break; - case Area::Hex: - return _hex; - break; + case Area::Address: + return _address; + break; + case Area::Ascii: + return _ascii; + break; + case Area::Hex: + return _hex; + break; } return _hex; // should never happen } @@ -173,12 +168,12 @@ ColoredArea &ColorManager::selection() return _selection; } -const ColoredArea& ColorManager::highlighting() const +const ColoredArea &ColorManager::highlighting() const { return _highlighting; } -ColoredArea& ColorManager::highlighting() +ColoredArea &ColorManager::highlighting() { return _highlighting; } diff --git a/src/color_manager.h b/src/color_manager.h index 01961c6..1df88e6 100644 --- a/src/color_manager.h +++ b/src/color_manager.h @@ -76,7 +76,6 @@ class ColoredArea QBrush _areaStyle; }; - class ColorManager { public: @@ -84,10 +83,10 @@ class ColorManager ColorManager(); // reload the palette and adapt the apeareance - void setPalette(const QPalette &palette); + void setPalette(const QPalette& palette); // Method returns color definitions for data at position pos in area area - ColoredArea markedArea(qint64 pos, Area area, Chunks *chunks) const; + ColoredArea markedArea(qint64 pos, Area area, Chunks* chunks) const; // Method returns standard collors (without marking) const ColoredArea& notMarked(Area) const; diff --git a/src/commands.cpp b/src/commands.cpp index 0f7eedb..6eef274 100644 --- a/src/commands.cpp +++ b/src/commands.cpp @@ -19,15 +19,13 @@ #include "commands.h" #include - // Helper class to store single byte commands class CharCommand : public QUndoCommand { public: - enum CCmd {insert, removeAt, overwrite}; + enum CCmd { insert, removeAt, overwrite }; - CharCommand(Chunks * chunks, CCmd cmd, qint64 charPos, char newChar, - QUndoCommand *parent=nullptr); + CharCommand(Chunks *chunks, CCmd cmd, qint64 charPos, char newChar, QUndoCommand *parent = nullptr); void undo(); void redo(); @@ -35,7 +33,7 @@ class CharCommand : public QUndoCommand int id() const { return 1234; } private: - Chunks * _chunks; + Chunks *_chunks; qint64 _charPos; bool _wasChanged; char _newChar; @@ -43,7 +41,7 @@ class CharCommand : public QUndoCommand CCmd _cmd; }; -CharCommand::CharCommand(Chunks * chunks, CCmd cmd, qint64 charPos, char newChar, QUndoCommand *parent) +CharCommand::CharCommand(Chunks *chunks, CCmd cmd, qint64 charPos, char newChar, QUndoCommand *parent) : QUndoCommand(parent) , _chunks(chunks) , _charPos(charPos) @@ -51,19 +49,16 @@ CharCommand::CharCommand(Chunks * chunks, CCmd cmd, qint64 charPos, char newChar , _newChar(newChar) , _oldChar('\0') , _cmd(cmd) -{ -} +{} bool CharCommand::mergeWith(const QUndoCommand *command) { const CharCommand *nextCommand = static_cast(command); bool result = false; - if (_cmd != CharCommand::removeAt) - { + if (_cmd != CharCommand::removeAt) { if (nextCommand->_cmd == overwrite) - if (nextCommand->_charPos == _charPos) - { + if (nextCommand->_charPos == _charPos) { _newChar = nextCommand->_newChar; result = true; } @@ -73,43 +68,41 @@ bool CharCommand::mergeWith(const QUndoCommand *command) void CharCommand::undo() { - switch (_cmd) - { - case insert: - _chunks->removeAt(_charPos); - break; - case overwrite: - _chunks->overwrite(_charPos, _oldChar); - _chunks->setDataChanged(_charPos, _wasChanged); - break; - case removeAt: - _chunks->insert(_charPos, _oldChar); - _chunks->setDataChanged(_charPos, _wasChanged); - break; + switch (_cmd) { + case insert: + _chunks->removeAt(_charPos); + break; + case overwrite: + _chunks->overwrite(_charPos, _oldChar); + _chunks->setDataChanged(_charPos, _wasChanged); + break; + case removeAt: + _chunks->insert(_charPos, _oldChar); + _chunks->setDataChanged(_charPos, _wasChanged); + break; } } void CharCommand::redo() { - switch (_cmd) - { - case insert: - _chunks->insert(_charPos, _newChar); - break; - case overwrite: - _oldChar = (*_chunks)[_charPos]; - _wasChanged = _chunks->dataChanged(_charPos); - _chunks->overwrite(_charPos, _newChar); - break; - case removeAt: - _oldChar = (*_chunks)[_charPos]; - _wasChanged = _chunks->dataChanged(_charPos); - _chunks->removeAt(_charPos); - break; + switch (_cmd) { + case insert: + _chunks->insert(_charPos, _newChar); + break; + case overwrite: + _oldChar = (*_chunks)[_charPos]; + _wasChanged = _chunks->dataChanged(_charPos); + _chunks->overwrite(_charPos, _newChar); + break; + case removeAt: + _oldChar = (*_chunks)[_charPos]; + _wasChanged = _chunks->dataChanged(_charPos); + _chunks->removeAt(_charPos); + break; } } -UndoStack::UndoStack(Chunks * chunks, QObject * parent) +UndoStack::UndoStack(Chunks *chunks, QObject *parent) : QUndoStack(parent) { _chunks = chunks; @@ -118,8 +111,7 @@ UndoStack::UndoStack(Chunks * chunks, QObject * parent) void UndoStack::insert(qint64 pos, char c) { - if ((pos >= 0) && (pos <= _chunks->size())) - { + if ((pos >= 0) && (pos <= _chunks->size())) { QUndoCommand *cc = new CharCommand(_chunks, CharCommand::insert, pos, c); this->push(cc); } @@ -127,12 +119,10 @@ void UndoStack::insert(qint64 pos, char c) void UndoStack::insert(qint64 pos, const QByteArray &ba) { - if ((pos >= 0) && (pos <= _chunks->size())) - { + if ((pos >= 0) && (pos <= _chunks->size())) { QString txt = QString(tr("Inserting %1 bytes")).arg(ba.size()); beginMacro(txt); - for (int idx=0; idx < ba.size(); idx++) - { + for (int idx = 0; idx < ba.size(); idx++) { QUndoCommand *cc = new CharCommand(_chunks, CharCommand::insert, pos + idx, ba.at(idx)); this->push(cc); } @@ -142,19 +132,14 @@ void UndoStack::insert(qint64 pos, const QByteArray &ba) void UndoStack::removeAt(qint64 pos, qint64 len) { - if ((pos >= 0) && (pos < _chunks->size())) - { - if (len==1) - { + if ((pos >= 0) && (pos < _chunks->size())) { + if (len == 1) { QUndoCommand *cc = new CharCommand(_chunks, CharCommand::removeAt, pos, char(0)); this->push(cc); - } - else - { + } else { QString txt = QString(tr("Delete %1 chars")).arg(len); beginMacro(txt); - for (qint64 cnt=0; cnt= 0) && (pos < _chunks->size())) - { + if ((pos >= 0) && (pos < _chunks->size())) { QUndoCommand *cc = new CharCommand(_chunks, CharCommand::overwrite, pos, c); this->push(cc); } @@ -174,8 +158,7 @@ void UndoStack::overwrite(qint64 pos, char c) void UndoStack::overwrite(qint64 pos, int len, const QByteArray &ba) { - if ((pos >= 0) && (pos < _chunks->size())) - { + if ((pos >= 0) && (pos < _chunks->size())) { QString txt = QString(tr("Overwrite %1 chars")).arg(len); beginMacro(txt); removeAt(pos, len); diff --git a/src/commands.h b/src/commands.h index 45b4359..84b23a5 100644 --- a/src/commands.h +++ b/src/commands.h @@ -48,15 +48,15 @@ class UndoStack : public QUndoStack Q_OBJECT public: - UndoStack(Chunks *chunks, QObject * ); + UndoStack(Chunks *chunks, QObject *); void insert(qint64 pos, char c); void insert(qint64 pos, const QByteArray &ba); - void removeAt(qint64 pos, qint64 len=1); + void removeAt(qint64 pos, qint64 len = 1); void overwrite(qint64 pos, char c); void overwrite(qint64 pos, int len, const QByteArray &ba); private: - Chunks * _chunks; + Chunks *_chunks; }; /** \endcond docNever */ diff --git a/src/qhexedit.cpp b/src/qhexedit.cpp index 9736579..fc1a583 100644 --- a/src/qhexedit.cpp +++ b/src/qhexedit.cpp @@ -25,13 +25,14 @@ #include #include "chunks.h" -#include "commands.h" #include "color_manager.h" +#include "commands.h" #include "qhexedit.h" // ********************************************************************** Constructor, destructor -QHexEdit::QHexEdit(QWidget *parent) : QAbstractScrollArea(parent) +QHexEdit::QHexEdit(QWidget *parent) + : QAbstractScrollArea(parent) , _addressArea(true) , _addressWidth(4) , _asciiArea(true) @@ -118,10 +119,21 @@ int QHexEdit::addressWidth() const { qint64 size = _chunks->size(); int n = 1; - if (size > Q_INT64_C(0x100000000)){ n += 8; size /= Q_INT64_C(0x100000000);} - if (size > 0x10000){ n += 4; size /= 0x10000;} - if (size > 0x100){ n += 2; size /= 0x100;} - if (size > 0x10){ n += 1;} + if (size > Q_INT64_C(0x100000000)) { + n += 8; + size /= Q_INT64_C(0x100000000); + } + if (size > 0x10000) { + n += 4; + size /= 0x10000; + } + if (size > 0x100) { + n += 2; + size /= 0x100; + } + if (size > 0x10) { + n += 1; + } if (n > _addressWidth) return n; @@ -181,7 +193,7 @@ void QHexEdit::setCursorPosition(qint64 position) // 2. Check, if cursor in range? if (position > (_chunks->size() * 2 - 1)) - position = _chunks->size() * 2 - (_overwriteMode ? 1 : 0); + position = _chunks->size() * 2 - (_overwriteMode ? 1 : 0); if (position < 0) position = 0; @@ -190,8 +202,7 @@ void QHexEdit::setCursorPosition(qint64 position) _bPosCurrent = position / 2; _pxCursorY = ((position / 2 - _bPosFirst) / _bytesPerLine + 1) * _pxCharHeight; int x = (position % (2 * _bytesPerLine)); - if (_editAreaIsAscii) - { + if (_editAreaIsAscii) { _pxCursorX = x / 2 * _pxCharWidth + _pxPosAsciiX; _cursorPosition = position & 0xFFFFFFFFFFFFFFFE; } else { @@ -201,27 +212,11 @@ void QHexEdit::setCursorPosition(qint64 position) int pxOfsX = horizontalScrollBar()->value(); if (_readOnly) - _cursorRect = QRect( - _pxCursorX - pxOfsX, - _pxCursorY - _pxCharHeight + _pxSelectionSub, - _pxCharWidth, - _pxCharHeight - ); - else - if (_overwriteMode) - _cursorRect = QRect( - _pxCursorX - pxOfsX, - _pxCursorY + _pxCursorWidth, - _pxCharWidth, - _pxCursorWidth - ); - else - _cursorRect = QRect( - _pxCursorX - pxOfsX, - _pxCursorY - _pxCharHeight + _pxSelectionSub, - _pxCursorWidth, - _pxCharHeight - ); + _cursorRect = QRect(_pxCursorX - pxOfsX, _pxCursorY - _pxCharHeight + _pxSelectionSub, _pxCharWidth, _pxCharHeight); + else if (_overwriteMode) + _cursorRect = QRect(_pxCursorX - pxOfsX, _pxCursorY + _pxCursorWidth, _pxCharWidth, _pxCursorWidth); + else + _cursorRect = QRect(_pxCursorX - pxOfsX, _pxCursorY - _pxCharHeight + _pxSelectionSub, _pxCursorWidth, _pxCharHeight); // 4. Immediately draw new cursor _blink = true; @@ -235,22 +230,18 @@ qint64 QHexEdit::cursorPosition(QPoint pos) qint64 result = -1; int posX = pos.x() + horizontalScrollBar()->value(); int posY = pos.y() - 3; - if ((posX >= _pxPosHexX) && (posX < (_pxPosHexX + (1 + _hexCharsInLine) * _pxCharWidth))) - { + if ((posX >= _pxPosHexX) && (posX < (_pxPosHexX + (1 + _hexCharsInLine) * _pxCharWidth))) { _editAreaIsAscii = false; int x = (posX - _pxPosHexX) / _pxCharWidth; x = (x / 3) * 2 + x % 3; int y = (posY / _pxCharHeight) * 2 * _bytesPerLine; result = _bPosFirst * 2 + x + y; + } else if (_asciiArea && (posX >= _pxPosAsciiX) && (posX < (_pxPosAsciiX + (1 + _bytesPerLine) * _pxCharWidth))) { + _editAreaIsAscii = true; + int x = 2 * (posX - _pxPosAsciiX) / _pxCharWidth; + int y = (posY / _pxCharHeight) * 2 * _bytesPerLine; + result = _bPosFirst * 2 + x + y; } - else - if (_asciiArea && (posX >= _pxPosAsciiX) && (posX < (_pxPosAsciiX + (1 + _bytesPerLine) * _pxCharWidth))) - { - _editAreaIsAscii = true; - int x = 2 * (posX - _pxPosAsciiX) / _pxCharWidth; - int y = (posY / _pxCharHeight) * 2 * _bytesPerLine; - result = _bPosFirst * 2 + x + y; - } return result; } @@ -403,9 +394,9 @@ void QHexEdit::clearUserAreas() void QHexEdit::ensureVisible() { if (_cursorPosition < (_bPosFirst * 2)) - verticalScrollBar()->setValue((int)(_cursorPosition / 2 / _bytesPerLine)); - if (_cursorPosition > ((_bPosFirst + (_rowsShown - 1)*_bytesPerLine) * 2)) - verticalScrollBar()->setValue((int)(_cursorPosition / 2 / _bytesPerLine) - _rowsShown + 1); + verticalScrollBar()->setValue((int) (_cursorPosition / 2 / _bytesPerLine)); + if (_cursorPosition > ((_bPosFirst + (_rowsShown - 1) * _bytesPerLine) * 2)) + verticalScrollBar()->setValue((int) (_cursorPosition / 2 / _bytesPerLine) - _rowsShown + 1); if (_pxCursorX < horizontalScrollBar()->value()) horizontalScrollBar()->setValue(_pxCursorX); if ((_pxCursorX + _pxCharWidth) > (horizontalScrollBar()->value() + viewport()->width())) @@ -416,12 +407,11 @@ void QHexEdit::ensureVisible() qint64 QHexEdit::indexOf(const QByteArray &ba, qint64 from) { qint64 pos = _chunks->indexOf(ba, from); - if (pos > -1) - { - qint64 curPos = pos*2; - setCursorPosition(curPos + ba.length()*2); + if (pos > -1) { + qint64 curPos = pos * 2; + setCursorPosition(curPos + ba.length() * 2); resetSelection(curPos); - setSelection(curPos + ba.length()*2); + setSelection(curPos + ba.length() * 2); ensureVisible(); } return pos; @@ -435,12 +425,11 @@ bool QHexEdit::isModified() const qint64 QHexEdit::lastIndexOf(const QByteArray &ba, qint64 from) { qint64 pos = _chunks->lastIndexOf(ba, from); - if (pos > -1) - { - qint64 curPos = pos*2; + if (pos > -1) { + qint64 curPos = pos * 2; setCursorPosition(curPos - 1); resetSelection(curPos); - setSelection(curPos + ba.length()*2); + setSelection(curPos + ba.length() * 2); ensureVisible(); } return pos; @@ -449,7 +438,7 @@ qint64 QHexEdit::lastIndexOf(const QByteArray &ba, qint64 from) void QHexEdit::redo() { _undoStack->redo(); - setCursorPosition(_chunks->pos()*(_editAreaIsAscii ? 1 : 2)); + setCursorPosition(_chunks->pos() * (_editAreaIsAscii ? 1 : 2)); refresh(); } @@ -492,7 +481,7 @@ QString QHexEdit::toReadableString() void QHexEdit::undo() { _undoStack->undo(); - setCursorPosition(_chunks->pos()*(_editAreaIsAscii ? 1 : 2)); + setCursorPosition(_chunks->pos() * (_editAreaIsAscii ? 1 : 2)); refresh(); } @@ -500,343 +489,286 @@ void QHexEdit::undo() void QHexEdit::keyPressEvent(QKeyEvent *event) { // Cursor movements - if (event->matches(QKeySequence::MoveToNextChar)) - { + if (event->matches(QKeySequence::MoveToNextChar)) { qint64 pos = _cursorPosition + 1; if (_editAreaIsAscii) pos += 1; setCursorPosition(pos); resetSelection(pos); } - if (event->matches(QKeySequence::MoveToPreviousChar)) - { + if (event->matches(QKeySequence::MoveToPreviousChar)) { qint64 pos = _cursorPosition - 1; if (_editAreaIsAscii) pos -= 1; setCursorPosition(pos); resetSelection(pos); } - if (event->matches(QKeySequence::MoveToEndOfLine)) - { + if (event->matches(QKeySequence::MoveToEndOfLine)) { qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)) + (2 * _bytesPerLine) - 1; setCursorPosition(pos); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToStartOfLine)) - { + if (event->matches(QKeySequence::MoveToStartOfLine)) { qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)); setCursorPosition(pos); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToPreviousLine)) - { + if (event->matches(QKeySequence::MoveToPreviousLine)) { setCursorPosition(_cursorPosition - (2 * _bytesPerLine)); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToNextLine)) - { + if (event->matches(QKeySequence::MoveToNextLine)) { setCursorPosition(_cursorPosition + (2 * _bytesPerLine)); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToNextPage)) - { + if (event->matches(QKeySequence::MoveToNextPage)) { setCursorPosition(_cursorPosition + (((_rowsShown - 1) * 2 * _bytesPerLine))); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToPreviousPage)) - { + if (event->matches(QKeySequence::MoveToPreviousPage)) { setCursorPosition(_cursorPosition - (((_rowsShown - 1) * 2 * _bytesPerLine))); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToEndOfDocument)) - { - setCursorPosition(_chunks->size() * 2 ); + if (event->matches(QKeySequence::MoveToEndOfDocument)) { + setCursorPosition(_chunks->size() * 2); resetSelection(_cursorPosition); } - if (event->matches(QKeySequence::MoveToStartOfDocument)) - { + if (event->matches(QKeySequence::MoveToStartOfDocument)) { setCursorPosition(0); resetSelection(_cursorPosition); } // Select commands - if (event->matches(QKeySequence::SelectAll)) - { + if (event->matches(QKeySequence::SelectAll)) { resetSelection(0); setSelection(2 * _chunks->size() + 1); } - if (event->matches(QKeySequence::SelectNextChar)) - { + if (event->matches(QKeySequence::SelectNextChar)) { qint64 pos = _cursorPosition + 1; if (_editAreaIsAscii) pos += 1; setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectPreviousChar)) - { + if (event->matches(QKeySequence::SelectPreviousChar)) { qint64 pos = _cursorPosition - 1; if (_editAreaIsAscii) pos -= 1; setSelection(pos); setCursorPosition(pos); } - if (event->matches(QKeySequence::SelectEndOfLine)) - { + if (event->matches(QKeySequence::SelectEndOfLine)) { qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)) + (2 * _bytesPerLine) - 1; setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectStartOfLine)) - { + if (event->matches(QKeySequence::SelectStartOfLine)) { qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)); setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectPreviousLine)) - { + if (event->matches(QKeySequence::SelectPreviousLine)) { qint64 pos = _cursorPosition - (2 * _bytesPerLine); setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectNextLine)) - { + if (event->matches(QKeySequence::SelectNextLine)) { qint64 pos = _cursorPosition + (2 * _bytesPerLine); setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectNextPage)) - { + if (event->matches(QKeySequence::SelectNextPage)) { qint64 pos = _cursorPosition + (((viewport()->height() / _pxCharHeight) - 1) * 2 * _bytesPerLine); setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectPreviousPage)) - { + if (event->matches(QKeySequence::SelectPreviousPage)) { qint64 pos = _cursorPosition - (((viewport()->height() / _pxCharHeight) - 1) * 2 * _bytesPerLine); setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectEndOfDocument)) - { + if (event->matches(QKeySequence::SelectEndOfDocument)) { qint64 pos = _chunks->size() * 2; setCursorPosition(pos); setSelection(pos); } - if (event->matches(QKeySequence::SelectStartOfDocument)) - { + if (event->matches(QKeySequence::SelectStartOfDocument)) { qint64 pos = 0; setCursorPosition(pos); setSelection(pos); } // Edit Commands - if (!_readOnly) - { + if (!_readOnly) { /* Cut */ - if (event->matches(QKeySequence::Cut)) - { + if (event->matches(QKeySequence::Cut)) { QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()).toHex(); - for (qint64 idx = 32; idx < ba.size(); idx +=33) + for (qint64 idx = 32; idx < ba.size(); idx += 33) ba.insert(idx, "\n"); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ba); - if (_overwriteMode) - { + if (_overwriteMode) { qint64 len = getSelectionEnd() - getSelectionBegin(); - replace(getSelectionBegin(), (int)len, QByteArray((int)len, char(0))); - } - else - { + replace(getSelectionBegin(), (int) len, QByteArray((int) len, char(0))); + } else { remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()); } setCursorPosition(2 * getSelectionBegin()); resetSelection(2 * getSelectionBegin()); } else - /* Paste */ - if (event->matches(QKeySequence::Paste)) - { - QClipboard *clipboard = QApplication::clipboard(); - QByteArray ba = QByteArray().fromHex(clipboard->text().toLatin1()); - if (_overwriteMode) - { - ba = ba.left(std::min(ba.size(), (_chunks->size() - _bPosCurrent))); - replace(_bPosCurrent, ba.size(), ba); - } - else - insert(_bPosCurrent, ba); - setCursorPosition(_cursorPosition + 2 * ba.size()); - resetSelection(getSelectionBegin()); - } else - - /* Delete char */ - if (event->matches(QKeySequence::Delete)) - { - if (getSelectionBegin() != getSelectionEnd()) - { - _bPosCurrent = getSelectionBegin(); - if (_overwriteMode) - { - QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0)); - replace(_bPosCurrent, ba.size(), ba); - } - else - { - remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin()); - } - } - else - { - if (_overwriteMode) - replace(_bPosCurrent, char(0)); - else - remove(_bPosCurrent, 1); - } - setCursorPosition(2 * _bPosCurrent); - resetSelection(2 * _bPosCurrent); - } else - - /* Backspace */ - if ((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier)) - { - if (getSelectionBegin() != getSelectionEnd()) - { - _bPosCurrent = getSelectionBegin(); - setCursorPosition(2 * _bPosCurrent); - if (_overwriteMode) - { - QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0)); + /* Paste */ + if (event->matches(QKeySequence::Paste)) { + QClipboard *clipboard = QApplication::clipboard(); + QByteArray ba = QByteArray().fromHex(clipboard->text().toLatin1()); + if (_overwriteMode) { + ba = ba.left(std::min(ba.size(), (_chunks->size() - _bPosCurrent))); replace(_bPosCurrent, ba.size(), ba); - } - else - { - remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin()); - } - resetSelection(2 * _bPosCurrent); - } - else - { - bool behindLastByte = false; - if ((_cursorPosition / 2) == _chunks->size()) - behindLastByte = true; - - _bPosCurrent -= 1; - if (_overwriteMode) - replace(_bPosCurrent, char(0)); - else - remove(_bPosCurrent, 1); - - if (!behindLastByte) - _bPosCurrent -= 1; - - setCursorPosition(2 * _bPosCurrent); - resetSelection(2 * _bPosCurrent); - } - } else - - /* undo */ - if (event->matches(QKeySequence::Undo)) - { - undo(); - } else - - /* redo */ - if (event->matches(QKeySequence::Redo)) - { - redo(); - } else - - if ((QApplication::keyboardModifiers() == Qt::NoModifier) || - (QApplication::keyboardModifiers() == Qt::KeypadModifier) || - (QApplication::keyboardModifiers() == Qt::ShiftModifier) || - (QApplication::keyboardModifiers() == (Qt::AltModifier | Qt::ControlModifier)) || - (QApplication::keyboardModifiers() == Qt::GroupSwitchModifier)) - { - /* Hex and ascii input */ - int key = 0; - QString text = event->text(); - if (!text.isEmpty()) - { - if (_editAreaIsAscii) - key = (uchar)text.at(0).toLatin1(); - else - key = int(text.at(0).toLower().toLatin1()); - } - - if ((((key >= '0' && key <= '9') || (key >= 'a' && key <= 'f')) && _editAreaIsAscii == false) - || (key >= ' ' && _editAreaIsAscii)) - { - if (getSelectionBegin() != getSelectionEnd()) - { - if (_overwriteMode) - { - qint64 len = getSelectionEnd() - getSelectionBegin(); - replace(getSelectionBegin(), (int)len, QByteArray((int)len, char(0))); - } else - { - remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()); + } else + insert(_bPosCurrent, ba); + setCursorPosition(_cursorPosition + 2 * ba.size()); + resetSelection(getSelectionBegin()); + } else + + /* Delete char */ + if (event->matches(QKeySequence::Delete)) { + if (getSelectionBegin() != getSelectionEnd()) { _bPosCurrent = getSelectionBegin(); + if (_overwriteMode) { + QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0)); + replace(_bPosCurrent, ba.size(), ba); + } else { + remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin()); + } + } else { + if (_overwriteMode) + replace(_bPosCurrent, char(0)); + else + remove(_bPosCurrent, 1); } setCursorPosition(2 * _bPosCurrent); resetSelection(2 * _bPosCurrent); - } - - // If insert mode, then insert a byte - if (_overwriteMode == false) - if ((_cursorPosition % 2) == 0) - insert(_bPosCurrent, char(0)); - - // Change content - if (_chunks->size() > 0) - { - char ch = key; - if (!_editAreaIsAscii){ - QByteArray hexValue = _chunks->data(_bPosCurrent, 1).toHex(); - if ((_cursorPosition % 2) == 0) - hexValue[0] = key; - else - hexValue[1] = key; - ch = QByteArray().fromHex(hexValue)[0]; - } - replace(_bPosCurrent, ch); - if (_editAreaIsAscii) - setCursorPosition(_cursorPosition + 2); - else - setCursorPosition(_cursorPosition + 1); - resetSelection(_cursorPosition); - } - } - } - + } else + + /* Backspace */ + if ((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier)) { + if (getSelectionBegin() != getSelectionEnd()) { + _bPosCurrent = getSelectionBegin(); + setCursorPosition(2 * _bPosCurrent); + if (_overwriteMode) { + QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0)); + replace(_bPosCurrent, ba.size(), ba); + } else { + remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin()); + } + resetSelection(2 * _bPosCurrent); + } else { + bool behindLastByte = false; + if ((_cursorPosition / 2) == _chunks->size()) + behindLastByte = true; + + _bPosCurrent -= 1; + if (_overwriteMode) + replace(_bPosCurrent, char(0)); + else + remove(_bPosCurrent, 1); + + if (!behindLastByte) + _bPosCurrent -= 1; + + setCursorPosition(2 * _bPosCurrent); + resetSelection(2 * _bPosCurrent); + } + } else + /* undo */ + if (event->matches(QKeySequence::Undo)) { + undo(); + } else + + /* redo */ + if (event->matches(QKeySequence::Redo)) { + redo(); + } else + + if ((QApplication::keyboardModifiers() == Qt::NoModifier) || (QApplication::keyboardModifiers() == Qt::KeypadModifier) + || (QApplication::keyboardModifiers() == Qt::ShiftModifier) + || (QApplication::keyboardModifiers() == (Qt::AltModifier | Qt::ControlModifier)) + || (QApplication::keyboardModifiers() == Qt::GroupSwitchModifier)) { + /* Hex and ascii input */ + int key = 0; + QString text = event->text(); + if (!text.isEmpty()) { + if (_editAreaIsAscii) + key = (uchar) text.at(0).toLatin1(); + else + key = int(text.at(0).toLower().toLatin1()); + } + + if ((((key >= '0' && key <= '9') || (key >= 'a' && key <= 'f')) && _editAreaIsAscii == false) + || (key >= ' ' && _editAreaIsAscii)) { + if (getSelectionBegin() != getSelectionEnd()) { + if (_overwriteMode) { + qint64 len = getSelectionEnd() - getSelectionBegin(); + replace(getSelectionBegin(), (int) len, QByteArray((int) len, char(0))); + } else { + remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()); + _bPosCurrent = getSelectionBegin(); + } + setCursorPosition(2 * _bPosCurrent); + resetSelection(2 * _bPosCurrent); + } + + // If insert mode, then insert a byte + if (_overwriteMode == false) + if ((_cursorPosition % 2) == 0) + insert(_bPosCurrent, char(0)); + + // Change content + if (_chunks->size() > 0) { + char ch = key; + if (!_editAreaIsAscii) { + QByteArray hexValue = _chunks->data(_bPosCurrent, 1).toHex(); + if ((_cursorPosition % 2) == 0) + hexValue[0] = key; + else + hexValue[1] = key; + ch = QByteArray().fromHex(hexValue)[0]; + } + replace(_bPosCurrent, ch); + if (_editAreaIsAscii) + setCursorPosition(_cursorPosition + 2); + else + setCursorPosition(_cursorPosition + 1); + resetSelection(_cursorPosition); + } + } + } } /* Copy */ - if (event->matches(QKeySequence::Copy)) - { + if (event->matches(QKeySequence::Copy)) { QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()).toHex(); - for (qint64 idx = 32; idx < ba.size(); idx +=33) + for (qint64 idx = 32; idx < ba.size(); idx += 33) ba.insert(idx, "\n"); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(ba); } // Switch between insert/overwrite mode - if ((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier)) - { + if ((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier)) { setOverwriteMode(!overwriteMode()); setCursorPosition(_cursorPosition); } // switch from hex to ascii edit - if (event->key() == Qt::Key_Tab && !_editAreaIsAscii){ + if (event->key() == Qt::Key_Tab && !_editAreaIsAscii) { _editAreaIsAscii = true; setCursorPosition(_cursorPosition); } // switch from ascii to hex edit - if (event->key() == Qt::Key_Backtab && _editAreaIsAscii){ + if (event->key() == Qt::Key_Backtab && _editAreaIsAscii) { _editAreaIsAscii = false; setCursorPosition(_cursorPosition); } @@ -844,25 +776,23 @@ void QHexEdit::keyPressEvent(QKeyEvent *event) refresh(); } -void QHexEdit::mouseMoveEvent(QMouseEvent * event) +void QHexEdit::mouseMoveEvent(QMouseEvent *event) { _blink = false; viewport()->update(); qint64 actPos = cursorPosition(event->pos()); - if (actPos >= 0) - { + if (actPos >= 0) { setCursorPosition(actPos); setSelection(actPos); } } -void QHexEdit::mousePressEvent(QMouseEvent * event) +void QHexEdit::mousePressEvent(QMouseEvent *event) { _blink = false; viewport()->update(); qint64 cPos = cursorPosition(event->pos()); - if (cPos >= 0) - { + if (cPos >= 0) { if (event->button() != Qt::RightButton) resetSelection(cPos); setCursorPosition(cPos); @@ -873,60 +803,38 @@ void QHexEdit::paintEvent(QPaintEvent *event) { QPainter painter(viewport()); int pxOfsX = horizontalScrollBar()->value(); - int pxPosAsciiX2 = _pxPosAsciiX - pxOfsX; + int pxPosAsciiX2 = _pxPosAsciiX - pxOfsX; - if (event->rect() != _cursorRect) - { + if (event->rect() != _cursorRect) { int pxPosStartY = _pxCharHeight; // *** prepare background - painter.fillRect( - event->rect(), - viewport()->palette().color(QPalette::Base) - ); + painter.fillRect(event->rect(), viewport()->palette().color(QPalette::Base)); if (_addressArea) - painter.fillRect( - QRect( - -pxOfsX, - event->rect().top(), - _pxCharWidth * (_addrDigits + 1), - height() - ), - _colorManager->notMarked(Area::Address).areaStyle() - ); - if (_asciiArea) - { - painter.fillRect( - QRect( - pxPosAsciiX2 - _pxAreaMargin, - event->rect().top(), - _pxCharWidth * _bytesPerLine + 2 * _pxAreaMargin, - height() - ), - _colorManager->notMarked(Area::Ascii).areaStyle() - ); + painter.fillRect(QRect(-pxOfsX, event->rect().top(), _pxCharWidth * (_addrDigits + 1), height()), + _colorManager->notMarked(Area::Address).areaStyle()); + if (_asciiArea) { + painter.fillRect(QRect(pxPosAsciiX2 - _pxAreaMargin, event->rect().top(), _pxCharWidth * _bytesPerLine + 2 * _pxAreaMargin, height()), + _colorManager->notMarked(Area::Ascii).areaStyle()); } // *** paint central areas - for (int row = 0, pxPosY = pxPosStartY; row <= _rowsShown; row++, pxPosY +=_pxCharHeight) - { + for (int row = 0, pxPosY = pxPosStartY; row <= _rowsShown; row++, pxPosY += _pxCharHeight) { QByteArray hex; qint64 bPosLine = row * _bytesPerLine; - int pxPosX = _pxPosHexX - pxOfsX; - int pxPosAsciiX2 = _pxPosAsciiX - pxOfsX; + int pxPosX = _pxPosHexX - pxOfsX; + int pxPosAsciiX2 = _pxPosAsciiX - pxOfsX; // *** address info - if (_addressArea && row * _bytesPerLine < _dataShown.size()) - { - QString address = QString("%1").arg(_bPosFirst + row*_bytesPerLine + _addressOffset, _addrDigits, 16, QChar('0')); + if (_addressArea && row * _bytesPerLine < _dataShown.size()) { + QString address = QString("%1").arg(_bPosFirst + row * _bytesPerLine + _addressOffset, _addrDigits, 16, QChar('0')); ColoredArea addressArea = _colorManager->notMarked(Area::Address); painter.setPen(addressArea.fontPen()); painter.drawText(_pxPosAdrX - pxOfsX, pxPosY, hexCaps() ? address.toUpper() : address); } - for (int colIdx = 0; ((bPosLine + colIdx) < _dataShown.size() && (colIdx < _bytesPerLine)); colIdx++) - { + for (int colIdx = 0; ((bPosLine + colIdx) < _dataShown.size() && (colIdx < _bytesPerLine)); colIdx++) { qint64 posBa = _bPosFirst + bPosLine + colIdx; // *** hex values @@ -934,32 +842,21 @@ void QHexEdit::paintEvent(QPaintEvent *event) painter.setPen(hexArea.fontPen()); QRect rect; if (colIdx == 0) - rect = QRect( - pxPosX, - pxPosY - _pxCharHeight + _pxSelectionSub, - 2*_pxCharWidth, - _pxCharHeight - ); + rect = QRect(pxPosX, pxPosY - _pxCharHeight + _pxSelectionSub, 2 * _pxCharWidth, _pxCharHeight); else - rect = QRect( - pxPosX - _pxCharWidth, - pxPosY - _pxCharHeight + _pxSelectionSub, - 3*_pxCharWidth, - _pxCharHeight - ); + rect = QRect(pxPosX - _pxCharWidth, pxPosY - _pxCharHeight + _pxSelectionSub, 3 * _pxCharWidth, _pxCharHeight); painter.fillRect(rect, hexArea.areaStyle()); hex = _hexDataShown.mid((bPosLine + colIdx) * 2, 2); - painter.drawText(pxPosX, pxPosY, hexCaps()?hex.toUpper():hex); - pxPosX += 3*_pxCharWidth; + painter.drawText(pxPosX, pxPosY, hexCaps() ? hex.toUpper() : hex); + pxPosX += 3 * _pxCharWidth; // *** ascii values - if (_asciiArea) - { + if (_asciiArea) { ColoredArea asciiArea = _colorManager->markedArea(posBa, Area::Ascii, _chunks); painter.setPen(asciiArea.fontPen()); - int ch = (uchar)_dataShown.at(bPosLine + colIdx); - if ( ch < ' ' || ch > '~' ) + int ch = (uchar) _dataShown.at(bPosLine + colIdx); + if (ch < ' ' || ch > '~') ch = _defaultChar; rect.setRect(pxPosAsciiX2, pxPosY - _pxCharHeight + _pxSelectionSub, _pxCharWidth, _pxCharHeight); painter.fillRect(rect, asciiArea.areaStyle()); @@ -974,16 +871,14 @@ void QHexEdit::paintEvent(QPaintEvent *event) int hexPos = _cursorPosition - 2 * _bPosFirst; // due to scrolling the cursor can go out of the currently displayed data - if ((hexPos >= 0) && (hexPos <= _hexDataShown.size())) - { + if ((hexPos >= 0) && (hexPos <= _hexDataShown.size())) { ColoredArea curArea; if (_editAreaIsAscii) curArea = _colorManager->markedArea(hexPos / 2, Area::Ascii, _chunks); else curArea = _colorManager->markedArea(hexPos / 2, Area::Hex, _chunks); - if (_blink && hasFocus()) - { + if (_blink && hasFocus()) { if (_readOnly) painter.fillRect(_cursorRect, curArea.fontColor()); else @@ -992,17 +887,14 @@ void QHexEdit::paintEvent(QPaintEvent *event) // We have to repaint the current char because the curser destroys the char painter.setPen(curArea.fontColor()); - if (_editAreaIsAscii) - { + if (_editAreaIsAscii) { // every 2 hex there is 1 ascii - int ch = (uchar)_dataShown.at(hexPos / 2); + int ch = (uchar) _dataShown.at(hexPos / 2); if (ch < ' ' || ch > '~') ch = _defaultChar; painter.drawText(_pxCursorX - pxOfsX, _pxCursorY, QChar(ch)); - } - else - { + } else { QByteArray txt = _hexDataShown.mid(hexPos, 1); if (_hexCaps) txt = txt.toUpper(); @@ -1011,8 +903,7 @@ void QHexEdit::paintEvent(QPaintEvent *event) } // *** emit event, if size has changed - if (_lastEventSize != _chunks->size()) - { + if (_lastEventSize != _chunks->size()) { _lastEventSize = _chunks->size(); emit currentSizeChanged(_lastEventSize); } @@ -1020,8 +911,7 @@ void QHexEdit::paintEvent(QPaintEvent *event) void QHexEdit::resizeEvent(QResizeEvent *) { - if (_dynamicBytesPerLine) - { + if (_dynamicBytesPerLine) { int pxFixGaps = 0; if (_addressArea) pxFixGaps = addressWidth() * _pxCharWidth + 2 * _pxAreaMargin; @@ -1030,7 +920,7 @@ void QHexEdit::resizeEvent(QResizeEvent *) pxFixGaps += 2 * _pxAreaMargin; // +1 because the last hex value do not have space. so it is effective one char more - int charWidth = (viewport()->width() - pxFixGaps ) / _pxCharWidth + 1; + int charWidth = (viewport()->width() - pxFixGaps) / _pxCharWidth + 1; // 2 hex alfa-digits 1 space 1 ascii per byte = 4; if ascii is disabled then 3 // to prevent devision by zero use the min value 1 @@ -1041,15 +931,12 @@ void QHexEdit::resizeEvent(QResizeEvent *) bool QHexEdit::focusNextPrevChild(bool next) { - if (_addressArea) - { - if ( (next && _editAreaIsAscii) || (!next && !_editAreaIsAscii )) + if (_addressArea) { + if ((next && _editAreaIsAscii) || (!next && !_editAreaIsAscii)) return QWidget::focusNextPrevChild(next); else return false; - } - else - { + } else { return QWidget::focusNextPrevChild(next); } } @@ -1064,7 +951,7 @@ void QHexEdit::resetSelection() void QHexEdit::resetSelection(qint64 pos) { - pos = pos / 2 ; + pos = pos / 2; if (pos < 0) pos = 0; if (pos > _chunks->size()) @@ -1083,12 +970,9 @@ void QHexEdit::setSelection(qint64 pos) if (pos > _chunks->size()) pos = _chunks->size(); - if (pos > _bSelectionBegin) - { + if (pos > _bSelectionBegin) { _bSelectionEnd = pos; - } - else - { + } else { _bSelectionBegin = pos; } _colorManager->selection().setRange(_bSelectionBegin, _bSelectionEnd); @@ -1107,8 +991,7 @@ qint64 QHexEdit::getSelectionEnd() const // ********************************************************************** Private utility functions bool QHexEdit::event(QEvent *event) { - if (event->type() == QEvent::QEvent::PaletteChange) - { + if (event->type() == QEvent::QEvent::PaletteChange) { QPalette palette = this->palette(); _colorManager->setPalette(palette); } @@ -1128,12 +1011,10 @@ void QHexEdit::init() void QHexEdit::adjust() { // recalc Graphics - if (_addressArea) - { + if (_addressArea) { _addrDigits = addressWidth(); - _pxPosHexX = _pxAreaMargin + _addrDigits*_pxCharWidth + 2 * _pxAreaMargin; - } - else + _pxPosHexX = _pxAreaMargin + _addrDigits * _pxCharWidth + 2 * _pxAreaMargin; + } else _pxPosHexX = _pxAreaMargin; _pxPosAdrX = _pxAreaMargin; _pxPosAsciiX = _pxPosHexX + _hexCharsInLine * _pxCharWidth + 2 * _pxAreaMargin; @@ -1141,19 +1022,19 @@ void QHexEdit::adjust() // set horizontalScrollBar() int pxWidth = _pxPosAsciiX; if (_asciiArea) - pxWidth += _bytesPerLine*_pxCharWidth; + pxWidth += _bytesPerLine * _pxCharWidth; horizontalScrollBar()->setRange(0, pxWidth - viewport()->width()); horizontalScrollBar()->setPageStep(viewport()->width()); // set verticalScrollbar() - _rowsShown = ((viewport()->height()-4)/_pxCharHeight); - int lineCount = (int)(_chunks->size() / (qint64)_bytesPerLine) + 1; + _rowsShown = ((viewport()->height() - 4) / _pxCharHeight); + int lineCount = (int) (_chunks->size() / (qint64) _bytesPerLine) + 1; verticalScrollBar()->setRange(0, lineCount - _rowsShown); verticalScrollBar()->setPageStep(_rowsShown); int value = verticalScrollBar()->value(); - _bPosFirst = (qint64)value * _bytesPerLine; - _bPosLast = _bPosFirst + (qint64)(_rowsShown * _bytesPerLine) - 1; + _bPosFirst = (qint64) value * _bytesPerLine; + _bPosLast = _bPosFirst + (qint64) (_rowsShown * _bytesPerLine) - 1; if (_bPosLast >= _chunks->size()) _bPosLast = _chunks->size() - 1; readBuffers(); @@ -1183,19 +1064,16 @@ QString QHexEdit::toReadable(const QByteArray &ba) const { QString result; - for (int i=0; i < ba.size(); i += 16) - { + for (int i = 0; i < ba.size(); i += 16) { QString addrStr = QString("%1").arg(_addressOffset + i, addressWidth(), 16, QChar('0')); QString hexStr; QString ascStr; - for (int j=0; j<16; j++) - { - if ((i + j) < ba.size()) - { - hexStr.append(" ").append(ba.mid(i+j, 1).toHex()); + for (int j = 0; j < 16; j++) { + if ((i + j) < ba.size()) { + hexStr.append(" ").append(ba.mid(i + j, 1).toHex()); char ch = ba[i + j]; if ((ch < 0x20) || (ch > 0x7e)) - ch = _defaultChar; + ch = _defaultChar; ascStr.append(QChar(ch)); } } diff --git a/src/qhexedit.h b/src/qhexedit.h index 94d4cd7..321162c 100644 --- a/src/qhexedit.h +++ b/src/qhexedit.h @@ -20,8 +20,8 @@ #define QHEXEDIT_H #include -#include #include +#include #include #include @@ -44,7 +44,6 @@ QHexEdit is a binary editor widget for Qt. \image html qhexedit.png */ - /** QHexEdit is a hex editor widget written in C++ for the Qt (Qt4, Qt5) framework. It is a simple editor for binary data, just like QPlainTextEdit is for text data. There are sip configuration files included, so it is easy to create @@ -161,7 +160,7 @@ class QHEXEDIT_API QHexEdit : public QAbstractScrollArea /*! Creates an instance of QHexEdit. \param parent Parent widget of QHexEdit. */ - explicit QHexEdit(QWidget *parent=nullptr); + explicit QHexEdit(QWidget *parent = nullptr); // Access to data of qhexedit @@ -174,13 +173,12 @@ class QHEXEDIT_API QHexEdit : public QAbstractScrollArea /*! Gives back the data as a QByteArray starting at position \param pos and delivering \param count bytes. */ - QByteArray dataAt(qint64 pos, qint64 count=-1) const; + QByteArray dataAt(qint64 pos, qint64 count = -1) const; /*! Gives back the data into a \param iODevice starting at position \param pos and delivering \param count bytes. */ - bool write(QIODevice &iODevice, qint64 pos=0, qint64 count=-1) const; - + bool write(QIODevice &iODevice, qint64 pos = 0, qint64 count = -1) const; // Char handling @@ -195,7 +193,7 @@ class QHEXEDIT_API QHexEdit : public QAbstractScrollArea \param pos Index position, where to remove \param len Amount of bytes to remove */ - void remove(qint64 pos, qint64 len=1); + void remove(qint64 pos, qint64 len = 1); /*! Replaces a char. \param pos Index position, where to overwrite @@ -204,7 +202,6 @@ class QHEXEDIT_API QHexEdit : public QAbstractScrollArea */ void replace(qint64 pos, char ch); - // ByteArray handling /*! Inserts a byte array. @@ -222,9 +219,8 @@ class QHEXEDIT_API QHexEdit : public QAbstractScrollArea */ void replace(qint64 pos, qint64 len, const QByteArray &ba); - // User marking areas - + /*! Adds a user defined marking area \param posStart Index position, where the area starts (including) \param posEnd Index position where the area ends (exluding) @@ -313,8 +309,7 @@ public slots: /*! The signal is emitted every time, the overwrite mode is changed. */ void overwriteModeChanged(bool state); - -/*! \cond docNever */ + /*! \cond docNever */ public: ~QHexEdit(); @@ -365,16 +360,17 @@ public slots: // Handle events bool event(QEvent *event); void keyPressEvent(QKeyEvent *event); - void mouseMoveEvent(QMouseEvent * event); - void mousePressEvent(QMouseEvent * event); + void mouseMoveEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *); virtual bool focusNextPrevChild(bool next); + private: // Handle selections - void resetSelection(qint64 pos); // set selectionStart and selectionEnd to pos - void resetSelection(); // set selectionEnd to selectionStart - void setSelection(qint64 pos); // set min (if below init) or max (if greater init) + void resetSelection(qint64 pos); // set selectionStart and selectionEnd to pos + void resetSelection(); // set selectionEnd to selectionStart + void setSelection(qint64 pos); // set min (if below init) or max (if greater init) qint64 getSelectionBegin() const; qint64 getSelectionEnd() const; @@ -384,32 +380,32 @@ public slots: QString toReadable(const QByteArray &ba) const; private slots: - void adjust(); // recalc pixel positions - void dataChangedPrivate(int idx=0); // emit dataChanged() signal - void refresh(); // ensureVisible() and readBuffers() - void updateCursor(); // update blinking cursor + void adjust(); // recalc pixel positions + void dataChangedPrivate(int idx = 0); // emit dataChanged() signal + void refresh(); // ensureVisible() and readBuffers() + void updateCursor(); // update blinking cursor private: // Name convention: pixel positions start with _px - int _pxCharWidth, _pxCharHeight; // char dimensions (dependend on font) - int _pxPosHexX; // X-Pos of HeaxArea - int _pxPosAdrX; // X-Pos of Address Area - int _pxPosAsciiX; // X-Pos of Ascii Area - int _pxAreaMargin; // gap left and right from areas - int _pxCursorWidth; // cursor width - int _pxSelectionSub; // offset selection rect - int _pxCursorX; // current cursor pos - int _pxCursorY; // current cursor pos + int _pxCharWidth, _pxCharHeight; // char dimensions (dependend on font) + int _pxPosHexX; // X-Pos of HeaxArea + int _pxPosAdrX; // X-Pos of Address Area + int _pxPosAsciiX; // X-Pos of Ascii Area + int _pxAreaMargin; // gap left and right from areas + int _pxCursorWidth; // cursor width + int _pxSelectionSub; // offset selection rect + int _pxCursorX; // current cursor pos + int _pxCursorY; // current cursor pos // Name convention: absolute byte positions in chunks start with _b - qint64 _bSelectionBegin; // first position of Selection - qint64 _bSelectionEnd; // end of Selection - qint64 _bPosFirst; // position of first byte shown - qint64 _bPosLast; // position of last byte shown - qint64 _bPosCurrent; // current position + qint64 _bSelectionBegin; // first position of Selection + qint64 _bSelectionEnd; // end of Selection + qint64 _bPosFirst; // position of first byte shown + qint64 _bPosLast; // position of last byte shown + qint64 _bPosCurrent; // current position // variables to store the property values - bool _addressArea; // left area of QHexEdit + bool _addressArea; // left area of QHexEdit int _addressWidth; bool _asciiArea; qint64 _addressOffset; @@ -423,23 +419,23 @@ private slots: bool _dynamicBytesPerLine; // other variables - bool _editAreaIsAscii; // flag about the ascii mode edited - int _addrDigits; // real no of addressdigits, may be > addressWidth - bool _blink; // help get cursor blinking - QBuffer _bData; // buffer, when setup with QByteArray - Chunks *_chunks; // IODevice based access to data - QTimer _cursorTimer; // for blinking cursor - qint64 _cursorPosition; // absolute position of cursor, 1 Byte == 2 tics - QRect _cursorRect; // physical dimensions of cursor - QByteArray _data; // QHexEdit's data, when setup with QByteArray - QByteArray _dataShown; // data in the current View - QByteArray _hexDataShown; // data in view, transformed to hex - qint64 _lastEventSize; // size, which was emitted last time - QByteArray _markedShown; // marked data in view - bool _modified; // Is any data in editor modified? - int _rowsShown; // lines of text shown - UndoStack * _undoStack; // stack to store edit actions for undo/redo - ColorManager * _colorManager; // holds highlighting, selection and other area colors + bool _editAreaIsAscii; // flag about the ascii mode edited + int _addrDigits; // real no of addressdigits, may be > addressWidth + bool _blink; // help get cursor blinking + QBuffer _bData; // buffer, when setup with QByteArray + Chunks *_chunks; // IODevice based access to data + QTimer _cursorTimer; // for blinking cursor + qint64 _cursorPosition; // absolute position of cursor, 1 Byte == 2 tics + QRect _cursorRect; // physical dimensions of cursor + QByteArray _data; // QHexEdit's data, when setup with QByteArray + QByteArray _dataShown; // data in the current View + QByteArray _hexDataShown; // data in view, transformed to hex + qint64 _lastEventSize; // size, which was emitted last time + QByteArray _markedShown; // marked data in view + bool _modified; // Is any data in editor modified? + int _rowsShown; // lines of text shown + UndoStack *_undoStack; // stack to store edit actions for undo/redo + ColorManager *_colorManager; // holds highlighting, selection and other area colors /*! \endcond docNever */ }; diff --git a/test/main.cpp b/test/main.cpp index ddac845..c2f9c4a 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -17,18 +17,17 @@ * https://www.gnu.org/licenses/ */ #include -#include #include +#include #include "testchunks.h" - int main() { QDir dir("logs"); dir.setNameFilters(QStringList() << "*.*"); dir.setFilter(QDir::Files); - foreach(QString dirFile, dir.entryList()) + foreach (QString dirFile, dir.entryList()) dir.remove(dirFile); QString logFilename = "logs/Summary.log"; @@ -50,28 +49,28 @@ int main() tc.overwrite(0x2fff, '.'); TestChunks tc2(sumLog, "insert", 0x4000, true); - tc2.insert(0, 'E'); // 0 - tc2.insert(0x50, 'x'); // 1 - tc2.insert(0x100, 'x'); // 2 - tc2.insert(0x1002, 'L'); // 3 - tc2.insert(0x1004, 'E'); // 4 - tc2.insert(0x2004, 'L'); // 5 - tc2.insert(0x4005, 'L'); // 6 - tc2.insert(0x3007, 'E'); // 7 - tc2.insert(0x2008, 'E'); // 8 - tc2.insert(0x3008, 'L'); // 9 + tc2.insert(0, 'E'); // 0 + tc2.insert(0x50, 'x'); // 1 + tc2.insert(0x100, 'x'); // 2 + tc2.insert(0x1002, 'L'); // 3 + tc2.insert(0x1004, 'E'); // 4 + tc2.insert(0x2004, 'L'); // 5 + tc2.insert(0x4005, 'L'); // 6 + tc2.insert(0x3007, 'E'); // 7 + tc2.insert(0x2008, 'E'); // 8 + tc2.insert(0x3008, 'L'); // 9 TestChunks tc3(sumLog, "remove", 0x4000, true); - tc3.removeAt(0); // 0 - tc3.removeAt(0x50); // f - tc3.removeAt(0x100); // e - tc3.removeAt(0xffc); // d - tc3.removeAt(0xffc); // c - tc3.removeAt(0x1ffa); // b - tc3.removeAt(0x3ff9); // a - tc3.removeAt(0x2ffa); // 9 - tc3.removeAt(0x2ff7); // 8 - tc3.removeAt(0x1ff7); // 7 + tc3.removeAt(0); // 0 + tc3.removeAt(0x50); // f + tc3.removeAt(0x100); // e + tc3.removeAt(0xffc); // d + tc3.removeAt(0xffc); // c + tc3.removeAt(0x1ffa); // b + tc3.removeAt(0x3ff9); // a + tc3.removeAt(0x2ffa); // 9 + tc3.removeAt(0x2ff7); // 8 + tc3.removeAt(0x1ff7); // 7 TestChunks tc4(sumLog, "random", 0x40000, true); tc4.random(1000); diff --git a/test/testchunks.cpp b/test/testchunks.cpp index f044504..d4b12f0 100644 --- a/test/testchunks.cpp +++ b/test/testchunks.cpp @@ -19,13 +19,12 @@ #include "testchunks.h" #include - -TestChunks::TestChunks(QTextStream &log, QString tName, int size, bool random, int saveFile) : _chunks(nullptr) +TestChunks::TestChunks(QTextStream &log, QString tName, int size, bool random, int saveFile) + : _chunks(nullptr) { char hex[] = "0123456789abcdef"; srand(0); - for (int idx=0; idx < size; idx++) - { + for (int idx = 0; idx < size; idx++) { if (random) _data += char(rand() % 0x100); else @@ -44,13 +43,11 @@ TestChunks::TestChunks(QTextStream &log, QString tName, int size, bool random, i void TestChunks::random(int count) { - for (int idx=1; idx < count; idx++) - { + for (int idx = 1; idx < count; idx++) { int action = rand() % 3; int pos = rand() % _data.size(); char b = char(rand() % 0x100); - switch (action) - { + switch (action) { case 0: removeAt(pos); break; @@ -66,25 +63,25 @@ void TestChunks::random(int count) void TestChunks::insert(qint64 pos, char b) { - _data.insert((int)pos, b); - _copy.insert((int)pos, char(0)); - _highlighted.insert((int)pos, 1); + _data.insert((int) pos, b); + _copy.insert((int) pos, char(0)); + _highlighted.insert((int) pos, 1); _chunks.insert(pos, b); compare(); } void TestChunks::overwrite(qint64 pos, char b) { - _data[(int)pos] = b; - _highlighted[(int)pos] = 1; + _data[(int) pos] = b; + _highlighted[(int) pos] = 1; _chunks.overwrite(pos, b); compare(); } void TestChunks::removeAt(qint64 pos) { - _data.remove((int)pos, 1); - _highlighted.remove((int)pos, 1); + _data.remove((int) pos, 1); + _highlighted.remove((int) pos, 1); _chunks.removeAt(pos); compare(); } @@ -104,8 +101,7 @@ void TestChunks::compare() int chunkSize = _chunks.chunkSize(); QString tName = QString("logs/%1_%2_%3").arg(_tName).arg(_tCnt).arg(chunkSize); - if (error || (_tCnt >= _saveFile)) - { + if (error || (_tCnt >= _saveFile)) { QFile file1(tName + "_data.txt"); file1.open(QIODevice::WriteOnly); file1.write(_data); @@ -127,15 +123,11 @@ void TestChunks::compare() file4.close(); } - if (error) - { + if (error) { qDebug() << "NOK " << tName; *_log << "NOK " << tName << "\n"; - } - else - { + } else { qDebug() << "OK " << tName; *_log << "OK " << tName << "\n"; } - } diff --git a/test/testchunks.h b/test/testchunks.h index f91d0e9..618273b 100644 --- a/test/testchunks.h +++ b/test/testchunks.h @@ -29,14 +29,13 @@ class TestChunks { public: - TestChunks(QTextStream &log, QString tName, int size, bool random=true, int saveFile=0x7fffffff); + TestChunks(QTextStream &log, QString tName, int size, bool random = true, int saveFile = 0x7fffffff); void insert(qint64 pos, char b); void overwrite(qint64 pos, char b); void removeAt(qint64 pos); void random(int count); void compare(); - private: QByteArray _data, _highlighted, _copy; QBuffer _cData;