QGIS API Documentation 3.99.0-Master (e9821da5c6b)
Loading...
Searching...
No Matches
qgslocator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgslocator.cpp
3 --------------
4 begin : May 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
18#include "qgslocator.h"
19
20#include <functional>
21#include <memory>
22
23#include "qgsmessagelog.h"
25
26#include <QString>
27#include <QtConcurrent>
28
29#include "moc_qgslocator.cpp"
30
31using namespace Qt::StringLiterals;
32
33const QgsSettingsEntryBool *QgsLocator::settingsLocatorFilterEnabled = new QgsSettingsEntryBool( u"enabled"_s, sTreeLocatorFilters, true, QObject::tr( "Locator filter enabled" ) );
34
35const QgsSettingsEntryBool *QgsLocator::settingsLocatorFilterDefault = new QgsSettingsEntryBool( u"default"_s, sTreeLocatorFilters, false, QObject::tr( "Locator filter default value" ) );
36
37const QgsSettingsEntryString *QgsLocator::settingsLocatorFilterPrefix = new QgsSettingsEntryString( u"prefix"_s, sTreeLocatorFilters, QString(), QObject::tr( "Locator filter prefix" ) );
38
39const QList<QString> QgsLocator::CORE_FILTERS = QList<QString>() << u"actions"_s
40 << u"processing_alg"_s
41 << u"layertree"_s
42 << u"layouts"_s
43 << u"features"_s
44 << u"allfeatures"_s
45 << u"calculator"_s
46 << u"bookmarks"_s
47 << u"optionpages"_s
48 << u"edit_features"_s
49 << u"goto"_s
50 << u"nominatimgeocoder"_s ;
51
52QgsLocator::QgsLocator( QObject *parent )
53 : QObject( parent )
54{
55 qRegisterMetaType<QgsLocatorResult>( "QgsLocatorResult" );
56}
57
59{
60 cancelRunningQuery();
61 qDeleteAll( mFilters );
62}
63
65{
66 cancelRunningQuery();
67 mFilters.removeAll( filter );
68 delete filter;
69}
70
71QList<QgsLocatorFilter *> QgsLocator::filters( const QString &prefix )
72{
73 if ( !prefix.isEmpty() )
74 {
75 QList<QgsLocatorFilter *> filters = QList<QgsLocatorFilter *>();
76 for ( QgsLocatorFilter *filter : mFilters )
77 {
78 if ( !filter->activePrefix().isEmpty() && filter->activePrefix().compare( prefix, Qt::CaseInsensitive ) == 0 )
79 {
80 filters << filter;
81 }
82 }
83 return filters;
84 }
85 else
86 {
87 return mFilters;
88 }
89}
90
91QMap<QString, QgsLocatorFilter *> QgsLocator::prefixedFilters() const
92{
93 QMap<QString, QgsLocatorFilter *> filters = QMap<QString, QgsLocatorFilter *>();
94 for ( QgsLocatorFilter *filter : mFilters )
95 {
96 if ( !filter->activePrefix().isEmpty() && filter->enabled() )
97 {
98 filters.insert( filter->activePrefix(), filter );
99 }
100 }
101 return filters;
102}
103
105{
106 mFilters.append( filter );
107 filter->setParent( this );
108
109 // restore settings
110 bool enabled = QgsLocator::settingsLocatorFilterEnabled->value( filter->name() );
111 bool byDefault = QgsLocator::settingsLocatorFilterDefault->valueWithDefaultOverride( filter->useWithoutPrefix(), filter->name() );
112 QString prefix = QgsLocator::settingsLocatorFilterPrefix->valueWithDefaultOverride( filter->prefix(), filter->name() );
113 if ( prefix.isEmpty() )
114 {
115 prefix = filter->prefix();
116 }
117
118 if ( !prefix.isEmpty() )
119 {
120 if ( CORE_FILTERS.contains( filter->name() ) )
121 {
122 //inbuilt filter, no prefix check
123 filter->setActivePrefix( prefix );
124 }
125 else if ( prefix.length() >= 3 || prefix != filter->prefix() )
126 {
127 // for plugins either the native prefix is >3 char or it has been customized by user
128 filter->setActivePrefix( prefix );
129 }
130 else
131 {
132 // otherwise set it to empty string (not NULL)
133 filter->setActivePrefix( QString( "" ) );
134 }
135 }
136
137 filter->setEnabled( enabled );
138 filter->setUseWithoutPrefix( byDefault );
139}
140
141void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &c, QgsFeedback *feedback )
142{
143 mAutocompletionList.clear();
144
145 QgsLocatorContext context( c );
146 // ideally this should not be required, as well behaved callers
147 // will NOT fire up a new fetchResults call while an existing one is
148 // operating/waiting to be canceled...
149 cancelRunningQuery();
150
151 // if no feedback object was passed, create one that is owned by this object
152 // to ensure that filters ALWAYS receive a valid feedback
153 if ( !feedback )
154 {
155 mOwnedFeedback = std::make_unique<QgsFeedback>( );
156 feedback = mOwnedFeedback.get();
157 }
158 else
159 {
160 mOwnedFeedback.reset( nullptr );
161 }
162 mFeedback = feedback;
163
164 QList< QgsLocatorFilter * > activeFilters;
165 QString searchString = string;
166 QString prefix = searchString.left( std::max( static_cast<int>( searchString.indexOf( ' ' ) ), 0 ) );
167 if ( !prefix.isEmpty() )
168 {
169 for ( QgsLocatorFilter *filter : std::as_const( mFilters ) )
170 {
171 if ( filter->activePrefix().compare( prefix, Qt::CaseInsensitive ) == 0 && filter->enabled() )
172 {
173 activeFilters << filter;
174 }
175 }
176 context.usingPrefix = !activeFilters.empty();
177 }
178 if ( !activeFilters.isEmpty() )
179 {
180 searchString = searchString.mid( prefix.length() + 1 );
181 }
182 else
183 {
184 for ( QgsLocatorFilter *filter : std::as_const( mFilters ) )
185 {
186 if ( filter->useWithoutPrefix() && filter->enabled() )
187 {
188 activeFilters << filter;
189 }
190 }
191 }
192
193 QList< QgsLocatorFilter *> threadedFilters;
194 for ( QgsLocatorFilter *filter : std::as_const( activeFilters ) )
195 {
196 filter->clearPreviousResults();
197 std::unique_ptr< QgsLocatorFilter > clone( filter->clone() );
198 if ( ! clone )
199 {
200 QgsMessageLog::logMessage( tr( "QgsLocatorFilter '%1' could not provide a valid clone" ).arg( filter->name() ), QString(), Qgis::MessageLevel::Critical );
201 continue;
202 }
203 connect( clone.get(), &QgsLocatorFilter::resultFetched, clone.get(), [this, filter]( QgsLocatorResult result )
204 {
205 result.filter = filter;
206 filterSentResult( result );
207 } );
208 QStringList autoCompleteList = clone->prepare( searchString, context );
209 if ( context.usingPrefix )
210 {
211 for ( int i = 0; i < autoCompleteList.length(); i++ )
212 {
213 autoCompleteList[i].prepend( u"%1 "_s.arg( prefix ) );
214 }
215 }
216 mAutocompletionList.append( autoCompleteList );
217
218 if ( clone->flags() & QgsLocatorFilter::FlagFast )
219 {
220 // filter is fast enough to fetch results on the main thread
221 clone->fetchResults( searchString, context, feedback );
222 }
223 else
224 {
225 threadedFilters.append( clone.release() );
226 }
227 }
228
229 mActiveThreads.clear();
230 for ( QgsLocatorFilter *filter : std::as_const( threadedFilters ) )
231 {
232 QThread *thread = new QThread();
233 mActiveThreads.append( thread );
234 filter->moveToThread( thread );
235 connect( thread, &QThread::started, filter, [filter, searchString, context, feedback]
236 {
237 int delay = filter->fetchResultsDelay();
238 while ( delay > 0 )
239 {
240 if ( feedback->isCanceled() )
241 break;
242 QThread::msleep( 50 );
243 delay -= 50;
244 }
245 if ( !feedback->isCanceled() )
246 filter->fetchResults( searchString, context, feedback );
247 filter->emit finished();
248 }, Qt::QueuedConnection );
249 connect( filter, &QgsLocatorFilter::finished, thread, &QThread::quit );
250 connect( filter, &QgsLocatorFilter::finished, filter, &QgsLocatorFilter::deleteLater );
251 connect( thread, &QThread::finished, thread, [this, thread]
252 {
253 mActiveThreads.removeAll( thread );
254 if ( mActiveThreads.empty() )
255 emit finished();
256 } );
257 connect( thread, &QThread::finished, thread, &QThread::deleteLater );
258 thread->start();
259 }
260
261 emit searchPrepared();
262
263 if ( mActiveThreads.empty() )
264 emit finished();
265}
266
268{
269 cancelRunningQuery();
270}
271
273{
274 if ( mFeedback )
275 mFeedback->cancel();
276}
277
279{
280 return !mActiveThreads.empty();
281}
282
284{
285 for ( QgsLocatorFilter *filter : std::as_const( mFilters ) )
286 {
287 if ( filter->enabled() )
288 {
289 filter->clearPreviousResults();
290 }
291 }
292}
293
294void QgsLocator::filterSentResult( QgsLocatorResult result )
295{
296 // if query has been canceled then discard any results we receive
297 if ( mFeedback->isCanceled() )
298 return;
299
300 emit foundResult( result );
301}
302
303void QgsLocator::cancelRunningQuery()
304{
305 if ( !mActiveThreads.empty() )
306 {
307 // cancel existing job
308 mFeedback->cancel();
309 while ( !mActiveThreads.empty() )
310 {
311 QCoreApplication::processEvents();
312 }
313 }
314}
@ Critical
Critical/error message.
Definition qgis.h:162
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
Encapsulates the properties relating to the context of a locator search.
bool usingPrefix
Will be true if search is being conducted using a filter prefix.
Abstract base class for filters which collect locator results.
void setEnabled(bool enabled)
Sets whether the filter is enabled.
void setActivePrefix(const QString &activePrefix)
Sets the prefix as being used by the locator.
virtual QString prefix() const
Returns the search prefix character(s) for this filter.
bool useWithoutPrefix() const
Returns true if the filter should be used when no prefix is entered.
@ FlagFast
Filter finds results quickly and can be safely run in the main thread.
void setUseWithoutPrefix(bool useWithoutPrefix)
Sets whether the filter should be used when no prefix is entered.
void finished()
Emitted when the filter finishes fetching results.
virtual QString name() const =0
Returns the unique name for the filter.
void resultFetched(const QgsLocatorResult &result)
Should be emitted by filters whenever they encounter a matching result during within their fetchResul...
Encapsulates properties of an individual matching result found by a QgsLocatorFilter.
static const QList< QString > CORE_FILTERS
List of core filters (i.e. not plugin filters).
Definition qgslocator.h:71
void searchPrepared()
Emitted when locator has prepared the search (.
void cancel()
Cancels any current running query, and blocks until query is completely canceled by all filters.
QgsLocator(QObject *parent=nullptr)
Constructor for QgsLocator.
static const QgsSettingsEntryBool * settingsLocatorFilterDefault
Settings entry locator filter default value.
Definition qgslocator.h:168
void registerFilter(QgsLocatorFilter *filter)
Registers a filter within the locator.
void finished()
Emitted when locator has finished a query, either as a result of successful completion or early cance...
void foundResult(const QgsLocatorResult &result)
Emitted whenever a filter encounters a matching result after the fetchResults() method is called.
void fetchResults(const QString &string, const QgsLocatorContext &context, QgsFeedback *feedback=nullptr)
Triggers the background fetching of filter results for a specified search string.
void clearPreviousResults()
Will call clearPreviousResults on all filters.
static const QgsSettingsEntryBool * settingsLocatorFilterEnabled
Settings entry locator filter enabled.
Definition qgslocator.h:166
~QgsLocator() override
Destructor for QgsLocator.
Q_DECL_DEPRECATED QMap< QString, QgsLocatorFilter * > prefixedFilters() const
Returns a map of prefix to filter, for all registered filters with valid prefixes.
bool isRunning() const
Returns true if a query is currently being executed by the locator.
static const QgsSettingsEntryString * settingsLocatorFilterPrefix
Settings entry locator filter prefix.
Definition qgslocator.h:170
void cancelWithoutBlocking()
Triggers cancellation of any current running query without blocking.
QList< QgsLocatorFilter * > filters(const QString &prefix=QString())
Returns the list of filters registered in the locator.
void deregisterFilter(QgsLocatorFilter *filter)
Deregisters a filter from the locator and deletes it.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
A boolean settings entry.
A string settings entry.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c