]> cloud.milkyroute.net Git - dolphin.git/blob - src/search/dolphinsearchbox.cpp
Dolphin Service Installer: Run uninstall scripts, rename methods
[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 }
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::slotFacetChanged()
290 {
291 m_startedSearching = true;
292 m_startSearchTimer->stop();
293 emit searchRequest();
294 }
295
296 void DolphinSearchBox::slotSearchSaved()
297 {
298 const QUrl searchURL = urlForSearching();
299 if (searchURL.isValid()) {
300 PlacesItemModel model;
301 const QString label = i18n("Search for %1 in %2", text(), searchPath().fileName());
302 model.createPlacesItem(label,
303 searchURL,
304 QStringLiteral("folder-saved-search-symbolic"));
305 }
306 }
307
308 void DolphinSearchBox::initButton(QToolButton* button)
309 {
310 button->installEventFilter(this);
311 button->setAutoExclusive(true);
312 button->setAutoRaise(true);
313 button->setCheckable(true);
314 connect(button, &QToolButton::clicked, this, &DolphinSearchBox::slotConfigurationChanged);
315 }
316
317 void DolphinSearchBox::loadSettings()
318 {
319 if (SearchSettings::location() == QLatin1String("Everywhere")) {
320 m_everywhereButton->setChecked(true);
321 } else {
322 m_fromHereButton->setChecked(true);
323 }
324
325 if (SearchSettings::what() == QLatin1String("Content")) {
326 m_contentButton->setChecked(true);
327 } else {
328 m_fileNameButton->setChecked(true);
329 }
330
331 updateFacetsVisible();
332 }
333
334 void DolphinSearchBox::saveSettings()
335 {
336 SearchSettings::setLocation(m_fromHereButton->isChecked() ? QStringLiteral("FromHere") : QStringLiteral("Everywhere"));
337 SearchSettings::setWhat(m_fileNameButton->isChecked() ? QStringLiteral("FileName") : QStringLiteral("Content"));
338 SearchSettings::self()->save();
339 }
340
341 void DolphinSearchBox::init()
342 {
343 // Create close button
344 QToolButton* closeButton = new QToolButton(this);
345 closeButton->setAutoRaise(true);
346 closeButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close")));
347 closeButton->setToolTip(i18nc("@info:tooltip", "Quit searching"));
348 connect(closeButton, &QToolButton::clicked, this, &DolphinSearchBox::emitCloseRequest);
349
350 // Create search box
351 m_searchInput = new QLineEdit(this);
352 m_searchInput->setPlaceholderText(i18n("Search..."));
353 m_searchInput->installEventFilter(this);
354 m_searchInput->setClearButtonEnabled(true);
355 m_searchInput->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));
356 connect(m_searchInput, &QLineEdit::returnPressed,
357 this, &DolphinSearchBox::slotReturnPressed);
358 connect(m_searchInput, &QLineEdit::textChanged,
359 this, &DolphinSearchBox::slotSearchTextChanged);
360 setFocusProxy(m_searchInput);
361
362 // Add "Save search" button inside search box
363 m_saveSearchAction = new QAction(this);
364 m_saveSearchAction->setIcon (QIcon::fromTheme(QStringLiteral("document-save-symbolic")));
365 m_saveSearchAction->setText(i18nc("action:button", "Save this search to quickly access it again in the future"));
366 m_saveSearchAction->setEnabled(false);
367 m_searchInput->addAction(m_saveSearchAction, QLineEdit::TrailingPosition);
368 connect(m_saveSearchAction, &QAction::triggered, this, &DolphinSearchBox::slotSearchSaved);
369
370 // Apply layout for the search input
371 QHBoxLayout* searchInputLayout = new QHBoxLayout();
372 searchInputLayout->setContentsMargins(0, 0, 0, 0);
373 searchInputLayout->addWidget(closeButton);
374 searchInputLayout->addWidget(m_searchInput);
375
376 // Create "Filename" and "Content" button
377 m_fileNameButton = new QToolButton(this);
378 m_fileNameButton->setText(i18nc("action:button", "Filename"));
379 initButton(m_fileNameButton);
380
381 m_contentButton = new QToolButton();
382 m_contentButton->setText(i18nc("action:button", "Content"));
383 initButton(m_contentButton);
384
385 QButtonGroup* searchWhatGroup = new QButtonGroup(this);
386 searchWhatGroup->addButton(m_fileNameButton);
387 searchWhatGroup->addButton(m_contentButton);
388
389 m_separator = new KSeparator(Qt::Vertical, this);
390
391 // Create "From Here" and "Your files" buttons
392 m_fromHereButton = new QToolButton(this);
393 m_fromHereButton->setText(i18nc("action:button", "From Here"));
394 initButton(m_fromHereButton);
395
396 m_everywhereButton = new QToolButton(this);
397 m_everywhereButton->setText(i18nc("action:button", "Your files"));
398 m_everywhereButton->setToolTip(i18nc("action:button", "Search in your home directory"));
399 m_everywhereButton->setIcon(QIcon::fromTheme(QStringLiteral("user-home")));
400 m_everywhereButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
401 initButton(m_everywhereButton);
402
403 QButtonGroup* searchLocationGroup = new QButtonGroup(this);
404 searchLocationGroup->addButton(m_fromHereButton);
405 searchLocationGroup->addButton(m_everywhereButton);
406
407 auto moreSearchToolsButton = new QToolButton(this);
408 moreSearchToolsButton->setAutoRaise(true);
409 moreSearchToolsButton->setPopupMode(QToolButton::InstantPopup);
410 moreSearchToolsButton->setIcon(QIcon::fromTheme("arrow-down-double"));
411 moreSearchToolsButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
412 moreSearchToolsButton->setText(i18n("More Search Tools"));
413 moreSearchToolsButton->setMenu(new QMenu(this));
414 connect(moreSearchToolsButton->menu(), &QMenu::aboutToShow, moreSearchToolsButton->menu(), [this, moreSearchToolsButton]()
415 {
416 m_menuFactory.reset(new KMoreToolsMenuFactory("dolphin/search-tools"));
417 moreSearchToolsButton->menu()->clear();
418 m_menuFactory->fillMenuFromGroupingNames(moreSearchToolsButton->menu(), { "files-find" }, this->m_searchPath);
419 } );
420
421 // Create "Facets" widget
422 m_facetsWidget = new DolphinFacetsWidget(this);
423 m_facetsWidget->installEventFilter(this);
424 m_facetsWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
425 m_facetsWidget->layout()->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
426 connect(m_facetsWidget, &DolphinFacetsWidget::facetChanged, this, &DolphinSearchBox::slotFacetChanged);
427
428 // Apply layout for the options
429 QHBoxLayout* optionsLayout = new QHBoxLayout();
430 optionsLayout->setContentsMargins(0, 0, 0, 0);
431 optionsLayout->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
432 optionsLayout->addWidget(m_fileNameButton);
433 optionsLayout->addWidget(m_contentButton);
434 optionsLayout->addWidget(m_separator);
435 optionsLayout->addWidget(m_fromHereButton);
436 optionsLayout->addWidget(m_everywhereButton);
437 optionsLayout->addWidget(new KSeparator(Qt::Vertical, this));
438 optionsLayout->addWidget(moreSearchToolsButton);
439 optionsLayout->addStretch(1);
440
441 // Put the options into a QScrollArea. This prevents increasing the view width
442 // in case that not enough width for the options is available.
443 QWidget* optionsContainer = new QWidget(this);
444 optionsContainer->setLayout(optionsLayout);
445
446 m_optionsScrollArea = new QScrollArea(this);
447 m_optionsScrollArea->setFrameShape(QFrame::NoFrame);
448 m_optionsScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
449 m_optionsScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
450 m_optionsScrollArea->setMaximumHeight(optionsContainer->sizeHint().height());
451 m_optionsScrollArea->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
452 m_optionsScrollArea->setWidget(optionsContainer);
453 m_optionsScrollArea->setWidgetResizable(true);
454
455 m_topLayout = new QVBoxLayout(this);
456 m_topLayout->setContentsMargins(0, 0, 0, 0);
457 m_topLayout->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
458 m_topLayout->addLayout(searchInputLayout);
459 m_topLayout->addWidget(m_optionsScrollArea);
460 m_topLayout->addWidget(m_facetsWidget);
461
462 loadSettings();
463
464 // The searching should be started automatically after the user did not change
465 // the text within one second
466 m_startSearchTimer = new QTimer(this);
467 m_startSearchTimer->setSingleShot(true);
468 m_startSearchTimer->setInterval(1000);
469 connect(m_startSearchTimer, &QTimer::timeout, this, &DolphinSearchBox::emitSearchRequest);
470 }
471
472 QUrl DolphinSearchBox::balooUrlForSearching() const
473 {
474 #ifdef HAVE_BALOO
475 const QString text = m_searchInput->text();
476
477 Baloo::Query query;
478 query.addType(m_facetsWidget->facetType());
479
480 QStringList queryStrings = m_facetsWidget->searchTerms();
481
482 if (m_contentButton->isChecked()) {
483 queryStrings << text;
484 } else if (!text.isEmpty()) {
485 queryStrings << QStringLiteral("filename:\"%1\"").arg(text);
486 }
487
488 if (m_fromHereButton->isChecked()) {
489 query.setIncludeFolder(m_searchPath.toLocalFile());
490 }
491
492 query.setSearchString(queryStrings.join(QLatin1Char(' ')));
493
494 return query.toSearchUrl(i18nc("@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.",
495 "Query Results from '%1'", text));
496 #else
497 return QUrl();
498 #endif
499 }
500
501 void DolphinSearchBox::updateFromQuery(const DolphinQuery& query)
502 {
503 // Block all signals to avoid unnecessary "searchRequest" signals
504 // while we adjust the search text and the facet widget.
505 blockSignals(true);
506
507 const QString customDir = query.includeFolder();
508 if (!customDir.isEmpty()) {
509 setSearchPath(QUrl::fromLocalFile(customDir));
510 } else {
511 setSearchPath(QUrl::fromLocalFile(QDir::homePath()));
512 }
513
514 setText(query.text());
515
516 if (query.hasContentSearch()) {
517 m_contentButton->setChecked(true);
518 } else if (query.hasFileName()) {
519 m_fileNameButton->setChecked(true);
520 }
521
522 m_facetsWidget->resetSearchTerms();
523 m_facetsWidget->setFacetType(query.type());
524 const QStringList searchTerms = query.searchTerms();
525 for (const QString& searchTerm : searchTerms) {
526 m_facetsWidget->setSearchTerm(searchTerm);
527 }
528
529 m_startSearchTimer->stop();
530 blockSignals(false);
531 }
532
533 void DolphinSearchBox::updateFacetsVisible()
534 {
535 const bool indexingEnabled = isIndexingEnabled();
536 m_facetsWidget->setEnabled(indexingEnabled);
537 m_facetsWidget->setVisible(indexingEnabled);
538 }
539
540 bool DolphinSearchBox::isIndexingEnabled() const
541 {
542 #ifdef HAVE_BALOO
543 const Baloo::IndexerConfig searchInfo;
544 return searchInfo.fileIndexingEnabled() && searchInfo.shouldBeIndexed(searchPath().toLocalFile());
545 #else
546 return false;
547 #endif
548 }