diff --git a/3rdparty/QConsoleWidget/QConsoleIODevice.cpp b/3rdparty/QConsoleWidget/QConsoleIODevice.cpp index a9b4cf5..5fd6358 100644 --- a/3rdparty/QConsoleWidget/QConsoleIODevice.cpp +++ b/3rdparty/QConsoleWidget/QConsoleIODevice.cpp @@ -9,7 +9,7 @@ QConsoleIODevice::QConsoleIODevice(QConsoleWidget *w, QObject *parent) : QIODevice(parent), widget_(w), readpos_(0), writtenSinceLastEmit_(0), readSinceLastEmit_(0) { - setCurrentWriteChannel(QConsoleWidget::StandardOutput); + setCurrentWriteChannel(STDOUT_FILENO); open(QIODevice::ReadWrite | QIODevice::Unbuffered); } @@ -53,10 +53,10 @@ qint64 QConsoleIODevice::readData(char *data, qint64 len) { qint64 QConsoleIODevice::writeData(const char *data, qint64 len) { QByteArray ba(data, (int)len); int ch = currentWriteChannel(); - if (ch == QConsoleWidget::StandardError) - widget_->writeStdErr(ba); - else + if (ch == STDOUT_FILENO) widget_->writeStdOut(ba); + else + widget_->writeStdErr(ba); writtenSinceLastEmit_ += len; if (!signalsBlocked()) { diff --git a/3rdparty/QConsoleWidget/QConsoleIODevice.h b/3rdparty/QConsoleWidget/QConsoleIODevice.h index f2f8c29..1c04880 100644 --- a/3rdparty/QConsoleWidget/QConsoleIODevice.h +++ b/3rdparty/QConsoleWidget/QConsoleIODevice.h @@ -6,6 +6,14 @@ class QConsoleWidget; +#ifndef STDOUT_FILENO +#define STDOUT_FILENO 1 +#endif + +#ifndef STDERR_FILENO +#define STDERR_FILENO 2 +#endif + class QConsoleIODevice : public QIODevice { Q_OBJECT diff --git a/3rdparty/QConsoleWidget/QConsoleWidget.cpp b/3rdparty/QConsoleWidget/QConsoleWidget.cpp index d347db8..f616eb7 100644 --- a/3rdparty/QConsoleWidget/QConsoleWidget.cpp +++ b/3rdparty/QConsoleWidget/QConsoleWidget.cpp @@ -1,12 +1,14 @@ #include "QConsoleWidget.h" -#include "QConsoleIODevice.h" -#include "class/langservice.h" +#include "class/ascompletion.h" +#include "control/qcodecompletionwidget.h" #include "qdocumentline.h" #include "qformatscheme.h" #include "qlanguagefactory.h" #include "utilities.h" +#include "QConsoleIODevice.h" + #include #include #include @@ -19,18 +21,8 @@ #include QConsoleWidget::QConsoleWidget(QWidget *parent) - : QEditor(false, parent), mode_(Output), completer_(nullptr) { + : QEditor(false, parent), mode_(Output) { iodevice_ = new QConsoleIODevice(this, this); - - // QTextCharFormat fmt = currentCharFormat(); - // for (int i = 0; i < nConsoleChannels; i++) - // chanFormat_[i] = fmt; - - chanFormat_[StandardOutput].setForeground(Qt::darkBlue); - chanFormat_[StandardError].setForeground(Qt::red); - - // setTextInteractionFlags(); - setUndoRedoEnabled(false); } @@ -44,7 +36,6 @@ void QConsoleWidget::setMode(ConsoleMode m) { auto cursor = this->cursor(); cursor.movePosition(QDocumentCursor::End); setCursor(cursor); - // setCurrentCharFormat(chanFormat_[StandardInput]); inpos_ = cursor; mode_ = Input; } @@ -88,34 +79,26 @@ void QConsoleWidget::handleReturnKey() { emit consoleCommand(code); } -void QConsoleWidget::setCompleter(QCodeCompletionWidget *c) { - if (completer_) { - // completer_->setWidget(0); - // QObject::disconnect(completer_, SIGNAL(activated(const QString &)), - // this, SLOT(insertCompletion(const QString &))); - } - completer_ = c; - if (completer_) { - // completer_->setWidget(this); - // QObject::connect(completer_, SIGNAL(activated(const QString &)), - // this, - // SLOT(insertCompletion(const QString &))); - } -} - void QConsoleWidget::keyPressEvent(QKeyEvent *e) { - if (completer_ && completer_->isVisible()) { - // The following keys are forwarded by the completer to the widget - switch (e->key()) { - case Qt::Key_Tab: - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_Escape: - case Qt::Key_Backtab: - e->ignore(); - return; // let the completer do default behavior - default: - break; + if (mode() == Input) { + auto ascom = dynamic_cast(completionEngine()); + if (ascom) { + auto cw = ascom->codeCompletionWidget(); + if (cw && cw->isVisible()) { + // The following keys are forwarded by the completer to the + // widget + switch (e->key()) { + case Qt::Key_Tab: + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_Escape: + case Qt::Key_Backtab: + e->ignore(); + return; // let the completer do default behavior + default: + break; + } + } } } @@ -302,7 +285,6 @@ bool QConsoleWidget::canPaste() const { } void QConsoleWidget::replaceCommandLine(const QString &str) { - // Select the text after the last command prompt ... auto textCursor = this->cursor(); auto line = textCursor.line(); @@ -321,25 +303,14 @@ QString QConsoleWidget::getHistoryPath() { return dir.absoluteFilePath(QStringLiteral(".command_history.lst")); } -void QConsoleWidget::write(const QString &message, const QTextCharFormat &fmt) { - // QTextCharFormat currfmt = currentCharFormat(); +void QConsoleWidget::write(const QString &message, const QString &sfmtID) { auto tc = cursor(); + auto ascom = dynamic_cast(completionEngine()); + Q_ASSERT(ascom); + auto cw = ascom->codeCompletionWidget(); - if (mode() == Input) { - // in Input mode output messages are inserted - // before the edit block - - // get offset of current pos from the end - auto editpos = tc; - auto line = editpos.line(); - tc.moveTo(line, 0); - tc.insertLine(); - tc.insertText(message /*, fmt*/); - - setCursor(editpos); - // setCurrentCharFormat(currfmt); - } else { - // in output mode messages are appended + if (mode() == Output || (cw && cw->isCompleting())) { + // in output mode or completion messages are appended auto tc1 = tc; tc1.movePosition(QDocumentCursor::End); @@ -349,21 +320,32 @@ void QConsoleWidget::write(const QString &message, const QTextCharFormat &fmt) { // insert text setCursor(tc1); - tc.insertText(message /*, fmt*/); + tc.insertText(message, false, sfmtID); ensureCursorVisible(); // restore cursor if needed if (needsRestore) setCursor(tc); + } else { + // in Input mode output messages are inserted + // before the edit block + + // get offset of current pos from the end + auto editpos = tc; + auto line = editpos.line(); + tc.moveTo(line, 0); + tc.insertLine(); + tc.insertText(message, false, sfmtID); + setCursor(editpos); } } void QConsoleWidget::writeStdOut(const QString &s) { - write(s, chanFormat_[StandardOutput]); + write(s, QStringLiteral("stdout")); } void QConsoleWidget::writeStdErr(const QString &s) { - write(s, chanFormat_[StandardError]); + write(s, QStringLiteral("stderr")); } /////////////////// QConsoleWidget::History ///////////////////// @@ -454,12 +436,12 @@ QTextStream &inputMode(QTextStream &s) { QTextStream &outChannel(QTextStream &s) { QConsoleIODevice *d = qobject_cast(s.device()); if (d) - d->setCurrentWriteChannel(QConsoleWidget::StandardOutput); + d->setCurrentWriteChannel(STDOUT_FILENO); return s; } QTextStream &errChannel(QTextStream &s) { QConsoleIODevice *d = qobject_cast(s.device()); if (d) - d->setCurrentWriteChannel(QConsoleWidget::StandardError); + d->setCurrentWriteChannel(STDERR_FILENO); return s; } diff --git a/3rdparty/QConsoleWidget/QConsoleWidget.h b/3rdparty/QConsoleWidget/QConsoleWidget.h index d69e6a4..a65535f 100644 --- a/3rdparty/QConsoleWidget/QConsoleWidget.h +++ b/3rdparty/QConsoleWidget/QConsoleWidget.h @@ -5,7 +5,6 @@ #include #include -#include "control/qcodecompletionwidget.h" #include "qeditor.h" #include "qlanguagefactory.h" @@ -18,31 +17,20 @@ public: enum ConsoleMode { Input, Output }; Q_ENUM(ConsoleMode) - enum ConsoleChannel { - StandardInput, - StandardOutput, - StandardError, - nConsoleChannels - }; - Q_ENUM(ConsoleChannel) - explicit QConsoleWidget(QWidget *parent = nullptr); virtual ~QConsoleWidget(); ConsoleMode mode() const { return mode_; } void setMode(ConsoleMode m); QIODevice *device() const { return (QIODevice *)iodevice_; } - QTextCharFormat channelCharFormat(ConsoleChannel ch) const { - return chanFormat_[ch]; - } - void setChannelCharFormat(ConsoleChannel ch, const QTextCharFormat &fmt) { - chanFormat_[ch] = fmt; - } + virtual QSize sizeHint() const override { return QSize(600, 400); } + // write a formatted message to the console - void write(const QString &message, const QTextCharFormat &fmt); + void write(const QString &message, const QString &sfmtID = {}) override; + static const QStringList &history() { return history_.strings_; } - void setCompleter(QCodeCompletionWidget *c); + // get the current command line QString getCommandLine(); @@ -103,8 +91,6 @@ private: QDocumentCursor inpos_; QString currentMultiLineCode_; QConsoleIODevice *iodevice_; - QTextCharFormat chanFormat_[nConsoleChannels]; - QCodeCompletionWidget *completer_; QLanguageFactory *m_language = nullptr; }; diff --git a/3rdparty/qcodeedit2/lib/document/qdocument.cpp b/3rdparty/qcodeedit2/lib/document/qdocument.cpp index 8048294..3e958ac 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocument.cpp +++ b/3rdparty/qcodeedit2/lib/document/qdocument.cpp @@ -169,11 +169,6 @@ static InitStruct init_inst; */ QDocument::QDocument(QObject *p) : QObject(p), m_impl(new QDocumentPrivate(this)) { - if (!QDocumentPrivate::m_font) { - // must not happen if config dialog plugged in... - setFont(qApp->font()); - } - setText(QString()); setLineEnding(QDocument::Conservative); @@ -186,9 +181,8 @@ QDocument::QDocument(QObject *p) connect(&(m_impl->m_commands), SIGNAL(canRedoChanged(bool)), this, SIGNAL(redoAvailable(bool))); - connect(this, SIGNAL(lineDeleted(QDocumentLineHandle *)), - QLineMarksInfoCenter::instance(), - SLOT(lineDeleted(QDocumentLineHandle *))); + connect(this, &QDocument::lineDeleted, QLineMarksInfoCenter::instance(), + &QLineMarksInfoCenter::lineDeleted); } /*! @@ -744,7 +738,7 @@ void QDocument::setLineEnding(LineEnding le) { \note this limitation is historic and may disappear in future versions */ -QFont QDocument::font() { return *(QDocumentPrivate::m_font); } +QFont QDocument::font() { return m_impl->m_font; } /*! \brief Set the font of ALL documents @@ -753,7 +747,7 @@ QFont QDocument::font() { return *(QDocumentPrivate::m_font); } in future versions */ void QDocument::setFont(const QFont &f) { - QDocumentPrivate::setFont(f); + m_impl->setFont(f); // emit contentsChanged(); } @@ -763,9 +757,7 @@ void QDocument::setFont(const QFont &f) { \note this limitation is historic and may disappear in future versions */ -const QFontMetrics &QDocument::fontMetrics() { - return *(QDocumentPrivate::m_fontMetrics); -} +const QFontMetrics &QDocument::fontMetrics() { return m_impl->m_fontMetrics; } /*! \return The default tab stop common to ALL documents @@ -773,7 +765,7 @@ const QFontMetrics &QDocument::fontMetrics() { \note this limitation is historic and may disappear in future versions */ -int QDocument::tabStop() { return QDocumentPrivate::m_defaultTabStop; } +int QDocument::tabStop() { return m_impl->m_tabStop; } /*! \brief Set the default tab stop common to all documents @@ -782,29 +774,23 @@ int QDocument::tabStop() { return QDocumentPrivate::m_defaultTabStop; } in future versions */ void QDocument::setTabStop(int n) { - QDocumentPrivate::m_defaultTabStop = n; - - foreach (QDocumentPrivate *d, QDocumentPrivate::m_documents) { - d->m_tabStop = n; - d->emitFormatsChanged(); - } + m_impl->m_tabStop = n; + emit formatsChanged(); } /*! \return the whitesapce display mode */ QDocument::WhiteSpaceMode QDocument::showSpaces() { - return QDocumentPrivate::m_showSpaces; + return m_impl->m_showSpaces; } /*! \brief Set the whitespace display mode */ void QDocument::setShowSpaces(WhiteSpaceMode m) { - QDocumentPrivate::m_showSpaces = m; - - foreach (QDocumentPrivate *d, QDocumentPrivate::m_documents) - d->emitFormatsChanged(); + m_impl->m_showSpaces = m; + emit formatsChanged(); } /*! @@ -887,8 +873,8 @@ int QDocument::visualLineCount() const { /*! \brief Convert a text (logical) line number int a visual line number - \note this is not a 1:1 mapping as logical lines can span over several - visual lines + \note this is not a 1:1 mapping as logical lines can span over + several visual lines */ int QDocument::visualLineNumber(int textLineNumber) const { return m_impl ? m_impl->visualLine(textLineNumber) : -1; @@ -897,8 +883,8 @@ int QDocument::visualLineNumber(int textLineNumber) const { /*! \brief Convert a visual line number int a text (logical) line number - \note this is not a 1:1 mapping as logical lines can span over several - visual lines + \note this is not a 1:1 mapping as logical lines can span over + several visual lines */ int QDocument::textLineNumber(int visualLineNumber) const { return m_impl ? m_impl->textLine(visualLineNumber) : -1; @@ -916,8 +902,8 @@ void QDocument::clearWidthConstraint() { \brief Set a new width constraint \param width maximum width to allow - Passing a value inferior (or equal) to zero clear the width constraint, - if any. + Passing a value inferior (or equal) to zero clear the width + constraint, if any. */ void QDocument::setWidthConstraint(int width) { if (m_impl) @@ -933,10 +919,10 @@ QDocumentLine QDocument::line(int line) const { } /*! - \return the line number corresponding to a given document y coordinate - \param ypos Y document coordinate of the target - \param wrap if not null, will be set to the wrap offset (position of the - visual line among the sublines of the wrapped text line). + \return the line number corresponding to a given document y + coordinate \param ypos Y document coordinate of the target \param wrap if + not null, will be set to the wrap offset (position of the visual line + among the sublines of the wrapped text line). */ int QDocument::lineNumber(int ypos, int *wrap) const { @@ -955,21 +941,21 @@ QDocumentLine QDocument::line(QDocumentConstIterator iterator) const { } /*! - \return A cursor operating on the document, placed at a given position - \param line target line number (text line) - \param column target text column + \return A cursor operating on the document, placed at a given + position \param line target line number (text line) \param column target + text column */ QDocumentCursor QDocument::cursor(int line, int column) const { return QDocumentCursor(const_cast(this), line, column); } /*! - \return the document line which contains a given (document-wide) text - position + \return the document line which contains a given (document-wide) + text position - \note The sole purpose of this method is to have an API close to that of - QTextDocument. This method being ridiculously slow it is recommended to avoid - it whenever possible. + \note The sole purpose of this method is to have an API close to + that of QTextDocument. This method being ridiculously slow it is + recommended to avoid it whenever possible. */ QDocumentLine QDocument::findLine(int &position) const { if (!m_impl) @@ -1010,11 +996,11 @@ int QDocument::y(const QDocumentLine &l) const { \note the width of the returned rectangle is the DOCUMENT's width */ QRect QDocument::lineRect(int line) const { - const int yoff = y(line) - 1; + const int yoff = y(line); return (yoff != -1) ? QRect(0, yoff, width(), - this->line(line).lineSpan() * m_impl->m_lineSpacing + 1) + this->line(line).lineSpan() * m_impl->m_lineSpacing) : QRect(); } @@ -1088,9 +1074,9 @@ QDocumentConstIterator QDocument::iterator(const QDocumentLine &l) const { /*! \brief Convert a document (or viewport) (x, y) position to a (line, - column) cursor position \param p document position \param line where the line - number will be stored \param column where the column (text position within - line) will be stored + column) cursor position \param p document position \param line where the + line number will be stored \param column where the column (text position + within line) will be stored */ void QDocument::cursorForDocumentPosition(const QPoint &p, int &line, int &column) const { @@ -1105,10 +1091,10 @@ void QDocument::cursorForDocumentPosition(const QPoint &p, int &line, return; // qDebug("%i %i", line, wrap); - column = - l.documentOffsetToCursor(p.x(), wrap * QDocumentPrivate::m_lineSpacing); + column = l.documentOffsetToCursor(p.x(), wrap * m_impl->m_lineSpacing); - // qDebug("(%i, %i) -> (%i [+%i], %i)", p.x(), p.y(), line, wrap, column); + // qDebug("(%i, %i) -> (%i [+%i], %i)", p.x(), p.y(), line, wrap, + // column); } /*! @@ -1125,8 +1111,8 @@ QDocumentCursor QDocument::cursorAt(const QPoint &p) const { /*! \brief Draw the contents of the document \param p painter to use - \param cxt paint context (specifies what part of the document to draw, - among other things) + \param cxt paint context (specifies what part of the document to + draw, among other things) */ void QDocument::draw(QPainter *p, PaintContext &cxt) { m_impl->draw(p, cxt); } @@ -1138,27 +1124,6 @@ void QDocument::execute(QDocumentCommand *cmd) { m_impl->execute(cmd); } -/*! - \return The default line ending policy -*/ -QDocument::LineEnding QDocument::defaultLineEnding() { - return QDocumentPrivate::m_defaultLineEnding; -} - -/*! - \brief Set the default line ending policy - - \note The line ending policy of existing documents is changed - accordingly -*/ -void QDocument::setDefaultLineEnding(QDocument::LineEnding le) { - QDocumentPrivate::m_defaultLineEnding = le; - - foreach (QDocumentPrivate *d, QDocumentPrivate::m_documents) { - d->m_doc->setLineEnding(le); - } -} - /*! \return The default format scheme used to draw document contents */ @@ -1169,8 +1134,8 @@ QFormatScheme *QDocument::defaultFormatScheme() { /*! \brief Set the default format scheme - \note Existing documents using the default format scheme will see their - format scheme changed + \note Existing documents using the default format scheme will see + their format scheme changed */ void QDocument::setDefaultFormatScheme(QFormatScheme *f) { foreach (QDocumentPrivate *d, QDocumentPrivate::m_documents) { @@ -1198,7 +1163,8 @@ void QDocument::setFormatFactory(QFormatScheme *f) { /*! \brief Begin a macro - Macro in QDocument map directly to macro in the underlying undo stack + Macro in QDocument map directly to macro in the underlying undo + stack */ void QDocument::beginMacro() { if (m_impl) @@ -1237,7 +1203,8 @@ void QDocument::clearMatches(int gid) { /*! \brief Highlight the matched sequences - \note Both position are BEFORE the matched characters (cursor position). + \note Both position are BEFORE the matched characters (cursor + position). */ void QDocument::addMatch(int gid, int line, int pos, int len, int format) { if (m_impl) { @@ -1499,26 +1466,28 @@ void QDocumentLineHandle::updateWrap() const { m_indent = 0; m_frontiers.clear(); - if (!m_doc->impl()->m_constrained) { + auto impl = m_doc->impl(); + + if (!impl->m_constrained) { if (m_layout) setFlag(QDocumentLine::LayoutDirty, true); return; } - const int tabStop = m_doc->impl()->m_tabStop; + const int tabStop = impl->m_tabStop; const int maxWidth = m_doc->widthConstraint(); if (m_layout) { layout(); - } else if (QDocumentPrivate::m_fixedPitch) { + } else if (impl->m_fixedPitch) { int idx = 0, minx = 0, lastBreak = 0, lastWidth = 0, lastX = 0, rx, - x = QDocumentPrivate::m_leftMargin, column = 0, cwidth; + x = impl->m_leftMargin, column = 0, cwidth; QChar c; int indent = 0; - const int sw = QDocumentPrivate::m_spaceWidth; + const int sw = impl->m_spaceWidth; while (idx < m_text.length() && m_text.at(idx).isSpace()) { c = m_text.at(idx); @@ -1541,16 +1510,16 @@ void QDocumentLineHandle::updateWrap() const { minx = rx = x; if ((minx + sw) >= maxWidth) { - // qWarning("Please stop shrinking so aggressively.\nNo attempt will - // be made to show something decent"); + // qWarning("Please stop shrinking so aggressively.\nNo attempt + // will be made to show something decent"); // shrinking too aggresively (or too much spaces...) ungraceful // fallback indent = idx = 0; - minx = rx = x = QDocumentPrivate::m_leftMargin; + minx = rx = x = impl->m_leftMargin; } - m_indent = minx - QDocumentPrivate::m_leftMargin; + m_indent = minx - impl->m_leftMargin; while (idx < m_text.length()) { if (c.isSpace()) //! isWord(c) || !isWord(m_text.at(idx)) ) @@ -1599,7 +1568,7 @@ void QDocumentLineHandle::updateWrap() const { QMediumArray composited = compose(); int idx = 0, minx = 0, lastBreak = 0, lastWidth = 0, lastX = 0, rx, - x = QDocumentPrivate::m_leftMargin, column = 0, cwidth; + x = impl->m_leftMargin, column = 0, cwidth; QChar c; int indent = 0; @@ -1628,15 +1597,15 @@ void QDocumentLineHandle::updateWrap() const { indent = idx; minx = rx = x; - if ((minx + QDocumentPrivate::m_spaceWidth) >= maxWidth) { - // qWarning("Please stop shrinking so aggressively.\nNo attempt will - // be made to show something decent"); + if ((minx + impl->m_spaceWidth) >= maxWidth) { + // qWarning("Please stop shrinking so aggressively.\nNo attempt + // will be made to show something decent"); indent = idx = 0; - minx = rx = x = QDocumentPrivate::m_leftMargin; + minx = rx = x = impl->m_leftMargin; } - m_indent = minx - QDocumentPrivate::m_leftMargin; + m_indent = minx - impl->m_leftMargin; while (idx < m_text.length()) { if (c.isSpace()) //! isWord(c) || !isWord(m_text.at(idx)) ) @@ -1689,9 +1658,10 @@ void QDocumentLineHandle::updateWrap() const { int QDocumentLineHandle::cursorToX(int cpos) const { cpos = qBound(0, cpos, m_text.length()); + auto impl = m_doc->impl(); + if (m_layout) { - int xoff = QDocumentPrivate::m_leftMargin, coff = 0, - line = m_frontiers.count(); + int xoff = impl->m_leftMargin, coff = 0, line = m_frontiers.count(); for (int i = 0; i < m_frontiers.count(); ++i) { if (m_frontiers.at(i).first >= cpos) { @@ -1706,16 +1676,17 @@ int QDocumentLineHandle::cursorToX(int cpos) const { xoff = m_frontiers.at(line - 1).second; } - // qDebug("c:%i (wrap:%i) => c2x(x - %i) + %i", cpos, line, coff, xoff); + // qDebug("c:%i (wrap:%i) => c2x(x - %i) + %i", cpos, line, coff, + // xoff); return qRound(m_layout->lineAt(line).cursorToX(cpos - coff)) + xoff; } int tabStop = m_doc->impl()->m_tabStop; - if (QDocumentPrivate::m_fixedPitch) { + if (impl->m_fixedPitch) { return QDocument::screenLength(m_text.constData(), cpos, tabStop) * - QDocumentPrivate::m_spaceWidth + - QDocumentPrivate::m_leftMargin; + impl->m_spaceWidth + + impl->m_leftMargin; } // qDebug("c->x(%i) unsafe computations...", cpos); @@ -1724,11 +1695,10 @@ int QDocumentLineHandle::cursorToX(int cpos) const { const QVector &fonts = m_doc->impl()->m_fonts; if ((composited.count() < cpos) || fonts.isEmpty()) - return QDocumentPrivate::m_fontMetrics->horizontalAdvance( - m_text.left(cpos)); + return impl->m_fontMetrics.horizontalAdvance(m_text.left(cpos)); int idx = 0, column = 0, cwidth; - int screenx = QDocumentPrivate::m_leftMargin; + int screenx = impl->m_leftMargin; while (idx < cpos) { QChar c = m_text.at(idx); @@ -1756,9 +1726,10 @@ int QDocumentLineHandle::cursorToX(int cpos) const { int QDocumentLineHandle::xToCursor(int xpos) const { // qDebug("x->c(%i) unsafe computations...", xpos); + auto impl = m_doc->impl(); + if (m_layout) { - int xoff = QDocumentPrivate::m_leftMargin, coff = 0, - line = m_frontiers.count(); + int xoff = impl->m_leftMargin, coff = 0, line = m_frontiers.count(); for (int i = 0; i < m_frontiers.count(); ++i) { if (m_frontiers.at(i).second >= xpos) { @@ -1773,7 +1744,8 @@ int QDocumentLineHandle::xToCursor(int xpos) const { xoff = m_frontiers.at(line - 1).second; } - // qDebug("x:%i (wrap:%i) => x2c(x - %i) + %i", xpos, line, xoff, coff); + // qDebug("x:%i (wrap:%i) => x2c(x - %i) + %i", xpos, line, xoff, + // coff); return m_layout->lineAt(line).xToCursor(xpos - xoff) + coff; } @@ -1781,9 +1753,8 @@ int QDocumentLineHandle::xToCursor(int xpos) const { int tabStop = m_doc->impl()->m_tabStop; const QVector &fonts = m_doc->impl()->m_fonts; - if (QDocumentPrivate::m_fixedPitch) { - int screenPos = (screenx - QDocumentPrivate::m_leftMargin / 2) / - QDocumentPrivate::m_spaceWidth; + if (impl->m_fixedPitch) { + int screenPos = (screenx - impl->m_leftMargin / 2) / impl->m_spaceWidth; if (tabStop == 1) return screenPos; @@ -1805,13 +1776,13 @@ int QDocumentLineHandle::xToCursor(int xpos) const { return idx; } else { - if (screenx <= QDocumentPrivate::m_leftMargin) + if (screenx <= impl->m_leftMargin) return 0; QMediumArray composited = compose(); int idx = 0, x = 0, column = 0, cwidth; - screenx -= QDocumentPrivate::m_leftMargin; + screenx -= impl->m_leftMargin; while (idx < m_text.length()) { QFontMetrics fm( @@ -1856,7 +1827,8 @@ int QDocumentLineHandle::wrappedLineForCursor(int cpos) const { } int QDocumentLineHandle::documentOffsetToCursor(int x, int y) const { - int wrap = y / QDocumentPrivate::m_lineSpacing; + auto impl = m_doc->impl(); + int wrap = y / impl->m_lineSpacing; if (wrap > m_frontiers.count()) { // return an invalid value instead? @@ -1880,20 +1852,20 @@ int QDocumentLineHandle::documentOffsetToCursor(int x, int y) const { if (wrap > 0) cpos = m_frontiers.at(wrap - 1).first; - x -= QDocumentPrivate::m_leftMargin; + x -= impl->m_leftMargin; int idx = cpos, column = 0; const int ts = m_doc->tabStop(); if (m_layout) { cpos = m_layout->lineAt(wrap).xToCursor(x); - } else if (QDocumentPrivate::m_fixedPitch) { + } else if (impl->m_fixedPitch) { if (wrap) x -= m_indent; while ((idx < max) && (x > 0)) { bool tab = m_text.at(idx).unicode() == '\t'; - int cwidth = QDocumentPrivate::m_spaceWidth; + int cwidth = impl->m_spaceWidth; if (tab) { int coff = ts - (column % ts); @@ -1963,6 +1935,8 @@ int QDocumentLineHandle::documentOffsetToCursor(int x, int y) const { void QDocumentLineHandle::cursorToDocumentOffset(int cpos, int &x, int &y) const { + auto impl = m_doc->impl(); + if (cpos > m_text.length()) cpos = m_text.length(); else if (cpos < 0) @@ -1971,8 +1945,8 @@ void QDocumentLineHandle::cursorToDocumentOffset(int cpos, int &x, int idx = 0; int wrap = wrappedLineForCursor(cpos); - x = QDocumentPrivate::m_leftMargin; - y = wrap * QDocumentPrivate::m_lineSpacing; + x = impl->m_leftMargin; + y = wrap * impl->m_lineSpacing; if (wrap) { idx = m_frontiers.at(wrap - 1).first; @@ -1983,13 +1957,13 @@ void QDocumentLineHandle::cursorToDocumentOffset(int cpos, int &x, if (m_layout) { x += m_layout->lineAt(wrap).cursorToX(cpos); - } else if (QDocumentPrivate::m_fixedPitch) { + } else if (impl->m_fixedPitch) { if (wrap) x += m_indent; while (idx < cpos) { bool tab = m_text.at(idx).unicode() == '\t'; - int cwidth = QDocumentPrivate::m_spaceWidth; + int cwidth = impl->m_spaceWidth; if (tab) { int coff = ts - (column % ts); @@ -2251,7 +2225,7 @@ void QDocumentLineHandle::layout() const { // qDebug("layout needed at line %i", this->line()); if (!m_layout) { - m_layout = new QTextLayout(m_text, QDocument::font()); + m_layout = new QTextLayout(m_text, m_doc->font()); } else { m_layout->setText(m_text); // m_layout->setFont(config()->font()); @@ -2263,8 +2237,7 @@ void QDocumentLineHandle::layout() const { // Tab width QTextOption opt; opt.setFlags(QTextOption::IncludeTrailingSpaces); - opt.setTabStopDistance(m_doc->tabStop() * - QDocumentPrivate::m_spaceWidth); + opt.setTabStopDistance(m_doc->tabStop() * m_doc->impl()->m_spaceWidth); // opt.setWrapMode(QTextOption::NoWrap); opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); @@ -2273,11 +2246,11 @@ void QDocumentLineHandle::layout() const { // If it is an RTL character, set the base layout direction of the // string to RTL. // - // See http://www.unicode.org/reports/tr9/#The_Paragraph_Level (Sections - // P2 & P3). Qt's text renderer ("scribe") version 4.2 assumes a - // "higher-level protocol" (such as KatePart) will specify the paragraph - // level, so it does not apply P2 & P3 by itself. If this ever change in - // Qt, the next code block could be removed. + // See http://www.unicode.org/reports/tr9/#The_Paragraph_Level + // (Sections P2 & P3). Qt's text renderer ("scribe") version 4.2 + // assumes a "higher-level protocol" (such as KatePart) will specify + // the paragraph level, so it does not apply P2 & P3 by itself. If + // this ever change in Qt, the next code block could be removed. if (m_text.isRightToLeft()) opt.setTextDirection(Qt::RightToLeft); @@ -2305,7 +2278,7 @@ void QDocumentLineHandle::layout() const { if (m_doc->widthConstraint()) line.setLineWidth(m_doc->widthConstraint() - - QDocumentPrivate::m_leftMargin); + m_doc->impl()->m_leftMargin); else line.setNumColumns(m_text.length()); @@ -2316,7 +2289,7 @@ void QDocumentLineHandle::layout() const { m_layout->textOption().textDirection() == Qt::RightToLeft) { line.setPosition( QPoint(qRound(qreal(m_doc->widthConstraint() - - 2 * QDocumentPrivate::m_leftMargin) - + 2 * m_doc->impl()->m_leftMargin) - line.naturalTextWidth()), height)); } else { @@ -2324,7 +2297,7 @@ void QDocumentLineHandle::layout() const { if (!i) { m_indent = minwidth = cursorToX(nextNonSpaceChar(0)) - - QDocumentPrivate::m_leftMargin; + m_doc->impl()->m_leftMargin; if (minwidth < 0 || minwidth >= m_doc->widthConstraint()) minwidth = 0; @@ -2335,7 +2308,7 @@ void QDocumentLineHandle::layout() const { ++i; - height += QDocumentPrivate::m_lineSpacing; + height += m_doc->impl()->m_lineSpacing; // height += QDocument::fontMetrics().height(); } @@ -2371,12 +2344,13 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, m_layout->setFormats(decorations()); QMediumArray m_composited = compose(); + auto impl = m_doc->impl(); if (m_layout) { // if ( !hasFlag(QDocumentLine::FormatsApplied) ) // applyOverlays(); - const int lh = QDocument::fontMetrics().height(); + const int lh = m_doc->fontMetrics().height(); QVector selections; @@ -2405,8 +2379,8 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, qreal lineWidth = m_layout->lineAt(m_layout->lineCount() - 1) .naturalTextWidth(); - const int endX = QDocumentPrivate::m_leftMargin + - qRound(lineWidth) - xOffset; + const int endX = + impl->m_leftMargin + qRound(lineWidth) - xOffset; QRect area(endX, lh * i, vWidth - endX, lh); @@ -2417,7 +2391,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, } } - QPoint off(QDocumentPrivate::m_leftMargin, 0); + QPoint off(impl->m_leftMargin, 0); m_layout->draw(p, off, selections); @@ -2428,15 +2402,13 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, } else if (m_text.isEmpty()) { // enforce selection drawing on empty lines if (sel.count() == 1) - p->fillRect(qMax(xOffset, QDocumentPrivate::m_leftMargin), 0, - vWidth, QDocumentPrivate::m_lineSpacing, - pal.highlight()); + p->fillRect(qMax(xOffset, impl->m_leftMargin), 0, vWidth, + impl->m_lineSpacing, pal.highlight()); // enforce cursor drawing on empty lines - if (cursor.count() && (xOffset < QDocumentPrivate::m_leftMargin)) - p->drawLine(QDocumentPrivate::m_leftMargin, 0, - QDocumentPrivate::m_leftMargin, - QDocumentPrivate::m_lineSpacing); + if (cursor.count() && (xOffset < impl->m_leftMargin)) + p->drawLine(impl->m_leftMargin, 0, impl->m_leftMargin, + impl->m_lineSpacing); } else if (true) { @@ -2552,21 +2524,19 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, const bool unbounded = sel.count() & 1; const QColor ht = pal.highlightedText().color(); - const bool showTabs = QDocument::showSpaces() & QDocument::ShowTabs, - showLeading = - QDocument::showSpaces() & QDocument::ShowLeading, - showTrailing = - QDocument::showSpaces() & QDocument::ShowTrailing; + const bool showTabs = m_doc->showSpaces() & QDocument::ShowTabs, + showLeading = m_doc->showSpaces() & QDocument::ShowLeading, + showTrailing = m_doc->showSpaces() & QDocument::ShowTrailing; // const int fns = nextNonSpaceChar(0); - int indent = qMax(m_indent, QDocumentPrivate::m_leftMargin); + int indent = qMax(m_indent, impl->m_leftMargin); int cidx = 0; int rngIdx = 0; int column = 0; bool continuingWave = false, brokenWave = false; int dir = 0; // 0 = down; 1 = up - int wrap = 0, xpos = QDocumentPrivate::m_leftMargin, ypos = 0; + int wrap = 0, xpos = impl->m_leftMargin, ypos = 0; bool leading = ranges.first().format & 0x4000, pastLead = false; foreach (const RenderRange &r, ranges) { @@ -2578,24 +2548,22 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, if (fmt & 0x8000) { // finish selection p->fillRect(xpos, ypos, maxWidth - xpos, - QDocumentPrivate::m_lineSpacing, - pal.highlight()); + impl->m_lineSpacing, pal.highlight()); } if (pastLead && (r.format & 0x4000)) { - indent = QDocumentPrivate::m_leftMargin; + indent = impl->m_leftMargin; } ++wrap; column = 0; - ypos += QDocumentPrivate::m_lineSpacing; + ypos += impl->m_lineSpacing; xpos = indent; if (r.format & 0x8000) { // finish selection - p->fillRect(QDocumentPrivate::m_leftMargin, ypos, xpos, - QDocumentPrivate::m_lineSpacing, - pal.highlight()); + p->fillRect(impl->m_leftMargin, ypos, xpos, + impl->m_lineSpacing, pal.highlight()); } } if (leading && !(r.format & 0x4000)) { @@ -2622,18 +2590,18 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, foreach (QChar c, rng) { if (c.unicode() == '\t') { int toff = ts - (tcol % ts); - rwidth += toff * QDocumentPrivate::m_spaceWidth; + rwidth += toff * impl->m_spaceWidth; tcol += toff; } else { - rwidth += QDocumentPrivate::m_spaceWidth; + rwidth += impl->m_spaceWidth; ++tcol; } } } else { column += r.length; - if (QDocumentPrivate::m_fixedPitch) - rwidth = QDocumentPrivate::m_spaceWidth * r.length; + if (impl->m_fixedPitch) + rwidth = impl->m_spaceWidth * r.length; else rwidth = p->fontMetrics().horizontalAdvance(rng); } @@ -2650,7 +2618,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, QFormat format; int xspos = xpos; const QPen oldpen = p->pen(); - const int baseline = ypos + QDocumentPrivate::m_ascent; + const int baseline = ypos + impl->m_ascent; if (d->m_formatScheme) format = d->m_formatScheme->format(fmt & 0x0fff); @@ -2658,7 +2626,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, if (fullSel || (fmt & 0x8000)) { p->setPen(ht); - p->fillRect(xpos, ypos, rwidth, QDocumentPrivate::m_lineSpacing, + p->fillRect(xpos, ypos, rwidth, impl->m_lineSpacing, pal.highlight()); } else { @@ -2669,8 +2637,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, } if (format.background.isValid()) { - p->fillRect(xpos, ypos, rwidth, - QDocumentPrivate::m_lineSpacing, + p->fillRect(xpos, ypos, rwidth, impl->m_lineSpacing, format.background); } } @@ -2686,7 +2653,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, while (cidx < cursor.count()) { if (cursor.at(cidx) == i) { p->drawLine(xpos, ypos, xpos, - ypos + QDocumentPrivate::m_lineSpacing); + ypos + impl->m_lineSpacing); ++cidx; } else { break; @@ -2701,7 +2668,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, if (isTab) { int toff = ts - (column % ts); column += toff; - int xoff = toff * QDocumentPrivate::m_spaceWidth; + int xoff = toff * impl->m_spaceWidth; /* if ( r.format & 0x8000 ) { @@ -2713,11 +2680,11 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, */ if (showTabs) { p->translate(xpos - m_spaceSignOffset, - ypos + QDocumentPrivate::m_ascent); + ypos + impl->m_ascent); p->drawPoints(m_spaceSign, sizeof(m_spaceSign) / sizeof(QPoint)); p->translate(m_spaceSignOffset - xpos, - -ypos - QDocumentPrivate::m_ascent); + -ypos - impl->m_ascent); } xpos += xoff; @@ -2735,14 +2702,14 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, if ((leading && showLeading) || ((r.position >= last) && showTrailing)) { p->translate(xpos - m_spaceSignOffset, - ypos + QDocumentPrivate::m_ascent); + ypos + impl->m_ascent); p->drawPoints(m_spaceSign, sizeof(m_spaceSign) / sizeof(QPoint)); p->translate(m_spaceSignOffset - xpos, - -ypos - QDocumentPrivate::m_ascent); + -ypos - impl->m_ascent); } - xpos += QDocumentPrivate::m_spaceWidth; + xpos += impl->m_spaceWidth; } } @@ -2771,8 +2738,8 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, int xcpos = xpos; if (xcoff) { - if (QDocumentPrivate::m_fixedPitch) { - xcpos += xcoff * QDocumentPrivate::m_spaceWidth; + if (impl->m_fixedPitch) { + xcpos += xcoff * impl->m_spaceWidth; } else { xcpos += p->fontMetrics().horizontalAdvance( rng.left(xcoff)); @@ -2783,7 +2750,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, // cursor.at(cidx), xcpos); p->drawLine(xcpos, ypos, xcpos, - ypos + QDocumentPrivate::m_lineSpacing); + ypos + impl->m_lineSpacing); ++cidx; } else { @@ -2794,13 +2761,14 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, xpos += rwidth; } - // qDebug("underline pos : %i", p->fontMetrics().underlinePos()); + // qDebug("underline pos : %i", + // p->fontMetrics().underlinePos()); if (format.linescolor.isValid()) p->setPen(format.linescolor); const int ydo = qMin(baseline + p->fontMetrics().underlinePos(), - ypos + QDocumentPrivate::m_lineSpacing - 1); + ypos + impl->m_lineSpacing - 1); const int yin = baseline - p->fontMetrics().strikeOutPos(); const int yup = qMax(baseline - p->fontMetrics().overlinePos() + 1, ypos); @@ -2820,10 +2788,10 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, if (format.waveUnderline) { /* those goddamn font makers take liberties with common sense - and make it so damn harder to figure proper y offset for wave - underline (keeping the regular underline pos make it look - weird or even invisible on some fonts... reference rendering - with DejaVu Sans Mono) + and make it so damn harder to figure proper y offset for + wave underline (keeping the regular underline pos make it + look weird or even invisible on some fonts... reference + rendering with DejaVu Sans Mono) */ // we used fixed wave amplitude of 3 (well strictly speaking @@ -2831,7 +2799,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, // focus on getting that code to work... // gotta center things - const int ycenter = ypos + QDocumentPrivate::m_lineSpacing - 3; + const int ycenter = ypos + impl->m_lineSpacing - 3; /* qMin( ypos + (QDocumentPrivate::m_ascent + @@ -2895,8 +2863,8 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, } if (unbounded) - p->fillRect(xpos, ypos, maxWidth - xpos, - QDocumentPrivate::m_lineSpacing, pal.highlight()); + p->fillRect(xpos, ypos, maxWidth - xpos, impl->m_lineSpacing, + pal.highlight()); } else { QChar c; @@ -2908,14 +2876,14 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, int fmt = 0; bool leading = true, unbounded = false, leftSel = false, - showTabs = QDocument::showSpaces() & QDocument::ShowTabs, - showLeading = QDocument::showSpaces() & QDocument::ShowLeading, - showTrailing = QDocument::showSpaces() & QDocument::ShowTrailing; + showTabs = m_doc->showSpaces() & QDocument::ShowTabs, + showLeading = m_doc->showSpaces() & QDocument::ShowLeading, + showTrailing = m_doc->showSpaces() & QDocument::ShowTrailing; int cwidth, ypos = 0, indent = 0, idx = 0, column = 0, selidx = 0, - sellen = 0, wrap = 0, xpos = QDocumentPrivate::m_leftMargin; + sellen = 0, wrap = 0, xpos = impl->m_leftMargin; - const int ts = QDocument::tabStop(); + const int ts = m_doc->tabStop(); // find start of trailing whitespaces int last = m_text.length(); @@ -2940,8 +2908,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, sellen = m_text.length() - idx; p->fillRect(xpos, ypos, maxWidth - xpos, - QDocumentPrivate::m_lineSpacing, - pal.highlight()); + impl->m_lineSpacing, pal.highlight()); } } @@ -2949,10 +2916,10 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, if (c == '\t') { int toff = ts - (column % ts); - cwidth = toff * QDocumentPrivate::m_spaceWidth; + cwidth = toff * impl->m_spaceWidth; column += toff - 1; } else if (c == ' ') { - cwidth = QDocumentPrivate::m_spaceWidth; + cwidth = impl->m_spaceWidth; } else if (idx < m_composited.count()) { int nfmt = m_composited[idx]; @@ -2961,11 +2928,12 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, fmt = nfmt; } - // make sure bold/italicized/.. chars are taken into account... + // make sure bold/italicized/.. chars are taken into + // account... cwidth = p->fontMetrics().horizontalAdvance(c); } else { // char uses default font... - cwidth = QDocumentPrivate::m_fontMetrics->horizontalAdvance(c); + cwidth = impl->m_fontMetrics.horizontalAdvance(c); } if ((xpos + cwidth) > xOffset) { @@ -2974,31 +2942,28 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, (idx >= m_frontiers.at(wrap).first)) { if (sellen || leftSel) { p->fillRect(xpos, ypos, maxWidth - xpos, - QDocumentPrivate::m_lineSpacing, - pal.highlight()); + impl->m_lineSpacing, pal.highlight()); } ++wrap; xpos = indent; - ypos += QDocumentPrivate::m_lineSpacing; + ypos += impl->m_lineSpacing; if (sellen || leftSel) { - p->fillRect(QDocumentPrivate::m_leftMargin, ypos, - xpos - QDocumentPrivate::m_leftMargin + + p->fillRect(impl->m_leftMargin, ypos, + xpos - impl->m_leftMargin + (leftSel ? 0 : cwidth), - QDocumentPrivate::m_lineSpacing, - pal.highlight()); + impl->m_lineSpacing, pal.highlight()); } } else { if (sellen) { - p->fillRect(xpos, ypos, cwidth, - QDocumentPrivate::m_lineSpacing, + p->fillRect(xpos, ypos, cwidth, impl->m_lineSpacing, pal.highlight()); } } - const int baseline = ypos + QDocumentPrivate::m_ascent; + const int baseline = ypos + impl->m_ascent; if (!c.isSpace()) { if (leading) @@ -3017,17 +2982,17 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, // QDocumentPrivate::m_ascent, QChar(0x231E)); p->translate(xpos - m_spaceSignOffset, - ypos + QDocumentPrivate::m_ascent); + ypos + impl->m_ascent); p->drawPoints(m_spaceSign, sizeof(m_spaceSign) / sizeof(QPoint)); p->translate(m_spaceSignOffset - xpos, - -ypos - QDocumentPrivate::m_ascent); + -ypos - impl->m_ascent); } for (int cidx = 0; cidx < cursor.count(); ++cidx) { if (cursor[cidx] == idx) p->drawLine(xpos, ypos, xpos, - ypos + QDocumentPrivate::m_lineSpacing); + ypos + impl->m_lineSpacing); } if (idx < m_composited.count()) { @@ -3058,10 +3023,10 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, p->setPen(QColor(255, 0, 0)); p->drawLine(xpos, ydo, xpos + cwidth / 2, - ypos + QDocumentPrivate::m_lineSpacing - 1); + ypos + impl->m_lineSpacing - 1); p->drawLine(xpos + cwidth / 2, - ypos + QDocumentPrivate::m_lineSpacing - 1, + ypos + impl->m_lineSpacing - 1, xpos + cwidth, ydo); p->setPen(oldpen); @@ -3072,7 +3037,7 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, (idx >= m_frontiers.at(wrap).first)) { ++wrap; xpos = indent; - ypos += QDocumentPrivate::m_lineSpacing; + ypos += impl->m_lineSpacing; } if (!c.isSpace()) { @@ -3104,13 +3069,12 @@ void QDocumentLineHandle::draw(QPainter *p, int xOffset, int vWidth, // ensure drawing of cursor at EOL for (int cidx = 0; cidx < cursor.count(); ++cidx) { if (cursor[cidx] == idx) - p->drawLine(xpos, ypos, xpos, - ypos + QDocumentPrivate::m_lineSpacing); + p->drawLine(xpos, ypos, xpos, ypos + impl->m_lineSpacing); } if (wrapped && unbounded) - p->fillRect(xpos, ypos, maxWidth - xpos, - QDocumentPrivate::m_lineSpacing, pal.highlight()); + p->fillRect(xpos, ypos, maxWidth - xpos, impl->m_lineSpacing, + pal.highlight()); } } @@ -3273,7 +3237,7 @@ int QDocumentCursorHandle::anchorColumnNumber() const { int QDocumentCursorHandle::visualColumnNumber() const { return QDocument::screenLength(line().text().constData(), m_begOffset, - QDocument::tabStop()); + m_doc->tabStop()); } int QDocumentCursorHandle::columnNumber() const { return m_begOffset; } @@ -3496,7 +3460,7 @@ bool QDocumentCursorHandle::movePosition(int count, int op, int m) { if (hasColumnMemory()) p.rx() = qMax(p.x(), m_max); - p.ry() -= QDocumentPrivate::m_lineSpacing * count; + p.ry() -= m_doc->impl()->m_lineSpacing * count; if (p.y() >= 0) { m_doc->cursorForDocumentPosition(p, line, offset); @@ -3516,7 +3480,8 @@ bool QDocumentCursorHandle::movePosition(int count, int op, int m) { } //*line = QDocumentLine(*it); - //*offset = line->xToCursor(qMin(line->cursorToX(*offset), m_max), 0); + //*offset = line->xToCursor(qMin(line->cursorToX(*offset), m_max), + // 0); l = m_doc->line(line); if (count) @@ -3540,7 +3505,7 @@ bool QDocumentCursorHandle::movePosition(int count, int op, int m) { if (hasColumnMemory()) p.rx() = qMax(p.x(), m_max); - p.ry() += QDocumentPrivate::m_lineSpacing * count; + p.ry() += m_doc->impl()->m_lineSpacing * count; int oldLine = line, oldCol = offset; m_doc->cursorForDocumentPosition(p, line, offset); @@ -3676,9 +3641,8 @@ bool QDocumentCursorHandle::movePosition(int count, int op, int m) { // -- patch -- { // //offset = qMin(offset, - // l.length() - 1); bool - // next = (l.length() && offset >= 0) ? - // isWord(l.text().at(offset)) : true; + // l.length() - 1); bool next = (l.length() && offset >= 0) + // ? isWord(l.text().at(offset)) : true; // // if ( loop ) // next = !next; @@ -3700,7 +3664,7 @@ bool QDocumentCursorHandle::movePosition(int count, int op, int m) { // offset = l.length() - 1; // } while ( l.isValid() && (line != beg) && // l.hasFlag(QDocumentLine::Hidden) ); - // } else { break; + // } else { break; // } // } // } @@ -3771,8 +3735,8 @@ bool QDocumentCursorHandle::movePosition(int count, int op, int m) { // { // ++offset; // } else if ( (line + 1) - // != end ) { offset = - // 0; do + // != end ) { offset = 0; + // do // { // ++line; // l = @@ -3889,7 +3853,8 @@ void QDocumentCursorHandle::moveTo(int line, int column) { refreshColumnMemory(); } -void QDocumentCursorHandle::insertText(const QString &s, bool keepAnchor) { +void QDocumentCursorHandle::insertText(const QString &s, bool keepAnchor, + const QString &sfmtID) { if (!m_doc || s.isEmpty() || m_doc->line(m_begLine).isNull()) return; @@ -3901,7 +3866,7 @@ void QDocumentCursorHandle::insertText(const QString &s, bool keepAnchor) { } QDocumentCommand *command = - new QDocumentInsertCommand(m_begLine, m_begOffset, s, m_doc); + new QDocumentInsertCommand(m_begLine, m_begOffset, s, m_doc, sfmtID); command->setKeepAnchor(keepAnchor); command->setTargetCursor(this); @@ -4121,7 +4086,8 @@ QString QDocumentCursorHandle::selectedText() const { s = l1.text().mid(m_begOffset); int it = m_begLine; - // QDocumentConstIterator it = m_doc->impl()->index(m_begLine.handle()); + // QDocumentConstIterator it = + // m_doc->impl()->index(m_begLine.handle()); while (++it < m_endLine) { s += '\n'; @@ -4134,7 +4100,8 @@ QString QDocumentCursorHandle::selectedText() const { s = l2.text().mid(m_endOffset); int it = m_endLine; - // QDocumentConstIterator it = m_doc->impl()->index(m_endLine.handle()); + // QDocumentConstIterator it = + // m_doc->impl()->index(m_endLine.handle()); while (++it < m_begLine) { s += '\n'; @@ -4187,8 +4154,8 @@ void QDocumentCursorHandle::replaceSelectedText(const QString &text) { */ } - // qDebug("[%i, %i] => ( (%i, %i), (%i, %i) )", begline, begcol, m_begLine, - // m_begOffset, m_endLine, m_endOffset); + // qDebug("[%i, %i] => ( (%i, %i), (%i, %i) )", begline, begcol, + // m_begLine, m_begOffset, m_endLine, m_endOffset); } void QDocumentCursorHandle::select(QDocumentCursor::SelectionType t) { @@ -4393,8 +4360,8 @@ void QDocumentCursorHandle::substractBoundaries(int lbeg, int cbeg, int lend, } } - // qDebug("(%i, %i : %i, %i) corrected to (%i, %i : %i, %i)", tlmin, tcmin, - // tlmax, tcmax, m_begLine, m_begOffset, m_endLine, m_endOffset); + // qDebug("(%i, %i : %i, %i) corrected to (%i, %i : %i, %i)", tlmin, + // tcmin, tlmax, tcmax, m_begLine, m_begOffset, m_endLine, m_endOffset); } void QDocumentCursorHandle::intersectBoundaries(int &lbeg, int &cbeg, int &lend, @@ -4476,7 +4443,8 @@ void QDocumentCursorHandle::intersectBoundaries(QDocumentCursorHandle *h, QDocumentCursor QDocumentCursorHandle::intersect(const QDocumentCursor &c) const { if (!hasSelection()) { - // if ( c.hasSelection() && c.isWithinSelection(QDocumentCursor(this)) ) + // if ( c.hasSelection() && + // c.isWithinSelection(QDocumentCursor(this)) ) // return QDocumentCursor(clone()); } else if (!c.hasSelection()) { @@ -4553,35 +4521,19 @@ T *getStaticDefault() { return &_globStatInst; } -QFont *QDocumentPrivate::m_font = nullptr; // = QApplication::font(); -QFontMetrics *QDocumentPrivate::m_fontMetrics = nullptr; //(m_font); - -int QDocumentPrivate::m_defaultTabStop = 4; QFormatScheme *QDocumentPrivate::m_defaultFormatScheme = getStaticDefault(); QList QDocumentPrivate::m_documents; -bool QDocumentPrivate::m_fixedPitch; -int QDocumentPrivate::m_ascent; // = m_fontMetrics.ascent(); -int QDocumentPrivate::m_descent; // = m_fontMetrics.descent(); -int QDocumentPrivate::m_leading; // = m_fontMetrics.leading(); -int QDocumentPrivate::m_spaceWidth; // = m_fontMetrics.width(' '); -int QDocumentPrivate::m_lineHeight; // = m_fontMetrics.height(); -int QDocumentPrivate::m_lineSpacing; // = m_fontMetrics.lineSpacing(); - -int QDocumentPrivate::m_leftMargin = 5; -QDocument::WhiteSpaceMode QDocumentPrivate::m_showSpaces = QDocument::ShowNone; -QDocument::LineEnding QDocumentPrivate::m_defaultLineEnding = - QDocument::Conservative; - -int QDocumentPrivate::m_wrapMargin = 15; - QDocumentPrivate::QDocumentPrivate(QDocument *d) : m_doc(d), m_editCursor(0), m_lastGroupId(-1), m_constrained(false), - m_width(0), m_height(0), m_tabStop(m_defaultTabStop), m_formatScheme(0), - m_language(0), m_maxMarksPerLine(0), _nix(0), _dos(0), _mac(0), - m_lineEnding(m_defaultLineEnding) { + m_width(0), m_height(0), m_tabStop(4), m_formatScheme(0), + m_language(nullptr), m_maxMarksPerLine(0), _nix(0), _dos(0), _mac(0), + m_lineEnding(QDocument::Conservative), m_wrapMargin(15), m_font(), + m_fontMetrics(m_font), m_leftMargin(5), + m_showSpaces(QDocument::ShowNone) { + setFont(qApp->font()); m_documents << this; updateFormatCache(); } @@ -4710,7 +4662,7 @@ void QDocumentPrivate::draw(QPainter *p, QDocument::PaintContext &cxt) { if (cxt.height % m_lineSpacing) ++lastLine; - p->setFont(*m_font); + p->setFont(m_font); QBrush bg, base = cxt.palette.base(), selbg = cxt.palette.highlight(), alternate = cxt.palette.base().color().lighter(); @@ -4960,8 +4912,8 @@ void QDocumentPrivate::setWidth(int width) { } } } else if (oldWidth > width) { - // shrink : scan whole document and create new wraps wherever needed - // qDebug("global width scan [constraint on]"); + // shrink : scan whole document and create new wraps wherever + // needed qDebug("global width scan [constraint on]"); // m_wrapped.clear(); setWidth(); } @@ -4978,7 +4930,7 @@ void QDocumentPrivate::setWidth(int width) { emitWidthChanged(); setHeight(); - emitFormatsChanged(); + emit m_doc->formatsChanged(); } void QDocumentPrivate::setWidth() { @@ -5105,42 +5057,36 @@ void QDocumentPrivate::setHeight() { } void QDocumentPrivate::setFont(const QFont &f) { - if (!m_font) { - m_font = new QFont; - m_fontMetrics = new QFontMetrics(*m_font); - } - - *m_font = f; + m_font = f; // ensures the font is fixed pitch to avoid idsplay glitches // and inconsistency of column selections // :( does not work well... // m_font->setFixedPitch(true); - // set the styling so that if the font is not found Courier one will be used - m_font->setStyleHint(QFont::Courier, QFont::PreferQuality); + // set the styling so that if the font is not found Courier one will be + // used + m_font.setStyleHint(QFont::Courier, QFont::PreferQuality); - *m_fontMetrics = QFontMetrics(*m_font); + m_fontMetrics = QFontMetrics(m_font); - m_spaceWidth = m_fontMetrics->horizontalAdvance(' '); - m_lineSpacing = m_fontMetrics->lineSpacing(); - m_ascent = m_fontMetrics->ascent(); - m_descent = m_fontMetrics->descent(); - m_leading = m_fontMetrics->leading(); + m_spaceWidth = m_fontMetrics.horizontalAdvance(' '); + m_lineSpacing = m_fontMetrics.lineSpacing(); + m_ascent = m_fontMetrics.ascent(); + m_descent = m_fontMetrics.descent(); + m_leading = m_fontMetrics.leading(); - m_lineHeight = m_fontMetrics->height(); + m_lineHeight = m_fontMetrics.height(); // m_lineHeight = m_ascent + m_descent - 2; - m_fixedPitch = QFontInfo(*m_font).fixedPitch(); + m_fixedPitch = QFontInfo(m_font).fixedPitch(); + + updateFormatCache(); + setWidth(); + setHeight(); // if ( !m_fixedPitch ) // qDebug("unsafe computations..."); - - foreach (QDocumentPrivate *d, m_documents) { - d->updateFormatCache(); - d->setWidth(); - d->setHeight(); - } } void QDocumentPrivate::setFormatScheme(QFormatScheme *f) { @@ -5153,7 +5099,7 @@ void QDocumentPrivate::tunePainter(QPainter *p, int fid) { p->setFont(m_fonts.at(fid)); // p->setPen(m_colors.at(fid)); } else { - p->setFont(*m_font); + p->setFont(m_font); // p->setPen(Qt::black); } } @@ -5161,15 +5107,12 @@ void QDocumentPrivate::tunePainter(QPainter *p, int fid) { void QDocumentPrivate::updateFormatCache() { m_fonts.clear(); - if (!m_font) - return; - if (!m_formatScheme) { - m_fonts << *m_font; + m_fonts << m_font; return; } - QFont f(*m_font); + QFont f(m_font); const int end = m_formatScheme->formatCount(); m_fonts.reserve(end); @@ -5186,7 +5129,7 @@ void QDocumentPrivate::updateFormatCache() { // foreach ( QDocumentPrivate *d, m_documents ) // d->emitFormatsChanged(); - emitFormatsChanged(); + emit m_doc->formatsChanged(); } void QDocumentPrivate::emitWidthChanged() { @@ -5432,7 +5375,8 @@ void QDocumentPrivate::clearMatches(int groupId) { /*! \brief Highlight the matched sequences - \note Both position are BEFORE the matched characters (cursor position). + \note Both position are BEFORE the matched characters (cursor + position). */ void QDocumentPrivate::addMatch(int groupId, int line, int pos, int len, int format) { @@ -5654,8 +5598,8 @@ int QDocumentPrivate::textLine(int visualLine, int *wrap) const { break; if (w != we && w.key() == hl) { - // qDebug("trying to solve : h=(%i, %i), w=(%i, %i)", hl, - // *h, w.key(), *w); + // qDebug("trying to solve : h=(%i, %i), w=(%i, %i)", + // hl, *h, w.key(), *w); const int off = (visualLine + mess) - hl; if (off <= *w) { // qDebug("%i -> %i + %i", visualLine, hl, off); @@ -5673,8 +5617,8 @@ int QDocumentPrivate::textLine(int visualLine, int *wrap) const { ++h; } while ((h != he) && (h.key() <= hl + max)); - // very important : do not forget possible wrapping on folded - // block start + // very important : do not forget possible wrapping on + // folded block start if (w != we && w.key() == hl) { wrappedLines += *w; ++w; @@ -5764,7 +5708,7 @@ void QDocumentPrivate::hideEvent(int line, int count) { setHeight(); // emitFormatsChange(line, count); - emitFormatsChanged(); + emit m_doc->formatsChanged(); } void QDocumentPrivate::showEvent(int line, int count) { @@ -5772,7 +5716,8 @@ void QDocumentPrivate::showEvent(int line, int count) { while ((it != m_hidden.end()) && (it.key() == line)) { if (*it == count) { - // qDebug("showing %i lines from %i", count, line); + // qDebug("showing %i lines from %i", + // count, line); it = m_hidden.erase(it); } else ++it; @@ -5780,7 +5725,7 @@ void QDocumentPrivate::showEvent(int line, int count) { setHeight(); // emitFormatsChange(line, count); - emitFormatsChanged(); + emit m_doc->formatsChanged(); } void QDocumentPrivate::updateHidden(int line, int count) { @@ -5820,8 +5765,8 @@ void QDocumentPrivate::updateWrapped(int line, int count) { if (it.key() < line) { m_wrapped.insert(it.key(), *it); } else { - // qDebug("moved wrap from line %i to line %i", it.key(), it.key() + - // count); + // qDebug("moved wrap from line %i to line %i", it.key(), + // it.key() + count); m_wrapped.insert(it.key() + count, *it); } @@ -5851,8 +5796,6 @@ void QDocumentPrivate::emitContentsChange(int line, int lines) { emitFormatsChange(line + lines, n - lines); } -void QDocumentPrivate::emitFormatsChanged() { emit m_doc->formatsChanged(); } - void QDocumentPrivate::emitContentsChanged() { // emit m_doc->contentsChanged(); } @@ -5884,7 +5827,7 @@ void QDocumentPrivate::emitLineDeleted(QDocumentLineHandle *h) { } void QDocumentPrivate::emitMarkChanged(QDocumentLineHandle *l, int m, bool on) { - emitFormatsChanged(); + emit m_doc->formatsChanged(); emit m_doc->markChanged(l, m, on); } diff --git a/3rdparty/qcodeedit2/lib/document/qdocument.h b/3rdparty/qcodeedit2/lib/document/qdocument.h index a23ac3a..1264bdd 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocument.h +++ b/3rdparty/qcodeedit2/lib/document/qdocument.h @@ -192,18 +192,15 @@ public: void flushMatches(int groupId); void addMatch(int groupId, int line, int pos, int len, int format); - static QFont font(); - static void setFont(const QFont &f); - static const QFontMetrics &fontMetrics(); + QFont font(); + void setFont(const QFont &f); + const QFontMetrics &fontMetrics(); - static LineEnding defaultLineEnding(); - static void setDefaultLineEnding(LineEnding le); + int tabStop(); + void setTabStop(int n); - static int tabStop(); - static void setTabStop(int n); - - static WhiteSpaceMode showSpaces(); - static void setShowSpaces(WhiteSpaceMode y); + WhiteSpaceMode showSpaces(); + void setShowSpaces(WhiteSpaceMode y); static QFormatScheme *defaultFormatScheme(); static void setDefaultFormatScheme(QFormatScheme *f); diff --git a/3rdparty/qcodeedit2/lib/document/qdocument_p.h b/3rdparty/qcodeedit2/lib/document/qdocument_p.h index f92f32a..825e8ca 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocument_p.h +++ b/3rdparty/qcodeedit2/lib/document/qdocument_p.h @@ -86,7 +86,7 @@ public: void setWidth(); void setHeight(); - static void setFont(const QFont &f); + void setFont(const QFont &f); void beginChangeBlock(); void endChangeBlock(); @@ -120,7 +120,6 @@ public: void setWidth(int width); - void emitFormatsChanged(); void emitContentsChanged(); void emitLineDeleted(QDocumentLineHandle *h); @@ -165,7 +164,7 @@ private: struct Match { int line; QFormatRange range; - QDocumentLineHandle *h; + QDocumentLineHandle *h = nullptr; }; struct MatchList : QList { @@ -182,21 +181,19 @@ private: int m_width, m_height; int m_tabStop; - static int m_defaultTabStop; - static QFont *m_font; - static bool m_fixedPitch; - static QFontMetrics *m_fontMetrics; - static int m_leftMargin; - static QDocument::WhiteSpaceMode m_showSpaces; - static QDocument::LineEnding m_defaultLineEnding; - static int m_lineHeight; - static int m_lineSpacing; - static int m_spaceWidth; - static int m_ascent; - static int m_descent; - static int m_leading; - static int m_wrapMargin; + QFont m_font; + bool m_fixedPitch; + QFontMetrics m_fontMetrics; + int m_leftMargin; + QDocument::WhiteSpaceMode m_showSpaces; + int m_lineHeight; + int m_lineSpacing; + int m_spaceWidth; + int m_ascent; + int m_descent; + int m_leading; + int m_wrapMargin; QFormatScheme *m_formatScheme; QLanguageDefinition *m_language; diff --git a/3rdparty/qcodeedit2/lib/document/qdocumentcommand.cpp b/3rdparty/qcodeedit2/lib/document/qdocumentcommand.cpp index 917266b..5c27e74 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocumentcommand.cpp +++ b/3rdparty/qcodeedit2/lib/document/qdocumentcommand.cpp @@ -21,6 +21,7 @@ */ #include "qdocument_p.h" +#include "qformatscheme.h" /*! \ingroup document @@ -142,7 +143,8 @@ void QDocumentCommand::setUndoOffset(int off) { m_undoOffset = off; } This helper method is provided so that subclasses may actually modify the document contents without using private API. */ -void QDocumentCommand::insertText(int line, int pos, const QString &s) { +void QDocumentCommand::insertText(int line, int pos, const QString &s, + const QString &sfmtID) { if (!m_doc) return; @@ -155,6 +157,19 @@ void QDocumentCommand::insertText(int line, int pos, const QString &s) { h->textBuffer().insert(pos, s); h->shiftOverlays(pos, s.length()); + if (!sfmtID.isEmpty()) { + auto fmt = m_doc->formatScheme(); + auto id = fmt->id(sfmtID); + if (id) { + QFormatRange range; + range.format = id; + range.offset = pos; + range.length = s.length(); + + h->addOverlay(range); + } + } + pd->adjustWidth(line); } @@ -484,8 +499,9 @@ void QDocumentCommand::markUndone(QDocumentLineHandle *h) { QDocumentInsertCommand::QDocumentInsertCommand(int l, int offset, const QString &text, QDocument *doc, + const QString &sfmtID, QDocumentCommand *p) - : QDocumentCommand(Insert, doc, p) { + : QDocumentCommand(Insert, doc, p), m_sfmtID(sfmtID) { QStringList lines = text.split(QLatin1Char('\n'), Qt::KeepEmptyParts); if (!m_doc || text.isEmpty()) @@ -497,8 +513,9 @@ QDocumentInsertCommand::QDocumentInsertCommand(int l, int offset, m_data.begin = lines.takeAt(0); m_data.endOffset = lines.count() ? lines.last().length() : -1; - foreach (const QString &s, lines) + for (auto &s : lines) { m_data.handles << new QDocumentLineHandle(s, m_doc); + } QDocumentLine bl = m_doc->line(l); @@ -541,7 +558,7 @@ void QDocumentInsertCommand::redo() { removeText(m_data.lineNumber, m_data.startOffset, m_data.end.length()); } - insertText(m_data.lineNumber, m_data.startOffset, m_data.begin); + insertText(m_data.lineNumber, m_data.startOffset, m_data.begin, m_sfmtID); insertLines(m_data.lineNumber, m_data.handles); diff --git a/3rdparty/qcodeedit2/lib/document/qdocumentcommand.h b/3rdparty/qcodeedit2/lib/document/qdocumentcommand.h index 0612e8d..fb7ca33 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocumentcommand.h +++ b/3rdparty/qcodeedit2/lib/document/qdocumentcommand.h @@ -41,7 +41,7 @@ public: QList handles; }; - QDocumentCommand(Command c, QDocument *d, QDocumentCommand *p = 0); + QDocumentCommand(Command c, QDocument *d, QDocumentCommand *p = nullptr); virtual ~QDocumentCommand(); virtual int id() const; @@ -77,7 +77,8 @@ protected: void updateTarget(int l, int offset); - void insertText(int line, int pos, const QString &s); + void insertText(int line, int pos, const QString &s, + const QString &sfmtID = {}); void removeText(int line, int pos, int length); void insertLines(int after, const QList &l); @@ -102,7 +103,8 @@ Q_DECLARE_TYPEINFO(QDocumentCommand::TextCommandData, Q_MOVABLE_TYPE); class QCE_EXPORT QDocumentInsertCommand : public QDocumentCommand { public: QDocumentInsertCommand(int l, int offset, const QString &text, - QDocument *doc, QDocumentCommand *p = 0); + QDocument *doc, const QString &sfmtID = 0, + QDocumentCommand *p = nullptr); virtual ~QDocumentInsertCommand(); @@ -113,12 +115,13 @@ public: private: TextCommandData m_data; + QString m_sfmtID; }; class QCE_EXPORT QDocumentEraseCommand : public QDocumentCommand { public: QDocumentEraseCommand(int bl, int bo, int el, int eo, QDocument *doc, - QDocumentCommand *p = 0); + QDocumentCommand *p = nullptr); virtual ~QDocumentEraseCommand(); diff --git a/3rdparty/qcodeedit2/lib/document/qdocumentcursor.cpp b/3rdparty/qcodeedit2/lib/document/qdocumentcursor.cpp index e96fdd1..5cd3b71 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocumentcursor.cpp +++ b/3rdparty/qcodeedit2/lib/document/qdocumentcursor.cpp @@ -515,9 +515,10 @@ void QDocumentCursor::insertLine(bool keepAnchor) { \note Nothing happens if \a s is empty */ -void QDocumentCursor::insertText(const QString &s, bool keepAnchor) { +void QDocumentCursor::insertText(const QString &s, bool keepAnchor, + const QString &sfmtID) { if (m_handle) - m_handle->insertText(s, keepAnchor); + m_handle->insertText(s, keepAnchor, sfmtID); } /*! diff --git a/3rdparty/qcodeedit2/lib/document/qdocumentcursor.h b/3rdparty/qcodeedit2/lib/document/qdocumentcursor.h index 42bb0b2..c05cf0d 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocumentcursor.h +++ b/3rdparty/qcodeedit2/lib/document/qdocumentcursor.h @@ -141,7 +141,8 @@ public: void eraseLine(); void insertLine(bool keepAnchor = false); - void insertText(const QString &s, bool keepAnchor = false); + void insertText(const QString &s, bool keepAnchor = false, + const QString &sfmtID = {}); QDocumentCursor selectionStart() const; QDocumentCursor selectionEnd() const; diff --git a/3rdparty/qcodeedit2/lib/document/qdocumentcursor_p.h b/3rdparty/qcodeedit2/lib/document/qdocumentcursor_p.h index cd5d5cf..0c7da64 100644 --- a/3rdparty/qcodeedit2/lib/document/qdocumentcursor_p.h +++ b/3rdparty/qcodeedit2/lib/document/qdocumentcursor_p.h @@ -92,7 +92,8 @@ public: void shift(int offset); bool movePosition(int offset, int op, int m); - void insertText(const QString &s, bool keepAnchor = false); + void insertText(const QString &s, bool keepAnchor = false, + const QString &sfmtID = {}); QChar nextChar() const; QChar previousChar() const; diff --git a/3rdparty/qcodeedit2/lib/qce-config.h b/3rdparty/qcodeedit2/lib/qce-config.h index 6243e7c..c330424 100644 --- a/3rdparty/qcodeedit2/lib/qce-config.h +++ b/3rdparty/qcodeedit2/lib/qce-config.h @@ -59,7 +59,7 @@ void addDataPath(const QString &path); template class Registar { public: - Registar() { Registerable::_register(); } + constexpr Registar() { Registerable::_register(); } }; // added by wingsummer diff --git a/3rdparty/qcodeedit2/lib/qeditor.cpp b/3rdparty/qcodeedit2/lib/qeditor.cpp index 62f9601..5550fde 100644 --- a/3rdparty/qcodeedit2/lib/qeditor.cpp +++ b/3rdparty/qcodeedit2/lib/qeditor.cpp @@ -1927,34 +1927,6 @@ void QEditor::paste() { insertFromMimeData(d); } -static bool unindent(const QDocumentCursor &cur) { - QDocumentLine beg(cur.line()); - int r = 0, n = 0, t = QDocument::tabStop(); - QString txt = beg.text().left(beg.firstChar()); - - while (txt.size() && (n < t)) { - if (txt.at(txt.length() - 1) == '\t') - n += t - (n % t); - else - ++n; - - ++r; - txt.chop(1); - } - - if (!r) - return false; - - QDocumentCursor c(cur); - c.setSilent(true); - c.movePosition(1, QDocumentCursor::StartOfBlock, - QDocumentCursor::MoveAnchor); - c.movePosition(r, QDocumentCursor::Right, QDocumentCursor::KeepAnchor); - c.removeSelectedText(); - - return true; -} - static void insert(const QDocumentCursor &cur, const QString &txt) { QDocumentCursor c(cur); c.setSilent(true); @@ -2325,6 +2297,11 @@ bool QEditor::protectedCursor(const QDocumentCursor &c) const { \internal */ void QEditor::keyPressEvent(QKeyEvent *e) { + if (flag(ReadOnly)) { + e->ignore(); + return; + } + for (auto &b : m_bindings) if (b->keyPressEvent(e, this)) return; @@ -2534,13 +2511,10 @@ void QEditor::inputMethodEvent(QInputMethodEvent *e) { if (b->inputMethodEvent(e, this)) return; - /* - if ( m_doc->readOnly() ) - { - e->ignore(); - return; + if (flag(ReadOnly)) { + e->ignore(); + return; } - */ m_cursor.beginEditBlock(); @@ -3471,7 +3445,7 @@ void QEditor::pageUp(QDocumentCursor::MoveMode moveMode) { if (m_cursor.atStart()) return; - int n = viewport()->height() / QDocument::fontMetrics().lineSpacing(); + int n = viewport()->height() / m_doc->fontMetrics().lineSpacing(); repaintCursor(); m_cursor.movePosition(n, QDocumentCursor::Up, moveMode); @@ -3493,7 +3467,7 @@ void QEditor::pageDown(QDocumentCursor::MoveMode moveMode) { if (m_cursor.atEnd()) return; - int n = viewport()->height() / QDocument::fontMetrics().lineSpacing(); + int n = viewport()->height() / m_doc->fontMetrics().lineSpacing(); repaintCursor(); m_cursor.movePosition(n, QDocumentCursor::Down, moveMode); @@ -3691,7 +3665,8 @@ void QEditor::preInsert(QDocumentCursor &c, const QString &s) { This function is provided to keep indenting/outdenting working when editing */ -void QEditor::insertText(QDocumentCursor &c, const QString &text) { +void QEditor::insertText(QDocumentCursor &c, const QString &text, + const QString &sfmtID) { if (protectedCursor(c)) return; @@ -3712,11 +3687,11 @@ void QEditor::insertText(QDocumentCursor &c, const QString &text) { // TODO : replace tabs by spaces properly } - c.insertText(text); + c.insertText(text, false, sfmtID); } else { preInsert(c, lines.first()); - c.insertText(lines.takeFirst()); + c.insertText(lines.takeFirst(), false, sfmtID); QString indent; // FIXME ? work on strings to make sure command grouping does not @@ -3743,11 +3718,11 @@ void QEditor::insertText(QDocumentCursor &c, const QString &text) { } c.insertLine(); - c.insertText(indent); + c.insertText(indent, false, sfmtID); preInsert(c, l); - c.insertText(l); + c.insertText(l, false, sfmtID); } } } @@ -3759,13 +3734,13 @@ void QEditor::insertText(QDocumentCursor &c, const QString &text) { from the outside and to keep them compatible with cursor mirrors. */ -void QEditor::write(const QString &s) { +void QEditor::write(const QString &s, const QString &sfmtID) { m_doc->beginMacro(); - insertText(m_cursor, s); + insertText(m_cursor, s, sfmtID); for (int i = 0; i < m_mirrors.count(); ++i) - insertText(m_mirrors[i], s); + insertText(m_mirrors[i], s, sfmtID); m_doc->endMacro(); @@ -3850,7 +3825,7 @@ void QEditor::ensureCursorVisible() { QPoint pos = m_cursor.documentPosition(); - const int ls = QDocument::fontMetrics().lineSpacing(); + const int ls = m_doc->fontMetrics().lineSpacing(); int ypos = pos.y(), yval = verticalOffset(), ylen = viewport()->height(), yend = ypos + ls; @@ -3882,7 +3857,7 @@ void QEditor::ensureVisible(int line) { if (!m_doc) return; - const int ls = QDocument::fontMetrics().lineSpacing(); + const int ls = m_doc->fontMetrics().lineSpacing(); int ypos = m_doc->y(line), yval = verticalOffset(), ylen = viewport()->height(), yend = ypos + ls; @@ -3900,7 +3875,7 @@ void QEditor::ensureVisible(const QRect &rect) { if (!m_doc) return; - const int ls = QDocument::fontMetrics().lineSpacing(); + const int ls = m_doc->fontMetrics().lineSpacing(); int ypos = rect.y(), yval = verticalOffset(), ylen = viewport()->height(), yend = ypos + rect.height(); @@ -4002,7 +3977,7 @@ QRect QEditor::lineRect(const QDocumentLine &l) const { \return The line rect of the given cursor */ QRect QEditor::cursorRect(const QDocumentCursor &c) const { - return QEditor::lineRect(c.lineNumber()); + return QEditor::lineRect(c.lineNumber()).adjusted(0, -1, 0, 1); } /*! @@ -4164,6 +4139,34 @@ void QEditor::addCursorMirror(const QDocumentCursor &c) { bool QEditor::undoRedoEnabled() const { return m_undoRedoEnabled; } +bool QEditor::unindent(const QDocumentCursor &cur) { + QDocumentLine beg(cur.line()); + int r = 0, n = 0, t = m_doc->tabStop(); + QString txt = beg.text().left(beg.firstChar()); + + while (txt.size() && (n < t)) { + if (txt.at(txt.length() - 1) == '\t') + n += t - (n % t); + else + ++n; + + ++r; + txt.chop(1); + } + + if (!r) + return false; + + QDocumentCursor c(cur); + c.setSilent(true); + c.movePosition(1, QDocumentCursor::StartOfBlock, + QDocumentCursor::MoveAnchor); + c.movePosition(r, QDocumentCursor::Right, QDocumentCursor::KeepAnchor); + c.removeSelectedText(); + + return true; +} + /*! \internal \brief Copy the selection to the clipboard diff --git a/3rdparty/qcodeedit2/lib/qeditor.h b/3rdparty/qcodeedit2/lib/qeditor.h index 3eaa3e9..f16685d 100644 --- a/3rdparty/qcodeedit2/lib/qeditor.h +++ b/3rdparty/qcodeedit2/lib/qeditor.h @@ -237,7 +237,7 @@ public slots: virtual void retranslate(); - virtual void write(const QString &s); + virtual void write(const QString &s, const QString &sfmtID = {}); void addAction(QAction *a, const QString &menu, const QString &toolbar = QString()); @@ -372,7 +372,8 @@ public: void ensureVisible(const QRect &rect); void preInsert(QDocumentCursor &c, const QString &text); - void insertText(QDocumentCursor &c, const QString &text); + void insertText(QDocumentCursor &c, const QString &text, + const QString &sfmtID = {}); QDocumentLine lineAtPosition(const QPoint &p) const; QDocumentCursor cursorForPosition(const QPoint &p) const; @@ -388,6 +389,9 @@ public: bool undoRedoEnabled() const; +private: + bool unindent(const QDocumentCursor &cur); + protected slots: void documentWidthChanged(int newWidth); void documentHeightChanged(int newWidth); diff --git a/3rdparty/qcodeedit2/lib/qlinemarksinfocenter.h b/3rdparty/qcodeedit2/lib/qlinemarksinfocenter.h index d2c6afd..d647f48 100644 --- a/3rdparty/qcodeedit2/lib/qlinemarksinfocenter.h +++ b/3rdparty/qcodeedit2/lib/qlinemarksinfocenter.h @@ -156,6 +156,8 @@ public slots: void toggleLineMark(const QLineMarkHandle &mark); void removeLineMark(const QLineMarkHandle &mark); + void lineDeleted(QDocumentLineHandle *h); + void flush(const QString &file); signals: @@ -168,7 +170,6 @@ protected: protected slots: void cursorMoved(QEditor *e); - void lineDeleted(QDocumentLineHandle *h); void markChanged(const QString &f, QDocumentLineHandle *h, int mark, bool on); diff --git a/3rdparty/qcodeedit2/lib/widgets/qlinechangepanel.cpp b/3rdparty/qcodeedit2/lib/widgets/qlinechangepanel.cpp index f12436d..2281f51 100644 --- a/3rdparty/qcodeedit2/lib/widgets/qlinechangepanel.cpp +++ b/3rdparty/qcodeedit2/lib/widgets/qlinechangepanel.cpp @@ -73,8 +73,6 @@ void QLineChangePanel::paint(QPainter *p, QEditor *e) { pageBottom = e->viewport()->height(), contentsY = e->verticalOffset(); - QString txt; - QDocument *d = e->document(); n = d->lineNumber(contentsY); posY = 2 + d->y(n) - contentsY; diff --git a/CMakeLists.txt b/CMakeLists.txt index b21694d..5f816f3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -232,7 +232,9 @@ set(CLASS_SRC src/class/qcodenode.cpp src/class/qcodenode.h src/class/langservice.h - src/class/langservice.cpp) + src/class/langservice.cpp + src/class/clangformatmanager.h + src/class/clangformatmanager.cpp) if(WINGHEX_USE_FRAMELESS) set(WIDGET_FRAME_SRC @@ -268,6 +270,7 @@ set(MODEL_SRC src/model/dbgbreakpointmodel.cpp) set(SETTING_SRC + src/settings/settings.h src/settings/generalsettingdialog.h src/settings/generalsettingdialog.cpp src/settings/generalsettingdialog.ui @@ -285,7 +288,10 @@ set(SETTING_SRC src/settings/scriptbehaviorsettingdialog.ui src/settings/othersettingsdialog.h src/settings/othersettingsdialog.cpp - src/settings/othersettingsdialog.ui) + src/settings/othersettingsdialog.ui + src/settings/clangformatsetdialog.h + src/settings/clangformatsetdialog.cpp + src/settings/clangformatsetdialog.ui) set(SCRIPT_ADDON_SRC src/scriptaddon/scriptqstring.h @@ -312,7 +318,9 @@ set(CODEEDIT_WIDGET src/qcodeeditwidget/qformatconfig.ui src/qcodeeditwidget/qsnippetedit.cpp src/qcodeeditwidget/qsnippetedit.h - src/qcodeeditwidget/qsnippetedit.ui) + src/qcodeeditwidget/qsnippetedit.ui + src/qcodeeditwidget/qdocumentswaptextcommand.h + src/qcodeeditwidget/qdocumentswaptextcommand.cpp) set(PLUGIN_SRC src/plugin/iwingplugin.h src/plugin/pluginsystem.cpp src/plugin/pluginsystem.h src/plugin/settingpage.h) diff --git a/images/codefmt.png b/images/codefmt.png new file mode 100644 index 0000000..9411eeb Binary files /dev/null and b/images/codefmt.png differ diff --git a/images/codeformat.png b/images/codeformat.png new file mode 100644 index 0000000..40e5a72 Binary files /dev/null and b/images/codeformat.png differ diff --git a/images/snippt.png b/images/snippt.png new file mode 100644 index 0000000..451d455 Binary files /dev/null and b/images/snippt.png differ diff --git a/lang/zh_CN/winghex.ts b/lang/zh_CN/winghex.ts index a5d96dc..1447721 100644 --- a/lang/zh_CN/winghex.ts +++ b/lang/zh_CN/winghex.ts @@ -94,6 +94,75 @@ 校验和 + + ClangFormatSetDialog + + + Enable + 启用 + + + + Info + 信息 + + + + Path + 路径 + + + + Version + 版本 + + + + Configure + 配置 + + + + Location + 位置 + + + + Browse + 浏览 + + + + Style + 样式 + + + + Custom + 自定义 + + + + Edit + 编辑 + + + + IndentWidth + 缩进宽度 + + + + AutoFormatWhenSave + 保存时自动格式化 + + + + + ClangFormat + Clang Format + + ColorPickerDialog @@ -682,24 +751,24 @@ MainWindow - + File 文件 - - + + View 视图 - + About 关于 - + WingHexExplorer 羽云十六进制编辑器 @@ -714,831 +783,831 @@ 选长: - + Edit 编辑 - + Script 脚本 - - - + + + Plugin 插件 - + Setting 设置 - - + + Log 日志 - + ExportFindResult 导出搜索结果 - + ClearFindResult 清空记录 - + FindResult 搜索结果 - - - + + + Copy 复制 - - - - + + + + CopyToClipBoard 数据已拷贝到粘贴板 - + LittleEndian 小端 - + BigEndian 大端 - + Number 数值 - - + + CheckSum 校验和 - - + + DeleteBookMark 删除书签 - - + + ClearBookMark 清空书签 - - - - + + + + BookMark 书签 - + DecodeText 解码字符串 - + ScriptConsole 脚本控制台 - + DVList 可视化列表 - + DVTree 可视化树数据 - + DVTable 可视化表格 - + DVText 可视化文本 - - + + Basic 基础 - + New 新建 - + OpenF 打开文件 - + OpenFR 打开局部文件 - + OpenWorkSpace 打开工作区 - + OpenD 打开驱动器 - + RecentFiles 最近打开 - + Reload 重新加载 - - + + Save 保存 - + SaveAs 另存为 - + Export 导出 - + SaveSel 保存选区字节 - - - - + + + + General 基本 - + Undo 撤销 - + Redo 恢复 - + Cut 剪切 - + Paste 粘贴 - + Delete 删除 - + Clone 克隆 - + Lookup 查询 - + Find 查找 - + Goto 跳转 - + Encoding 编码 - + FileInfo 文件信息 - - + + Hex 十六进制 - + CutHex 剪切(十六进制) - + CopyHex 复制(十六进制) - + PasteHex 粘贴(十六进制) - - + + Fill 填充 - + FillZero 填充零 - - - - - + + + + + MetaData 标注 - + DeleteMetadata 删除标注 - + ClearMetadata 清空标注 - + MetaDataEdit 编辑标注 - + DeleteMetaData 删除标注 - + ClearMetaData 清空标注 - + Display 显示 - + Scale 缩放 - + ResetScale 重置缩放 - + ShowMetafg 标注前景色 - + ShowMetabg 标注背景色 - + ShowMetaComment 批注 - + MetaShowAll 显示所有标注 - + MetaHideAll 隐藏所有标注 - + FileStatus 文件状态 - + InfoSave 是否保存 - + ReadOnly 可读写 - + SetLocked 启用/禁用锁定编辑 - + ErrUnLock 锁定编辑失败 - + SetOver 启用/禁用改变大小 - + MetaBrokingPos 检测到已有元数据:如果打开此项,添加/删除字节将会使元数据错位失效,你确定继续吗? - + ErrUnOver 锁定文件大小失败 - + InfoCanOverLimit 当前编辑处于受限模式! - + Window 窗体 - + Editor 编辑器 - + Tools 工具 - + HexEditorLayout 编辑器布局 - + SetBaseAddr 设置基址 - + addressBase 基址 - + inputAddressBase 请输入基址 - + WarnBigBaseAddress 基址过大,你得到的地址将会不正确! - + ErrBaseAddress 非法基址输入 - + SetColInfo 显示/隐藏地址栏 - + SetHeaderInfo 显示/隐藏表头 - + SetAsciiString 显示/隐藏解码字符串 - + Layout 布局 - + Fullscreen 全屏 - + RestoreLayout 恢复默认布局 - + ExportLog 导出日志 - + ClearLog 清空日志 - + ScriptEditor 脚本编辑器 - + Scripts 脚本仓库 - + PluginFunctions 插件功能 - + PluginSettings 插件设置 - + Info 信息 - + Software 软件 - + Sponsor 赞助 - + Wiki 网页 Wiki - + AboutQT 关于 QT - + SetPageIDEmptyTryUseName 设置页 ID 为空,尝试使用名称作为 ID - + SetPageDupNameIgnored 设置页重复的 ID 名称,已忽略加载 - + Plugin %1 contains a duplicate ID (%2) that is already registered by plugin %3 插件 %1 包含重复 ID (%2),该 ID 已被插件 %3 注册 - - + + ChooseFile 选择文件 - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Error 错误 - - - - + + + + FileNotExist 文件不存在! - - - - - + + + + + FilePermission 因文件权限无法继续! - + ProjectFile (*.wingpro) 项目文件 (*.wingpro) - + Root Required! 需要管理员权限继续操作! - + ReloadSuccessfully 文件重新加载成功! - + ReloadUnSuccessfully 文件重新加载失败! - - - + + + ChooseSaveFile 请选择保存文件路径: - + NoMoreClone 克隆已到上限,无法继续操作! - + FindFininishBusy 查找任务繁忙,请勿重复查找! - + MayTooMuchFindResult 搜索数量已到达上限,结果可能不全,建议请按区段搜索。 - + ConfirmSave 正在关闭未保存的文件或工作区,你确定保存吗? - + ConfirmAPPSave 你尝试关闭程序,但仍存在未保存的文件或工作区,你确定保存这些更改吗? - - + + SaveSuccessfully 保存成功! - - + + SaveWSError 保存工作区错误! - - - + + + Warn 警告 - + ScriptObjShow 脚本对象 - - - + + + SourceChanged 局部打开原始文件更改! - - + + SaveSourceFileError 由于原文件更改,保存文件失败! - + SaveUnSuccessfully 保存失败! - + ChooseExportFile 请选择导出文件路径: - + ExportSuccessfully 导出成功! - + ExportSourceFileError 由于原文件更改,导出文件失败! - + ExportUnSuccessfully 导出失败! - + SaveSelSuccess 保存选区字节成功! - + SaveSelError 保存选区字节失败,因文件不具有可写权限! - - + + CutToClipBoard 数据已剪切到粘贴板! - - + + UnCutToClipBoard 由于保持大小限制,数据剪切到粘贴板失败! - - + + UnCopyToClipBoard 由于保持大小限制,数据剪切到复制板失败! - + FindFininish 查找结果完毕! - + PleaseInputFill 请输入填充字节值 - + FillInputError 填充字节输入错误 - - - - - - - - + + + + + + + + CheckKeepSize 请检查锁定文件大小是否开启! - - + + InputComment 请输入批注: - - - + + + NoSelection 没有选区,无法继续的操作! - + NoMetaData 无可编辑标记 - + EmptyFindResult 没有可导出的搜索结果! - + SaveFindResult 导出搜索结果成功! - + SaveFindResultError 导出结果失败! - + TooManyBytesDecode 超出解码字节限制…… - + ExportLogError 导出日志失败! - + ExportLogSuccess 导出日志成功,路径: - + ClearLogSuccess 清空日志成功! - + Too much opened files 打开的文件过多,无法继续操作! - + CopyLimit 拷贝字节超出限制 - + ErrOpenFileBelow 打开文件出现错误(由于权限不足),如下为打开错误的文件: @@ -1892,82 +1961,82 @@ Restart from the begining ? 字体 - - text which <i>should</i> be a <b>fair</b> test of the font - 文本<i>应该</i>是字体的<b>公平</b>测试 + + Takes Effect on Terminal as well + 该设置也会在终端有效 - + Tabulators && Whitespaces 制表符 && 空格 - + Tab width 制表符宽度 - + Show leading whitespaces 显示前导空格 - + Show tabs which are neither leading nor trailing 显示既不是前导也不是尾随的制表符 - + Show trailing whitespaces 显示尾随空格 - + Replace tabs by blanks 用空格替换制表符 - + Load && Save 加载和保存 - + Preserve line endings 保留行尾 - + Local 本地 - + Unix/Linux Unix/Linux - + DOS/Windows DOS/Windows - + Old Mac 老版 Mac - + Remove trailing spaces 删除尾随空格 - + Preserve trailing indent 保留尾部缩进 - + Edit 编辑 @@ -2165,7 +2234,7 @@ Do you wish to keep up to date by reloading the file? Unix - + untitled 未命名 @@ -2454,49 +2523,49 @@ Do you want them to be saved? QSnippetEdit - + Snippets 代码片段 - - + + Unsaved changes 未保存的更改 - + Do you want to save pattern changes to snippet %1 ? 是否要将样式模板更改保存至片段 %1 ? - + The current snippet data will be discarded. Do you want to continue? 当前片段数据将被丢弃。是否继续? - + Missing data 数据缺失 - + Please provide a name and a content to create a new snippet 请提供名称和内容以创建新的代码片段 - - + + Error 错误 - + Invalid snippet pattern. 无效的代码片段模板。 - + Please select a valid snippet to erase 请选择要删除的有效片段 @@ -4326,27 +4395,27 @@ Do you want them to be saved? ScriptingConsole - + Scripting console for WingHexExplorer 羽云十六进制编辑器脚本控制台 - + >>>> Powered by AngelScript <<<< >>>> 由 AngelScript 引擎提供支持 <<<< - + [Info] 【信息】 - + [Warn] 【警告】 - + [Error] 【错误】 @@ -4354,395 +4423,420 @@ Do you want them to be saved? ScriptingDialog - + ScriptEditor 脚本编辑器 - + ScriptPermissionDenied 因权限无法打开脚本 - + File 文件 - + Edit 编辑 - + Debugger 调试器 - + Setting 设置 - + About 关于 - + Basic 基础 - + New 新建 - + OpenF 打开文件 - + RecentFiles 最近打开 - + Reload 重新加载 - - + + Save 保存 - + SaveAs 另存为 - + General 基本 - + Undo 撤销 - + Redo 恢复 - + Cut 剪切 - + Copy 复制 - + Paste 粘贴 - + Delete 删除 - + Lookup 查询 - + Find 查找 - + Replace 替换 - + Goto 跳转 - + + Format + + + + + CodeFormat + + + + Display 显示 - + Scale 缩放 - + ResetScale 重置缩放 - + Window 窗体 - - + + Editor 编辑器 - + Tools 工具 - + Layout 布局 - + Fullscreen 全屏 - + RestoreLayout 恢复默认布局 - + BreakPoint 断点 - + ToggleBreakPoint 切换断点 - + AddBreakPoint 添加断点 - + Settings 设置 - + + Snippets + 代码片段 + + + + ClangFormat + Clang Format + + + Local 本地 - + Global 全局 - + Variables 变量 - + BreakPoints 断点 - + ConsoleOutput 输出 - + StackTrace 栈跟踪 - + Watch 监视 - - - - - - + + + + + + Error 错误 - + Too much opened files 打开的文件过多,无法继续操作! - + ConfirmSave 正在关闭未保存的脚本文件,你确定保存吗? - + ScriptSaveFailedClose 脚本保存失败,你仍确认关闭吗? - - + + ChooseFile 选择文件 - - - + + + FilePermission 因文件权限无法继续! - + ReloadSuccessfully 文件重新加载成功! - + ReloadUnSuccessfully 文件重新加载失败! - + ChooseSaveFile 请选择保存文件路径: - - + + SaveSuccessfully 保存成功! - + SaveUnSuccessfully 保存失败! - - + + FormatCodeFailed + + + + + CannotSave2RunScript 无法保存,故无法继续运行脚本。 - - + + ScriptStillRunning 脚本仍在运行,你确定要退出吗? - + ConfirmScriptSave 你尝试关闭程序,但仍存在未保存的脚本文件,你确定保存这些更改吗? - + View 视图 - + Debug 调试 - + Run 运行 - + RunWithDbg 调试运行 - + Pause 暂停 - + Continue 继续 - + Stop 停止 - + Restart 重启 - + StepInto 单步步入 - + StepOver 单步步过 - + StepOut 单步跳出 - + RemoveBreakPoint 删除断点 - + Info 信息 - + Software 软件 - + Sponsor 赞助 - + Wiki 网页 Wiki - + AboutQT 关于 QT @@ -4755,12 +4849,12 @@ Do you want them to be saved? 设置 - + TakeEffectRestart 该选项重启软件生效 - + This will reset all settings. Are you sure to continue? 这将会重置所有设置。你确认继续吗? diff --git a/mkinstaller/innoSetup/mkinnopak.py b/mkinstaller/innoSetup/mkinnopak.py index f2ef952..1e3bbff 100644 --- a/mkinstaller/innoSetup/mkinnopak.py +++ b/mkinstaller/innoSetup/mkinnopak.py @@ -45,7 +45,6 @@ def main(): "folder", help="A folder that has contained the binary build") parser.add_argument("-c", "--cc", help="where ISCC.exe locates", default="C:\Program Files (x86)\Inno Setup 6\ISCC.exe") parser.add_argument("-o", "--output", help="where to put the installer") - parser.add_argument("--no-build", action='store_false') args = parser.parse_args() @@ -231,7 +230,7 @@ Source: {#MyAppExePath}; DestDir: "{app}"; Flags: ignoreversion """ iss_content += r'Root: HKCR; Subkey: "*\shell\OpenWithWingHexExplorer"; ValueType: expandsz; ValueName: ""; ValueData: {cm:OpenWithWingHexExplorer}; Flags: uninsdeletekey' + '\n' - iss_content += r'Root: HKCR; Subkey: "*\shell\WingHexExplorer"; ValueType: expandsz; ValueName: "Icon"; ValueData: {app}\{#MyAppExeName}; Flags: uninsdeletekey' + '\n' + iss_content += r'Root: HKCR; Subkey: "*\shell\OpenWithWingHexExplorer"; ValueType: expandsz; ValueName: "Icon"; ValueData: {app}\{#MyAppExeName}; Flags: uninsdeletekey' + '\n' iss_content += r'Root: HKCR; Subkey: "*\shell\OpenWithWingHexExplorer\command"; ValueType: expandsz; ValueName: ""; ValueData: """{app}\{#MyAppExeName}"" ""%1"""; Flags: uninsdeletekey' + '\n' iss_content += """ @@ -249,19 +248,18 @@ Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChang with codecs.open(script_src,'w', "utf-8-sig") as iss: iss.write(iss_content) - if(args.build): - print(Fore.GREEN + ">> Copying finished, running ISCC building..." + Style.RESET_ALL) - - pak_out = "" - if args.output is None: - pak_out = exeDebPath - else: - pak_out = args.output - - ret = run_command_interactive([args.cc, f'/O{pak_out}', script_src]) - exit(ret) - - exit(0) + + print(Fore.GREEN + ">> Copying finished, running ISCC building..." + Style.RESET_ALL) + + pak_out = "" + if args.output is None: + pak_out = exeDebPath + else: + pak_out = args.output + + ret = run_command_interactive([args.cc, f'/O{pak_out}', script_src]) + exit(ret) + if __name__ == "__main__": main() diff --git a/resources.qrc b/resources.qrc index c22406b..0b96a13 100644 --- a/resources.qrc +++ b/resources.qrc @@ -10,6 +10,8 @@ images/clearhis.png images/clone.png images/closefile.png + images/codefmt.png + images/codeformat.png images/copy.png images/copyhex.png images/cut.png @@ -89,6 +91,7 @@ images/scriptfolderusr.png images/setting.png images/settingplugin.png + images/snippt.png images/soft.png images/sponsor.png images/sum.png @@ -100,6 +103,7 @@ images/win.png images/workspace.png images/writable.png + src/TESTCODE.as 3rdparty/QPathEdit/Fatcow-Farm-Fresh-Dialog.ico @@ -114,14 +118,13 @@ images/copy.png images/cut.png images/find.png + images/goto.png images/paste.png images/redo.png images/replace.png images/undo.png - images/goto.png - images/completion/classnew.png images/completion/CTvirtuals.png images/completion/CVclass.png images/completion/CVenum.png @@ -146,5 +149,6 @@ images/completion/CVstruct.png images/completion/CVtypedef.png images/completion/CVunion.png + images/completion/classnew.png diff --git a/src/TESTCODE.as b/src/TESTCODE.as new file mode 100644 index 0000000..be98c40 --- /dev/null +++ b/src/TESTCODE.as @@ -0,0 +1,19 @@ +#include + +class CMyClass { + int method() { a++; return a; } + int method() const { return a; } + int a; +} + +int main() { + // This is a script + + for (int i = 0; i < 5; ++i){ + print("hello world!") + } + + print("AngelScript for WingHexExplorer2 by wingsummer.") + + return 0; +} diff --git a/src/class/appmanager.cpp b/src/class/appmanager.cpp index 34881b0..4f62c92 100644 --- a/src/class/appmanager.cpp +++ b/src/class/appmanager.cpp @@ -19,6 +19,8 @@ #include +#include "class/clangformatmanager.h" +#include "class/langservice.h" #include "class/logger.h" #include "languagemanager.h" #include "settingmanager.h" @@ -58,6 +60,7 @@ AppManager::AppManager(int &argc, char *argv[]) SkinManager::instance(); LanguageManager::instance(); + ClangFormatManager::instance(); _w = new MainWindow; diff --git a/src/class/ascompletion.cpp b/src/class/ascompletion.cpp index 92d83d0..6318d05 100644 --- a/src/class/ascompletion.cpp +++ b/src/class/ascompletion.cpp @@ -82,8 +82,11 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) { // parser.parse(codes, this->editor()->fileName()); // QList nodes = parser.codeNodes(); - auto txt = c.line().text().left(c.columnNumber()); - auto code = txt.toUtf8(); + auto txt = c.line().text(); + if (txt.isEmpty()) { + return; + } + auto code = txt.left(c.columnNumber()).toUtf8(); auto p = code.data(); auto len = code.length(); @@ -140,21 +143,25 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) { } else if (eb.type == asTC_IDENTIFIER) { if (r != tokens.rend()) { auto pr = std::next(r); - if (pr->content == *SEMI_COLON_TRIGGER) { - if (pr != tokens.rend()) { - auto prr = std::next(pr); - auto ns = prr->content; + if (pr != tokens.rend()) { + if (pr->content == *SEMI_COLON_TRIGGER) { + if (pr != tokens.rend()) { + auto prr = std::next(pr); + auto ns = prr->content; - if (prr->type == asTC_IDENTIFIER) { - for (auto &n : _headerNodes) { - auto name = n->qualifiedName(); - if (name == ns) { - nodes << n; - break; + if (prr->type == asTC_IDENTIFIER) { + for (auto &n : _headerNodes) { + auto name = n->qualifiedName(); + if (name == ns) { + nodes << n; + break; + } } + } else { + return; } } else { - return; + applyEmptyNsNode(nodes); } } else { applyEmptyNsNode(nodes); @@ -186,20 +193,22 @@ void AsCompletion::complete(const QDocumentCursor &c, const QString &trigger) { } else if (trigger == *LEFT_PARE_TRIGGER) { if (r != tokens.rend()) { auto pr = std::next(r); - if (pr->content == *SEMI_COLON_TRIGGER) { - if (pr != tokens.rend()) { - auto prr = std::next(pr); - auto ns = prr->content; - if (prr->type == asTC_IDENTIFIER) { - for (auto &n : _headerNodes) { - auto name = n->qualifiedName(); - if (name == ns) { - nodes << n; - break; + if (pr != tokens.rend()) { + if (pr->content == *SEMI_COLON_TRIGGER) { + if (pr != tokens.rend()) { + auto prr = std::next(pr); + auto ns = prr->content; + if (prr->type == asTC_IDENTIFIER) { + for (auto &n : _headerNodes) { + auto name = n->qualifiedName(); + if (name == ns) { + nodes << n; + break; + } } + } else { + return; } - } else { - return; } } } @@ -284,6 +293,10 @@ void AsCompletion::applyEmptyNsNode(QList &nodes) { nodes = _emptyNsNodes; } +QCodeCompletionWidget *AsCompletion::codeCompletionWidget() const { + return pPopup; +} + void AsCompletion::setEditor(QEditor *e) { QCodeCompletionEngine::setEditor(e); pPopup->setEditor(e); diff --git a/src/class/ascompletion.h b/src/class/ascompletion.h index c67091c..b2fda95 100644 --- a/src/class/ascompletion.h +++ b/src/class/ascompletion.h @@ -33,10 +33,13 @@ public: virtual QCodeCompletionEngine *clone() override; virtual QString language() const override; + virtual QStringList extensions() const override; virtual void setEditor(QEditor *e) override; + QCodeCompletionWidget *codeCompletionWidget() const; + protected: virtual void complete(const QDocumentCursor &c, const QString &trigger) override; diff --git a/src/class/clangformatmanager.cpp b/src/class/clangformatmanager.cpp new file mode 100644 index 0000000..aeb7f6b --- /dev/null +++ b/src/class/clangformatmanager.cpp @@ -0,0 +1,171 @@ +#include "clangformatmanager.h" +#include "settings/settings.h" + +#include +#include +#include + +Q_GLOBAL_STATIC_WITH_ARGS(QString, CLANG_ENABLE_FMT, ("clang.enabled")) +Q_GLOBAL_STATIC_WITH_ARGS(QString, CLANG_AUTO_FMT, ("clang.auto")) +Q_GLOBAL_STATIC_WITH_ARGS(QString, CLANG_STYLE, ("clang.style")) + +ClangFormatManager::ClangFormatManager() { + // load config + HANDLE_CONFIG; + + READ_CONFIG_BOOL(m_enabled, CLANG_ENABLE_FMT, true); + READ_CONFIG_BOOL(m_autoFmt, CLANG_AUTO_FMT, true); + + auto styles = supportedStyles(); + READ_CONFIG_STRING(m_clangStyle, CLANG_STYLE, styles.first()); + + // ok find + refind(); +} + +ClangFormatManager &ClangFormatManager::instance() { + static ClangFormatManager ins; + return ins; +} + +bool ClangFormatManager::exists() { return !m_clangPath.isEmpty(); } + +bool ClangFormatManager::refind() { + m_clangPath.clear(); + + // Get the PATH environment variable + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + QString pathEnv = env.value("PATH"); + + // Split the PATH variable into individual directories + QStringList paths = pathEnv.split(QDir::listSeparator()); + + auto name = getProgramName(); + for (auto &path : paths) { + QDir dir(path); + + auto pp = dir.absoluteFilePath(name); + QFileInfo fileInfo(pp); + + // Check if the file exists and is executable + if (fileInfo.exists() && fileInfo.isExecutable()) { + m_clangPath = pp; + bool ok; + auto ret = runClangFormat({"--version"}, QString(), ok); + if (ok) { + auto vstr = QStringLiteral("clang-format version "); + if (ret.startsWith(vstr)) { + m_clangVersion = ret.mid(vstr.length()).simplified(); + return true; + } else { + m_clangPath.clear(); + } + } + } + } + return false; +} + +QString ClangFormatManager::getProgramName() { +#ifdef Q_OS_WIN + return QStringLiteral("clang-format.exe"); +#else + return QStringLiteral("clang-format"); +#endif +} + +QStringList ClangFormatManager::supportedStyles() { + static QStringList styles{"LLVM", "GNU", "Google", "Chromium", + "Microsoft", "Mozilla", "WebKit", "Custom"}; + return styles; +} + +QString ClangFormatManager::formatCode(const QString &codes, bool &ok) { + auto styles = supportedStyles(); + auto fmtind = styles.indexOf(m_clangStyle); + Q_ASSERT(fmtind >= 0); + if (fmtind != styles.size() - 1) { + auto style = + QStringLiteral("--style={BasedOnStyle: %1, IndentWidth: %2}") + .arg(m_clangStyle) + .arg(m_identWidth); + auto ret = runClangFormat( + {style, QStringLiteral("--assume-filename=wing.cpp")}, codes, ok); + return ret; + } else { + return runClangFormat({}, codes, ok); + } +} + +QString ClangFormatManager::runClangFormat(const QStringList ¶ms, + const QString &stdinput, bool &ok) { + if (!exists()) { + ok = false; + return {}; + } + + QProcess process; + process.setProgram(m_clangPath); + process.setArguments(params); + + process.start(); + if (!process.waitForStarted()) { + process.kill(); // Kill the process if it timed out + process.waitForFinished(); // Ensure process has terminated + ok = false; + return {}; + } + + process.write(stdinput.toUtf8()); + process.closeWriteChannel(); + + bool finished = process.waitForFinished(-1); + if (finished) { + auto data = process.readAllStandardOutput(); + auto error = process.readAllStandardError(); + ok = error.isEmpty(); + if (ok) { + return QString::fromUtf8(data); + } else { + return {}; + } + } else { + process.kill(); // Kill the process if it timed out + process.waitForFinished(); // Ensure process has terminated + ok = false; + return {}; + } +} + +quint32 ClangFormatManager::identWidth() const { return m_identWidth; } + +void ClangFormatManager::setIdentWidth(quint32 newIdentWidth) { + m_identWidth = newIdentWidth; +} + +QString ClangFormatManager::clangStyle() const { return m_clangStyle; } + +void ClangFormatManager::setClangStyle(const QString &newClangStyle) { + m_clangStyle = newClangStyle; +} + +bool ClangFormatManager::enabled() const { return m_enabled; } + +void ClangFormatManager::setEnabled(bool newEnabled) { m_enabled = newEnabled; } + +QString ClangFormatManager::path() const { return m_clangPath; } + +QString ClangFormatManager::customStyleString() const { + return m_customStyleString; +} + +void ClangFormatManager::setCustomStyleString( + const QString &newCustomStyleString) { + m_customStyleString = newCustomStyleString; +} + +QString ClangFormatManager::version() const { return m_clangVersion; } + +int ClangFormatManager::runningTimeout() const { return m_timeout; } + +void ClangFormatManager::setRunningTimeout(int msecs) { m_timeout = msecs; } diff --git a/src/class/clangformatmanager.h b/src/class/clangformatmanager.h new file mode 100644 index 0000000..5afbed2 --- /dev/null +++ b/src/class/clangformatmanager.h @@ -0,0 +1,63 @@ +#ifndef CLANGFORMATMANAGER_H +#define CLANGFORMATMANAGER_H + +#include + +class ClangFormatManager { +public: + static ClangFormatManager &instance(); + +public: + bool exists(); + + bool refind(); + + static QString getProgramName(); + + static QStringList supportedStyles(); + + QString formatCode(const QString &codes, bool &ok); + + int runningTimeout() const; + + void setRunningTimeout(int msecs); + + QString version() const; + + QString customStyleString() const; + + void setCustomStyleString(const QString &newCustomStyleString); + + QString path() const; + + bool enabled() const; + void setEnabled(bool newEnabled); + + QString clangStyle() const; + void setClangStyle(const QString &newClangStyle); + + quint32 identWidth() const; + void setIdentWidth(quint32 newIdentWidth); + +private: + explicit ClangFormatManager(); + + QString runClangFormat(const QStringList ¶ms, const QString &stdinput, + bool &ok); + +private: + bool m_enabled = true; + bool m_autoFmt = true; + + quint32 m_identWidth = 4; + + QString m_clangPath; + QString m_clangVersion; + QString m_clangStyle; + + QString m_customStyleString; + + int m_timeout = 5000; +}; + +#endif // CLANGFORMATMANAGER_H diff --git a/src/class/langservice.cpp b/src/class/langservice.cpp index 3d5cbac..da35368 100644 --- a/src/class/langservice.cpp +++ b/src/class/langservice.cpp @@ -4,6 +4,7 @@ #include "class/skinmanager.h" #include "qdocument.h" #include "qeditor.h" +#include "qformat.h" #include "qformatscheme.h" #include "qsnippetmanager.h" @@ -25,11 +26,22 @@ void LangService::init(asIScriptEngine *engine) { new QFormatScheme(QStringLiteral(":/qcodeedit/as_light.qxf"), this); break; } + + // additional formats + QFormat fmt; + fmt.foreground = Qt::red; + format->setFormat(QStringLiteral("stderr"), fmt); + fmt.foreground = QColorConstants::Svg::gold; + format->setFormat(QStringLiteral("stdwarn"), fmt); + fmt.foreground = Qt::cyan; + format->setFormat(QStringLiteral("stdout"), fmt); + QDocument::setDefaultFormatScheme(format); m_language = new QLanguageFactory(format, this); m_language->addDefinitionPath(QStringLiteral(":/qcodeedit")); - m_language->addCompletionEngine(new AsCompletion(engine, this)); + _completion = new AsCompletion(engine, this); + m_language->addCompletionEngine(_completion); m_snippetManager = new QSnippetManager(this); m_snipbind = new QSnippetBinding(m_snippetManager); diff --git a/src/class/langservice.h b/src/class/langservice.h index d1235f4..fd93905 100644 --- a/src/class/langservice.h +++ b/src/class/langservice.h @@ -1,6 +1,7 @@ #ifndef LANGSERVICE_H #define LANGSERVICE_H +#include "class/ascompletion.h" #include "qlanguagefactory.h" #include "qsnippetbinding.h" @@ -33,6 +34,8 @@ private: QLanguageFactory *m_language = nullptr; QSnippetManager *m_snippetManager = nullptr; + AsCompletion *_completion = nullptr; + Q_DISABLE_COPY_MOVE(LangService) }; diff --git a/src/class/settingmanager.cpp b/src/class/settingmanager.cpp index f49ec2a..9efd78f 100644 --- a/src/class/settingmanager.cpp +++ b/src/class/settingmanager.cpp @@ -19,68 +19,17 @@ #include "class/logger.h" #include "class/skinmanager.h" +#include "settings/settings.h" #include "utilities.h" #include #include -#include -QString getRealContent(const QString &value) { return value; } - -template -QString getRealContent(T &value) { - static_assert(std::is_same()); - return *value; -} - -#define HANDLE_CONFIG \ - QSettings set(QStringLiteral(APP_ORG), QStringLiteral(APP_NAME)) - -#define CONFIG set - -#define WRITE_CONFIG(config, dvalue) \ +#define WRITE_CONFIG_SET(config, dvalue) \ if (this->_setUnsaved.testFlag(SETTING_ITEM::config)) { \ - set.setValue(getRealContent(config), dvalue); \ + WRITE_CONFIG(config, dvalue); \ _setUnsaved.setFlag(SettingManager::SETTING_ITEM::config, false); \ } -#define READ_CONFIG(config, dvalue) set.value(getRealContent(config), dvalue) - -#define READ_CONFIG_SAFE(var, config, dvalue, func) \ - { \ - auto b = false; \ - var = READ_CONFIG(config, dvalue).func(&b); \ - if (!b) { \ - var = dvalue; \ - } \ - } - -#define READ_CONFIG_INT(var, config, dvalue) \ - READ_CONFIG_SAFE(var, config, dvalue, toInt) - -#define READ_CONFIG_BOOL(var, config, dvalue) \ - var = READ_CONFIG(config, dvalue).toBool() - -#define READ_CONFIG_QSIZETYPE(var, config, dvalue) \ - READ_CONFIG_SAFE(var, config, dvalue, toLongLong) - -#define READ_CONFIG_INT_POSITIVE(var, config, dvalue) \ - { \ - Q_ASSERT(dvalue > 0); \ - READ_CONFIG_SAFE(var, config, dvalue, toInt); \ - if (var <= 0) { \ - var = dvalue; \ - } \ - } - -#define READ_CONFIG_DOUBLE_POSITIVE(var, config, dvalue) \ - { \ - Q_ASSERT(dvalue > 0); \ - READ_CONFIG_SAFE(var, config, dvalue, toDouble); \ - if (var <= 0) { \ - var = dvalue; \ - } \ - } - Q_GLOBAL_STATIC_WITH_ARGS(QString, DOCK_LAYOUT, ("dock.layout")) Q_GLOBAL_STATIC_WITH_ARGS(QString, SCRIPT_DOCK_LAYOUT, ("script.layout")) Q_GLOBAL_STATIC_WITH_ARGS(QString, APP_LASTUSED_PATH, ("app.lastusedpath")) @@ -144,8 +93,8 @@ void SettingManager::load() { m_dockLayout = READ_CONFIG(DOCK_LAYOUT, QByteArray()).toByteArray(); m_scriptDockLayout = READ_CONFIG(SCRIPT_DOCK_LAYOUT, QByteArray()).toByteArray(); - m_appFontFamily = - READ_CONFIG(APP_FONTFAMILY, _defaultFont.family()).toString(); + READ_CONFIG_STRING(m_appFontFamily, APP_FONTFAMILY, _defaultFont.family()); + // check font QFont fm(m_appFontFamily); if (!QFontInfo(fm).exactMatch()) { @@ -373,79 +322,79 @@ void SettingManager::setDefaultWinState(Qt::WindowState newDefaultWinState) { void SettingManager::save(SETTINGS cat) { HANDLE_CONFIG; - WRITE_CONFIG(DOCK_LAYOUT, m_dockLayout); - WRITE_CONFIG(SCRIPT_DOCK_LAYOUT, m_scriptDockLayout); - WRITE_CONFIG(EDITOR_RECENTFILES, getVarList(m_recentHexFiles)); - WRITE_CONFIG(SCRIPT_RECENTFILES, getVarList(m_recentScriptFiles)); - WRITE_CONFIG(APP_LASTUSED_PATH, m_lastUsedPath); + WRITE_CONFIG_SET(DOCK_LAYOUT, m_dockLayout); + WRITE_CONFIG_SET(SCRIPT_DOCK_LAYOUT, m_scriptDockLayout); + WRITE_CONFIG_SET(EDITOR_RECENTFILES, getVarList(m_recentHexFiles)); + WRITE_CONFIG_SET(SCRIPT_RECENTFILES, getVarList(m_recentScriptFiles)); + WRITE_CONFIG_SET(APP_LASTUSED_PATH, m_lastUsedPath); if (cat.testFlag(SETTING::APP)) { - WRITE_CONFIG(SKIN_THEME, m_themeID); - WRITE_CONFIG(APP_LANGUAGE, m_defaultLang); - WRITE_CONFIG(APP_FONTFAMILY, m_appFontFamily); - WRITE_CONFIG(APP_FONTSIZE, m_appfontSize); - WRITE_CONFIG(APP_WINDOWSIZE, m_defaultWinState); + WRITE_CONFIG_SET(SKIN_THEME, m_themeID); + WRITE_CONFIG_SET(APP_LANGUAGE, m_defaultLang); + WRITE_CONFIG_SET(APP_FONTFAMILY, m_appFontFamily); + WRITE_CONFIG_SET(APP_FONTSIZE, m_appfontSize); + WRITE_CONFIG_SET(APP_WINDOWSIZE, m_defaultWinState); } if (cat.testFlag(SETTING::PLUGIN)) { - WRITE_CONFIG(PLUGIN_ENABLE, m_enablePlugin); - WRITE_CONFIG(PLUGIN_ENABLE_ROOT, m_enablePlgInRoot); + WRITE_CONFIG_SET(PLUGIN_ENABLE, m_enablePlugin); + WRITE_CONFIG_SET(PLUGIN_ENABLE_ROOT, m_enablePlgInRoot); } if (cat.testFlag(SETTING::EDITOR)) { - WRITE_CONFIG(EDITOR_FONTSIZE, m_editorfontSize); - WRITE_CONFIG(EDITOR_SHOW_ADDR, m_editorShowHeader); - WRITE_CONFIG(EDITOR_SHOW_COL, m_editorShowcol); - WRITE_CONFIG(EDITOR_SHOW_TEXT, m_editorShowtext); - WRITE_CONFIG(EDITOR_ENCODING, m_editorEncoding); - WRITE_CONFIG(EDITOR_COPY_LIMIT, m_copylimit); - WRITE_CONFIG(EDITOR_DECSTRLIMIT, m_decodeStrlimit); + WRITE_CONFIG_SET(EDITOR_FONTSIZE, m_editorfontSize); + WRITE_CONFIG_SET(EDITOR_SHOW_ADDR, m_editorShowHeader); + WRITE_CONFIG_SET(EDITOR_SHOW_COL, m_editorShowcol); + WRITE_CONFIG_SET(EDITOR_SHOW_TEXT, m_editorShowtext); + WRITE_CONFIG_SET(EDITOR_ENCODING, m_editorEncoding); + WRITE_CONFIG_SET(EDITOR_COPY_LIMIT, m_copylimit); + WRITE_CONFIG_SET(EDITOR_DECSTRLIMIT, m_decodeStrlimit); } if (cat.testFlag(SETTING::SCRIPT)) { - WRITE_CONFIG(SCRIPT_ALLOW_USRSCRIPT_INROOT, m_allowUsrScriptInRoot); - WRITE_CONFIG(SCRIPT_USRHIDECATS, m_usrHideCats); - WRITE_CONFIG(SCRIPT_SYSHIDECATS, m_sysHideCats); + WRITE_CONFIG_SET(SCRIPT_ALLOW_USRSCRIPT_INROOT, m_allowUsrScriptInRoot); + WRITE_CONFIG_SET(SCRIPT_USRHIDECATS, m_usrHideCats); + WRITE_CONFIG_SET(SCRIPT_SYSHIDECATS, m_sysHideCats); } if (cat.testFlag(SETTING::OTHER)) { - WRITE_CONFIG(OTHER_USESYS_FILEDIALOG, m_useNativeFileDialog); + WRITE_CONFIG_SET(OTHER_USESYS_FILEDIALOG, m_useNativeFileDialog); #ifdef WINGHEX_USE_FRAMELESS - WRITE_CONFIG(OTHER_USE_NATIVE_TITLEBAR, m_useNativeTitleBar); + WRITE_CONFIG_SET(OTHER_USE_NATIVE_TITLEBAR, m_useNativeTitleBar); #endif - WRITE_CONFIG(OTHER_LOG_LEVEL, m_logLevel); + WRITE_CONFIG_SET(OTHER_LOG_LEVEL, m_logLevel); } } void SettingManager::reset(SETTINGS cat) { HANDLE_CONFIG; if (cat.testFlag(SETTING::APP)) { - WRITE_CONFIG(SKIN_THEME, 0); - WRITE_CONFIG(APP_LANGUAGE, QString()); - WRITE_CONFIG(APP_FONTFAMILY, _defaultFont.family()); - WRITE_CONFIG(APP_FONTSIZE, _defaultFont.pointSize()); - WRITE_CONFIG(APP_WINDOWSIZE, Qt::WindowMaximized); + WRITE_CONFIG_SET(SKIN_THEME, 0); + WRITE_CONFIG_SET(APP_LANGUAGE, QString()); + WRITE_CONFIG_SET(APP_FONTFAMILY, _defaultFont.family()); + WRITE_CONFIG_SET(APP_FONTSIZE, _defaultFont.pointSize()); + WRITE_CONFIG_SET(APP_WINDOWSIZE, Qt::WindowMaximized); } if (cat.testFlag(SETTING::PLUGIN)) { - WRITE_CONFIG(PLUGIN_ENABLE, true); - WRITE_CONFIG(PLUGIN_ENABLE_ROOT, false); + WRITE_CONFIG_SET(PLUGIN_ENABLE, true); + WRITE_CONFIG_SET(PLUGIN_ENABLE_ROOT, false); } if (cat.testFlag(SETTING::EDITOR)) { - WRITE_CONFIG(EDITOR_FONTSIZE, _defaultFont.pointSize()); - WRITE_CONFIG(EDITOR_SHOW_ADDR, true); - WRITE_CONFIG(EDITOR_SHOW_COL, true); - WRITE_CONFIG(EDITOR_SHOW_TEXT, true); - WRITE_CONFIG(EDITOR_ENCODING, QStringLiteral("ASCII")); - WRITE_CONFIG(EDITOR_FIND_MAXCOUNT, 100); - WRITE_CONFIG(EDITOR_COPY_LIMIT, 100); - WRITE_CONFIG(EDITOR_DECSTRLIMIT, 10); + WRITE_CONFIG_SET(EDITOR_FONTSIZE, _defaultFont.pointSize()); + WRITE_CONFIG_SET(EDITOR_SHOW_ADDR, true); + WRITE_CONFIG_SET(EDITOR_SHOW_COL, true); + WRITE_CONFIG_SET(EDITOR_SHOW_TEXT, true); + WRITE_CONFIG_SET(EDITOR_ENCODING, QStringLiteral("ASCII")); + WRITE_CONFIG_SET(EDITOR_FIND_MAXCOUNT, 100); + WRITE_CONFIG_SET(EDITOR_COPY_LIMIT, 100); + WRITE_CONFIG_SET(EDITOR_DECSTRLIMIT, 10); } if (cat.testFlag(SETTING::SCRIPT)) { - WRITE_CONFIG(SCRIPT_ALLOW_USRSCRIPT_INROOT, false); - WRITE_CONFIG(SCRIPT_USRHIDECATS, QStringList()); - WRITE_CONFIG(SCRIPT_SYSHIDECATS, QStringList()); + WRITE_CONFIG_SET(SCRIPT_ALLOW_USRSCRIPT_INROOT, false); + WRITE_CONFIG_SET(SCRIPT_USRHIDECATS, QStringList()); + WRITE_CONFIG_SET(SCRIPT_SYSHIDECATS, QStringList()); } if (cat.testFlag(SETTING::OTHER)) { - WRITE_CONFIG(OTHER_USESYS_FILEDIALOG, true); + WRITE_CONFIG_SET(OTHER_USESYS_FILEDIALOG, true); #ifdef WINGHEX_USE_FRAMELESS - WRITE_CONFIG(OTHER_USE_NATIVE_TITLEBAR, false); + WRITE_CONFIG_SET(OTHER_USE_NATIVE_TITLEBAR, false); #endif - WRITE_CONFIG(OTHER_LOG_LEVEL, Logger::defaultLevel()); + WRITE_CONFIG_SET(OTHER_LOG_LEVEL, Logger::defaultLevel()); } load(); } diff --git a/src/control/qcodecompletionwidget.cpp b/src/control/qcodecompletionwidget.cpp index 588770d..0632db3 100644 --- a/src/control/qcodecompletionwidget.cpp +++ b/src/control/qcodecompletionwidget.cpp @@ -80,7 +80,7 @@ void QCodeCompletionWidget::adjustGeometry() { QDocumentCursor cursor = e->cursor(); QDocumentLine line = cursor.line(); const QRect lrect = e->lineRect(cursor.lineNumber()); - const QFontMetrics fm = QDocument::fontMetrics(); + const QFontMetrics fm = e->document()->fontMetrics(); int h = 0, w = 300, ls = fm.lineSpacing(), y = lrect.y(), x = line.cursorToX(cursor.columnNumber() + offset); @@ -165,6 +165,8 @@ void QCodeCompletionWidget::setTemporaryNodes(const QList &l) { m_temps = l; } +bool QCodeCompletionWidget::isCompleting() const { return _completing; } + void QCodeCompletionWidget::clear() { pModel->clear(); } void QCodeCompletionWidget::popup() { @@ -191,6 +193,8 @@ void QCodeCompletionWidget::popup() { } void QCodeCompletionWidget::complete(const QModelIndex &index) { + _completing = true; + QEditor *e = editor(); if (!index.isValid() || !e) @@ -226,6 +230,8 @@ void QCodeCompletionWidget::complete(const QModelIndex &index) { } e->setFocus(); + + _completing = false; } void QCodeCompletionWidget::showEvent(QShowEvent *e) { diff --git a/src/control/qcodecompletionwidget.h b/src/control/qcodecompletionwidget.h index 24afd7b..67bc7b9 100644 --- a/src/control/qcodecompletionwidget.h +++ b/src/control/qcodecompletionwidget.h @@ -78,6 +78,8 @@ public: void setTemporaryNodes(const QList &l); + bool isCompleting() const; + public slots: void popup(); void clear(); @@ -102,6 +104,7 @@ private: QCodeCompletionModel *pModel; QPointer pEditor; QList m_temps; + bool _completing = false; }; #endif // _QCOMPLETION_WIDGET_H_ diff --git a/src/control/scripteditor.cpp b/src/control/scripteditor.cpp index 6368680..b148056 100644 --- a/src/control/scripteditor.cpp +++ b/src/control/scripteditor.cpp @@ -65,7 +65,11 @@ ScriptEditor::ScriptEditor(QWidget *parent) true); } -ScriptEditor::~ScriptEditor() { m_editor->editor()->document(); } +ScriptEditor::~ScriptEditor() { + auto e = m_editor->editor(); + e->disconnect(); + e->document()->disconnect(); +} QString ScriptEditor::fileName() const { return m_editor->editor()->fileName(); diff --git a/src/control/scriptingconsole.cpp b/src/control/scriptingconsole.cpp index 2ac8ce7..da187e8 100644 --- a/src/control/scriptingconsole.cpp +++ b/src/control/scriptingconsole.cpp @@ -23,24 +23,6 @@ #include ScriptingConsole::ScriptingConsole(QWidget *parent) : QConsoleWidget(parent) { - // m_stdoutFmtTitle = this->currentCharFormat(); - - m_stdoutFmtWarn = m_stdoutFmtContent = - channelCharFormat(ConsoleChannel::StandardOutput); - - m_stdoutFmtContent.setForeground(Qt::green); - m_stdoutFmtWarn.setForeground(QColorConstants::Svg::gold); - - setChannelCharFormat(ConsoleChannel::StandardOutput, m_stdoutFmtContent); - - _s.setDevice(this->device()); - stdWarn(tr("Scripting console for WingHexExplorer")); - _s << Qt::endl; - stdWarn(tr(">>>> Powered by AngelScript <<<<")); - _s << Qt::endl << Qt::endl; - appendCommandPrompt(); - setMode(Input); - auto shortCut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_L), this); connect(shortCut, &QShortcut::activated, this, &ScriptingConsole::clearConsole); @@ -53,7 +35,7 @@ void ScriptingConsole::stdOut(const QString &str) { writeStdOut(str); } void ScriptingConsole::stdErr(const QString &str) { writeStdErr(str); } void ScriptingConsole::stdWarn(const QString &str) { - write(str, m_stdoutFmtWarn); + write(str, QStringLiteral("stdwarn")); } void ScriptingConsole::newLine() { _s << Qt::endl; } @@ -91,6 +73,17 @@ void ScriptingConsole::init() { &ScriptingConsole::consoleCommand); } +void ScriptingConsole::initOutput() { + _s.setDevice(this->device()); + stdWarn(tr("Scripting console for WingHexExplorer")); + + _s << Qt::endl; + stdWarn(tr(">>>> Powered by AngelScript <<<<")); + _s << Qt::endl << Qt::endl; + appendCommandPrompt(); + setMode(Input); +} + void ScriptingConsole::clearConsole() { setMode(Output); clear(); @@ -131,7 +124,7 @@ QString ScriptingConsole::getInput() { if (!_cmdQueue.isEmpty()) { instr = _cmdQueue.takeFirst(); setMode(Output); - write(instr, QTextCharFormat()); + QConsoleWidget::write(instr); setMode(Input); break; } @@ -165,7 +158,7 @@ void ScriptingConsole::appendCommandPrompt(bool storeOnly) { _lastCommandPrompt = storeOnly; - write(commandPrompt, m_stdoutFmtTitle); + QConsoleWidget::write(commandPrompt); } ScriptMachine *ScriptingConsole::machine() const { return _sp; } diff --git a/src/control/scriptingconsole.h b/src/control/scriptingconsole.h index 3df5519..7d659f1 100644 --- a/src/control/scriptingconsole.h +++ b/src/control/scriptingconsole.h @@ -45,6 +45,8 @@ public slots: void init(); + void initOutput(); + void clearConsole(); void pushInputCmd(const QString &cmd); @@ -64,10 +66,6 @@ private: QMutex _queueLocker; bool _waitforRead = false; - QTextCharFormat m_stdoutFmtTitle; - QTextCharFormat m_stdoutFmtContent; - QTextCharFormat m_stdoutFmtWarn; - std::function _getInputFn; }; diff --git a/src/dialog/mainwindow.cpp b/src/dialog/mainwindow.cpp index d61c67b..6cf3277 100644 --- a/src/dialog/mainwindow.cpp +++ b/src/dialog/mainwindow.cpp @@ -121,7 +121,6 @@ MainWindow::MainWindow(QWidget *parent) : FramelessMainWindow(parent) { layout->addWidget(m_status); buildUpContent(cw); - m_scriptDialog = new ScriptingDialog(this); m_toolBtneditors.value(ToolButtonIndex::EDITOR_VIEWS)->setEnabled(false); @@ -144,13 +143,17 @@ MainWindow::MainWindow(QWidget *parent) : FramelessMainWindow(parent) { plg.LoadPlugin(); // At this time, AngelScript service plugin has started m_scriptConsole->init(); - m_scriptDialog->initConsole(); ScriptManager::instance().attach(m_scriptConsole); auto &langins = LangService::instance(); langins.init(m_scriptConsole->machine()->engine()); langins.applyLanguageSerivce(m_scriptConsole); + m_scriptConsole->initOutput(); + + m_scriptDialog = new ScriptingDialog(this); + m_scriptDialog->initConsole(); + // load the model Q_ASSERT(m_scriptConsole && m_scriptConsole->machine()); m_varshowtable->setModel(m_scriptConsole->consoleMachine()->model()); diff --git a/src/dialog/scriptingdialog.cpp b/src/dialog/scriptingdialog.cpp index 9c349f0..ed6553d 100644 --- a/src/dialog/scriptingdialog.cpp +++ b/src/dialog/scriptingdialog.cpp @@ -20,6 +20,7 @@ #include "QWingRibbon/ribbontabcontent.h" #include "Qt-Advanced-Docking-System/src/DockAreaWidget.h" #include "aboutsoftwaredialog.h" +#include "class/clangformatmanager.h" #include "class/langservice.h" #include "class/languagemanager.h" #include "class/qkeysequences.h" @@ -27,12 +28,14 @@ #include "class/wingfiledialog.h" #include "class/wingmessagebox.h" #include "control/toast.h" +#include "qcodeeditwidget/qdocumentswaptextcommand.h" #include "qcodeeditwidget/qeditconfig.h" #include "qcodeeditwidget/qsnippetedit.h" #include "qdocumentline.h" #include "qeditor.h" #include "qformatscheme.h" #include "qlinemarksinfocenter.h" +#include "settings/clangformatsetdialog.h" #include #include @@ -375,6 +378,12 @@ RibbonTabContent *ScriptingDialog::buildEditPage(RibbonTabContent *tab) { shortcuts.keySequence(QKeySequences::Key::GOTO)); } + { + auto pannel = tab->addGroup(tr("Format")); + addPannelAction(pannel, QStringLiteral("codefmt"), tr("CodeFormat"), + &ScriptingDialog::on_codefmt); + } + return tab; } @@ -508,8 +517,13 @@ RibbonTabContent *ScriptingDialog::buildSettingPage(RibbonTabContent *tab) { auto pannel = tab->addGroup(tr("Settings")); addPannelAction(pannel, QStringLiteral("file"), tr("Editor"), - &ScriptingDialog::on_setting); - + [=] { m_setdialog->showConfig(QStringLiteral("Edit")); }); + addPannelAction(pannel, QStringLiteral("snippt"), tr("Snippets"), [=] { + m_setdialog->showConfig(QStringLiteral("Snippets")); + }); + addPannelAction( + pannel, QStringLiteral("codeformat"), tr("ClangFormat"), + [=] { m_setdialog->showConfig(QStringLiteral("ClangFormat")); }); return tab; } @@ -572,7 +586,6 @@ ScriptingDialog::buildUpOutputShowDock(ads::CDockManager *dock, ads::DockWidgetArea area, ads::CDockAreaWidget *areaw) { m_consoleout = new ScriptingConsole(this); - m_consoleout->clear(); m_consoleout->setMode(ScriptingConsole::Output); auto dw = buildDockWidget(dock, QStringLiteral("ConsoleOutput"), tr("ConsoleOutput"), m_consoleout); @@ -954,6 +967,9 @@ void ScriptingDialog::buildUpSettingDialog() { new QSnippetEdit(LangService::instance().snippetManager(), m_setdialog); m_setdialog->addPage(snip); + auto clang = new ClangFormatSetDialog(m_setdialog); + m_setdialog->addPage(clang); + m_setdialog->build(); } @@ -1239,7 +1255,23 @@ void ScriptingDialog::on_gotoline() { } } -void ScriptingDialog::on_setting() { m_setdialog->showConfig(); } +void ScriptingDialog::on_codefmt() { + auto e = currentEditor(); + if (e) { + auto editor = e->editor(); + auto codes = editor->text(); + bool ok; + + auto fmtcodes = ClangFormatManager::instance().formatCode(codes, ok); + if (ok) { + auto doc = editor->document(); + doc->execute(new QDocumentSwapTextCommand(fmtcodes, doc)); + } else { + Toast::toast(this, NAMEICONRES(QStringLiteral("codefmt")), + tr("FormatCodeFailed")); + } + } +} void ScriptingDialog::on_about() { AboutSoftwareDialog().exec(); } diff --git a/src/dialog/scriptingdialog.h b/src/dialog/scriptingdialog.h index 63f2911..88bf0e8 100644 --- a/src/dialog/scriptingdialog.h +++ b/src/dialog/scriptingdialog.h @@ -227,7 +227,8 @@ private slots: void on_replace(); void on_gotoline(); - void on_setting(); + void on_codefmt(); + void on_about(); void on_sponsor(); void on_wiki(); diff --git a/src/dialog/settingdialog.cpp b/src/dialog/settingdialog.cpp index bcdee24..7a00cd0 100644 --- a/src/dialog/settingdialog.cpp +++ b/src/dialog/settingdialog.cpp @@ -86,6 +86,8 @@ void SettingDialog::showConfig(const QString &id) { ui->listWidget->setCurrentRow(0); } ui->listWidget->setCurrentRow(m_pages.indexOf(*r)); + Utilities::moveToCenter(this); + _dialog->exec(); } void SettingDialog::toastTakeEffectReboot() { diff --git a/src/qcodeeditwidget/qdocumentswaptextcommand.cpp b/src/qcodeeditwidget/qdocumentswaptextcommand.cpp new file mode 100644 index 0000000..1719cac --- /dev/null +++ b/src/qcodeeditwidget/qdocumentswaptextcommand.cpp @@ -0,0 +1,42 @@ +/*============================================================================== +** Copyright (C) 2024-2027 WingSummer +** +** This program is free software: you can redistribute it and/or modify it under +** the terms of the GNU Affero General Public License as published by the Free +** Software Foundation, version 3. +** +** This program is distributed in the hope that it will be useful, but WITHOUT +** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +** FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +** details. +** +** You should have received a copy of the GNU Affero General Public License +** along with this program. If not, see . +** ============================================================================= +*/ + +#include "qdocumentswaptextcommand.h" + +#include "qdocument_p.h" + +QDocumentSwapTextCommand::QDocumentSwapTextCommand(const QString &text, + QDocument *doc, + QDocumentCommand *p) + : QDocumentCommand(Command::Custom, doc, p), oldtext(m_doc->text()), + newtext(text) {} + +void QDocumentSwapTextCommand::undo() { + m_doc->setText(oldtext); + for (int i = 0; i < m_doc->lineCount(); ++i) { + auto line = m_doc->line(i); + markUndone(line.handle()); + } +} + +void QDocumentSwapTextCommand::redo() { + m_doc->setText(newtext); + for (int i = 0; i < m_doc->lineCount(); ++i) { + auto line = m_doc->line(i); + markRedone(line.handle(), m_first); + } +} diff --git a/src/qcodeeditwidget/qdocumentswaptextcommand.h b/src/qcodeeditwidget/qdocumentswaptextcommand.h new file mode 100644 index 0000000..ae15656 --- /dev/null +++ b/src/qcodeeditwidget/qdocumentswaptextcommand.h @@ -0,0 +1,38 @@ +/*============================================================================== +** Copyright (C) 2024-2027 WingSummer +** +** This program is free software: you can redistribute it and/or modify it under +** the terms of the GNU Affero General Public License as published by the Free +** Software Foundation, version 3. +** +** This program is distributed in the hope that it will be useful, but WITHOUT +** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +** FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +** details. +** +** You should have received a copy of the GNU Affero General Public License +** along with this program. If not, see . +** ============================================================================= +*/ + +#ifndef QDOCUMENTSWAPTEXTCOMMAND_H +#define QDOCUMENTSWAPTEXTCOMMAND_H + +#include "qdocumentcommand.h" + +class QDocumentSwapTextCommand : public QDocumentCommand { +public: + explicit QDocumentSwapTextCommand(const QString &text, QDocument *doc, + QDocumentCommand *p = nullptr); + + // QUndoCommand interface +public: + void undo(); + void redo(); + +private: + QString oldtext; + QString newtext; +}; + +#endif // QDOCUMENTSWAPTEXTCOMMAND_H diff --git a/src/qcodeeditwidget/qeditconfig.cpp b/src/qcodeeditwidget/qeditconfig.cpp index 0a66814..b0f130c 100644 --- a/src/qcodeeditwidget/qeditconfig.cpp +++ b/src/qcodeeditwidget/qeditconfig.cpp @@ -22,6 +22,7 @@ \see QEditConfig */ +#include "class/langservice.h" #include "qdocument.h" #include "qdocument_p.h" #include "qeditor.h" @@ -42,6 +43,20 @@ QEditConfig::QEditConfig(QWidget *w) : WingHex::SettingPage(w), ui(new Ui::QEditConfig()) { ui->setupUi(this); + + QFile code(QStringLiteral(":/com.wingsummer.winghex/src/TESTCODE.as")); + auto ret = code.open(QFile::ReadOnly); + Q_ASSERT(ret); + Q_UNUSED(ret); + + auto cbuffer = code.readAll(); + _edit = new QEditor(QString::fromUtf8(cbuffer), this); + LangService::instance().applyLanguageSerivce(_edit); + + _edit->setFlag(QEditor::ReadOnly, true); + _edit->setUndoRedoEnabled(false); + ui->layoutFont->addWidget(_edit, ui->layoutFont->rowCount(), 0, 1, + ui->layoutFont->columnCount()); reload(); } @@ -54,46 +69,51 @@ void QEditConfig::apply() { QFont font = ui->cbFont->currentFont(); font.setPointSize(ui->spnFontSize->value()); - QDocument::setFont(font); - QDocument::setTabStop(ui->spnTabWidth->value()); + auto &doc_ps = QDocumentPrivate::m_documents; + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setFont(font); + doc->setTabStop(ui->spnTabWidth->value()); - if (ui->chkDetectLE->isChecked()) - QDocument::setDefaultLineEnding(QDocument::Conservative); - else - QDocument::setDefaultLineEnding( - QDocument::LineEnding(ui->cbLineEndings->currentIndex() + 1)); + if (ui->chkDetectLE->isChecked()) { + doc->setLineEnding(QDocument::Conservative); + } else { + doc->setLineEnding( + QDocument::LineEnding(ui->cbLineEndings->currentIndex() + 1)); + } - QDocument::WhiteSpaceMode ws = QDocument::ShowNone; + QDocument::WhiteSpaceMode ws = QDocument::ShowNone; - if (ui->chkShowLeadingWhitespace->isChecked()) - ws |= QDocument::ShowLeading; + if (ui->chkShowLeadingWhitespace->isChecked()) + ws |= QDocument::ShowLeading; - if (ui->chkShowTrailingWhitespace->isChecked()) - ws |= QDocument::ShowTrailing; + if (ui->chkShowTrailingWhitespace->isChecked()) + ws |= QDocument::ShowTrailing; - if (ui->chkShowTabsInText->isChecked()) - ws |= QDocument::ShowTabs; + if (ui->chkShowTabsInText->isChecked()) + ws |= QDocument::ShowTabs; - QDocument::setShowSpaces(ws); + doc->setShowSpaces(ws); - int flags = QEditor::defaultFlags(); + int flags = QEditor::defaultFlags(); - if (ui->chkReplaceTabs->isChecked()) - flags |= QEditor::ReplaceTabs; - else - flags &= ~QEditor::ReplaceTabs; + if (ui->chkReplaceTabs->isChecked()) + flags |= QEditor::ReplaceTabs; + else + flags &= ~QEditor::ReplaceTabs; - if (ui->chkAutoRemoveTrailingWhitespace->isChecked()) - flags |= QEditor::RemoveTrailing; - else - flags &= ~QEditor::RemoveTrailing; + if (ui->chkAutoRemoveTrailingWhitespace->isChecked()) + flags |= QEditor::RemoveTrailing; + else + flags &= ~QEditor::RemoveTrailing; - if (ui->chkPreserveTrailingIndent->isChecked()) - flags |= QEditor::PreserveTrailingIndent; - else - flags &= ~QEditor::PreserveTrailingIndent; + if (ui->chkPreserveTrailingIndent->isChecked()) + flags |= QEditor::PreserveTrailingIndent; + else + flags &= ~QEditor::PreserveTrailingIndent; - QEditor::setDefaultFlags(flags); + QEditor::setDefaultFlags(flags); + } } /*! @@ -135,26 +155,26 @@ void QEditConfig::reset() { void QEditConfig::reload() { // reload the current config - ui->cbFont->setFont(QDocument::font()); - ui->spnFontSize->setValue(QDocument::font().pointSize()); + // ui->cbFont->setFont(QDocument::font()); + // ui->spnFontSize->setValue(QDocument::font().pointSize()); - ui->spnTabWidth->setValue(QDocument::tabStop()); + // ui->spnTabWidth->setValue(QDocument::tabStop()); - QDocument::WhiteSpaceMode ws = QDocument::showSpaces(); - ui->chkShowTabsInText->setChecked(ws & QDocument::ShowTabs); - ui->chkShowLeadingWhitespace->setChecked(ws & QDocument::ShowLeading); - ui->chkShowTrailingWhitespace->setChecked(ws & QDocument::ShowTrailing); + // QDocument::WhiteSpaceMode ws = QDocument::showSpaces(); + // ui->chkShowTabsInText->setChecked(ws & QDocument::ShowTabs); + // ui->chkShowLeadingWhitespace->setChecked(ws & QDocument::ShowLeading); + // ui->chkShowTrailingWhitespace->setChecked(ws & QDocument::ShowTrailing); - QDocument::LineEnding le = QDocument::defaultLineEnding(); - ui->chkDetectLE->setChecked(le == QDocument::Conservative); - ui->cbLineEndings->setCurrentIndex(le ? le - 1 : 0); + // QDocument::LineEnding le = QDocument::defaultLineEnding(); + // ui->chkDetectLE->setChecked(le == QDocument::Conservative); + // ui->cbLineEndings->setCurrentIndex(le ? le - 1 : 0); - int flags = QEditor::defaultFlags(); - ui->chkReplaceTabs->setChecked(flags & QEditor::ReplaceTabs); - ui->chkAutoRemoveTrailingWhitespace->setChecked(flags & - QEditor::RemoveTrailing); - ui->chkPreserveTrailingIndent->setChecked(flags & - QEditor::PreserveTrailingIndent); + // int flags = QEditor::defaultFlags(); + // ui->chkReplaceTabs->setChecked(flags & QEditor::ReplaceTabs); + // ui->chkAutoRemoveTrailingWhitespace->setChecked(flags & + // QEditor::RemoveTrailing); + // ui->chkPreserveTrailingIndent->setChecked(flags & + // QEditor::PreserveTrailingIndent); } /*! @@ -213,9 +233,7 @@ void QEditConfig::loadKeys(const QMap &keys) { ui->cbFont->setCurrentFont(f); ui->spnFontSize->setValue(f.pointSize()); - QDocument::setFont(f); - - ui->lblSampleText->setFont(f); + // QDocument::setFont(f); } else if (it.key() == "tab_width") { ui->spnTabWidth->setValue(it->toInt()); @@ -266,10 +284,7 @@ void QEditConfig::loadKeys(const QMap &keys) { void QEditConfig::on_spnFontSize_valueChanged(int size) { QFont font = ui->cbFont->currentFont(); font.setPointSize(size); - - ui->lblSampleText->setFont(font); - - QDocument::setFont(font); + _edit->setFont(font); } /*! @@ -277,67 +292,80 @@ void QEditConfig::on_spnFontSize_valueChanged(int size) { */ void QEditConfig::on_cbFont_currentFontChanged(QFont font) { font.setPointSize(ui->spnFontSize->value()); - ui->lblSampleText->setFont(font); - - QDocument::setFont(font); + _edit->setFont(font); } /*! \brief Slot used to apply tab width settings */ void QEditConfig::on_spnTabWidth_valueChanged(int n) { - QDocument::setTabStop(n); + _edit->document()->setTabStop(n); } /*! \brief Slot used to apply tabs replacement settings */ void QEditConfig::on_chkReplaceTabs_toggled(bool y) { - // FIXME - foreach (QEditor *e, QEditor::m_editors) { - e->setFlag(QEditor::ReplaceTabs, y); - } + _edit->setFlag(QEditor::ReplaceTabs, y); } /*! \brief Slot used to apply tabs display settings */ void QEditConfig::on_chkShowTabsInText_toggled(bool y) { - if (y) - QDocument::setShowSpaces(QDocument::showSpaces() | QDocument::ShowTabs); - else - QDocument::setShowSpaces(QDocument::showSpaces() & - ~QDocument::ShowTabs); + auto &doc_ps = QDocumentPrivate::m_documents; + if (y) { + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setShowSpaces(doc->showSpaces() | QDocument::ShowTabs); + } + } else { + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setShowSpaces(doc->showSpaces() & ~QDocument::ShowTabs); + } + } } /*! \brief Slot used to apply trailing whitespace display settings */ void QEditConfig::on_chkShowLeadingWhitespace_toggled(bool y) { - if (y) - QDocument::setShowSpaces(QDocument::showSpaces() | - QDocument::ShowLeading); - else - QDocument::setShowSpaces(QDocument::showSpaces() & - ~QDocument::ShowLeading); + auto &doc_ps = QDocumentPrivate::m_documents; + if (y) { + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setShowSpaces(doc->showSpaces() | QDocument::ShowLeading); + } + } else { + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setShowSpaces(doc->showSpaces() & ~QDocument::ShowLeading); + } + } } /*! \brief Slot used to apply leading whitespace display settings */ void QEditConfig::on_chkShowTrailingWhitespace_toggled(bool y) { - if (y) - QDocument::setShowSpaces(QDocument::showSpaces() | - QDocument::ShowTrailing); - else - QDocument::setShowSpaces(QDocument::showSpaces() & - ~QDocument::ShowTrailing); + auto &doc_ps = QDocumentPrivate::m_documents; + if (y) { + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setShowSpaces(doc->showSpaces() | QDocument::ShowTrailing); + } + } else { + for (auto &pdoc : doc_ps) { + auto doc = pdoc->m_doc; + doc->setShowSpaces(doc->showSpaces() & ~QDocument::ShowTrailing); + } + } } void QEditConfig::on_cbLineEndings_currentIndexChanged(int idx) { QDocument::LineEnding le = QDocument::LineEnding(idx + 1); - - QDocument::setDefaultLineEnding(le); + _edit->document()->setLineEnding(le); } /*! @@ -350,27 +378,21 @@ void QEditConfig::on_chkDetectLE_toggled(bool y) { le = QDocument::LineEnding(ui->cbLineEndings->currentIndex() + 1); } - QDocument::setDefaultLineEnding(le); + _edit->document()->setLineEnding(le); } /*! \brief Slot used to apply trailing space removal settings */ void QEditConfig::on_chkAutoRemoveTrailingWhitespace_toggled(bool y) { - // FIXME - foreach (QEditor *e, QEditor::m_editors) { - e->setFlag(QEditor::RemoveTrailing, y); - } + _edit->setFlag(QEditor::RemoveTrailing, y); } /*! \brief Slot used to indent preservation settings */ void QEditConfig::on_chkPreserveTrailingIndent_toggled(bool y) { - // FIXME - foreach (QEditor *e, QEditor::m_editors) { - e->setFlag(QEditor::PreserveTrailingIndent, y); - } + _edit->setFlag(QEditor::PreserveTrailingIndent, y); } /*! @} */ diff --git a/src/qcodeeditwidget/qeditconfig.h b/src/qcodeeditwidget/qeditconfig.h index 5a3a34c..d445ff2 100644 --- a/src/qcodeeditwidget/qeditconfig.h +++ b/src/qcodeeditwidget/qeditconfig.h @@ -2,6 +2,7 @@ #define QEDITCONFIG_H #include "plugin/settingpage.h" +#include "qeditor.h" #include namespace Ui { @@ -50,6 +51,8 @@ private slots: private: Ui::QEditConfig *ui; + + QEditor *_edit; }; #endif // QEDITCONFIG_H diff --git a/src/qcodeeditwidget/qeditconfig.ui b/src/qcodeeditwidget/qeditconfig.ui index c068622..a887055 100644 --- a/src/qcodeeditwidget/qeditconfig.ui +++ b/src/qcodeeditwidget/qeditconfig.ui @@ -22,11 +22,8 @@ Font - - - 4 - - + + @@ -40,10 +37,10 @@ - + - QAbstractSpinBox::UpDownArrows + QAbstractSpinBox::ButtonSymbols::UpDownArrows 6 @@ -56,49 +53,22 @@ - - - - - 0 - 0 - - + + - Monospace + true + true - - QFrame::StyledPanel - - - QFrame::Sunken - - text which <i>should</i> be a <b>fair</b> test of the font + Takes Effect on Terminal as well - Qt::AlignCenter - - - 0 + Qt::AlignmentFlag::AlignCenter - - - - Qt::Horizontal - - - - 40 - 20 - - - - @@ -145,7 +115,7 @@ - Qt::Horizontal + Qt::Orientation::Horizontal @@ -263,10 +233,10 @@ - Qt::Vertical + Qt::Orientation::Vertical - QSizePolicy::MinimumExpanding + QSizePolicy::Policy::MinimumExpanding diff --git a/src/qcodeeditwidget/qsnippetedit.cpp b/src/qcodeeditwidget/qsnippetedit.cpp index 825e050..f8af5c1 100644 --- a/src/qcodeeditwidget/qsnippetedit.cpp +++ b/src/qcodeeditwidget/qsnippetedit.cpp @@ -23,6 +23,7 @@ #include "qsnippet.h" #include "qsnippetmanager.h" +#include "utilities.h" #include @@ -49,7 +50,9 @@ QSnippetEdit::QSnippetEdit(QSnippetManager *mgr, QWidget *p) QSnippetManager *QSnippetEdit::snippetManager() const { return m_manager; } -QIcon QSnippetEdit::categoryIcon() const { return QIcon(); } +QIcon QSnippetEdit::categoryIcon() const { + return ICONRES(QStringLiteral("snippt")); +} QString QSnippetEdit::name() const { return tr("Snippets"); } diff --git a/src/settings/clangformatsetdialog.cpp b/src/settings/clangformatsetdialog.cpp new file mode 100644 index 0000000..03f001d --- /dev/null +++ b/src/settings/clangformatsetdialog.cpp @@ -0,0 +1,50 @@ +#include "clangformatsetdialog.h" +#include "class/clangformatmanager.h" +#include "class/winginputdialog.h" +#include "ui_clangformatsetdialog.h" +#include "utilities.h" + +ClangFormatSetDialog::ClangFormatSetDialog(QWidget *parent) + : WingHex::SettingPage(parent), ui(new Ui::ClangFormatSetDialog) { + ui->setupUi(this); + + auto clang = ClangFormatManager::instance(); + ui->cbStyle->addItems(clang.supportedStyles()); + + ui->leLocation->setText(ClangFormatManager::getProgramName()); + + if (clang.exists()) { + ui->lblClangPath->setText(clang.path()); + ui->lblClangPath->setToolTip(clang.path()); + ui->lblClangVersion->setText(clang.version()); + } else { + ui->lblClangPath->setStyleSheet(QStringLiteral("color:red")); + } +} + +ClangFormatSetDialog::~ClangFormatSetDialog() { delete ui; } + +QIcon ClangFormatSetDialog::categoryIcon() const { + return ICONRES(QStringLiteral("codeformat")); +} + +QString ClangFormatSetDialog::name() const { return tr("ClangFormat"); } + +QString ClangFormatSetDialog::id() const { + return QStringLiteral("ClangFormat"); +} + +void ClangFormatSetDialog::apply() {} + +void ClangFormatSetDialog::reset() {} + +void ClangFormatSetDialog::cancel() {} + +void ClangFormatSetDialog::on_cbStyle_currentTextChanged(const QString &arg1) { + ui->btnStyleCustom->setEnabled(arg1 == QStringLiteral("Custom")); +} + +void ClangFormatSetDialog::on_btnStyleCustom_clicked() { + // TODO + WingInputDialog::getMultiLineText(this, tr("ClangFormat"), ""); +} diff --git a/src/settings/clangformatsetdialog.h b/src/settings/clangformatsetdialog.h new file mode 100644 index 0000000..aad44e7 --- /dev/null +++ b/src/settings/clangformatsetdialog.h @@ -0,0 +1,37 @@ +#ifndef CLANGFORMATSETDIALOG_H +#define CLANGFORMATSETDIALOG_H + +#include "plugin/settingpage.h" + +namespace Ui { +class ClangFormatSetDialog; +} + +class ClangFormatSetDialog : public WingHex::SettingPage { + Q_OBJECT + +public: + explicit ClangFormatSetDialog(QWidget *parent = nullptr); + ~ClangFormatSetDialog(); + +private: + Ui::ClangFormatSetDialog *ui; + + // PageBase interface +public: + virtual QIcon categoryIcon() const override; + virtual QString name() const override; + virtual QString id() const override; + + // SettingPage interface +public: + virtual void apply() override; + virtual void reset() override; + virtual void cancel() override; + +private slots: + void on_cbStyle_currentTextChanged(const QString &arg1); + void on_btnStyleCustom_clicked(); +}; + +#endif // CLANGFORMATSETDIALOG_H diff --git a/src/settings/clangformatsetdialog.ui b/src/settings/clangformatsetdialog.ui new file mode 100644 index 0000000..eb1b406 --- /dev/null +++ b/src/settings/clangformatsetdialog.ui @@ -0,0 +1,201 @@ + + + ClangFormatSetDialog + + + + 0 + 0 + 425 + 323 + + + + + + + + 8 + + + 10 + + + 10 + + + 10 + + + 10 + + + + + Enable + + + true + + + + + + + Info + + + + + + Path + + + + + + + - + + + Qt::AlignCenter + + + + + + + Version + + + + + + + - + + + Qt::AlignCenter + + + + + + + + + + Configure + + + + 10 + + + 10 + + + 5 + + + 5 + + + 5 + + + 5 + + + + + Location + + + + + + + + + + + + Browse + + + + + + + + + Style + + + + + + + + + + Custom + + + + + + + Edit + + + + + + + IndentWidth + + + + + + + 2 + + + 16 + + + 4 + + + + + + + + + + AutoFormatWhenSave + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/settings/settings.h b/src/settings/settings.h new file mode 100644 index 0000000..3059f38 --- /dev/null +++ b/src/settings/settings.h @@ -0,0 +1,64 @@ +#ifndef SETTINGS_H +#define SETTINGS_H + +#include +#include + +inline QString getRealContent(const QString &value) { return value; } + +template +inline QString getRealContent(T &value) { + static_assert(std::is_same()); + return *value; +} + +#define HANDLE_CONFIG \ + QSettings set(QStringLiteral(APP_ORG), QStringLiteral(APP_NAME)) + +#define CONFIG set + +#define WRITE_CONFIG(config, dvalue) \ + set.setValue(getRealContent(config), dvalue); + +#define READ_CONFIG(config, dvalue) set.value(getRealContent(config), dvalue) + +#define READ_CONFIG_SAFE(var, config, dvalue, func) \ + { \ + auto b = false; \ + var = READ_CONFIG(config, dvalue).func(&b); \ + if (!b) { \ + var = dvalue; \ + } \ + } + +#define READ_CONFIG_INT(var, config, dvalue) \ + READ_CONFIG_SAFE(var, config, dvalue, toInt) + +#define READ_CONFIG_STRING(var, config, dvalue) \ + var = READ_CONFIG(config, dvalue).toString() + +#define READ_CONFIG_BOOL(var, config, dvalue) \ + var = READ_CONFIG(config, dvalue).toBool() + +#define READ_CONFIG_QSIZETYPE(var, config, dvalue) \ + READ_CONFIG_SAFE(var, config, dvalue, toLongLong) + +#define READ_CONFIG_INT_POSITIVE(var, config, dvalue) \ + { \ + Q_ASSERT(dvalue > 0); \ + READ_CONFIG_SAFE(var, config, dvalue, toInt); \ + if (var <= 0) { \ + var = dvalue; \ + } \ + } + +#define READ_CONFIG_DOUBLE_POSITIVE(var, config, dvalue) \ + { \ + Q_ASSERT(dvalue > 0); \ + READ_CONFIG_SAFE(var, config, dvalue, toDouble); \ + if (var <= 0) { \ + var = dvalue; \ + } \ + } + +#endif // SETTINGS_H diff --git a/theme/dark/stylesheet.qss b/theme/dark/stylesheet.qss index 432d1a6..d0edf73 100644 --- a/theme/dark/stylesheet.qss +++ b/theme/dark/stylesheet.qss @@ -2980,3 +2980,10 @@ QCallTip qproperty-foreground: #eff0f1; qproperty-opacity: 0.8; } + +QConsoleWidget +{ + background-color: #1d2023; + color: #eff0f1; + selection-background-color: #3daee9; +}