]> cloud.milkyroute.net Git - dolphin.git/blob - src/search/dolphinsearchbox.cpp
22941104cc95aff67dc8dda92efcdca5b735e9ba
[dolphin.git] / src / search / dolphinsearchbox.cpp
1 /***************************************************************************
2 * Copyright (C) 2010 by Peter Penz <peter.penz19@gmail.com> *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 * **************************************************************************/
19
20 #include "global.h"
21 #include "dolphinsearchbox.h"
22
23 #include "dolphin_searchsettings.h"
24 #include "dolphinfacetswidget.h"
25 #include "dolphinquery.h"
26 #include "panels/places/placesitemmodel.h"
27
28 #include <KLocalizedString>
29 #include <KNS3/KMoreToolsMenuFactory>
30 #include <KSeparator>
31 #include <config-baloo.h>
32 #ifdef HAVE_BALOO
33 #include <Baloo/Query>
34 #include <Baloo/IndexerConfig>
35 #endif
36
37 #include <QButtonGroup>
38 #include <QDir>
39 #include <QFontDatabase>
40 #include <QHBoxLayout>
41 #include <QIcon>
42 #include <QKeyEvent>
43 #include <QLabel>
44 #include <QLineEdit>
45 #include <QScrollArea>
46 #include <QShowEvent>
47 #include <QTimer>
48 #include <QToolButton>
49 #include <QUrlQuery>
50
51 DolphinSearchBox::DolphinSearchBox(QWidget* parent) :
52 QWidget(parent),
53 m_startedSearching(false),
54 m_active(true),
55 m_topLayout(nullptr),
56 m_searchInput(nullptr),
57 m_saveSearchAction(nullptr),
58 m_optionsScrollArea(nullptr),
59 m_fileNameButton(nullptr),
60 m_contentButton(nullptr),
61 m_separator(nullptr),
62 m_fromHereButton(nullptr),
63 m_everywhereButton(nullptr),
64 m_facetsWidget(nullptr),
65 m_searchPath(),
66 m_startSearchTimer(nullptr)
67 {
68 }
69
70 DolphinSearchBox::~DolphinSearchBox()
71 {
72 saveSettings();
73 }
74
75 void DolphinSearchBox::setText(const QString& text)
76 {
77 m_searchInput->setText(text);
78 }
79
80 QString DolphinSearchBox::text() const
81 {
82 return m_searchInput->text();
83 }
84
85 void DolphinSearchBox::setSearchPath(const QUrl& url)
86 {
87 if (url == m_searchPath) {
88 return;
89 }
90
91 const QUrl cleanedUrl = url.adjusted(QUrl::RemoveUserInfo | QUrl::StripTrailingSlash);
92
93 if (cleanedUrl.path() == QDir::homePath()) {
94 m_fromHereButton->setChecked(false);
95 m_everywhereButton->setChecked(true);
96 if (!m_searchPath.isEmpty()) {
97 return;
98 }
99 } else {
100 m_everywhereButton->setChecked(false);
101 m_fromHereButton->setChecked(true);
102 }
103
104 m_searchPath = url;
105
106 QFontMetrics metrics(m_fromHereButton->font());
107 const int maxWidth = metrics.height() * 8;
108
109 QString location = cleanedUrl.fileName();
110 if (location.isEmpty()) {
111 location = cleanedUrl.toString(QUrl::PreferLocalFile);
112 }
113 const QString elidedLocation = metrics.elidedText(location, Qt::ElideMiddle, maxWidth);
114 m_fromHereButton->setText(i18nc("action:button", "From Here (%1)", elidedLocation));
115 m_fromHereButton->setToolTip(i18nc("action:button", "Limit search to '%1' and its subfolders", cleanedUrl.toString(QUrl::PreferLocalFile)));
116 }
117
118 QUrl DolphinSearchBox::searchPath() const
119 {
120 return m_everywhereButton->isChecked() ? QUrl::fromLocalFile(QDir::homePath()) : m_searchPath;
121 }
122
123 QUrl DolphinSearchBox::urlForSearching() const
124 {
125 QUrl url;
126
127 if (isIndexingEnabled()) {
128 url = balooUrlForSearching();
129 } else {
130 url.setScheme(QStringLiteral("filenamesearch"));
131
132 QUrlQuery query;
133 query.addQueryItem(QStringLiteral("search"), m_searchInput->text());
134 if (m_contentButton->isChecked()) {
135 query.addQueryItem(QStringLiteral("checkContent"), QStringLiteral("yes"));
136 }
137
138 query.addQueryItem(QStringLiteral("url"), searchPath().url());
139
140 url.setQuery(query);
141 }
142
143 return url;
144 }
145
146 void DolphinSearchBox::fromSearchUrl(const QUrl& url)
147 {
148 if (url.scheme() == QLatin1String("baloosearch")) {
149 const DolphinQuery query = DolphinQuery::fromBalooSearchUrl(url);
150 updateFromQuery(query);
151 } else if (url.scheme() == QLatin1String("filenamesearch")) {
152 const QUrlQuery query(url);
153 setText(query.queryItemValue(QStringLiteral("search")));
154 if (m_searchPath.scheme() != url.scheme()) {
155 m_searchPath = QUrl();
156 }
157 setSearchPath(QUrl::fromUserInput(query.queryItemValue(QStringLiteral("url")), QString(), QUrl::AssumeLocalFile));
158 m_contentButton->setChecked(query.queryItemValue(QStringLiteral("checkContent")) == QLatin1String("yes"));
159 } else {
160 setText(QString());
161 m_searchPath = QUrl();
162 setSearchPath(url);
163 }
164
165 updateFacetsVisible();
166 }
167
168 void DolphinSearchBox::selectAll()
169 {
170 m_searchInput->selectAll();
171 }
172
173 void DolphinSearchBox::setActive(bool active)
174 {
175 if (active != m_active) {
176 m_active = active;
177
178 if (active) {
179 emit activated();
180 }
181 }
182 }
183
184 bool DolphinSearchBox::isActive() const
185 {
186 return m_active;
187 }
188
189 bool DolphinSearchBox::event(QEvent* event)
190 {
191 if (event->type() == QEvent::Polish) {
192 init();
193 }
194 return QWidget::event(event);
195 }
196
197 void DolphinSearchBox::showEvent(QShowEvent* event)
198 {
199 if (!event->spontaneous()) {
200 m_searchInput->setFocus();
201 m_startedSearching = false;
202 }
203 }
204
205 void DolphinSearchBox::hideEvent(QHideEvent* event)
206 {
207 Q_UNUSED(event)
208 m_startedSearching = false;
209 m_startSearchTimer->stop();
210 }
211
212 void DolphinSearchBox::keyReleaseEvent(QKeyEvent* event)
213 {
214 QWidget::keyReleaseEvent(event);
215 if (event->key() == Qt::Key_Escape) {
216 if (m_searchInput->text().isEmpty()) {
217 emit closeRequest();
218 } else {
219 m_searchInput->clear();
220 }
221 }
222 else if (event->key() == Qt::Key_Down) {
223 emit focusViewRequest();
224 }
225 }
226
227 bool DolphinSearchBox::eventFilter(QObject* obj, QEvent* event)
228 {
229 switch (event->type()) {
230 case QEvent::FocusIn:
231 // #379135: we get the FocusIn event when we close a tab but we don't want to emit
232 // the activated() signal before the removeTab() call in DolphinTabWidget::closeTab() returns.
233 // To avoid this issue, we delay the activation of the search box.
234 // We also don't want to schedule the activation process if we are already active,
235 // otherwise we can enter in a loop of FocusIn/FocusOut events with the searchbox of another tab.
236 if (!isActive()) {
237 QTimer::singleShot(0, this, [this] {
238 setActive(true);
239 setFocus();
240 });
241 }
242 break;
243
244 default:
245 break;
246 }
247
248 return QObject::eventFilter(obj, event);
249 }
250
251 void DolphinSearchBox::emitSearchRequest()
252 {
253 m_startSearchTimer->stop();
254 m_startedSearching = true;
255 m_saveSearchAction->setEnabled(true);
256 emit searchRequest();
257 }
258
259 void DolphinSearchBox::emitCloseRequest()
260 {
261 m_startSearchTimer->stop();
262 m_startedSearching = false;
263 m_saveSearchAction->setEnabled(false);
264 emit closeRequest();
265 }
266
267 void DolphinSearchBox::slotConfigurationChanged()
268 {
269 saveSettings();
270 if (m_startedSearching) {
271 emitSearchRequest();
272 }
273 }
274
275 void DolphinSearchBox::slotSearchTextChanged(const QString& text)
276 {
277
278 if (text.isEmpty()) {
279 m_startSearchTimer->stop();
280 } else {
281 m_startSearchTimer->start();
282 }
283 emit searchTextChanged(text);
284 }
285
286 void DolphinSearchBox::slotReturnPressed()
287 {
288 emitSearchRequest();
289 emit focusViewRequest();
290 }
291
292 void DolphinSearchBox::slotFacetChanged()
293 {
294 m_startedSearching = true;
295 m_startSearchTimer->stop();
296 emit searchRequest();
297 }
298
299 void DolphinSearchBox::slotSearchSaved()
300 {
301 const QUrl searchURL = urlForSearching();
302 if (searchURL.isValid()) {
303 PlacesItemModel model;
304 const QString label = i18n("Search for %1 in %2", text(), searchPath().fileName());
305 model.createPlacesItem(label,
306 searchURL,
307 QStringLiteral("folder-saved-search-symbolic"));
308 }
309 }
310
311 void DolphinSearchBox::initButton(QToolButton* button)
312 {
313 button->installEventFilter(this);
314 button->setAutoExclusive(true);
315 button->setAutoRaise(true);
316 button->setCheckable(true);
317 connect(button, &QToolButton::clicked, this, &DolphinSearchBox::slotConfigurationChanged);
318 }
319
320 void DolphinSearchBox::loadSettings()
321 {
322 if (SearchSettings::location() == QLatin1String("Everywhere")) {
323 m_everywhereButton->setChecked(true);
324 } else {
325 m_fromHereButton->setChecked(true);
326 }
327
328 if (SearchSettings::what() == QLatin1String("Content")) {
329 m_contentButton->setChecked(true);
330 } else {
331 m_fileNameButton->setChecked(true);
332 }
333
334 updateFacetsVisible();
335 }
336
337 void DolphinSearchBox::saveSettings()
338 {
339 SearchSettings::setLocation(m_fromHereButton->isChecked() ? QStringLiteral("FromHere") : QStringLiteral("Everywhere"));
340 SearchSettings::setWhat(m_fileNameButton->isChecked() ? QStringLiteral("FileName") : QStringLiteral("Content"));
341 SearchSettings::self()->save();
342 }
343
344 void DolphinSearchBox::init()
345 {
346 // Create close button
347 QToolButton* closeButton = new QToolButton(this);
348 closeButton->setAutoRaise(true);
349 closeButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close")));
350 closeButton->setToolTip(i18nc("@info:tooltip", "Quit searching"));
351 connect(closeButton, &QToolButton::clicked, this, &DolphinSearchBox::emitCloseRequest);
352
353 // Create search box
354 m_searchInput = new QLineEdit(this);
355 m_searchInput->setPlaceholderText(i18n("Search..."));
356 m_searchInput->installEventFilter(this);
357 m_searchInput->setClearButtonEnabled(true);
358 m_searchInput->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));
359 connect(m_searchInput, &QLineEdit::returnPressed,
360 this, &DolphinSearchBox::slotReturnPressed);
361 connect(m_searchInput, &QLineEdit::textChanged,
362 this, &DolphinSearchBox::slotSearchTextChanged);
363 setFocusProxy(m_searchInput);
364
365 // Add "Save search" button inside search box
366 m_saveSearchAction = new QAction(this);
367 m_saveSearchAction->setIcon (QIcon::fromTheme(QStringLiteral("document-save-symbolic")));
368 m_saveSearchAction->setText(i18nc("action:button", "Save this search to quickly access it again in the future"));
369 m_saveSearchAction->setEnabled(false);
370 m_searchInput->addAction(m_saveSearchAction, QLineEdit::TrailingPosition);
371 connect(m_saveSearchAction, &QAction::triggered, this, &DolphinSearchBox::slotSearchSaved);
372
373 // Apply layout for the search input
374 QHBoxLayout* searchInputLayout = new QHBoxLayout();
375 searchInputLayout->setContentsMargins(0, 0, 0, 0);
376 searchInputLayout->addWidget(closeButton);
377 searchInputLayout->addWidget(m_searchInput);
378
379 // Create "Filename" and "Content" button
380 m_fileNameButton = new QToolButton(this);
381 m_fileNameButton->setText(i18nc("action:button", "Filename"));
382 initButton(m_fileNameButton);
383
384 m_contentButton = new QToolButton();
385 m_contentButton->setText(i18nc("action:button", "Content"));
386 initButton(m_contentButton);
387
388 QButtonGroup* searchWhatGroup = new QButtonGroup(this);
389 searchWhatGroup->addButton(m_fileNameButton);
390 searchWhatGroup->addButton(m_contentButton);
391
392 m_separator = new KSeparator(Qt::Vertical, this);
393
394 // Create "From Here" and "Your files" buttons
395 m_fromHereButton = new QToolButton(this);
396 m_fromHereButton->setText(i18nc("action:button", "From Here"));
397 initButton(m_fromHereButton);
398
399 m_everywhereButton = new QToolButton(this);
400 m_everywhereButton->setText(i18nc("action:button", "Your files"));
401 m_everywhereButton->setToolTip(i18nc("action:button", "Search in your home directory"));
402 m_everywhereButton->setIcon(QIcon::fromTheme(QStringLiteral("user-home")));
403 m_everywhereButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
404 initButton(m_everywhereButton);
405
406 QButtonGroup* searchLocationGroup = new QButtonGroup(this);
407 searchLocationGroup->addButton(m_fromHereButton);
408 searchLocationGroup->addButton(m_everywhereButton);
409
410 auto moreSearchToolsButton = new QToolButton(this);
411 moreSearchToolsButton->setAutoRaise(true);
412 moreSearchToolsButton->setPopupMode(QToolButton::InstantPopup);
413 moreSearchToolsButton->setIcon(QIcon::fromTheme("arrow-down-double"));
414 moreSearchToolsButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
415 moreSearchToolsButton->setText(i18n("More Search Tools"));
416 moreSearchToolsButton->setMenu(new QMenu(this));
417 connect(moreSearchToolsButton->menu(), &QMenu::aboutToShow, moreSearchToolsButton->menu(), [this, moreSearchToolsButton]()
418 {
419 m_menuFactory.reset(new KMoreToolsMenuFactory("dolphin/search-tools"));
420 moreSearchToolsButton->menu()->clear();
421 m_menuFactory->fillMenuFromGroupingNames(moreSearchToolsButton->menu(), { "files-find" }, this->m_searchPath);
422 } );
423
424 // Create "Facets" widget
425 m_facetsWidget = new DolphinFacetsWidget(this);
426 m_facetsWidget->installEventFilter(this);
427 m_facetsWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
428 m_facetsWidget->layout()->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
429 connect(m_facetsWidget, &DolphinFacetsWidget::facetChanged, this, &DolphinSearchBox::slotFacetChanged);
430
431 // Apply layout for the options
432 QHBoxLayout* optionsLayout = new QHBoxLayout();
433 optionsLayout->setContentsMargins(0, 0, 0, 0);
434 optionsLayout->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
435 optionsLayout->addWidget(m_fileNameButton);
436 optionsLayout->addWidget(m_contentButton);
437 optionsLayout->addWidget(m_separator);
438 optionsLayout->addWidget(m_fromHereButton);
439 optionsLayout->addWidget(m_everywhereButton);
440 optionsLayout->addWidget(new KSeparator(Qt::Vertical, this));
441 optionsLayout->addWidget(moreSearchToolsButton);
442 optionsLayout->addStretch(1);
443
444 // Put the options into a QScrollArea. This prevents increasing the view width
445 // in case that not enough width for the options is available.
446 QWidget* optionsContainer = new QWidget(this);
447 optionsContainer->setLayout(optionsLayout);
448
449 m_optionsScrollArea = new QScrollArea(this);
450 m_optionsScrollArea->setFrameShape(QFrame::NoFrame);
451 m_optionsScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
452 m_optionsScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
453 m_optionsScrollArea->setMaximumHeight(optionsContainer->sizeHint().height());
454 m_optionsScrollArea->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
455 m_optionsScrollArea->setWidget(optionsContainer);
456 m_optionsScrollArea->setWidgetResizable(true);
457
458 m_topLayout = new QVBoxLayout(this);
459 m_topLayout->setContentsMargins(0, 0, 0, 0);
460 m_topLayout->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
461 m_topLayout->addLayout(searchInputLayout);
462 m_topLayout->addWidget(m_optionsScrollArea);
463 m_topLayout->addWidget(m_facetsWidget);
464
465 loadSettings();
466
467 // The searching should be started automatically after the user did not change
468 // the text within one second
469 m_startSearchTimer = new QTimer(this);
470 m_startSearchTimer->setSingleShot(true);
471 m_startSearchTimer->setInterval(1000);
472 connect(m_startSearchTimer, &QTimer::timeout, this, &DolphinSearchBox::emitSearchRequest);
473 }
474
475 QUrl DolphinSearchBox::balooUrlForSearching() const
476 {
477 #ifdef HAVE_BALOO
478 const QString text = m_searchInput->text();
479
480 Baloo::Query query;
481 query.addType(m_facetsWidget->facetType());
482
483 QStringList queryStrings = m_facetsWidget->searchTerms();
484
485 if (m_contentButton->isChecked()) {
486 queryStrings << text;
487 } else if (!text.isEmpty()) {
488 queryStrings << QStringLiteral("filename:\"%1\"").arg(text);
489 }
490
491 if (m_fromHereButton->isChecked()) {
492 query.setIncludeFolder(m_searchPath.toLocalFile());
493 }
494
495 query.setSearchString(queryStrings.join(QLatin1Char(' ')));
496
497 return query.toSearchUrl(i18nc("@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.",
498 "Query Results from '%1'", text));
499 #else
500 return QUrl();
501 #endif
502 }
503
504 void DolphinSearchBox::updateFromQuery(const DolphinQuery& query)
505 {
506 // Block all signals to avoid unnecessary "searchRequest" signals
507 // while we adjust the search text and the facet widget.
508 blockSignals(true);
509
510 const QString customDir = query.includeFolder();
511 if (!customDir.isEmpty()) {
512 setSearchPath(QUrl::fromLocalFile(customDir));
513 } else {
514 setSearchPath(QUrl::fromLocalFile(QDir::homePath()));
515 }
516
517 setText(query.text());
518
519 if (query.hasContentSearch()) {
520 m_contentButton->setChecked(true);
521 } else if (query.hasFileName()) {
522 m_fileNameButton->setChecked(true);
523 }
524
525 m_facetsWidget->resetSearchTerms();
526 m_facetsWidget->setFacetType(query.type());
527 const QStringList searchTerms = query.searchTerms();
528 for (const QString& searchTerm : searchTerms) {
529 m_facetsWidget->setSearchTerm(searchTerm);
530 }
531
532 m_startSearchTimer->stop();
533 blockSignals(false);
534 }
535
536 void DolphinSearchBox::updateFacetsVisible()
537 {
538 const bool indexingEnabled = isIndexingEnabled();
539 m_facetsWidget->setEnabled(indexingEnabled);
540 m_facetsWidget->setVisible(indexingEnabled);
541 }
542
543 bool DolphinSearchBox::isIndexingEnabled() const
544 {
545 #ifdef HAVE_BALOO
546 const Baloo::IndexerConfig searchInfo;
547 return searchInfo.fileIndexingEnabled() && searchInfo.shouldBeIndexed(searchPath().toLocalFile());
548 #else
549 return false;
550 #endif
551 }