diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,4 +1,3 @@ -#add_subdirectory(naturalqueryparser) add_definitions(-DTRANSLATION_DOMAIN=\"baloowidgets5\") add_subdirectory(filepropertiesplugin) @@ -16,9 +15,6 @@ keditcommentdialog.cpp metadatafilter.cpp widgetfactory.cpp - #groupedlineedit.cpp - #querybuilder.cpp - #querybuildercompleter.cpp filefetchjob.cpp ) @@ -38,7 +34,6 @@ KF5::FileMetaData KF5::WidgetsAddons KF5::Baloo - #KF5::BalooNaturalQueryParser KF5::CoreAddons KF5::ConfigGui ) @@ -60,8 +55,6 @@ TagWidget FileMetaDataWidget FileMetaDataConfigWidget - #QueryBuilder - #GroupedLineEdit PREFIX baloo REQUIRED_HEADERS KF5BalooWidgets_HEADERS diff --git a/src/groupedlineedit.h b/src/groupedlineedit.h deleted file mode 100644 --- a/src/groupedlineedit.h +++ /dev/null @@ -1,130 +0,0 @@ -/* This file is part of the Baloo widgets collection - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __GROUPEDLINEEDIT_H__ -#define __GROUPEDLINEEDIT_H__ - -#include - -#include "widgets_export.h" - -namespace Baloo { - -/** - * \class GroupedLineEdit groupedlineedit.h baloo/groupedlineedit.h - * \brief Single-line text editor with grouped terms support - * - * This widget looks like a QLineEdit, but terms can be grouped in it. A group - * consists of terms drawn inside a rounded rectangle. Rectangles have different - * colors, that allow the user to recognize parts of the input. They can be - * nested. - * - * This widget can be used to show how a line can be tokenized or parsed. For - * instance, the QueryBuilder widget uses this widget to show the filters of a - * query, but a mail client can also use the control to highlight e-mail - * addresses. - */ -class BALOO_WIDGETS_EXPORT GroupedLineEdit : public QPlainTextEdit -{ -Q_OBJECT - -public: - explicit GroupedLineEdit(QWidget *parent = 0); - virtual ~GroupedLineEdit(); - - /** - * Text displayed in this control. Use this method instead of - * toPlainText() as it is garanteed that this method will return exactly - * what the user sees. - */ - QString text() const; - - /** - * Current cursor position. The cursor position starts at 0 when the - * cursor is completely at the left of the control (for right-to-left - * languages) and goes to text().length() when the cursor is completely - * at the right of the control. - */ - int cursorPosition() const; - - /** - * Set the cursor position - * - * \sa cursorPosition - */ - void setCursorPosition(int position); - - /** - * Set the text dislayed by the control. Calling this method removes all - * the blocks. - * - * \sa text - * \sa removeAllBlocks - */ - void setText(const QString &text); - - /** - * Clear the text and the blocks contained in the widget. - */ - void clear(); - - /** - * Select all the text present in the control. - */ - void selectAll(); - - /** - * Remove all the blocks that were present in the control. The text is - * not changed, but no block will be drawn any more. - */ - void removeAllBlocks(); - - /** - * Add a block to the control. A block represents a group and is - * identified by the indexes of the first and the last characters in it. - * These limits are inclusive. - * - * The control maintains a list of block colors, that are cycled through - * at each block insertion. If you want the blocks to always have the - * same color even if they are removed and then re-added, always add - * them in the same order. - */ - void addBlock(int start, int end); - - virtual QSize sizeHint() const; - virtual QSize minimumSizeHint() const; - -Q_SIGNALS: - /** - * Signal triggered when the user presses Enter or Return in the control - */ - void editingFinished(); - -protected: - virtual void paintEvent(QPaintEvent *e); - virtual void keyPressEvent(QKeyEvent *e); - -private: - struct Private; - Private *d; -}; - -} - -#endif diff --git a/src/groupedlineedit.cpp b/src/groupedlineedit.cpp deleted file mode 100644 --- a/src/groupedlineedit.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* This file is part of the Baloo widgets collection - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "groupedlineedit.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace Baloo; - -struct GroupedLineEdit::Private -{ - struct Block { - int start; - int end; - }; - - QVector blocks; - QBrush base; -}; - -GroupedLineEdit::GroupedLineEdit(QWidget* parent) -: QPlainTextEdit(parent), - d(new Private) -{ - setWordWrapMode(QTextOption::NoWrap); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - - document()->setMaximumBlockCount(1); - - // Use a transparent base, to make the rectangle visible - QPalette pal = palette(); - - d->base = pal.base(); - pal.setBrush(QPalette::Base, Qt::transparent); - - setPalette(pal); -} - -GroupedLineEdit::~GroupedLineEdit() -{ - delete d; -} - -QString GroupedLineEdit::text() const -{ - // Remove the block crosses from the text - return toPlainText(); -} - -int GroupedLineEdit::cursorPosition() const -{ - return textCursor().positionInBlock(); -} - -void GroupedLineEdit::addBlock(int start, int end) -{ - Private::Block block; - - block.start = start; - block.end = end; - - d->blocks.append(block); - viewport()->update(); -} - -void GroupedLineEdit::setCursorPosition(int position) -{ - QTextCursor c = textCursor(); - - c.setPosition(position, QTextCursor::MoveAnchor); - - setTextCursor(c); -} - -void GroupedLineEdit::setText(const QString &text) -{ - setPlainText(text); -} - -void GroupedLineEdit::clear() -{ - QPlainTextEdit::clear(); - removeAllBlocks(); -} - -void GroupedLineEdit::selectAll() -{ - QTextCursor c = textCursor(); - - c.select(QTextCursor::LineUnderCursor); - - setTextCursor(c); -} - -void GroupedLineEdit::removeAllBlocks() -{ - d->blocks.clear(); - viewport()->update(); -} - -QSize GroupedLineEdit::sizeHint() const -{ - QSize rs( - 40, - document()->findBlock(0).layout()->lineAt(0).height() + - document()->documentMargin() * 2 + - frameWidth() * 2 - ); - - return rs; -} - -QSize GroupedLineEdit::minimumSizeHint() const -{ - return sizeHint(); -} - -void GroupedLineEdit::keyPressEvent(QKeyEvent *e) -{ - switch (e->key()) { - case Qt::Key_Return: - case Qt::Key_Enter: - emit editingFinished(); - return; - } - - QPlainTextEdit::keyPressEvent(e); -} - -void GroupedLineEdit::paintEvent(QPaintEvent *e) -{ - static const unsigned char colors[] = { - 0 , 87 , 174, - 243, 195, 0 , - 0 , 179, 119, - 235, 115, 49 , - 139, 179, 0 , - 85 , 87 , 83 , - 0 , 140, 0 , - 117, 81 , 26 - }; - - QTextLine line = document()->findBlock(0).layout()->lineAt(0); - QPainter painter(viewport()); - int color_index = 0; - - painter.setRenderHint(QPainter::Antialiasing, true); - painter.setRenderHint(QPainter::HighQualityAntialiasing, true); - - painter.fillRect(0, 0, viewport()->width(), viewport()->height(), d->base); - - Q_FOREACH(const Private::Block &block, d->blocks) { - qreal start_x = line.cursorToX(block.start, QTextLine::Leading); - qreal end_x = line.cursorToX(block.end + 1, QTextLine::Leading); - QPainterPath path; - QRectF rectangle( - start_x - 1.0 - double(horizontalScrollBar()->value()), - 1.0, - end_x - start_x + 2.0, - double(viewport()->height() - 2) - ); - - const unsigned char *c = colors + (color_index * 3); - QColor color(c[0], c[1], c[2]); - - path.addRoundedRect(rectangle, 5.0, 5.0); - painter.setPen(color); - painter.setBrush(color.lighter(180)); - painter.drawPath(path); - - color_index = (color_index + 1) & 0x7; // Increment color_index, modulo 8 so that it does not overflow colors - } - - QPlainTextEdit::paintEvent(e); -} - diff --git a/src/naturalqueryparser/CMakeLists.txt b/src/naturalqueryparser/CMakeLists.txt deleted file mode 100644 --- a/src/naturalqueryparser/CMakeLists.txt +++ /dev/null @@ -1,68 +0,0 @@ -remove_definitions(-DTRANSLATION_DOMAIN) -add_definitions(-DTRANSLATION_DOMAIN=\"baloo_naturalqueryparser\") - -set(QUERYPARSER_SRCS - completionproposal.cpp - pass_comparators.cpp - pass_dateperiods.cpp - pass_datevalues.cpp - pass_decimalvalues.cpp - pass_filenames.cpp - pass_filesize.cpp - pass_numbers.cpp - pass_periodnames.cpp - pass_properties.cpp - pass_propertyinfo.cpp - pass_splitunits.cpp - pass_subqueries.cpp - pass_typehints.cpp - patternmatcher.cpp - naturalqueryparser.cpp - naturalfilequeryparser.cpp - utils.cpp -) - -add_library(KF5BalooNaturalQueryParser ${QUERYPARSER_SRCS}) -add_library(KF5::BalooNaturalQueryParser ALIAS KF5BalooNaturalQueryParser) - -target_link_libraries(KF5BalooNaturalQueryParser - KF5::Baloo - KF5::KDELibs4Support - KF5::FileMetaData -) - -set_target_properties(KF5BalooNaturalQueryParser PROPERTIES - VERSION ${BALOO_WIDGETS_VERSION} - SOVERSION ${BALOO_WIDGETS_VERSION} - EXPORT_NAME BalooNaturalQueryParser -) - -target_include_directories(KF5BalooNaturalQueryParser INTERFACE "$") - -generate_export_header(KF5BalooNaturalQueryParser BASE_NAME BALOO_NATURALQUERYPARSER EXPORT_FILE_NAME naturalqueryparser_export.h) -ecm_generate_headers(KF5BalooNaturalQueryParser_CamelCase_HEADERS - HEADER_NAMES - CompletionProposal - NaturalQueryParser - NaturalFileQueryParser - - PREFIX baloo - REQUIRED_HEADERS KF5BalooNaturalQueryParser_HEADERS -) - -install(TARGETS KF5BalooNaturalQueryParser EXPORT KF5BalooWidgetsTargets ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) - -install(FILES - ${CMAKE_CURRENT_BINARY_DIR}/naturalqueryparser_export.h - ${KF5BalooNaturalQueryParser_HEADERS} - DESTINATION ${KF5_INCLUDE_INSTALL_DIR}/BalooWidgets/baloo - COMPONENT Devel -) - -install(FILES - ${KF5BalooNaturalQueryParser_CamelCase_HEADERS} - DESTINATION ${KF5_INCLUDE_INSTALL_DIR}/BalooWidgets/Baloo - COMPONENT Devel -) - -add_subdirectory(autotests) diff --git a/src/naturalqueryparser/Messages.sh b/src/naturalqueryparser/Messages.sh deleted file mode 100755 --- a/src/naturalqueryparser/Messages.sh +++ /dev/null @@ -1,2 +0,0 @@ -#! /usr/bin/env bash -$XGETTEXT `find . -name "*.cpp" | grep -v "/autotests/"` -o $podir/baloo_naturalqueryparser.pot diff --git a/src/naturalqueryparser/autotests/CMakeLists.txt b/src/naturalqueryparser/autotests/CMakeLists.txt deleted file mode 100644 --- a/src/naturalqueryparser/autotests/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -# -# Query Parser -# -set(queryParser_SRC naturalqueryparsertest.cpp) - -ecm_add_test(naturalqueryparsertest.cpp - TEST_NAME "naturalqueryparsertest" - LINK_LIBRARIES Qt5::Test KF5::Baloo KF5BalooNaturalQueryParser -) diff --git a/src/naturalqueryparser/autotests/naturalqueryparsertest.h b/src/naturalqueryparser/autotests/naturalqueryparsertest.h deleted file mode 100644 --- a/src/naturalqueryparser/autotests/naturalqueryparsertest.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of the Baloo Query Parser - * Copyright (C) 2014 Denis Steckelmacher - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef BALOO_NATURALQUERYPARSERTEST_H -#define BALOO_NATURALQUERYPARSERTEST_H - -#include - -namespace Baloo { - -class NaturalQueryParserTest : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - void testSearchString(); - void testNumbers(); - void testDecimal(); - void testFilesize(); - void testDatetime(); - void testFilename(); - void testTypehints(); - void testReduction(); - void testTags(); - void testPropertyInfo(); -}; -} - -#endif diff --git a/src/naturalqueryparser/autotests/naturalqueryparsertest.cpp b/src/naturalqueryparser/autotests/naturalqueryparsertest.cpp deleted file mode 100644 --- a/src/naturalqueryparser/autotests/naturalqueryparsertest.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* - * This file is part of the Baloo Query Parser - * Copyright (C) 2014 Denis Steckelmacher - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include "naturalqueryparsertest.h" - -#include -#include - -#include "../naturalfilequeryparser.h" - -#include - -#include - -using namespace Baloo; - -namespace QTest { - template<> - char *toString(const Query &query) - { - Query *q = const_cast(&query); // query.toJSON does not modify query but is not marked const - - return qstrdup(q->toJSON().constData()); - } -} - - -void NaturalQueryParserTest::testSearchString() -{ - QString search_string(QLatin1String("correct horse battery staple ")); - - QCOMPARE( - NaturalFileQueryParser::parseQuery(search_string).searchString(), - search_string - ); -} - -void NaturalQueryParserTest::testNumbers() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("size > 1024")), - Query(Term(QLatin1String("size"), 1024LL, Term::Greater)) - ); -} - -void NaturalQueryParserTest::testDecimal() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("size > 1024.38")), - Query(Term(QLatin1String("size"), 1024.38, Term::Greater)) - ); -} - -void NaturalQueryParserTest::testFilesize() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("size > 2K")), - Query(Term(QLatin1String("size"), 2048, Term::Greater)) - ); -} - -void NaturalQueryParserTest::testDatetime() -{ - Query expected; - QDateTime now = QDateTime::currentDateTime(); - - // Today - expected.setDateFilter(now.date().year(), now.date().month(), now.date().day()); - expected.setTerm(Term()); - - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("today")), - expected - ); - - // Yesterday - now = now.addDays(-1); - expected.setDateFilter(now.date().year(), now.date().month(), now.date().day()); - - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("yesterday")), - expected - ); - - // A specific date - expected.setDateFilter(2011, 1, 2); - - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("January 2, 2011")), - expected - ); -} - -void NaturalQueryParserTest::testFilename() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("\"*.txt\""), NaturalQueryParser::DetectFilenamePattern), - Query(Term(QLatin1String("filename"), QRegExp(QLatin1String("^.*\\\\.txt$")), Term::Contains)) - ); -} - -void NaturalQueryParserTest::testTypehints() -{ - Query expected; - - expected.setType(QLatin1String("Email")); - - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("emails")), - expected - ); -} - -void NaturalQueryParserTest::testReduction() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("size > 2K and size < 3K")), - Query(Term(QLatin1String("size"), 2048, Term::Greater) && Term(QLatin1String("size"), 3072, Term::Less)) - ); - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("size > 2K or size < 3K")), - Query(Term(QLatin1String("size"), 2048, Term::Greater) || Term(QLatin1String("size"), 3072, Term::Less)) - ); -} - -void NaturalQueryParserTest::testTags() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("tagged as Important")), - Query(Term(QLatin1String("tags"), QLatin1String("Important"), Term::Contains)) - ); -} - -void NaturalQueryParserTest::testPropertyInfo() -{ - QCOMPARE( - NaturalFileQueryParser::parseQuery(QLatin1String("bitRate > 44000")), - Query(Term(QLatin1String("bitRate"), 44000, Term::Greater)) - ); -} - -QTEST_KDEMAIN_CORE(NaturalQueryParserTest) diff --git a/src/naturalqueryparser/completionproposal.h b/src/naturalqueryparser/completionproposal.h deleted file mode 100644 --- a/src/naturalqueryparser/completionproposal.h +++ /dev/null @@ -1,124 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __BALOO_SEARCH_COMPLETION_PROPOSAL_H__ -#define __BALOO_SEARCH_COMPLETION_PROPOSAL_H__ - -#include -#include - -#include "naturalqueryparser_export.h" -#include "klocalizedstring.h" - -namespace Baloo -{ - -/** - * \class CompletionProposal completionproposal.h Baloo/Query/CompletionProposal - * \brief Information about an auto-completion proposal - * - * When parsing an user query, QueryParser may find that a pattern that nearly - * matches and that the user may want to use. In this case, one or more - * completion proposals are used to describe what patterns can be used. - */ -class BALOO_NATURALQUERYPARSER_EXPORT CompletionProposal -{ - private: - Q_DISABLE_COPY(CompletionProposal) - - public: - /** - * \brief Data-type used by the first placeholder of the pattern - * - * If the pattern is "sent by $1", the type of "$1" is Contact. This - * way, a GUI can show to the user a list of his or her contacts. - */ - enum Type - { - NoType, /*!< No specific type (integer, string, something that does not need any auto-completion list) */ - DateTime, /*!< A date-time */ - Tag, /*!< A valid tag name */ - Contact, /*!< Something that can be parsed unambiguously to a contact (a contact name, email, pseudo, etc) */ - Email, /*!< An e-mail address */ - PropertyName, /*!< A property name. List of these names can be found in kde:kfilemetadata/src/propertyinfo.h */ - }; - - /** - * \param pattern list of terms matched by the proposal ("sent", - * "by", "$1" for instance) - * \param last_matched_part index of the last part of the mattern - * that has been matched against the user - * query - * \param position position in the user query of the pattern matched - * \param length length in the user query of the terms matched - * \param type if the pattern contains "$1", this is the type of - * the value matched by this placeholder - * \param description human description of the pattern - */ - CompletionProposal(const QStringList &pattern, - int last_matched_part, - int position, - int length, - Type type, - const KLocalizedString &description); - ~CompletionProposal(); - - /** - * \return list of terms that make the pattern - */ - QStringList pattern() const; - - /** - * \return index of the last matched part of the pattern - */ - int lastMatchedPart() const; - - /** - * \return position in the user query of the pattern - * - * As an user query can contain spaces and separators that are - * ignored by the pattern matcher, position() and length() are - * used to find the sub-string of the user query that has matched - * against the pattern. - */ - int position() const; - - /** - * \sa position - */ - int length() const; - - /** - * \return type of the value represented by the "$1" term in the pattern - */ - Type type() const; - - /** - * \return description of the pattern - */ - KLocalizedString description() const; - - private: - struct Private; - Private *const d; -}; - -} - -#endif diff --git a/src/naturalqueryparser/completionproposal.cpp b/src/naturalqueryparser/completionproposal.cpp deleted file mode 100644 --- a/src/naturalqueryparser/completionproposal.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "completionproposal.h" - -#include "klocalizedstring.h" - -using namespace Baloo; - -struct CompletionProposal::Private -{ - QStringList pattern; - int last_matched_part; - int position; - int length; - CompletionProposal::Type type; - KLocalizedString description; -}; - -CompletionProposal::CompletionProposal(const QStringList &pattern, - int last_matched_part, - int position, - int length, - Type type, - const KLocalizedString &description) -: d(new Private) -{ - d->pattern = pattern; - d->last_matched_part = last_matched_part; - d->position = position; - d->length = length; - d->type = type; - d->description = description; -} - -CompletionProposal::~CompletionProposal() -{ - delete d; -} - -int CompletionProposal::position() const -{ - return d->position; -} - -int CompletionProposal::length() const -{ - return d->length; -} - -int CompletionProposal::lastMatchedPart() const -{ - return d->last_matched_part; -} - -QStringList CompletionProposal::pattern() const -{ - return d->pattern; -} - -CompletionProposal::Type CompletionProposal::type() const -{ - return d->type; -} - -KLocalizedString CompletionProposal::description() const -{ - return d->description; -} diff --git a/src/naturalqueryparser/naturalfilequeryparser.h b/src/naturalqueryparser/naturalfilequeryparser.h deleted file mode 100644 --- a/src/naturalqueryparser/naturalfilequeryparser.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - This file is part of the Baloo KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - 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 _BALOO_NATURAL_FILE_QUERY_PARSER_H_ -#define _BALOO_NATURAL_FILE_QUERY_PARSER_H_ - -#include "naturalqueryparser.h" - -namespace Baloo { -/** - * \class NaturalFileQueryParser naturalqueryparser.h baloo/naturalqueryparser.h - * - * \brief Parser for desktop file user queries. - * - * Natural query parser tailored for File queries. It extends NaturalQueryParser - * (please read its documentation for advice and important notices) by providing - * patterns specifically targetting file queries. For instance, the user can - * specify which type a file must have, or what its size should be. - */ -class BALOO_NATURALQUERYPARSER_EXPORT NaturalFileQueryParser : public NaturalQueryParser -{ -public: - /** - * Create a new query parser. - */ - NaturalFileQueryParser(); - - /** - * Destructor - */ - ~NaturalFileQueryParser(); - - /** - * Convenience method to quickly parse a query without creating an object. - * - * \warning The parser caches many useful information that is slow to - * retrieve from the Baloo database. If you have to parse - * many queries, consider using a QueryParser object. - * - * \param query The query string to parse - * \param flags a set of flags influencing the parsing process. - * \return The parsed query or an invalid Query object in case the parsing failed. - */ - static Query parseQuery( const QString& query, ParserFlags flags = NoParserFlags); - -protected: - virtual void addSpecificPatterns(int cursor_position, NaturalQueryParser::ParserFlags flags) const; - -private: - struct Private; - Private *d; -}; - -} - -#endif diff --git a/src/naturalqueryparser/naturalfilequeryparser.cpp b/src/naturalqueryparser/naturalfilequeryparser.cpp deleted file mode 100644 --- a/src/naturalqueryparser/naturalfilequeryparser.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "naturalfilequeryparser.h" -#include "naturalqueryparser_p.h" -#include "pass_properties.h" -#include "pass_propertyinfo.h" - -using namespace Baloo; - -struct NaturalFileQueryParser::Private -{ - PassPropertyInfo pass_propertyinfo; -}; - -NaturalFileQueryParser::NaturalFileQueryParser() -: d(new Private) -{ -} - -NaturalFileQueryParser::~NaturalFileQueryParser() -{ - delete d; -} - -void NaturalFileQueryParser::addSpecificPatterns(int cursor_position, NaturalQueryParser::ParserFlags flags) const -{ - NaturalQueryParser::addSpecificPatterns(cursor_position, flags); - - // Properties associated with any Baloo resource - passProperties().setProperty(QLatin1String("rating"), PassProperties::Integer); - runPass(passProperties(), cursor_position, - i18nc("Numeric rating of a resource", "rated as $1;rated $1;score is $1;score|scored $1;having $1 stars|star"), - ki18n("Rating (0 to 10)"), CompletionProposal::NoType); - passProperties().setProperty(QLatin1String("usercomment"), PassProperties::String); - runPass(passProperties(), cursor_position, - i18nc("Comment of a resource", "described as $1;description|comment is $1;described|description|comment $1"), - ki18n("Comment or description"), CompletionProposal::NoType); - - // File-related properties - passProperties().setProperty(QLatin1String("author"), PassProperties::Contact); - runPass(passProperties(), cursor_position, - i18nc("Author of a document", "written|created|composed by $1;author is $1;by $1"), - ki18n("Author"), CompletionProposal::Contact); - passProperties().setProperty(QLatin1String("size"), PassProperties::IntegerOrDouble); - runPass(passProperties(), cursor_position, - i18nc("Size of a file", "size is $1;size $1;being $1 large;$1 large"), - ki18n("Size")); - passProperties().setProperty(QLatin1String("filename"), PassProperties::String); - runPass(passProperties(), cursor_position, - i18nc("Name of a file or contact", "name is $1;name $1;named $1"), - ki18n("Name")); - passProperties().setProperty(QLatin1String("_k_datecreated"), PassProperties::DateTime); - runPass(passProperties(), cursor_position, - i18nc("Date of creation", "created|dated at|on|in|of $1;created|dated $1;creation date|time|datetime is $1"), - ki18n("Date of creation"), CompletionProposal::DateTime); - passProperties().setProperty(QLatin1String("_k_datemodified"), PassProperties::DateTime); - runPass(passProperties(), cursor_position, - i18nc("Date of last modification", "modified|edited at|on $1;modified|edited $1;modification|edition date|time|datetime is $1"), - ki18n("Date of last modification"), CompletionProposal::DateTime); - - // Tags - passProperties().setProperty(QLatin1String("tags"), PassProperties::Tag); - runPass(passProperties(), cursor_position, - i18nc("A document is associated with a tag", "tagged as $1;has tag $1;tag is $1;# $1"), - ki18n("Tag name"), CompletionProposal::Tag); - - // Generic properties using a simpler and more discoverable syntax - runPass(d->pass_propertyinfo, cursor_position, - i18nc("$1 is a property name (non-translatable unfortunately) and $2 is the value against which the property is matched. Note that the equal/greater/smaller sign has already been folded in $2", "$1 is $2;$1 $2"), - ki18n("File property"), CompletionProposal::PropertyName); -} - -Query NaturalFileQueryParser::parseQuery(const QString& query, ParserFlags flags) -{ - return NaturalFileQueryParser().parse(query, flags); -} diff --git a/src/naturalqueryparser/naturalqueryparser.h b/src/naturalqueryparser/naturalqueryparser.h deleted file mode 100644 --- a/src/naturalqueryparser/naturalqueryparser.h +++ /dev/null @@ -1,185 +0,0 @@ -/* - This file is part of the Baloo KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - 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 _BALOO_NATURAL_QUERY_PARSER_H_ -#define _BALOO_NATURAL_QUERY_PARSER_H_ - -#include -#include "completionproposal.h" -#include "naturalqueryparser_export.h" - -#include - -class PatternMatcher; -class PassProperties; - -namespace Baloo { -/** - * \class NaturalQueryParser naturalqueryparser.h baloo/naturalqueryparser.h - * - * \brief Parser for desktop user queries. - * - * \warning This is NOT a SPARQL parser. - * \note Don't forget to insert the "baloo_naturalqueryparser" localization catalog - * for this class to be localized. Do so using KLocale::insertCatalog. - * - * The NaturalQueryParser can be used to parse user queries, ie. queries that the user - * would enter in any search interface, and convert them into Query instances. - * - * The syntax is language-dependent and as natural as possible. Words are - * by default matched against the content of documents, and special patterns - * like "sent by X" are recognized and changed to property comparisons. - * - * Natural date-times can also be used and are recognized as date-time - * literals. "sent on March 6" and "created last week" work as expected. - * - * \section naturalqueryparser_examples Examples - * - * %Query everything that contains the term "baloo": - * \code - * baloo - * \endcode - * - * %Query everything that contains both the terms "Hello" and "World": - * \code - * Hello World - * \endcode - * - * %Query everything that contains the term "Hello World": - * \code - * "Hello World" - * \endcode - * - * %Query everything that has a tag whose label matches "baloo": - * \code - * tagged as baloo, has tag baloo - * \endcode - * - * %Query everything that has a tag labeled "baloo" or a tag labeled "scribo": - * \code - * tagged as baloo OR tagged as scribo - * \endcode - * - * \note "tagged as baloo or scribo" currently does not work as expected - * - * %Query everything that has a tag labeled "baloo" but not a tag labeled "scribo": - * \code - * tagged as baloo and not tagged as scribo - * \endcode - * - * Some properties also accept nested queries. For instance, this %Query - * returns the list of documents related to emails tagged as important. - * \code - * documents related to mails tagged as important - * \endcode - * - * More complex nested queries can be built, and are ended with a comma - * (in English): - * \code - * documents related to mails from Smith and tagged as important, size > 2M - * \endcode - * - * \author Denis Steckelmacher - * - * \since 4.14 - */ -class BALOO_NATURALQUERYPARSER_EXPORT NaturalQueryParser -{ -public: - /** - * Create a new query parser. - */ - NaturalQueryParser(); - - /** - * Destructor - */ - virtual ~NaturalQueryParser(); - - /** - * Flags to change the behaviour of the parser. - */ - enum ParserFlag { - /** - * No flags. Default for parse() - */ - NoParserFlags = 0x0, - - /** - * Try to detect filename pattern like *.mp3 - * or hello*.txt and use regular expressions to match these terms - */ - DetectFilenamePattern = 0x1 - }; - Q_DECLARE_FLAGS( ParserFlags, ParserFlag ) - - /** - * Parse a user query. - * - * \param query The query string to parse - * \param flags a set of flags influencing the parsing process. - * \param cursor_position position of the cursor in a line edit used - * by the user to enter the query. It is used - * to provide auto-completion proposals. - * - * \return The parsed query or an invalid Query object - * in case the parsing failed. - */ - Query parse(const QString& query, - ParserFlags flags = NoParserFlags, - int cursor_position = -1) const; - - /** - * List of completion proposals related to the previously parsed query - * - * \note The query parser is responsible for deleting the CompletionProposal - * objects. - */ - QList completionProposals() const; - -private: - void addCompletionProposal(CompletionProposal *proposal) const; - QStringList split(const QString &query, bool is_user_query, QList *positions = NULL) const; - QList &terms() const; - -protected: - virtual void addSpecificPatterns(int cursor_position, NaturalQueryParser::ParserFlags flags) const; - - template - void runPass(const T &pass, - int cursor_position, - const QString &pattern, - const KLocalizedString &description = KLocalizedString(), - CompletionProposal::Type type = CompletionProposal::NoType) const; - - // Some passes that subclass may want to use - PassProperties &passProperties() const; - -private: - struct Private; - Private* const d; - - friend class ::PatternMatcher; -}; - -} - -Q_DECLARE_OPERATORS_FOR_FLAGS(Baloo::NaturalQueryParser::ParserFlags) - -#endif diff --git a/src/naturalqueryparser/naturalqueryparser.cpp b/src/naturalqueryparser/naturalqueryparser.cpp deleted file mode 100644 --- a/src/naturalqueryparser/naturalqueryparser.cpp +++ /dev/null @@ -1,788 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "naturalqueryparser.h" -#include "naturalqueryparser_p.h" -#include "completionproposal.h" -#include "utils.h" - -#include "pass_splitunits.h" -#include "pass_numbers.h" -#include "pass_decimalvalues.h" -#include "pass_filenames.h" -#include "pass_filesize.h" -#include "pass_typehints.h" -#include "pass_properties.h" -#include "pass_dateperiods.h" -#include "pass_datevalues.h" -#include "pass_periodnames.h" -#include "pass_subqueries.h" -#include "pass_comparators.h" - -#include -#include - -#include -#include -#include - -#include - -using namespace Baloo; - -struct Field { - enum Flags { - Unset = 0, - Absolute, - Relative - }; - - int value; - Flags flags; - - void reset() - { - value = 0; - flags = Unset; - } -}; - -struct DateTimeSpec { - Field fields[PassDatePeriods::MaxPeriod]; - - void reset() - { - for (int i=0; i=#+-")) - { - } - - void foldDateTimes(); - void handleDateTimeComparison(DateTimeSpec &spec, const Term &term); - - Term intervalComparison(const QString &prop, - const Term &min, - const Term &max); - Term dateTimeComparison(const QString &prop, - const Term &term); - Term tuneTerm(Term term, Query &query); - - NaturalQueryParser *parser; - QList terms; - QList proposals; - - // Parsing passes (they cache translations, queries, etc) - PassSplitUnits pass_splitunits; - PassNumbers pass_numbers; - PassDecimalValues pass_decimalvalues; - PassFileNames pass_filenames; - PassFileSize pass_filesize; - PassTypeHints pass_typehints; - PassComparators pass_comparators; - PassProperties pass_properties; - PassDatePeriods pass_dateperiods; - PassDateValues pass_datevalues; - PassPeriodNames pass_periodnames; - PassSubqueries pass_subqueries; - - // Locale-specific - QString separators; -}; - -NaturalQueryParser::NaturalQueryParser() -: d(new Private) -{ - d->parser = this; -} - -NaturalQueryParser::~NaturalQueryParser() -{ - qDeleteAll(d->proposals); - delete d; -} - -Query NaturalQueryParser::parse(const QString &query, ParserFlags flags, int cursor_position) const -{ - qDeleteAll(d->proposals); - - d->terms.clear(); - d->proposals.clear(); - - // Split the query into terms - QList positions; - QStringList parts = split(query, true, &positions); - - for (int i=0; i 0 && - query.at(position - 1) == QLatin1Char('"')) { - // Absorb the starting quote into the term's position - --position; - ++length; - } - if (position + length < query.length() && - query.at(position + length) == QLatin1Char('"')) { - // Absorb the ending quote into the term's position - ++length; - } - - d->terms.append(Term(QString(), part, Term::Equal)); - setTermRange(d->terms.last(), position, position + length - 1); - } - - // Run the parsing passes - addSpecificPatterns(cursor_position, flags); - - // Product the query - int unused; - Term term = fuseTerms(d->terms, 0, unused); - Query rs; - - rs.setTerm(d->tuneTerm(term, rs)); - - return rs; -} - -QList NaturalQueryParser::completionProposals() const -{ - return d->proposals; -} - -void NaturalQueryParser::addSpecificPatterns(int cursor_position, NaturalQueryParser::ParserFlags flags) const -{ - // Prepare literal values - runPass(d->pass_splitunits, cursor_position, QLatin1String("$1")); - runPass(d->pass_numbers, cursor_position, QLatin1String("$1")); - runPass(d->pass_filesize, cursor_position, QLatin1String("$1 $2")); - runPass(d->pass_typehints, cursor_position, QLatin1String("$1")); - - if (flags & DetectFilenamePattern) { - runPass(d->pass_filenames, cursor_position, QLatin1String("$1")); - } - - // Date-time periods - runPass(d->pass_periodnames, cursor_position, QLatin1String("$1")); - - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::Offset); - runPass(d->pass_dateperiods, cursor_position, - i18nc("Adding an offset to a period of time ($1=period, $2=offset)", "in $2 $1")); - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::InvertedOffset); - runPass(d->pass_dateperiods, cursor_position, - i18nc("Removing an offset from a period of time ($1=period, $2=offset)", "$2 $1 ago")); - - d->pass_dateperiods.setKind(PassDatePeriods::Day, PassDatePeriods::Offset, 1); - runPass(d->pass_dateperiods, cursor_position, - i18nc("In one day", "tomorrow"), - ki18n("Tomorrow")); - d->pass_dateperiods.setKind(PassDatePeriods::Day, PassDatePeriods::Offset, -1); - runPass(d->pass_dateperiods, cursor_position, - i18nc("One day ago", "yesterday"), - ki18n("Yesterday")); - d->pass_dateperiods.setKind(PassDatePeriods::Day, PassDatePeriods::Offset, 0); - runPass(d->pass_dateperiods, cursor_position, - i18nc("The current day", "today"), - ki18n("Today")); - - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::Value, 1); - runPass(d->pass_dateperiods, cursor_position, - i18nc("First period (first day, month, etc)", "first $1"), - ki18n("First week, month, day, ...")); - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::Value, -1); - runPass(d->pass_dateperiods, cursor_position, - i18nc("Last period (last day, month, etc)", "last $1 of"), - ki18n("Last week, month, day, ...")); - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::Value); - runPass(d->pass_dateperiods, cursor_position, - i18nc("Setting the value of a period, as in 'third week' ($1=period, $2=value)", "$2 $1")); - - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::Offset, 1); - runPass(d->pass_dateperiods, cursor_position, - i18nc("Adding 1 to a period of time", "next $1"), - ki18n("Next week, month, day, ...")); - d->pass_dateperiods.setKind(PassDatePeriods::VariablePeriod, PassDatePeriods::Offset, -1); - runPass(d->pass_dateperiods, cursor_position, - i18nc("Removing 1 to a period of time", "last $1"), - ki18n("Previous week, month, day, ...")); - - // Setting values of date-time periods (14:30, June 6, etc) - d->pass_datevalues.setPm(true); - runPass(d->pass_datevalues, cursor_position, - i18nc("An hour ($5) and an optional minute ($6), PM", "at $5 :|\\. $6 pm;at $5 h pm;at $5 pm;$5 : $6 pm;$5 h pm;$5 pm"), - ki18n("A time after midday")); - d->pass_datevalues.setPm(false); - runPass(d->pass_datevalues, cursor_position, - i18nc("An hour ($5) and an optional minute ($6), AM", "at $5 :|\\. $6 am;at $5 \\. $6;at $5 h am;at $5 am;at $5;$5 :|\\. $6 am;$5 : $6 : $7;$5 : $6;$5 h am;$5 h;$5 am"), - ki18n("A time")); - - runPass(d->pass_datevalues, cursor_position, i18nc( - "A year ($1), month ($2), day ($3), day of week ($4), hour ($5), " - "minute ($6), second ($7), in every combination supported by your language", - "$3 of $2 $1;$3 st|nd|rd|th $2 $1;$3 st|nd|rd|th of $2 $1;" - "$3 of $2;$3 st|nd|rd|th $2;$3 st|nd|rd|th of $2;$2 $3 st|nd|rd|th;$2 $3;$2 $1;" - "$1 - $2 - $3;$1 - $2;$3 / $2 / $1;$3 / $2;" - "in $2 $1; in $1;, $1" - )); - - // Fold date-time properties into real DateTime values - d->foldDateTimes(); - - // Decimal values - runPass(d->pass_decimalvalues, cursor_position, - i18nc("Decimal values with an integer ($1) and decimal ($2) part", "$1 \\. $2"), - ki18n("A decimal value") - ); - - // Comparators - d->pass_comparators.setComparator(Term::Contains); - runPass(d->pass_comparators, cursor_position, - i18nc("Equality", "contains|containing $1"), - ki18n("Containing")); - d->pass_comparators.setComparator(Term::Greater); - runPass(d->pass_comparators, cursor_position, - i18nc("Strictly greater", "greater|bigger|more than $1;at least $1;> $1"), - ki18n("Greater than")); - runPass(d->pass_comparators, cursor_position, - i18nc("After in time", "after|since $1"), - ki18n("After"), CompletionProposal::DateTime); - d->pass_comparators.setComparator(Term::Less); - runPass(d->pass_comparators, cursor_position, - i18nc("Strictly smaller", "smaller|less|lesser than $1;at most $1;< $1"), - ki18n("Smaller than")); - runPass(d->pass_comparators, cursor_position, - i18nc("Before in time", "before|until $1"), - ki18n("Before"), CompletionProposal::DateTime); - d->pass_comparators.setComparator(Term::Equal); - runPass(d->pass_comparators, cursor_position, - i18nc("Equality", "equal|equals|= $1;equal to $1"), - ki18n("Equal to")); -} - -void NaturalQueryParser::addCompletionProposal(CompletionProposal *proposal) const -{ - d->proposals.append(proposal); -} - -QStringList NaturalQueryParser::split(const QString &query, bool is_user_query, QList *positions) const -{ - QStringList parts; - QString part; - int size = query.size(); - bool between_quotes = false; - bool split_at_every_char = !localeWordsSeparatedBySpaces(); - - for (int i=0; iseparators.contains(c)))) { - // If there is a cluster of several spaces in the input, part may be empty - if (part.size() > 0) { - parts.append(part); - part.clear(); - } - - // Add a separator, if any - if (!c.isSpace()) { - if (positions) { - positions->append(i); - } - - part.append(c); - } - } else if (c == QLatin1Char('"')) { - between_quotes = !between_quotes; - } else { - if (is_user_query && part.length() == 1 && d->separators.contains(part.at(0))) { - // The part contains only a separator, split "-KMail" to "-", "KMail" - parts.append(part); - part.clear(); - } - - if (positions && part.size() == 0) { - // Start of a new part, save its position in the stream - positions->append(i); - } - - part.append(c); - } - } - - if (!part.isEmpty()) { - parts.append(part); - } - - return parts; -} - -QList &NaturalQueryParser::terms() const -{ - return d->terms; -} - -PassProperties &NaturalQueryParser::passProperties() const -{ - return d->pass_properties; -} - -/* - * Term tuning (setting the right properties of comparisons, etc) - */ -Term NaturalQueryParser::Private::intervalComparison(const QString &prop, - const Term &min, - const Term &max) -{ - int start_position = qMin(termStart(min), termStart(max)); - int end_position = qMax(termEnd(min), termEnd(max)); - - Term greater(prop, min.value(), Term::GreaterEqual); - Term smaller(prop, max.value(), Term::LessEqual); - - setTermRange(greater, start_position, end_position); - copyTermRange(smaller, greater); - - Term total = (greater && smaller); - copyTermRange(total, greater); - - return total; -} - -Term NaturalQueryParser::Private::dateTimeComparison(const QString &prop, - const Term &term) -{ - const KCalendarSystem *cal = KLocale::global()->calendar(); - QDateTime start_date_time = term.value().toDateTime(); - - QDate start_date(start_date_time.date()); - QTime start_time(start_date_time.time()); - QDate end_date(start_date); - PassDatePeriods::Period last_defined_period = (PassDatePeriods::Period)(start_time.msec()); - - switch (last_defined_period) { - case PassDatePeriods::Year: - end_date = cal->addYears(start_date, 1); - break; - case PassDatePeriods::Month: - end_date = cal->addMonths(start_date, 1); - break; - case PassDatePeriods::Week: - end_date = cal->addDays(start_date, cal->daysInWeek(end_date)); - break; - case PassDatePeriods::DayOfWeek: - case PassDatePeriods::Day: - end_date = cal->addDays(start_date, 1); - break; - default: - break; - } - - QDateTime datetime(end_date, start_time); - - switch (last_defined_period) { - case PassDatePeriods::Hour: - datetime = datetime.addSecs(60 * 60); - break; - case PassDatePeriods::Minute: - datetime = datetime.addSecs(60); - break; - case PassDatePeriods::Second: - datetime = datetime.addSecs(1); - break; - default: - break; - } - - Term end_term(QString(), datetime, Term::Equal); - copyTermRange(end_term, term); - - return intervalComparison( - prop, - term, - end_term - ); -} - -Term NaturalQueryParser::Private::tuneTerm(Term term, Query &query) -{ - // Recurse in the subterms - QList subterms; - - Q_FOREACH (const Term &subterm, term.subTerms()) { - subterms.append(tuneTerm(subterm, query)); - - const Term &last_term = subterms.last(); - - if (last_term.property().isEmpty() && last_term.subTerms().isEmpty()) { - // Special properties have been lowered to Query attributes, and - // literal terms (having an empty property) are now in Query::searchString. - // All these terms can therefore be discarded. Note that AND and OR - // terms also have an empty property but have to be kept - subterms.removeLast(); - } - } - - term.setSubTerms(subterms); - - // Special property giving a resource type hint - if (query.types().isEmpty() && term.property() == QLatin1String("_k_typehint")) { - query.setType(term.value().toString()); - - term = Term(); - } - - // Put string literal terms into Query::searchString, and give other literal - // terms the property they deserve. - if (term.property().isNull()) { - QVariant value = term.value(); - - switch (value.type()) - { - case QVariant::String: - query.setSearchString(query.searchString() + value.toString() + QLatin1Char(' ')); - - // The term is not needed anymore - term = Term(); - break; - - case QVariant::Int: - case QVariant::LongLong: - term.setProperty(QLatin1String("size")); - break; - - case QVariant::DateTime: - term.setProperty(QLatin1String("_k_datecreated")); - break; - - default: - break; - } - } - - // Change equality comparisons to interval comparisons - if (term.comparator() == Term::Equal) { - QVariant value = term.value(); - - switch (value.type()) - { - case QVariant::Int: - case QVariant::LongLong: - { - // Compare with the value +- 20% - long long int v = value.toLongLong(); - Term min(QString(), v * 80LL / 100LL, Term::Equal); - Term max(QString(), v * 120LL / 100LL, Term::Equal); - - copyTermRange(min, term); - copyTermRange(max, term); - - term = intervalComparison( - term.property(), - min, - max - ); - break; - } - - case QVariant::DateTime: - { - // The width of the interval is encoded into the millisecond part - // of the date-time -#if 0 - // FIXME: This section has been removed in order to keep date-time simples, - // so that they can be sent to Query::setDateFilter. - term = dateTimeComparison( - term.property(), - term - ); -#endif - break; - } - - default: - break; - } - } - - // Currently, date-time comparisons in Baloo can only be performed using Query - // No backend supports explicit date-time comparisons (using equality, greater - // than, etc). - if (term.value().type() == QVariant::DateTime) - { - if (query.yearFilter() == -1) { - QDateTime datetime = term.value().toDateTime(); - PassDatePeriods::Period period = (PassDatePeriods::Period)(datetime.time().msec()); - - switch (period) { - case PassDatePeriods::Year: - query.setDateFilter( - datetime.date().year() - ); - break; - case PassDatePeriods::Month: - query.setDateFilter( - datetime.date().year(), - datetime.date().month() - ); - break; - case PassDatePeriods::Week: - case PassDatePeriods::DayOfWeek: - case PassDatePeriods::Day: - query.setDateFilter( - datetime.date().year(), - datetime.date().month(), - datetime.date().day() - ); - break; - default: - break; - } - } - - // Kill the term as backends do not understand it - term = Term(); - } - - // The term is now okay - return term; -} - -/* - * Datetime-folding - */ -void NaturalQueryParser::Private::handleDateTimeComparison(DateTimeSpec &spec, const Term &term) -{ - QString property = term.property(); // Name like _k_date_week_offset|value - QString type = property.section(QLatin1Char('_'), 3, 3); - QString flag = property.section(QLatin1Char('_'), 4, 4); - long long value = term.value().toLongLong(); - - // Populate the field corresponding to the property being compared to - Field &field = spec.fields[pass_dateperiods.periodFromName(type)]; - - field.value = value; - field.flags = - (flag == QLatin1String("offset") ? Field::Relative : Field::Absolute); -} - -static int fieldIsRelative(const Field &field, int if_yes, int if_no) -{ - return (field.flags == Field::Relative ? if_yes : if_no); -} - -static int fieldValue(const Field &field, bool in_defined_period, int now_value, int null_value) -{ - switch (field.flags) { - case Field::Unset: - return (in_defined_period ? now_value : null_value); - case Field::Absolute: - return field.value; - case Field::Relative: - return now_value; - } - - return 0; -} - -static Term buildDateTimeLiteral(const DateTimeSpec &spec) -{ - const KCalendarSystem *calendar = KLocale::global()->calendar(); - QDate cdate = QDate::currentDate(); - QTime ctime = QTime::currentTime(); - - const Field &year = spec.fields[PassDatePeriods::Year]; - const Field &month = spec.fields[PassDatePeriods::Month]; - const Field &week = spec.fields[PassDatePeriods::Week]; - const Field &dayofweek = spec.fields[PassDatePeriods::DayOfWeek]; - const Field &day = spec.fields[PassDatePeriods::Day]; - const Field &hour = spec.fields[PassDatePeriods::Hour]; - const Field &minute = spec.fields[PassDatePeriods::Minute]; - const Field &second = spec.fields[PassDatePeriods::Second]; - - // Last defined period - PassDatePeriods::Period last_defined_date = PassDatePeriods::Day; // If no date is given, use the current date-time - PassDatePeriods::Period last_defined_time = PassDatePeriods::Year; // If no time is given, use 00:00:00 - - if (day.flags != Field::Unset) { - last_defined_date = PassDatePeriods::Day; - } else if (dayofweek.flags != Field::Unset) { - last_defined_date = PassDatePeriods::DayOfWeek; - } else if (week.flags != Field::Unset) { - last_defined_date = PassDatePeriods::Week; - } else if (month.flags != Field::Unset) { - last_defined_date = PassDatePeriods::Month; - } else if (year.flags != Field::Unset) { - last_defined_date = PassDatePeriods::Year; - } - - if (second.flags != Field::Unset) { - last_defined_time = PassDatePeriods::Second; - } else if (minute.flags != Field::Unset) { - last_defined_time = PassDatePeriods::Minute; - } else if (hour.flags != Field::Unset) { - last_defined_time = PassDatePeriods::Hour; - } - - // Absolute year, month, day of month - QDate date; - - if (month.flags != Field::Unset) - { - // Month set, day of month - calendar->setDate( - date, - fieldValue(year, last_defined_date >= PassDatePeriods::Year, calendar->year(cdate), 1), - fieldValue(month, last_defined_date >= PassDatePeriods::Month, calendar->month(cdate), 1), - fieldValue(day, last_defined_date >= PassDatePeriods::Day, calendar->day(cdate), 1) - ); - } else { - calendar->setDate( - date, - fieldValue(year, last_defined_date >= PassDatePeriods::Year, calendar->year(cdate), 1), - fieldValue(day, last_defined_date >= PassDatePeriods::Week, calendar->dayOfYear(cdate), 1) - ); - } - - // Week (absolute or relative, it is easy as the date is currently at the beginning - // of a year or a month) - if (week.flags == Field::Absolute) { - date = calendar->addDays(date, (week.value - 1) * calendar->daysInWeek(date)); - } else if (week.flags == Field::Relative) { - date = calendar->addDays(date, week.value * calendar->daysInWeek(date)); - } - - // Day of week - int isoyear; - int isoweek = calendar->week(date, KLocale::IsoWeekNumber, &isoyear); - int isoday = calendar->dayOfWeek(date); - - calendar->setDateIsoWeek( - date, - isoyear, - isoweek, - fieldValue(dayofweek, last_defined_date >= PassDatePeriods::DayOfWeek, isoday, 1) - ); - - // Relative year, month, day of month - if (year.flags == Field::Relative) { - date = calendar->addYears(date, year.value); - } - if (month.flags == Field::Relative) { - date = calendar->addMonths(date, month.value); - } - if (day.flags == Field::Relative) { - date = calendar->addDays(date, day.value); - } - - // Absolute time - QTime time = QTime( - fieldValue(hour, last_defined_time >= PassDatePeriods::Hour, ctime.hour(), 0), - fieldValue(minute, last_defined_time >= PassDatePeriods::Minute, ctime.minute(), 0), - fieldValue(second, last_defined_time >= PassDatePeriods::Second, ctime.second(), 0) - ); - - // Relative time - QDateTime rs(date, time); - - rs = rs.addSecs( - fieldIsRelative(hour, hour.value * 60 * 60, 0) + - fieldIsRelative(minute, minute.value * 60, 0) + - fieldIsRelative(second, second.value, 0) - ); - - // Store the last defined period in the millisecond part of the date-time. - // This way, equality comparisons with a date-time can be changed to comparisons - // against an interval whose size is defined by the last defined period. - rs = rs.addMSecs( - qMax(last_defined_date, last_defined_time) - ); - - return Term(QString(), rs, Term::Equal); -} - -void NaturalQueryParser::Private::foldDateTimes() -{ - QList new_terms; - - DateTimeSpec spec; - bool spec_contains_interesting_data = false; - int start_position = INT_MAX; - int end_position = 0; - - spec.reset(); - - Q_FOREACH(const Term &term, terms) { - bool end_of_cluster = true; - - if (term.property().startsWith(QLatin1String("_k_date_"))) { - // A date-time fragment that can be assembled - handleDateTimeComparison(spec, term); - - spec_contains_interesting_data = true; - end_of_cluster = false; - - start_position = qMin(start_position, termStart(term)); - end_position = qMax(end_position, termEnd(term)); - } else if (spec_contains_interesting_data) { - // A small string literal, like "a", "on", etc. These terms can be - // ignored and removed from date-times. - QString value = stringValueIfLiteral(term); - - if (value.length() == 2 || (value.length() == 1 && !separators.contains(value.at(0)))) { - end_of_cluster = false; - } - } - - if (end_of_cluster) { - if (spec_contains_interesting_data) { - // End a date-time spec build its corresponding QDateTime - new_terms.append(buildDateTimeLiteral(spec)); - - setTermRange(new_terms.last(), start_position, end_position); - - spec.reset(); - spec_contains_interesting_data = false; - start_position = INT_MAX; - end_position = 0; - } - - new_terms.append(term); // Preserve non-datetime terms - } - } - - if (spec_contains_interesting_data) { - // Query ending with a date-time, don't forget to build it - new_terms.append(buildDateTimeLiteral(spec)); - - setTermRange(new_terms.last(), start_position, end_position); - } - - terms.swap(new_terms); -} diff --git a/src/naturalqueryparser/naturalqueryparser_p.h b/src/naturalqueryparser/naturalqueryparser_p.h deleted file mode 100644 --- a/src/naturalqueryparser/naturalqueryparser_p.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __BALOO_NATURALQUERYPARSER_P_H__ -#define __BALOO_NATURALQUERYPARSER_P_H__ - -#include "naturalqueryparser.h" -#include "patternmatcher.h" - -namespace Baloo -{ - -template -void NaturalQueryParser::runPass(const T &pass, - int cursor_position, - const QString &pattern, - const KLocalizedString &description, - CompletionProposal::Type type) const -{ - // Split the pattern at ";" characters, as a locale can have more than one - // pattern that can be used for a given rule - QStringList rules = pattern.split(QLatin1Char(';')); - - Q_FOREACH(const QString &rule, rules) { - // Split the rule into parts that have to be matched - QStringList parts = split(rule, false); - PatternMatcher matcher(this, terms(), cursor_position, parts, type, description); - - matcher.runPass(pass); - } -} - -} - -#endif diff --git a/src/naturalqueryparser/pass_comparators.h b/src/naturalqueryparser/pass_comparators.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_comparators.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_COMPARATORS_H__ -#define __PASS_COMPARATORS_H__ - -#include - -#include - -class PassComparators -{ - public: - PassComparators(); - - void setComparator(Baloo::Term::Comparator comparator); - - QList run(const QList &match) const; - - private: - Baloo::Term::Comparator comparator; -}; - -#endif diff --git a/src/naturalqueryparser/pass_comparators.cpp b/src/naturalqueryparser/pass_comparators.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_comparators.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_comparators.h" - -PassComparators::PassComparators() -: comparator(Baloo::Term::Equal) -{ -} - -void PassComparators::setComparator(Baloo::Term::Comparator comparator) -{ - this->comparator = comparator; -} - -QList PassComparators::run(const QList &match) const -{ - Baloo::Term term(match.at(0)); - - // Set the comparator of the term and ignore the property and the value, that - // will be (or are already) filled by other passes - term.setComparator(comparator); - - return QList() << term; -} diff --git a/src/naturalqueryparser/pass_dateperiods.h b/src/naturalqueryparser/pass_dateperiods.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_dateperiods.h +++ /dev/null @@ -1,74 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_DATEPERIODS_H__ -#define __PASS_DATEPERIODS_H__ - -#include -#include -#include -#include - -namespace Baloo { class Term; } - -class PassDatePeriods -{ - public: - enum Period { - Year = 0, - Month, - Week, - DayOfWeek, - Day, - Hour, - Minute, - Second, - VariablePeriod, - MaxPeriod = VariablePeriod - }; - - enum ValueType { - Value, - Offset, - InvertedOffset - }; - - public: - PassDatePeriods(); - - void setKind(Period period, ValueType value_type, int value = 0); - - QList run(const QList &match) const; - - Period periodFromName(const QString &name) const; - static QString nameOfPeriod(Period period); - static QString propertyName(Period period, bool offset); - - private: - void registerPeriod(Period period, const QString &names); - - private: - QHash periods; - - Period period; - ValueType value_type; - int value; -}; - -#endif diff --git a/src/naturalqueryparser/pass_dateperiods.cpp b/src/naturalqueryparser/pass_dateperiods.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_dateperiods.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_dateperiods.h" -#include "utils.h" - -#include - -#include - -PassDatePeriods::PassDatePeriods() -: period(Year), - value_type(Value), - value(0) -{ - registerPeriod(Year, - i18nc("Space-separated list of words representing a year", "year years")); - registerPeriod(Month, - i18nc("Space-separated list of words representing a month", "month months")); - registerPeriod(Week, - i18nc("Space-separated list of words representing a week", "week weeks")); - registerPeriod(Day, - i18nc("Space-separated list of words representing a day", "day days")); - registerPeriod(Hour, - i18nc("Space-separated list of words representing an hour", "hour hours")); - registerPeriod(Minute, - i18nc("Space-separated list of words representing a minute", "minute minutes")); - registerPeriod(Second, - i18nc("Space-separated list of words representing a second", "second seconds")); - - periods.insert(nameOfPeriod(DayOfWeek), DayOfWeek); -} - -void PassDatePeriods::registerPeriod(Period period, const QString &names) -{ - Q_FOREACH(const QString &name, names.split(QLatin1Char(' '))) { - periods.insert(name, period); - } - - // Also insert the plain English name, used to get the period corresponding - // to a name extracted from an URL - periods.insert(nameOfPeriod(period), period); -} - -void PassDatePeriods::setKind(PassDatePeriods::Period period, PassDatePeriods::ValueType value_type, int value) -{ - this->period = period; - this->value_type = value_type; - this->value = value; -} - -QString PassDatePeriods::nameOfPeriod(Period period) -{ - static const char *const period_names[] = { - "year", "month", "week", "dayofweek", "day", "hour", "minute", "second", "" - }; - - return QLatin1String(period_names[(int)period]); -} - -PassDatePeriods::Period PassDatePeriods::periodFromName(const QString &name) const -{ - return periods.value(name); -} - -QString PassDatePeriods::propertyName(Period period, bool offset) -{ - return QString::fromLatin1("_k_date_%1_%2") - .arg(nameOfPeriod(period)) - .arg(QLatin1String(offset ? "offset" : "value")); -} - -QList PassDatePeriods::run(const QList &match) const -{ - int value_match_index = 0; - - Period p = period; - long long v = value; - - if (p == VariablePeriod && !match.isEmpty()) { - // Parse the period from match.at(0) - QString period_name = stringValueIfLiteral(match.at(0)); - - if (period_name.isNull() || !periods.contains(period_name)) { - return QList(); - } - - p = periodFromName(period_name); - value_match_index = 1; - } - - if (v == 0 && value_match_index < match.count()) { - // Parse the value either from match.at(0) (there was no period) or - // match.at(1) - const Baloo::Term &period_value = match.at(value_match_index); - - if (period_value.value().type() != QVariant::LongLong) { - return QList(); - } - - v = period_value.value().toLongLong(); - } - - // Create a comparison on the right "property", that will be used in a later - // pass to build a real date-time object - return QList() << Baloo::Term( - propertyName(p, value_type != Value), - value_type == InvertedOffset ? -v : v, - Baloo::Term::Equal - ); -} diff --git a/src/naturalqueryparser/pass_datevalues.h b/src/naturalqueryparser/pass_datevalues.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_datevalues.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_DATEVALUES_H__ -#define __PASS_DATEVALUES_H__ - -#include - -namespace Baloo { class Term; } - -class PassDateValues -{ - public: - PassDateValues(); - - void setPm(bool pm); - - QList run(const QList &match) const; - - private: - bool pm; -}; - -#endif diff --git a/src/naturalqueryparser/pass_datevalues.cpp b/src/naturalqueryparser/pass_datevalues.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_datevalues.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_datevalues.h" -#include "pass_dateperiods.h" -#include "utils.h" - -#include - -PassDateValues::PassDateValues() -: pm(false) -{ -} - -void PassDateValues::setPm(bool pm) -{ - this->pm = pm; -} - -QList PassDateValues::run(const QList &match) const -{ - QList rs; - bool valid_input = true; - bool progress = false; - - static const PassDatePeriods::Period periods[7] = { - PassDatePeriods::Year, PassDatePeriods::Month, PassDatePeriods::Day, - PassDatePeriods::DayOfWeek, PassDatePeriods::Hour, PassDatePeriods::Minute, - PassDatePeriods::Second - }; - // Conservative minimum values (not every calendar already reached year 2000+) - static const int min_values[7] = { - 0 /* Y */, 1 /* M */, 1 /* D */, 1 /* DW */, 0 /* H */, 0 /* M */, 0 /* S */ - }; - // Conservative maximum values (some calendars may have months of 100+ days) - static const int max_values[7] = { - 1<<30 /* Y */, 60 /* M */, 500 /* D */, 7 /* DW */, 24 /* H */, 60 /* M */, 60 /* S */ - }; - - // See if a match sets a value for any period - for (int i=0; i<7; ++i) { - PassDatePeriods::Period period = periods[i]; - - if (i < match.count() && match.at(i).value().isValid()) { - const Baloo::Term &term = match.at(i); - bool value_is_integer; - long long value = term.value().toLongLong(&value_is_integer); - - if (term.property().startsWith(QLatin1String("_k_date"))) { - // The term is already a date part, no need to change it - rs.append(term); - continue; - } - - if (!term.property().isNull()) { - // This term has already a property (and is therefore a comparison) - valid_input = false; - break; - } - - if (!value_is_integer) { - // Something that is neither a date part nor a valid integer - valid_input = false; - break; - } - - if (value < min_values[i] || value > max_values[i]) { - // Integer too big or too small to be a valid date part - valid_input = false; - break; - } - - if (period == PassDatePeriods::Hour && pm) { - value += 12; - } - - // Build a comparison of the right type - Baloo::Term comparison( - PassDatePeriods::propertyName(period, false), - value, - Baloo::Term::Equal - ); - - copyTermRange(comparison, term); - - progress = true; - rs.append(comparison); - } - } - - if (!valid_input || !progress) { - rs.clear(); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_decimalvalues.h b/src/naturalqueryparser/pass_decimalvalues.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_decimalvalues.h +++ /dev/null @@ -1,33 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_DECIMALVALUES_H__ -#define __PASS_DECIMALVALUES_H__ - -#include - -namespace Baloo { class Term; } - -class PassDecimalValues -{ - public: - QList run(const QList &match) const; -}; - -#endif diff --git a/src/naturalqueryparser/pass_decimalvalues.cpp b/src/naturalqueryparser/pass_decimalvalues.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_decimalvalues.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_decimalvalues.h" -#include "utils.h" - -#include - -static const double scales[] = { - 1.0, - 0.1, - 0.01, - 0.001, - 0.0001, - 0.00001, - 0.000001, - 0.0000001, - 0.00000001, - 0.000000001, - 0.0000000001, - 0.00000000001, - 0.000000000001 -}; - -QList PassDecimalValues::run(const QList &match) const -{ - QList rs; - bool has_integer_part; - bool has_decimal_part; - long long integer_part = longValueIfLiteral(match.at(0), &has_integer_part); - long long decimal_part = longValueIfLiteral(match.at(1), &has_decimal_part); - int decimal_length = termEnd(match.at(1)) - termStart(match.at(1)) + 1; - - if (has_integer_part && - has_decimal_part && - decimal_length <= 12) { - - double scale = scales[decimal_length]; - - rs.append(Baloo::Term( - QString(), - double(integer_part) + (double(decimal_part) * scale), - Baloo::Term::Equal - )); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_filenames.h b/src/naturalqueryparser/pass_filenames.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_filenames.h +++ /dev/null @@ -1,33 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_FILENAMES_H__ -#define __PASS_FILENAMES_H__ - -#include - -namespace Baloo { class Term; } - -class PassFileNames -{ - public: - QList run(const QList &match) const; -}; - -#endif diff --git a/src/naturalqueryparser/pass_filenames.cpp b/src/naturalqueryparser/pass_filenames.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_filenames.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_filenames.h" -#include "utils.h" - -#include - -#include - -QList PassFileNames::run(const QList &match) const -{ - QList rs; - const QString value = stringValueIfLiteral(match.at(0)); - - if (value.contains(QLatin1Char('.'))) { - if (value.contains(QLatin1Char('*')) || value.contains(QLatin1Char('?'))) { - // Filename globbing (original code here from Vishesh Handa) - QString regex = QRegExp::escape(value); - - regex.replace(QLatin1String("\\*"), QLatin1String(".*")); - regex.replace(QLatin1String("\\?"), QLatin1String(".")); - regex.replace(QLatin1String("\\"), QLatin1String("\\\\")); - regex.prepend(QLatin1Char('^')); - regex.append(QLatin1Char('$')); - - rs.append(Baloo::Term( - QLatin1String("filename"), - QRegExp(regex), // NOTE: QRegExp::toString gives the literal value entered by the user, but some backends may want to use the actual QRegExp object - Baloo::Term::Contains - )); - } else { - rs.append(Baloo::Term( - QLatin1String("filename"), - value, - Baloo::Term::Contains - )); - } - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_filesize.h b/src/naturalqueryparser/pass_filesize.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_filesize.h +++ /dev/null @@ -1,43 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_FILESIZE_H__ -#define __PASS_FILESIZE_H__ - -#include -#include -#include - -namespace Baloo { class Term; } - -class PassFileSize -{ - public: - PassFileSize(); - - QList run(const QList &match) const; - - private: - void registerUnits(long long int multiplier, const QString &units); - - private: - QHash multipliers; -}; - -#endif diff --git a/src/naturalqueryparser/pass_filesize.cpp b/src/naturalqueryparser/pass_filesize.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_filesize.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_filesize.h" -#include "utils.h" - -#include - -#include - -PassFileSize::PassFileSize() -{ - // File size units - registerUnits(1000LL, i18nc("Lower-case units corresponding to a kilobyte", "kb kilobyte kilobytes")); - registerUnits(1000000LL, i18nc("Lower-case units corresponding to a megabyte", "mb megabyte megabytes")); - registerUnits(1000000000LL, i18nc("Lower-case units corresponding to a gigabyte", "gb gigabyte gigabytes")); - registerUnits(1000000000000LL, i18nc("Lower-case units corresponding to a terabyte", "tb terabyte terabytes")); - - registerUnits(1LL << 10, i18nc("Lower-case units corresponding to a kibibyte", "kib k kibibyte kibibytes")); - registerUnits(1LL << 20, i18nc("Lower-case units corresponding to a mebibyte", "mib m mebibyte mebibytes")); - registerUnits(1LL << 30, i18nc("Lower-case units corresponding to a gibibyte", "gib g gibibyte gibibytes")); - registerUnits(1LL << 40, i18nc("Lower-case units corresponding to a tebibyte", "tib t tebibyte tebibytes")); -} - -void PassFileSize::registerUnits(long long int multiplier, const QString &units) -{ - Q_FOREACH(const QString &unit, units.split(QLatin1Char(' '))) { - multipliers.insert(unit, multiplier); - } -} - -QList PassFileSize::run(const QList &match) const -{ - QList rs; - - // Unit - QString unit = stringValueIfLiteral(match.at(1)).toLower(); - - if (multipliers.contains(unit)) { - long long int multiplier = multipliers.value(unit); - QVariant value = match.at(0).value(); - - if (!match.at(0).property().isNull()) { - return rs; - } else if (value.type() == QVariant::Double) { - value = QVariant(value.toDouble() * double(multiplier)); - } else if (value.type() == QVariant::LongLong) { - value = QVariant(value.toLongLong() * multiplier); - } else { - // String or anything that is not a number - return rs; - } - - rs.append(Baloo::Term( - QLatin1String("size"), - value, - Baloo::Term::Equal - )); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_numbers.h b/src/naturalqueryparser/pass_numbers.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_numbers.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_NUMBERS_H__ -#define __PASS_NUMBERS_H__ - -#include -#include - -namespace Baloo { class Term; } - -class PassNumbers -{ - public: - PassNumbers(); - - QList run(const QList &match) const; - - private: - void registerNames(long long int number, const QString &names); - - private: - QHash number_names; -}; - -#endif diff --git a/src/naturalqueryparser/pass_numbers.cpp b/src/naturalqueryparser/pass_numbers.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_numbers.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_numbers.h" -#include "utils.h" - -#include - -#include - -PassNumbers::PassNumbers() -{ - registerNames(0, i18nc("Space-separated list of words meaning 0", "zero nought null")); - registerNames(1, i18nc("Space-separated list of words meaning 1", "one a first")); - registerNames(2, i18nc("Space-separated list of words meaning 2", "two second")); - registerNames(3, i18nc("Space-separated list of words meaning 3", "three third")); - registerNames(4, i18nc("Space-separated list of words meaning 4", "four fourth")); - registerNames(5, i18nc("Space-separated list of words meaning 5", "five fifth")); - registerNames(6, i18nc("Space-separated list of words meaning 6", "six sixth")); - registerNames(7, i18nc("Space-separated list of words meaning 7", "seven seventh")); - registerNames(8, i18nc("Space-separated list of words meaning 8", "eight eighth")); - registerNames(9, i18nc("Space-separated list of words meaning 9", "nine ninth")); - registerNames(10, i18nc("Space-separated list of words meaning 10", "ten tenth")); -} - -void PassNumbers::registerNames(long long int number, const QString &names) -{ - Q_FOREACH(const QString &name, names.split(QLatin1Char(' '))) { - number_names.insert(name, number); - } -} - -QList PassNumbers::run(const QList &match) const -{ - QList rs; - - // Convert a string to a number - const QString value = stringValueIfLiteral(match.at(0)); - - if (number_names.contains(value)) { - // Named number - rs.append(Baloo::Term( - QString(), - number_names.value(value), - Baloo::Term::Equal - )); - } else { - // Integer - bool ok; - long long int as_integer = value.toLongLong(&ok); - - if (ok) { - rs.append(Baloo::Term( - QString(), - as_integer, - Baloo::Term::Equal - )); - } - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_periodnames.h b/src/naturalqueryparser/pass_periodnames.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_periodnames.h +++ /dev/null @@ -1,43 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_PERIODNAMES_H__ -#define __PASS_PERIODNAMES_H__ - -#include -#include -#include - -namespace Baloo { class Term; } - -class PassPeriodNames -{ - public: - PassPeriodNames(); - - QList run(const QList &match) const; - - private: - bool insertName(QHash &hash, int value, const QString &shortName, const QString &longName); - - QHash day_names; - QHash month_names; -}; - -#endif diff --git a/src/naturalqueryparser/pass_periodnames.cpp b/src/naturalqueryparser/pass_periodnames.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_periodnames.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_periodnames.h" -#include "pass_dateperiods.h" -#include "utils.h" - -#include - -#include -#include - -PassPeriodNames::PassPeriodNames() -{ - const KCalendarSystem *cal = KLocale::global()->calendar(); - - // List of all the day names (try to get as many days as the calendar can provide) - for (int day=1; - insertName(day_names, - day, - cal->weekDayName(day, KCalendarSystem::ShortDayName), - cal->weekDayName(day, KCalendarSystem::LongDayName)); - ++day) { - } - - // List of all the month names (NOTE: Using the current year, and a previous - // year that is a leap year (or not a leap year if the current year is one)) - int years[2]; - - years[0] = cal->year(QDate::currentDate()); - years[1] = years[0]; - - while (cal->isLeapYear(years[0]) == cal->isLeapYear(years[1])) { - --years[1]; - } - - for (int year=0; year<2; ++year) { - for (int month=1; - insertName(month_names, - month, - cal->monthName(month, years[year], KCalendarSystem::ShortName), - cal->monthName(month, years[year], KCalendarSystem::LongName)); - ++month) { - } - } -} - -bool PassPeriodNames::insertName(QHash &hash, int value, const QString &shortName, const QString &longName) -{ - if (shortName.isEmpty() || longName.isEmpty()) { - return false; - } - - hash.insert(shortName.toLower(), value); - hash.insert(longName.toLower(), value); - - return true; -} - -QList PassPeriodNames::run(const QList &match) const -{ - QList rs; - QString name = stringValueIfLiteral(match.at(0)).toLower(); - - PassDatePeriods::Period period = PassDatePeriods::VariablePeriod; - int value; - - if (day_names.contains(name)) { - period = PassDatePeriods::DayOfWeek; - value = day_names.value(name); - } else if (month_names.contains(name)) { - period = PassDatePeriods::Month; - value = month_names.value(name); - } - - if (period != PassDatePeriods::VariablePeriod) { - rs.append(Baloo::Term( - PassDatePeriods::propertyName(period, false), - QVariant((long long)value), - Baloo::Term::Equal - )); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_properties.h b/src/naturalqueryparser/pass_properties.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_properties.h +++ /dev/null @@ -1,54 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_PROPERTIES_H__ -#define __PASS_PROPERTIES_H__ - -#include - -#include - -class PassProperties -{ - public: - enum Types { - Integer, - IntegerOrDouble, - String, - DateTime, - Tag, - Contact, - EmailAddress - }; - - PassProperties(); - - void setProperty(const QString &property, Types range); - - QList run(const QList &match) const; - - private: - QVariant convertToRange(const QVariant &value) const; - - private: - QString property; - Types range; -}; - -#endif diff --git a/src/naturalqueryparser/pass_properties.cpp b/src/naturalqueryparser/pass_properties.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_properties.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_properties.h" -#include "utils.h" - -PassProperties::PassProperties() -{ -} - -void PassProperties::setProperty(const QString &property, Types range) -{ - this->property = property; - this->range = range; -} - -QVariant PassProperties::convertToRange(const QVariant &value) const -{ - switch (range) { - case Integer: - if (value.type() == QVariant::LongLong) { - return value; - } - break; - - case IntegerOrDouble: - if (value.type() == QVariant::LongLong || value.type() == QVariant::Double) { - return value; - } - break; - - case String: - if (value.type() == QVariant::String) { - return value; - } - break; - - case DateTime: - if (value.type() == QVariant::DateTime) { - return value; - } - break; - - case Tag: - case Contact: - case EmailAddress: - if (value.type() == QVariant::String) { - return value; - } - break; - } - - return QVariant(); -} - -QList PassProperties::run(const QList &match) const -{ - QList rs; - Baloo::Term term = match.at(0); - QVariant value = convertToRange(term.value()); - - // If the term could be converted to the range of the desired property, - // then build a comparison - if (value.isValid()) { - term.setValue(value); - term.setProperty(property); - - // Mutate "equals" to "contains" for String ranges - if (term.comparator() == Baloo::Term::Equal && - (range == String || range == Tag)) { - term.setComparator(Baloo::Term::Contains); - } - - rs.append(term); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_propertyinfo.h b/src/naturalqueryparser/pass_propertyinfo.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_propertyinfo.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2014 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_PROPERTYINFO_H__ -#define __PASS_PROPERTYINFO_H__ - -#include - -#include - -class PassPropertyInfo -{ - public: - PassPropertyInfo(); - - QList run(const QList &match) const; - - private: - QSet validPropertyNames; -}; - -#endif diff --git a/src/naturalqueryparser/pass_propertyinfo.cpp b/src/naturalqueryparser/pass_propertyinfo.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_propertyinfo.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2014 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_propertyinfo.h" -#include "utils.h" - -#include - -PassPropertyInfo::PassPropertyInfo() -{ - // Query PropertyInfo for all the valid property names - int lastProperty = KFileMetaData::Property::LastProperty; - - for (int i=0; i PassPropertyInfo::run(const QList &match) const -{ - Q_ASSERT(match.count() == 2); - QList rs; - QString propertyName = stringValueIfLiteral(match.at(0)); - Baloo::Term term = match.at(1); - - // Build a simple property comparison if the property name is something valid - if (!propertyName.isNull() && validPropertyNames.contains(propertyName)) { - term.setProperty(propertyName); - rs.append(term); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_splitunits.h b/src/naturalqueryparser/pass_splitunits.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_splitunits.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_SPLITUNITS_H__ -#define __PASS_SPLITUNITS_H__ - -#include -#include -#include - -namespace Baloo { class Term; } - -class PassSplitUnits -{ - public: - PassSplitUnits(); - - QList run(const QList &match) const; - - private: - QSet known_units; -}; - -#endif diff --git a/src/naturalqueryparser/pass_splitunits.cpp b/src/naturalqueryparser/pass_splitunits.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_splitunits.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_splitunits.h" -#include "utils.h" - -#include - -#include - -PassSplitUnits::PassSplitUnits() -: known_units( - QSet::fromList( - i18nc( - "List of lowercase prefixes or suffix that need to be split from values", - "k m g b kb mb gb tb kib mib gib tib h am pm th rd nd st" - ).split(QLatin1Char(' ')) - ) - ) -{ -} - -QList PassSplitUnits::run(const QList &match) const -{ - QList rs; - Baloo::Term value_term; - Baloo::Term unit_term; - - QString value = stringValueIfLiteral(match.at(0)); - int value_position = termStart(match.at(0)); - - if (value.isNull()) { - return rs; - } - - // Possible prefix - QString prefix; - - for (int i=0; i=0 && value.at(i).isLetter(); --i) { - postfix.prepend(value.at(i).toLower()); - } - - if (postfix.size() < value.size() && known_units.contains(postfix)) { - value.resize(value.size() - postfix.size()); - - unit_term.setValue(postfix); - - setTermRange( - unit_term, - value_position + value.size(), - value_position + value.size() + postfix.size() - 1 - ); - } - - // Value - value_term.setValue(value); - - setTermRange(value_term, value_position, value_position + value.size() - 1); - - if (unit_term.value().isValid()) { - rs.append(value_term); - rs.append(unit_term); - } - - return rs; -} diff --git a/src/naturalqueryparser/pass_subqueries.h b/src/naturalqueryparser/pass_subqueries.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_subqueries.h +++ /dev/null @@ -1,39 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_SUBQUERIES_H__ -#define __PASS_SUBQUERIES_H__ - -#include -#include - -namespace Baloo { class Term; } - -class PassSubqueries -{ - public: - void setProperty(const QString &property); - - QList run(const QList &match) const; - - private: - QString property; -}; - -#endif diff --git a/src/naturalqueryparser/pass_subqueries.cpp b/src/naturalqueryparser/pass_subqueries.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_subqueries.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_subqueries.h" -#include "utils.h" - -#include - -void PassSubqueries::setProperty(const QString &property) -{ - this->property = property; -} - -QList PassSubqueries::run(const QList &match) const -{ - // Fuse the matched terms (... in "related to ... ,") into a subquery - int end_index; - Baloo::Term fused_term = fuseTerms(match, 0, end_index); - - fused_term.setProperty(property); // FIXME: Do backends understand terms having a property and subterms and no value? (for instance "related = AND(term, term, term)") - fused_term.setComparator(Baloo::Term::Equal); - - return QList() << fused_term; -} diff --git a/src/naturalqueryparser/pass_typehints.h b/src/naturalqueryparser/pass_typehints.h deleted file mode 100644 --- a/src/naturalqueryparser/pass_typehints.h +++ /dev/null @@ -1,44 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PASS_TYPEHINTS_H__ -#define __PASS_TYPEHINTS_H__ - -#include -#include -#include -#include - -namespace Baloo { class Term; } - -class PassTypeHints -{ - public: - PassTypeHints(); - - QList run(const QList &match) const; - - private: - void registerHints(const QString &type, const QString &hints); - - private: - QHash type_hints; -}; - -#endif diff --git a/src/naturalqueryparser/pass_typehints.cpp b/src/naturalqueryparser/pass_typehints.cpp deleted file mode 100644 --- a/src/naturalqueryparser/pass_typehints.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "pass_typehints.h" -#include "utils.h" - -#include - -#include - -PassTypeHints::PassTypeHints() -{ - registerHints(QLatin1String("File"), - i18nc("List of words representing a file", "file files")); - registerHints(QLatin1String("Image"), - i18nc("List of words representing an image", "image images picture pictures photo photos")); - registerHints(QLatin1String("Video"), - i18nc("List of words representing a video", "video videos movie movies film films")); - registerHints(QLatin1String("Audio"), - i18nc("List of words representing an audio file", "music musics")); - registerHints(QLatin1String("Document"), - i18nc("List of words representing a document", "document documents")); - registerHints(QLatin1String("Email"), - i18nc("List of words representing an email", "mail mails email emails e-mail e-mails message messages")); - registerHints(QLatin1String("Archive"), - i18nc("List of words representing an archive", "archive archives tarball tarballs zip")); - registerHints(QLatin1String("Folder"), - i18nc("List of words representing a folder", "folder folders directory directories")); - registerHints(QLatin1String("Contact"), - i18nc("List of words representing a contact", "contact contacts person people")); - registerHints(QLatin1String("Note"), - i18nc("List of words representing a note", "note notes")); -} - -void PassTypeHints::registerHints(const QString &type, const QString &hints) -{ - Q_FOREACH(const QString &hint, hints.split(QLatin1Char(' '))) { - type_hints.insert(hint, type); - } -} - -QList PassTypeHints::run(const QList &match) const -{ - QList rs; - const QString value = stringValueIfLiteral(match.at(0)).toLower(); - - if (value.isNull()) { - return rs; - } - - if (type_hints.contains(value)) { - rs.append(Baloo::Term( - QLatin1String("_k_typehint"), - type_hints.value(value), - Baloo::Term::Equal - )); - } - - return rs; -} diff --git a/src/naturalqueryparser/patternmatcher.h b/src/naturalqueryparser/patternmatcher.h deleted file mode 100644 --- a/src/naturalqueryparser/patternmatcher.h +++ /dev/null @@ -1,113 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __PATTERNMATCHER_H__ -#define __PATTERNMATCHER_H__ - -#include "completionproposal.h" -#include "utils.h" - -#include - -#include - -namespace Baloo { class NaturalQueryParser; } - -class PatternMatcher -{ - public: - PatternMatcher(const Baloo::NaturalQueryParser *parser, - QList &terms, - int cursor_position, - const QStringList &pattern, - Baloo::CompletionProposal::Type completion_type, - const KLocalizedString &completion_description); - - template - void runPass(const T &pass) - { - QList matched_terms; - - for (int i=0; i 0) { - // The pattern matched, run the pass on the matching terms - QList replacement = pass.run(matched_terms); - - if (replacement.count() > 0) { - // Replace terms first_match_index..i with replacement - for (int i=0; i=0; --i) { - terms.insert(index, replacement.at(i)); - } - - // If the pass returned only one replacement term, set - // its position. If more terms are returned, the pass - // must handle positions itself - if (replacement.count() == 1) { - setTermRange(terms[index], start_position, end_position); - } - - // Re-explore the terms vector as indexes have changed - index = -1; - } - - // If the pattern contains "$$", terms are appended to the end - // of matched_terms. Remove them now that they are not needed anymore - while (matched_terms.count() > capture_count) { - matched_terms.removeLast(); - } - } - } - } - - private: - int captureCount() const; - int matchPattern(int first_term_index, - QList &matched_terms, - int &start_position, - int &end_position) const; - bool matchTerm(const Baloo::Term &term, const QString &pattern, int &capture_index) const; - void addCompletionProposal(int first_pattern_index_not_matching, - int first_term_index_matching, - int first_term_index_not_matching) const; - - private: - const Baloo::NaturalQueryParser *parser; - QList &terms; - int cursor_position; - QStringList pattern; - Baloo::CompletionProposal::Type completion_type; - KLocalizedString completion_description; - - int capture_count; -}; - -#endif diff --git a/src/naturalqueryparser/patternmatcher.cpp b/src/naturalqueryparser/patternmatcher.cpp deleted file mode 100644 --- a/src/naturalqueryparser/patternmatcher.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "patternmatcher.h" -#include "naturalqueryparser.h" -#include "utils.h" - -#include - -PatternMatcher::PatternMatcher(const Baloo::NaturalQueryParser *parser, - QList &terms, - int cursor_position, - const QStringList &pattern, - Baloo::CompletionProposal::Type completion_type, - const KLocalizedString &completion_description) -: parser(parser), - terms(terms), - cursor_position(cursor_position), - pattern(pattern), - completion_type(completion_type), - completion_description(completion_description), - capture_count(captureCount()) -{ -} - -int PatternMatcher::captureCount() const -{ - int max_capture = 0; - int capture; - - Q_FOREACH(const QString &p, pattern) { - if (p.at(0) == QLatin1Char('$')) { - capture = p.mid(1).toInt(); - - if (capture > max_capture) { - max_capture = capture; - } - } - } - - return max_capture; -} - -int PatternMatcher::matchPattern(int first_term_index, - QList &matched_terms, - int &start_position, - int &end_position) const -{ - Q_ASSERT(first_term_index < terms.count()); - - int pattern_index = 0; - int term_index = first_term_index; - bool has_matched_a_literal = false; - bool match_anything = false; // Match "$$" - bool contains_catchall = false; - - start_position = 1 << 30; - end_position = 0; - - while (pattern_index < pattern.count() && term_index < terms.count()) { - const Baloo::Term &term = terms.at(term_index); - int capture_index = -1; - - // Always update start and end position, they will be simply discarded - // if the pattern ends not matching. - start_position = qMin(start_position, termStart(term)); - end_position = qMax(end_position, termEnd(term)); - - if (pattern.at(pattern_index) == QLatin1String("$$")) { - // Start to match anything - match_anything = true; - contains_catchall = true; - ++pattern_index; - - continue; - } - - bool match = matchTerm(term, pattern.at(pattern_index), capture_index); - - if (match_anything) { - if (!match) { - // The stop pattern is not yet matched, continue to match - // anything - matched_terms.append(term); - } else { - // The terminating pattern is matched, stop to match anything - match_anything = false; - ++pattern_index; - } - } else if (match) { - if (capture_index != -1) { - matched_terms[capture_index] = term; - } else { - has_matched_a_literal = true; // At least one literal has been matched, enable auto-completion - } - - // Try to match the next pattern - ++pattern_index; - } else { - // The pattern does not match, abort - break; - } - - // Match the next term - ++term_index; - } - - // See if the partially matched pattern can be used to provide a completion proposal - if ((has_matched_a_literal || completion_type == Baloo::CompletionProposal::PropertyName) && - term_index - first_term_index > 0) { - addCompletionProposal(pattern_index, first_term_index, term_index); - } - - if (contains_catchall || pattern_index == pattern.count()) { - // Patterns containing "$$" typically end with an optional terminating - // term. Allow them to match even if we reach the end of the term list - // without encountering the terminating term. - return (term_index - first_term_index); - } else { - return 0; - } -} - -bool PatternMatcher::matchTerm(const Baloo::Term &term, const QString &pattern, int &capture_index) const -{ - if (pattern.at(0) == QLatin1Char('$')) { - // Placeholder - capture_index = pattern.mid(1).toInt() - 1; - - return true; - } else { - // Literal value that has to be matched against a regular expression - QString value = stringValueIfLiteral(term); - QStringList allowed_values = pattern.split(QLatin1Char('|')); - - if (value.isNull()) { - return false; - } - - Q_FOREACH(const QString &allowed_value, allowed_values) { - if (QRegExp(allowed_value, Qt::CaseInsensitive, QRegExp::RegExp2).exactMatch(value)) { - return true; - } - } - - return false; - } -} - -void PatternMatcher::addCompletionProposal(int first_pattern_index_not_matching, - int first_term_index_matching, - int first_term_index_not_matching) const -{ - // Don't count terms that are not literal terms. This avoids problems when the - // user types "sent to size > 2M", that is seen here as "sent to ". - if (!terms.at(first_term_index_not_matching - 1).property().isNull()) { - if (--first_term_index_not_matching <= 0) { - return; // Avoid an underflow when the pattern is only "$1" for instance. - } - } - - const Baloo::Term &first_matching = terms.at(first_term_index_matching); - const Baloo::Term &last_matching = terms.at(first_term_index_not_matching - 1); - - // Check that the completion proposal would be valid - if (completion_description.isEmpty()) { - return; - } - - if (cursor_position < termStart(first_matching)) { - return; - } - - if (first_term_index_not_matching < terms.count() && - cursor_position > termStart(terms.at(first_term_index_not_matching))) { - return; - } - - // Replace pattern parts that have matched with their matched terms, and - // replace "a|b|c" with "a". This makes the pattern nicer for the user - int pattern_parts_to_replace = first_term_index_not_matching - first_term_index_matching; - QStringList user_friendly_pattern(pattern); - - for (int i=0; iaddCompletionProposal(new Baloo::CompletionProposal( - user_friendly_pattern, - first_pattern_index_not_matching - 1, - termStart(first_matching), - termEnd(last_matching) - termStart(first_matching) + 1, - completion_type, - completion_description - )); -} diff --git a/src/naturalqueryparser/utils.h b/src/naturalqueryparser/utils.h deleted file mode 100644 --- a/src/naturalqueryparser/utils.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __UTILS_H__ -#define __UTILS_H__ - -#include - -#include -#include - -bool localeWordsSeparatedBySpaces(); - -int termStart(const Baloo::Term &term); -int termEnd(const Baloo::Term &term); -void setTermRange(Baloo::Term &term, int start, int end); - -QString stringValueIfLiteral(const Baloo::Term &term); -long long longValueIfLiteral(const Baloo::Term &term, bool *ok); -void copyTermRange(Baloo::Term &target, const Baloo::Term &source); - -Baloo::Term fuseTerms(const QList &terms, - int first_term_index, - int &end_term_index); - -#endif diff --git a/src/naturalqueryparser/utils.cpp b/src/naturalqueryparser/utils.cpp deleted file mode 100644 --- a/src/naturalqueryparser/utils.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* This file is part of the Baloo query parser - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "utils.h" -#include "pass_dateperiods.h" - -#include - -bool localeWordsSeparatedBySpaces() -{ - return i18nc("Are words of your language separated by spaces (Y/N) ?", "Y") == QLatin1String("Y"); -} - -int termStart(const Baloo::Term &term) -{ - return term.userData(QLatin1String("start_position")).toInt(); -} - -int termEnd(const Baloo::Term &term) -{ - return term.userData(QLatin1String("end_position")).toInt(); -} - -void setTermRange(Baloo::Term &term, int start, int end) -{ - term.setUserData(QLatin1String("start_position"), start); - term.setUserData(QLatin1String("end_position"), end); -} - -QString stringValueIfLiteral(const Baloo::Term &term) -{ - if (!term.property().isNull()) { - return QString(); - } - - if (term.value().type() != QVariant::String) { - return QString(); - } - - return term.value().toString(); -} - -long long int longValueIfLiteral(const Baloo::Term& term, bool *ok) -{ - if (!term.property().isNull()) { - *ok = false; - return 0; - } - - if (term.value().type() != QVariant::LongLong) { - *ok = false; - return 0; - } - - *ok = true; - return term.value().toLongLong(); -} - -void copyTermRange(Baloo::Term &target, const Baloo::Term &source) -{ - setTermRange( - target, - termStart(source), - termEnd(source) - ); -} - -Baloo::Term fuseTerms(const QList &terms, int first_term_index, int &end_term_index) -{ - Baloo::Term fused_term; - bool words_separated_by_spaces = localeWordsSeparatedBySpaces(); - bool build_and = true; - bool build_not = false; - bool first = true; - - QString and_string = i18n("and"); - QString or_string = i18n("or"); - QString not_string = i18n("not"); - - // Fuse terms in nested AND and OR terms. "a AND b OR c" is fused as - // "(a AND b) OR c" - for (end_term_index=first_term_index; end_term_index - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __QUERYEDITOR_H__ -#define __QUERYEDITOR_H__ - -#include "widgets_export.h" -#include "groupedlineedit.h" - -namespace Baloo { - -class CompletionProposal; -class NaturalQueryParser; -class Term; - -class BALOO_WIDGETS_EXPORT QueryBuilder : public GroupedLineEdit -{ -Q_OBJECT - -public: - explicit QueryBuilder(NaturalQueryParser *parser, QWidget *parent = 0); - - /** - * @brief Parse the user query and provide syntax-highlighting and auto-completion - * - * If parsing is disabled, the query builder acts like a simple - * QLineEdit without any fancy coloring. If parsing is enabled, all the - * features are exposed to the user. - * - * By default, parsing is enabled. - */ - void setParsingEnabled(bool enable); - - /** - * @return whether parsing is enabled - */ - bool parsingEnabled() const; - -private: - void handleTerm(const Term &term); - -private Q_SLOTS: - void reparse(); - void proposalSelected(CompletionProposal *proposal, - const QString &value); - -private: - struct Private; - Private *d; -}; - -} - -#endif diff --git a/src/querybuilder.cpp b/src/querybuilder.cpp deleted file mode 100644 --- a/src/querybuilder.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* This file is part of the Baloo widgets collection - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "querybuilder.h" -#include "groupedlineedit.h" -#include "querybuildercompleter_p.h" - -#include "completionproposal.h" -#include "naturalqueryparser.h" - -#include -#include - -using namespace Baloo; - -struct QueryBuilder::Private -{ - NaturalQueryParser *parser; - QueryBuilderCompleter *completer; - - bool parsing_enabled; -}; - -static int termStart(const Baloo::Term &term) -{ - return term.userData(QLatin1String("start_position")).toInt(); -} - -static int termEnd(const Baloo::Term &term) -{ - return term.userData(QLatin1String("end_position")).toInt(); -} - -QueryBuilder::QueryBuilder(NaturalQueryParser *parser, QWidget *parent) -: GroupedLineEdit(parent), - d(new Private) -{ - d->parser = parser; - d->completer = new QueryBuilderCompleter(this); - d->parsing_enabled = true; - - connect(this, &QueryBuilder::textChanged, this, &QueryBuilder::reparse); - connect(d->completer, &QueryBuilderCompleter::proposalSelected, this, &QueryBuilder::proposalSelected); -} - -void QueryBuilder::setParsingEnabled(bool enable) -{ - d->parsing_enabled = enable; -} - -bool QueryBuilder::parsingEnabled() const -{ - return d->parsing_enabled; -} - -void QueryBuilder::handleTerm(const Term &term) -{ - // If the term has subterms (AND or OR), highlight these - if (term.subTerms().count() > 0) { - Q_FOREACH (const Term &subterm, term.subTerms()) { - addBlock(termStart(subterm), termEnd(subterm)); - handleTerm(subterm); - } - } -} - -void QueryBuilder::reparse() -{ - if (!parsingEnabled()) { - d->completer->hide(); - return; - } - - int position = cursorPosition(); - QString t = text(); - - Query query = d->parser->parse(t, NaturalQueryParser::DetectFilenamePattern, position); - Term term(query.term()); - - // Extract the term just before the cursor - QString term_before_cursor; - - for (int i=position-1; i>=0 && !t.at(i).isSpace(); --i) { - term_before_cursor.prepend(t.at(i)); - } - - // Highlight the input field - removeAllBlocks(); - handleTerm(term); - - setCursorPosition(position); - - // Build the list of auto-completions - QList proposals = d->parser->completionProposals(); - - if (proposals.count() > 0) { - d->completer->clear(); - - Q_FOREACH(CompletionProposal *proposal, d->parser->completionProposals()) { - d->completer->addProposal(proposal, term_before_cursor); - } - - d->completer->open(); - } else { - // No completion available - d->completer->hide(); - } -} - -void QueryBuilder::proposalSelected(CompletionProposal *proposal, - const QString &value) -{ - QString t = text(); - - // Term before the cursor (if any) - int term_before_cursor_pos = cursorPosition(); - QString term_before_cursor; - - while (term_before_cursor_pos > 0 && !t.at(term_before_cursor_pos - 1).isSpace()) { - term_before_cursor.prepend(t.at(term_before_cursor_pos - 1)); - --term_before_cursor_pos; - } - - // Build the text that will be used to auto-complete the query - QStringList pattern = proposal->pattern(); - QString replacement; - int first_unmatched_part = proposal->lastMatchedPart() + 1; - bool valueHasBeenUsed = false; - - if (!term_before_cursor.isEmpty()) { - // The last matched part will be replaced by value, so count it - // as unmatched to have it replaced - --first_unmatched_part; - } - - for (int i=first_unmatched_part; i - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "querybuildercompleter_p.h" - -#include "completionproposal.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace Baloo; - -QueryBuilderCompleter::QueryBuilderCompleter(QWidget *parent) -: QListWidget(parent) -{ - // Display the completer in its own non-decorated popup - setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); - setAttribute(Qt::WA_X11NetWmWindowTypeCombo); - setAttribute(Qt::WA_ShowWithoutActivating); - - setFocusPolicy(Qt::NoFocus); - setFocusProxy(parent); - setFrameShape(NoFrame); - setUniformItemSizes(true); - - parent->installEventFilter(this); - - connect(this, &QueryBuilderCompleter::itemActivated, this, &QueryBuilderCompleter::proposalActivated); - - // Load the list of all the valid property names - int lastProperty = KFileMetaData::Property::LastProperty; - - for (int i=0; ipattern(); - bool valueHasBeenUsed = false; - - for (int i=0; i"); - - if (!valueHasBeenUsed && !value.isEmpty()) { - proposal_text += value; - valueHasBeenUsed = true; - } else { - switch (proposal->type()) { - case CompletionProposal::NoType: - proposal_text += i18nc("Pattern placeholder having no specific type", "[something]"); - break; - - case CompletionProposal::DateTime: - proposal_text += i18nc("Pattern placeholder of date-time type", "[date and time]"); - break; - - case CompletionProposal::Tag: - proposal_text += i18nc("Pattern placeholder for a tag name", "[tag name]"); - break; - - case CompletionProposal::Contact: - proposal_text += i18nc("Pattern placeholder for a contact identifier", "[contact]"); - break; - - case CompletionProposal::Email: - proposal_text += i18nc("Pattern placeholder for an e-mail address", "[email address]"); - break; - - case CompletionProposal::PropertyName: - proposal_text += i18nc("Pattern placeholder for a standard property name", "[property]"); - break; - } - } - - proposal_text += QLatin1String(""); - } else if (i <= proposal->lastMatchedPart()) { - proposal_text += QLatin1String("") + part.toHtmlEscaped() + QLatin1String(""); - } else { - proposal_text += part.toHtmlEscaped(); - } - } - - // Widget displaying the proposal - QWidget *widget = new QWidget(this); - QLabel *title_label = new QLabel(proposal->description().toString(), widget); - QLabel *content_label = new QLabel(proposal_text); - QVBoxLayout *vlayout = new QVBoxLayout(widget); - - QFont title_font(title_label->font()); - title_font.setBold(true); - title_label->setFont(title_font); - - title_label->setTextFormat(Qt::PlainText); - content_label->setTextFormat(Qt::RichText); - - vlayout->addWidget(title_label); - vlayout->addWidget(content_label); - - return widget; -} - -QString QueryBuilderCompleter::valueStartingWith(const QStringList &strings, - const QString &prefix) const -{ - QStringList::const_iterator it = qLowerBound(strings, prefix); - - if (it == strings.end() || !(*it).startsWith(prefix)) { - return QString(); - } else { - return QLatin1Char('"') + *it + QLatin1Char('"'); - } -} - -void QueryBuilderCompleter::addProposal(CompletionProposal *proposal, - const QString &prefix) -{ - QString value; - QStringList pattern = proposal->pattern(); - - // If the term the user is entering is a placeholder, pre-fill it - if (!prefix.isEmpty() && - proposal->lastMatchedPart() < pattern.size() && - pattern.at(proposal->lastMatchedPart()).at(0) == QLatin1Char('$')) - { - switch (proposal->type()) { -#if 0 - case CompletionProposal::Contact: - value = valueStartingWith(parser->allContacts(), prefix); - break; - case CompletionProposal::Tag: - value = valueStartingWith(parser->allTags(), prefix); - break; - case CompletionProposal::Email: - value = valueStartingWith(parser->allEmailAddresses(), prefix); - break; -#endif - case CompletionProposal::PropertyName: - value = valueStartingWith(validPropertyNames, prefix); - break; - case CompletionProposal::DateTime: - value = QDate::currentDate().toString(Qt::DefaultLocaleShortDate); - break; - default: - break; - } - } - - // Add a new item to the list - QListWidgetItem *item = new QListWidgetItem(this); - QWidget *widget = widgetForProposal(proposal, value); - - item->setData(Qt::UserRole, QVariant::fromValue(static_cast(proposal))); - item->setData(Qt::UserRole + 1, value); - item->setSizeHint(widget->sizeHint()); - - addItem(item); - setItemWidget(item, widget); - - if (count() == 1 || !value.isEmpty()) { - // Select the first item, or an interesting completion if possible - setCurrentRow(count() - 1); - } -} - -void QueryBuilderCompleter::open() -{ - if (count() == 0) { - return; - } - - QWidget *p = parentWidget(); - QPoint parent_position = p->mapToGlobal(QPoint(0, 0)); - - // Display the popup just below the parent widget - resize(p->width(), count() * item(0)->sizeHint().height()); - move(parent_position.x(), parent_position.y() + p->height()); - - show(); -} - -void QueryBuilderCompleter::proposalActivated(QListWidgetItem *item) -{ - CompletionProposal *proposal = - static_cast( - item->data(Qt::UserRole).value() - ); - - emit proposalSelected(proposal, item->data(Qt::UserRole + 1).toString()); -} - -bool QueryBuilderCompleter::eventFilter(QObject *, QEvent *event) -{ - bool rs = false; - - if (!isVisible()) { - return rs; // Don't block events when the completer is not open - } - - if (event->type() == QEvent::KeyPress) { - QKeyEvent *keypress = static_cast(event); - - switch (keypress->key()) { - case Qt::Key_Up: - if (currentRow() > 0) { - setCurrentRow(currentRow() - 1); - } - break; - - case Qt::Key_Down: - if (currentRow() < count() - 1) { - setCurrentRow(currentRow() + 1); - } - break; - - case Qt::Key_Enter: - case Qt::Key_Tab: - case Qt::Key_Return: - proposalActivated(currentItem()); - rs = true; // In Dolphin, don't trigger a search when Enter is pressed in the auto-completion box - break; - - case Qt::Key_Escape: - hide(); - rs = true; - break; - - default: - break; - } - } else if (event->type() == QEvent::FocusOut) { - hide(); - } - - return rs; -} - diff --git a/src/querybuildercompleter_p.h b/src/querybuildercompleter_p.h deleted file mode 100644 --- a/src/querybuildercompleter_p.h +++ /dev/null @@ -1,65 +0,0 @@ -/* This file is part of the Baloo widgets collection - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 __QUERYBUILDERCOMPLETER_H__ -#define __QUERYBUILDERCOMPLETER_H__ - -#include - -class QListWidgetItem; - -namespace Baloo { - -class CompletionProposal; - -class QueryBuilderCompleter : public QListWidget -{ -Q_OBJECT - -public: - explicit QueryBuilderCompleter(QWidget *parent); - - void addProposal(CompletionProposal *proposal, const QString &prefix); - -public Q_SLOTS: - void open(); - -private Q_SLOTS: - void proposalActivated(QListWidgetItem *item); - -protected: - virtual bool eventFilter(QObject *, QEvent *event); - -Q_SIGNALS: - void proposalSelected(CompletionProposal *proposal, - const QString &value); - -private: - QString valueStartingWith(const QStringList &strings, - const QString &prefix) const; - QWidget *widgetForProposal(CompletionProposal *proposal, - const QString &value); - -private: - QStringList validPropertyNames; -}; - -} - -#endif diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -21,11 +21,3 @@ Qt5::Widgets Qt5::Core ) - -#add_executable(querybuilderapp querybuilderapp.cpp ) -#target_link_libraries(querybuilderapp -# KF5::BalooNaturalQueryParser -# KF5::BalooWidgets -# Qt5::Widgets -# Qt5::Core -#) diff --git a/test/querybuilderapp.cpp b/test/querybuilderapp.cpp deleted file mode 100644 --- a/test/querybuilderapp.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* This file is part of the Nepomuk widgets collection - Copyright (c) 2013 Denis Steckelmacher - - 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.1 as published by the Free Software Foundation, - or any later version. - - 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 "querybuilder.h" - -#include -#include "naturalfilequeryparser.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - Baloo::NaturalFileQueryParser parser; - Baloo::QueryBuilder builder(&parser, 0); - - builder.show(); - - return app.exec(); -}