diff --git a/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp b/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp index f26d51b..9fd8a92 100644 --- a/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp +++ b/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp @@ -1,305 +1,305 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "kmultiformlistbox-multivisible.h" #include #include #include #include #include "kmultiformlistboxfactory.h" #include "indexWindow.h" #include "ccp.h" const int indexButtonWidth = 16; const int indexButtonHeight = 12; const uchar indexButtonBits[] = { 0x00, 0x00, 0x00, 0x00, 0x0e, 0x02, 0x04, 0x02, 0x04, 0x02, 0xc4, 0x8a, 0x24, 0x53, 0x14, 0x22, 0x14, 0x22, 0x24, 0x53, 0xce, 0x8a, 0x00, 0x00 }; KMultiFormListBoxMultiVisible::KMultiFormListBoxMultiVisible(KMultiFormListBoxFactory *fact, QWidget *parent) : QScrollArea(parent) { factory = fact; // Initialize the element list elms = new WidgetList(); QWidget *widget = new QWidget(); layout = new QVBoxLayout(widget); layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); setWidget(widget); setWidgetResizable(true); } //---------------------------------------------------------------------- // This function returns a list of the elements in the KMultiFormListBox widget. //---------------------------------------------------------------------- KMultiFormListBoxEntryList KMultiFormListBoxMultiVisible::elements() { KMultiFormListBoxEntryList res; foreach (QWidget *child, *elms) { if (child->objectName() != QStringLiteral("separator")) { res.append((KMultiFormListBoxEntry *)child); } } return res; } //---------------------------------------------------------------------- // This function is called whenever the KMultiFormListBox widget is resized. It is // necessary to ensure that the content of the clipper is resized. //---------------------------------------------------------------------- void KMultiFormListBoxMultiVisible::resizeEvent(QResizeEvent *e) { // The call of the super class ensures that the outer border is updated. QScrollArea::resizeEvent(e); updateClipperContent(); } void KMultiFormListBoxMultiVisible::updateClipperContent() { // Extract the current size of the clipper /* int ClipperWidth = clipper()->size().width(); int ClipperHeight = clipper()->size().height(); // Initialize the calculation of the size of the new clipper. int totalHeight = 0; int maxWidth = ClipperWidth; int count = 0; // calculate the required size. foreach (QWidget *child , *elms) { maxWidth = qMax(maxWidth, child->sizeHint().width()); if ( child->objectName() != "separator" ) { totalHeight += child->sizeHint().height(); count++; } else { totalHeight += child->size().height(); } } // Calculate the extra height for the elements. int extra = 0; if (totalHeight < ClipperHeight && count != 0) { extra = (ClipperHeight - totalHeight) / count; totalHeight = ClipperHeight; } // Now place the elements in the clipper. int yPos = 0; foreach (QWidget *child2 , *elms) { int h; if ( child2->objectName() != "separator" ) { h = child2->sizeHint().height(); h += extra; } else { h = child2->size().height(); } moveChild(child2, 0,yPos); child2->resize(maxWidth,h); yPos += h; } */ // Finally call the resize procedure for the clipper to ensure that the // new sizes is shown properly. //resizeContents(maxWidth, totalHeight); } void KMultiFormListBoxMultiVisible::addElement() { addElement(nullptr); } void KMultiFormListBoxMultiVisible::addElement(KMultiFormListBoxEntry *after) { KMultiFormListBoxEntry *elm = factory->create(widget()); insertElmIntoWidget(elm, after); } void KMultiFormListBoxMultiVisible::append(KMultiFormListBoxEntry *elm) { elm->setParent(widget()); insertElmIntoWidget(elm, nullptr); } void KMultiFormListBoxMultiVisible::delElement(QWidget *elm) { int index = elms->indexOf(elm); QWidget *next = elms->at(index + 1); if (next->objectName() != QStringLiteral("separator")) { elms->removeOne(next); layout->removeWidget(next); } elms->removeOne(elm); layout->removeWidget(elm); updateClipperContent(); } void KMultiFormListBoxMultiVisible::delAnElement() { delElement(elms->at(0)); } void KMultiFormListBoxMultiVisible::insertElmIntoWidget(KMultiFormListBoxEntry *elm, KMultiFormListBoxEntry *after) { // Bind the index button if it exists. if (elm->indexButton()) { elm->indexButton()->setIcon(static_cast(QBitmap::fromData(QSize(indexButtonWidth, indexButtonHeight), indexButtonBits, QImage::Format_MonoLSB))); connect(elm->indexButton(), &QAbstractButton::clicked, elm, &KMultiFormListBoxEntry::acceptIndexButton); - connect(elm, SIGNAL(gotoIndex(KMultiFormListBoxEntry*)), - this, SLOT(showIndexList(KMultiFormListBoxEntry*))); + connect(elm, &KMultiFormListBoxEntry::gotoIndex, + this, &KMultiFormListBoxMultiVisible::showIndexList); } // Find the location to insert the new element. int index = elms->count(); if (after) { index = elms->indexOf(after); } // Now show the new element. elms->insert(index, elm); layout->insertWidget(index, elm); elm->show(); ensureWidgetVisible(elm, 0, 0); //addChild(elm,0,0); // updateClipperContent will place the child correctly. QWidget *sep = factory->separator(widget()); if (sep != nullptr) { sep->setObjectName(QStringLiteral("separator")); sep->show(); layout->insertWidget(index + 1, sep); // updateClipperContent will place the child correctly. elms->insert(index + 1, sep); } updateClipperContent(); showWidget(elm); // scroll to show the new widget. // install cut'n'paste functionallity new CCP(this, elm); } //---------------------------------------------------------------------- // This function shows the list of available Idx elements. //---------------------------------------------------------------------- void KMultiFormListBoxMultiVisible::showIndexList(KMultiFormListBoxEntry *elm) { indexWindow *menu = new indexWindow(); // Insert the elements into the menu item. foreach (QWidget *child, *elms) { if (child->objectName() != QStringLiteral("separator")) { QString txt = ((KMultiFormListBoxEntry *)child)->idxString(); menu->insertItem(txt); } } // Calculate the location of the window QPoint start; int width; elm->indexWindowPos(&start, &width); // Show the window. int index = menu->exec(start, width); if (index != -1) { foreach (QWidget *child, *elms) { if (child->objectName() != QLatin1String("separator")) { if (index == 0) { showWidget((KMultiFormListBoxEntry *)child); break; } index--; } } } delete menu; } //---------------------------------------------------------------------- // Scroll to the loaction of the given KMultiFormListBoxEntry element. //---------------------------------------------------------------------- void KMultiFormListBoxMultiVisible::showWidget(KMultiFormListBoxEntry *elm) { ensureWidgetVisible(elm); } void KMultiFormListBoxMultiVisible::cut(KMultiFormListBoxEntry *elm) { if (countElements(elms) == 1) { KMessageBox::information(this, i18n("Due to a bug, it is not possible to remove the last element."), i18n("Internal Error")); return; } QDataStream stream(&clipboard, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_3_1); factory->toStream(elm, stream); delElement(elm); } void KMultiFormListBoxMultiVisible::copy(KMultiFormListBoxEntry *elm) { QDataStream stream(&clipboard, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_3_1); factory->toStream(elm, stream); } void KMultiFormListBoxMultiVisible::paste(KMultiFormListBoxEntry *oldElm) { if (clipboard.isEmpty()) { KMessageBox::information(this, i18n("There is no element on the clipboard to paste in.")); return; } KMultiFormListBoxEntry *newElm = factory->create(widget()); QDataStream stream(&clipboard, QIODevice::ReadOnly); stream.setVersion(QDataStream::Qt_3_1); factory->fromStream(stream, newElm); insertElmIntoWidget(newElm, oldElm); } int KMultiFormListBoxMultiVisible::countElements(WidgetList *elms) { int count = 0; foreach (QWidget *child, *elms) { if (dynamic_cast(child)) { count++; } } return count; } diff --git a/src/KMultiFormListBox/kmultiformlistbox.cpp b/src/KMultiFormListBox/kmultiformlistbox.cpp index 3422abe..d06a57a 100644 --- a/src/KMultiFormListBox/kmultiformlistbox.cpp +++ b/src/KMultiFormListBox/kmultiformlistbox.cpp @@ -1,103 +1,103 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "kmultiformlistbox-multivisible.h" #include "kmultiformlistbox-windowed.h" #include #include "kmultiformlistboxfactory.h" -KMultiFormListBox::KMultiFormListBox(KMultiFormListBoxFactory *factory, KMultiFormListBoxType tp, QWidget *parent, bool showUpDownButtons, bool showHelpButton, QString addButtonText) +KMultiFormListBox::KMultiFormListBox(KMultiFormListBoxFactory *factory, KMultiFormListBoxType tp, QWidget *parent, bool showUpDownButtons, bool showHelpButton, const QString &addButtonText) : QWidget(parent) { switch (tp) { case MultiVisible: theWidget = new KMultiFormListBoxMultiVisible(factory, this); break; case Windowed: theWidget = new KMultiFormListBoxWindowed(factory, this, showUpDownButtons, showHelpButton, addButtonText); break; } QWidget *widget = theWidget->qWidget(); QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); _factory = factory; layout->addWidget(widget); } void KMultiFormListBox::append(KMultiFormListBoxEntry *element) { theWidget->append(element); } void KMultiFormListBox::addElement() { theWidget->addElement(); } KMultiFormListBoxEntryList KMultiFormListBox::elements() { return theWidget->elements(); } const KMultiFormListBoxEntryList KMultiFormListBox::elements() const { return const_cast(this)->elements(); } void KMultiFormListBox::slotChangeFace(KMultiFormListBoxType /*newFace*/) { // TODO // kDebug() << "It's not possible yet to change the face on the fly." // << "Please let me (blackie@kde.org) know that you need it, and I'll work on it" << endl; } void KMultiFormListBox::toStream(QDataStream &stream) const { const KMultiFormListBoxEntryList elms = elements(); stream << elms.count(); foreach (KMultiFormListBoxEntry *entry, elms) { _factory->toStream(entry, stream); } } void KMultiFormListBox::fromStream(QDataStream &stream) { unsigned int fromCount, toCount; stream >> fromCount; toCount = elements().count(); // adds/remove elements in the to list, to make it have the correct length. for (unsigned int j = toCount; j < fromCount; ++j) { addElement(); } for (unsigned int k = fromCount; k < toCount; ++k) { theWidget->delAnElement(); } KMultiFormListBoxEntryList elms = elements(); foreach (KMultiFormListBoxEntry *entry, elms) { _factory->fromStream(stream, entry); } } diff --git a/src/KMultiFormListBox/kmultiformlistbox.h b/src/KMultiFormListBox/kmultiformlistbox.h index 82a388d..c7b4790 100644 --- a/src/KMultiFormListBox/kmultiformlistbox.h +++ b/src/KMultiFormListBox/kmultiformlistbox.h @@ -1,113 +1,113 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #ifndef __kmultiformlistbox #define __kmultiformlistbox #include "kmultiformlistboxentry.h" #include class QDataStream; class KMultiFormListBoxFactory; class KMultiFormListBoxShower; typedef QList KMultiFormListBoxEntryList; typedef QList WidgetList; /** The main class used to get an KMultiFormListBox widget. The KMultiFormListBox widget consist of a sub-widget which is repeated a number of times, it is up to the end user to determine the number of times the sub widget is repeated, and he may require an additional copy simply by pressing a ``Add'' or ``More Entries'' button. The KMultiFormListBox widget has two different faces (i.e. two different end user interfaces). One (Windowed) will show a listbox from which the end user can access each subwidget containing data by pressing the LMB on a name for the element. The other face (MultiVisible) shows all the subwidgets in one huge ``Listbox''. To use the KMultiFormListBox widget you must create a class which is inherited from the @ref KMultiFormListBoxFactory class. This new class must override the function `create'. This function must return a freshly made instance of the class @ref KMultiFormListBoxEntry (or a subclass of this). The KMultiFormListBoxEntry instance is the one inserted into the KMultiFormListBox widget (one instance for each sub widget in the KMultiFormListBox widget). @author Jesper Kjær Pedersen **/ class KMultiFormListBox : public QWidget { Q_OBJECT public: enum KMultiFormListBoxType { MultiVisible, Windowed }; /** @param factory A factory used to generate the instances of KMultiFormListBoxEntry class which is repeated in the KMultiFormListBox @param parent A pointer to the parent widget **/ explicit KMultiFormListBox(KMultiFormListBoxFactory *factory, KMultiFormListBoxType tp = Windowed, QWidget *parent = nullptr, bool showUpDownButtons = true, bool showHelpButton = true, - QString addButtonText = i18n("Add")); + const QString &addButtonText = i18n("Add")); /** @return The elements in the KMultiFormListBox. **/ KMultiFormListBoxEntryList elements(); const KMultiFormListBoxEntryList elements() const; /** TODO. **/ void append(KMultiFormListBoxEntry *); /** write data out to stream */ void toStream(QDataStream &stream) const; /** reads data in from stream */ void fromStream(QDataStream &stream); public Q_SLOTS: /** Adds an empty element to the KMultiFormListBox. This slot is only required for the @ref MultiVisible face. It should be connected to a button which lets the user know that he may get more elements in this KMultiFormListBox by pressing it. The button should be labeled ``More Entries'' or something similar. **/ void addElement(); // Adds an empty element to the KMultiFormListBox /** Changes the face of the KMultiFormListBox. @param face The new face of the KMultiFormListBox **/ void slotChangeFace(KMultiFormListBoxType newFace); private: KMultiFormListBoxShower *theWidget = nullptr; KMultiFormListBoxFactory *_factory = nullptr; }; #endif /* kmultiformlistbox */ diff --git a/src/compoundwidget.cpp b/src/compoundwidget.cpp index 9f5144f..98b033f 100644 --- a/src/compoundwidget.cpp +++ b/src/compoundwidget.cpp @@ -1,331 +1,331 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "compoundwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "concwidget.h" #include "kwidgetstreamer.h" #include "compoundregexp.h" //================================================================================ CompoundDetailWindow::CompoundDetailWindow(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); QLabel *label = new QLabel(i18n("&Title:"), this); layout->addWidget(label); _title = new QLineEdit(this); layout->addWidget(_title); label->setBuddy(_title); label = new QLabel(i18n("&Description:"), this); layout->addWidget(label); _description = new KTextEdit(this); layout->addWidget(_description); label->setBuddy(_description); _allowReplace = new QCheckBox(i18n("&Automatically replace using this item"), this); layout->addWidget(_allowReplace); _allowReplace->setToolTip(i18n("When the content of this box is typed in to the ASCII line,
" "this box will automatically be added around it,
" "if this check box is selected.")); _allowReplace->setChecked(true); _title->setFocus(); } QString CompoundDetailWindow::title() const { return _title->text(); } QString CompoundDetailWindow::description() const { return _description->toPlainText(); } bool CompoundDetailWindow::allowReplace() const { return _allowReplace->isChecked(); } void CompoundDetailWindow::setTitle(const QString &txt) { _title->setText(txt); } void CompoundDetailWindow::setDescription(const QString &txt) { _description->setText(txt); } void CompoundDetailWindow::setAllowReplace(bool b) { _allowReplace->setChecked(b); } //================================================================================ CompoundWidget::CompoundWidget(RegExpEditorWindow *editorWindow, QWidget *parent) : SingleContainerWidget(editorWindow, parent) { _child = new ConcWidget(editorWindow, this); init(); } CompoundWidget::CompoundWidget(CompoundRegExp *regexp, RegExpEditorWindow *editorWindow, QWidget *parent) : SingleContainerWidget(editorWindow, parent) { init(); _content->setTitle(regexp->title()); _content->setDescription(regexp->description()); _content->setAllowReplace(regexp->allowReplace()); RegExpWidget *child = WidgetFactory::createWidget(regexp->child(), _editorWindow, this); if (!(_child = dynamic_cast(child))) { _child = new ConcWidget(_editorWindow, child, this); } _hidden = regexp->hidden(); } void CompoundWidget::init() { _configWindow = new QDialog(this); _configWindow->setWindowTitle(i18n("Configure Compound")); QVBoxLayout *mainLayout = new QVBoxLayout; _configWindow->setLayout(mainLayout); _content = new CompoundDetailWindow(_configWindow); mainLayout->addWidget(_content); connect(_configWindow, &QDialog::rejected, this, &CompoundWidget::slotConfigCanceled); connect(_configWindow, &QDialog::finished, this, &CompoundWidget::slotConfigWindowClosed); _down = getIcon(QStringLiteral("arrow-down")); _up = getIcon(QStringLiteral("arrow-up")); _hidden = false; _backRefId = -1; QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - _configWindow->connect(buttonBox, SIGNAL(accepted()), _configWindow, SLOT(accept())); - _configWindow->connect(buttonBox, SIGNAL(rejected()), _configWindow, SLOT(reject())); + _configWindow->connect(buttonBox, &QDialogButtonBox::accepted, _configWindow, &QDialog::accept); + _configWindow->connect(buttonBox, &QDialogButtonBox::rejected, _configWindow, &QDialog::reject); mainLayout->addWidget(buttonBox); } QSize CompoundWidget::sizeHint() const { QFontMetrics metrics = fontMetrics(); _childSize = _child->sizeHint(); _textSize = metrics.size(0, _content->title()); int width, height; if (_hidden) { _pixmapSize = _up.size(); width = 2 * pw + qMax(2 * bdSize + _textSize.width(), 2 * bdSize + _pixmapSize.width()); height = _pixmapSize.height() + 2 * bdSize + _textSize.height() + pw; } else { _pixmapSize = _down.size(); int headerLineWidth = 2 * pw + 2 * bdSize + _pixmapSize.width(); if (_textSize.width() != 0) { headerLineWidth += 3 * bdSize + _textSize.width(); } width = qMax(2 * pw + _childSize.width(), headerLineWidth); height = qMax(_textSize.height(), _pixmapSize.height()) +2 * bdSize + _childSize.height() + pw; } return QSize(width, height); } void CompoundWidget::paintEvent(QPaintEvent *e) { QSize mySize = sizeHint(); QPainter painter(this); drawPossibleSelection(painter, mySize); int horLineY, childY; // draw top line if (_hidden) { horLineY = _pixmapSize.height() / 2; childY = _pixmapSize.height() + bdSize; _pixmapPos = QPoint(mySize.width() - pw - bdSize - _pixmapSize.width(), 0); painter.drawLine(pw, horLineY, _pixmapPos.x(), horLineY); painter.drawLine(mySize.width() - bdSize - pw, horLineY, mySize.width(), horLineY); painter.drawPixmap(_pixmapPos, _up); } else { int maxH = qMax(_textSize.height(), _pixmapSize.height()); int offset = 0; horLineY = maxH / 2; childY = maxH + bdSize; painter.drawLine(pw, horLineY, bdSize, horLineY); if (_textSize.width() != 0) { offset += pw + 2 * bdSize; painter.drawText(offset, horLineY - _textSize.height() / 2, bdSize + _textSize.width(), horLineY + _textSize.height() / 2, 0, _content->title()); offset += _textSize.width() + bdSize; } _pixmapPos = QPoint(mySize.width() - pw - bdSize - _pixmapSize.width(), horLineY - _pixmapSize.height() / 2); painter.drawLine(offset, horLineY, _pixmapPos.x(), horLineY); painter.drawPixmap(_pixmapPos, _down); painter.drawLine(mySize.width() - bdSize - pw, horLineY, mySize.width(), horLineY); } // draw rest frame painter.drawLine(0, horLineY, 0, mySize.height()); painter.drawLine(mySize.width() - pw, horLineY, mySize.width() - pw, mySize.height()); painter.drawLine(0, mySize.height() - pw, mySize.width(), mySize.height() - pw); // place/size child if (_hidden) { _child->hide(); painter.drawText(pw + bdSize, childY, pw + bdSize + _textSize.width(), childY + _textSize.height(), 0, _content->title()); } else { QSize curSize = _child->size(); QSize newSize = QSize(qMax(_child->sizeHint().width(), mySize.width() - 2 * pw), _child->sizeHint().height()); _child->move(pw, childY); if (curSize != newSize) { _child->resize(newSize); // I resized the child, so give it a chance to relect thus. _child->update(); } _child->show(); } RegExpWidget::paintEvent(e); } void CompoundWidget::slotConfigWindowClosed() { _editorWindow->updateContent(0); update(); } void CompoundWidget::slotConfigCanceled() { QDataStream stream(&_backup, QIODevice::ReadOnly); stream.setVersion(QDataStream::Qt_3_1); KWidgetStreamer streamer; streamer.fromStream(stream, _content); repaint(); } RegExp *CompoundWidget::regExp() const { return new CompoundRegExp(isSelected(), _content->title(), _content->description(), _hidden, _content->allowReplace(), _child->regExp()); } void CompoundWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && QRect(_pixmapPos, _pixmapSize).contains(event->pos())) { // Skip otherwise we will never see the mouse release // since it is eaten by Editor window. } else { SingleContainerWidget::mousePressEvent(event); } } void CompoundWidget::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && QRect(_pixmapPos, _pixmapSize).contains(event->pos())) { _hidden = !_hidden; _editorWindow->updateContent(0); repaint(); // is this necesary? _editorWindow->emitChange(); } else { SingleContainerWidget::mouseReleaseEvent(event); } } bool CompoundWidget::updateSelection(bool parentSelected) { if (_hidden) { bool changed = RegExpWidget::updateSelection(parentSelected); _child->selectWidget(_isSelected); if (changed) { repaint(); } return changed; } else { return SingleContainerWidget::updateSelection(parentSelected); } } int CompoundWidget::edit() { _configWindow->move(QCursor::pos() - QPoint(_configWindow->sizeHint().width() / 2, _configWindow->sizeHint().height() / 2)); QDataStream stream(&_backup, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_3_1); KWidgetStreamer streamer; streamer.toStream(_content, stream); return _configWindow->exec(); } int nextId() { static int counter = 0; return ++counter; } QPixmap CompoundWidget::getIcon(const QString &name) { return SmallIcon(name); } diff --git a/src/emacsregexpconverter.cpp b/src/emacsregexpconverter.cpp index 8c6734e..67f078f 100644 --- a/src/emacsregexpconverter.cpp +++ b/src/emacsregexpconverter.cpp @@ -1,250 +1,250 @@ /* * Copyright (c) 2002-2004 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "emacsregexpconverter.h" #include #include #include "regexp.h" #include "altnregexp.h" #include "concregexp.h" #include "textrangeregexp.h" #include "textregexp.h" #include "compoundregexp.h" #include "positionregexp.h" #include "repeatregexp.h" bool EmacsRegExpConverter::canParse() { return false; } QString EmacsRegExpConverter::toString(AltnRegExp *regexp, bool markSelection) { QString res; bool first = true; RegExpList list = regexp->children(); foreach (RegExp *r, list) { if (!first) { res += QLatin1String("\\|"); } first = false; res += toStr(r, markSelection); } return res; } QString EmacsRegExpConverter::toString(ConcRegExp *regexp, bool markSelection) { QString res; RegExpList list = regexp->children(); foreach (RegExp *r, list) { QString startPar = QString(); QString endPar = QString(); if (r->precedence() < regexp->precedence()) { startPar = QStringLiteral("\\("); endPar = QStringLiteral("\\)"); } res += startPar + toStr(r, markSelection) + endPar; } return res; } QString EmacsRegExpConverter::toString(LookAheadRegExp * /*regexp*/, bool /*markSelection*/) { static bool haveWarned = false; if (!haveWarned) { KMessageBox::sorry(nullptr, i18n("Look ahead regular expressions not supported in Emacs style")); haveWarned = true; } return QString(); } QString EmacsRegExpConverter::toString(TextRangeRegExp *regexp, bool /*markSelection*/) { QString txt; bool foundCarrot = false; bool foundDash = false; bool foundParenthesis = false; // print the single characters, but keep "^" as the very // last element of the characters. QStringList chars = regexp->chars(); for (int i = 0; i < chars.count(); i++) { if (chars.at(i).at(0) == QLatin1Char(']')) { foundParenthesis = true; } else if (chars.at(i).at(0) == QLatin1Char('-')) { foundDash = true; } else if (chars.at(i).at(0) == QLatin1Char('^')) { foundCarrot = true; } else { txt.append(chars.at(i).at(0)); } } // Now insert the ranges. foreach (const StringPair &elm, regexp->range()) { - txt.append(elm.first + QLatin1String("-") + elm.second); + txt.append(elm.first + QStringLiteral("-") + elm.second); } // Ok, its time to build each part of the regexp, here comes the rule: // if a ']' is one of the characters, then it must be the first one in the // list (after then opening '[' and eventually negation '^') // Next if a '-' is one of the characters, then it must come // finally if '^' is one of the characters, then it must not be the first // one! QString res = QStringLiteral("["); if (regexp->negate()) { res.append(QLatin1String("^")); } // a ']' must be the first character in teh range. if (foundParenthesis) { res.append(QLatin1String("]")); } // a '-' must be the first character ( only coming after a ']') if (foundDash) { res.append(QLatin1String("-")); } res += txt; // Insert equivalents to \s,\S,\d,\D,\w, and \W // non-digit, non-space, and non-word is not supported in Emacs style if (regexp->digit()) { res += QStringLiteral("0-9"); } if (regexp->space()) { res += QStringLiteral(" ") + QString(QLatin1Char((char)9)); // Tab char } if (regexp->wordChar()) { res += QStringLiteral("a-zA-Z"); } if (foundCarrot) { res.append(QLatin1Char('^')); } res.append(QLatin1String("]")); return res; } QString EmacsRegExpConverter::toString(CompoundRegExp *regexp, bool markSelection) { return toStr(regexp->child(), markSelection); } QString EmacsRegExpConverter::toString(DotRegExp * /*regexp*/, bool /*markSelection*/) { return QStringLiteral("."); } QString EmacsRegExpConverter::toString(PositionRegExp *regexp, bool /*markSelection*/) { static bool haveWarned = false; switch (regexp->position()) { case PositionRegExp::BEGLINE: return QStringLiteral("^"); case PositionRegExp::ENDLINE: return QStringLiteral("$"); case PositionRegExp::WORDBOUNDARY: case PositionRegExp::NONWORDBOUNDARY: if (!haveWarned) { KMessageBox::sorry(nullptr, i18n("Word boundary and non word boundary is not supported in Emacs syntax")); haveWarned = true; return QString(); } } return QString(); } QString EmacsRegExpConverter::toString(RepeatRegExp *regexp, bool markSelection) { RegExp *child = regexp->child(); QString cText = toStr(child, markSelection); QString startPar; QString endPar; if (child->precedence() < regexp->precedence()) { startPar = QStringLiteral("\\("); endPar = QStringLiteral("\\)"); } if (regexp->min() == 0 && regexp->max() == -1) { return startPar + cText + endPar + QStringLiteral("*"); } else if (regexp->min() == 0 && regexp->max() == 1) { return startPar + cText + endPar + QStringLiteral("?"); } else if (regexp->min() == 1 && regexp->max() == -1) { return startPar + cText + endPar + QStringLiteral("+"); } else { QString res = QString(); for (int i = 0; i < regexp->min(); ++i) { - res += QLatin1String("\\(") + cText + QLatin1String("\\)"); + res += QStringLiteral("\\(") + cText + QStringLiteral("\\)"); } if (regexp->max() != -1) { for (int i = regexp->min(); i < regexp->max(); ++i) { - res += QLatin1String("\\(") + cText + QLatin1String("\\)?"); + res += QStringLiteral("\\(") + cText + QStringLiteral("\\)?"); } } else { res += QLatin1String("+"); } return res; } } QString EmacsRegExpConverter::toString(TextRegExp *regexp, bool /*markSelection*/) { QList list; list << QLatin1Char('$') << QLatin1Char('^') << QLatin1Char('.') << QLatin1Char('*') << QLatin1Char('+') << QLatin1Char('?') << QLatin1Char('[') << QLatin1Char(']') << QLatin1Char('\\'); QString res = escape(regexp->text(), list, QLatin1Char('\\')); return res; } QString EmacsRegExpConverter::name() { return QStringLiteral("Emacs"); } int EmacsRegExpConverter::features() { return WordStart | WordEnd; } diff --git a/src/kregexpeditorprivate.cpp b/src/kregexpeditorprivate.cpp index 0ee8e92..48d6d6b 100644 --- a/src/kregexpeditorprivate.cpp +++ b/src/kregexpeditorprivate.cpp @@ -1,426 +1,426 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "kregexpeditorprivate.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "auxbuttons.h" #include "verifybuttons.h" #include "regexpbuttons.h" #include "userdefinedregexps.h" #include "scrollededitorwindow.h" #include "infopage.h" #include "verifier.h" #include "regexpconverter.h" #include "regexp.h" KRegExpEditorPrivate::KRegExpEditorPrivate(QWidget *parent) : QMainWindow(parent) , _updating(false) , _autoVerify(true) , _matchGreedy(false) { setMinimumSize(730, 300); setWindowFlags(Qt::Widget); // The DockWindows. _regExpButtons = new RegExpButtons(this, QStringLiteral("RegExpButton")); addToolBar(Qt::TopToolBarArea, _regExpButtons); _verifyButtons = new VerifyButtons(this, QStringLiteral("VerifyButtons")); addToolBar(Qt::TopToolBarArea, _verifyButtons); _auxButtons = new AuxButtons(this, QStringLiteral("AuxButtons")); addToolBar(Qt::TopToolBarArea, _auxButtons); _userRegExps = new UserDefinedRegExps(/*verArea1*/ this, /*"KRegExpEditorPrivate::userRegExps"*/ i18n("Compound regular expression:")); _userRegExps->setWhatsThis(i18n("In this window you will find predefined regular expressions. Both regular expressions " "you have developed and saved, and regular expressions shipped with the system.")); addDockWidget(Qt::LeftDockWidgetArea, _userRegExps); // Editor window _editor = new QSplitter(Qt::Vertical, this); _editor->setObjectName(QStringLiteral("KRegExpEditorPrivate::_editor")); _scrolledEditorWindow = new RegExpScrolledEditorWindow(_editor); _scrolledEditorWindow->setWhatsThis(i18n("In this window you will develop your regular expressions. " "Select one of the actions from the action buttons above, and click the mouse in this " "window to insert the given action.")); _info = new InfoPage(this); _info->setObjectName(QStringLiteral("_info")); _verifier = new Verifier(_editor); - connect(_verifier, SIGNAL(textChanged()), this, SLOT(maybeVerify())); + connect(_verifier, &QTextEdit::textChanged, this, &KRegExpEditorPrivate::maybeVerify); _verifier->setWhatsThis(i18n("

Type in some text in this window, and see what the regular expression you have developed matches.

" "

Each second match will be colored in red and each other match will be colored blue, simply so you " "can distinguish them from each other.

" "

If you select part of the regular expression in the editor window, then this part will be " "highlighted - This allows you to debug your regular expressions

")); _editor->hide(); _editor->setSizes(QList() << _editor->height() / 2 << _editor->height() / 2); QWidget *centralWidget = new QWidget(this); QHBoxLayout *layout = new QHBoxLayout(centralWidget); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(_editor); layout->addWidget(_info); setCentralWidget(centralWidget); // Connect the buttons connect(_regExpButtons, SIGNAL(clicked(int)), _scrolledEditorWindow, SLOT(slotInsertRegExp(int))); - connect(_regExpButtons, SIGNAL(doSelect()), _scrolledEditorWindow, SLOT(slotDoSelect())); + connect(_regExpButtons, &RegExpButtons::doSelect, _scrolledEditorWindow, &RegExpScrolledEditorWindow::slotDoSelect); connect(_userRegExps, SIGNAL(load(RegExp*)), _scrolledEditorWindow, SLOT(slotInsertRegExp(RegExp*))); connect(_regExpButtons, SIGNAL(clicked(int)), _userRegExps, SLOT(slotUnSelect())); connect(_regExpButtons, SIGNAL(doSelect()), _userRegExps, SLOT(slotUnSelect())); - connect(_userRegExps, SIGNAL(load(RegExp*)), _regExpButtons, SLOT(slotUnSelect())); + connect(_userRegExps, &UserDefinedRegExps::load, _regExpButtons, &RegExpButtons::slotUnSelect); - connect(_scrolledEditorWindow, SIGNAL(doneEditing()), _regExpButtons, SLOT(slotSelectNewAction())); - connect(_scrolledEditorWindow, SIGNAL(doneEditing()), _userRegExps, SLOT(slotSelectNewAction())); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::doneEditing, _regExpButtons, &RegExpButtons::slotSelectNewAction); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::doneEditing, _userRegExps, &UserDefinedRegExps::slotSelectNewAction); - connect(_regExpButtons, SIGNAL(clicked(int)), this, SLOT(slotShowEditor())); - connect(_userRegExps, SIGNAL(load(RegExp*)), this, SLOT(slotShowEditor())); - connect(_regExpButtons, SIGNAL(doSelect()), this, SLOT(slotShowEditor())); + connect(_regExpButtons, &RegExpButtons::clicked, this, &KRegExpEditorPrivate::slotShowEditor); + connect(_userRegExps, &UserDefinedRegExps::load, this, &KRegExpEditorPrivate::slotShowEditor); + connect(_regExpButtons, &RegExpButtons::doSelect, this, &KRegExpEditorPrivate::slotShowEditor); connect(_scrolledEditorWindow, SIGNAL(savedRegexp()), _userRegExps, SLOT(slotPopulateUserRegexps())); - connect(_auxButtons, SIGNAL(undo()), this, SLOT(slotUndo())); - connect(_auxButtons, SIGNAL(redo()), this, SLOT(slotRedo())); - connect(_auxButtons, SIGNAL(cut()), _scrolledEditorWindow, SLOT(slotCut())); - connect(_auxButtons, SIGNAL(copy()), _scrolledEditorWindow, SLOT(slotCopy())); - connect(_auxButtons, SIGNAL(paste()), _scrolledEditorWindow, SLOT(slotPaste())); - connect(_auxButtons, SIGNAL(save()), _scrolledEditorWindow, SLOT(slotSave())); - connect(_verifyButtons, SIGNAL(autoVerify(bool)), this, SLOT(setAutoVerify(bool))); - connect(_verifyButtons, SIGNAL(verify()), this, SLOT(doVerify())); - connect(_verifyButtons, SIGNAL(changeSyntax(QString)), this, SLOT(setSyntax(QString))); - connect(_verifyButtons, SIGNAL(matchGreedy(bool)), this, SLOT(setMatchGreedy(bool))); + connect(_auxButtons, &AuxButtons::undo, this, &KRegExpEditorPrivate::slotUndo); + connect(_auxButtons, &AuxButtons::redo, this, &KRegExpEditorPrivate::slotRedo); + connect(_auxButtons, &AuxButtons::cut, _scrolledEditorWindow, &RegExpScrolledEditorWindow::slotCut); + connect(_auxButtons, &AuxButtons::copy, _scrolledEditorWindow, &RegExpScrolledEditorWindow::slotCopy); + connect(_auxButtons, &AuxButtons::paste, _scrolledEditorWindow, &RegExpScrolledEditorWindow::slotPaste); + connect(_auxButtons, &AuxButtons::save, _scrolledEditorWindow, &RegExpScrolledEditorWindow::slotSave); + connect(_verifyButtons, &VerifyButtons::autoVerify, this, &KRegExpEditorPrivate::setAutoVerify); + connect(_verifyButtons, &VerifyButtons::verify, this, &KRegExpEditorPrivate::doVerify); + connect(_verifyButtons, &VerifyButtons::changeSyntax, this, &KRegExpEditorPrivate::setSyntax); + connect(_verifyButtons, &VerifyButtons::matchGreedy, this, &KRegExpEditorPrivate::setMatchGreedy); - connect(this, SIGNAL(canUndo(bool)), _auxButtons, SLOT(slotCanUndo(bool))); - connect(this, SIGNAL(canRedo(bool)), _auxButtons, SLOT(slotCanRedo(bool))); - connect(_scrolledEditorWindow, SIGNAL(anythingSelected(bool)), _auxButtons, SLOT(slotCanCut(bool))); - connect(_scrolledEditorWindow, SIGNAL(anythingSelected(bool)), _auxButtons, SLOT(slotCanCopy(bool))); - connect(_scrolledEditorWindow, SIGNAL(anythingOnClipboard(bool)), _auxButtons, SLOT(slotCanPaste(bool))); - connect(_scrolledEditorWindow, SIGNAL(canSave(bool)), _auxButtons, SLOT(slotCanSave(bool))); + connect(this, &KRegExpEditorPrivate::canUndo, _auxButtons, &AuxButtons::slotCanUndo); + connect(this, &KRegExpEditorPrivate::canRedo, _auxButtons, &AuxButtons::slotCanRedo); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::anythingSelected, _auxButtons, &AuxButtons::slotCanCut); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::anythingSelected, _auxButtons, &AuxButtons::slotCanCopy); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::anythingOnClipboard, _auxButtons, &AuxButtons::slotCanPaste); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::canSave, _auxButtons, &AuxButtons::slotCanSave); - connect(_scrolledEditorWindow, SIGNAL(verifyRegExp()), this, SLOT(maybeVerify())); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::verifyRegExp, this, &KRegExpEditorPrivate::maybeVerify); - connect(_verifyButtons, SIGNAL(loadVerifyText(QString)), this, SLOT(setVerifyText(QString))); + connect(_verifyButtons, &VerifyButtons::loadVerifyText, this, &KRegExpEditorPrivate::setVerifyText); _auxButtons->slotCanPaste(false); _auxButtons->slotCanCut(false); _auxButtons->slotCanCopy(false); _auxButtons->slotCanSave(false); // Line Edit QDockWidget *editDock = new QDockWidget(i18n("ASCII syntax:"), this); editDock->setFeatures(QDockWidget::NoDockWidgetFeatures); addDockWidget(Qt::BottomDockWidgetArea, editDock); QWidget *editDockWidget = new QWidget(editDock); editDock->setWidget(editDockWidget); QHBoxLayout *dockLayout = new QHBoxLayout(editDockWidget); dockLayout->setContentsMargins(0, 0, 0, 0); _regexpEdit = new QLineEdit(editDockWidget); dockLayout->addWidget(_regexpEdit); _regexpEdit->setFocus(Qt::OtherFocusReason); _regexpEdit->setClearButtonEnabled(true); _regexpEdit->setWhatsThis(i18n("

This is the regular expression in ASCII syntax. You are likely only " "to be interested in this if you are a programmer, and need to " "develop a regular expression using QRegExp.

" "

You may develop your regular expression both by using the graphical " "editor, and by typing the regular expression in this line edit.

")); QPixmap pix = KIconLoader::global()->loadIcon(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kregexpeditor/pics/error.png")), KIconLoader::Toolbar); _error = new QLabel(editDockWidget); _error->setPixmap(pix); dockLayout->addWidget(_error); _error->hide(); _timer = new QTimer(this); _timer->setSingleShot(true); - connect(_scrolledEditorWindow, SIGNAL(change()), this, SLOT(slotUpdateLineEdit())); - connect(_regexpEdit, SIGNAL(textChanged(QString)), this, SLOT(slotTriggerUpdate())); - connect(_timer, SIGNAL(timeout()), this, SLOT(slotTimeout())); + connect(_scrolledEditorWindow, &RegExpScrolledEditorWindow::change, this, &KRegExpEditorPrivate::slotUpdateLineEdit); + connect(_regexpEdit, &QLineEdit::textChanged, this, &KRegExpEditorPrivate::slotTriggerUpdate); + connect(_timer, &QTimer::timeout, this, &KRegExpEditorPrivate::slotTimeout); // Push an initial empty element on the stack. _undoStack.push(_scrolledEditorWindow->regExp()); (void)new QShortcut(Qt::CTRL + Qt::Key_Z, this, SLOT(slotUndo())); (void)new QShortcut(Qt::CTRL + Qt::Key_R, this, SLOT(slotRedo())); setSyntax(QStringLiteral("Qt")); } KRegExpEditorPrivate::~KRegExpEditorPrivate() { qDeleteAll(_undoStack); qDeleteAll(_redoStack); } QString KRegExpEditorPrivate::regexp() { RegExp *regexp = _scrolledEditorWindow->regExp(); QString res = RegExpConverter::current()->toStr(regexp, false); delete regexp; return res; } void KRegExpEditorPrivate::slotUpdateEditor(const QString &txt) { _updating = true; bool ok; if (!RegExpConverter::current()->canParse()) { // This can happend if the application set a text through the API. //qDebug("cannot parse"); } else { RegExp *result = RegExpConverter::current()->parse(txt, &ok); if (ok) { QList list = _userRegExps->regExps(); foreach (CompoundRegExp *regExp, list) { result->replacePart(regExp); } _scrolledEditorWindow->slotSetRegExp(result); _error->hide(); maybeVerify(); recordUndoInfo(); result->check(_errorMap); } else { _error->show(); if (_autoVerify) { _verifier->clearRegexp(); } } delete result; } _updating = false; } void KRegExpEditorPrivate::slotUpdateLineEdit() { if (_updating) { return; } _updating = true; RegExp *regexp = _scrolledEditorWindow->regExp(); regexp->check(_errorMap); QString str = RegExpConverter::current()->toStr(regexp, false); _regexpEdit->setText(str); delete regexp; recordUndoInfo(); _updating = false; } void KRegExpEditorPrivate::recordUndoInfo() { Q_ASSERT(_updating); // Update undo/redo stacks RegExp *regexp = _scrolledEditorWindow->regExp(); if (regexp->toXmlString() != _undoStack.top()->toXmlString()) { _undoStack.push(regexp); qDeleteAll(_redoStack); _redoStack = QStack(); emitUndoRedoSignals(); } } void KRegExpEditorPrivate::slotRedo() { if (!_redoStack.isEmpty()) { _undoStack.push(_redoStack.pop()); _scrolledEditorWindow->slotSetRegExp(_undoStack.top()); slotUpdateLineEdit(); emitUndoRedoSignals(); maybeVerify(); } } void KRegExpEditorPrivate::slotUndo() { if (_undoStack.count() > 1) { _redoStack.push(_undoStack.pop()); _scrolledEditorWindow->slotSetRegExp(_undoStack.top()); slotUpdateLineEdit(); emitUndoRedoSignals(); maybeVerify(); } } void KRegExpEditorPrivate::slotShowEditor() { _info->hide(); _editor->show(); } void KRegExpEditorPrivate::emitUndoRedoSignals() { Q_EMIT canUndo(_undoStack.count() > 1); Q_EMIT changes(_undoStack.count() > 1); Q_EMIT canRedo(_redoStack.count() > 0); } void KRegExpEditorPrivate::slotSetRegexp(const QString ®exp) { _regexpEdit->setText(regexp); } void KRegExpEditorPrivate::slotTriggerUpdate() { /* ### Guess this timeout value should be configurable somewhere, or (even * better: do some kind of benchmark each time the editor view gets updated * to measure how long it takes on the client system to render the editor * with the current complexity. That way we'd get good response times for * simple regexps, and flicker-free display for complex regexps. * - Frerich */ if (!_updating) { _timer->start(300); slotShowEditor(); } } void KRegExpEditorPrivate::slotTimeout() { slotUpdateEditor(_regexpEdit->text()); } void KRegExpEditorPrivate::setMatchText(const QString &text) { bool autoVerify = _autoVerify; _autoVerify = false; _verifier->setText(text); _autoVerify = autoVerify; } void KRegExpEditorPrivate::maybeVerify() { if (_autoVerify) { doVerify(); } else { _verifyButtons->setMatchCount(-1); } } void KRegExpEditorPrivate::doVerify() { bool autoVerify = _autoVerify; // prevent loop due to verify emit changed, which calls maybeVerify _autoVerify = false; RegExp *regexp = _scrolledEditorWindow->regExp(); _verifier->verify(RegExpConverter::current()->toStr(regexp, true)); delete regexp; _autoVerify = autoVerify; } void KRegExpEditorPrivate::setAutoVerify(bool on) { _autoVerify = on; if (!_autoVerify) { _verifier->clearRegexp(); } else { doVerify(); } } void KRegExpEditorPrivate::setVerifyText(const QString &fileName) { bool autoVerify = _autoVerify; _autoVerify = false; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { KMessageBox::sorry(nullptr, i18n("Could not open file '%1' for reading", fileName)); } else { QTextStream s(&file); QString txt = s.readAll(); file.close(); RegExp *regexp = _scrolledEditorWindow->regExp(); _verifier->setText(txt); _verifier->verify(RegExpConverter::current()->toStr(regexp, true)); delete regexp; } _autoVerify = autoVerify; } void KRegExpEditorPrivate::setCaseSensitive(bool b) { _verifier->setCaseSensitive(b); } void KRegExpEditorPrivate::setMinimal(bool b) { _verifier->setMinimal(b); } void KRegExpEditorPrivate::setSyntax(const QString &syntax) { RegExpConverter *converter = _verifyButtons->setSyntax(syntax); RegExpConverter::setCurrent(converter); if (converter->canParse()) { _regexpEdit->setReadOnly(false); _regexpEdit->setBackgroundRole(QPalette::Base); } else { _regexpEdit->setReadOnly(true); _regexpEdit->setBackgroundRole(QPalette::Window); } _regExpButtons->setFeatures(converter->features()); _verifier->setHighlighter(converter->highlighter(_verifier)); slotUpdateLineEdit(); } void KRegExpEditorPrivate::showHelp() { _info->show(); _editor->hide(); } void KRegExpEditorPrivate::setAllowNonQtSyntax(bool b) { _verifyButtons->setAllowNonQtSyntax(b); } void KRegExpEditorPrivate::setMatchGreedy(bool b) { _matchGreedy = b; _verifier->setMinimal(!b); doVerify(); } diff --git a/src/qtregexpconverter.cpp b/src/qtregexpconverter.cpp index df53539..f439b2f 100644 --- a/src/qtregexpconverter.cpp +++ b/src/qtregexpconverter.cpp @@ -1,304 +1,304 @@ /* * Copyright (c) 2002-2004 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "qtregexpconverter.h" #include "qtregexphighlighter.h" #include "regexp.h" #include "textregexp.h" #include "altnregexp.h" #include "concregexp.h" #include "lookaheadregexp.h" #include "textrangeregexp.h" #include "compoundregexp.h" #include "dotregexp.h" #include "positionregexp.h" #include "repeatregexp.h" extern RegExp *parseQtRegExp(const QString &qstr, bool *ok); bool QtRegExpConverter::canParse() { return true; } RegExp *QtRegExpConverter::parse(const QString &txt, bool *ok) { return parseQtRegExp(txt, ok); } QString QtRegExpConverter::toString(AltnRegExp *regexp, bool markSelection) { QString res; bool first = true; RegExpList list = regexp->children(); foreach (RegExp *r, list) { if (!first) { res += QLatin1String("|"); } first = false; if (markSelection && !regexp->isSelected() && r->isSelected()) { - res += QLatin1String("(") + toStr(r, markSelection) + QLatin1String(")"); + res += QStringLiteral("(") + toStr(r, markSelection) + QStringLiteral(")"); } else { res += toStr(r, markSelection); } } return res; } QString QtRegExpConverter::toString(ConcRegExp *regexp, bool markSelection) { QString res; bool childSelected = false; RegExpList list = regexp->children(); foreach (RegExp *r, list) { QString startPar = QString(); QString endPar = QString(); if (r->precedence() < regexp->precedence()) { if (markSelection) { startPar = QStringLiteral("(?:"); } else { startPar = QStringLiteral("("); } endPar = QStringLiteral(")"); } // Note these two have different tests! They are activated in each their iteration of the loop. if (markSelection && !childSelected && !regexp->isSelected() && r->isSelected()) { res += QLatin1String("("); childSelected = true; } if (markSelection && childSelected && !regexp->isSelected() && !r->isSelected()) { res += QLatin1String(")"); childSelected = false; } res += startPar + toStr(r, markSelection) + endPar; } if (markSelection && childSelected && !regexp->isSelected()) { res += QLatin1String(")"); } return res; } QString QtRegExpConverter::toString(LookAheadRegExp *regexp, bool markSelection) { if (regexp->lookAheadType() == LookAheadRegExp::POSITIVE) { - return QLatin1String("(?=") + toStr(regexp->child(), markSelection) + QStringLiteral(")"); + return QStringLiteral("(?=") + toStr(regexp->child(), markSelection) + QStringLiteral(")"); } else { - return QLatin1String("(?!") + toStr(regexp->child(), markSelection) + QStringLiteral(")"); + return QStringLiteral("(?!") + toStr(regexp->child(), markSelection) + QStringLiteral(")"); } } QString QtRegExpConverter::toString(TextRangeRegExp *regexp, bool /*markSelection*/) { QString txt; bool foundCarrot = false; bool foundDash = false; bool foundParenthesis = false; // Now print the rest of the single characters, but keep "^" as the very // last element of the characters. QStringList chars = regexp->chars(); for (int i = 0; i < chars.count(); i++) { if (chars.at(i).at(0) == QLatin1Char(']')) { foundParenthesis = true; } else if (chars.at(i).at(0) == QLatin1Char('-')) { foundDash = true; } else if (chars.at(i).at(0) == QLatin1Char('^')) { foundCarrot = true; } else { txt.append(chars.at(i).at(0)); } } // Now insert the ranges. foreach (const StringPair &elm, regexp->range()) { - txt.append(elm.first + QLatin1String("-") + elm.second); + txt.append(elm.first + QStringLiteral("-") + elm.second); } // Ok, its time to build each part of the regexp, here comes the rule: // if a ']' is one of the characters, then it must be the first one in the // list (after then opening '[' and eventually negation '^') // Next if a '-' is one of the characters, then it must come // finally if '^' is one of the characters, then it must not be the first // one! QString res = QStringLiteral("["); if (regexp->negate()) { res.append(QLatin1String("^")); } // a ']' must be the first character in teh range. if (foundParenthesis) { res.append(QLatin1String("]")); } // a '-' must be the first character ( only coming after a ']') if (foundDash) { res.append(QLatin1String("-")); } res += txt; // Insert \s,\S,\d,\D,\w, and \W if (regexp->digit()) { res += QStringLiteral("\\d"); } if (regexp->nonDigit()) { res += QStringLiteral("\\D"); } if (regexp->space()) { res += QStringLiteral("\\s"); } if (regexp->nonSpace()) { res += QStringLiteral("\\S"); } if (regexp->wordChar()) { res += QStringLiteral("\\w"); } if (regexp->nonWordChar()) { res += QStringLiteral("\\W"); } if (foundCarrot) { res.append(QLatin1Char('^')); } res.append(QLatin1String("]")); return res; } QString QtRegExpConverter::toString(CompoundRegExp *regexp, bool markSelection) { if (markSelection && !regexp->isSelected() && regexp->child()->isSelected()) { - return QLatin1String("(") + toStr(regexp->child(), markSelection) + QLatin1String(")"); + return QStringLiteral("(") + toStr(regexp->child(), markSelection) + QStringLiteral(")"); } else { return toStr(regexp->child(), markSelection); } } QString QtRegExpConverter::toString(DotRegExp * /*regexp*/, bool /*markSelection*/) { return QStringLiteral("."); } QString QtRegExpConverter::toString(PositionRegExp *regexp, bool /*markSelection*/) { switch (regexp->position()) { case PositionRegExp::BEGLINE: return QStringLiteral("^"); case PositionRegExp::ENDLINE: return QStringLiteral("$"); case PositionRegExp::WORDBOUNDARY: return QStringLiteral("\\b"); case PositionRegExp::NONWORDBOUNDARY: return QStringLiteral("\\B"); } Q_ASSERT(false); return QString(); } QString QtRegExpConverter::toString(RepeatRegExp *regexp, bool markSelection) { RegExp *child = regexp->child(); QString cText = toStr(child, markSelection); QString startPar; QString endPar; QString quantity; if (markSelection) { if (!regexp->isSelected() && child->isSelected()) { startPar = QStringLiteral("("); endPar = QStringLiteral(")"); } else if (child->precedence() < regexp->precedence()) { startPar = QStringLiteral("(?:"); endPar = QStringLiteral(")"); } } else if (child->precedence() < regexp->precedence()) { startPar = QStringLiteral("("); endPar = QStringLiteral(")"); } if (regexp->min() == 0 && regexp->max() == -1) { quantity = QStringLiteral("*"); } else if (regexp->min() == 0 && regexp->max() == 1) { quantity = QStringLiteral("?"); } else if (regexp->min() == 1 && regexp->max() == -1) { quantity = QStringLiteral("+"); } else if (regexp->max() == -1) { quantity = QStringLiteral("{") +QString::number(regexp->min()) + QStringLiteral(",") +QStringLiteral("}"); } else { quantity = QStringLiteral("{") +QString::number(regexp->min()) + QStringLiteral(",") +QString::number(regexp->max()) + QStringLiteral("}"); } return startPar + cText + endPar + quantity; } QString QtRegExpConverter::toString(TextRegExp *regexp, bool /*markSelection*/) { QList list; list << QLatin1Char('$') << QLatin1Char('^') << QLatin1Char('.') << QLatin1Char('*') << QLatin1Char('+') << QLatin1Char('?') << QLatin1Char('[') << QLatin1Char(']') << QLatin1Char('\\') << QLatin1Char('{') << QLatin1Char('}') << QLatin1Char('(') << QLatin1Char(')') << QLatin1Char('|'); QString res = escape(regexp->text(), list, QLatin1Char('\\')); return res; } QString QtRegExpConverter::name() { return QStringLiteral("Qt"); } int QtRegExpConverter::features() { return WordBoundary | NonWordBoundary | PosLookAhead | NegLookAhead | CharacterRangeNonItems | ExtRange; } RegexpHighlighter *QtRegExpConverter::highlighter(QTextEdit *edit) // krazy:exclude=qclasses { return new QtRegexpHighlighter(edit); } diff --git a/src/regexpbuttons.cpp b/src/regexpbuttons.cpp index 747f9db..f9b3b2e 100644 --- a/src/regexpbuttons.cpp +++ b/src/regexpbuttons.cpp @@ -1,186 +1,186 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "regexpbuttons.h" #include #include #include #include #include #include "dcbutton.h" #include "regexpconverter.h" RegExpButtons::RegExpButtons(QWidget *parent, const QString &name) : QToolBar(name, parent) , _keepMode(false) { _grp = new QButtonGroup(this); _grp->setExclusive(true); // The "select" button. _selectBut = new QToolButton(this); QPixmap pix = KIconLoader::global()->loadIcon(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kregexpeditor/pics/select.png")), KIconLoader::Toolbar); _selectBut->setIcon(static_cast(pix)); addWidget(_selectBut); _grp->addButton(_selectBut); _selectBut->setCheckable(true); - connect(_selectBut, SIGNAL(clicked()), SIGNAL(doSelect())); - connect(_selectBut, SIGNAL(clicked()), this, SLOT(slotSetNonKeepMode())); + connect(_selectBut, &QAbstractButton::clicked, this, &RegExpButtons::doSelect); + connect(_selectBut, &QAbstractButton::clicked, this, &RegExpButtons::slotSetNonKeepMode); _selectBut->setToolTip(i18n("Selection tool")); _selectBut->setWhatsThis(i18n("

This will change the state of the editor to selection state.

" "

In this state you will not be inserting regexp items, but instead select them. " "To select a number of items, press down the left mouse button and drag it over the items.

" "

When you have selected a number of items, you may use cut/copy/paste. These functions are " "found in the right mouse button menu.

")); // Insert buttons. DoubleClickButton *but; but = insert(TEXT, QStringLiteral("text"), i18n("Text"), i18n("This will insert a text field, where you may write text. The text you write will " "be matched literally. (i.e. you do not need to escape any characters)")); addWidget(but); but = insert(CHARSET, QStringLiteral("characters"), i18n("A single character specified in a range"), i18n("

This will match a single character from a predefined range.

" "

When you insert this widget a dialog box will appear, which lets you specify " "which characters this regexp item will match.

")); addWidget(but); but = insert(DOT, QStringLiteral("anychar"), i18n("Any character"), i18n("This will match any single character")); addWidget(but); but = insert(REPEAT, QStringLiteral("repeat"), i18n("Repeated content"), i18n("This regexp item will repeat the regexp items it surrounds " "a specified number of times.
" "The number of times to repeat may be specified using ranges; e.g. it could be specified " "that it should match from 2 to 4 times, that it should match exactly 5 times, or " "that it should match at least one time.
" "Examples:
" "If you specify that it should match any time, and the content it surrounds " "is abc, then this regexp item will match the empty string, " "the string abc, the string abcabc, the string abcabcabcabc, " "etc.
")); addWidget(but); but = insert(ALTN, QStringLiteral("altn"), i18n("Alternatives"), i18n("

This regexp item will match any of its alternatives.

" "

Alternatives are specified by placing regexp items on top of " "each other inside this widget.

")); addWidget(but); but = insert(COMPOUND, QStringLiteral("compound"), i18n("Compound regexp"), i18n("This regexp item serves two purposes:" "
  • It makes it possible for you to collapse a huge regexp item into " "a small box. This makes it easier for you to get an overview of large " "regexp items. This is especially useful if you load a predefined regexp item " "that you perhaps do not care about the inner workings of.")); addWidget(but); but = insert(BEGLINE, QStringLiteral("begline"), i18n("Beginning of line"), i18n("This will match the beginning of a line.")); addWidget(but); but = insert(ENDLINE, QStringLiteral("endline"), i18n("End of line"), i18n("This will match the end of a line.")); addWidget(but); _wordBoundary = insert(WORDBOUNDARY, QStringLiteral("wordboundary"), i18n("Word boundary"), i18n("This asserts a word boundary (This part does not actually match any characters)")); addWidget(_wordBoundary); _nonWordBoundary = insert(NONWORDBOUNDARY, QStringLiteral("nonwordboundary"), i18n("Non Word boundary"), i18n("This asserts a non-word boundary " "(This part does not actually match any characters)")); addWidget(_nonWordBoundary); _posLookAhead = insert(POSLOOKAHEAD, QStringLiteral("poslookahead"), i18n("Positive Look Ahead"), i18n("This asserts a regular expression (This part does not actually match any characters). " "You can only use this at the end of a regular expression.")); addWidget(_posLookAhead); _negLookAhead = insert(NEGLOOKAHEAD, QStringLiteral("neglookahead"), i18n("Negative Look Ahead"), i18n("This asserts a regular expression that must not match " "(This part does not actually match any characters). " "You can only use this at the end of a regular expression.")); addWidget(_negLookAhead); } DoubleClickButton *RegExpButtons::insert(RegExpType tp, const QString &name, const QString &tooltip, const QString &whatsthis) { QPixmap pix = KIconLoader::global()->loadIcon(QStandardPaths::locate(QStandardPaths::GenericDataLocation, - QLatin1String("kregexpeditor/pics/") + name + QLatin1String( + QStringLiteral("kregexpeditor/pics/") + name + QStringLiteral( ".png")), KIconLoader::Toolbar); DoubleClickButton *but = new DoubleClickButton(pix, this, QStringLiteral("RegExpButtons::but")); connect(but, &DoubleClickButton::clicked, [this, tp](){ Q_EMIT clicked(tp); }); - connect(but, SIGNAL(clicked()), this, SLOT(slotSetNonKeepMode())); - connect(but, SIGNAL(doubleClicked()), this, SLOT(slotSetKeepMode())); + connect(but, &QAbstractButton::clicked, this, &RegExpButtons::slotSetNonKeepMode); + connect(but, &DoubleClickButton::doubleClicked, this, &RegExpButtons::slotSetKeepMode); _grp->addButton(but); but->setCheckable(true); but->setToolTip(tooltip); but->setWhatsThis(whatsthis); return but; } void RegExpButtons::slotUnSelect() { if (_grp->checkedId() != -1) { QToolButton *pb = static_cast(_grp->checkedButton()); if (pb) { pb->setChecked(false); } } } void RegExpButtons::slotSetKeepMode() { _keepMode = true; } void RegExpButtons::slotSetNonKeepMode() { _keepMode = false; } void RegExpButtons::slotSelectNewAction() { if (!_keepMode) { Q_EMIT doSelect(); _selectBut->click(); } } void RegExpButtons::setFeatures(int features) { _wordBoundary->setVisible(features & RegExpConverter::WordBoundary); _nonWordBoundary->setVisible(features & RegExpConverter::NonWordBoundary); _posLookAhead->setVisible(features & RegExpConverter::PosLookAhead); _negLookAhead->setVisible(features & RegExpConverter::NegLookAhead); } diff --git a/src/repeatwidget.cpp b/src/repeatwidget.cpp index f8e3ef5..f441557 100644 --- a/src/repeatwidget.cpp +++ b/src/repeatwidget.cpp @@ -1,371 +1,371 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "repeatwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include "kwidgetstreamer.h" #include "concwidget.h" #include "repeatregexp.h" RepeatWidget::RepeatWidget(RegExpEditorWindow *editorWindow, QWidget *parent) : SingleContainerWidget(editorWindow, parent) { _child = new ConcWidget(editorWindow, this); init(); } RepeatWidget::RepeatWidget(RepeatRegExp *regexp, RegExpEditorWindow *editorWindow, QWidget *parent) : SingleContainerWidget(editorWindow, parent) { init(); RegExpWidget *child = WidgetFactory::createWidget(regexp->child(), editorWindow, this); if (!(_child = dynamic_cast(child))) { _child = new ConcWidget(editorWindow, child, this); } if (regexp->max() == -1) { if (regexp->min() == 0) { _content->set(RepeatRangeWindow::ANY, regexp->min(), regexp->max()); } else { _content->set(RepeatRangeWindow::ATLEAST, regexp->min(), regexp->max()); // krazy:exclude=spelling } } else { if (regexp->min() == 0) { _content->set(RepeatRangeWindow::ATMOST, regexp->min(), regexp->max()); } else if (regexp->min() == regexp->max()) { _content->set(RepeatRangeWindow::EXACTLY, regexp->min(), regexp->max()); } else { _content->set(RepeatRangeWindow::MINMAX, regexp->min(), regexp->max()); } } } void RepeatWidget::init() { _configWindow = new QDialog(this); _configWindow->setWindowTitle(i18n("Number of Times to Repeat Content")); QVBoxLayout *mainLayout = new QVBoxLayout; _configWindow->setLayout(mainLayout); _content = new RepeatRangeWindow(_configWindow); - connect(_configWindow, SIGNAL(rejected()), this, SLOT(slotConfigCanceled())); - connect(_configWindow, SIGNAL(finished(int)), this, SLOT(slotConfigWindowClosed())); + connect(_configWindow, &QDialog::rejected, this, &RepeatWidget::slotConfigCanceled); + connect(_configWindow, &QDialog::finished, this, &RepeatWidget::slotConfigWindowClosed); mainLayout->addWidget(_content); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); okButton->setDefault(true); okButton->setShortcut(Qt::CTRL | Qt::Key_Return); mainLayout->addWidget(buttonBox); - _configWindow->connect(buttonBox, SIGNAL(accepted()), _configWindow, SLOT(accept())); - _configWindow->connect(buttonBox, SIGNAL(rejected()), _configWindow, SLOT(reject())); + _configWindow->connect(buttonBox, &QDialogButtonBox::accepted, _configWindow, &QDialog::accept); + _configWindow->connect(buttonBox, &QDialogButtonBox::rejected, _configWindow, &QDialog::reject); } QSize RepeatWidget::sizeHint() const { // TODO: Merge with LookAheadWidget::sizeHint QFontMetrics metrics = fontMetrics(); _textSize = metrics.size(0, _content->text()); _childSize = _child->sizeHint(); int height = _textSize.height() + bdSize + _childSize.height() + bdSize + 2 * pw; int width = 2 * pw + qMax(_childSize.width(), 4 * bdSize + _textSize.width()); return QSize(width, height); } void RepeatWidget::paintEvent(QPaintEvent *e) { // TODO: Merge with LookAheadWidget::paintEvent QSize mySize = sizeHint(); QPainter painter(this); drawPossibleSelection(painter, mySize); // move the child to its position and resize it. _child->move(pw, _textSize.height() + bdSize); QSize curChildSize = _child->size(); QSize newChildSize = QSize(mySize.width() - 2 * pw, _childSize.height()); if (curChildSize != newChildSize) { _child->resize(newChildSize); // I resized the child, so give it a chance to relect thus. _child->update(); } // Draw the border and the text. int startY = _textSize.height() / 2; // Top lines and text painter.drawLine(pw, startY, bdSize, startY); painter.drawText(pw + 2 * bdSize, 0, _textSize.width(), _textSize.height(), 0, _content->text()); int offset = pw + 3 * bdSize + _textSize.width(); painter.drawLine(offset, startY, mySize.width() - pw, startY); // horizontal lines painter.drawLine(0, startY, 0, mySize.height() - pw); painter.drawLine(mySize.width() - pw, startY, mySize.width() - pw, mySize.height() - pw); // buttom line painter.drawLine(0, mySize.height() - pw, mySize.width() - pw, mySize.height() - pw); SingleContainerWidget::paintEvent(e); } RegExp *RepeatWidget::regExp() const { return new RepeatRegExp(isSelected(), _content->min(), _content->max(), _child->regExp()); } void RepeatWidget::slotConfigWindowClosed() { _editorWindow->updateContent(0); update(); } void RepeatWidget::slotConfigCanceled() { QDataStream stream(&_backup, QIODevice::ReadOnly); stream.setVersion(QDataStream::Qt_3_1); KWidgetStreamer streamer; streamer.fromStream(stream, _content); repaint(); } int RepeatWidget::edit() { _configWindow->move(QCursor::pos() - QPoint(_configWindow->sizeHint().width() / 2, _configWindow->sizeHint().height() / 2)); QDataStream stream(&_backup, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_3_1); KWidgetStreamer streamer; streamer.toStream(_content, stream); return _configWindow->exec(); } //-------------------------------------------------------------------------------- RepeatRangeWindow::RepeatRangeWindow(QWidget *parent) : QWidget(parent) { QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(0, 0, 0, 0); _groupWidget = new QGroupBox(i18n("Times to Match")); mainLayout->addWidget(_groupWidget); _group = new QButtonGroup(this); QGridLayout *groupLayout = new QGridLayout(_groupWidget); // Any number of times QRadioButton *radioBut = new QRadioButton(i18n("Any number of times (including zero times)")); radioBut->setObjectName(QStringLiteral("RepeatRangeWindow::choice any times")); groupLayout->addWidget(radioBut, 0, 0, 1, 3); _group->addButton(radioBut, ANY); radioBut->click(); createLine(groupLayout, i18n("At least"), &_leastTimes, ATLEAST); // krazy:exclude=spelling createLine(groupLayout, i18n("At most"), &_mostTimes, ATMOST); createLine(groupLayout, i18n("Exactly"), &_exactlyTimes, EXACTLY); // from ___ to ___ times radioBut = new QRadioButton(i18n("From")); radioBut->setObjectName(QStringLiteral("RepeatRangeWindow::from")); groupLayout->addWidget(radioBut, 4, 0); _group->addButton(radioBut, MINMAX); _rangeFrom = new QSpinBox(); _rangeFrom->setRange(1, 999); _rangeFrom->setSingleStep(1); groupLayout->addWidget(_rangeFrom, 4, 1); QHBoxLayout *layout = new QHBoxLayout(); QLabel *label = new QLabel(i18n("to")); layout->addWidget(label); _rangeTo = new QSpinBox(); _rangeTo->setRange(1, 999); _rangeTo->setSingleStep(1); layout->addWidget(_rangeTo); label = new QLabel(i18n("time(s)")); layout->addWidget(label); groupLayout->addLayout(layout, 4, 2); connect(_rangeFrom, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateMaxVal(int))); connect(_rangeTo, SIGNAL(valueChanged(int)), this, SLOT(slotUpdateMinVal(int))); connect(_group, SIGNAL(buttonClicked(int)), this, SLOT(slotItemChange(int))); _group->button(ANY)->click(); } void RepeatRangeWindow::createLine(QGridLayout *layout, const QString &text, QSpinBox **spin, REPEATTYPE tp) { int row = layout->rowCount(); QRadioButton *radioBut = new QRadioButton(text); layout->addWidget(radioBut, row, 0); *spin = new QSpinBox(); (*spin)->setRange(1, 999); (*spin)->setSingleStep(1); (*spin)->setValue(1); layout->addWidget(*spin, row, 1); QLabel *label = new QLabel(i18n("time(s)")); layout->addWidget(label, row, 2, 1, 2); _group->addButton(radioBut, tp); } void RepeatRangeWindow::slotItemChange(int which) { _leastTimes->setEnabled(false); _mostTimes->setEnabled(false); _exactlyTimes->setEnabled(false); _rangeFrom->setEnabled(false); _rangeTo->setEnabled(false); switch (which) { case ANY: break; case ATLEAST: _leastTimes->setEnabled(true); break; // krazy:exclude=spelling case ATMOST: _mostTimes->setEnabled(true); break; case EXACTLY: _exactlyTimes->setEnabled(true); break; case MINMAX: _rangeFrom->setEnabled(true); _rangeTo->setEnabled(true); break; } } void RepeatRangeWindow::slotUpdateMinVal(int maxVal) { if (_rangeFrom->value() > maxVal) { _rangeFrom->setValue(maxVal); } } void RepeatRangeWindow::slotUpdateMaxVal(int minVal) { if (_rangeTo->value() < minVal) { _rangeTo->setValue(minVal); } } QString RepeatRangeWindow::text() { switch (_group->checkedId()) { case ANY: return i18n("Repeated Any Number of Times"); case ATLEAST: return i18np("Repeated at Least 1 Time", "Repeated at Least %1 Times", _leastTimes->value()); // krazy:exclude=spelling case ATMOST: return i18np("Repeated at Most 1 Time", "Repeated at Most %1 Times", _mostTimes->value()); case EXACTLY: return i18np("Repeated Exactly 1 Time", "Repeated Exactly %1 Times", _exactlyTimes->value()); case MINMAX: return i18n("Repeated From %1 to %2 Times", _rangeFrom->value(), _rangeTo->value()); } qFatal("Fall through!"); return QString(); } int RepeatRangeWindow::min() { switch (_group->checkedId()) { case ANY: return 0; case ATLEAST: return _leastTimes->value(); // krazy:exclude=spelling case ATMOST: return 0; case EXACTLY: return _exactlyTimes->value(); case MINMAX: return _rangeFrom->value(); } qFatal("Fall through!"); return -1; } int RepeatRangeWindow::max() { switch (_group->checkedId()) { case ANY: return -1; case ATLEAST: return -1; // krazy:exclude=spelling case ATMOST: return _mostTimes->value(); case EXACTLY: return _exactlyTimes->value(); case MINMAX: return _rangeTo->value(); } qFatal("Fall through!"); return -1; } void RepeatRangeWindow::set(REPEATTYPE tp, int min, int max) { _group->button(tp)->click(); switch (tp) { case ANY: break; case ATLEAST: // krazy:exclude=spelling _leastTimes->setValue(min); break; case ATMOST: _mostTimes->setValue(max); break; case EXACTLY: _exactlyTimes->setValue(min); break; case MINMAX: _rangeFrom->setValue(min); _rangeTo->setValue(max); break; } } diff --git a/src/scrollededitorwindow.cpp b/src/scrollededitorwindow.cpp index 586cf7d..8e45337 100644 --- a/src/scrollededitorwindow.cpp +++ b/src/scrollededitorwindow.cpp @@ -1,124 +1,124 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "scrollededitorwindow.h" #include #include #include #include "regexpeditorwindow.h" RegExpScrolledEditorWindow::RegExpScrolledEditorWindow(QWidget *parent) : QWidget(parent) { _scrollArea = new QScrollArea(this); _editorWindow = new RegExpEditorWindow(this); _scrollArea->setWidget(_editorWindow); _scrollArea->setWidgetResizable(true); // Morten Sjøgren: This is for some reason required for pasting to work. _scrollArea->ensureWidgetVisible(_editorWindow); - connect(_editorWindow, SIGNAL(contentChanged(QPoint)), - this, SLOT(slotUpdateContentSize(QPoint))); + connect(_editorWindow, &RegExpEditorWindow::contentChanged, + this, &RegExpScrolledEditorWindow::slotUpdateContentSize); - connect(_editorWindow, SIGNAL(scrolling(QPoint)), - this, SLOT(slotScroll(QPoint))); + connect(_editorWindow, &RegExpEditorWindow::scrolling, + this, &RegExpScrolledEditorWindow::slotScroll); - connect(_editorWindow, SIGNAL(doneEditing()), this, SIGNAL(doneEditing())); + connect(_editorWindow, &RegExpEditorWindow::doneEditing, this, &RegExpScrolledEditorWindow::doneEditing); - connect(_editorWindow, SIGNAL(change()), this, SIGNAL(change())); - connect(_editorWindow, SIGNAL(savedRegexp()), this, SIGNAL(savedRegexp())); + connect(_editorWindow, &RegExpEditorWindow::change, this, &RegExpScrolledEditorWindow::change); + connect(_editorWindow, &RegExpEditorWindow::savedRegexp, this, &RegExpScrolledEditorWindow::savedRegexp); - connect(_editorWindow, SIGNAL(anythingSelected(bool)), this, SIGNAL(anythingSelected(bool))); - connect(_editorWindow, SIGNAL(anythingOnClipboard(bool)), this, SIGNAL(anythingOnClipboard(bool))); - connect(_editorWindow, SIGNAL(canSave(bool)), this, SIGNAL(canSave(bool))); - connect(_editorWindow, SIGNAL(verifyRegExp()), this, SIGNAL(verifyRegExp())); + connect(_editorWindow, &RegExpEditorWindow::anythingSelected, this, &RegExpScrolledEditorWindow::anythingSelected); + connect(_editorWindow, &RegExpEditorWindow::anythingOnClipboard, this, &RegExpScrolledEditorWindow::anythingOnClipboard); + connect(_editorWindow, &RegExpEditorWindow::canSave, this, &RegExpScrolledEditorWindow::canSave); + connect(_editorWindow, &RegExpEditorWindow::verifyRegExp, this, &RegExpScrolledEditorWindow::verifyRegExp); } void RegExpScrolledEditorWindow::slotSetRegExp(RegExp *regexp) { _editorWindow->slotSetRegExp(regexp); slotUpdateContentSize(QPoint()); } void RegExpScrolledEditorWindow::slotInsertRegExp(int tp) { _editorWindow->slotInsertRegExp((RegExpType)tp); } void RegExpScrolledEditorWindow::slotInsertRegExp(RegExp *regexp) { _editorWindow->slotInsertRegExp(regexp); } void RegExpScrolledEditorWindow::slotDeleteSelection() { _editorWindow->slotDeleteSelection(); } void RegExpScrolledEditorWindow::slotDoSelect() { _editorWindow->slotDoSelect(); } void RegExpScrolledEditorWindow::slotCut() { _editorWindow->slotCut(); } void RegExpScrolledEditorWindow::slotCopy() { _editorWindow->slotCopy(); } void RegExpScrolledEditorWindow::slotPaste() { _editorWindow->slotStartPasteAction(); } void RegExpScrolledEditorWindow::slotSave() { _editorWindow->slotSave(); } RegExp *RegExpScrolledEditorWindow::regExp() { return _editorWindow->regExp(); } void RegExpScrolledEditorWindow::resizeEvent(QResizeEvent *event) { _scrollArea->resize(event->size()); slotUpdateContentSize(QPoint()); } void RegExpScrolledEditorWindow::slotUpdateContentSize(QPoint focusPoint) { _editorWindow->resize(_editorWindow->sizeHint()); if (!focusPoint.isNull()) { _scrollArea->ensureVisible(focusPoint.x(), focusPoint.y(), 250, 250); } } // TODO: add timers, which will make the widget scroll when mouse is located // outside the QScrollView. void RegExpScrolledEditorWindow::slotScroll(QPoint focusPoint) { _scrollArea->ensureVisible(focusPoint.x(), focusPoint.y()); } diff --git a/src/textwidget.cpp b/src/textwidget.cpp index c741754..e40ef49 100644 --- a/src/textwidget.cpp +++ b/src/textwidget.cpp @@ -1,142 +1,142 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "textwidget.h" #include #include #include #include "textregexp.h" #include "selectablelineedit.h" TextWidget::TextWidget(RegExpEditorWindow *editorWindow, QWidget *parent) : RegExpWidget(editorWindow, parent) { init(QString()); } TextWidget::TextWidget(TextRegExp *regexp, RegExpEditorWindow *editorWindow, QWidget *parent) : RegExpWidget(editorWindow, parent) { init(regexp->text()); } void TextWidget::init(const QString &txt) { QHBoxLayout *lay = new QHBoxLayout(this); _edit = new SelectableLineEdit(this, this, QStringLiteral("TextWidget::edit")); _edit->setDragEnabled(false); //otherwise QLineEdit::mouseMoveEvent will set the cursor over and over again. lay->addWidget(_edit); _edit->setText(txt); - connect(_edit, SIGNAL(parentPleaseUpdate()), this, SLOT(slotUpdate())); + connect(_edit, &SelectableLineEdit::parentPleaseUpdate, this, &TextWidget::slotUpdate); setFocusProxy(_edit); _edit->installEventFilter(this); - connect(_edit, SIGNAL(textChanged(QString)), _editorWindow, SLOT(emitChange())); + connect(_edit, &QLineEdit::textChanged, _editorWindow, &RegExpEditorWindow::emitChange); } void TextWidget::slotUpdate() { // I need to force the parent to repaint, as the size change of this // widget may not be enough for the parent to change size, and in that // case the parent would not repaint, and the text widget would not be // resized. QWidget *p = static_cast(parent()); if (p) { p->repaint(); } _editorWindow->updateContent(this); } void TextWidget::paintEvent(QPaintEvent *e) { RegExpWidget::paintEvent(e); } void TextWidget::selectWidget(bool sel) { _edit->setSelected(sel); } bool TextWidget::updateSelection(bool parentSelected) { bool changed = RegExpWidget::updateSelection(parentSelected); // I need to call this function all the time, else the rubber band will // not be correctly deleted in the line edit. _edit->setSelected(_isSelected); return changed; } void TextWidget::updateAll() { _edit->update(); update(); } void TextWidget::clearSelection() { _isSelected = false; _edit->setSelected(false); } RegExp *TextWidget::regExp() const { return new TextRegExp(isSelected(), _edit->text()); } bool TextWidget::eventFilter(QObject *, QEvent *event) { // This is an event filter (in contrast to methods in SelectableLineEdit), // otherwise lots of functions would need to be exported from TextWidget. if (event->type() == QEvent::MouseButtonRelease) { if (_editorWindow->isInserting()) { if (acceptWidgetInsert(_editorWindow->insertType())) { mouseReleaseEvent(static_cast(event)); } return true; } } else if (event->type() == QEvent::MouseButtonPress) { if (_editorWindow->isInserting()) { return true; } else if (isSelected()) { QMouseEvent *e = static_cast(event); QMouseEvent ev(event->type(), mapTo(_editorWindow, e->pos()), e->button(), e->buttons(), e->modifiers()); QApplication::sendEvent(_editorWindow, &ev); return true; } } else if (event->type() == QEvent::Enter) { if (_editorWindow->isInserting()) { if (acceptWidgetInsert(_editorWindow->insertType())) { _edit->setCursor(Qt::CrossCursor); } else { _edit->setCursor(Qt::ForbiddenCursor); } } else if (isSelected()) { _edit->setCursor(Qt::ArrowCursor); } else { _edit->setCursor(Qt::IBeamCursor); } } else if (event->type() == QEvent::MouseButtonDblClick && _editorWindow->isInserting()) { return true; } return false; } diff --git a/src/userdefinedregexps.cpp b/src/userdefinedregexps.cpp index c48b229..b55bb2b 100644 --- a/src/userdefinedregexps.cpp +++ b/src/userdefinedregexps.cpp @@ -1,274 +1,274 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "userdefinedregexps.h" #include #include #include #include #include #include #include #include #include #include #include "widgetfactory.h" #include "compoundregexp.h" UserDefinedRegExps::UserDefinedRegExps(QWidget *parent, const QString &title) : QDockWidget(title, parent) { QWidget *top = new QWidget(this); QVBoxLayout *lay = new QVBoxLayout(top); lay->setContentsMargins(0, 0, 0, 0); //QLabel* label = new QLabel( i18n("Compound regular expression:"), top ); // This is to avoid that the label set the minimum width for the window. //label->setMinimumSize(1,0); //lay->addWidget(label); _userDefined = new QTreeWidget(top /*, "UserDefinedRegExps::_userDefined"*/); //_userDefined->addColumn( QString() ); _userDefined->header()->hide(); _userDefined->setRootIsDecorated(true); _userDefined->setContextMenuPolicy(Qt::CustomContextMenu); lay->addWidget(_userDefined); setWidget(top); slotPopulateUserRegexps(); - connect(_userDefined, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotLoad(QTreeWidgetItem*))); - connect(_userDefined, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenuTriggered(QPoint))); + connect(_userDefined, &QTreeWidget::itemClicked, this, &UserDefinedRegExps::slotLoad); + connect(_userDefined, &QWidget::customContextMenuRequested, this, &UserDefinedRegExps::slotContextMenuTriggered); } void UserDefinedRegExps::slotPopulateUserRegexps() { _userDefined->clear(); _regExps.clear(); createItems(i18n("User Defined"), WidgetWinItem::path(), true); const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("kregexpeditor/predefined/"), QStandardPaths::LocateDirectory); for (QStringList::ConstIterator it1 = dirs.constBegin(); it1 != dirs.constEnd(); ++it1) { QDir dir(*it1, QString(), QDir::Name, QDir::Dirs); QStringList subdirs = dir.entryList(); for (QStringList::iterator it2 = subdirs.begin(); it2 != subdirs.end(); ++it2) { if (*it2 == QStringLiteral(".") || *it2 == QStringLiteral("..")) { continue; } createItems(*it2, *it1 + QLatin1Char('/') + *it2, false); } } } void UserDefinedRegExps::createItems(const QString &_title, const QString &dir, bool usersRegExp) { QString title = _title; if (_title == QLatin1String("general")) { title = i18n("general"); } QTreeWidgetItem *lvItem = new QTreeWidgetItem((QTreeWidget *)nullptr, QStringList(title)); lvItem->setExpanded(true); _userDefined->addTopLevelItem(lvItem); QDir directory(dir); QStringList files = directory.entryList(QStringList(QStringLiteral("*.regexp"))); for (QStringList::Iterator it = files.begin(), total = files.end(); it != total; ++it) { const QString fileName = dir + QLatin1Char('/') + *it; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { KMessageBox::sorry(this, i18n("Could not open file for reading: %1", fileName)); continue; } QTextStream stream(&file); QString data = stream.readAll(); file.close(); RegExp *regexp = WidgetFactory::createRegExp(data); if (!regexp) { KMessageBox::sorry(this, i18n("File %1 containing user defined regular expression contained an error", fileName)); continue; } new WidgetWinItem(*it, regexp, usersRegExp, lvItem); // Inserth the regexp into the list of compound regexps if (regexp->type() == RegExp::COMPOUND) { CompoundRegExp *cregexp = dynamic_cast(regexp); if (cregexp && cregexp->allowReplace()) { _regExps.append(cregexp); } } } } const QList UserDefinedRegExps::regExps() const { return _regExps; } void UserDefinedRegExps::slotUnSelect() { _userDefined->clearSelection(); } void UserDefinedRegExps::slotLoad(QTreeWidgetItem *item) { if (!item || !dynamic_cast(item)) { // Mouse pressed outside a widget. return; } WidgetWinItem *wwi = dynamic_cast(item); if (wwi) { Q_EMIT load(wwi->regExp()); } } void UserDefinedRegExps::slotContextMenuTriggered(const QPoint &pos) { QMenu menu; - QAction *deleteAction = menu.addAction(i18n("Delete"), this, SLOT(slotDeleteUserRegexp())); - QAction *renameAction = menu.addAction(i18n("Rename"), this, SLOT(slotRenameUserRegexp())); + QAction *deleteAction = menu.addAction(i18n("Delete"), this, &UserDefinedRegExps::slotDeleteUserRegexp); + QAction *renameAction = menu.addAction(i18n("Rename"), this, &UserDefinedRegExps::slotRenameUserRegexp); QTreeWidgetItem *item = _userDefined->itemAt(pos); if (!item || !dynamic_cast(item)) { // menu not selected on an item deleteAction->setEnabled(false); renameAction->setEnabled(false); } else { // Only allow rename and delete of users own regexps. WidgetWinItem *winItem = dynamic_cast(item); if (winItem) { if (!winItem->isUsersRegExp()) { deleteAction->setEnabled(false); renameAction->setEnabled(false); } else { QVariant var = QVariant::fromValue((void *)(winItem)); deleteAction->setData(var); renameAction->setData(var); } } } menu.exec(_userDefined->mapToGlobal(pos)); } void UserDefinedRegExps::slotSelectNewAction() { slotUnSelect(); } void UserDefinedRegExps::slotRenameUserRegexp() { QAction *const action = qobject_cast(sender()); Q_ASSERT(action); WidgetWinItem *winItem = static_cast(action->data().value()); Q_ASSERT(winItem); QString oldName = winItem->name(); QString txt = QInputDialog::getText(this, i18n("Rename Item"), i18n("New name:"), QLineEdit::Normal, oldName); if (!txt.isNull() && oldName != txt) { const QString fileName = WidgetWinItem::path() + QLatin1Char('/') + txt + QStringLiteral(".regexp"); QFileInfo finfo(fileName); if (finfo.exists()) { int answer = KMessageBox::warningYesNo(this, i18n("

    Overwrite named regular expression %1?

    ", txt), QString(), KStandardGuiItem::overwrite(), KGuiItem(i18n("Do Not Overwrite"))); if (answer != KMessageBox::Yes) { return; } // An item with this name already exists. delete winItem; } else { winItem->setName(txt); } QDir dir; dir.remove(fileName); } } void UserDefinedRegExps::slotDeleteUserRegexp() { QAction *const action = qobject_cast(sender()); Q_ASSERT(action); WidgetWinItem *winItem = static_cast(action->data().value()); Q_ASSERT(winItem); QFile file(winItem->fileName()); Q_ASSERT(file.exists()); file.remove(); delete winItem; } WidgetWinItem::WidgetWinItem(const QString &fileName, RegExp *regexp, bool usersRegExp, QTreeWidgetItem *parent) : QTreeWidgetItem(parent) , _regexp(regexp) , _usersRegExp(usersRegExp) { int index = fileName.lastIndexOf(QLatin1String(".regexp")); _name = fileName.left(index); setText(0, _name); } WidgetWinItem::~WidgetWinItem() { delete _regexp; } QString WidgetWinItem::fileName() const { return path() + QLatin1Char('/') + _name + QStringLiteral(".regexp"); } RegExp *WidgetWinItem::regExp() const { return _regexp; } QString WidgetWinItem::name() const { return _name; } void WidgetWinItem::setName(const QString &nm) { _name = nm; setText(0, nm); } QString WidgetWinItem::path() { const QString regexppath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + QStringLiteral("KRegExpEditor/"); QDir().mkpath(regexppath); return regexppath; } diff --git a/src/verifybuttons.cpp b/src/verifybuttons.cpp index 1161785..fd943bb 100644 --- a/src/verifybuttons.cpp +++ b/src/verifybuttons.cpp @@ -1,209 +1,208 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "verifybuttons.h" #include #include #include #include #include #include "qtregexpconverter.h" #include "emacsregexpconverter.h" VerifyButtons::VerifyButtons(QWidget *parent, const QString &name) : QToolBar(name, parent) , _configMenu(nullptr) { _verify = new QToolButton(this); QIcon icon = QIcon::fromTheme(QStringLiteral("tools-check-spelling")); _verify->setIcon(icon); _verify->setToolTip(i18n("Verify regular expression")); _verify->setWhatsThis(i18n("Shows what part of the regular expression is being matched in the verifier window." "(The window below the graphical editor window).")); addWidget(_verify); - connect(_verify, SIGNAL(clicked()), this, SIGNAL(verify())); + connect(_verify, &QAbstractButton::clicked, this, &VerifyButtons::verify); QToolButton *button = new QToolButton(this); button->setIcon(QIcon::fromTheme(QStringLiteral("document-open"))); addWidget(button); - connect(button, SIGNAL(clicked()), this, SLOT(loadText())); + connect(button, &QAbstractButton::clicked, this, &VerifyButtons::loadText); button->setToolTip(i18n("Load text in the verifier window")); button = new QToolButton(this); button->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); addWidget(button); button->setToolTip(i18n("Verification Settings")); button->setPopupMode(QToolButton::InstantPopup); // It is currently not possible to ask for the paragraph being highlighted, thefore scrolling to next/prev match // do not work. Enable this when they work. // _first = new QToolButton( QString::fromLatin1("<<"), this); // layout->addWidget( _first ); // connect(_first, SIGNAL(clicked()), this, SIGNAL(gotoFirst())); // _first->setFixedWidth( 25 ); // // _prev = new QToolButton(QString::fromLatin1("<"), this); // layout->addWidget( _prev ); // connect(_prev, SIGNAL(clicked()), this, SIGNAL(gotoPrev())); // _prev->setFixedWidth( 20 ); // // _next = new QToolButton(QString::fromLatin1(">"), this); // layout->addWidget( _next ); // connect(_next, SIGNAL(clicked()), this, SIGNAL(gotoNext())); // _next->setFixedWidth( 20 ); // // _last = new QToolButton(QString::fromLatin1(">>"), this); // layout->addWidget( _last ); // connect(_last, SIGNAL(clicked()), this, SIGNAL(gotoLast())); // _last->setFixedWidth( 25 ); // Same as above // QLabel* label = new QLabel( i18n("Matches: "), this ); // layout->addWidget( label ); // _matches = new QLabel(i18n("-"), this ); // layout->addWidget( _matches ); // QString txt = i18n( "Shows number of times regular expression matches the text in the verifier window"); // label->setToolTip( txt ); // _matches->setToolTip( txt ); _verify->setEnabled(false); // -------------------------------------------------- RegExp Converters // Qt RegExpConverter *converter = new QtRegExpConverter(); _converters.append(qMakePair(converter, static_cast(nullptr))); QString qtConverterName = converter->name(); // Emacs converter = new EmacsRegExpConverter(); _converters.append(qMakePair(converter, static_cast(nullptr))); - QString emacsConverterName = converter->name(); // -------------------------------------------------- Initialize the config menu _configMenu = new QMenu(i18n("config menu"), this); // Auto Verify QAction *autoVerify = new QAction(i18n("Verify on the Fly"), this); autoVerify->setCheckable(true); autoVerify->setChecked(true); - connect(autoVerify, SIGNAL(toggled(bool)), this, SLOT(updateVerifyButton(bool))); - connect(autoVerify, SIGNAL(toggled(bool)), this, SIGNAL(autoVerify(bool))); + connect(autoVerify, &QAction::toggled, this, &VerifyButtons::updateVerifyButton); + connect(autoVerify, &QAction::toggled, this, &VerifyButtons::autoVerify); _configMenu->addAction(autoVerify); autoVerify->setToolTip(i18n("Toggle on-the-fly verification of regular expression")); autoVerify->setWhatsThis(i18n("Enabling this option will make the verifier update for each edit. " "If the verify window contains much text, or if the regular expression is either " "complex or matches a lot of time, this may be very slow.")); QAction *matchGreedy = new QAction(i18n("Match Greedy"), this); matchGreedy->setCheckable(true); matchGreedy->setChecked(false); - connect(matchGreedy, SIGNAL(toggled(bool)), this, SIGNAL(matchGreedy(bool))); + connect(matchGreedy, &QAction::toggled, this, &VerifyButtons::matchGreedy); _configMenu->addAction(matchGreedy); matchGreedy->setToolTip(i18n("Toggle greedy matching when verifying the regular expression.")); matchGreedy->setWhatsThis(i18n("When this option is enabled, the regular expression will be evaluated on a so-called greedy way.")); // RegExp Languages _languages = new QMenu(i18n("RegExp Language"), _configMenu); _configMenu->addMenu(_languages); QActionGroup *grp = new QActionGroup(this); for (QLinkedList< QPair >::Iterator it = _converters.begin(); it != _converters.end(); ++it) { QString name = (*it).first->name(); QAction *action = new QAction(name, this); action->setCheckable(true); grp->addAction(action); (*it).second = action; } _languages->addActions(grp->actions()); - connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(slotChangeSyntax(QAction*))); + connect(grp, &QActionGroup::triggered, this, &VerifyButtons::slotChangeSyntax); _languages->setEnabled(false); button->setMenu(_configMenu); // Select the Qt converter by default setSyntax(qtConverterName); } void VerifyButtons::updateVerifyButton(bool b) { _verify->setEnabled(!b); } void VerifyButtons::loadText() { const QString fileName = QFileDialog::getOpenFileName(this, QString(), QString(), QString()); if (!fileName.isNull()) { Q_EMIT loadVerifyText(fileName); } } // Qt anchors do not work for
    ...
    , thefore scrolling to next/prev match // do not work. Enable this when they work. // void VerifyButtons::enableBackwardButtons( bool b ) // { // _first->setEnabled( b ); // _prev->setEnabled( b ); // } // // void VerifyButtons::enableForwardButtons( bool b ) // { // _next->setEnabled( b ); // _last->setEnabled( b ); // } void VerifyButtons::setMatchCount(int /*count*/) { // currently this is not possible due to limitation in QSyntaxHighlighter /* if ( count == -1 ) { _matches->setText( QString::fromLatin1("-") ); } else { _matches->setText( QString::number( count ) ); } */ } void VerifyButtons::slotChangeSyntax(QAction *action) { Q_EMIT changeSyntax(action->text()); } RegExpConverter *VerifyButtons::setSyntax(const QString &which) { QString noAmpersand = which; noAmpersand.remove(QLatin1Char('&')); // HACK, can probably be done more cleanly for (QLinkedList< QPair >::Iterator it = _converters.begin(); it != _converters.end(); ++it) { QString name = (*it).first->name(); if (name == noAmpersand) { (*it).second->setChecked(true); return (*it).first; } } qWarning("No such converter: '%s'", qPrintable(noAmpersand)); return nullptr; } void VerifyButtons::setAllowNonQtSyntax(bool b) { _languages->setEnabled(b); } diff --git a/src/widgetfactory.cpp b/src/widgetfactory.cpp index a576c7a..4f4d238 100644 --- a/src/widgetfactory.cpp +++ b/src/widgetfactory.cpp @@ -1,209 +1,209 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #include "widgetfactory.h" #include #include #include "repeatwidget.h" #include "textwidget.h" #include "characterswidget.h" #include "altnwidget.h" #include "zerowidgets.h" #include "compoundwidget.h" #include "concwidget.h" #include "lookaheadwidget.h" #include "textregexp.h" #include "textrangeregexp.h" #include "repeatregexp.h" #include "lookaheadregexp.h" #include "concregexp.h" #include "altnregexp.h" #include "positionregexp.h" #include "dotregexp.h" #include "compoundregexp.h" #include "kregexpeditorgui.h" bool WidgetFactory::isContainer(RegExpType tp) { return tp == REPEAT || tp == ALTN || tp == COMPOUND; } RegExpWidget *WidgetFactory::createWidget(RegExpEditorWindow *win, QWidget *parent, RegExpType type) { RegExpWidget *widget = nullptr; switch (type) { case TEXT: return new TextWidget(win, parent); case ALTN: return new AltnWidget(win, parent); case DOT: return new AnyCharWidget(win, parent); case BEGLINE: return new BegLineWidget(win, parent); case ENDLINE: return new EndLineWidget(win, parent); case WORDBOUNDARY: return new WordBoundaryWidget(win, parent); case NONWORDBOUNDARY: return new NonWordBoundaryWidget(win, parent); case POSLOOKAHEAD: case NEGLOOKAHEAD: return new LookAheadWidget(win, type, parent); case REPEAT: widget = new RepeatWidget(win, parent); break; case CHARSET: widget = new CharactersWidget(win, parent); break; case COMPOUND: widget = new CompoundWidget(win, parent); break; default: qFatal("It should not be possible to get here!"); return nullptr; } if (widget->edit() == QDialog::Rejected) { delete widget; return nullptr; } return widget; } RegExpWidget *WidgetFactory::createWidget(RegExp *regexp, RegExpEditorWindow *editorWindow, QWidget *parent) { if (regexp == nullptr) { qFatal("%s:%d Regexp is 0", __FILE__, __LINE__); } else if (TextRegExp *reg = dynamic_cast(regexp)) { return new TextWidget(reg, editorWindow, parent); } else if (TextRangeRegExp *reg = dynamic_cast(regexp)) { return new CharactersWidget(reg, editorWindow, parent); } else if (RepeatRegExp *reg = dynamic_cast(regexp)) { return new RepeatWidget(reg, editorWindow, parent); } else if (LookAheadRegExp *reg = dynamic_cast(regexp)) { if (reg->lookAheadType() == LookAheadRegExp::POSITIVE) { return new LookAheadWidget(reg, editorWindow, POSLOOKAHEAD, parent); } else { return new LookAheadWidget(reg, editorWindow, NEGLOOKAHEAD, parent); } } else if (ConcRegExp *reg = dynamic_cast(regexp)) { return new ConcWidget(reg, editorWindow, parent); } else if (AltnRegExp *reg = dynamic_cast(regexp)) { return new AltnWidget(reg, editorWindow, parent); } else if (PositionRegExp *reg = dynamic_cast(regexp)) { switch (reg->position()) { case PositionRegExp::BEGLINE: return new BegLineWidget(editorWindow, parent); case PositionRegExp::ENDLINE: return new EndLineWidget(editorWindow, parent); case PositionRegExp::WORDBOUNDARY: return new WordBoundaryWidget(editorWindow, parent); case PositionRegExp::NONWORDBOUNDARY: return new NonWordBoundaryWidget(editorWindow, parent); } } else if (dynamic_cast(regexp)) { return new AnyCharWidget(editorWindow, parent); } else if (CompoundRegExp *reg = dynamic_cast(regexp)) { return new CompoundWidget(reg, editorWindow, parent); } else { qFatal("%s:%d Internal Error: Unknown RegExp type", __FILE__, __LINE__); } return nullptr; } -RegExp *WidgetFactory::createRegExp(QDomElement node, const QString &version) +RegExp *WidgetFactory::createRegExp(const QDomElement &node, const QString &version) { QString tag = node.tagName(); RegExp *regexp; if (tag == QStringLiteral("TextRange")) { regexp = new TextRangeRegExp(false); } else if (tag == QStringLiteral("Text")) { regexp = new TextRegExp(false); } else if (tag == QStringLiteral("Concatenation")) { regexp = new ConcRegExp(false); } else if (tag == QStringLiteral("Alternatives")) { regexp = new AltnRegExp(false); } else if (tag == QStringLiteral("BegLine")) { regexp = new PositionRegExp(false, PositionRegExp::BEGLINE); } else if (tag == QStringLiteral("EndLine")) { regexp = new PositionRegExp(false, PositionRegExp::ENDLINE); } else if (tag == QStringLiteral("WordBoundary")) { regexp = new PositionRegExp(false, PositionRegExp::WORDBOUNDARY); } else if (tag == QStringLiteral("NonWordBoundary")) { regexp = new PositionRegExp(false, PositionRegExp::NONWORDBOUNDARY); } else if (tag == QStringLiteral("PositiveLookAhead")) { regexp = new LookAheadRegExp(false, LookAheadRegExp::POSITIVE); } else if (tag == QStringLiteral("NegativeLookAhead")) { regexp = new LookAheadRegExp(false, LookAheadRegExp::NEGATIVE); } else if (tag == QStringLiteral("Compound")) { regexp = new CompoundRegExp(false); } else if (tag == QStringLiteral("AnyChar")) { regexp = new DotRegExp(false); } else if (tag == QStringLiteral("Repeat")) { regexp = new RepeatRegExp(false); } else { KMessageBox::sorry(nullptr, i18n("

    Unknown tag while reading XML. Tag was %1

    ", tag), i18n("Error While Loading From XML File")); return nullptr; } bool ok = regexp->load(node, version); if (ok) { return regexp; } delete regexp; return nullptr; } RegExp *WidgetFactory::createRegExp(const QString &str) { QDomDocument doc; QString error; int errorLine, errorCol; bool ok = doc.setContent(str, &error, &errorLine, &errorCol); if (!ok) { qDebug() << error << "at line" << errorLine << "xml was:"; qDebug() << str; KMessageBox::sorry(nullptr, i18n("Error while loading regular expression from XML.") + QLatin1Char('\n') + error, i18n("Error While Loading Regular Expression From XML")); } // Read the RegularExpression element, and extract the version. QDomElement top = doc.documentElement(); if (!(top.tagName() == QStringLiteral("RegularExpression"))) { KMessageBox::sorry(nullptr, i18n("

    XML file did not contain a %1 tag.

    ", QStringLiteral("RegularExpression")), i18n("Error While Loading From XML File")); } QString version = top.attribute(QStringLiteral("version"), KRegExpEditorGUI::version); QDomNode child = top.firstChild(); if (!child.isElement()) { KMessageBox::sorry(nullptr, i18n("

    Error while reading XML file. The element just below the tag " "%1 was not an element.

    ", QStringLiteral("RegularExpression")), i18n("Error While Loading From XML File")); } RegExp *regexp = WidgetFactory::createRegExp(child.toElement(), version); return regexp; } diff --git a/src/widgetfactory.h b/src/widgetfactory.h index 730b69b..7d13b06 100644 --- a/src/widgetfactory.h +++ b/src/widgetfactory.h @@ -1,57 +1,57 @@ /* * Copyright (c) 2002-2003 Jesper K. Pedersen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. **/ #ifndef widgetfactory #define widgetfactory #include class RegExpWidget; class RegExpEditorWindow; class QWidget; class RegExp; /** All the different regular expression types. */ enum RegExpType { TEXT = 0, CHARSET = 1, DOT = 2, REPEAT = 3, ALTN = 4, COMPOUND = 5, BEGLINE = 6, ENDLINE = 7, WORDBOUNDARY = 8, NONWORDBOUNDARY = 9, CONC = 10, DRAGACCEPTER = 11, POSLOOKAHEAD = 12, NEGLOOKAHEAD = 13 }; /** Class used to encapsulate information about widgets. When reading widgets from a stream, it is necessary to know about all sub-widgets to the @ref RegExpWidget class. This class exists to make sure that such general information is only kept once. @internal */ class WidgetFactory { public: static RegExpWidget *createWidget(RegExpEditorWindow *editorWindow, QWidget *parent, RegExpType type); static RegExpWidget *createWidget(RegExp *regexp, RegExpEditorWindow *editorWindow, QWidget *parent); - static RegExp *createRegExp(QDomElement node, const QString &version); + static RegExp *createRegExp(const QDomElement &node, const QString &version); static RegExp *createRegExp(const QString &str); static bool isContainer(RegExpType); }; #endif // widgetfactory