]> cloud.milkyroute.net Git - dolphin.git/blob - src/search/dolphinsearchbox.cpp
[PlacesItemModelTest] Ignore user tag places
[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 QString location = url.fileName();
91 if (location.isEmpty()) {
92 if (url.isLocalFile()) {
93 location = QStringLiteral("/");
94 } else {
95 location = url.scheme() + QLatin1String(" - ") + url.host();
96 }
97 }
98
99 const QString elidedLocation = metrics.elidedText(location, Qt::ElideMiddle, maxWidth);
100 m_fromHereButton->setText(i18nc("action:button", "From Here (%1)", elidedLocation));
101
102 const bool showSearchFromButtons = url.isLocalFile();
103 m_separator->setVisible(showSearchFromButtons);
104 m_fromHereButton->setVisible(showSearchFromButtons);
105 m_everywhereButton->setVisible(showSearchFromButtons);
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 // It is very unlikely, that the majority of Dolphins target users
142 // mean "the whole harddisk" instead of "my home folder" when
143 // selecting the "Everywhere" button.
144 encodedUrl = QDir::homePath();
145 } else {
146 encodedUrl = m_searchPath.url();
147 }
148 query.addQueryItem(QStringLiteral("url"), encodedUrl);
149
150 url.setQuery(query);
151 }
152
153 return url;
154 }
155
156 void DolphinSearchBox::fromSearchUrl(const QUrl& url)
157 {
158 if (url.scheme() == QLatin1String("baloosearch")) {
159 fromBalooSearchUrl(url);
160 } else if (url.scheme() == QLatin1String("filenamesearch")) {
161 const QUrlQuery query(url);
162 setText(query.queryItemValue(QStringLiteral("search")));
163 setSearchPath(QUrl::fromUserInput(query.queryItemValue(QStringLiteral("url")), QString(), QUrl::AssumeLocalFile));
164 m_contentButton->setChecked(query.queryItemValue(QStringLiteral("checkContent")) == QLatin1String("yes"));
165 } else {
166 setText(QString());
167 setSearchPath(url);
168 }
169 }
170
171 void DolphinSearchBox::selectAll()
172 {
173 m_searchInput->selectAll();
174 }
175
176 void DolphinSearchBox::setActive(bool active)
177 {
178 if (active != m_active) {
179 m_active = active;
180
181 if (active) {
182 emit activated();
183 }
184 }
185 }
186
187 bool DolphinSearchBox::isActive() const
188 {
189 return m_active;
190 }
191
192 bool DolphinSearchBox::event(QEvent* event)
193 {
194 if (event->type() == QEvent::Polish) {
195 init();
196 }
197 return QWidget::event(event);
198 }
199
200 void DolphinSearchBox::showEvent(QShowEvent* event)
201 {
202 if (!event->spontaneous()) {
203 m_searchInput->setFocus();
204 m_startedSearching = false;
205 }
206 }
207
208 void DolphinSearchBox::hideEvent(QHideEvent* event)
209 {
210 Q_UNUSED(event);
211 m_startedSearching = false;
212 m_startSearchTimer->stop();
213 }
214
215 void DolphinSearchBox::keyReleaseEvent(QKeyEvent* event)
216 {
217 QWidget::keyReleaseEvent(event);
218 if (event->key() == Qt::Key_Escape) {
219 if (m_searchInput->text().isEmpty()) {
220 emit closeRequest();
221 } else {
222 m_searchInput->clear();
223 }
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 returnPressed();
290 }
291
292 void DolphinSearchBox::slotFacetsButtonToggled()
293 {
294 const bool facetsIsVisible = !m_facetsWidget->isVisible();
295 m_facetsWidget->setVisible(facetsIsVisible);
296 updateFacetsToggleButton();
297 }
298
299 void DolphinSearchBox::slotFacetChanged()
300 {
301 m_startedSearching = true;
302 m_startSearchTimer->stop();
303 emit searchRequest();
304 }
305
306 void DolphinSearchBox::slotSearchSaved()
307 {
308 const QUrl searchURL = urlForSearching();
309 if (searchURL.isValid()) {
310 PlacesItemModel model;
311 const QString label = i18n("Search for %1 in %2", text(), searchPath().fileName());
312 model.createPlacesItem(label,
313 searchURL,
314 QStringLiteral("folder-saved-search-symbolic"));
315 }
316 }
317
318 void DolphinSearchBox::initButton(QToolButton* button)
319 {
320 button->installEventFilter(this);
321 button->setAutoExclusive(true);
322 button->setAutoRaise(true);
323 button->setCheckable(true);
324 connect(button, &QToolButton::clicked, this, &DolphinSearchBox::slotConfigurationChanged);
325 }
326
327 void DolphinSearchBox::loadSettings()
328 {
329 if (SearchSettings::location() == QLatin1String("Everywhere")) {
330 m_everywhereButton->setChecked(true);
331 } else {
332 m_fromHereButton->setChecked(true);
333 }
334
335 if (SearchSettings::what() == QLatin1String("Content")) {
336 m_contentButton->setChecked(true);
337 } else {
338 m_fileNameButton->setChecked(true);
339 }
340
341 m_facetsWidget->setVisible(SearchSettings::showFacetsWidget());
342 }
343
344 void DolphinSearchBox::saveSettings()
345 {
346 SearchSettings::setLocation(m_fromHereButton->isChecked() ? QStringLiteral("FromHere") : QStringLiteral("Everywhere"));
347 SearchSettings::setWhat(m_fileNameButton->isChecked() ? QStringLiteral("FileName") : QStringLiteral("Content"));
348 SearchSettings::setShowFacetsWidget(m_facetsToggleButton->isChecked());
349 SearchSettings::self()->save();
350 }
351
352 void DolphinSearchBox::init()
353 {
354 // Create close button
355 QToolButton* closeButton = new QToolButton(this);
356 closeButton->setAutoRaise(true);
357 closeButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close")));
358 closeButton->setToolTip(i18nc("@info:tooltip", "Quit searching"));
359 connect(closeButton, &QToolButton::clicked, this, &DolphinSearchBox::emitCloseRequest);
360
361 // Create search label
362 m_searchLabel = new QLabel(this);
363
364 // Create search box
365 m_searchInput = new QLineEdit(this);
366 m_searchInput->installEventFilter(this);
367 m_searchInput->setClearButtonEnabled(true);
368 m_searchInput->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));
369 connect(m_searchInput, &QLineEdit::returnPressed,
370 this, &DolphinSearchBox::slotReturnPressed);
371 connect(m_searchInput, &QLineEdit::textChanged,
372 this, &DolphinSearchBox::slotSearchTextChanged);
373 setFocusProxy(m_searchInput);
374
375 // Add "Save search" button inside search box
376 m_saveSearchAction = new QAction(this);
377 m_saveSearchAction->setIcon (QIcon::fromTheme(QStringLiteral("document-save-symbolic")));
378 m_saveSearchAction->setText(i18nc("action:button", "Save this search to quickly access it again in the future"));
379 m_saveSearchAction->setEnabled(false);
380 m_searchInput->addAction(m_saveSearchAction, QLineEdit::TrailingPosition);
381 connect(m_saveSearchAction, &QAction::triggered, this, &DolphinSearchBox::slotSearchSaved);
382
383 // Apply layout for the search input
384 QHBoxLayout* searchInputLayout = new QHBoxLayout();
385 searchInputLayout->setContentsMargins(0, 0, 0, 0);
386 searchInputLayout->addWidget(closeButton);
387 searchInputLayout->addWidget(m_searchLabel);
388 searchInputLayout->addWidget(m_searchInput);
389
390 // Create "Filename" and "Content" button
391 m_fileNameButton = new QToolButton(this);
392 m_fileNameButton->setText(i18nc("action:button", "Filename"));
393 initButton(m_fileNameButton);
394
395 m_contentButton = new QToolButton();
396 m_contentButton->setText(i18nc("action:button", "Content"));
397 initButton(m_contentButton);
398
399 QButtonGroup* searchWhatGroup = new QButtonGroup(this);
400 searchWhatGroup->addButton(m_fileNameButton);
401 searchWhatGroup->addButton(m_contentButton);
402
403 m_separator = new KSeparator(Qt::Vertical, this);
404
405 // Create "From Here" and "Everywhere"button
406 m_fromHereButton = new QToolButton(this);
407 m_fromHereButton->setText(i18nc("action:button", "From Here"));
408 initButton(m_fromHereButton);
409
410 m_everywhereButton = new QToolButton(this);
411 m_everywhereButton->setText(i18nc("action:button", "Everywhere"));
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