diff --git a/CMakeLists.txt b/CMakeLists.txt index 93d6572..8d75591 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,68 +1,67 @@ project(kregexpeditor) ############### search packages used by KDE ############### cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR) find_package(ECM 5.20 REQUIRED NO_MODULE) set(QT5_REQUIRED_VERSION "5.5.0") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR}) option(ENABLE_KTEXTWIDGETS "Build KTextWidgets integration" OFF) option(BUILD_TEST "Build test widget" OFF) include(ECMGenerateHeaders) include(ECMInstallIcons) include(ECMAddAppIcon) include(ECMMarkNonGuiExecutable) include(ECMOptionalAddSubdirectory) include(ECMSetupVersion) include(FeatureSummary) include(KDEInstallDirs) include(KDECMakeSettings) include(KDECompilerSettings NO_POLICY_SCOPE) find_package(Qt5 ${QT5_REQUIRED_VERSION} CONFIG REQUIRED Core Widgets Xml) find_package(KF5 REQUIRED I18n DocTools - WidgetsAddons Crash CoreAddons ) find_package(BISON REQUIRED) find_package(FLEX REQUIRED) include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ) ############### Find the stuff we need ############### add_definitions( -DQT_NO_CAST_ASCII ) add_definitions( -DQT_DISABLE_DEPRECATED_BEFORE=0x060000 ) # not for now, the code is not fully ready for it #add_definitions( -DQT_NO_CAST_FROM_ASCII ) add_definitions( -DQT_NO_CAST_TO_ASCII ) add_definitions( -DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT ) add_subdirectory(src) add_subdirectory( doc ) if (ENABLE_KTEXTWIDGETS) add_definitions( -DENABLE_KTEXTWIDGETS ) find_package(KF5 REQUIRED TextWidgets ) endif() if (BUILD_TEST) find_package(KF5 REQUIRED KIO ) add_subdirectory(tests) endif() feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 71927c7..e5f2a2d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,136 +1,135 @@ BISON_TARGET(qregexpparser qregexpparser.y ${CMAKE_CURRENT_BINARY_DIR}/gen_qregexpparser.cc COMPILE_FLAGS "-d -p qregexp") FLEX_TARGET(qregexplexer qregexpparser.l ${CMAKE_CURRENT_BINARY_DIR}/gen_qregexplexer.cpp COMPILE_FLAGS "-Pqregexp") ADD_FLEX_BISON_DEPENDENCY( qregexplexer qregexpparser ) set_property(SOURCE ${BISON_qregexpparser_OUTPUTS} PROPERTY SKIP_AUTOMOC ON) set_property(SOURCE ${FLEX_qregexplexer_OUTPUTS} PROPERTY SKIP_AUTOMOC ON) add_subdirectory( predefined ) add_subdirectory( pics ) include_directories( KWidgetStreamer/ KMultiFormListBox/ ) ########### next target ############### set(kregexpeditorcommon_SRCS ${BISON_qregexpparser_OUTPUTS} ${FLEX_qregexplexer_OUTPUTS} altnregexp.cpp altnwidget.cpp auxbuttons.cpp characterswidget.cpp charselector.cpp compoundregexp.cpp compoundwidget.cpp concregexp.cpp concwidget.cpp dcbutton.cpp dotregexp.cpp dragaccepter.cpp regexpeditorwindow.cpp emacsregexpconverter.cpp errormap.cpp infopage.cpp KMultiFormListBox/ccp.cpp KMultiFormListBox/kmultiformlistboxentry.cpp KMultiFormListBox/kmultiformlistbox.cpp KMultiFormListBox/kmultiformlistbox-multivisible.cpp KMultiFormListBox/kmultiformlistboxfactory.cpp KMultiFormListBox/indexWindow.cpp KMultiFormListBox/kmultiformlistbox-windowed.cpp KMultiFormListBox/widgetwindow.cpp KMultiFormListBox/windowlistboxitem.cpp kregexpeditorgui.cpp kregexpeditorguidialog.cpp kregexpeditorprivate.cpp KWidgetStreamer/kwidgetstreamer.cpp limitedcharlineedit.cpp lookaheadregexp.cpp lookaheadwidget.cpp multicontainerwidget.cpp myfontmetrics.cpp positionregexp.cpp qtregexpconverter.cpp qtregexphighlighter.cpp regexpbuttons.cpp regexpconverter.cpp regexp.cpp regexphighlighter.cpp regexpwidget.cpp repeatregexp.cpp repeatwidget.cpp scrollededitorwindow.cpp selectablelineedit.cpp singlecontainerwidget.cpp textrangeregexp.cpp textregexp.cpp textwidget.cpp userdefinedregexps.cpp verifier.cpp verifybuttons.cpp widgetfactory.cpp zerowidgets.cpp ) add_library(kregexpeditorcommon SHARED ${kregexpeditorcommon_SRCS}) target_link_libraries(kregexpeditorcommon KF5::I18n KF5::CoreAddons - KF5::WidgetsAddons Qt5::Widgets Qt5::Xml ) set_target_properties(kregexpeditorcommon PROPERTIES VERSION 1.0.0 SOVERSION 1) install(TARGETS kregexpeditorcommon ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) ########### next target ############### set(kregexpeditorgui_PART_SRCS kregexpeditorfactory.cpp ) add_library(kregexpeditorgui MODULE ${kregexpeditorgui_PART_SRCS}) target_link_libraries(kregexpeditorgui kregexpeditorcommon) install(TARGETS kregexpeditorgui DESTINATION ${KDE_INSTALL_PLUGINDIR}) ########### next target ############### set(kregexpeditor_SRCS main.cpp) file(GLOB ICONS_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/*-apps-kregexpeditor.png") ecm_add_app_icon(kregexpeditor_SRCS ICONS ${ICONS_SRCS}) add_executable(kregexpeditor ${kregexpeditor_SRCS}) target_link_libraries(kregexpeditor Qt5::Widgets kregexpeditorcommon KF5::Crash) install(TARGETS kregexpeditor ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) ########### install files ############### install(FILES org.kde.kregexpeditor.desktop DESTINATION ${KDE_INSTALL_APPDIR}) install(FILES kregexpeditorgui.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) install(FILES KMultiFormListBox/kmultiformlistboxentry.h KMultiFormListBox/kmultiformlistbox.h KMultiFormListBox/kmultiformlistboxfactory.h DESTINATION ${KDE_INSTALL_INCLUDEDIR} ) install(FILES KWidgetStreamer/kwidgetstreamer.h DESTINATION ${KDE_INSTALL_INCLUDEDIR}) ecm_install_icons(ICONS 128-apps-kregexpeditor.png 16-apps-kregexpeditor.png 22-apps-kregexpeditor.png 32-apps-kregexpeditor.png 48-apps-kregexpeditor.png 64-apps-kregexpeditor.png DESTINATION ${KDE_INSTALL_ICONDIR} THEME hicolor ) diff --git a/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp b/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp index b700595..a412374 100644 --- a/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp +++ b/src/KMultiFormListBox/kmultiformlistbox-multivisible.cpp @@ -1,305 +1,308 @@ /* * 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 #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->setMargin(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 *))); } // 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")); + QMessageBox::information(this, + i18n("Internal Error"), + i18n("Due to a bug, it is not possible to remove the last element.") + ); 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.")); + QMessageBox::information(this, QString(), 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-windowed.cpp b/src/KMultiFormListBox/kmultiformlistbox-windowed.cpp index df4a1d4..4d1013a 100644 --- a/src/KMultiFormListBox/kmultiformlistbox-windowed.cpp +++ b/src/KMultiFormListBox/kmultiformlistbox-windowed.cpp @@ -1,227 +1,224 @@ /* * 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-windowed.h" #include #include #include -#include +#include #include -#include -#include #include "widgetwindow.h" #include "windowlistboxitem.h" KMultiFormListBoxWindowed::KMultiFormListBoxWindowed(KMultiFormListBoxFactory *factory, QWidget *parent, bool showUpDownButtons, bool showHelpButton, const QString &addButtonText) : QWidget(parent) { _layout = new QVBoxLayout(this); QHBoxLayout *innerLayout = new QHBoxLayout(); _layout->addLayout(innerLayout); _listbox = new QListWidget(this); _listbox->setObjectName(QStringLiteral("listbox")); _listbox->setSelectionMode(QAbstractItemView::SingleSelection); innerLayout->addWidget(_listbox); QVBoxLayout *buttons = new QVBoxLayout(); innerLayout->addLayout(buttons); QPushButton *but = new QPushButton(addButtonText, this); but->setObjectName(QStringLiteral("Add Button")); buttons->addWidget(but, 0); connect(but, &QAbstractButton::clicked, this, &KMultiFormListBoxWindowed::addNewElement); but = new QPushButton(i18n("Edit"), this); but->setObjectName(QStringLiteral("Edit Button")); buttons->addWidget(but, 0); connect(but, SIGNAL(clicked()), this, SLOT(slotEditSelected())); connect(_listbox, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(slotEditSelected(QListWidgetItem *))); _buttonList.append(but); but = new QPushButton(i18n("Delete"), this); but->setObjectName(QStringLiteral("Delete Button")); buttons->addWidget(but, 0); connect(but, &QAbstractButton::clicked, this, &KMultiFormListBoxWindowed::slotDeleteEntry); _buttonList.append(but); but = new QPushButton(i18n("Copy"), this); but->setObjectName(QStringLiteral("Copy Button")); buttons->addWidget(but, 0); connect(but, &QAbstractButton::clicked, this, &KMultiFormListBoxWindowed::slotCopySelected); _buttonList.append(but); if (showUpDownButtons) { but = new QPushButton(i18n("Up"), this); but->setObjectName(QStringLiteral("Up Button")); buttons->addWidget(but, 0); connect(but, &QAbstractButton::clicked, this, &KMultiFormListBoxWindowed::slotMoveItemUp); _buttonList.append(but); but = new QPushButton(i18n("Down"), this); but->setObjectName(QStringLiteral("Down Button")); buttons->addWidget(but, 0); connect(but, &QAbstractButton::clicked, this, &KMultiFormListBoxWindowed::slotMoveItemDown); _buttonList.append(but); } if (showHelpButton) { - but = new QPushButton(this); - KGuiItem::assign(but, KStandardGuiItem::help()); + but = new QPushButton(i18n("Help"), this); but->setObjectName(QStringLiteral("Help Button")); buttons->addWidget(but, 0); connect(but, &QAbstractButton::clicked, this, &KMultiFormListBoxWindowed::showHelp); } buttons->addStretch(1); _factory = factory; slotUpdateButtonState(); } KMultiFormListBoxEntryList KMultiFormListBoxWindowed::elements() { KMultiFormListBoxEntryList list; for (int i = 0; i < _listbox->count(); ++i) { WindowListboxItem *item = (WindowListboxItem *)_listbox->item(i); list.append(item->entry()); } return list; } void KMultiFormListBoxWindowed::delElement(QWidget * /*elm*/) { // kDebug() << "KMultiFormListBoxWindowed::delElement NOT YET IMPLEMENTED"; // TODO } void KMultiFormListBoxWindowed::delAnElement() { // kDebug() << "KMultiFormListBoxWindowed::delAnElement NOT YET IMPLEMENTED"; // TODO } void KMultiFormListBoxWindowed::append(KMultiFormListBoxEntry *elm) { (void)new WidgetWindow(_factory, elm, _listbox); slotUpdateButtonState(); } void KMultiFormListBoxWindowed::addNewElement() { // kDebug() << "addNewElement " << _factory << "," << _listbox ; QWidget *widget = new WidgetWindow(_factory, _listbox); widget->show(); connect(widget, SIGNAL(finished()), this, SLOT(slotUpdateButtonState())); } void KMultiFormListBoxWindowed::addElement() { new WidgetWindow(_factory, _listbox); slotUpdateButtonState(); } void KMultiFormListBoxWindowed::slotEditSelected(QListWidgetItem *item) { ((WindowListboxItem *)item)->displayWidget(); } void KMultiFormListBoxWindowed::slotEditSelected() { WindowListboxItem *item = selected(); if (item) { slotEditSelected(item); } } void KMultiFormListBoxWindowed::slotDeleteEntry() { WindowListboxItem *item = selected(); if (item) { int answer - = KMessageBox::warningContinueCancel(nullptr, i18n("Delete item \"%1\"?", item->text()), i18n("Delete Item"), KStandardGuiItem::del()); - if (answer == KMessageBox::Continue) { + = QMessageBox::question(nullptr, i18n("Delete Item"), i18n("Delete item \"%1\"?", item->text())); + if (answer == QMessageBox::Yes) { delete item; slotUpdateButtonState(); } } } void KMultiFormListBoxWindowed::slotCopySelected() { WindowListboxItem *item = selected(); if (item) { item->cloneItem(); } } WindowListboxItem *KMultiFormListBoxWindowed::selected() { /* int i = _listbox->currentItem(); if (i == -1) { return 0; } else { return (WindowListboxItem *) _listbox->item(i); } */ return (WindowListboxItem *)_listbox->currentItem(); } void KMultiFormListBoxWindowed::slotMoveItemUp() { WindowListboxItem *item = selected(); if (item == nullptr) { return; } int index = _listbox->row(item); if (index != 0) { _listbox->takeItem(index); _listbox->insertItem(index - 1, item); _listbox->setCurrentItem(item); } } void KMultiFormListBoxWindowed::slotMoveItemDown() { WindowListboxItem *item = selected(); if (item == nullptr) { return; } int index = _listbox->row(item); if (index < _listbox->count()) { _listbox->takeItem(index); _listbox->insertItem(index + 1, item); _listbox->setCurrentItem(item); } } void KMultiFormListBoxWindowed::slotUpdateButtonState() { bool on = (_listbox->count() != 0); const int nbButton = _buttonList.count(); for (int i = 0; i < nbButton; i++) { _buttonList.at(i)->setEnabled(on); } } diff --git a/src/altnwidget.cpp b/src/altnwidget.cpp index e636208..f9885e3 100644 --- a/src/altnwidget.cpp +++ b/src/altnwidget.cpp @@ -1,248 +1,248 @@ /* * 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 "altnwidget.h" #include #include #include -#include +#include #include "dragaccepter.h" #include "concwidget.h" #include "altnregexp.h" AltnWidget::AltnWidget(RegExpEditorWindow *editorWindow, QWidget *parent) : MultiContainerWidget(editorWindow, parent) { DragAccepter *accepter = new DragAccepter(editorWindow, this); accepter->resize(0, 0); // See note (1) in Comments _children.append(accepter); _text = i18n("Alternatives"); } AltnWidget::AltnWidget(AltnRegExp *regexp, RegExpEditorWindow *editorWindow, QWidget *parent) : MultiContainerWidget(editorWindow, parent) { DragAccepter *accepter = new DragAccepter(editorWindow, this); accepter->resize(0, 0); // See note (1) in Comments _children.append(accepter); _text = i18n("Alternatives"); RegExpList list = regexp->children(); foreach (RegExp *r, list) { RegExpWidget *child = WidgetFactory::createWidget(r, editorWindow, this); ConcWidget *conc; if (!(conc = dynamic_cast(child))) { conc = new ConcWidget(editorWindow, child, parent); } append(conc); } updateDrawLineInfo(); } void AltnWidget::addNewChild(DragAccepter *accepter, RegExpWidget *child) { ConcWidget *conc = new ConcWidget(_editorWindow, child, this); MultiContainerWidget::addNewChild(accepter, conc); updateDrawLineInfo(); repaint(); } void AltnWidget::setConcChild(ConcWidget *child) { addNewConcChild(dynamic_cast(_children.at(0)), child); } void AltnWidget::addNewConcChild(DragAccepter *accepter, ConcWidget *child) { child->setParent(this); MultiContainerWidget::addNewChild(accepter, child); updateDrawLineInfo(); } QSize AltnWidget::sizeHint() const { QList::const_iterator it = _children.constBegin(); // Skip the first child, as we only need half of the size of the first and the // last drag accepter. Does, however, not apply when there only is onw child. if (_children.count() != 1) { ++it; } _childrenWidth = 0; _childrenHeight = 0; for (; it != _children.constEnd(); ++it) { QSize thisChildSize = (*it)->sizeHint(); _childrenWidth = qMax(_childrenWidth, thisChildSize.width()); _childrenHeight += thisChildSize.height(); } // Now add the size of the header QFontMetrics metrics = fontMetrics(); _textSize = metrics.size(0, _text); int headerWidth = _textSize.width() + 2 * bdSize + 2; _childrenWidth = qMax(_childrenWidth, headerWidth); return QSize(_childrenWidth + 2 * pw, _childrenHeight + _textSize.height() + 1 * pw); } void AltnWidget::paintEvent(QPaintEvent *e) { Q_ASSERT(dynamic_cast(_children.at(0))); // if this fails, then I should check the location of the show() Q_ASSERT(_children.count() == 1 || (_children.count() >= 3 && dynamic_cast(_children.at(_children.count() - 1)))); int offset = 0; QSize mySize = sizeHint(); QPainter painter(this); drawPossibleSelection(painter, mySize); //-------------------------------------- First draw the border and text int startY = _textSize.height() / 2; painter.drawLine(0, startY, bdSize, startY); int xOffset = bdSize + 1; painter.drawText(xOffset, 0, _textSize.width(), _textSize.height(), 0, _text); xOffset += _textSize.width() + 1; painter.drawLine(xOffset, startY, mySize.width(), startY); painter.drawLine(0, startY, 0, mySize.height()); painter.drawLine(mySize.width() - pw, startY, mySize.width() - pw, mySize.height()); painter.drawLine(0, mySize.height() - pw, mySize.width() - pw, mySize.height() - pw); //---- Run through all the children and place them at the correct location. offset = _textSize.height(); xOffset = pw; for (int i = 0; i < _children.count(); i++) { RegExpWidget *child = _children.at(i); QSize childSize = child->sizeHint(); QSize curChildSize = child->size(); //-------------------------------------- place the child int x = xOffset; int y = offset; int h = childSize.height(); if ((_children.count() != 1) && (i == 0 || i == _children.count() - 1)) { // first and last DragAccepter should only be half size. h /= 2; } int w = _childrenWidth; child->setGeometry(x, y, w, h); if (w != curChildSize.width() || h != curChildSize.height()) { // I resized the child, so give it a chance to relect thus. child->update(); } offset += h; } MultiContainerWidget::paintEvent(e); } RegExp *AltnWidget::regExp() const { AltnRegExp *regexp = new AltnRegExp(isSelected()); QList::const_iterator it = _children.constBegin(); ++it; // start with the second element for (; it != _children.constEnd(); it += 2) { regexp->addRegExp((*it)->regExp()); } return regexp; } void AltnWidget::applyRegExpToSelection(RegExpType type) { for (int i = 1; i < _children.count(); i += 2) { RegExpWidget *child = _children.at(i); if (child->hasSelection()) { child->applyRegExpToSelection(type); } } } RegExp *AltnWidget::selection() const { if (isSelected()) { return regExp(); } else { QList::const_iterator it = _children.constBegin(); ++it; // Skip past DragAccepter for (; *it; it += 2) { if ((*it)->hasSelection()) { return (*it)->selection(); } } } qFatal("Selection not found"); return nullptr; // compiler shut up. } bool AltnWidget::validateSelection() const { if (_isSelected) { return true; } bool foundASelection = false; QList::const_iterator it = _children.constBegin(); ++it; // Skip past DragAccepter for (; it != _children.constEnd(); it += 2) { if ((*it)->hasSelection()) { if (foundASelection) { - KMessageBox::information(const_cast(this), + QMessageBox::information(const_cast(this), + i18n("Selection Invalid"), i18n("Selecting several alternatives is " - "currently not supported."), - i18n("Selection Invalid")); + "currently not supported.")); _editorWindow->clearSelection(true); return false; } else { foundASelection = true; } } } return true; } void AltnWidget::updateDrawLineInfo() { for (int i = 0; i < _children.count(); i += 2) { bool line = (i != 0 && i != _children.count() - 1); DragAccepter *accepter = dynamic_cast(_children.at(i)); if (accepter) { accepter->setDrawLine(line); } } } void AltnWidget::deleteSelection() { MultiContainerWidget::deleteSelection(); updateDrawLineInfo(); } diff --git a/src/emacsregexpconverter.cpp b/src/emacsregexpconverter.cpp index 8c6734e..6e24072 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 #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")); + QMessageBox::warning(nullptr, i18n("Unsupported expression"), 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); } // 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")); + QMessageBox::warning(nullptr, QString(), 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("\\)"); } if (regexp->max() != -1) { for (int i = regexp->min(); i < regexp->max(); ++i) { res += QLatin1String("\\(") + cText + QLatin1String("\\)?"); } } 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/errormap.cpp b/src/errormap.cpp index 7ead8d4..e76c563 100644 --- a/src/errormap.cpp +++ b/src/errormap.cpp @@ -1,69 +1,75 @@ /* * 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 "errormap.h" -#include +#include #include ErrorMap::ErrorMap() : _prevLineStartError(false) , _prevLineEndError(false) , _prevLookAHeadError(false) { } void ErrorMap::start() { _lineStartError = false; _lineEndError = false; _lookAHeadError = false; } void ErrorMap::end() { _prevLineStartError = _lineStartError; _prevLineEndError = _lineEndError; _prevLookAHeadError = _lookAHeadError; } void ErrorMap::lineStartError() { if (!_prevLineStartError) { - KMessageBox::information(nullptr, i18n("Your regular expression is invalid, due to something preceding a 'line start'."), - i18n("Regular Expression Error"), QStringLiteral("KRegExpEditorLineStartError")); + QMessageBox::information(nullptr, + i18n("Regular Expression Error"), + i18n("Your regular expression is invalid, due to something preceding a 'line start'.") + ); } _lineStartError = true; } void ErrorMap::lineEndError() { if (!_prevLineEndError) { - KMessageBox::information(nullptr, i18n("Your regular expression is invalid, due to something following a 'line end'."), - i18n("Regular Expression Error"), QStringLiteral("KRegExpEditorLineEndError")); + QMessageBox::information(nullptr, + i18n("Regular Expression Error"), + i18n("Your regular expression is invalid, due to something following a 'line end'.") + ); } _lineEndError = true; } void ErrorMap::lookAheadError() { if (!_prevLookAHeadError) { - KMessageBox::information(nullptr, i18n("Your regular expression is invalid. 'Look Ahead' regular expression must be the last sub expression."), - i18n("Regular Expression Error"), QStringLiteral("KRegExpEditorLookAHeadError")); + QMessageBox::information(nullptr, + i18n("Your regular expression is invalid. 'Look Ahead' regular expression must be the last sub expression."), + i18n("Regular Expression Error") + ); } _lookAHeadError = true; } diff --git a/src/kregexpeditorprivate.cpp b/src/kregexpeditorprivate.cpp index b671ef3..df80864 100644 --- a/src/kregexpeditorprivate.cpp +++ b/src/kregexpeditorprivate.cpp @@ -1,436 +1,436 @@ /* * 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(/*area*/ this, QStringLiteral("KRegExpEditorPrivate::regExpButton")); addToolBar(Qt::TopToolBarArea, _regExpButtons); _verifyButtons = new VerifyButtons(/*area*/ this, QStringLiteral("KRegExpEditorPrivate::VerifyButtons")); addToolBar(Qt::TopToolBarArea, _verifyButtons); _auxButtons = new AuxButtons(/*area*/ this, QStringLiteral("KRegExpEditorPrivate::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())); _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->setMargin(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(_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(_scrolledEditorWindow, SIGNAL(doneEditing()), _regExpButtons, SLOT(slotSelectNewAction())); connect(_scrolledEditorWindow, SIGNAL(doneEditing()), _userRegExps, SLOT(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(_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(const QString&)), this, SLOT(setSyntax(const QString&))); connect(_verifyButtons, SIGNAL(matchGreedy(bool)), this, SLOT(setMatchGreedy(bool))); 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(_scrolledEditorWindow, SIGNAL(verifyRegExp()), this, SLOT(maybeVerify())); connect(_verifyButtons, SIGNAL(loadVerifyText(const QString&)), this, SLOT(setVerifyText(const QString&))); // connect( _verifier, SIGNAL( countChanged( int ) ), _verifyButtons, SLOT( setMatchCount( int ) ) ); // Qt anchors do not work for
...
, thefore scrolling to next/prev match // do not work. Enable this when they work. // connect( _verifyButtons, SIGNAL( gotoFirst() ), _verifier, SLOT( gotoFirst() ) ); // connect( _verifyButtons, SIGNAL( gotoPrev() ), _verifier, SLOT( gotoPrev() ) ); // connect( _verifyButtons, SIGNAL( gotoNext() ), _verifier, SLOT( gotoNext() ) ); // connect( _verifyButtons, SIGNAL( gotoLast() ), _verifier, SLOT( gotoLast() ) ); // connect( _verifier, SIGNAL( goForwardPossible( bool ) ), _verifyButtons, SLOT( enableForwardButtons( bool ) ) ); // connect( _verifier, SIGNAL( goBackwardPossible( bool ) ), _verifyButtons, SLOT( enableBackwardButtons( bool ) ) ); _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->setMargin(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(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kregexpeditor/pics/error.png"))); _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(const QString&)), this, SLOT(slotTriggerUpdate())); connect(_timer, SIGNAL(timeout()), this, SLOT(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() { emit canUndo(_undoStack.count() > 1); emit changes(_undoStack.count() > 1); 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)); + QMessageBox::warning(nullptr, QString(), 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::Background); } _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/qregexpparser.y b/src/qregexpparser.y index b950eda..170cf8b 100644 --- a/src/qregexpparser.y +++ b/src/qregexpparser.y @@ -1,228 +1,228 @@ /* * 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 YYENABLE_NLS # define YYENABLE_NLS 0 #endif #ifndef YYLTYPE_IS_TRIVIAL # define YYLTYPE_IS_TRIVIAL 0 #endif #include - #include + #include #include #include "regexp.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 "gen_qregexpparser.hh" #define YY_EXTRA_TYPE struct parse_context * extern int yylex( YYSTYPE* yylval, yyscan_t scanner ); extern void scannerInit( yyscan_t* scanner, struct parse_context* context, const QString& qstr ); extern void scannerDestroy( yyscan_t scanner ); int yyerror( yyscan_t scanner, struct parse_context* context, const char * ); void setParseResult( RegExp*, struct parse_context* ); RegExp* parseQtRegExp( const QString &qstr, bool* ok ); %} %code requires { #include "qregexpparsercommon.h" #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void *yyscan_t; #endif } %union { struct { int min; int max; } range; int backRef; RegExp* regexp; char ch; } %token TOK_Dot %token TOK_Dollar %token TOK_Carat %token TOK_MagicLeftParent %token TOK_PosLookAhead %token TOK_NegLookAhead %token TOK_LeftParen %token TOK_RightParent %token TOK_Bar %token TOK_Quantifier %token TOK_BackRef %token TOK_CharClass %token TOK_Char %token TOK_EscapeChar %token TOK_PosWordChar %token TOK_PosNonWordChar %start regexp %pure-parser %param { yyscan_t scanner } %parse-param { struct parse_context *context } %% empty : /* nothing */ ; regexp : expression { setParseResult( $1, context ) ; } | empty { setParseResult( new ConcRegExp( false ), context ); } ; expression : expression TOK_Bar term { if ( dynamic_cast( $1 ) ) { $$ = $1; } else { $$ = new AltnRegExp( false ); dynamic_cast( $$ )->addRegExp( $1 ); } dynamic_cast( $$ )->addRegExp( $3 ); } | term { $$ = $1; } | expression TOK_Bar { if ( dynamic_cast( $1 ) ) { $$ = $1; } else { $$ = new AltnRegExp( false ); dynamic_cast( $$ )->addRegExp( $1 ); } dynamic_cast( $$ )->addRegExp( new TextRegExp( false, QString::fromLatin1("") ) ); } | TOK_Bar term { $$ = new AltnRegExp( false ); dynamic_cast( $$ )->addRegExp( new TextRegExp( false, QString::fromLatin1("") ) ); dynamic_cast( $$ )->addRegExp( $2 ); } | TOK_Bar { $$ = new AltnRegExp( false ); } ; term : term factor { RegExp* last = dynamic_cast( $1 )->lastRegExp(); TextRegExp *reg1, *reg2; if ( last && ( reg1 = dynamic_cast( last ) ) && ( reg2 = dynamic_cast( $2 ) ) ) { reg1->append( reg2->text() ); delete reg2; } else { dynamic_cast($$)->addRegExp( $2 ); } $$ = $1; } | factor { ConcRegExp* reg = new ConcRegExp( false ); reg->addRegExp( $1 ); $$ = reg; } ; factor : atom TOK_Quantifier { $$ = new RepeatRegExp( false, $2.min, $2.max, $1 ); } | atom { $$ = $1; } ; atom : TOK_LeftParen expression TOK_RightParent { $$ = $2; } | TOK_MagicLeftParent expression TOK_RightParent { $$ = $2; } | TOK_PosLookAhead expression TOK_RightParent { $$ = new LookAheadRegExp( false, LookAheadRegExp::POSITIVE, $2 ); } | TOK_NegLookAhead expression TOK_RightParent { $$ = new LookAheadRegExp( false, LookAheadRegExp::NEGATIVE, $2 ); } | TOK_CharClass { $$ = $1; } | char { $$ = $1; } | TOK_Dollar { $$ = new PositionRegExp( false, PositionRegExp::ENDLINE ); } | TOK_Carat { $$ = new PositionRegExp( false, PositionRegExp::BEGLINE ); } | TOK_Dot { $$ = new DotRegExp( false ); } | TOK_BackRef { QString match = QString::fromLocal8Bit("\\%1").arg( $1 ); $$ = new TextRegExp( false, match ); context->backrefs << match; } | TOK_PosWordChar { $$ = new PositionRegExp( false, PositionRegExp::WORDBOUNDARY ); } | TOK_PosNonWordChar { $$ = new PositionRegExp( false, PositionRegExp::NONWORDBOUNDARY ); } ; char : TOK_Char { if ( $1 == '{' || $1 == '}' || $1 == '[' || $1 == ']' || $1 == '\\' ) { yyerror( scanner, context, "illigal character - needs escaping" ); } $$ = new TextRegExp( false, QString::fromLocal8Bit("%1").arg($1)); } | TOK_EscapeChar { $$ = new TextRegExp( false, QString::fromLocal8Bit("%1").arg($1)); } ; %% RegExp* parseQtRegExp( const QString &qstr, bool* ok ) { struct parse_context context; yyscan_t scanner; context.result = 0; context.nerrs = 0; scannerInit( &scanner, &context, qstr ); (void) yyparse( scanner, &context ); scannerDestroy( scanner ); foreach ( const QString &match, context.backrefs ) { - KMessageBox::information(nullptr,i18n("

Back reference regular expressions are not supported.

" + QMessageBox::information(nullptr, + i18n("Back reference regular expressions not supported"), + i18n("

Back reference regular expressions are not supported.

" "

\\1, \\2, ... are back references, meaning they " "refer to previous matches. " "Unfortunately this is not supported in the current version of this editor.

" "

In the graphical area the text %1 has been inserted. This is however " "just a workaround to ensure that the application handles the regexp at all. " "Therefore, as soon as you edit the regular expression in the graphical area, " "the back reference will be replaced by matching the text %2 literally.

", - match, match ), - i18n("Back reference regular expressions not supported"), - QString::fromLocal8Bit("backReferenceNotSupported") ); + match, match )); } *ok = ( context.nerrs == 0 ); return context.result; } void setParseResult( RegExp* regexp, struct parse_context* context ) { context->result = regexp; } int yyerror( yyscan_t, struct parse_context* context, const char * ) { context->nerrs++; return 0; } diff --git a/src/regexpeditorwindow.cpp b/src/regexpeditorwindow.cpp index 0532e7e..006da79 100644 --- a/src/regexpeditorwindow.cpp +++ b/src/regexpeditorwindow.cpp @@ -1,467 +1,475 @@ /* * 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 "regexpeditorwindow.h" #include #include #include #include #include #include #include #include #include #include #include #include #include -#include +#include #include #include "regexp.h" #include "userdefinedregexps.h" #include "concwidget.h" #include "regexpconverter.h" RegExpEditorWindow::RegExpEditorWindow(QWidget *parent) : QWidget(parent /*, Qt::WPaintUnclipped*/) { _top = new ConcWidget(this, this); _layout = new QHBoxLayout(this); _layout->addWidget(_top); _top->setToplevel(); _menu = nullptr; _insertInAction = false; _pasteInAction = false; _pasteData = nullptr; _PosEdit = QPoint(0, 0); (void)new QShortcut(Qt::CTRL + Qt::Key_C, this, SLOT(slotCopy())); (void)new QShortcut(Qt::CTRL + Qt::Key_X, this, SLOT(slotCut())); (void)new QShortcut(Qt::Key_Delete, this, SLOT(slotCut())); (void)new QShortcut(Qt::Key_Backspace, this, SLOT(slotCut())); (void)new QShortcut(Qt::CTRL + Qt::Key_V, this, SLOT(slotStartPasteAction())); (void)new QShortcut(Qt::Key_Escape, this, SLOT(slotEndActions())); (void)new QShortcut(Qt::CTRL + Qt::Key_S, this, SLOT(slotSave())); connect(this, &RegExpEditorWindow::change, this, &RegExpEditorWindow::emitVerifyRegExp); } RegExpEditorWindow::~RegExpEditorWindow() { delete _pasteData; } RegExp *RegExpEditorWindow::regExp() const { return _top->regExp(); } void RegExpEditorWindow::mousePressEvent(QMouseEvent *event) { setFocus(); updateContent(nullptr); _start = event->pos(); _lastPoint = QPoint(0, 0); if (pointSelected(event->globalPos())) { _isDndOperation = true; } else { _isDndOperation = false; _selection = QRect(); _top->updateSelection(false); QWidget::mousePressEvent(event); } grabMouse(); } bool RegExpEditorWindow::pointSelected(QPoint p) const { QRect rect = _top->selectionRect(); return rect.contains(p); } void RegExpEditorWindow::mouseMoveEvent(QMouseEvent *event) { if (_isDndOperation) { if ((_start - event->pos()).manhattanLength() > QApplication::startDragDistance()) { RegExp *regexp = _top->selection(); if (!regexp) { return; } QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; mimeData->setText(RegExpConverter::current()->toStr(regexp, false)); mimeData->setData(QStringLiteral("KRegExpEditor/widgetdrag"), regexp->toXmlString().toLocal8Bit()); delete regexp; drag->setMimeData(mimeData); Qt::DropAction dropAction = drag->exec(Qt::MoveAction | Qt::CopyAction, Qt::CopyAction); if (dropAction == Qt::MoveAction) { slotDeleteSelection(); } else { clearSelection(true); } releaseMouse(); emit change(); emit canSave(_top->hasAnyChildren()); } } else { _top->updateSelection(false); emit scrolling(event->pos()); _lastPoint = event->pos(); update(); _selection = QRect(mapToGlobal(_start), mapToGlobal(_lastPoint)).normalized(); } } void RegExpEditorWindow::mouseReleaseEvent(QMouseEvent *event) { releaseMouse(); QWidget::mouseReleaseEvent(event); _lastPoint = QPoint(0, 0); _top->validateSelection(); _top->updateAll(); emit anythingSelected(hasSelection()); if (hasSelection()) { emit verifyRegExp(); } } bool RegExpEditorWindow::selectionOverlap(QPoint pos, QSize size) const { QRect child(pos, size); return _selection.intersects(child) && !child.contains(_selection); } bool RegExpEditorWindow::hasSelection() const { return _top->hasSelection(); } void RegExpEditorWindow::clearSelection(bool update) { _top->clearSelection(); if (update) { _top->updateAll(); } emit anythingSelected(false); } void RegExpEditorWindow::slotInsertRegExp(RegExpType type) { _insertInAction = true; _insertTp = type; updateCursorUnderPoint(); setFocus(); } void RegExpEditorWindow::slotInsertRegExp(RegExp *regexp) { delete _pasteData; _pasteData = regexp->clone(); _pasteInAction = true; updateCursorUnderPoint(); setFocus(); } void RegExpEditorWindow::slotDoSelect() { _pasteInAction = false; _insertInAction = false; // I need to update the cursor recursively, as a repaint may not have been issued yet // when this method is invoked. This means that when the repaint comes, the cursor may // move to an other widget. _top->updateCursorRecursively(); } void RegExpEditorWindow::slotDeleteSelection() { if (!hasSelection()) { - KMessageBox::information(this, i18n("There is no selection."), i18n("Missing Selection")); + QMessageBox::information(this, i18n("There is no selection."), i18n("Missing Selection")); } else { _top->deleteSelection(); } updateContent(nullptr); } void RegExpEditorWindow::updateContent(QWidget *focusChild) { QPoint p(0, 0); if (focusChild) { p = focusChild->mapTo(this, QPoint(0, 0)); } _top->update(); emit contentChanged(p); } QSize RegExpEditorWindow::sizeHint() const { return _top->sizeHint(); } void RegExpEditorWindow::paintEvent(QPaintEvent *event) { QPainter p(this); p.setPen(Qt::DotLine); if (!_lastPoint.isNull()) { p.drawRect(QRect(_start, _lastPoint)); } QWidget::paintEvent(event); } void RegExpEditorWindow::slotCut() { cut(QCursor::pos()); emit change(); emit canSave(_top->hasAnyChildren()); } void RegExpEditorWindow::cut(QPoint pos) { cutCopyAux(pos); slotDeleteSelection(); } void RegExpEditorWindow::slotCopy() { copy(QCursor::pos()); } void RegExpEditorWindow::copy(QPoint pos) { cutCopyAux(pos); clearSelection(true); } void RegExpEditorWindow::cutCopyAux(QPoint pos) { if (!hasSelection()) { RegExpWidget *widget = _top->widgetUnderPoint(pos, true); if (!widget) { - KMessageBox::information(this, i18n("There is no widget under cursor."), i18n("Invalid Operation")); + QMessageBox::information(this, + i18n("Invalid Operation"), + i18n("There is no widget under cursor.") + ); return; } else { widget->updateSelection(true); // HACK! } } RegExp *regexp = _top->selection(); QMimeData *mimeData = new QMimeData; mimeData->setText(RegExpConverter::current()->toStr(regexp, false)); mimeData->setData(QStringLiteral("KRegExpEditor/widgetdrag"), regexp->toXmlString().toLocal8Bit()); delete regexp; QClipboard *clipboard = qApp->clipboard(); clipboard->setMimeData(mimeData); emit anythingOnClipboard(true); emit canSave(_top->hasAnyChildren()); } void RegExpEditorWindow::slotStartPasteAction() { QString str = QString::fromLatin1(qApp->clipboard()->mimeData()->data(QStringLiteral("KRegExpEditor/widgetdrag"))); if (str.isEmpty()) { return; } RegExp *regexp = WidgetFactory::createRegExp(str); if (regexp) { slotInsertRegExp(regexp); } } void RegExpEditorWindow::slotEndActions() { emit doneEditing(); emit change(); emit canSave(_top->hasAnyChildren()); } void RegExpEditorWindow::showRMBMenu(bool enableCutCopy) { enum CHOICES { CUT, COPY, PASTE, SAVE, EDIT }; if (!_menu) { _menu = new QMenu(nullptr); _cutAction = _menu->addAction(getIcon(QStringLiteral("edit-cut")), i18n("C&ut")); connect(_cutAction, &QAction::triggered, this, &RegExpEditorWindow::slotCut); _copyAction = _menu->addAction(getIcon(QStringLiteral("edit-copy")), i18n("&Copy")); connect(_copyAction, &QAction::triggered, this, &RegExpEditorWindow::slotCopy); _pasteAction = _menu->addAction(getIcon(QStringLiteral("edit-paste")), i18n("&Paste")); connect(_pasteAction, &QAction::triggered, this, &RegExpEditorWindow::slotStartPasteAction); _menu->addSeparator(); _editAction = _menu->addAction(getIcon(QStringLiteral("document-properties")), i18n("&Edit")); connect(_editAction, &QAction::triggered, this, &RegExpEditorWindow::editWidget); _saveAction = _menu->addAction(getIcon(QStringLiteral("document-save")), i18n("&Save Regular Expression...")); connect(_saveAction, &QAction::triggered, this, &RegExpEditorWindow::slotSave); } _cutAction->setEnabled(enableCutCopy); _copyAction->setEnabled(enableCutCopy); if (!qApp->clipboard()->mimeData()->hasFormat(QStringLiteral("KRegExpEditor/widgetdrag"))) { _pasteAction->setEnabled(false); } else { _pasteAction->setEnabled(true); } _saveAction->setEnabled(_top->hasAnyChildren()); _PosEdit = QCursor::pos(); RegExpWidget *editWidget = _top->findWidgetToEdit(_PosEdit); _editAction->setEnabled(editWidget); _menu->exec(_PosEdit); _PosEdit = QPoint(0, 0); emit change(); emit canSave(_top->hasAnyChildren()); } void RegExpEditorWindow::applyRegExpToSelection(RegExpType tp) { _top->applyRegExpToSelection(tp); } void RegExpEditorWindow::slotSave() { QString dir = WidgetWinItem::path(); QString txt; const QString tmp = QInputDialog::getText(this, i18n("Name for Regular Expression"), i18n("Enter name:")); if (tmp.trimmed().isEmpty()) { - KMessageBox::error(this, i18n("Empty name is not supported"), i18n("Save Regular Expression")); + QMessageBox::warning(this, + i18n("Save Regular Expression"), + i18n("Empty name is not supported") + ); return; } txt = tmp; QString fileName = dir + QStringLiteral("/") + txt + QStringLiteral(".regexp"); QFileInfo finfo(fileName); if (finfo.exists()) { - int answer = KMessageBox::warningContinueCancel(this, i18n("

Overwrite named regular expression %1

", txt), QString(), KStandardGuiItem::overwrite()); - if (answer != KMessageBox::Continue) { + int answer = QMessageBox::question(this, + QString(), + i18n("Overwrite named regular expression %1", txt)); + if (answer != QMessageBox::Yes) { return; } } QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { - KMessageBox::sorry(this, i18n("Could not open file for writing: %1", fileName)); + QMessageBox::critical(this, QString(), i18n("Could not open file for writing: %1", fileName)); return; } // Convert to XML. RegExp *regexp = _top->regExp(); QString xml = regexp->toXmlString(); delete regexp; QTextStream stream(&file); stream << xml; file.close(); emit savedRegexp(); } void RegExpEditorWindow::slotSetRegExp(RegExp *regexp) { // I have no clue why the following line is necesarry, but if it is not here // then the editor area is messed up when calling slotSetRegExp before starting the eventloop. qApp->processEvents(); delete _top; RegExpWidget *widget = WidgetFactory::createWidget(regexp, this, this); if (!(_top = dynamic_cast(widget))) { // It was not a ConcWidget _top = new ConcWidget(this, widget, this); } _top->setToplevel(); _top->show(); _layout->addWidget(_top); clearSelection(true); // HACK? emit canSave(_top->hasAnyChildren()); } void RegExpEditorWindow::updateCursorUnderPoint() { RegExpWidget *widget = _top->widgetUnderPoint(QCursor::pos(), false); if (widget) { widget->updateCursorShape(); } } void RegExpEditorWindow::emitVerifyRegExp() { emit verifyRegExp(); } void RegExpEditorWindow::editWidget() { QPoint EditPos = _PosEdit.isNull() ? QCursor::pos() : _PosEdit; RegExpWidget *editWidget = _top->findWidgetToEdit(EditPos); if (editWidget) { editWidget->edit(); } } QIcon RegExpEditorWindow::getIcon(const QString &name) { return QIcon::fromTheme(name); } diff --git a/src/repeatregexp.cpp b/src/repeatregexp.cpp index 26324a2..87420a0 100644 --- a/src/repeatregexp.cpp +++ b/src/repeatregexp.cpp @@ -1,93 +1,97 @@ /* * 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 "repeatregexp.h" -#include +#include #include RepeatRegExp::RepeatRegExp(bool selected, int lower, int upper, RegExp *child) : RegExp(selected) { _lower = lower; _upper = upper; _child = child; if (child) { addChild(child); } } bool RepeatRegExp::check(ErrorMap &map, bool first, bool last) { _child->check(map, first, last); return _lower == 0; } QDomNode RepeatRegExp::toXml(QDomDocument *doc) const { QDomElement top = doc->createElement(QStringLiteral("Repeat")); top.setAttribute(QStringLiteral("lower"), _lower); top.setAttribute(QStringLiteral("upper"), _upper); top.appendChild(_child->toXml(doc)); return top; } bool RepeatRegExp::load(const QDomElement &top, const QString &version) { Q_ASSERT(top.tagName() == QStringLiteral("Repeat")); QString lower = top.attribute(QStringLiteral("lower"), QStringLiteral("0")); QString upper = top.attribute(QStringLiteral("upper"), QStringLiteral("0")); bool ok; _lower = lower.toInt(&ok); if (!ok) { - KMessageBox::sorry(nullptr, i18n("

Value for attribute %1 was not an integer for element " + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

Value for attribute %1 was not an integer for element " "%2

It contained the value %3

", - QStringLiteral("lower"), QStringLiteral("Repeat"), lower), - i18n("Error While Loading From XML File")); + QStringLiteral("lower"), QStringLiteral("Repeat"), lower) + ); _lower = 0; } _upper = upper.toInt(&ok); if (!ok) { - KMessageBox::sorry(nullptr, i18n("

Value for attribute %1 was not an integer for element " + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

Value for attribute %1 was not an integer for element " "%2

It contained the value %3

", - QStringLiteral("upper"), QStringLiteral("Repeat"), upper), - i18n("Error While Loading From XML File")); + QStringLiteral("upper"), QStringLiteral("Repeat"), upper) + ); _upper = -1; } _child = readRegExp(top, version); if (_child) { addChild(_child); return true; } else { return false; } } bool RepeatRegExp::operator==(const RegExp &other) const { if (type() != other.type()) { return false; } const RepeatRegExp &theOther = dynamic_cast(other); if (_lower != theOther._lower || _upper != theOther._upper) { return false; } return *_child == *(theOther._child); } diff --git a/src/textrangeregexp.cpp b/src/textrangeregexp.cpp index 7681bc6..2281489 100644 --- a/src/textrangeregexp.cpp +++ b/src/textrangeregexp.cpp @@ -1,157 +1,159 @@ /* * 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 "textrangeregexp.h" #include -#include +#include #include "regexpconverter.h" TextRangeRegExp::TextRangeRegExp(bool selected) : RegExp(selected) , _negate(false) , _digit(false) , _nonDigit(false) , _space(false) , _nonSpace(false) , _wordChar(false) , _nonWordChar(false) { } TextRangeRegExp::~TextRangeRegExp() { } void TextRangeRegExp::addCharacter(const QString &str) { _chars.append(str); } void TextRangeRegExp::addRange(const QString &from, const QString &to) { _ranges.append(StringPair(from, to)); } bool TextRangeRegExp::check(ErrorMap &, bool, bool) { return false; } QDomNode TextRangeRegExp::toXml(QDomDocument *doc) const { QDomElement top = doc->createElement(QStringLiteral("TextRange")); if (_negate) { top.setAttribute(QStringLiteral("negate"), true); } if (_digit) { top.setAttribute(QStringLiteral("digit"), true); } if (_nonDigit) { top.setAttribute(QStringLiteral("nonDigit"), true); } if (_space) { top.setAttribute(QStringLiteral("space"), true); } if (_nonSpace) { top.setAttribute(QStringLiteral("nonSpace"), true); } if (_wordChar) { top.setAttribute(QStringLiteral("wordChar"), true); } if (_nonWordChar) { top.setAttribute(QStringLiteral("nonWordChar"), true); } for (QStringList::ConstIterator it = _chars.begin(); it != _chars.end(); ++it) { QDomElement elm = doc->createElement(QStringLiteral("Character")); elm.setAttribute(QStringLiteral("char"), *it); top.appendChild(elm); } foreach (const StringPair &pair, _ranges) { QDomElement elm = doc->createElement(QStringLiteral("Range")); elm.setAttribute(QStringLiteral("from"), pair.first); elm.setAttribute(QStringLiteral("to"), pair.second); top.appendChild(elm); } return top; } bool TextRangeRegExp::load(const QDomElement &top, const QString & /*version*/) { Q_ASSERT(top.tagName() == QStringLiteral("TextRange")); QString str; QString one = QStringLiteral("1"); QString zero = QStringLiteral("0"); str = top.attribute(QStringLiteral("negate"), zero); _negate = (str == one); str = top.attribute(QStringLiteral("digit"), zero); _digit = (str == one); str = top.attribute(QStringLiteral("nonDigit"), zero); _nonDigit = (str == one); str = top.attribute(QStringLiteral("space"), zero); _space = (str == one); str = top.attribute(QStringLiteral("nonSpace"), zero); _nonSpace = (str == one); str = top.attribute(QStringLiteral("wordChar"), zero); _wordChar = (str == one); str = top.attribute(QStringLiteral("nonWordChar"), zero); _nonWordChar = (str == one); for (QDomNode node = top.firstChild(); !node.isNull(); node = node.nextSibling()) { if (!node.isElement()) { continue; // Skip comments. } QDomElement child = node.toElement(); if (child.tagName() == QStringLiteral("Character")) { QString ch = child.attribute(QStringLiteral("char")); addCharacter(ch); } else if (child.tagName() == QStringLiteral("Range")) { QString from = child.attribute(QStringLiteral("from")); QString to = child.attribute(QStringLiteral("to")); addRange(from, to); } else { - KMessageBox::sorry(nullptr, i18n("

Invalid sub element to element TextRange. Tag was %1

", child.tagName()), - i18n("Error While Loading From XML File")); + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

Invalid sub element to element TextRange. Tag was %1

", child.tagName()) + ); return false; } } return true; } bool TextRangeRegExp::operator==(const RegExp &other) const { return RegExpConverter::current()->toStr(const_cast(this), false) == RegExpConverter::current()->toStr(const_cast(&other), false); } diff --git a/src/textregexp.cpp b/src/textregexp.cpp index 8384c64..db4cd04 100644 --- a/src/textregexp.cpp +++ b/src/textregexp.cpp @@ -1,78 +1,80 @@ /* * 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 "textregexp.h" -#include +#include #include TextRegExp::TextRegExp(bool selected, const QString &text) : RegExp(selected) { _text = text; } bool TextRegExp::check(ErrorMap &, bool, bool) { return false; } void TextRegExp::append(const QString &str) { _text.append(str); } QDomNode TextRegExp::toXml(QDomDocument *doc) const { QDomElement top = doc->createElement(QStringLiteral("Text")); QDomText text = doc->createTextNode(_text); top.appendChild(text); return top; } bool TextRegExp::load(const QDomElement &top, const QString & /*version*/) { Q_ASSERT(top.tagName() == QStringLiteral("Text")); if (top.hasChildNodes()) { QDomNode child = top.firstChild(); if (!child.isText()) { - KMessageBox::sorry(nullptr, i18n("

Element Text did not contain any textual data.

"), - i18n("Error While Loading From XML File")); + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

Element Text did not contain any textual data.

") + ); return false; } QDomText txtNode = child.toText(); _text = txtNode.data(); } else { _text = QString(); } return true; } bool TextRegExp::operator==(const RegExp &other) const { if (other.type() != type()) { return false; } const TextRegExp &theOther = dynamic_cast(other); if (text() == theOther.text()) { return true; } return false; } diff --git a/src/userdefinedregexps.cpp b/src/userdefinedregexps.cpp index 72649c2..9589879 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 #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->setMargin(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(const QPoint&)), this, SLOT(slotContextMenuTriggered(const QPoint&))); } 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 + QStringLiteral("/") + *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 *)0, QStringList(title)); lvItem->setExpanded(true); _userDefined->addTopLevelItem(lvItem); QDir directory(dir); QStringList files = directory.entryList(QStringList(QStringLiteral("*.regexp"))); for (QStringList::Iterator it = files.begin(); it != files.end(); ++it) { QString fileName = dir + QStringLiteral("/") + *it; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { - KMessageBox::sorry(this, i18n("Could not open file for reading: %1", fileName)); + QMessageBox::warning(this, QString(), 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)); + QMessageBox::warning(this, QString(), 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) { 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())); 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) { QString fileName = WidgetWinItem::path() + QStringLiteral("/") + 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) { + = QMessageBox::question(this, QString(), i18n("

Overwrite named regular expression %1?

", txt)); + if (answer != QMessageBox::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/widgetfactory.cpp b/src/widgetfactory.cpp index a576c7a..968f001 100644 --- a/src/widgetfactory.cpp +++ b/src/widgetfactory.cpp @@ -1,209 +1,217 @@ /* * 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 #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) { 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")); + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

Unknown tag while reading XML. Tag was %1

", tag) + ); 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")); + QMessageBox::warning(nullptr, + i18n("Error While Loading Regular Expression From XML"), + i18n("Error while loading regular expression from XML.") + QLatin1Char('\n') + error + ); } // 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")); + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

XML file did not contain a %1 tag.

", QStringLiteral("RegularExpression")) + ); } 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")); + QMessageBox::warning(nullptr, + i18n("Error While Loading From XML File"), + i18n("

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

", QStringLiteral("RegularExpression")) + ); } RegExp *regexp = WidgetFactory::createRegExp(child.toElement(), version); return regexp; }