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