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