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