feat(api)!: 补充遗漏的插件函数实现和机制并移除一些接口;重构十六进制编辑组件增强标注能力;更好的代码提示;

This commit is contained in:
寂静的羽夏 2024-11-08 18:35:24 +08:00
parent 96fa55d930
commit c08c2a859e
64 changed files with 1803 additions and 1958 deletions

View File

@ -75,7 +75,7 @@ add_library(
set_target_properties( set_target_properties(
QHexView QHexView
PROPERTIES AUTOMOC ON PROPERTIES AUTOMOC ON
CXX_STANDARD 11 CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON) CXX_STANDARD_REQUIRED ON)
target_link_libraries(QHexView PRIVATE Qt${QT_VERSION_MAJOR}::Widgets target_link_libraries(QHexView PRIVATE Qt${QT_VERSION_MAJOR}::Widgets

View File

@ -1,8 +1,8 @@
#include "bookmarkclearcommand.h" #include "bookmarkclearcommand.h"
BookMarkClearCommand::BookMarkClearCommand(QHexDocument *doc, BookMarkClearCommand::BookMarkClearCommand(
QList<BookMarkStruct> bookmarks, QHexDocument *doc, const QMap<qsizetype, QString> &bookmarks,
QUndoCommand *parent) QUndoCommand *parent)
: QUndoCommand(parent), m_doc(doc), m_bookmarks(bookmarks) {} : QUndoCommand(parent), m_doc(doc), m_bookmarks(bookmarks) {}
void BookMarkClearCommand::redo() { m_doc->clearBookMark(); } void BookMarkClearCommand::redo() { m_doc->clearBookMark(); }

View File

@ -2,12 +2,14 @@
#define BOOKMARKCLEARCOMMAND_H #define BOOKMARKCLEARCOMMAND_H
#include "document/qhexdocument.h" #include "document/qhexdocument.h"
#include <QMap>
#include <QObject> #include <QObject>
#include <QUndoCommand> #include <QUndoCommand>
class BookMarkClearCommand : public QUndoCommand { class BookMarkClearCommand : public QUndoCommand {
public: public:
BookMarkClearCommand(QHexDocument *doc, QList<BookMarkStruct> bookmarks, BookMarkClearCommand(QHexDocument *doc,
const QMap<qsizetype, QString> &bookmarks,
QUndoCommand *parent = nullptr); QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
@ -15,7 +17,7 @@ public:
protected: protected:
QHexDocument *m_doc; QHexDocument *m_doc;
QList<BookMarkStruct> m_bookmarks; QMap<qsizetype, QString> m_bookmarks;
}; };
#endif // BOOKMARKCLEARCOMMAND_H #endif // BOOKMARKCLEARCOMMAND_H

View File

@ -1,7 +1,7 @@
#include "metaaddcommand.h" #include "metaaddcommand.h"
MetaAddCommand::MetaAddCommand(QHexMetadata *hexmeta, MetaAddCommand::MetaAddCommand(QHexMetadata *hexmeta,
QHexMetadataAbsoluteItem &meta, const QHexMetadataItem &meta,
QUndoCommand *parent) QUndoCommand *parent)
: MetaCommand(hexmeta, meta, parent) {} : MetaCommand(hexmeta, meta, parent) {}

View File

@ -6,7 +6,7 @@
class MetaAddCommand : public MetaCommand { class MetaAddCommand : public MetaCommand {
public: public:
MetaAddCommand(QHexMetadata *hexmeta, QHexMetadataAbsoluteItem &meta, MetaAddCommand(QHexMetadata *hexmeta, const QHexMetadataItem &meta,
QUndoCommand *parent = nullptr); QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;

View File

@ -1,7 +1,7 @@
#include "metaclearcommand.h" #include "metaclearcommand.h"
MetaClearCommand::MetaClearCommand(QHexMetadata *hexmeta, MetaClearCommand::MetaClearCommand(QHexMetadata *hexmeta,
QList<QHexMetadataAbsoluteItem> metas, const QVector<QHexMetadataItem> &metas,
QUndoCommand *parent) QUndoCommand *parent)
: QUndoCommand(parent), m_hexmeta(hexmeta), m_metas(metas) {} : QUndoCommand(parent), m_hexmeta(hexmeta), m_metas(metas) {}

View File

@ -12,7 +12,7 @@
class MetaClearCommand : public QUndoCommand { class MetaClearCommand : public QUndoCommand {
public: public:
MetaClearCommand(QHexMetadata *hexmeta, MetaClearCommand(QHexMetadata *hexmeta,
QList<QHexMetadataAbsoluteItem> metas, const QVector<QHexMetadataItem> &metas,
QUndoCommand *parent = nullptr); QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
@ -20,7 +20,7 @@ public:
protected: protected:
QHexMetadata *m_hexmeta; QHexMetadata *m_hexmeta;
QList<QHexMetadataAbsoluteItem> m_metas; QVector<QHexMetadataItem> m_metas;
}; };
#endif // METACLEARCOMMAND_H #endif // METACLEARCOMMAND_H

View File

@ -1,5 +1,5 @@
#include "metacommand.h" #include "metacommand.h"
MetaCommand::MetaCommand(QHexMetadata *hexmeta, QHexMetadataAbsoluteItem &meta, MetaCommand::MetaCommand(QHexMetadata *hexmeta, const QHexMetadataItem &meta,
QUndoCommand *parent) QUndoCommand *parent)
: QUndoCommand(parent), m_hexmeta(hexmeta), m_meta(meta) {} : QUndoCommand(parent), m_hexmeta(hexmeta), m_meta(meta) {}

View File

@ -10,12 +10,12 @@
class MetaCommand : public QUndoCommand { class MetaCommand : public QUndoCommand {
public: public:
MetaCommand(QHexMetadata *hexmeta, QHexMetadataAbsoluteItem &meta, MetaCommand(QHexMetadata *hexmeta, const QHexMetadataItem &meta,
QUndoCommand *parent = nullptr); QUndoCommand *parent = nullptr);
protected: protected:
QHexMetadata *m_hexmeta; QHexMetadata *m_hexmeta;
QHexMetadataAbsoluteItem m_meta; QHexMetadataItem m_meta;
}; };
#endif // METACOMMAND_H #endif // METACOMMAND_H

View File

@ -1,7 +1,7 @@
#include "metaremovecommand.h" #include "metaremovecommand.h"
MetaRemoveCommand::MetaRemoveCommand(QHexMetadata *hexmeta, MetaRemoveCommand::MetaRemoveCommand(QHexMetadata *hexmeta,
QHexMetadataAbsoluteItem &meta, const QHexMetadataItem &meta,
QUndoCommand *parent) QUndoCommand *parent)
: MetaCommand(hexmeta, meta, parent) {} : MetaCommand(hexmeta, meta, parent) {}

View File

@ -9,7 +9,7 @@
class MetaRemoveCommand : public MetaCommand { class MetaRemoveCommand : public MetaCommand {
public: public:
MetaRemoveCommand(QHexMetadata *hexmeta, QHexMetadataAbsoluteItem &meta, MetaRemoveCommand(QHexMetadata *hexmeta, const QHexMetadataItem &meta,
QUndoCommand *parent = nullptr); QUndoCommand *parent = nullptr);
void undo() override; void undo() override;

View File

@ -9,7 +9,7 @@ MetaRemovePosCommand::MetaRemovePosCommand(QHexMetadata *hexmeta, qsizetype pos,
void MetaRemovePosCommand::redo() { m_hexmeta->removeMetadata(m_pos); } void MetaRemovePosCommand::redo() { m_hexmeta->removeMetadata(m_pos); }
void MetaRemovePosCommand::undo() { void MetaRemovePosCommand::undo() {
for (auto item : olditems) for (auto &item : olditems)
m_hexmeta->metadata(item.begin, item.end, item.foreground, m_hexmeta->metadata(item.begin, item.end, item.foreground,
item.background, item.comment); item.background, item.comment);
} }

View File

@ -18,7 +18,7 @@ public:
protected: protected:
QHexMetadata *m_hexmeta; QHexMetadata *m_hexmeta;
qsizetype m_pos; qsizetype m_pos;
QList<QHexMetadataAbsoluteItem> olditems; QVector<QHexMetadataItem> olditems;
}; };
#endif // METAREMOVEPOSCOMMAND_H #endif // METAREMOVEPOSCOMMAND_H

View File

@ -1,8 +1,8 @@
#include "metareplacecommand.h" #include "metareplacecommand.h"
MetaReplaceCommand::MetaReplaceCommand(QHexMetadata *hexmeta, MetaReplaceCommand::MetaReplaceCommand(QHexMetadata *hexmeta,
QHexMetadataAbsoluteItem &meta, const QHexMetadataItem &meta,
QHexMetadataAbsoluteItem &oldmeta, const QHexMetadataItem &oldmeta,
QUndoCommand *parent) QUndoCommand *parent)
: MetaCommand(hexmeta, meta, parent), m_old(oldmeta) {} : MetaCommand(hexmeta, meta, parent), m_old(oldmeta) {}

View File

@ -6,14 +6,14 @@
class MetaReplaceCommand : public MetaCommand { class MetaReplaceCommand : public MetaCommand {
public: public:
MetaReplaceCommand(QHexMetadata *hexmeta, QHexMetadataAbsoluteItem &meta, MetaReplaceCommand(QHexMetadata *hexmeta, const QHexMetadataItem &meta,
QHexMetadataAbsoluteItem &oldmeta, const QHexMetadataItem &oldmeta,
QUndoCommand *parent = nullptr); QUndoCommand *parent = nullptr);
void undo() override; void undo() override;
void redo() override; void redo() override;
private: private:
QHexMetadataAbsoluteItem m_old; QHexMetadataItem m_old;
}; };
#endif // METAREPLACECOMMAND_H #endif // METAREPLACECOMMAND_H

View File

@ -23,25 +23,29 @@
/*======================*/ /*======================*/
// added by wingsummer // added by wingsummer
QList<qsizetype> QHexDocument::getsBookmarkPos(qsizetype line) { QList<qsizetype> QHexDocument::getLineBookmarksPos(qsizetype line) {
QList<qsizetype> pos; QList<qsizetype> pos;
auto begin = m_hexlinewidth * line; auto begin = m_hexlinewidth * line;
auto end = m_hexlinewidth + begin; auto end = m_hexlinewidth + begin;
for (auto item : bookmarks) {
if (item.pos >= begin && item.pos <= end) auto lbound = _bookmarks.lowerBound(begin);
pos.push_back(item.pos); auto ubound = _bookmarks.upperBound(end);
for (auto p = lbound; p != ubound; ++p) {
pos.append(p.key());
} }
return pos; return pos;
} }
bool QHexDocument::lineHasBookMark(qsizetype line) { bool QHexDocument::lineHasBookMark(qsizetype line) {
auto begin = m_hexlinewidth * line; auto begin = m_hexlinewidth * line;
auto end = m_hexlinewidth + begin; auto end = m_hexlinewidth + begin;
for (auto item : bookmarks) {
if (item.pos >= begin && item.pos <= end) auto lbound = _bookmarks.lowerBound(begin);
return true; auto ubound = _bookmarks.upperBound(end);
}
return false; return lbound != ubound;
} }
void QHexDocument::addUndoCommand(QUndoCommand *command) { void QHexDocument::addUndoCommand(QUndoCommand *command) {
@ -117,10 +121,8 @@ bool QHexDocument::setKeepSize(bool b) {
return true; return true;
} }
QList<BookMarkStruct> *QHexDocument::bookMarksPtr() { return &bookmarks; } const QMap<qsizetype, QString> &QHexDocument::bookMarks() const {
return _bookmarks;
const QList<BookMarkStruct> &QHexDocument::bookMarks() const {
return bookmarks;
} }
bool QHexDocument::AddBookMark(qsizetype pos, QString comment) { bool QHexDocument::AddBookMark(qsizetype pos, QString comment) {
@ -130,25 +132,29 @@ bool QHexDocument::AddBookMark(qsizetype pos, QString comment) {
return true; return true;
} }
bool QHexDocument::RemoveBookMark(qsizetype pos) {
m_undostack->push(new BookMarkRemoveCommand(this, pos, bookMark(pos)));
return true;
}
bool QHexDocument::ModBookMark(qsizetype pos, QString comment) { bool QHexDocument::ModBookMark(qsizetype pos, QString comment) {
if (!m_keepsize) if (!m_keepsize)
return false; return false;
m_undostack->push( m_undostack->push(
new BookMarkReplaceCommand(this, pos, comment, bookMarkComment(pos))); new BookMarkReplaceCommand(this, pos, comment, bookMark(pos)));
return true; return true;
} }
bool QHexDocument::ClearBookMark() { bool QHexDocument::ClearBookMark() {
if (!m_keepsize) if (!m_keepsize)
return false; return false;
m_undostack->push(new BookMarkClearCommand(this, getAllBookMarks())); m_undostack->push(new BookMarkClearCommand(this, _bookmarks));
return true; return true;
} }
bool QHexDocument::addBookMark(qsizetype pos, QString comment) { bool QHexDocument::addBookMark(qsizetype pos, QString comment) {
if (m_keepsize && !existBookMark(pos)) { if (m_keepsize && !existBookMark(pos)) {
BookMarkStruct b{pos, comment}; _bookmarks.insert(pos, comment);
bookmarks.append(b);
setDocSaved(false); setDocSaved(false);
emit documentChanged(); emit documentChanged();
emit bookMarkChanged(); emit bookMarkChanged();
@ -157,97 +163,41 @@ bool QHexDocument::addBookMark(qsizetype pos, QString comment) {
return false; return false;
} }
QString QHexDocument::bookMarkComment(qsizetype pos) { QString QHexDocument::bookMark(qsizetype pos) { return _bookmarks.value(pos); }
if (pos > 0 && pos < m_buffer->length()) {
for (auto item : bookmarks) { bool QHexDocument::bookMarkExists(qsizetype pos) {
if (item.pos == pos) { return _bookmarks.contains(pos);
return item.comment;
}
}
}
return QString();
} }
BookMarkStruct QHexDocument::bookMark(qsizetype pos) { qsizetype QHexDocument::bookMarkPos(qsizetype index) {
if (pos > 0 && pos < m_buffer->length()) { Q_ASSERT(index >= 0 && index < _bookmarks.size());
for (auto item : bookmarks) { return *(std::next(_bookmarks.keyBegin(), index));
if (item.pos == pos) {
return item;
}
}
}
return BookMarkStruct{-1, ""};
} }
BookMarkStruct QHexDocument::bookMarkByIndex(qsizetype index) { bool QHexDocument::RemoveBookMarks(const QList<qsizetype> &pos) {
if (index >= 0 && index < bookmarks.count()) {
return bookmarks.at(index);
} else {
BookMarkStruct b;
b.pos = -1;
return b;
}
}
bool QHexDocument::RemoveBookMarks(QList<qsizetype> &pos) {
if (!m_keepsize) if (!m_keepsize)
return false; return false;
m_undostack->beginMacro("RemoveBookMarks"); m_undostack->beginMacro("RemoveBookMarks");
for (auto p : pos) { for (auto p : pos) {
m_undostack->push( m_undostack->push(new BookMarkRemoveCommand(this, p, bookMark(p)));
new BookMarkRemoveCommand(this, p, bookMarkComment(p)));
} }
m_undostack->endMacro(); m_undostack->endMacro();
emit documentChanged(); emit documentChanged();
return true; return true;
} }
bool QHexDocument::RemoveBookMark(qsizetype index) {
if (!m_keepsize)
return false;
auto b = bookmarks.at(index);
m_undostack->push(new BookMarkRemoveCommand(this, b.pos, b.comment));
return true;
}
bool QHexDocument::removeBookMark(qsizetype pos) { bool QHexDocument::removeBookMark(qsizetype pos) {
if (m_keepsize && pos >= 0 && pos < m_buffer->length()) { if (m_keepsize) {
int index = 0; return _bookmarks.remove(pos) != 0;
for (auto item : bookmarks) {
if (pos == item.pos) {
bookmarks.removeAt(index);
setDocSaved(false);
emit documentChanged();
emit bookMarkChanged();
break;
}
index++;
}
return true;
} }
return false; return false;
} }
bool QHexDocument::removeBookMarkByIndex(qsizetype index) { bool QHexDocument::modBookMark(qsizetype pos, const QString &comment) {
if (m_keepsize && index >= 0 && index < bookmarks.count()) { if (m_keepsize) {
bookmarks.removeAt(index); if (_bookmarks.contains(pos)) {
setDocSaved(false); _bookmarks[pos] = comment;
emit documentChanged(); return true;
emit bookMarkChanged();
return true;
}
return false;
}
bool QHexDocument::modBookMark(qsizetype pos, QString comment) {
if (m_keepsize && pos > 0 && pos < m_buffer->length()) {
for (auto &item : bookmarks) {
if (item.pos == pos) {
item.comment = comment;
setDocSaved(false);
emit bookMarkChanged();
return true;
}
} }
} }
return false; return false;
@ -255,7 +205,7 @@ bool QHexDocument::modBookMark(qsizetype pos, QString comment) {
bool QHexDocument::clearBookMark() { bool QHexDocument::clearBookMark() {
if (m_keepsize) { if (m_keepsize) {
bookmarks.clear(); _bookmarks.clear();
setDocSaved(false); setDocSaved(false);
emit documentChanged(); emit documentChanged();
emit bookMarkChanged(); emit bookMarkChanged();
@ -265,22 +215,13 @@ bool QHexDocument::clearBookMark() {
} }
bool QHexDocument::existBookMark(qsizetype pos) { bool QHexDocument::existBookMark(qsizetype pos) {
for (auto item : bookmarks) { return _bookmarks.contains(pos);
if (item.pos == pos) {
return true;
}
}
return false;
} }
const QList<BookMarkStruct> &QHexDocument::getAllBookMarks() { qsizetype QHexDocument::bookMarksCount() const { return _bookmarks.count(); }
return bookmarks;
}
qsizetype QHexDocument::bookMarksCount() const { return bookmarks.count(); } void QHexDocument::applyBookMarks(const QMap<qsizetype, QString> &books) {
_bookmarks = books;
void QHexDocument::applyBookMarks(const QList<BookMarkStruct> &books) {
bookmarks.append(books);
setDocSaved(false); setDocSaved(false);
emit documentChanged(); emit documentChanged();
} }
@ -424,9 +365,6 @@ void QHexDocument::setHexLineWidth(quint8 value) {
} }
QHexMetadata *QHexDocument::metadata() const { return m_metadata; } QHexMetadata *QHexDocument::metadata() const { return m_metadata; }
QByteArray QHexDocument::read(qsizetype offset, qsizetype len) {
return m_buffer->read(offset, len);
}
char QHexDocument::at(qsizetype offset) const { char QHexDocument::at(qsizetype offset) const {
return char(m_buffer->at(offset)); return char(m_buffer->at(offset));

View File

@ -9,16 +9,6 @@
#include <QStorageInfo> #include <QStorageInfo>
#include <QUndoStack> #include <QUndoStack>
/*=========================*/
// added by wingsummer
struct BookMarkStruct {
qsizetype pos;
QString comment;
};
/*=========================*/
class QHexDocument : public QObject { class QHexDocument : public QObject {
Q_OBJECT Q_OBJECT
@ -44,7 +34,7 @@ public:
void addUndoCommand(QUndoCommand *command); void addUndoCommand(QUndoCommand *command);
bool lineHasBookMark(qsizetype line); bool lineHasBookMark(qsizetype line);
QList<qsizetype> getsBookmarkPos(qsizetype line); QList<qsizetype> getLineBookmarksPos(qsizetype line);
bool setLockedFile(bool b); bool setLockedFile(bool b);
bool setKeepSize(bool b); bool setKeepSize(bool b);
@ -54,28 +44,27 @@ public:
//---------------------------------- //----------------------------------
bool AddBookMark(qsizetype pos, QString comment); bool AddBookMark(qsizetype pos, QString comment);
bool RemoveBookMark(qsizetype index); bool RemoveBookMark(qsizetype pos);
bool RemoveBookMarks(QList<qsizetype> &pos); bool RemoveBookMarks(const QList<qsizetype> &pos);
bool ModBookMark(qsizetype pos, QString comment); bool ModBookMark(qsizetype pos, QString comment);
bool ClearBookMark(); bool ClearBookMark();
//---------------------------------- //----------------------------------
bool addBookMark(qsizetype pos, QString comment); bool addBookMark(qsizetype pos, QString comment);
bool modBookMark(qsizetype pos, QString comment); bool modBookMark(qsizetype pos, const QString &comment);
BookMarkStruct bookMarkByIndex(qsizetype index); QString bookMark(qsizetype pos);
BookMarkStruct bookMark(qsizetype pos); bool bookMarkExists(qsizetype pos);
// note: maybe changed when bookmarks are chaged
qsizetype bookMarkPos(qsizetype index);
QString bookMarkComment(qsizetype pos);
const QList<BookMarkStruct> &getAllBookMarks();
qsizetype bookMarksCount() const; qsizetype bookMarksCount() const;
void applyBookMarks(const QList<BookMarkStruct> &books); void applyBookMarks(const QMap<qsizetype, QString> &books);
bool removeBookMarkByIndex(qsizetype index);
bool removeBookMark(qsizetype pos); bool removeBookMark(qsizetype pos);
bool clearBookMark(); bool clearBookMark();
QList<BookMarkStruct> *bookMarksPtr(); const QMap<qsizetype, QString> &bookMarks() const;
const QList<BookMarkStruct> &bookMarks() const;
bool existBookMark(qsizetype pos); bool existBookMark(qsizetype pos);
@ -101,7 +90,7 @@ public:
/*======================*/ /*======================*/
public: public:
QByteArray read(qsizetype offset, qsizetype len = -1); QByteArray read(qsizetype offset, qsizetype len = -1) const;
char at(qsizetype offset) const; char at(qsizetype offset) const;
void SetBaseAddress(quintptr baseaddress); void SetBaseAddress(quintptr baseaddress);
@ -122,7 +111,6 @@ public slots:
bool Remove(QHexCursor *cursor, qsizetype offset, qsizetype len, bool Remove(QHexCursor *cursor, qsizetype offset, qsizetype len,
int nibbleindex = 0); int nibbleindex = 0);
QByteArray read(qsizetype offset, qsizetype len) const;
bool saveTo(QIODevice *device, bool cleanUndo); bool saveTo(QIODevice *device, bool cleanUndo);
// qsizetype searchForward(const QByteArray &ba); // qsizetype searchForward(const QByteArray &ba);
@ -205,7 +193,7 @@ private:
bool m_readonly; bool m_readonly;
bool m_keepsize; bool m_keepsize;
bool m_islocked; bool m_islocked;
QList<BookMarkStruct> bookmarks; QMap<qsizetype, QString> _bookmarks;
bool m_metafg = true; bool m_metafg = true;
bool m_metabg = true; bool m_metabg = true;

View File

@ -5,12 +5,22 @@
#include "commands/meta/metaremoveposcommand.h" #include "commands/meta/metaremoveposcommand.h"
#include "commands/meta/metareplacecommand.h" #include "commands/meta/metareplacecommand.h"
#include <QtAlgorithms>
QHexMetadata::QHexMetadata(QUndoStack *undo, QObject *parent) QHexMetadata::QHexMetadata(QUndoStack *undo, QObject *parent)
: QObject(parent), m_undo(undo) {} : QObject(parent), m_undo(undo) {}
const QHexLineMetadata &QHexMetadata::get(qsizetype line) const { QHexLineMetadata QHexMetadata::get(qsizetype line) const {
auto it = m_metadata.find(line); if (!m_linemeta.contains(line)) {
return it.value(); return {};
}
QHexLineMetadata ret;
for (auto &item : m_linemeta[line]) {
ret.append(item);
}
return ret;
} }
/*==================================*/ /*==================================*/
@ -18,13 +28,12 @@ const QHexLineMetadata &QHexMetadata::get(qsizetype line) const {
//----------undo redo wrapper---------- //----------undo redo wrapper----------
void QHexMetadata::ModifyMetadata(QHexMetadataAbsoluteItem newmeta, void QHexMetadata::ModifyMetadata(QHexMetadataItem newmeta,
QHexMetadataAbsoluteItem oldmeta) { QHexMetadataItem oldmeta) {
m_undo->push(new MetaReplaceCommand(this, newmeta, oldmeta)); m_undo->push(new MetaReplaceCommand(this, newmeta, oldmeta));
} }
void QHexMetadata::RemoveMetadatas( void QHexMetadata::RemoveMetadatas(const QList<QHexMetadataItem> &items) {
const QList<QHexMetadataAbsoluteItem> &items) {
m_undo->beginMacro("RemoveMetadatas"); m_undo->beginMacro("RemoveMetadatas");
for (auto &item : items) { for (auto &item : items) {
RemoveMetadata(item); RemoveMetadata(item);
@ -32,7 +41,7 @@ void QHexMetadata::RemoveMetadatas(
m_undo->endMacro(); m_undo->endMacro();
} }
void QHexMetadata::RemoveMetadata(QHexMetadataAbsoluteItem item) { void QHexMetadata::RemoveMetadata(QHexMetadataItem item) {
m_undo->push(new MetaRemoveCommand(this, item)); m_undo->push(new MetaRemoveCommand(this, item));
} }
@ -43,81 +52,103 @@ void QHexMetadata::RemoveMetadata(qsizetype offset) {
void QHexMetadata::Metadata(qsizetype begin, qsizetype end, void QHexMetadata::Metadata(qsizetype begin, qsizetype end,
const QColor &fgcolor, const QColor &bgcolor, const QColor &fgcolor, const QColor &bgcolor,
const QString &comment) { const QString &comment) {
QHexMetadataAbsoluteItem absi{begin, end, fgcolor, bgcolor, comment}; QHexMetadataItem absi{begin, end, fgcolor, bgcolor, comment};
m_undo->push(new MetaAddCommand(this, absi)); m_undo->push(new MetaAddCommand(this, absi));
} }
void QHexMetadata::Clear() { void QHexMetadata::Clear() {
m_undo->push(new MetaClearCommand(this, getallMetas())); m_undo->push(new MetaClearCommand(this, this->getAllMetadata()));
} }
//-------- the real function----------- //-------- the real function-----------
void QHexMetadata::undo() { m_undo->undo(); }
void QHexMetadata::redo() { m_undo->redo(); }
bool QHexMetadata::canUndo() { return m_undo->canUndo(); }
bool QHexMetadata::canRedo() { return m_undo->canRedo(); }
QList<QHexMetadataAbsoluteItem> QHexMetadata::getallMetas() { bool QHexMetadata::modifyMetadata(const QHexMetadataItem &newmeta,
return m_absoluteMetadata; const QHexMetadataItem &oldmeta) {
if (removeMetadata(oldmeta)) {
metadata(newmeta.begin, newmeta.end, newmeta.foreground,
newmeta.background, newmeta.comment);
return true;
}
return false;
} }
const QList<QHexMetadataAbsoluteItem> &QHexMetadata::getallMetasPtr() { bool QHexMetadata::removeMetadata(const QHexMetadataItem &item) {
return m_absoluteMetadata; auto index = m_metadata.indexOf(item);
} if (index < 0) {
return false;
void QHexMetadata::modifyMetadata(QHexMetadataAbsoluteItem newmeta, }
QHexMetadataAbsoluteItem oldmeta) { m_metadata.removeAt(index);
removeMetadata(oldmeta); for (auto &l : m_linemeta) {
metadata(newmeta.begin, newmeta.end, newmeta.foreground, newmeta.background, l.remove(item);
newmeta.comment);
}
void QHexMetadata::removeMetadata(QHexMetadataAbsoluteItem item) {
auto firstRow = item.begin / m_lineWidth;
auto lastRow = item.end / m_lineWidth;
for (auto i = firstRow; i <= lastRow; i++) {
QList<QHexMetadataItem> delmeta;
auto it = m_metadata.find(i);
if (it != m_metadata.end()) {
for (auto iitem : *it) {
if (iitem.foreground == item.foreground &&
iitem.background == item.background &&
iitem.comment == item.comment) {
delmeta.push_back(iitem);
}
}
for (auto iitem : delmeta) {
it->remove(iitem);
}
m_absoluteMetadata.removeOne(item);
}
} }
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
m_linemeta.erase(std::remove_if(
m_linemeta.begin(), m_linemeta.end(),
[](const QHash<QHexMetadataItem, QHexLineMetadata> &item) {
return item.isEmpty();
}));
#else
m_linemeta.removeIf(
[](const QPair<qsizetype, QHash<QHexMetadataItem, QHexLineMetadata>>
&item) { return item.second.isEmpty(); });
#endif
emit metadataChanged(); emit metadataChanged();
return true;
} }
void QHexMetadata::removeMetadata(qsizetype offset) { void QHexMetadata::removeMetadata(qsizetype offset) {
QList<QHexMetadataAbsoluteItem> delneeded; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
for (auto item : m_absoluteMetadata) { m_metadata.erase(
if (offset >= item.begin && offset <= item.end) { std::remove_if(m_metadata.begin(), m_metadata.end(),
removeMetadata(item); [offset, this](const QHexMetadataItem &item) {
auto r = offset >= item.begin && offset <= item.end;
if (r) {
for (auto &l : m_linemeta) {
l.remove(item);
}
}
return r;
}));
#else
m_metadata.removeIf([offset, this](const QHexMetadataItem &item) {
auto r = offset >= item.begin && offset <= item.end;
if (r) {
for (auto &l : m_linemeta) {
l.remove(item);
}
} }
} return r;
});
#endif
} }
QList<QHexMetadataAbsoluteItem> QHexMetadata::gets(qsizetype offset) { QVector<QHexMetadataItem> QHexMetadata::getAllMetadata() const {
return m_absoluteMetadata; return m_metadata;
} }
void QHexMetadata::applyMetas(QList<QHexMetadataAbsoluteItem> metas) { QVector<QHexMetadataItem> QHexMetadata::gets(qsizetype offset) {
for (auto item : metas) { QVector<QHexMetadataItem> ret;
metadata(item.begin, item.end, item.foreground, item.background,
item.comment); std::copy_if(
} #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
m_metadata.begin(), m_metadata.end(),
#else
m_metadata.constBegin(), m_metadata.constEnd(),
#endif
std::back_inserter(ret), [offset](const QHexMetadataItem &item) {
return offset >= item.begin && offset <= item.end;
});
return ret;
} }
bool QHexMetadata::hasMetadata() { return m_absoluteMetadata.count() > 0; } void QHexMetadata::applyMetas(const QVector<QHexMetadataItem> &metas) {
m_metadata = metas;
}
bool QHexMetadata::hasMetadata() { return m_metadata.count() > 0; }
/*==================================*/ /*==================================*/
@ -145,13 +176,13 @@ QString QHexMetadata::comments(qsizetype line, qsizetype column) const {
} }
bool QHexMetadata::lineHasMetadata(qsizetype line) const { bool QHexMetadata::lineHasMetadata(qsizetype line) const {
return m_metadata.contains(line); return m_linemeta.contains(line);
} }
qsizetype QHexMetadata::size() const { return m_absoluteMetadata.size(); } qsizetype QHexMetadata::size() const { return m_metadata.size(); }
void QHexMetadata::clear() { void QHexMetadata::clear() {
m_absoluteMetadata.clear(); m_linemeta.clear();
m_metadata.clear(); m_metadata.clear();
emit metadataChanged(); emit metadataChanged();
} }
@ -159,27 +190,59 @@ void QHexMetadata::clear() {
void QHexMetadata::metadata(qsizetype begin, qsizetype end, void QHexMetadata::metadata(qsizetype begin, qsizetype end,
const QColor &fgcolor, const QColor &bgcolor, const QColor &fgcolor, const QColor &bgcolor,
const QString &comment) { const QString &comment) {
QHexMetadataAbsoluteItem absi{begin, end, fgcolor, bgcolor, comment}; QHexMetadataItem absi{begin, end, fgcolor, bgcolor, comment};
m_absoluteMetadata.append(absi); addMetadata(absi);
setAbsoluteMetadata(absi);
emit metadataChanged(); emit metadataChanged();
} }
void QHexMetadata::setAbsoluteMetadata(const QHexMetadataAbsoluteItem &mai) { void QHexMetadata::setLineWidth(quint8 width) {
Q_ASSERT(m_lineWidth > 0); if (width != m_lineWidth) {
m_lineWidth = width;
const auto firstRow = mai.begin / m_lineWidth; m_linemeta.clear();
const auto lastRow = mai.end / m_lineWidth; for (auto &item : m_metadata) {
addMetadata(item);
}
emit metadataChanged();
}
}
void QHexMetadata::color(qsizetype begin, qsizetype end, const QColor &fgcolor,
const QColor &bgcolor) {
this->metadata(begin, end, fgcolor, bgcolor, QString());
}
void QHexMetadata::foreground(qsizetype begin, qsizetype end,
const QColor &fgcolor) {
this->color(begin, end, fgcolor, QColor());
}
void QHexMetadata::background(qsizetype begin, qsizetype end,
const QColor &bgcolor) {
this->color(begin, end, QColor(), bgcolor);
}
void QHexMetadata::comment(qsizetype begin, qsizetype end,
const QString &comment) {
this->metadata(begin, end, QColor(), QColor(), comment);
}
void QHexMetadata::addMetadata(const QHexMetadataItem &mi) {
const auto firstRow = mi.begin / m_lineWidth;
const auto lastRow = mi.end / m_lineWidth;
for (auto row = firstRow; row <= lastRow; ++row) { for (auto row = firstRow; row <= lastRow; ++row) {
qsizetype start, length; qsizetype start, length;
if (row == firstRow) { if (row == firstRow) {
start = mai.begin % m_lineWidth; Q_ASSERT(m_lineWidth > 0);
start = mi.begin % m_lineWidth;
} else { } else {
start = 0; start = 0;
} }
if (row == lastRow) { if (row == lastRow) {
const int lastChar = mai.end % m_lineWidth; Q_ASSERT(m_lineWidth > 0);
const int lastChar = mi.end % m_lineWidth;
length = lastChar - start; length = lastChar - start;
} else { } else {
// fix the bug by wingsummer // fix the bug by wingsummer
@ -190,69 +253,10 @@ void QHexMetadata::setAbsoluteMetadata(const QHexMetadataAbsoluteItem &mai) {
} }
if (length > 0) { if (length > 0) {
setMetadata({row, start, length, mai.foreground, mai.background, m_linemeta[row][mi].append(
mai.comment}); {start, length, mi.foreground, mi.background, mi.comment});
} }
} }
}
void QHexMetadata::setLineWidth(quint8 width) { m_metadata << mi;
if (width != m_lineWidth) {
m_lineWidth = width;
// clean m_metadata
m_metadata.clear();
// and regenerate with new line width size
for (int i = 0; i < m_absoluteMetadata.size(); ++i) {
setAbsoluteMetadata(m_absoluteMetadata[i]);
}
}
}
void QHexMetadata::metadata(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor, const QColor &bgcolor,
const QString &comment) {
const qsizetype begin = qsizetype(line * m_lineWidth + uint(start));
const qsizetype end = begin + length;
// delegate to the new interface
this->metadata(begin, end, fgcolor, bgcolor, comment);
emit metadataChanged();
}
void QHexMetadata::color(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor, const QColor &bgcolor) {
this->metadata(line, start, length, fgcolor, bgcolor, QString());
}
void QHexMetadata::foreground(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor) {
this->color(line, start, length, fgcolor, QColor());
}
void QHexMetadata::background(qsizetype line, qsizetype start, qsizetype length,
const QColor &bgcolor) {
this->color(line, start, length, QColor(), bgcolor);
}
void QHexMetadata::comment(qsizetype line, qsizetype start, qsizetype length,
const QString &comment) {
this->metadata(line, start, length, QColor(), QColor(), comment);
}
void QHexMetadata::setMetadata(const QHexMetadataItem &mi) {
if (!m_metadata.contains(mi.line)) {
QHexLineMetadata linemetadata;
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
linemetadata << mi;
#else
linemetadata.push_back(mi);
#endif
m_metadata[mi.line] = linemetadata;
} else {
QHexLineMetadata &linemetadata = m_metadata[mi.line];
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
linemetadata << mi;
#else
linemetadata.push_back(mi);
#endif
}
} }

View File

@ -2,55 +2,80 @@
#define QHEXMETADATA_H #define QHEXMETADATA_H
#include <QObject> #include <QObject>
#include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
#include <QLinkedList>
#else
#include <list>
#endif
#include <QColor> #include <QColor>
#include <QHash> #include <QHash>
#include <QMap>
#include <QUndoStack> #include <QUndoStack>
#include <QVector> #include <QVector>
struct QHexMetadataAbsoluteItem { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
qsizetype begin; using qhash_result_t = uint;
qsizetype end;
// copying from QT6 source code for supporting QT5's qHashMulti
namespace QtPrivate {
template <typename T>
inline constexpr bool
QNothrowHashableHelper_v = noexcept(qHash(std::declval<const T &>()));
template <typename T, typename Enable = void>
struct QNothrowHashable : std::false_type {};
template <typename T>
struct QNothrowHashable<T, std::enable_if_t<QNothrowHashableHelper_v<T>>>
: std::true_type {};
template <typename T>
constexpr inline bool QNothrowHashable_v = QNothrowHashable<T>::value;
} // namespace QtPrivate
template <typename... T>
constexpr qhash_result_t qHashMulti(size_t seed, const T &...args) noexcept(
std::conjunction_v<QtPrivate::QNothrowHashable<T>...>) {
QtPrivate::QHashCombine hash;
return ((seed = hash(seed, args)), ...), seed;
}
#else
using qhash_result_t = size_t;
#endif
struct QHexMetadataItem {
qsizetype begin = -1;
qsizetype end = -1;
QColor foreground, background; QColor foreground, background;
QString comment; QString comment;
// added by wingsummer // added by wingsummer
bool operator==(const QHexMetadataAbsoluteItem &item) const { bool operator==(const QHexMetadataItem &item) const {
return begin == item.begin && end == item.end && return begin == item.begin && end == item.end &&
foreground == item.foreground && background == item.background && foreground == item.foreground && background == item.background &&
comment == item.comment; comment == item.comment;
} }
}; };
struct QHexMetadataItem { inline qhash_result_t qHash(const QHexMetadataItem &c,
qsizetype line; qhash_result_t seed) noexcept {
qsizetype start, length; return qHashMulti(seed, c.begin, c.end, c.foreground.rgba(),
c.background.rgba(), c.comment);
}
// only for rendering
struct QHexLineMetadataItem {
qsizetype start = -1, length = 0;
QColor foreground, background; QColor foreground, background;
QString comment; QString comment;
QHexMetadataItem *parent = nullptr;
// added by wingsummer
bool operator==(const QHexMetadataItem &item) const {
return line == item.line && start == item.start &&
foreground == item.foreground && background == item.background &&
comment == item.comment;
}
}; };
typedef std::list<QHexMetadataItem> QHexLineMetadata; typedef QList<QHexLineMetadataItem> QHexLineMetadata;
class QHexMetadata : public QObject { class QHexMetadata : public QObject {
Q_OBJECT Q_OBJECT
public: public:
explicit QHexMetadata(QUndoStack *undo, QObject *parent = nullptr); explicit QHexMetadata(QUndoStack *undo, QObject *parent = nullptr);
const QHexLineMetadata &get(qsizetype line) const; QHexLineMetadata get(qsizetype line) const;
QString comments(qsizetype line, qsizetype column) const; QString comments(qsizetype line, qsizetype column) const;
bool lineHasMetadata(qsizetype line) const; // modified by wingsummer bool lineHasMetadata(qsizetype line) const; // modified by wingsummer
@ -59,10 +84,9 @@ public:
/*============================*/ /*============================*/
// added by wingsummer // added by wingsummer
void ModifyMetadata(QHexMetadataAbsoluteItem newmeta, void ModifyMetadata(QHexMetadataItem newmeta, QHexMetadataItem oldmeta);
QHexMetadataAbsoluteItem oldmeta); void RemoveMetadatas(const QList<QHexMetadataItem> &items);
void RemoveMetadatas(const QList<QHexMetadataAbsoluteItem> &items); void RemoveMetadata(QHexMetadataItem item);
void RemoveMetadata(QHexMetadataAbsoluteItem item);
void RemoveMetadata(qsizetype offset); void RemoveMetadata(qsizetype offset);
void Metadata(qsizetype begin, qsizetype end, const QColor &fgcolor, void Metadata(qsizetype begin, qsizetype end, const QColor &fgcolor,
const QColor &bgcolor, const QString &comment); const QColor &bgcolor, const QString &comment);
@ -70,17 +94,15 @@ public:
//--------------------------------------------------------- //---------------------------------------------------------
void modifyMetadata(QHexMetadataAbsoluteItem newmeta, bool modifyMetadata(const QHexMetadataItem &newmeta,
QHexMetadataAbsoluteItem oldmeta); const QHexMetadataItem &oldmeta);
void removeMetadata(QHexMetadataAbsoluteItem item); bool removeMetadata(const QHexMetadataItem &item);
void removeMetadata(qsizetype offset); void removeMetadata(qsizetype offset);
QList<QHexMetadataAbsoluteItem> gets(qsizetype offset);
void applyMetas(QList<QHexMetadataAbsoluteItem> metas);
void redo(); QVector<QHexMetadataItem> getAllMetadata() const;
void undo(); QVector<QHexMetadataItem> gets(qsizetype offset);
bool canRedo(); void applyMetas(const QVector<QHexMetadataItem> &metas);
bool canUndo();
bool hasMetadata(); bool hasMetadata();
/*============================*/ /*============================*/
@ -93,39 +115,25 @@ public:
void metadata(qsizetype begin, qsizetype end, const QColor &fgcolor, void metadata(qsizetype begin, qsizetype end, const QColor &fgcolor,
const QColor &bgcolor, const QString &comment); const QColor &bgcolor, const QString &comment);
// old interface with line, start, length void color(qsizetype begin, qsizetype end, const QColor &fgcolor,
void metadata(qsizetype line, qsizetype start, qsizetype length, const QColor &bgcolor);
const QColor &fgcolor, const QColor &bgcolor, void foreground(qsizetype begin, qsizetype end, const QColor &fgcolor);
const QString &comment); void background(qsizetype begin, qsizetype end, const QColor &bgcolor);
void comment(qsizetype begin, qsizetype end, const QString &comment);
void color(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor, const QColor &bgcolor);
void foreground(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor);
void background(qsizetype line, qsizetype start, qsizetype length,
const QColor &bgcolor);
void comment(qsizetype line, qsizetype start, qsizetype length,
const QString &comment);
QList<QHexMetadataAbsoluteItem>
getallMetas(); // added by wingsummer to support workspace
const QList<QHexMetadataAbsoluteItem> &
getallMetasPtr(); // added by wingsummer to support workspace
private: private:
void setMetadata(const QHexMetadataItem &mi); void addMetadata(const QHexMetadataItem &mi);
void setAbsoluteMetadata(const QHexMetadataAbsoluteItem &mi);
signals: signals:
void metadataChanged(); void metadataChanged();
private: private:
quint8 m_lineWidth; quint8 m_lineWidth;
QHash<qsizetype, QHexLineMetadata> m_metadata;
QList<QHexMetadataAbsoluteItem> m_absoluteMetadata;
QUndoStack *m_undo; // added by wingsummer QMap<qsizetype, QHash<QHexMetadataItem, QHexLineMetadata>> m_linemeta;
QVector<QHexMetadataItem> m_metadata;
QUndoStack *m_undo = nullptr; // added by wingsummer
}; };
#endif // QHEXMETADATA_H #endif // QHEXMETADATA_H

View File

@ -5,7 +5,6 @@
#include <QTextCursor> #include <QTextCursor>
#include <QWidget> #include <QWidget>
#include <cctype> #include <cctype>
#include <cmath>
#include <cwctype> #include <cwctype>
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
@ -23,21 +22,21 @@ bool QHexRenderer::stringVisible() { return m_asciiVisible; }
void QHexRenderer::setStringVisible(bool b) { void QHexRenderer::setStringVisible(bool b) {
m_asciiVisible = b; m_asciiVisible = b;
m_document->documentChanged(); emit m_document->documentChanged();
} }
bool QHexRenderer::headerVisible() { return m_headerVisible; } bool QHexRenderer::headerVisible() { return m_headerVisible; }
void QHexRenderer::setHeaderVisible(bool b) { void QHexRenderer::setHeaderVisible(bool b) {
m_headerVisible = b; m_headerVisible = b;
m_document->documentChanged(); emit m_document->documentChanged();
} }
bool QHexRenderer::addressVisible() { return m_addressVisible; } bool QHexRenderer::addressVisible() { return m_addressVisible; }
void QHexRenderer::setAddressVisible(bool b) { void QHexRenderer::setAddressVisible(bool b) {
m_addressVisible = b; m_addressVisible = b;
m_document->documentChanged(); emit m_document->documentChanged();
} }
QString QHexRenderer::encoding() { QString QHexRenderer::encoding() {
@ -66,7 +65,7 @@ bool QHexRenderer::setEncoding(const QString &encoding) {
if (encoding.compare(QStringLiteral("ISO-8859-1"), Qt::CaseInsensitive) == if (encoding.compare(QStringLiteral("ISO-8859-1"), Qt::CaseInsensitive) ==
0) { 0) {
m_encoding = QStringLiteral("ASCII"); m_encoding = QStringLiteral("ASCII");
m_document->documentChanged(); emit m_document->documentChanged();
return true; return true;
} }
if (QStringConverter::encodingForName(enc.toUtf8())) { if (QStringConverter::encodingForName(enc.toUtf8())) {
@ -74,7 +73,7 @@ bool QHexRenderer::setEncoding(const QString &encoding) {
if (QTextCodec::codecForName(encoding.toUtf8())) { if (QTextCodec::codecForName(encoding.toUtf8())) {
#endif #endif
m_encoding = encoding; m_encoding = encoding;
m_document->documentChanged(); emit m_document->documentChanged();
return true; return true;
} }
return false; return false;
@ -406,7 +405,7 @@ void QHexRenderer::applyMetadata(QTextCursor &textcursor, qsizetype line,
return; return;
const QHexLineMetadata &linemetadata = metadata->get(line); const QHexLineMetadata &linemetadata = metadata->get(line);
for (const QHexMetadataItem &mi : linemetadata) { for (auto &mi : linemetadata) {
QTextCharFormat charformat; QTextCharFormat charformat;
if (m_document->metabgVisible() && mi.background.isValid() && if (m_document->metabgVisible() && mi.background.isValid() &&
mi.background.rgba()) mi.background.rgba())
@ -577,7 +576,7 @@ void QHexRenderer::applyBookMark(QTextCursor &textcursor, qsizetype line,
if (!m_document->lineHasBookMark(line)) if (!m_document->lineHasBookMark(line))
return; return;
auto pos = m_document->getsBookmarkPos(line); auto pos = m_document->getLineBookmarksPos(line);
for (auto item : pos) { for (auto item : pos) {
textcursor.setPosition(int((item % hexLineWidth()) * factor) + 2); textcursor.setPosition(int((item % hexLineWidth()) * factor) + 2);
auto charformat = textcursor.charFormat(); auto charformat = textcursor.charFormat();

View File

@ -115,16 +115,16 @@ void QHexView::establishSignal(QHexDocument *doc) {
&QHexView::canRedoChanged); &QHexView::canRedoChanged);
connect(doc, &QHexDocument::documentSaved, this, &QHexView::documentSaved); connect(doc, &QHexDocument::documentSaved, this, &QHexView::documentSaved);
connect(doc, &QHexDocument::metabgVisibleChanged, this, [=](bool b) { connect(doc, &QHexDocument::metabgVisibleChanged, this, [=](bool b) {
QHexView::metabgVisibleChanged(b); emit metabgVisibleChanged(b);
emit this->metaStatusChanged(); emit metaStatusChanged();
}); });
connect(doc, &QHexDocument::metafgVisibleChanged, this, [=](bool b) { connect(doc, &QHexDocument::metafgVisibleChanged, this, [=](bool b) {
QHexView::metafgVisibleChanged(b); emit metafgVisibleChanged(b);
emit this->metaStatusChanged(); emit metaStatusChanged();
}); });
connect(doc, &QHexDocument::metaCommentVisibleChanged, this, [=](bool b) { connect(doc, &QHexDocument::metaCommentVisibleChanged, this, [=](bool b) {
QHexView::metaCommentVisibleChanged(b); emit metaCommentVisibleChanged(b);
emit this->metaStatusChanged(); emit metaStatusChanged();
}); });
connect(doc, &QHexDocument::metaDataChanged, this, connect(doc, &QHexDocument::metaDataChanged, this,
[=] { this->viewport()->update(); }); [=] { this->viewport()->update(); });
@ -292,26 +292,6 @@ qsizetype QHexView::searchBackward(qsizetype begin, const QByteArray &ba) {
return m_document->searchBackward(startPos, ba); return m_document->searchBackward(startPos, ba);
} }
void QHexView::gotoBookMark(qsizetype index) {
if (index >= 0 && index < m_document->bookMarksCount()) {
auto bookmark = m_document->bookMarkByIndex(index);
m_cursor->moveTo(bookmark.pos);
}
}
bool QHexView::existBookMarkByIndex(qsizetype &index) {
auto curpos = m_cursor->position().offset();
int i = 0;
for (auto &item : m_document->getAllBookMarks()) {
if (item.pos == curpos) {
index = i;
return true;
}
i++;
}
return false;
}
bool QHexView::RemoveSelection(int nibbleindex) { bool QHexView::RemoveSelection(int nibbleindex) {
if (!m_cursor->hasSelection()) if (!m_cursor->hasSelection())
return false; return false;
@ -338,10 +318,6 @@ bool QHexView::atEnd() const {
return m_cursor->position().offset() >= m_document->length(); return m_cursor->position().offset() >= m_document->length();
} }
void QHexView::gotoMetaData(qsizetype index) {
m_cursor->moveTo(m_document->metadata()->getallMetasPtr().at(index).begin);
}
QByteArray QHexView::selectedBytes() const { QByteArray QHexView::selectedBytes() const {
if (!m_cursor->hasSelection()) if (!m_cursor->hasSelection())
return QByteArray(); return QByteArray();

View File

@ -97,14 +97,10 @@ public:
qsizetype searchForward(qsizetype begin, const QByteArray &ba); qsizetype searchForward(qsizetype begin, const QByteArray &ba);
qsizetype searchBackward(qsizetype begin, const QByteArray &ba); qsizetype searchBackward(qsizetype begin, const QByteArray &ba);
void gotoBookMark(qsizetype index);
bool existBookMarkByIndex(qsizetype &index);
bool RemoveSelection(int nibbleindex = 1); bool RemoveSelection(int nibbleindex = 1);
bool removeSelection(); bool removeSelection();
bool atEnd() const; bool atEnd() const;
void gotoMetaData(qsizetype index);
QByteArray selectedBytes() const; QByteArray selectedBytes() const;
bool cut(bool hex); bool cut(bool hex);

View File

@ -54,12 +54,9 @@ set(SNIPPET_SRC
lib/snippets/qsnippet_p.h lib/snippets/qsnippet_p.h
lib/snippets/qsnippetbinding.cpp lib/snippets/qsnippetbinding.cpp
lib/snippets/qsnippetbinding.h lib/snippets/qsnippetbinding.h
lib/snippets/qsnippetedit.cpp
lib/snippets/qsnippetedit.h
lib/snippets/qsnippetmanager.cpp lib/snippets/qsnippetmanager.cpp
lib/snippets/qsnippetmanager.h lib/snippets/qsnippetmanager.h
lib/snippets/qsnippetpatternloader.h lib/snippets/qsnippetpatternloader.h)
lib/snippets/snippetedit.ui)
set(SOURCE_FILES set(SOURCE_FILES
lib/qce-config.h lib/qce-config.h

View File

@ -214,7 +214,7 @@ public:
static int screenLength(const QChar *d, int l, int tabStop); static int screenLength(const QChar *d, int l, int tabStop);
static QString screenable(const QChar *d, int l, int tabStop); static QString screenable(const QChar *d, int l, int tabStop);
inline void markViewDirty() { formatsChanged(); } inline void markViewDirty() { emit formatsChanged(); }
bool isClean() const; bool isClean() const;

View File

@ -60,20 +60,7 @@
#include <QTextStream> #include <QTextStream>
#include <QTimer> #include <QTimer>
// #define Q_GL_EDITOR
#ifdef _QMDI_
#include "qmdiserver.h"
#endif
#ifdef _EDYUK_
#include "edyukapplication.h"
#include "qshortcutmanager.h"
#define Q_SHORTCUT(a, s, c) EDYUK_SHORTCUT(a, tr(c), tr(s))
#else
#define Q_SHORTCUT(a, s, c) a->setShortcut(QKeySequence(tr(s, c))) #define Q_SHORTCUT(a, s, c) a->setShortcut(QKeySequence(tr(s, c)))
#endif
#ifdef Q_GL_EDITOR #ifdef Q_GL_EDITOR
#include <QtOpenGLWidgets/QOpenGLWidget> #include <QtOpenGLWidgets/QOpenGLWidget>
@ -463,42 +450,35 @@ void QEditor::init(bool actions) {
setAttribute(Qt::WA_KeyCompression, true); setAttribute(Qt::WA_KeyCompression, true);
setAttribute(Qt::WA_InputMethodEnabled, true); setAttribute(Qt::WA_InputMethodEnabled, true);
connect(this, connect(this, &QEditor::markChanged, QLineMarksInfoCenter::instance(),
SIGNAL(markChanged(QString, QDocumentLineHandle *, int, bool)), &QLineMarksInfoCenter::markChanged);
QLineMarksInfoCenter::instance(),
SLOT(markChanged(QString, QDocumentLineHandle *, int, bool)));
m_doc = new QDocument(this); m_doc = new QDocument(this);
_docfont = m_doc->font(); _docfont = m_doc->font();
connect(m_doc, SIGNAL(formatsChange(int, int)), this, connect(m_doc, &QDocument::formatsChange, this, &QEditor::repaintContent);
SLOT(repaintContent(int, int)));
connect(m_doc, SIGNAL(contentsChange(int, int)), this, connect(m_doc, &QDocument::contentsChange, this, &QEditor::updateContent);
SLOT(updateContent(int, int)));
connect(m_doc, SIGNAL(formatsChanged()), viewport(), SLOT(update())); connect(m_doc, &QDocument::formatsChanged, this,
[=] { this->viewport()->update(); });
connect(m_doc, SIGNAL(widthChanged(int)), this, connect(m_doc, &QDocument::widthChanged, this,
SLOT(documentWidthChanged(int))); &QEditor::documentWidthChanged);
connect(m_doc, SIGNAL(heightChanged(int)), this, connect(m_doc, &QDocument::heightChanged, this,
SLOT(documentHeightChanged(int))); &QEditor::documentHeightChanged);
connect(m_doc, SIGNAL(cleanChanged(bool)), this, connect(m_doc, &QDocument::cleanChanged, this, &QEditor::setContentClean);
SLOT(setContentClean(bool)));
connect(m_doc, SIGNAL(undoAvailable(bool)), this, connect(m_doc, &QDocument::undoAvailable, this, &QEditor::undoAvailable);
SIGNAL(undoAvailable(bool)));
connect(m_doc, SIGNAL(redoAvailable(bool)), this, connect(m_doc, &QDocument::redoAvailable, this, &QEditor::redoAvailable);
SIGNAL(redoAvailable(bool)));
connect(m_doc, SIGNAL(markChanged(QDocumentLineHandle *, int, bool)), this, connect(m_doc, &QDocument::markChanged, this, &QEditor::emitMarkChanged);
SLOT(markChanged(QDocumentLineHandle *, int, bool)));
connect(m_doc, SIGNAL(lineEndingChanged(int)), this, connect(m_doc, &QDocument::lineEndingChanged, this,
SLOT(lineEndingChanged(int))); &QEditor::lineEndingChanged);
m_cursor = QDocumentCursor(m_doc); m_cursor = QDocumentCursor(m_doc);
m_cursor.setAutoUpdated(true); m_cursor.setAutoUpdated(true);
@ -516,8 +496,8 @@ void QEditor::init(bool actions) {
a->setObjectName("undo"); a->setObjectName("undo");
Q_SHORTCUT(a, "Ctrl+Z", "Edit"); Q_SHORTCUT(a, "Ctrl+Z", "Edit");
a->setEnabled(false); a->setEnabled(false);
connect(this, SIGNAL(undoAvailable(bool)), a, SLOT(setEnabled(bool))); connect(this, &QEditor::undoAvailable, a, &QAction::setEnabled);
connect(a, SIGNAL(triggered()), this, SLOT(undo())); connect(a, &QAction::triggered, this, &QEditor::undo);
addAction(a, "&Edit", "Edit"); addAction(a, "&Edit", "Edit");
@ -1127,14 +1107,6 @@ void QEditor::retranslate() {
if (aDefaultBinding) if (aDefaultBinding)
aDefaultBinding->setText(tr("Default")); aDefaultBinding->setText(tr("Default"));
#ifdef _QMDI_
menus.setTranslation("&Edit", tr("&Edit"));
menus.setTranslation("&Search", tr("&Search"));
toolbars.setTranslation("Edit", tr("Edit"));
toolbars.setTranslation("Search", tr("Search"));
#endif
} }
/*! /*!
@ -1167,16 +1139,6 @@ void QEditor::addAction(QAction *a, const QString &menu,
if (pMenu && menu.size()) { if (pMenu && menu.size()) {
pMenu->addAction(a); pMenu->addAction(a);
#ifdef _QMDI_
menus[menu]->addAction(a);
#endif
}
if (toolbar.size()) {
#ifdef _QMDI_
toolbars[toolbar]->addAction(a);
#endif
} }
} }
@ -1201,18 +1163,8 @@ void QEditor::removeAction(QAction *a, const QString &menu,
if (pMenu) if (pMenu)
pMenu->removeAction(a); pMenu->removeAction(a);
#ifdef _QMDI_
if (menu.count()) {
menus[menu]->removeAction(a);
}
if (toolbar.count()) {
toolbars[toolbar]->removeAction(a);
}
#else
Q_UNUSED(menu) Q_UNUSED(menu)
Q_UNUSED(toolbar) Q_UNUSED(toolbar)
#endif
} }
/*! /*!
@ -1576,7 +1528,6 @@ void QEditor::setCursor(const QDocumentCursor &c) {
setFlag(CursorOn, true); setFlag(CursorOn, true);
repaintCursor(); repaintCursor();
ensureCursorVisible(); ensureCursorVisible();
selectionChange();
updateMicroFocus(); updateMicroFocus();
} }
@ -1890,7 +1841,6 @@ void QEditor::undo() {
m_doc->undo(); m_doc->undo();
selectionChange();
ensureCursorVisible(); ensureCursorVisible();
setFlag(CursorOn, true); setFlag(CursorOn, true);
emitCursorPositionChanged(); emitCursorPositionChanged();
@ -1908,7 +1858,6 @@ void QEditor::redo() {
m_doc->redo(); m_doc->redo();
selectionChange();
ensureCursorVisible(); ensureCursorVisible();
setFlag(CursorOn, true); setFlag(CursorOn, true);
emitCursorPositionChanged(); emitCursorPositionChanged();
@ -2193,7 +2142,6 @@ void QEditor::selectAll() {
m_cursor.movePosition(1, QDocumentCursor::End, QDocumentCursor::KeepAnchor); m_cursor.movePosition(1, QDocumentCursor::End, QDocumentCursor::KeepAnchor);
emitCursorPositionChanged(); emitCursorPositionChanged();
selectionChange(true);
viewport()->update(); viewport()->update();
} }
@ -2412,8 +2360,6 @@ void QEditor::keyPressEvent(QKeyEvent *e) {
} }
} }
selectionChange();
// placeholders handling // placeholders handling
bool bHandled = false; bool bHandled = false;
@ -2481,7 +2427,6 @@ void QEditor::keyPressEvent(QKeyEvent *e) {
viewport()->update(); viewport()->update();
} else { } else {
repaintCursor(); repaintCursor();
selectionChange();
} }
bHandled = true; bHandled = true;
@ -2567,7 +2512,7 @@ void QEditor::keyPressEvent(QKeyEvent *e) {
setFlag(CursorOn, true); setFlag(CursorOn, true);
ensureCursorVisible(); ensureCursorVisible();
repaintCursor(); repaintCursor();
selectionChange();
break; break;
} }
@ -2634,7 +2579,6 @@ void QEditor::mouseMoveEvent(QMouseEvent *e) {
} }
repaintCursor(); repaintCursor();
selectionChange();
const QPoint mousePos = mapToContents(e->pos()); const QPoint mousePos = mapToContents(e->pos());
@ -2684,7 +2628,6 @@ void QEditor::mouseMoveEvent(QMouseEvent *e) {
// setFlag(FoldedCursor, isCollapsed()); // setFlag(FoldedCursor, isCollapsed());
} }
selectionChange(true);
ensureCursorVisible(); ensureCursorVisible();
// emit clearAutoCloseStack(); // emit clearAutoCloseStack();
emitCursorPositionChanged(); emitCursorPositionChanged();
@ -2715,7 +2658,6 @@ void QEditor::mousePressEvent(QMouseEvent *e) {
setFlag(MaybeDrag, false); setFlag(MaybeDrag, false);
repaintCursor(); repaintCursor();
selectionChange();
if (m_click.isActive() && if (m_click.isActive() &&
(( ((
@ -2819,7 +2761,7 @@ void QEditor::mousePressEvent(QMouseEvent *e) {
// emit clearAutoCloseStack(); // emit clearAutoCloseStack();
emitCursorPositionChanged(); emitCursorPositionChanged();
repaintCursor(); repaintCursor();
selectionChange();
break; break;
} }
@ -2838,7 +2780,6 @@ void QEditor::mouseReleaseEvent(QMouseEvent *e) {
m_scroll.stop(); m_scroll.stop();
repaintCursor(); repaintCursor();
selectionChange();
if (flag(MaybeDrag)) { if (flag(MaybeDrag)) {
setFlag(MousePressed, false); setFlag(MousePressed, false);
@ -2868,8 +2809,6 @@ void QEditor::mouseReleaseEvent(QMouseEvent *e) {
if (m_drag.isActive()) if (m_drag.isActive())
m_drag.stop(); m_drag.stop();
selectionChange();
for (QEditorInputBindingInterface *b : m_bindings) for (QEditorInputBindingInterface *b : m_bindings)
b->postMouseReleaseEvent(e, this); b->postMouseReleaseEvent(e, this);
} }
@ -2891,7 +2830,7 @@ void QEditor::mouseDoubleClickEvent(QMouseEvent *e) {
setFlag(MaybeDrag, false); setFlag(MaybeDrag, false);
repaintCursor(); repaintCursor();
selectionChange();
clearCursorMirrors(); clearCursorMirrors();
setCursorPosition(mapToContents(e->pos())); setCursorPosition(mapToContents(e->pos()));
@ -2905,7 +2844,7 @@ void QEditor::mouseDoubleClickEvent(QMouseEvent *e) {
emitCursorPositionChanged(); emitCursorPositionChanged();
repaintCursor(); repaintCursor();
selectionChange();
} else { } else {
// qDebug("invalid cursor"); // qDebug("invalid cursor");
} }
@ -3037,8 +2976,6 @@ void QEditor::dropEvent(QDropEvent *e) {
// m_cursor.endEditBlock(); // m_cursor.endEditBlock();
m_doc->endMacro(); m_doc->endMacro();
selectionChange();
} }
/*! /*!
@ -3163,46 +3100,17 @@ void QEditor::contextMenuEvent(QContextMenuEvent *e) {
return; return;
} }
selectionChange();
e->accept(); e->accept();
pMenu->exec(e->globalPos()); pMenu->exec(e->globalPos());
} }
/*!
\brief Close event
When build with qmdilib support (e.g in Edyuk) this check for
modifications and a dialog pops up to offer various options
(like saving, discarding or canceling)
*/
void QEditor::closeEvent(QCloseEvent *e) {
#ifdef _QMDI_
bool bOK = true;
if (isContentModified())
bOK = server()->maybeSave(this);
if (bOK) {
e->accept();
notifyDeletion();
} else {
e->ignore();
}
#else
QAbstractScrollArea::closeEvent(e);
#endif
}
#ifndef _QMDI_
/*! /*!
\return Whether the document has been modified. \return Whether the document has been modified.
*/ */
bool QEditor::isContentModified() const { bool QEditor::isContentModified() const {
return m_doc ? !m_doc->isClean() : false; return m_doc ? !m_doc->isClean() : false;
} }
#endif
/*! /*!
\brief Notify that the content is clean (modifications undone or \brief Notify that the content is clean (modifications undone or
@ -3218,10 +3126,6 @@ void QEditor::setContentClean(bool y) { setContentModified(!y); }
\note Don't mess with this. The document knows better. \note Don't mess with this. The document knows better.
*/ */
void QEditor::setContentModified(bool y) { void QEditor::setContentModified(bool y) {
#ifdef _QMDI_
qmdiClient::setContentModified(y);
#endif
setWindowModified(y); setWindowModified(y);
emit contentModified(y); emit contentModified(y);
} }
@ -3246,12 +3150,8 @@ void QEditor::setFileName(const QString &f) {
watcher()->removeWatch(QString(), this); watcher()->removeWatch(QString(), this);
#ifdef _QMDI_
qmdiClient::setFileName(f);
#else
m_fileName = f; m_fileName = f;
m_name = QFileInfo(f).fileName(); m_name = QFileInfo(f).fileName();
#endif
// if ( fileName().count() ) // if ( fileName().count() )
// m_watcher->addPath(fileName()); // m_watcher->addPath(fileName());
@ -3278,7 +3178,6 @@ void QEditor::setTitle(const QString &title) {
emit titleChanged(title); emit titleChanged(title);
} }
#ifndef _QMDI_
/*! /*!
\return The name of the file being edited (without its path) \return The name of the file being edited (without its path)
*/ */
@ -3288,7 +3187,6 @@ QString QEditor::name() const { return m_name; }
\return The full filename of the file being edited \return The full filename of the file being edited
*/ */
QString QEditor::fileName() const { return m_fileName; } QString QEditor::fileName() const { return m_fileName; }
#endif
/*! /*!
\brief Prevent tab key press to be considered as widget navigation \brief Prevent tab key press to be considered as widget navigation
@ -3734,8 +3632,6 @@ bool QEditor::processCursor(QDocumentCursor &c, QKeyEvent *e, bool &b) {
} }
} }
selectionChange();
return true; return true;
} }
@ -3871,7 +3767,6 @@ void QEditor::write(const QString &s) {
setFlag(CursorOn, true); setFlag(CursorOn, true);
ensureCursorVisible(); ensureCursorVisible();
repaintCursor(); repaintCursor();
selectionChange();
} }
/*! /*!
@ -3903,26 +3798,6 @@ void QEditor::setPanelMargins(int l, int t, int r, int b) {
} }
} }
/*!
\deprecated
\brief Does not do anything anymore...
*/
void QEditor::selectionChange(bool force) {
Q_UNUSED(force)
// TODO : repaint only selection rect
/*
if ( false )//force )
{
//qDebug("repainting selection... [%i]", force);
viewport()->update();
} else if ( m_cursor.hasSelection() ) {
viewport()->update(selectionRect());
}
m_selection = m_cursor.hasSelection();
*/
}
/*! /*!
\brief Request repaint (using QWidget::update()) for the region occupied \brief Request repaint (using QWidget::update()) for the region occupied
by the cursor by the cursor
@ -4047,7 +3922,8 @@ void QEditor::ensureVisible(const QRect &rect) {
background whenever the cursor move from a line to another. background whenever the cursor move from a line to another.
*/ */
QRect QEditor::cursorRect() const { QRect QEditor::cursorRect() const {
return m_cursor.hasSelection() ? selectionRect() : cursorRect(m_cursor); return m_cursor.hasSelection() ? selectionRect()
: QEditor::cursorRect(m_cursor);
} }
/*! /*!
@ -4062,12 +3938,12 @@ QRect QEditor::cursorRect() const {
*/ */
QRect QEditor::selectionRect() const { QRect QEditor::selectionRect() const {
if (!m_cursor.hasSelection()) if (!m_cursor.hasSelection())
return cursorRect(m_cursor); return QEditor::cursorRect(m_cursor);
QDocumentSelection s = m_cursor.selection(); QDocumentSelection s = m_cursor.selection();
if (s.startLine == s.endLine) if (s.startLine == s.endLine)
return cursorRect(m_cursor); return QEditor::cursorRect(m_cursor);
int y = m_doc->y(s.startLine); int y = m_doc->y(s.startLine);
QRect r = m_doc->lineRect(s.endLine); QRect r = m_doc->lineRect(s.endLine);
@ -4119,7 +3995,7 @@ QRect QEditor::lineRect(const QDocumentLine &l) const {
\return The line rect of the given cursor \return The line rect of the given cursor
*/ */
QRect QEditor::cursorRect(const QDocumentCursor &c) const { QRect QEditor::cursorRect(const QDocumentCursor &c) const {
return lineRect(c.lineNumber()); return QEditor::lineRect(c.lineNumber());
} }
/*! /*!
@ -4443,7 +4319,7 @@ void QEditor::updateContent(int i, int n) {
/*! /*!
\internal \internal
*/ */
void QEditor::markChanged(QDocumentLineHandle *l, int mark, bool on) { void QEditor::emitMarkChanged(QDocumentLineHandle *l, int mark, bool on) {
emit markChanged(fileName(), l, mark, on); emit markChanged(fileName(), l, mark, on);
} }

View File

@ -33,10 +33,6 @@
#include "qdocument.h" #include "qdocument.h"
#include "qdocumentcursor.h" #include "qdocumentcursor.h"
#ifdef _QMDI_
#include "qmdiclient.h"
#endif
class QMenu; class QMenu;
class QAction; class QAction;
class QMimeData; class QMimeData;
@ -51,12 +47,7 @@ class QCodeCompletionEngine;
class QEditorInputBindingInterface; class QEditorInputBindingInterface;
class QCE_EXPORT QEditor : public QAbstractScrollArea class QCE_EXPORT QEditor : public QAbstractScrollArea {
#ifdef _QMDI_
,
public qmdiClient
#endif
{
friend class QEditConfig; friend class QEditConfig;
friend class QEditorFactory; friend class QEditorFactory;
@ -165,12 +156,10 @@ public:
virtual QRect lineRect(const QDocumentLine &l) const; virtual QRect lineRect(const QDocumentLine &l) const;
virtual QRect cursorRect(const QDocumentCursor &c) const; virtual QRect cursorRect(const QDocumentCursor &c) const;
#ifndef _QMDI_
QString name() const; QString name() const;
QString fileName() const; QString fileName() const;
bool isContentModified() const; bool isContentModified() const;
#endif
bool isInConflict() const; bool isInConflict() const;
@ -274,8 +263,6 @@ public slots:
void setScaleRate(qreal rate); void setScaleRate(qreal rate);
qreal scaleRate() const;
void setPanelMargins(int l, int t, int r, int b); void setPanelMargins(int l, int t, int r, int b);
void getPanelMargins(int *l, int *t, int *r, int *b) const; void getPanelMargins(int *l, int *t, int *r, int *b) const;
@ -287,15 +274,17 @@ public slots:
void removePlaceHolder(int i); void removePlaceHolder(int i);
void addPlaceHolder(const PlaceHolder &p, bool autoUpdate = true); void addPlaceHolder(const PlaceHolder &p, bool autoUpdate = true);
int placeHolderCount() const;
int currentPlaceHolder() const;
void nextPlaceHolder(); void nextPlaceHolder();
void previousPlaceHolder(); void previousPlaceHolder();
void setPlaceHolder(int i); void setPlaceHolder(int i);
virtual void setFileName(const QString &f); virtual void setFileName(const QString &f);
public:
int placeHolderCount() const;
int currentPlaceHolder() const;
qreal scaleRate() const;
signals: signals:
void loaded(QEditor *e, const QString &s); void loaded(QEditor *e, const QString &s);
void saved(QEditor *e, const QString &s); void saved(QEditor *e, const QString &s);
@ -356,8 +345,6 @@ protected:
virtual void contextMenuEvent(QContextMenuEvent *e); virtual void contextMenuEvent(QContextMenuEvent *e);
virtual void closeEvent(QCloseEvent *e);
virtual bool focusNextPrevChild(bool next); virtual bool focusNextPrevChild(bool next);
virtual bool moveKeyEvent(QDocumentCursor &c, QKeyEvent *e, bool *leave); virtual bool moveKeyEvent(QDocumentCursor &c, QKeyEvent *e, bool *leave);
@ -377,8 +364,6 @@ public:
void pageUp(QDocumentCursor::MoveMode moveMode); void pageUp(QDocumentCursor::MoveMode moveMode);
void pageDown(QDocumentCursor::MoveMode moveMode); void pageDown(QDocumentCursor::MoveMode moveMode);
void selectionChange(bool force = false);
void repaintCursor(); void repaintCursor();
void ensureCursorVisible(); void ensureCursorVisible();
void ensureVisible(int line); void ensureVisible(int line);
@ -406,7 +391,7 @@ protected slots:
void repaintContent(int i, int n); void repaintContent(int i, int n);
void updateContent(int i, int n); void updateContent(int i, int n);
void markChanged(QDocumentLineHandle *l, int mark, bool on); void emitMarkChanged(QDocumentLineHandle *l, int mark, bool on);
void bindingSelected(QAction *a); void bindingSelected(QAction *a);
@ -419,9 +404,7 @@ protected:
void init(bool actions = true); void init(bool actions = true);
void updateBindingsMenu(); void updateBindingsMenu();
#ifndef _QMDI_
QString m_name, m_fileName; QString m_name, m_fileName;
#endif
QMenu *pMenu; QMenu *pMenu;
QHash<QString, QAction *> m_actions; QHash<QString, QAction *> m_actions;

View File

@ -516,7 +516,7 @@ void QLineMarksInfoCenter::cursorMoved(QEditor *e) {
\internal \internal
*/ */
void QLineMarksInfoCenter::lineDeleted(QDocumentLineHandle *h) { void QLineMarksInfoCenter::lineDeleted(QDocumentLineHandle *h) {
QLineMarkHandleList::iterator i = m_lineMarks.begin(); auto i = m_lineMarks.begin();
while (i != m_lineMarks.end()) { while (i != m_lineMarks.end()) {
if (i->line == h) { if (i->line == h) {

View File

@ -243,17 +243,12 @@ QLayoutItem *QPanelLayout::takeAt(int idx) {
\internal \internal
*/ */
void QPanelLayout::setGeometry(const QRect &r) { void QPanelLayout::setGeometry(const QRect &r) {
// qDebug("laying out %i panels", count());
#ifdef _PANEL_POSITION_FIX_
QScrollBar *vb = m_parent->verticalScrollBar(), QScrollBar *vb = m_parent->verticalScrollBar(),
*hb = m_parent->horizontalScrollBar(); *hb = m_parent->horizontalScrollBar();
QRect rect(r.x(), r.y(), QRect rect(r.x(), r.y(),
r.width() - (vb->isVisibleTo(m_parent) ? vb->width() : 0), r.width() - (vb->isVisibleTo(m_parent) ? vb->width() : 0),
r.height() - (hb->isVisibleTo(m_parent) ? hb->height() : 0)); r.height() - (hb->isVisibleTo(m_parent) ? hb->height() : 0));
#else
QRect rect(r.x(), r.y(), r.width(), r.height());
#endif
int i, eastWidth = 0, westWidth = 0, northHeight = 0, southHeight = 0, int i, eastWidth = 0, westWidth = 0, northHeight = 0, southHeight = 0,
centerHeight = 0; centerHeight = 0;

View File

@ -69,7 +69,7 @@ void QSnippetManager::removeSnippet(int i, bool cleanup) {
QSnippet *snip = m_snippets.takeAt(i); QSnippet *snip = m_snippets.takeAt(i);
emit snippetRemoved(i); emit snippetRemovedByIndex(i);
emit snippetRemoved(snip); emit snippetRemoved(snip);
if (cleanup) if (cleanup)
@ -84,7 +84,7 @@ void QSnippetManager::removeSnippet(QSnippet *snip) {
m_snippets.removeAt(idx); m_snippets.removeAt(idx);
emit snippetRemoved(idx); emit snippetRemovedByIndex(idx);
emit snippetRemoved(snip); emit snippetRemoved(snip);
} }

View File

@ -58,7 +58,7 @@ public slots:
signals: signals:
void snippetAdded(QSnippet *s); void snippetAdded(QSnippet *s);
void snippetRemoved(int i); void snippetRemovedByIndex(int i);
void snippetRemoved(QSnippet *s); void snippetRemoved(QSnippet *s);
private: private:

View File

@ -82,17 +82,17 @@ void QLineNumberPanel::editorChange(QEditor *e) {
} }
if (e) { if (e) {
setFixedWidth( _fixWidth =
QFontMetrics(e->document()->font()) QFontMetrics(e->document()->font())
.horizontalAdvance(QString::number(e->document()->lines())) + .horizontalAdvance(QString::number(e->document()->lines())) +
5); 5;
connect(e, SIGNAL(cursorPositionChanged()), this, SLOT(update())); connect(e, SIGNAL(cursorPositionChanged()), this, SLOT(update()));
connect(e, &QEditor::zoomed, this, [=] { connect(e, &QEditor::zoomed, this, [=] {
setFixedWidth(QFontMetrics(e->document()->font()) _fixWidth = QFontMetrics(e->document()->font())
.horizontalAdvance( .horizontalAdvance(
QString::number(e->document()->lines())) + QString::number(e->document()->lines())) +
5); 5;
}); });
} }
} }
@ -228,3 +228,5 @@ void QLineNumberPanel::paint(QPainter *p, QEditor *e) {
} }
/*! @} */ /*! @} */
QSize QLineNumberPanel::sizeHint() const { return QSize(_fixWidth, 0); }

View File

@ -38,6 +38,8 @@ public:
virtual QString type() const; virtual QString type() const;
virtual QSize sizeHint() const;
public slots: public slots:
void setVerboseMode(bool y); void setVerboseMode(bool y);
@ -47,6 +49,7 @@ protected:
bool m_verbose; bool m_verbose;
int mutable m_minWidth = 0; int mutable m_minWidth = 0;
int _fixWidth = 0;
}; };
#endif // _QLINE_NUMBER_PANEL_H_ #endif // _QLINE_NUMBER_PANEL_H_

View File

@ -302,7 +302,10 @@ set(CODEEDIT_WIDGET
src/qcodeeditwidget/qeditconfig.ui src/qcodeeditwidget/qeditconfig.ui
src/qcodeeditwidget/qformatconfig.h src/qcodeeditwidget/qformatconfig.h
src/qcodeeditwidget/qformatconfig.cpp src/qcodeeditwidget/qformatconfig.cpp
src/qcodeeditwidget/qformatconfig.ui) src/qcodeeditwidget/qformatconfig.ui
src/qcodeeditwidget/qsnippetedit.cpp
src/qcodeeditwidget/qsnippetedit.h
src/qcodeeditwidget/qsnippetedit.ui)
set(PLUGIN_SRC src/plugin/iwingplugin.h src/plugin/pluginsystem.cpp set(PLUGIN_SRC src/plugin/iwingplugin.h src/plugin/pluginsystem.cpp
src/plugin/pluginsystem.h src/plugin/settingpage.h) src/plugin/pluginsystem.h src/plugin/settingpage.h)

File diff suppressed because it is too large Load Diff

View File

@ -77,10 +77,6 @@ QStringList AsCompletion::extensions() const {
} }
void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) { void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
if (pPopup->isVisible()) {
return;
}
// TODO parse current code // TODO parse current code
// auto codes = c.document()->text(true, false); // auto codes = c.document()->text(true, false);
// parser.parse(codes, this->editor()->fileName()); // parser.parse(codes, this->editor()->fileName());
@ -129,7 +125,7 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
auto &_headerNodes = parser.headerNodes(); auto &_headerNodes = parser.headerNodes();
fn = r->content; fn = r->content;
if (trigger.isEmpty()) { if (trigger.isEmpty() && trigWordLen() <= r->content.length()) {
auto eb = tokens.back(); auto eb = tokens.back();
if (eb.type == asTC_KEYWORD) { if (eb.type == asTC_KEYWORD) {
// only support these // only support these
@ -137,6 +133,8 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
complete(c, *SEMI_COLON_TRIGGER); complete(c, *SEMI_COLON_TRIGGER);
} else if (eb.content == *DOT_TRIGGER) { } else if (eb.content == *DOT_TRIGGER) {
complete(c, *DOT_TRIGGER); complete(c, *DOT_TRIGGER);
} else {
pPopup->hide();
} }
return; return;
} else if (eb.type == asTC_IDENTIFIER) { } else if (eb.type == asTC_IDENTIFIER) {
@ -152,24 +150,27 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
auto name = n->qualifiedName(); auto name = n->qualifiedName();
if (name == ns) { if (name == ns) {
nodes << n; nodes << n;
break;
} }
} }
auto cur = c;
cur.movePosition(pr->pos + pr->content.length() -
txt.length());
pPopup->setCursor(cur);
} else { } else {
return; return;
} }
} else {
applyEmptyNsNode(nodes);
} }
} else {
applyEmptyNsNode(nodes);
} }
} else {
applyEmptyNsNode(nodes);
} }
} else { } else {
return; return;
} }
// pPopup->setTemporaryNodes(temp); // pPopup->setTemporaryNodes(temp);
pPopup->setPrefix(fn);
pPopup->setFilter(filter); pPopup->setFilter(filter);
pPopup->setCompletions(nodes); pPopup->setCompletions(nodes);
pPopup->popup(); pPopup->popup();
@ -179,6 +180,7 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
auto name = n->qualifiedName(); auto name = n->qualifiedName();
if (name == fn) { if (name == fn) {
nodes << n; nodes << n;
break;
} }
} }
} else if (trigger == *LEFT_PARE_TRIGGER) { } else if (trigger == *LEFT_PARE_TRIGGER) {
@ -193,6 +195,7 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
auto name = n->qualifiedName(); auto name = n->qualifiedName();
if (name == ns) { if (name == ns) {
nodes << n; nodes << n;
break;
} }
} }
} else { } else {
@ -248,6 +251,7 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
} }
} else { } else {
// pPopup->setTemporaryNodes(temp); // pPopup->setTemporaryNodes(temp);
pPopup->setPrefix({});
pPopup->setFilter(QCodeCompletionWidget::Filter(filter)); pPopup->setFilter(QCodeCompletionWidget::Filter(filter));
pPopup->setCompletions(nodes); pPopup->setCompletions(nodes);
@ -266,6 +270,20 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) {
} }
} }
void AsCompletion::applyEmptyNsNode(QList<QCodeNode *> &nodes) {
if (_emptyNsNodes.isEmpty()) {
for (auto &n : parser.headerNodes()) {
auto name = n->qualifiedName();
if (name.isEmpty()) {
// only one group for empty namespace
_emptyNsNodes << n;
}
}
}
nodes = _emptyNsNodes;
}
void AsCompletion::setEditor(QEditor *e) { void AsCompletion::setEditor(QEditor *e) {
QCodeCompletionEngine::setEditor(e); QCodeCompletionEngine::setEditor(e);
pPopup->setEditor(e); pPopup->setEditor(e);

View File

@ -41,10 +41,15 @@ protected:
virtual void complete(const QDocumentCursor &c, virtual void complete(const QDocumentCursor &c,
const QString &trigger) override; const QString &trigger) override;
private:
void applyEmptyNsNode(QList<QCodeNode *> &nodes);
private: private:
QAsParser parser; QAsParser parser;
asIScriptEngine *_engine; asIScriptEngine *_engine;
QCodeCompletionWidget *pPopup; QCodeCompletionWidget *pPopup;
QList<QCodeNode *> _emptyNsNodes;
}; };
#endif // _CPP_COMPLETION_H_ #endif // _CPP_COMPLETION_H_

View File

@ -233,6 +233,20 @@ void QAsParser::addGlobalFunctionCompletion(asIScriptEngine *engine) {
_maps[ns] << fnInfo; _maps[ns] << fnInfo;
} }
auto node = new QCodeNode;
node->setNodeType(QCodeNode::Group);
for (auto p = _maps.keyBegin(); p != _maps.keyEnd(); p++) {
if (p->isEmpty()) {
continue;
}
auto nsnode = new QCodeNode;
nsnode->setNodeType(QCodeNode::Namespace);
nsnode->setRole(QCodeNode::Name, *p);
nsnode->setParent(node);
node->children().append(nsnode);
}
_headerNodes << node;
for (auto p = _maps.keyValueBegin(); p != _maps.keyValueEnd(); p++) { for (auto p = _maps.keyValueBegin(); p != _maps.keyValueEnd(); p++) {
auto node = new QCodeNode; auto node = new QCodeNode;
_headerNodes << node; _headerNodes << node;

View File

@ -182,9 +182,6 @@ bool ScriptMachine::configureEngine(asIScriptEngine *engine) {
PluginSystem::instance().angelApi()->installAPI( PluginSystem::instance().angelApi()->installAPI(
engine, typeInfo(RegisteredType::tString)); engine, typeInfo(RegisteredType::tString));
// TODO TEST
QAsParser varname(engine);
_immediateContext = engine->CreateContext(); _immediateContext = engine->CreateContext();
_immediateContext->SetExceptionCallback( _immediateContext->SetExceptionCallback(
asMETHOD(ScriptMachine, exceptionCallback), this, asCALL_THISCALL); asMETHOD(ScriptMachine, exceptionCallback), this, asCALL_THISCALL);

View File

@ -26,14 +26,11 @@
WingAngelAPI::WingAngelAPI() { WingAngelAPI::WingAngelAPI() {
qsizetype signalCount = 0; qsizetype signalCount = 0;
const QMetaObject *objs[]{this->metaObject(), const QMetaObject *objs[]{
this->reader.metaObject(), WingAngelAPI::metaObject(), this->reader.metaObject(),
this->controller.metaObject(), this->controller.metaObject(), this->msgbox.metaObject(),
this->msgbox.metaObject(), this->inputbox.metaObject(), this->filedlg.metaObject(),
this->inputbox.metaObject(), this->colordlg.metaObject(), this->visual.metaObject()};
this->filedlg.metaObject(),
this->colordlg.metaObject(),
this->visual.metaObject()};
for (auto &obj : objs) { for (auto &obj : objs) {
for (auto i = obj->methodOffset(); i < obj->methodCount(); ++i) { for (auto i = obj->methodOffset(); i < obj->methodCount(); ++i) {
if (obj->method(i).methodType() == QMetaMethod::Signal) { if (obj->method(i).methodType() == QMetaMethod::Signal) {
@ -423,38 +420,6 @@ void WingAngelAPI::installHexBaseType(asIScriptEngine *engine) {
asCALL_THISCALL); asCALL_THISCALL);
Q_ASSERT(r >= 0); Q_ASSERT(r >= 0);
// HexMetadataAbsoluteItem
r = engine->RegisterObjectType(
"HexMetadataAbsoluteItem", sizeof(WingHex::HexMetadataAbsoluteItem),
asOBJ_VALUE | asOBJ_POD |
asGetTypeTraits<WingHex::HexMetadataAbsoluteItem>());
Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty(
"HexMetadataAbsoluteItem", QSIZETYPE_WRAP("begin"),
asOFFSET(WingHex::HexMetadataAbsoluteItem, begin));
Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty(
"HexMetadataAbsoluteItem", QSIZETYPE_WRAP("end"),
asOFFSET(WingHex::HexMetadataAbsoluteItem, end));
Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty(
"HexMetadataAbsoluteItem", "color foreground",
asOFFSET(WingHex::HexMetadataAbsoluteItem, foreground));
Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty(
"HexMetadataAbsoluteItem", "color background",
asOFFSET(WingHex::HexMetadataAbsoluteItem, background));
Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty(
"HexMetadataAbsoluteItem", "string comment",
asOFFSET(WingHex::HexMetadataAbsoluteItem, comment));
Q_ASSERT(r >= 0);
// HexMetadataItem // HexMetadataItem
r = engine->RegisterObjectType( r = engine->RegisterObjectType(
"HexMetadataItem", sizeof(WingHex::HexMetadataItem), "HexMetadataItem", sizeof(WingHex::HexMetadataItem),
@ -462,18 +427,12 @@ void WingAngelAPI::installHexBaseType(asIScriptEngine *engine) {
Q_ASSERT(r >= 0); Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty( r = engine->RegisterObjectProperty(
"HexMetadataItem", QSIZETYPE_WRAP("line"), "HexMetadataItem", QSIZETYPE_WRAP("begin"),
asOFFSET(WingHex::HexMetadataItem, line)); asOFFSET(WingHex::HexMetadataItem, begin));
Q_ASSERT(r >= 0); Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty( r = engine->RegisterObjectProperty("HexMetadataItem", QSIZETYPE_WRAP("end"),
"HexMetadataItem", "int start", asOFFSET(WingHex::HexMetadataItem, end));
asOFFSET(WingHex::HexMetadataItem, start));
Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty(
"HexMetadataItem", "int length",
asOFFSET(WingHex::HexMetadataItem, length));
Q_ASSERT(r >= 0); Q_ASSERT(r >= 0);
r = engine->RegisterObjectProperty( r = engine->RegisterObjectProperty(
@ -690,13 +649,7 @@ void WingAngelAPI::installHexReaderAPI(asIScriptEngine *engine) {
engine, engine,
std::bind(&WingAngelAPI::_HexReader_getMetadatas, this, std::bind(&WingAngelAPI::_HexReader_getMetadatas, this,
std::placeholders::_1), std::placeholders::_1),
"array<HexMetadataAbsoluteItem>@ getMetadatas(" QSIZETYPE ")"); "array<HexMetadataItem>@ getMetadatas(" QSIZETYPE ")");
registerAPI<CScriptArray *(qsizetype)>(
engine,
std::bind(&WingAngelAPI::_HexReader_getMetaLine, this,
std::placeholders::_1),
"array<HexMetadataItem>@ getMetaLine(" QSIZETYPE ")");
registerAPI<bool(qsizetype)>( registerAPI<bool(qsizetype)>(
engine, engine,
@ -805,11 +758,11 @@ void WingAngelAPI::installHexControllerAPI(asIScriptEngine *engine) {
std::placeholders::_2, std::placeholders::_3), std::placeholders::_2, std::placeholders::_3),
"bool insert(" QSIZETYPE ", ? &out)"); "bool insert(" QSIZETYPE ", ? &out)");
registerAPI<bool(qsizetype, void *, int)>( registerAPI<bool(void *, int)>(engine,
engine, std::bind(&WingAngelAPI::_HexReader_append,
std::bind(&WingAngelAPI::_HexReader_append, this, std::placeholders::_1, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3), std::placeholders::_2),
"bool append(" QSIZETYPE ", ? &out)"); "bool append(? &out)");
registerAPI<bool()>(engine, registerAPI<bool()>(engine,
std::bind(&WingHex::WingPlugin::Controller::undo, ctl), std::bind(&WingHex::WingPlugin::Controller::undo, ctl),
@ -1024,18 +977,6 @@ void WingAngelAPI::installHexControllerAPI(asIScriptEngine *engine) {
"bool metadata(" QSIZETYPE ", " QSIZETYPE "bool metadata(" QSIZETYPE ", " QSIZETYPE
", color &in, color &in, string &in)"); ", color &in, color &in, string &in)");
registerAPI<bool(qsizetype, qsizetype, qsizetype, const QColor &,
const QColor &, const QString &)>(
engine,
std::bind(QOverload<qsizetype, qsizetype, qsizetype, const QColor &,
const QColor &, const QString &>::
of(&WingHex::WingPlugin::Controller::metadata),
ctl, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4,
std::placeholders::_5, std::placeholders::_6),
"bool metadata(" QSIZETYPE ", " QSIZETYPE ", " QSIZETYPE
", color &in, color &in, string &in)");
registerAPI<bool(qsizetype)>( registerAPI<bool(qsizetype)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::removeMetadata, ctl, std::bind(&WingHex::WingPlugin::Controller::removeMetadata, ctl,
@ -1046,29 +987,26 @@ void WingAngelAPI::installHexControllerAPI(asIScriptEngine *engine) {
engine, std::bind(&WingHex::WingPlugin::Controller::clearMetadata, ctl), engine, std::bind(&WingHex::WingPlugin::Controller::clearMetadata, ctl),
"bool clearMetadata()"); "bool clearMetadata()");
registerAPI<bool(qsizetype, qsizetype, qsizetype, const QColor &)>( registerAPI<bool(qsizetype, qsizetype, const QColor &)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::foreground, ctl, std::bind(&WingHex::WingPlugin::Controller::foreground, ctl,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4), std::placeholders::_3),
"bool foreground(" QSIZETYPE ", " QSIZETYPE ", " QSIZETYPE "bool foreground(" QSIZETYPE ", " QSIZETYPE ", color &in)");
", color &in)");
registerAPI<bool(qsizetype, qsizetype, qsizetype, const QColor &)>( registerAPI<bool(qsizetype, qsizetype, const QColor &)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::background, ctl, std::bind(&WingHex::WingPlugin::Controller::background, ctl,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4), std::placeholders::_3),
"bool background(" QSIZETYPE ", " QSIZETYPE ", " QSIZETYPE "bool background(" QSIZETYPE ", " QSIZETYPE ", color &in)");
", color &in)");
registerAPI<bool(qsizetype, qsizetype, qsizetype, const QString &)>( registerAPI<bool(qsizetype, qsizetype, const QString &)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::comment, ctl, std::bind(&WingHex::WingPlugin::Controller::comment, ctl,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4), std::placeholders::_3),
"bool comment(" QSIZETYPE ", " QSIZETYPE ", " QSIZETYPE "bool comment(" QSIZETYPE ", " QSIZETYPE ", string &in)");
", string &in)");
registerAPI<bool(bool)>( registerAPI<bool(bool)>(
engine, engine,
@ -1118,31 +1056,31 @@ void WingAngelAPI::installHexControllerAPI(asIScriptEngine *engine) {
std::placeholders::_1), std::placeholders::_1),
"ErrFile openDriver(string &in)"); "ErrFile openDriver(string &in)");
registerAPI<WingHex::ErrFile(const QString &, bool)>( registerAPI<WingHex::ErrFile(int, bool)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::closeFile, ctl, std::bind(&WingHex::WingPlugin::Controller::closeFile, ctl,
std::placeholders::_1, std::placeholders::_2), std::placeholders::_1, std::placeholders::_2),
"ErrFile closeFile(string &in, bool = false)"); "ErrFile closeFile(int, bool = false)");
registerAPI<WingHex::ErrFile(const QString &, bool)>( registerAPI<WingHex::ErrFile(int, bool)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::saveFile, ctl, std::bind(&WingHex::WingPlugin::Controller::saveFile, ctl,
std::placeholders::_1, std::placeholders::_2), std::placeholders::_1, std::placeholders::_2),
"ErrFile saveFile(string &in, bool = false)"); "ErrFile saveFile(int, bool = false)");
registerAPI<WingHex::ErrFile(const QString &, const QString &, bool)>( registerAPI<WingHex::ErrFile(int, const QString &, bool)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::exportFile, ctl, std::bind(&WingHex::WingPlugin::Controller::exportFile, ctl,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3), std::placeholders::_3),
"ErrFile exportFile(string &in, string &in, bool = false)"); "ErrFile exportFile(int, string &in, bool = false)");
registerAPI<WingHex::ErrFile(const QString &, const QString &, bool)>( registerAPI<WingHex::ErrFile(int, const QString &, bool)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::saveAsFile, ctl, std::bind(&WingHex::WingPlugin::Controller::saveAsFile, ctl,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3), std::placeholders::_3),
"ErrFile saveasFile(string &in, string &in, bool = false)"); "ErrFile saveasFile(int, string &in, bool = false)");
registerAPI<WingHex::ErrFile(bool)>( registerAPI<WingHex::ErrFile(bool)>(
engine, engine,
@ -1215,11 +1153,11 @@ void WingAngelAPI::installHexControllerAPI(asIScriptEngine *engine) {
engine, std::bind(&WingHex::WingPlugin::Controller::clearBookMark, ctl), engine, std::bind(&WingHex::WingPlugin::Controller::clearBookMark, ctl),
"bool clearBookMark()"); "bool clearBookMark()");
registerAPI<bool(const QString &)>( registerAPI<WingHex::ErrFile(const QString &)>(
engine, engine,
std::bind(&WingHex::WingPlugin::Controller::openWorkSpace, ctl, std::bind(&WingHex::WingPlugin::Controller::openWorkSpace, ctl,
std::placeholders::_1), std::placeholders::_1),
"bool openWorkSpace(string &in)"); "ErrFile openWorkSpace(string &in)");
registerAPI<bool(const QString &)>( registerAPI<bool(const QString &)>(
engine, engine,
@ -1625,7 +1563,7 @@ bool WingAngelAPI::_HexReader_insert(qsizetype offset, void *ref, int typeId) {
} }
} }
bool WingAngelAPI::_HexReader_append(qsizetype offset, void *ref, int typeId) { bool WingAngelAPI::_HexReader_append(void *ref, int typeId) {
asIScriptContext *ctx = asGetActiveContext(); asIScriptContext *ctx = asGetActiveContext();
if (ctx) { if (ctx) {
asIScriptEngine *engine = ctx->GetEngine(); asIScriptEngine *engine = ctx->GetEngine();
@ -1764,17 +1702,9 @@ CScriptArray *WingAngelAPI::_HexReader_findAllBytes(qsizetype begin,
CScriptArray *WingAngelAPI::_HexReader_getMetadatas(qsizetype offset) { CScriptArray *WingAngelAPI::_HexReader_getMetadatas(qsizetype offset) {
return retarrayWrapperFunction( return retarrayWrapperFunction(
[this, offset]() -> QList<WingHex::HexMetadataAbsoluteItem> { [this, offset]() -> QList<WingHex::HexMetadataItem> {
return emit reader.getMetadatas(offset); return emit reader.getMetadatas(offset);
}, },
"array<HexMetadataAbsoluteItem>");
}
CScriptArray *WingAngelAPI::_HexReader_getMetaLine(qsizetype line) {
return retarrayWrapperFunction(
[this, line]() -> WingHex::HexLineMetadata {
return emit reader.getMetaLine(line);
},
"array<HexMetadataItem>"); "array<HexMetadataItem>");
} }

View File

@ -104,7 +104,7 @@ private:
bool _HexReader_insert(qsizetype offset, void *ref, int typeId); bool _HexReader_insert(qsizetype offset, void *ref, int typeId);
bool _HexReader_append(qsizetype offset, void *ref, int typeId); bool _HexReader_append(void *ref, int typeId);
qsizetype _HexReader_searchForward(qsizetype begin, const CScriptArray &ba); qsizetype _HexReader_searchForward(qsizetype begin, const CScriptArray &ba);
@ -116,8 +116,6 @@ private:
CScriptArray *_HexReader_getMetadatas(qsizetype offset); CScriptArray *_HexReader_getMetadatas(qsizetype offset);
CScriptArray *_HexReader_getMetaLine(qsizetype line);
CScriptArray *_HexReader_getsBookmarkPos(qsizetype line); CScriptArray *_HexReader_getsBookmarkPos(qsizetype line);
CScriptArray *_HexReader_getBookMarks(); CScriptArray *_HexReader_getBookMarks();

View File

@ -23,9 +23,9 @@
WorkSpaceManager::WorkSpaceManager() {} WorkSpaceManager::WorkSpaceManager() {}
bool WorkSpaceManager::loadWorkSpace(QString filename, QString &file, bool WorkSpaceManager::loadWorkSpace(const QString &filename, QString &file,
QList<BookMarkStruct> &bookmarks, QMap<qsizetype, QString> &bookmarks,
QList<QHexMetadataAbsoluteItem> &metas, QVector<QHexMetadataItem> &metas,
WorkSpaceInfo &infos) { WorkSpaceInfo &infos) {
bool b = false; bool b = false;
QFile f(filename); QFile f(filename);
@ -98,7 +98,7 @@ bool WorkSpaceManager::loadWorkSpace(QString filename, QString &file,
auto fcolor = QColor::fromRgba(nf); auto fcolor = QColor::fromRgba(nf);
auto bcolor = QColor::fromRgba(nb); auto bcolor = QColor::fromRgba(nb);
QHexMetadataAbsoluteItem metaitem; QHexMetadataItem metaitem;
metaitem.begin = nbegin; metaitem.begin = nbegin;
metaitem.end = nend; metaitem.end = nend;
metaitem.comment = comment.toString(); metaitem.comment = comment.toString();
@ -114,7 +114,8 @@ bool WorkSpaceManager::loadWorkSpace(QString filename, QString &file,
} }
values = jobj.value("bookmarks"); values = jobj.value("bookmarks");
if (!values.isUndefined() && values.isArray()) { if (!values.isUndefined() && values.isArray()) {
for (auto item : values.toArray()) { auto array = values.toArray();
for (auto item : array) {
if (!item.isUndefined() && item.isObject()) { if (!item.isUndefined() && item.isObject()) {
auto sitem = item.toObject(); auto sitem = item.toObject();
auto pos = sitem.value("pos"); auto pos = sitem.value("pos");
@ -127,10 +128,8 @@ bool WorkSpaceManager::loadWorkSpace(QString filename, QString &file,
pos.toString().toLongLong(&b); pos.toString().toLongLong(&b);
if (!b || ipos < 0 || ipos >= maxbytes) if (!b || ipos < 0 || ipos >= maxbytes)
continue; continue;
BookMarkStruct book; bookmarks.insert(ipos,
book.pos = ipos; comment.toString());
book.comment = comment.toString();
bookmarks.append(book);
} }
} }
} }
@ -138,7 +137,8 @@ bool WorkSpaceManager::loadWorkSpace(QString filename, QString &file,
values = jobj.value("plugindata"); values = jobj.value("plugindata");
if (!values.isUndefined() && values.isArray()) { if (!values.isUndefined() && values.isArray()) {
for (auto item : values.toArray()) { auto array = values.toArray();
for (auto item : array) {
if (!item.isUndefined() && item.isObject()) { if (!item.isUndefined() && item.isObject()) {
auto sitem = item.toObject(); auto sitem = item.toObject();
auto plgobj = sitem.value("key"); auto plgobj = sitem.value("key");
@ -168,28 +168,29 @@ bool WorkSpaceManager::loadWorkSpace(QString filename, QString &file,
return false; return false;
} }
bool WorkSpaceManager::saveWorkSpace(QString filename, QString file, bool WorkSpaceManager::saveWorkSpace(
QList<BookMarkStruct> bookmarklist, const QString &filename, const QString &file,
QList<QHexMetadataAbsoluteItem> metalist, const QMap<qsizetype, QString> &bookmarklist,
WorkSpaceInfo infos) { const QVector<QHexMetadataItem> &metalist, const WorkSpaceInfo &infos) {
QFile f(filename); QFile f(filename);
if (f.open(QFile::WriteOnly)) { if (f.open(QFile::WriteOnly)) {
QJsonObject jobj; QJsonObject jobj;
jobj.insert("type", "workspace"); jobj.insert("type", "workspace");
QString ff = file;
QFileInfo fileInfo(file); QFileInfo fileInfo(file);
if (fileInfo.isAbsolute()) { if (fileInfo.isAbsolute()) {
QDir dir(QFileInfo(f).absoluteDir()); QDir dir(QFileInfo(f).absoluteDir());
QFileInfo fi(file); QFileInfo fi(file);
file = dir.relativeFilePath(fi.absoluteFilePath()); ff = dir.relativeFilePath(fi.absoluteFilePath());
} }
jobj.insert("file", file); jobj.insert("file", ff);
jobj.insert("encoding", infos.encoding); jobj.insert("encoding", infos.encoding);
jobj.insert("base", QString::number(infos.base)); jobj.insert("base", QString::number(infos.base));
QJsonArray metas; QJsonArray metas;
for (auto meta : metalist) { for (auto &meta : metalist) {
QJsonObject obj; QJsonObject obj;
obj.insert("begin", QString::number(meta.begin)); obj.insert("begin", QString::number(meta.begin));
obj.insert("end", QString::number(meta.end)); obj.insert("end", QString::number(meta.end));
@ -201,12 +202,13 @@ bool WorkSpaceManager::saveWorkSpace(QString filename, QString file,
jobj.insert("metas", metas); jobj.insert("metas", metas);
QJsonArray bookmarks; QJsonArray bookmarks;
for (auto item : bookmarklist) { for (auto p = bookmarklist.cbegin(); p != bookmarklist.cend(); ++p) {
QJsonObject i; QJsonObject i;
i.insert("pos", QString::number(item.pos)); i.insert("pos", QString::number(p.key()));
i.insert("comment", item.comment); i.insert("comment", p.value());
bookmarks.append(i); bookmarks.append(i);
} }
jobj.insert("bookmarks", bookmarks); jobj.insert("bookmarks", bookmarks);
// plugin data // plugin data

View File

@ -18,17 +18,17 @@
#ifndef WORKSPACEMANAGER_H #ifndef WORKSPACEMANAGER_H
#define WORKSPACEMANAGER_H #define WORKSPACEMANAGER_H
#include "../../QHexView/document/qhexdocument.h" #include "QHexView/document/qhexmetadata.h"
#include "../../QHexView/document/qhexmetadata.h"
#include <QHash> #include <QHash>
#include <QJsonArray> #include <QJsonArray>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QJsonValue> #include <QJsonValue>
#include <QList> #include <QMap>
#include <QObject> #include <QObject>
#include <QStringList> #include <QStringList>
#include <QVector>
struct WorkSpaceInfo { struct WorkSpaceInfo {
QString encoding = QStringLiteral("ASCII"); QString encoding = QStringLiteral("ASCII");
@ -40,13 +40,13 @@ class WorkSpaceManager {
public: public:
explicit WorkSpaceManager(); explicit WorkSpaceManager();
bool static saveWorkSpace(QString filename, QString file, bool static saveWorkSpace(const QString &filename, const QString &file,
QList<BookMarkStruct> bookmarks, const QMap<qsizetype, QString> &bookmarks,
QList<QHexMetadataAbsoluteItem> metas, const QVector<QHexMetadataItem> &metas,
WorkSpaceInfo infos); const WorkSpaceInfo &infos);
bool static loadWorkSpace(QString filename, QString &file, bool static loadWorkSpace(const QString &filename, QString &file,
QList<BookMarkStruct> &bookmarks, QMap<qsizetype, QString> &bookmarks,
QList<QHexMetadataAbsoluteItem> &metas, QVector<QHexMetadataItem> &metas,
WorkSpaceInfo &infos); WorkSpaceInfo &infos);
}; };

View File

@ -293,8 +293,8 @@ ErrFile EditorView::openWorkSpace(const QString &filename,
} }
QString file; QString file;
QList<BookMarkStruct> bookmarks; QMap<qsizetype, QString> bookmarks;
QList<QHexMetadataAbsoluteItem> metas; QVector<QHexMetadataItem> metas;
WorkSpaceInfo infos; WorkSpaceInfo infos;
if (WorkSpaceManager::loadWorkSpace(filename, file, bookmarks, metas, if (WorkSpaceManager::loadWorkSpace(filename, file, bookmarks, metas,
@ -407,11 +407,11 @@ ErrFile EditorView::openDriver(const QString &driver, const QString &encoding) {
} }
ErrFile EditorView::save(const QString &workSpaceName, const QString &path, ErrFile EditorView::save(const QString &workSpaceName, const QString &path,
bool isExport, SaveWorkSpaceAttr workSpaceAttr, bool ignoreMd5, bool isExport,
bool ignoreMd5) { SaveWorkSpaceAttr workSpaceAttr) {
if (isCloneFile()) { if (isCloneFile()) {
return this->cloneParent()->save(workSpaceName, path, isExport, return this->cloneParent()->save(workSpaceName, path, ignoreMd5,
workSpaceAttr, ignoreMd5); isExport, workSpaceAttr);
} }
auto fileName = path.isEmpty() ? m_fileName : path; auto fileName = path.isEmpty() ? m_fileName : path;
auto doc = m_hex->document(); auto doc = m_hex->document();
@ -447,8 +447,8 @@ ErrFile EditorView::save(const QString &workSpaceName, const QString &path,
infos.base = doc->baseAddress(); infos.base = doc->baseAddress();
auto b = WorkSpaceManager::saveWorkSpace( auto b = WorkSpaceManager::saveWorkSpace(
workSpaceName, m_fileName, doc->getAllBookMarks(), workSpaceName, m_fileName, doc->bookMarks(),
doc->metadata()->getallMetas(), infos); doc->metadata()->getAllMetadata(), infos);
if (!b) if (!b)
return ErrFile::WorkSpaceUnSaved; return ErrFile::WorkSpaceUnSaved;
if (!isExport) { if (!isExport) {
@ -548,7 +548,7 @@ qsizetype EditorView::findAvailCloneIndex() {
bool EditorView::hasMeta() const { bool EditorView::hasMeta() const {
auto doc = m_hex->document(); auto doc = m_hex->document();
return doc->metadata()->hasMetadata() || doc->bookMarksPtr()->size() > 0; return doc->metadata()->hasMetadata() || doc->bookMarksCount() > 0;
} }
void EditorView::applyPluginData(const QHash<QString, QByteArray> &data) { void EditorView::applyPluginData(const QHash<QString, QByteArray> &data) {

View File

@ -108,9 +108,8 @@ public slots:
const QString &encoding = QString()); const QString &encoding = QString());
ErrFile ErrFile
save(const QString &workSpaceName, const QString &path = QString(), save(const QString &workSpaceName, const QString &path = QString(),
bool isExport = false, bool ignoreMd5 = false, bool isExport = false,
SaveWorkSpaceAttr workSpaceAttr = SaveWorkSpaceAttr::AutoWorkSpace, SaveWorkSpaceAttr workSpaceAttr = SaveWorkSpaceAttr::AutoWorkSpace);
bool ignoreMd5 = false);
ErrFile reload(); ErrFile reload();
void setCopyLimit(qsizetype sizeMB); void setCopyLimit(qsizetype sizeMB);

View File

@ -161,8 +161,6 @@ void QCodeCompletionWidget::setCompletions(const QList<QCodeNode *> &nodes) {
pModel->setFocusNodes(nodes); pModel->setFocusNodes(nodes);
} }
void QCodeCompletionWidget::setCursor(const QDocumentCursor &c) { m_begin = c; }
void QCodeCompletionWidget::setTemporaryNodes(const QList<QCodeNode *> &l) { void QCodeCompletionWidget::setTemporaryNodes(const QList<QCodeNode *> &l) {
m_temps = l; m_temps = l;
} }
@ -219,14 +217,6 @@ void QCodeCompletionWidget::complete(const QModelIndex &index) {
if (prefix.length() && txt.startsWith(prefix)) if (prefix.length() && txt.startsWith(prefix))
txt.remove(0, prefix.length()); txt.remove(0, prefix.length());
if (m_begin.isValid() && c > m_begin) {
m_begin.movePosition(c.position() - m_begin.position(),
QDocumentCursor::NextCharacter,
QDocumentCursor::KeepAnchor);
m_begin.removeSelectedText();
m_begin = QDocumentCursor();
}
e->write(txt); e->write(txt);
if (back) { if (back) {
@ -409,8 +399,6 @@ void QCodeCompletionModel::setFilter(QCodeCompletionWidget::Filter filter) {
void QCodeCompletionModel::update() { bUpdate = true; } void QCodeCompletionModel::update() { bUpdate = true; }
void QCodeCompletionModel::forceUpdate() const { void QCodeCompletionModel::forceUpdate() const {
// qDebug("updating model");
m_visibles.clear(); m_visibles.clear();
foreach (QCodeNode *n, m_nodes) { foreach (QCodeNode *n, m_nodes) {
@ -428,10 +416,8 @@ void QCodeCompletionModel::forceUpdate() const {
} }
} }
// qDebug("model updated"); emit const_cast<QCodeCompletionModel *>(this)->layoutChanged();
bUpdate = false; bUpdate = false;
emit const_cast<QCodeCompletionModel *>(this)->changed();
} }
QList<QCodeNode *> QCodeCompletionModel::focusNodes() const { return m_nodes; } QList<QCodeNode *> QCodeCompletionModel::focusNodes() const { return m_nodes; }

View File

@ -76,8 +76,6 @@ public:
QStringList completions() const; QStringList completions() const;
void setCompletions(const QList<QCodeNode *> &nodes); void setCompletions(const QList<QCodeNode *> &nodes);
void setCursor(const QDocumentCursor &c);
void setTemporaryNodes(const QList<QCodeNode *> &l); void setTemporaryNodes(const QList<QCodeNode *> &l);
public slots: public slots:
@ -101,7 +99,6 @@ private:
void adjustGeometry(); void adjustGeometry();
int offset; int offset;
QDocumentCursor m_begin;
QCodeCompletionModel *pModel; QCodeCompletionModel *pModel;
QPointer<QObject> pEditor; QPointer<QObject> pEditor;
QList<QCodeNode *> m_temps; QList<QCodeNode *> m_temps;

View File

@ -53,8 +53,6 @@ public:
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
signals: signals:
void changed();
void prefixChanged(const QString &newPrefix); void prefixChanged(const QString &newPrefix);
void filterChanged(QCodeCompletionWidget::Filter f); void filterChanged(QCodeCompletionWidget::Filter f);

View File

@ -512,7 +512,12 @@ MainWindow::buildUpHexBookMarkDock(ads::CDockManager *dock,
return; return;
} }
hexeditor->renderer()->enableCursor(true); hexeditor->renderer()->enableCursor(true);
hexeditor->gotoBookMark(index.row());
auto model = m_bookmarks->model();
auto offIndex = model->index(index.row(), 0);
auto offset = model->data(offIndex).value<qsizetype>();
hexeditor->cursor()->moveTo(offset);
}); });
m_aDelBookMark = new QAction(ICONRES(QStringLiteral("bookmarkdel")), m_aDelBookMark = new QAction(ICONRES(QStringLiteral("bookmarkdel")),
@ -524,11 +529,14 @@ MainWindow::buildUpHexBookMarkDock(ads::CDockManager *dock,
} }
auto s = m_bookmarks->selectionModel()->selectedRows(); auto s = m_bookmarks->selectionModel()->selectedRows();
auto doc = hexeditor->document(); auto doc = hexeditor->document();
const auto &bms = doc->bookMarks();
auto model = m_bookmarks->model();
QList<qsizetype> pos; QList<qsizetype> pos;
for (auto &item : s) { for (auto &item : s) {
pos.push_back(bms.at(item.row()).pos); auto offIndex = model->index(item.row(), 0);
auto offset = model->data(offIndex).value<qsizetype>();
pos.append(offset);
} }
doc->RemoveBookMarks(pos); doc->RemoveBookMarks(pos);
@ -567,7 +575,12 @@ MainWindow::buildUpHexMetaDataDock(ads::CDockManager *dock,
return; return;
} }
hexeditor->renderer()->enableCursor(true); hexeditor->renderer()->enableCursor(true);
hexeditor->gotoBookMark(index.row());
auto model = m_metadatas->model();
auto offIndex = model->index(index.row(), 0);
auto offset =
model->data(offIndex, Qt::UserRole).value<qsizetype>();
hexeditor->cursor()->moveTo(offset);
}); });
m_aDelMetaData = new QAction(ICONRES(QStringLiteral("metadatadel")), m_aDelMetaData = new QAction(ICONRES(QStringLiteral("metadatadel")),
@ -580,9 +593,9 @@ MainWindow::buildUpHexMetaDataDock(ads::CDockManager *dock,
auto s = m_metadatas->selectionModel()->selectedRows(); auto s = m_metadatas->selectionModel()->selectedRows();
auto doc = hexeditor->document(); auto doc = hexeditor->document();
const auto &mds = doc->metadata()->getallMetasPtr(); const auto &mds = doc->metadata()->getAllMetadata();
QList<QHexMetadataAbsoluteItem> pmetas; QList<QHexMetadataItem> pmetas;
for (auto &item : s) { for (auto &item : s) {
pmetas.push_back(mds.at(item.row())); pmetas.push_back(mds.at(item.row()));
} }
@ -1350,27 +1363,19 @@ void MainWindow::on_save() {
return; return;
} }
auto res = saveEditor(editor, {}, false);
auto isNewFile = editor->isNewFile(); auto isNewFile = editor->isNewFile();
if (isNewFile) { if (isNewFile) {
on_saveas(); on_saveas();
return; return;
} }
if (!writeSafeCheck(false, {})) {
if (WingMessageBox::warning(this, qAppName(), tr("RootSaveWarning"),
QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::No) {
return;
}
}
QString workspace = m_views.value(editor);
if (editor->change2WorkSpace()) {
workspace = editor->fileName() + PROEXT;
}
auto res = editor->save(workspace);
restart: restart:
if (res == ErrFile::IsNewFile) {
on_saveas();
return;
}
if (res == ErrFile::Permission) { if (res == ErrFile::Permission) {
WingMessageBox::critical(this, tr("Error"), tr("FilePermission")); WingMessageBox::critical(this, tr("Error"), tr("FilePermission"));
return; return;
@ -1379,7 +1384,7 @@ restart:
if (WingMessageBox::warning(this, tr("Warn"), tr("SourceChanged"), if (WingMessageBox::warning(this, tr("Warn"), tr("SourceChanged"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::Yes) { QMessageBox::Yes) {
res = editor->save(workspace); res = saveEditor(editor, {}, true);
goto restart; goto restart;
} else { } else {
Toast::toast(this, NAMEICONRES(QStringLiteral("save")), Toast::toast(this, NAMEICONRES(QStringLiteral("save")),
@ -1392,7 +1397,6 @@ restart:
return; return;
} }
m_views[editor] = workspace;
Toast::toast(this, NAMEICONRES(QStringLiteral("save")), Toast::toast(this, NAMEICONRES(QStringLiteral("save")),
tr("SaveSuccessfully")); tr("SaveSuccessfully"));
} }
@ -1409,26 +1413,13 @@ void MainWindow::on_saveas() {
return; return;
m_lastusedpath = QFileInfo(filename).absoluteDir().absolutePath(); m_lastusedpath = QFileInfo(filename).absoluteDir().absolutePath();
if (!writeSafeCheck(true, filename)) { auto res = saveEditor(editor, filename, false);
if (WingMessageBox::warning(this, qAppName(), tr("RootSaveWarning"),
QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::No) {
return;
}
}
QString workspace = m_views.value(editor);
if (editor->change2WorkSpace()) {
workspace = editor->fileName() + PROEXT;
}
auto res = editor->save(workspace, filename);
restart: restart:
switch (res) { switch (res) {
case ErrFile::Success: { case ErrFile::Success: {
Toast::toast(this, NAMEICONRES(QStringLiteral("saveas")), Toast::toast(this, NAMEICONRES(QStringLiteral("saveas")),
tr("SaveSuccessfully")); tr("SaveSuccessfully"));
m_views[editor] = workspace;
break; break;
} }
case ErrFile::WorkSpaceUnSaved: { case ErrFile::WorkSpaceUnSaved: {
@ -1440,7 +1431,7 @@ restart:
if (WingMessageBox::warning(this, tr("Warn"), tr("SourceChanged"), if (WingMessageBox::warning(this, tr("Warn"), tr("SourceChanged"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::Yes) { QMessageBox::Yes) {
res = editor->save(workspace, filename); res = saveEditor(editor, filename, true);
goto restart; goto restart;
} else { } else {
Toast::toast(this, NAMEICONRES(QStringLiteral("save")), Toast::toast(this, NAMEICONRES(QStringLiteral("save")),
@ -1467,12 +1458,7 @@ void MainWindow::on_exportfile() {
return; return;
m_lastusedpath = QFileInfo(filename).absoluteDir().absolutePath(); m_lastusedpath = QFileInfo(filename).absoluteDir().absolutePath();
QString workspace = m_views.value(editor); auto res = saveEditor(editor, filename, false, true);
if (editor->change2WorkSpace()) {
workspace = editor->fileName() + PROEXT;
}
auto res = editor->save(workspace, filename, true);
restart: restart:
switch (res) { switch (res) {
case ErrFile::Success: { case ErrFile::Success: {
@ -1484,7 +1470,7 @@ restart:
if (QMessageBox::warning(this, tr("Warn"), tr("SourceChanged"), if (QMessageBox::warning(this, tr("Warn"), tr("SourceChanged"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::Yes) { QMessageBox::Yes) {
res = editor->save(workspace, filename, true); res = saveEditor(editor, filename, true, true);
goto restart; goto restart;
} else { } else {
Toast::toast(this, NAMEICONRES(QStringLiteral("export")), Toast::toast(this, NAMEICONRES(QStringLiteral("export")),
@ -1791,16 +1777,17 @@ void MainWindow::on_bookmark() {
tr("CheckKeepSize")); tr("CheckKeepSize"));
return; return;
} }
qsizetype index = -1;
if (hexeditor->existBookMarkByIndex(index)) { auto pos = hexeditor->currentOffset();
auto b = doc->bookMarkByIndex(index); if (doc->existBookMark(pos)) {
auto bcomment = doc->bookMark(pos);
bool ok; bool ok;
hexeditor->renderer()->enableCursor(); hexeditor->renderer()->enableCursor();
auto comment = auto comment =
WingInputDialog::getText(this, tr("BookMark"), tr("InputComment"), WingInputDialog::getText(this, tr("BookMark"), tr("InputComment"),
QLineEdit::Normal, b.comment, &ok); QLineEdit::Normal, bcomment, &ok);
if (ok) { if (ok) {
doc->ModBookMark(b.pos, comment); doc->ModBookMark(pos, comment);
} }
} else { } else {
bool ok; bool ok;
@ -1808,7 +1795,6 @@ void MainWindow::on_bookmark() {
WingInputDialog::getText(this, tr("BookMark"), tr("InputComment"), WingInputDialog::getText(this, tr("BookMark"), tr("InputComment"),
QLineEdit::Normal, QString(), &ok); QLineEdit::Normal, QString(), &ok);
if (ok) { if (ok) {
auto pos = hexeditor->currentOffset();
doc->AddBookMark(pos, comment); doc->AddBookMark(pos, comment);
} }
} }
@ -1825,9 +1811,11 @@ void MainWindow::on_bookmarkdel() {
tr("CheckKeepSize")); tr("CheckKeepSize"));
return; return;
} }
qsizetype index = -1;
if (hexeditor->existBookMarkByIndex(index)) { auto pos = hexeditor->currentOffset();
doc->removeBookMarkByIndex(index);
if (doc->bookMarkExists(pos)) {
doc->RemoveBookMark(pos);
} }
} }
@ -1899,7 +1887,7 @@ void MainWindow::on_metadataedit() {
m.setComment(meta.comment); m.setComment(meta.comment);
if (m.exec()) { if (m.exec()) {
auto mi = hexeditor->document()->metadata(); auto mi = hexeditor->document()->metadata();
QHexMetadataAbsoluteItem o; QHexMetadataItem o;
o.begin = begin; o.begin = begin;
o.end = end; o.end = end;
o.foreground = m.foreGroundColor(); o.foreground = m.foreGroundColor();
@ -2098,7 +2086,7 @@ void MainWindow::on_locChanged() {
auto tmp = d->read(off, sizeof(quint64)); auto tmp = d->read(off, sizeof(quint64));
quint64 n = *reinterpret_cast<const quint64 *>(tmp.constData()); quint64 n = *reinterpret_cast<const quint64 *>(tmp.constData());
auto len = tmp.length(); auto len = size_t(tmp.length());
if (len == sizeof(quint64)) { if (len == sizeof(quint64)) {
auto s = processEndian(n); auto s = processEndian(n);
@ -2109,9 +2097,10 @@ void MainWindow::on_locChanged() {
_numsitem->setNumData(NumShowModel::NumTableIndex::Int64, _numsitem->setNumData(NumShowModel::NumTableIndex::Int64,
QString::number(s1)); QString::number(s1));
double s2 = *(double *)(&n); double s2 = *(double *)(&n);
auto s3 = processEndian(s2); // 大小端字节序转换函数 auto s3 = processEndian(s2);
_numsitem->setNumData(NumShowModel::NumTableIndex::Double64, _numsitem->setNumData(NumShowModel::NumTableIndex::Double64,
QString::number(s3)); qIsNaN(s3) ? QStringLiteral("NAN")
: QString::number(s3));
} else { } else {
_numsitem->setNumData(NumShowModel::NumTableIndex::Uint64, QString()); _numsitem->setNumData(NumShowModel::NumTableIndex::Uint64, QString());
_numsitem->setNumData(NumShowModel::NumTableIndex::Int64, QString()); _numsitem->setNumData(NumShowModel::NumTableIndex::Int64, QString());
@ -2129,7 +2118,8 @@ void MainWindow::on_locChanged() {
float s2 = *(float *)(&n); float s2 = *(float *)(&n);
auto s3 = processEndian(s2); auto s3 = processEndian(s2);
_numsitem->setNumData(NumShowModel::NumTableIndex::Float32, _numsitem->setNumData(NumShowModel::NumTableIndex::Float32,
QString::number(s3)); qIsNaN(s3) ? QStringLiteral("NAN")
: QString::number(s3));
} else { } else {
_numsitem->setNumData(NumShowModel::NumTableIndex::Uint32, QString()); _numsitem->setNumData(NumShowModel::NumTableIndex::Uint32, QString());
_numsitem->setNumData(NumShowModel::NumTableIndex::Int32, QString()); _numsitem->setNumData(NumShowModel::NumTableIndex::Int32, QString());
@ -2186,7 +2176,13 @@ void MainWindow::on_locChanged() {
} }
} }
void MainWindow::on_fullScreen() { this->showFullScreen(); } void MainWindow::on_fullScreen() {
if (this->isFullScreen()) {
this->showMaximized();
} else {
this->showFullScreen();
}
}
void MainWindow::on_restoreLayout() { m_dock->restoreState(_defaultLayout); } void MainWindow::on_restoreLayout() { m_dock->restoreState(_defaultLayout); }
@ -2362,7 +2358,7 @@ void MainWindow::connectEditorView(EditorView *editor) {
m.setComment(meta.comment); m.setComment(meta.comment);
if (m.exec()) { if (m.exec()) {
auto mi = hexeditor->document()->metadata(); auto mi = hexeditor->document()->metadata();
QHexMetadataAbsoluteItem o; QHexMetadataItem o;
o.begin = begin; o.begin = begin;
o.end = end; o.end = end;
o.foreground = m.foreGroundColor(); o.foreground = m.foreGroundColor();
@ -2394,41 +2390,16 @@ void MainWindow::connectEditorView(EditorView *editor) {
Q_ASSERT(editor); Q_ASSERT(editor);
Q_ASSERT(m_views.contains(editor)); Q_ASSERT(m_views.contains(editor));
if (!editor->isCloneFile()) { if (closeEditor(editor, m_isOnClosing) == ErrFile::UnSaved) {
auto hexeditor = editor->hexEditor(); auto ret = this->saveRequest();
if (!hexeditor->isSaved()) { if (ret == QMessageBox::Cancel) {
auto ret = return;
m_isOnClosing ? QMessageBox::Yes : this->saveRequest(); } else if (ret == QMessageBox::Yes) {
if (ret == QMessageBox::Cancel) { if (saveEditor(editor, {}, false) == ErrFile::Success) {
return; closeEditor(editor, m_isOnClosing);
} else if (ret == QMessageBox::Yes) {
this->on_save();
if (!hexeditor->isSaved()) {
return;
}
}
}
}
m_views.remove(editor);
if (currentEditor() == editor) {
_editorLock.lockForWrite();
m_curEditor = nullptr;
_editorLock.unlock();
}
PluginSystem::instance().cleanUpEditorViewHandle(editor);
editor->deleteDockWidget();
m_toolBtneditors.value(ToolButtonIndex::EDITOR_VIEWS)
->setEnabled(m_views.size() != 0);
if (m_dock->focusedDockWidget() == editor) {
if (!m_views.isEmpty()) {
for (auto p = m_views.keyBegin(); p != m_views.keyEnd(); ++p) {
auto ev = *p;
if (ev != editor && ev->isCurrentTab()) {
ev->setFocus();
}
} }
} else {
closeEditor(editor, true);
} }
} }
}); });
@ -2668,6 +2639,70 @@ ErrFile MainWindow::openRegionFile(QString file, EditorView **editor,
return ErrFile::Success; return ErrFile::Success;
} }
ErrFile MainWindow::saveEditor(EditorView *editor, const QString &filename,
bool ignoreMd5, bool isExport) {
if (editor == nullptr) {
return ErrFile::Error;
}
auto isNewFile = editor->isNewFile();
if (isNewFile && filename.isEmpty()) {
return ErrFile::IsNewFile;
}
if (!writeSafeCheck(false, {})) {
return ErrFile::Permission;
}
QString workspace = m_views.value(editor);
if (editor->change2WorkSpace()) {
workspace = editor->fileName() + PROEXT;
}
auto ret = editor->save(workspace, filename, ignoreMd5, isExport);
if (ret == ErrFile::Success) {
m_views[editor] = workspace;
}
return ret;
}
ErrFile MainWindow::closeEditor(EditorView *editor, bool force) {
if (editor == nullptr) {
return ErrFile::Error;
}
if (!editor->isCloneFile()) {
auto hexeditor = editor->hexEditor();
if (!force) {
if (!hexeditor->isSaved()) {
return ErrFile::UnSaved;
}
}
}
m_views.remove(editor);
if (currentEditor() == editor) {
_editorLock.lockForWrite();
m_curEditor = nullptr;
_editorLock.unlock();
}
PluginSystem::instance().cleanUpEditorViewHandle(editor);
editor->deleteDockWidget();
m_toolBtneditors.value(ToolButtonIndex::EDITOR_VIEWS)
->setEnabled(m_views.size() != 0);
if (m_dock->focusedDockWidget() == editor) {
if (!m_views.isEmpty()) {
for (auto p = m_views.keyBegin(); p != m_views.keyEnd(); ++p) {
auto ev = *p;
if (ev != editor && ev->isCurrentTab()) {
ev->setFocus();
}
}
}
}
return ErrFile::Success;
}
void MainWindow::updateEditModeEnabled() { void MainWindow::updateEditModeEnabled() {
auto editor = currentEditor(); auto editor = currentEditor();
auto b = (editor != nullptr); auto b = (editor != nullptr);

View File

@ -203,6 +203,10 @@ public:
ErrFile openRegionFile(QString file, EditorView **editor, qsizetype start, ErrFile openRegionFile(QString file, EditorView **editor, qsizetype start,
qsizetype length); qsizetype length);
ErrFile saveEditor(EditorView *editor, const QString &filename,
bool ignoreMd5, bool isExport = false);
ErrFile closeEditor(EditorView *editor, bool force);
private: private:
QString saveLog(); QString saveLog();

View File

@ -115,6 +115,7 @@ ScriptingDialog::ScriptingDialog(QWidget *parent)
// load saved docking layout // load saved docking layout
auto &set = SettingManager::instance(); auto &set = SettingManager::instance();
m_dock->restoreState(set.scriptDockLayout()); m_dock->restoreState(set.scriptDockLayout());
_savedLayout = set.scriptDockLayout();
this->setUpdatesEnabled(true); this->setUpdatesEnabled(true);
} }

View File

@ -21,22 +21,26 @@ BookMarksModel::BookMarksModel(QHexDocument *doc, QObject *parent)
: QAbstractTableModel(parent), _doc(doc) {} : QAbstractTableModel(parent), _doc(doc) {}
int BookMarksModel::rowCount(const QModelIndex &parent) const { int BookMarksModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return _doc ? _doc->bookMarksCount() : 0; return _doc ? _doc->bookMarksCount() : 0;
} }
int BookMarksModel::columnCount(const QModelIndex &parent) const { return 2; } int BookMarksModel::columnCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return 2;
}
QVariant BookMarksModel::data(const QModelIndex &index, int role) const { QVariant BookMarksModel::data(const QModelIndex &index, int role) const {
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
case Qt::ToolTipRole: { case Qt::ToolTipRole: {
auto r = index.row(); auto r = index.row();
auto b = _doc->bookMarkByIndex(r); auto offset = _doc->bookMarkPos(r);
switch (index.column()) { switch (index.column()) {
case 0: // offset case 0: // offset
return b.pos; return offset;
case 1: // comment case 1: // comment
return b.comment; return _doc->bookMark(offset);
} }
} }
case Qt::TextAlignmentRole: case Qt::TextAlignmentRole:

View File

@ -21,16 +21,20 @@ MetaDataModel::MetaDataModel(QHexDocument *doc, QObject *parent)
: QAbstractTableModel(parent), _doc(doc) {} : QAbstractTableModel(parent), _doc(doc) {}
int MetaDataModel::rowCount(const QModelIndex &parent) const { int MetaDataModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return _doc ? _doc->metadata()->size() : 0; return _doc ? _doc->metadata()->size() : 0;
} }
int MetaDataModel::columnCount(const QModelIndex &parent) const { return 5; } int MetaDataModel::columnCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return 5;
}
QVariant MetaDataModel::data(const QModelIndex &index, int role) const { QVariant MetaDataModel::data(const QModelIndex &index, int role) const {
switch (role) { switch (role) {
case Qt::DisplayRole: { case Qt::DisplayRole: {
auto r = index.row(); auto r = index.row();
const auto &b = _doc->metadata()->getallMetasPtr(); const auto &b = _doc->metadata()->getAllMetadata();
auto d = b.at(r); auto d = b.at(r);
switch (index.column()) { switch (index.column()) {
case 0: // begin case 0: // begin
@ -58,7 +62,7 @@ QVariant MetaDataModel::data(const QModelIndex &index, int role) const {
} }
case Qt::ToolTipRole: { case Qt::ToolTipRole: {
auto r = index.row(); auto r = index.row();
const auto &b = _doc->metadata()->getallMetasPtr(); const auto &b = _doc->metadata()->getAllMetadata();
auto d = b.at(r); auto d = b.at(r);
switch (index.column()) { switch (index.column()) {
case 2: { case 2: {
@ -82,7 +86,7 @@ QVariant MetaDataModel::data(const QModelIndex &index, int role) const {
} break; } break;
case Qt::BackgroundRole: { case Qt::BackgroundRole: {
auto r = index.row(); auto r = index.row();
const auto &b = _doc->metadata()->getallMetasPtr(); const auto &b = _doc->metadata()->getAllMetadata();
auto d = b.at(r); auto d = b.at(r);
switch (index.column()) { switch (index.column()) {
case 2: case 2:
@ -95,6 +99,16 @@ QVariant MetaDataModel::data(const QModelIndex &index, int role) const {
} break; } break;
case Qt::TextAlignmentRole: case Qt::TextAlignmentRole:
return int(Qt::AlignCenter); return int(Qt::AlignCenter);
case Qt::UserRole:
auto r = index.row();
const auto &b = _doc->metadata()->getAllMetadata();
auto d = b.at(r);
switch (index.column()) {
case 0: // begin
return d.begin;
case 1: // end
return d.end;
}
} }
return QVariant(); return QVariant();
} }

View File

@ -51,10 +51,12 @@ QVariant QJsonTableModel::headerData(int section, Qt::Orientation orientation,
} }
int QJsonTableModel::rowCount(const QModelIndex &parent) const { int QJsonTableModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return m_json.size(); return m_json.size();
} }
int QJsonTableModel::columnCount(const QModelIndex &parent) const { int QJsonTableModel::columnCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return m_header.size(); return m_header.size();
} }

View File

@ -19,15 +19,15 @@
#define QJSONTABLEMODEL_H #define QJSONTABLEMODEL_H
#include <QAbstractTableModel> #include <QAbstractTableModel>
#include <QHash>
#include <QJsonArray> #include <QJsonArray>
#include <QJsonDocument> #include <QJsonDocument>
#include <QMap>
#include <QObject> #include <QObject>
#include <QVector> #include <QVector>
class QJsonTableModel : public QAbstractTableModel { class QJsonTableModel : public QAbstractTableModel {
public: public:
typedef QMap<QString, QString> Heading; typedef QHash<QString, QString> Heading;
typedef QVector<Heading> Header; typedef QVector<Heading> Header;
QJsonTableModel(const Header &header, QObject *parent = 0); QJsonTableModel(const Header &header, QObject *parent = 0);

View File

@ -112,23 +112,23 @@ struct HexPosition {
} }
}; };
struct HexMetadataAbsoluteItem { struct HexMetadataItem {
qsizetype begin; qsizetype begin;
qsizetype end; qsizetype end;
QColor foreground, background; QColor foreground, background;
QString comment; QString comment;
// added by wingsummer // added by wingsummer
bool operator==(const HexMetadataAbsoluteItem &item) { bool operator==(const HexMetadataItem &item) {
return begin == item.begin && end == item.end && return begin == item.begin && end == item.end &&
foreground == item.foreground && background == item.background && foreground == item.foreground && background == item.background &&
comment == item.comment; comment == item.comment;
} }
HexMetadataAbsoluteItem() = default; HexMetadataItem() = default;
HexMetadataAbsoluteItem(qsizetype begin, qsizetype end, QColor foreground, HexMetadataItem(qsizetype begin, qsizetype end, QColor foreground,
QColor background, QString comment) { QColor background, QString comment) {
this->begin = begin; this->begin = begin;
this->end = end; this->end = end;
this->foreground = foreground; this->foreground = foreground;
@ -137,34 +137,6 @@ struct HexMetadataAbsoluteItem {
} }
}; };
struct HexMetadataItem {
qsizetype line;
int start, length;
QColor foreground, background;
QString comment;
HexMetadataItem() = default;
// added by wingsummer
bool operator==(const HexMetadataItem &item) {
return line == item.line && start == item.start &&
foreground == item.foreground && background == item.background &&
comment == item.comment;
}
HexMetadataItem(qsizetype line, int start, int length, QColor foreground,
QColor background, QString comment) {
this->line = line;
this->start = start;
this->length = length;
this->foreground = foreground;
this->background = background;
this->comment = comment;
}
};
typedef QList<HexMetadataItem> HexLineMetadata;
namespace WingPlugin { namespace WingPlugin {
class Reader : public QObject { class Reader : public QObject {
@ -223,8 +195,7 @@ signals:
// metadata // metadata
bool lineHasMetadata(qsizetype line); bool lineHasMetadata(qsizetype line);
QList<HexMetadataAbsoluteItem> getMetadatas(qsizetype offset); QList<HexMetadataItem> getMetadatas(qsizetype offset);
HexLineMetadata getMetaLine(qsizetype line);
// bookmark // bookmark
bool lineHasBookMark(qsizetype line); bool lineHasBookMark(qsizetype line);
@ -301,36 +272,32 @@ signals:
bool setInsertionMode(bool isinsert); bool setInsertionMode(bool isinsert);
// metadata // metadata
bool foreground(qsizetype begin, qsizetype end, const QColor &fgcolor);
bool background(qsizetype begin, qsizetype end, const QColor &bgcolor);
bool comment(qsizetype begin, qsizetype end, const QString &comment);
bool metadata(qsizetype begin, qsizetype end, const QColor &fgcolor, bool metadata(qsizetype begin, qsizetype end, const QColor &fgcolor,
const QColor &bgcolor, const QString &comment); const QColor &bgcolor, const QString &comment);
bool metadata(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor, const QColor &bgcolor,
const QString &comment);
bool removeMetadata(qsizetype offset); bool removeMetadata(qsizetype offset);
bool clearMetadata(); bool clearMetadata();
bool foreground(qsizetype line, qsizetype start, qsizetype length,
const QColor &fgcolor);
bool background(qsizetype line, qsizetype start, qsizetype length,
const QColor &bgcolor);
bool comment(qsizetype line, qsizetype start, qsizetype length,
const QString &comment);
bool setMetaVisible(bool b); bool setMetaVisible(bool b);
bool setMetafgVisible(bool b); bool setMetafgVisible(bool b);
bool setMetabgVisible(bool b); bool setMetabgVisible(bool b);
bool setMetaCommentVisible(bool b); bool setMetaCommentVisible(bool b);
// mainwindow // mainwindow
bool newFile(); ErrFile newFile();
ErrFile openFile(const QString &filename); ErrFile openFile(const QString &filename);
ErrFile openRegionFile(const QString &filename, qsizetype start = 0, ErrFile openRegionFile(const QString &filename, qsizetype start = 0,
qsizetype length = 1024); qsizetype length = 1024);
ErrFile openDriver(const QString &driver); ErrFile openDriver(const QString &driver);
ErrFile closeFile(const QString &filename, bool force = false); ErrFile closeFile(int handle, bool force = false);
ErrFile saveFile(const QString &filename, bool ignoreMd5 = false); ErrFile saveFile(int handle, bool ignoreMd5 = false);
ErrFile exportFile(const QString &filename, const QString &savename, ErrFile exportFile(int handle, const QString &savename,
bool ignoreMd5 = false); bool ignoreMd5 = false);
bool exportFileGUI(); bool exportFileGUI();
ErrFile saveAsFile(const QString &filename, const QString &savename, ErrFile saveAsFile(int handle, const QString &savename,
bool ignoreMd5 = false); bool ignoreMd5 = false);
bool saveAsFileGUI(); bool saveAsFileGUI();
ErrFile closeCurrentFile(bool force = false); ErrFile closeCurrentFile(bool force = false);
@ -350,7 +317,7 @@ signals:
bool clearBookMark(); bool clearBookMark();
// workspace // workspace
bool openWorkSpace(const QString &filename); ErrFile openWorkSpace(const QString &filename);
bool setCurrentEncoding(const QString &encoding); bool setCurrentEncoding(const QString &encoding);
}; };
@ -524,7 +491,7 @@ public slots:
virtual WingEditorViewWidget *clone() = 0; virtual WingEditorViewWidget *clone() = 0;
signals: signals:
void raise(); void raiseView();
}; };
class IWingPlugin : public QObject { class IWingPlugin : public QObject {

View File

@ -69,6 +69,60 @@ void PluginSystem::loadPlugin(QFileInfo fileinfo) {
WingAngelAPI *PluginSystem::angelApi() const { return _angelplg; } WingAngelAPI *PluginSystem::angelApi() const { return _angelplg; }
EditorView *PluginSystem::getCurrentPluginView(IWingPlugin *plg) {
if (plg == nullptr) {
return nullptr;
}
if (!m_plgviewMap.contains(plg)) {
return nullptr;
}
auto view = m_plgviewMap.value(plg);
if (view == nullptr) {
view = _win->m_curEditor;
}
return view;
}
EditorView *PluginSystem::handle2EditorView(IWingPlugin *plg, int handle) {
if (handle < 0) {
return getCurrentPluginView(plg);
}
auto handles = m_plgHandles.value(plg);
auto r = std::find_if(handles.begin(), handles.end(),
[handle](const QPair<int, EditorView *> &d) {
return d.first == handle;
});
if (r != handles.end()) {
return r->second;
}
return nullptr;
}
PluginSystem::UniqueId
PluginSystem::assginHandleForPluginView(IWingPlugin *plg, EditorView *view) {
if (plg == nullptr || view == nullptr) {
return {};
}
if (m_plgHandles.contains(plg)) {
auto id = m_idGen.get();
m_plgHandles[plg].append(qMakePair(id, view));
m_viewBindings[view].append(plg);
return id;
}
return {};
}
bool PluginSystem::checkPluginCanOpenedFile(IWingPlugin *plg) {
if (plg == nullptr) {
return false;
}
if (m_plgHandles.contains(plg)) {
return m_plgHandles.value(plg).size() <= RAND_MAX;
}
return false;
}
void PluginSystem::cleanUpEditorViewHandle(EditorView *view) { void PluginSystem::cleanUpEditorViewHandle(EditorView *view) {
if (m_viewBindings.contains(view)) { if (m_viewBindings.contains(view)) {
auto v = m_viewBindings.value(view); auto v = m_viewBindings.value(view);
@ -76,11 +130,11 @@ void PluginSystem::cleanUpEditorViewHandle(EditorView *view) {
// clean up // clean up
for (auto &plg : v) { for (auto &plg : v) {
auto handles = m_plgHandles.value(plg); auto handles = m_plgHandles.value(plg);
auto r = std::remove_if(handles.begin(), handles.end(), handles.erase(
[view](const QPair<int, EditorView *> &v) { std::remove_if(handles.begin(), handles.end(),
return v.second == view; [view](const QPair<int, EditorView *> &v) {
}); return v.second == view;
Q_UNUSED(r); }));
} }
m_viewBindings.remove(view); m_viewBindings.remove(view);
@ -567,31 +621,15 @@ void PluginSystem::connectReaderInterface(IWingPlugin *plg) {
} }
return qsizetype(-1); return qsizetype(-1);
}); });
connect(preader, &WingPlugin::Reader::getMetaLine, _win,
[=](qsizetype line) -> HexLineMetadata {
auto e = pluginCurrentEditor(plg);
if (e) {
auto ometas =
e->hexEditor()->document()->metadata()->get(line);
HexLineMetadata metas;
for (auto &item : ometas) {
metas.push_back(HexMetadataItem(
item.line, item.start, item.length, item.foreground,
item.background, item.comment));
}
return metas;
}
return {};
});
connect(preader, &WingPlugin::Reader::getMetadatas, _win, connect(preader, &WingPlugin::Reader::getMetadatas, _win,
[=](qsizetype offset) -> QList<HexMetadataAbsoluteItem> { [=](qsizetype offset) -> QList<HexMetadataItem> {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto ometaline = auto ometaline =
e->hexEditor()->document()->metadata()->gets(offset); e->hexEditor()->document()->metadata()->gets(offset);
QList<HexMetadataAbsoluteItem> metaline; QList<HexMetadataItem> metaline;
for (auto &item : ometaline) { for (auto &item : ometaline) {
metaline.push_back(HexMetadataAbsoluteItem( metaline.push_back(HexMetadataItem(
item.begin, item.end, item.foreground, item.begin, item.end, item.foreground,
item.background, item.comment)); item.background, item.comment));
} }
@ -621,7 +659,8 @@ void PluginSystem::connectReaderInterface(IWingPlugin *plg) {
[=](qsizetype line) -> QList<qsizetype> { [=](qsizetype line) -> QList<qsizetype> {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
return e->hexEditor()->document()->getsBookmarkPos(line); return e->hexEditor()->document()->getLineBookmarksPos(
line);
} }
return {}; return {};
}); });
@ -629,10 +668,10 @@ void PluginSystem::connectReaderInterface(IWingPlugin *plg) {
[=](qsizetype pos) -> BookMark { [=](qsizetype pos) -> BookMark {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto b = e->hexEditor()->document()->bookMark(pos); auto comment = e->hexEditor()->document()->bookMark(pos);
BookMark book; BookMark book;
book.pos = b.pos; book.pos = pos;
book.comment = b.comment; book.comment = comment;
return book; return book;
} }
return {}; return {};
@ -641,7 +680,7 @@ void PluginSystem::connectReaderInterface(IWingPlugin *plg) {
[=](qsizetype pos) -> QString { [=](qsizetype pos) -> QString {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
return e->hexEditor()->document()->bookMarkComment(pos); return e->hexEditor()->document()->bookMark(pos);
} }
return {}; return {};
}); });
@ -649,12 +688,12 @@ void PluginSystem::connectReaderInterface(IWingPlugin *plg) {
[=]() -> QList<BookMark> { [=]() -> QList<BookMark> {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto bs = e->hexEditor()->document()->getAllBookMarks(); auto &bs = e->hexEditor()->document()->bookMarks();
QList<BookMark> bookmarks; QList<BookMark> bookmarks;
for (auto &item : bs) { for (auto p = bs.cbegin(); p != bs.cbegin(); ++p) {
BookMark i; BookMark i;
i.pos = item.pos; i.pos = p.key();
i.comment = item.comment; i.comment = p.value();
bookmarks.push_back(i); bookmarks.push_back(i);
} }
} }
@ -1064,20 +1103,18 @@ void PluginSystem::connectControllerInterface(IWingPlugin *plg) {
return false; return false;
}); });
connect(pctl, connect(pctl,
QOverload<qsizetype, qsizetype, qsizetype, const QColor &, QOverload<qsizetype, qsizetype, const QColor &, const QColor &,
const QColor &,
const QString &>::of(&WingPlugin::Controller::metadata), const QString &>::of(&WingPlugin::Controller::metadata),
_win, _win,
[=](qsizetype line, qsizetype start, qsizetype length, [=](qsizetype begin, qsizetype end, const QColor &fgcolor,
const QColor &fgcolor, const QColor &bgcolor, const QColor &bgcolor, const QString &comment) -> bool {
const QString &comment) -> bool {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto doc = e->hexEditor()->document(); auto doc = e->hexEditor()->document();
if (!doc->isKeepSize()) if (!doc->isKeepSize())
return false; return false;
doc->metadata()->metadata(line, start, length, fgcolor, doc->metadata()->metadata(begin, end, fgcolor, bgcolor,
bgcolor, comment); comment);
return true; return true;
} }
return false; return false;
@ -1104,41 +1141,39 @@ void PluginSystem::connectControllerInterface(IWingPlugin *plg) {
} }
return false; return false;
}); });
connect(pctl, &WingPlugin::Controller::comment, _win, connect(
[=](qsizetype line, qsizetype start, qsizetype length, pctl, &WingPlugin::Controller::comment, _win,
const QString &comment) -> bool { [=](qsizetype begin, qsizetype end, const QString &comment) -> bool {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto doc = e->hexEditor()->document(); auto doc = e->hexEditor()->document();
if (!doc->isKeepSize()) if (!doc->isKeepSize())
return false; return false;
doc->metadata()->comment(line, start, length, comment); doc->metadata()->comment(begin, end, comment);
return true; return true;
} }
return false; return false;
}); });
connect(pctl, &WingPlugin::Controller::foreground, _win, connect(pctl, &WingPlugin::Controller::foreground, _win,
[=](qsizetype line, qsizetype start, qsizetype length, [=](qsizetype begin, qsizetype end, const QColor &fgcolor) -> bool {
const QColor &fgcolor) -> bool {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto doc = e->hexEditor()->document(); auto doc = e->hexEditor()->document();
if (!doc->isKeepSize()) if (!doc->isKeepSize())
return false; return false;
doc->metadata()->foreground(line, start, length, fgcolor); doc->metadata()->foreground(begin, end, fgcolor);
return true; return true;
} }
return false; return false;
}); });
connect(pctl, &WingPlugin::Controller::background, _win, connect(pctl, &WingPlugin::Controller::background, _win,
[=](qsizetype line, qsizetype start, qsizetype length, [=](qsizetype begin, qsizetype end, const QColor &bgcolor) -> bool {
const QColor &bgcolor) -> bool {
auto e = pluginCurrentEditor(plg); auto e = pluginCurrentEditor(plg);
if (e) { if (e) {
auto doc = e->hexEditor()->document(); auto doc = e->hexEditor()->document();
if (!doc->isKeepSize()) if (!doc->isKeepSize())
return false; return false;
doc->metadata()->background(line, start, length, bgcolor); doc->metadata()->background(begin, end, bgcolor);
return true; return true;
} }
return false; return false;
@ -1231,78 +1266,130 @@ void PluginSystem::connectControllerInterface(IWingPlugin *plg) {
}); });
// mainwindow // mainwindow
connect(pctl, &WingPlugin::Controller::newFile, _win, [=]() -> bool { connect(pctl, &WingPlugin::Controller::newFile, _win, [=]() -> ErrFile {
m_plgviewMap[plg] = _win->newfileGUI(); auto view = _win->newfileGUI();
return true; if (view) {
auto id = assginHandleForPluginView(plg, view);
m_plgviewMap[plg] = view;
return ErrFile(int(*id));
} else {
return ErrFile::Error;
}
}); });
connect(pctl, &WingPlugin::Controller::openWorkSpace, _win, connect(pctl, &WingPlugin::Controller::openWorkSpace, _win,
[=](const QString &filename) -> bool { [=](const QString &filename) -> ErrFile {
EditorView *view = nullptr; EditorView *view = nullptr;
auto ret = _win->openWorkSpace(filename, &view); auto ret = _win->openWorkSpace(filename, &view);
m_plgviewMap[plg] = view; if (view) {
return ret == ErrFile::Success; auto id = assginHandleForPluginView(plg, view);
m_plgviewMap[plg] = view;
return ErrFile(int(*id));
} else {
return ret;
}
}); });
connect(pctl, &WingPlugin::Controller::openFile, _win, connect(pctl, &WingPlugin::Controller::openFile, _win,
[=](const QString &filename) -> ErrFile { [=](const QString &filename) -> ErrFile {
EditorView *view = nullptr; EditorView *view = nullptr;
auto ret = _win->openFile(filename, &view); auto ret = _win->openFile(filename, &view);
m_plgviewMap[plg] = view; if (view) {
return ret; auto id = assginHandleForPluginView(plg, view);
m_plgviewMap[plg] = view;
return ErrFile(int(*id));
} else {
return ret;
}
}); });
connect(pctl, &WingPlugin::Controller::openRegionFile, _win, connect(pctl, &WingPlugin::Controller::openRegionFile, _win,
[=](const QString &filename, qsizetype start, [=](const QString &filename, qsizetype start,
qsizetype length) -> ErrFile { qsizetype length) -> ErrFile {
EditorView *view = nullptr; EditorView *view = nullptr;
auto ret = _win->openRegionFile(filename, &view, start, length); auto ret = _win->openRegionFile(filename, &view, start, length);
m_plgviewMap[plg] = view; if (view) {
return ret; auto id = assginHandleForPluginView(plg, view);
m_plgviewMap[plg] = view;
return ErrFile(int(*id));
} else {
return ret;
}
}); });
connect(pctl, &WingPlugin::Controller::openDriver, _win, connect(pctl, &WingPlugin::Controller::openDriver, _win,
[=](const QString &driver) -> ErrFile { [=](const QString &driver) -> ErrFile {
EditorView *view = nullptr; EditorView *view = nullptr;
auto ret = _win->openDriver(driver, &view); auto ret = _win->openDriver(driver, &view);
m_plgviewMap[plg] = view; if (view) {
return ret; auto id = assginHandleForPluginView(plg, view);
m_plgviewMap[plg] = view;
return ErrFile(int(*id));
} else {
return ret;
}
}); });
connect(pctl, &WingPlugin::Controller::closeFile, _win, connect(pctl, &WingPlugin::Controller::closeFile, _win,
[=](const QString &filename, bool force) -> ErrFile { [=](int handle, bool force) -> ErrFile {
// return closeFile(index, force); auto view = handle2EditorView(plg, handle);
return ErrFile::Success; if (view) {
_win->closeEditor(view, force);
return ErrFile::Success;
}
return ErrFile::NotExist;
}); });
connect(pctl, &WingPlugin::Controller::saveFile, _win, connect(pctl, &WingPlugin::Controller::saveFile, _win,
[=](const QString &filename, bool ignoreMd5) -> ErrFile { [=](int handle, bool ignoreMd5) -> ErrFile {
// return save(index, ignoreMd5); auto view = handle2EditorView(plg, handle);
return ErrFile::Success; if (view) {
_win->saveEditor(view, {}, ignoreMd5);
return ErrFile::Success;
}
return ErrFile::NotExist;
}); });
connect(pctl, &WingPlugin::Controller::exportFile, _win, connect(
[=](const QString &filename, const QString &savename, pctl, &WingPlugin::Controller::exportFile, _win,
bool ignoreMd5) -> ErrFile { [=](int handle, const QString &savename, bool ignoreMd5) -> ErrFile {
// return exportFile(filename, index, ignoreMd5); auto view = handle2EditorView(plg, handle);
if (view) {
_win->saveEditor(view, savename, ignoreMd5, true);
return ErrFile::Success; return ErrFile::Success;
}); }
return ErrFile::NotExist;
});
connect(pctl, &WingPlugin::Controller::exportFileGUI, _win, connect(pctl, &WingPlugin::Controller::exportFileGUI, _win,
&MainWindow::on_exportfile); &MainWindow::on_exportfile);
connect(pctl, &WingPlugin::Controller::saveAsFile, _win, connect(
[=](const QString &filename, const QString &savename, pctl, &WingPlugin::Controller::saveAsFile, _win,
bool ignoreMd5) -> ErrFile { [=](int handle, const QString &savename, bool ignoreMd5) -> ErrFile {
// return saveAs(filename, index, ignoreMd5); auto view = handle2EditorView(plg, handle);
if (view) {
_win->saveEditor(view, savename, ignoreMd5);
return ErrFile::Success; return ErrFile::Success;
}); }
return ErrFile::NotExist;
});
connect(pctl, &WingPlugin::Controller::saveAsFileGUI, _win, connect(pctl, &WingPlugin::Controller::saveAsFileGUI, _win,
&MainWindow::on_saveas); &MainWindow::on_saveas);
connect(pctl, &WingPlugin::Controller::closeCurrentFile, _win, connect(pctl, &WingPlugin::Controller::closeCurrentFile, _win,
[=](bool force) -> ErrFile { [=](bool force) -> ErrFile {
// return closeFile(_pcurfile, force); auto view = getCurrentPluginView(plg);
return ErrFile::Success; if (view == nullptr) {
return ErrFile::NotExist;
}
return _win->closeEditor(view, force);
}); });
connect(pctl, &WingPlugin::Controller::saveCurrentFile, _win, connect(pctl, &WingPlugin::Controller::saveCurrentFile, _win,
[=](bool ignoreMd5) -> ErrFile { [=](bool ignoreMd5) -> ErrFile {
// return save(_pcurfile, force); auto view = getCurrentPluginView(plg);
return ErrFile::Success; if (view) {
auto ws = _win->m_views.value(view);
return view->save(
ws, {}, ignoreMd5, false,
EditorView::SaveWorkSpaceAttr::AutoWorkSpace);
}
return ErrFile::Error;
}); });
connect(pctl, &WingPlugin::Controller::openFileGUI, _win, connect(pctl, &WingPlugin::Controller::openFileGUI, _win,
@ -1490,7 +1577,8 @@ void PluginSystem::connectUIInterface(IWingPlugin *plg) {
connect(colordlg, &WingPlugin::ColorDialog::getColor, _win, connect(colordlg, &WingPlugin::ColorDialog::getColor, _win,
[=](const QString &caption, QWidget *parent) -> QColor { [=](const QString &caption, QWidget *parent) -> QColor {
if (checkThreadAff()) { if (checkThreadAff()) {
ColorPickerDialog d; ColorPickerDialog d(parent);
d.setWindowTitle(caption);
if (d.exec()) { if (d.exec()) {
return d.color(); return d.color();
} }
@ -1527,7 +1615,26 @@ void PluginSystem::connectUIInterface(IWingPlugin *plg) {
oldmodel->deleteLater(); oldmodel->deleteLater();
} }
auto model = new QJsonTableModel({}); QJsonTableModel::Header header;
if (headers.size() > headerNames.size()) {
for (auto &name : headers) {
QJsonTableModel::Heading heading;
heading["index"] = name;
heading["title"] = name;
header.append(heading);
}
} else {
auto np = headerNames.cbegin();
for (auto p = headers.cbegin(); p != headers.cend();
++p, ++np) {
QJsonTableModel::Heading heading;
heading["index"] = *p;
heading["title"] = *np;
header.append(heading);
}
}
auto model = new QJsonTableModel(header);
model->setJson(QJsonDocument::fromJson(json.toUtf8())); model->setJson(QJsonDocument::fromJson(json.toUtf8()));
_win->m_infotable->setModel(model); _win->m_infotable->setModel(model);
}); });

View File

@ -38,6 +38,58 @@ class MainWindow;
class PluginSystem : public QObject { class PluginSystem : public QObject {
Q_OBJECT Q_OBJECT
private:
class UniqueIdGenerator {
public:
class UniqueId : public QSharedData {
public:
UniqueId() : _id(-1), _gen(nullptr) {}
UniqueId(UniqueIdGenerator *gen, int id) : _id(id), _gen(gen) {
Q_ASSERT(gen);
Q_ASSERT(id >= 0);
}
~UniqueId() {
if (_gen) {
_gen->release(_id);
}
}
operator int() { return _id; }
private:
int _id;
UniqueIdGenerator *_gen;
};
public:
UniqueIdGenerator() : currentId(0) {}
QExplicitlySharedDataPointer<UniqueId> get() {
if (!releasedIds.isEmpty()) {
int id = releasedIds.dequeue();
return QExplicitlySharedDataPointer<UniqueId>(
new UniqueId(this, id));
} else {
return QExplicitlySharedDataPointer<UniqueId>(
new UniqueId(this, currentId++));
}
}
void release(int id) {
if (id < currentId && !releasedIds.contains(id)) {
releasedIds.enqueue(id);
}
}
private:
int currentId;
QQueue<int> releasedIds;
};
using UniqueId = QExplicitlySharedDataPointer<UniqueIdGenerator::UniqueId>;
public: public:
static PluginSystem &instance(); static PluginSystem &instance();
@ -53,6 +105,14 @@ public:
WingAngelAPI *angelApi() const; WingAngelAPI *angelApi() const;
EditorView *getCurrentPluginView(IWingPlugin *plg);
EditorView *handle2EditorView(IWingPlugin *plg, int handle);
UniqueId assginHandleForPluginView(IWingPlugin *plg, EditorView *view);
bool checkPluginCanOpenedFile(IWingPlugin *plg);
void cleanUpEditorViewHandle(EditorView *view); void cleanUpEditorViewHandle(EditorView *view);
private: private:
@ -136,10 +196,11 @@ private:
QList<IWingPlugin *> loadedplgs; QList<IWingPlugin *> loadedplgs;
QMap<IWingPlugin *, EditorView *> m_plgviewMap; QMap<IWingPlugin *, EditorView *> m_plgviewMap;
QMap<IWingPlugin *, QList<QPair<UniqueId, EditorView *>>> m_plgHandles;
QMap<IWingPlugin *, QList<QPair<int, EditorView *>>> m_plgHandles;
QMap<EditorView *, QList<IWingPlugin *>> m_viewBindings; QMap<EditorView *, QList<IWingPlugin *>> m_viewBindings;
UniqueIdGenerator m_idGen;
WingAngelAPI *_angelplg = nullptr; WingAngelAPI *_angelplg = nullptr;
}; };

View File

@ -202,7 +202,7 @@
<property name="title"> <property name="title">
<string>Load &amp;&amp; Save</string> <string>Load &amp;&amp; Save</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout"> <layout class="QGridLayout" name="gridLayout_1">
<item row="0" column="0"> <item row="0" column="0">
<widget class="QCheckBox" name="chkDetectLE"> <widget class="QCheckBox" name="chkDetectLE">
<property name="text"> <property name="text">

View File

@ -177,7 +177,7 @@ void QFormatConfig::apply() {
ui->m_table->setRowCount(n); ui->m_table->setRowCount(n);
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
QString fid = m_currentScheme->id(i); // QString fid = m_currentScheme->id(i);
QFormat &fmt = m_currentScheme->formatRef(i); QFormat &fmt = m_currentScheme->formatRef(i);
QTableWidgetItem *item; QTableWidgetItem *item;

View File

@ -14,6 +14,7 @@
****************************************************************************/ ****************************************************************************/
#include "qsnippetedit.h" #include "qsnippetedit.h"
#include "ui_qsnippetedit.h"
/*! /*!
\file qsnippetedit.cpp \file qsnippetedit.cpp
@ -33,14 +34,14 @@
*/ */
QSnippetEdit::QSnippetEdit(QWidget *p) QSnippetEdit::QSnippetEdit(QWidget *p)
: QWidget(p), m_editedSnippet(-1), m_manager(0) { : QWidget(p), m_editedSnippet(-1), m_manager(nullptr) {
setupUi(this); ui->setupUi(this);
setEnabled(false); setEnabled(false);
} }
QSnippetEdit::QSnippetEdit(QSnippetManager *mgr, QWidget *p) QSnippetEdit::QSnippetEdit(QSnippetManager *mgr, QWidget *p)
: QWidget(p), m_editedSnippet(-1), m_manager(0) { : QWidget(p), m_editedSnippet(-1), m_manager(nullptr) {
setupUi(this); ui->setupUi(this);
setSnippetManager(mgr); setSnippetManager(mgr);
} }
@ -54,41 +55,35 @@ void QSnippetEdit::setSnippetManager(QSnippetManager *mgr) {
disconnect(m_manager, SIGNAL(snippetRemoved(int)), this, disconnect(m_manager, SIGNAL(snippetRemoved(int)), this,
SLOT(snippetRemoved(int))); SLOT(snippetRemoved(int)));
QListWidgetItem *empty = lwSnippets->takeItem(0); QListWidgetItem *empty = ui->lwSnippets->takeItem(0);
lwSnippets->clear(); ui->lwSnippets->clear();
lwSnippets->addItem(empty); ui->lwSnippets->addItem(empty);
} }
m_manager = mgr; m_manager = mgr;
setEnabled(mgr); setEnabled(mgr);
if (m_manager) { if (m_manager) {
connect(m_manager, SIGNAL(snippetAdded(QSnippet *)), this, connect(m_manager, &QSnippetManager::snippetAdded, this,
SLOT(snippetAdded(QSnippet *))); &QSnippetEdit::snippetAdded);
connect(m_manager, SIGNAL(snippetRemoved(int)), this, connect(m_manager, &QSnippetManager::snippetRemovedByIndex, this,
SLOT(snippetRemoved(int))); &QSnippetEdit::snippetRemoved);
for (int i = 0; i < m_manager->snippetCount(); ++i) { for (int i = 0; i < m_manager->snippetCount(); ++i) {
lwSnippets->addItem(m_manager->snippet(i)->name()); ui->lwSnippets->addItem(m_manager->snippet(i)->name());
} }
} }
lwSnippets->setCurrentItem(0); ui->lwSnippets->setCurrentItem(0);
} }
void QSnippetEdit::snippetRemoved(int i) { delete lwSnippets->takeItem(i + 1); } void QSnippetEdit::snippetRemoved(int i) {
delete ui->lwSnippets->takeItem(i + 1);
}
void QSnippetEdit::snippetAdded(QSnippet *s) { lwSnippets->addItem(s->name()); } void QSnippetEdit::snippetAdded(QSnippet *s) {
ui->lwSnippets->addItem(s->name());
void QSnippetEdit::retranslate() {
QSnippetManager *mgr = snippetManager();
setSnippetManager(0);
lwSnippets->clear();
retranslateUi(this);
setSnippetManager(mgr);
} }
static const QRegularExpression _cxt_splitter("\\s*,\\s*"); static const QRegularExpression _cxt_splitter("\\s*,\\s*");
@ -96,13 +91,13 @@ static const QRegularExpression _cxt_splitter("\\s*,\\s*");
bool QSnippetEdit::maybeSave() { bool QSnippetEdit::maybeSave() {
static const QRegularExpression nonTrivial("\\S"); static const QRegularExpression nonTrivial("\\S");
QString pattern = eSnippet->text(); QString pattern = ui->eSnippet->text();
if (pattern.endsWith('\n')) if (pattern.endsWith('\n'))
pattern.chop(1); pattern.chop(1);
QString name = leSnippetName->text(); // QString name = ui->leSnippetName->text();
QStringList contexts = leSnippetScope->text().split(_cxt_splitter); // QStringList contexts = ui->leSnippetScope->text().split(_cxt_splitter);
bool nonTrivialPattern = pattern.contains(nonTrivial); bool nonTrivialPattern = pattern.contains(nonTrivial);
if (m_editedSnippet >= 0) { if (m_editedSnippet >= 0) {
@ -142,26 +137,26 @@ void QSnippetEdit::on_lwSnippets_currentRowChanged(int idx) {
return; return;
if (maybeSave()) { if (maybeSave()) {
lwSnippets->setCurrentRow(m_editedSnippet); ui->lwSnippets->setCurrentRow(m_editedSnippet);
return; return;
} }
m_editedSnippet = idx - 1; m_editedSnippet = idx - 1;
if (idx <= 0) { if (idx <= 0) {
eSnippet->setText(QString()); ui->eSnippet->setText(QString());
leSnippetName->setText(QString()); ui->leSnippetName->setText(QString());
leSnippetScope->setText(QString()); ui->leSnippetScope->setText(QString());
} else { } else {
QSnippet *snip = m_manager->snippet(m_editedSnippet); QSnippet *snip = m_manager->snippet(m_editedSnippet);
eSnippet->setText(snip->pattern()); ui->eSnippet->setText(snip->pattern());
leSnippetName->setText(snip->name()); ui->leSnippetName->setText(snip->name());
leSnippetScope->setText(snip->contexts().join(",")); ui->leSnippetScope->setText(snip->contexts().join(","));
// eSnippet->highlight(); // ui->eSnippet->highlight();
} }
eSnippet->setFocus(); ui->eSnippet->setFocus();
} }
void QSnippetEdit::on_leSnippetName_editingFinished() { void QSnippetEdit::on_leSnippetName_editingFinished() {
@ -170,9 +165,9 @@ void QSnippetEdit::on_leSnippetName_editingFinished() {
QSnippet *snip = m_manager->snippet(m_editedSnippet); QSnippet *snip = m_manager->snippet(m_editedSnippet);
snip->setName(leSnippetName->text()); snip->setName(ui->leSnippetName->text());
lwSnippets->item(m_editedSnippet + 1)->setText(snip->name()); ui->lwSnippets->item(m_editedSnippet + 1)->setText(snip->name());
} }
void QSnippetEdit::on_leSnippetScope_editingFinished() { void QSnippetEdit::on_leSnippetScope_editingFinished() {
@ -181,13 +176,13 @@ void QSnippetEdit::on_leSnippetScope_editingFinished() {
QSnippet *snip = m_manager->snippet(m_editedSnippet); QSnippet *snip = m_manager->snippet(m_editedSnippet);
snip->setContexts(leSnippetScope->text().split(_cxt_splitter)); snip->setContexts(ui->leSnippetScope->text().split(_cxt_splitter));
} }
void QSnippetEdit::on_tbCreateSnippet_clicked() { void QSnippetEdit::on_tbCreateSnippet_clicked() {
QString name = leSnippetName->text(); QString name = ui->leSnippetName->text();
QString pattern = eSnippet->text(); QString pattern = ui->eSnippet->text();
QStringList contexts = leSnippetScope->text().split(_cxt_splitter); QStringList contexts = ui->leSnippetScope->text().split(_cxt_splitter);
if (pattern.endsWith('\n')) if (pattern.endsWith('\n'))
pattern.chop(1); pattern.chop(1);
@ -207,19 +202,19 @@ void QSnippetEdit::on_tbCreateSnippet_clicked() {
return; return;
} }
eSnippet->setText(QString()); ui->eSnippet->setText(QString());
leSnippetScope->clear(); ui->leSnippetScope->clear();
leSnippetName->clear(); ui->leSnippetName->clear();
QSnippet *snip = m_manager->snippet(m_manager->snippetCount() - 1); QSnippet *snip = m_manager->snippet(m_manager->snippetCount() - 1);
// snip->setName(name); // snip->setName(name);
snip->setContexts(contexts); snip->setContexts(contexts);
lwSnippets->setCurrentRow(0); ui->lwSnippets->setCurrentRow(0);
} }
void QSnippetEdit::on_tbDeleteSnippet_clicked() { void QSnippetEdit::on_tbDeleteSnippet_clicked() {
int row = lwSnippets->currentRow() - 1; int row = ui->lwSnippets->currentRow() - 1;
if (row < 0) { if (row < 0) {
QMessageBox::warning(0, tr("Error"), QMessageBox::warning(0, tr("Error"),
@ -229,5 +224,3 @@ void QSnippetEdit::on_tbDeleteSnippet_clicked() {
m_manager->removeSnippet(row); m_manager->removeSnippet(row);
} }
void QSnippetEdit::on_bMoreSnippets_clicked() {}

View File

@ -23,18 +23,21 @@
\brief Definition of the QSnippetEdit widget \brief Definition of the QSnippetEdit widget
*/ */
#include "ui_snippetedit.h"
#include <QWidget> #include <QWidget>
class QSnippet; class QSnippet;
class QSnippetManager; class QSnippetManager;
class QCE_EXPORT QSnippetEdit : public QWidget, private Ui::SnippetEdit { namespace Ui {
class QSnippetEdit;
}
class QCE_EXPORT QSnippetEdit : public QWidget {
Q_OBJECT Q_OBJECT
public: public:
QSnippetEdit(QWidget *p = 0); QSnippetEdit(QWidget *p = nullptr);
QSnippetEdit(QSnippetManager *mgr, QWidget *p = 0); QSnippetEdit(QSnippetManager *mgr, QWidget *p = nullptr);
QSnippetManager *snippetManager() const; QSnippetManager *snippetManager() const;
@ -43,8 +46,6 @@ public slots:
bool maybeSave(); bool maybeSave();
void retranslate();
private slots: private slots:
void on_lwSnippets_currentRowChanged(int idx); void on_lwSnippets_currentRowChanged(int idx);
@ -53,12 +54,13 @@ private slots:
void on_tbCreateSnippet_clicked(); void on_tbCreateSnippet_clicked();
void on_tbDeleteSnippet_clicked(); void on_tbDeleteSnippet_clicked();
void on_bMoreSnippets_clicked();
void snippetRemoved(int i); void snippetRemoved(int i);
void snippetAdded(QSnippet *s); void snippetAdded(QSnippet *s);
private: private:
Ui::QSnippetEdit *ui;
int m_editedSnippet; int m_editedSnippet;
QSnippetManager *m_manager; QSnippetManager *m_manager;
}; };

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"> <ui version="4.0">
<class>SnippetEdit</class> <class>QSnippetEdit</class>
<widget class="QWidget" name="SnippetEdit"> <widget class="QWidget" name="QSnippetEdit">
<property name="geometry"> <property name="geometry">
<rect> <rect>
<x>0</x> <x>0</x>
@ -14,7 +14,80 @@
<string/> <string/>
</property> </property>
<layout class="QGridLayout" name="gridLayout"> <layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" rowspan="4" colspan="5"> <item row="4" column="0">
<widget class="QToolButton" name="tbCreateSnippet">
<property name="text">
<string>+</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QToolButton" name="tbDeleteSnippet">
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="2" column="4">
<widget class="QLineEdit" name="leSnippetName">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Enter the name of the code snippet, which will also be its full-text trigger, if enabled.</string>
</property>
</widget>
</item>
<item row="1" column="3" colspan="2">
<widget class="QEditor" name="eSnippet">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QLabel" name="label_6">
<property name="text">
<string>Scope(s)</string>
</property>
<property name="buddy">
<cstring>leSnippetScope</cstring>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Edit snippet</string>
</property>
</widget>
</item>
<item row="3" column="4">
<widget class="QLineEdit" name="leSnippetScope">
<property name="toolTip">
<string>Enter a coma-separated list of languages in which the snippet can be used.</string>
</property>
</widget>
</item>
<item row="0" column="0" rowspan="4" colspan="3">
<widget class="QListWidget" name="lwSnippets"> <widget class="QListWidget" name="lwSnippets">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Expanding"> <sizepolicy hsizetype="Maximum" vsizetype="Expanding">
@ -39,82 +112,7 @@
</item> </item>
</widget> </widget>
</item> </item>
<item row="0" column="5"> <item row="4" column="3" colspan="2">
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Edit snippet</string>
</property>
</widget>
</item>
<item row="1" column="5" colspan="2">
<widget class="QEditor" name="eSnippet">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
</widget>
</item>
<item row="2" column="5">
<widget class="QLabel" name="label_5">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Name/trigger</string>
</property>
<property name="buddy">
<cstring>leSnippetName</cstring>
</property>
</widget>
</item>
<item row="2" column="6">
<widget class="QLineEdit" name="leSnippetName">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Enter the name of the code snippet, which will also be its full-text trigger, if enabled.</string>
</property>
</widget>
</item>
<item row="3" column="5">
<widget class="QLabel" name="label_6">
<property name="text">
<string>Scope(s)</string>
</property>
<property name="buddy">
<cstring>leSnippetScope</cstring>
</property>
</widget>
</item>
<item row="3" column="6">
<widget class="QLineEdit" name="leSnippetScope">
<property name="toolTip">
<string>Enter a coma-separated list of languages in which the snippet can be used.</string>
</property>
</widget>
</item>
<item row="4" column="5" colspan="2">
<spacer name="verticalSpacer"> <spacer name="verticalSpacer">
<property name="orientation"> <property name="orientation">
<enum>Qt::Vertical</enum> <enum>Qt::Vertical</enum>
@ -130,40 +128,19 @@
</property> </property>
</spacer> </spacer>
</item> </item>
<item row="4" column="3"> <item row="2" column="3">
<widget class="QPushButton" name="bMoreSnippets"> <widget class="QLabel" name="label_5">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text"> <property name="text">
<string>More</string> <string>Name/trigger</string>
</property> </property>
</widget> <property name="buddy">
</item> <cstring>leSnippetName</cstring>
<item row="4" column="2">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Preferred</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="4" column="1">
<widget class="QToolButton" name="tbDeleteSnippet">
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QToolButton" name="tbCreateSnippet">
<property name="text">
<string>+</string>
</property> </property>
</widget> </widget>
</item> </item>
@ -183,7 +160,6 @@
<tabstop>leSnippetScope</tabstop> <tabstop>leSnippetScope</tabstop>
<tabstop>tbCreateSnippet</tabstop> <tabstop>tbCreateSnippet</tabstop>
<tabstop>tbDeleteSnippet</tabstop> <tabstop>tbDeleteSnippet</tabstop>
<tabstop>bMoreSnippets</tabstop>
</tabstops> </tabstops>
<resources/> <resources/>
<connections/> <connections/>

View File

@ -103,9 +103,9 @@ public:
static CQStringFactory *stringFactory = nullptr; static CQStringFactory *stringFactory = nullptr;
// TODO: Make this public so the application can also use the string // Make this public so the application can also use the string
// factory and share the string constants if so desired, or to // factory and share the string constants if so desired, or to
// monitor the size of the string factory cache. // monitor the size of the string factory cache.
CQStringFactory *GetQStringFactorySingleton() { CQStringFactory *GetQStringFactorySingleton() {
if (stringFactory == nullptr) { if (stringFactory == nullptr) {
// Make sure no other thread is creating the string factory at the same // Make sure no other thread is creating the string factory at the same
@ -551,7 +551,6 @@ void RegisterQString_Native(asIScriptEngine *engine) {
// The string length can be accessed through methods or through virtual // The string length can be accessed through methods or through virtual
// property // property
// TODO: Register as size() for consistency with other types
#if AS_USE_ACCESSORS != 1 #if AS_USE_ACCESSORS != 1
r = engine->RegisterObjectMethod("string", "uint length() const", r = engine->RegisterObjectMethod("string", "uint length() const",
asFUNCTION(StringLength), asFUNCTION(StringLength),

View File

@ -80,7 +80,7 @@
<attribute name="title"> <attribute name="title">
<string>PluginInfo</string> <string>PluginInfo</string>
</attribute> </attribute>
<layout class="QVBoxLayout" name="verticalLayout"> <layout class="QVBoxLayout" name="verticalLayout_1">
<property name="spacing"> <property name="spacing">
<number>5</number> <number>5</number>
</property> </property>