]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphinviewcontainer.cpp
Clear filter bar on clicking current folder in places
[dolphin.git] / src / dolphinviewcontainer.cpp
1 /*
2 * SPDX-FileCopyrightText: 2007 Peter Penz <peter.penz19@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "dolphinviewcontainer.h"
8
9 #include "dolphin_generalsettings.h"
10 #include "dolphindebug.h"
11 #include "dolphinplacesmodelsingleton.h"
12 #include "filterbar/filterbar.h"
13 #include "global.h"
14 #include "search/dolphinsearchbox.h"
15 #include "selectionmode/topbar.h"
16 #include "statusbar/dolphinstatusbar.h"
17 #include "dolphin_detailsmodesettings.h"
18
19 #include <KActionCollection>
20 #if HAVE_KACTIVITIES
21 #include <KActivities/ResourceInstance>
22 #endif
23 #include <KFileItemActions>
24 #include <KFilePlacesModel>
25 #include <kio_version.h>
26 #if KIO_VERSION >= QT_VERSION_CHECK(5, 98, 0)
27 #include <KIO/JobUiDelegateFactory>
28 #else
29 #include <KIO/JobUiDelegate>
30 #endif
31 #include <KIO/OpenUrlJob>
32 #include <KLocalizedString>
33 #include <KMessageWidget>
34 #include <KProtocolManager>
35 #include <KShell>
36
37 #include <QDesktopServices>
38 #include <QDropEvent>
39 #include <QGridLayout>
40 #include <QGuiApplication>
41 #include <QTimer>
42 #include <QUrl>
43 #include <QRegularExpression>
44
45 // An overview of the widgets contained by this ViewContainer
46 struct LayoutStructure {
47 int searchBox = 0;
48 int messageWidget = 1;
49 int selectionModeTopBar = 2;
50 int view = 3;
51 int selectionModeBottomBar = 4;
52 int filterBar = 5;
53 int statusBar = 6;
54 };
55 constexpr LayoutStructure positionFor;
56
57 DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) :
58 QWidget(parent),
59 m_topLayout(nullptr),
60 m_urlNavigator{new DolphinUrlNavigator(url)},
61 m_urlNavigatorConnected{nullptr},
62 m_searchBox(nullptr),
63 m_searchModeEnabled(false),
64 m_messageWidget(nullptr),
65 m_selectionModeTopBar{nullptr},
66 m_view(nullptr),
67 m_filterBar(nullptr),
68 m_selectionModeBottomBar{nullptr},
69 m_statusBar(nullptr),
70 m_statusBarTimer(nullptr),
71 m_statusBarTimestamp(),
72 m_autoGrabFocus(true)
73 #if HAVE_KACTIVITIES
74 , m_activityResourceInstance(nullptr)
75 #endif
76 {
77 hide();
78
79 m_topLayout = new QGridLayout(this);
80 m_topLayout->setSpacing(0);
81 m_topLayout->setContentsMargins(0, 0, 0, 0);
82
83 m_searchBox = new DolphinSearchBox(this);
84 m_searchBox->hide();
85 connect(m_searchBox, &DolphinSearchBox::activated, this, &DolphinViewContainer::activate);
86 connect(m_searchBox, &DolphinSearchBox::closeRequest, this, &DolphinViewContainer::closeSearchBox);
87 connect(m_searchBox, &DolphinSearchBox::searchRequest, this, &DolphinViewContainer::startSearching);
88 connect(m_searchBox, &DolphinSearchBox::focusViewRequest, this, &DolphinViewContainer::requestFocus);
89 m_searchBox->setWhatsThis(xi18nc("@info:whatsthis findbar",
90 "<para>This helps you find files and folders. Enter a <emphasis>"
91 "search term</emphasis> and specify search settings with the "
92 "buttons at the bottom:<list><item>Filename/Content: "
93 "Does the item you are looking for contain the search terms "
94 "within its filename or its contents?<nl/>The contents of images, "
95 "audio files and videos will not be searched.</item><item>"
96 "From Here/Everywhere: Do you want to search in this "
97 "folder and its sub-folders or everywhere?</item><item>"
98 "More Options: Click this to search by media type, access "
99 "time or rating.</item><item>More Search Tools: Install other "
100 "means to find an item.</item></list></para>"));
101
102 m_messageWidget = new KMessageWidget(this);
103 m_messageWidget->setCloseButtonVisible(true);
104 m_messageWidget->hide();
105
106 #ifndef Q_OS_WIN
107 if (getuid() == 0) {
108
109 // We must be logged in as the root user; show a big scary warning
110 showMessage(i18n("Running Dolphin as root can be dangerous. Please be careful."), Warning);
111 }
112 #endif
113
114 // Initialize filter bar
115 m_filterBar = new FilterBar(this);
116 m_filterBar->setVisible(GeneralSettings::filterBar());
117
118 connect(m_filterBar, &FilterBar::filterChanged,
119 this, &DolphinViewContainer::setNameFilter);
120 connect(m_filterBar, &FilterBar::closeRequest,
121 this, &DolphinViewContainer::closeFilterBar);
122 connect(m_filterBar, &FilterBar::focusViewRequest,
123 this, &DolphinViewContainer::requestFocus);
124
125 // Initialize the main view
126 m_view = new DolphinView(url, this);
127 connect(m_view, &DolphinView::urlChanged,
128 m_filterBar, &FilterBar::clearIfUnlocked);
129 connect(m_view, &DolphinView::urlChanged,
130 m_messageWidget, &KMessageWidget::hide);
131 // m_urlNavigator stays in sync with m_view's location changes and
132 // keeps track of them so going back and forth in the history works.
133 connect(m_view, &DolphinView::urlChanged,
134 m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
135 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlChanged,
136 this, &DolphinViewContainer::slotUrlNavigatorLocationChanged);
137 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlAboutToBeChanged,
138 this, &DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged);
139 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlSelectionRequested,
140 this, &DolphinViewContainer::slotUrlSelectionRequested);
141 connect(m_view, &DolphinView::writeStateChanged,
142 this, &DolphinViewContainer::writeStateChanged);
143 connect(m_view, &DolphinView::requestItemInfo,
144 this, &DolphinViewContainer::showItemInfo);
145 connect(m_view, &DolphinView::itemActivated,
146 this, &DolphinViewContainer::slotItemActivated);
147 connect(m_view, &DolphinView::itemsActivated,
148 this, &DolphinViewContainer::slotItemsActivated);
149 connect(m_view, &DolphinView::redirection,
150 this, &DolphinViewContainer::redirect);
151 connect(m_view, &DolphinView::directoryLoadingStarted,
152 this, &DolphinViewContainer::slotDirectoryLoadingStarted);
153 connect(m_view, &DolphinView::directoryLoadingCompleted,
154 this, &DolphinViewContainer::slotDirectoryLoadingCompleted);
155 connect(m_view, &DolphinView::directoryLoadingCanceled,
156 this, &DolphinViewContainer::slotDirectoryLoadingCanceled);
157 connect(m_view, &DolphinView::itemCountChanged,
158 this, &DolphinViewContainer::delayedStatusBarUpdate);
159 connect(m_view, &DolphinView::directoryLoadingProgress,
160 this, &DolphinViewContainer::updateDirectoryLoadingProgress);
161 connect(m_view, &DolphinView::directorySortingProgress,
162 this, &DolphinViewContainer::updateDirectorySortingProgress);
163 connect(m_view, &DolphinView::selectionChanged,
164 this, &DolphinViewContainer::delayedStatusBarUpdate);
165 connect(m_view, &DolphinView::errorMessage,
166 this, &DolphinViewContainer::showErrorMessage);
167 connect(m_view, &DolphinView::urlIsFileError,
168 this, &DolphinViewContainer::slotUrlIsFileError);
169 connect(m_view, &DolphinView::activated,
170 this, &DolphinViewContainer::activate);
171 connect(m_view, &DolphinView::hiddenFilesShownChanged,
172 this, &DolphinViewContainer::slotHiddenFilesShownChanged);
173 connect(m_view, &DolphinView::sortHiddenLastChanged,
174 this, &DolphinViewContainer::slotSortHiddenLastChanged);
175 connect(m_view, &DolphinView::currentDirectoryRemoved,
176 this, &DolphinViewContainer::slotCurrentDirectoryRemoved);
177
178 // Initialize status bar
179 m_statusBar = new DolphinStatusBar(this);
180 m_statusBar->setUrl(m_view->url());
181 m_statusBar->setZoomLevel(m_view->zoomLevel());
182 connect(m_view, &DolphinView::urlChanged,
183 m_statusBar, &DolphinStatusBar::setUrl);
184 connect(m_view, &DolphinView::zoomLevelChanged,
185 m_statusBar, &DolphinStatusBar::setZoomLevel);
186 connect(m_view, &DolphinView::infoMessage,
187 m_statusBar, &DolphinStatusBar::setText);
188 connect(m_view, &DolphinView::operationCompletedMessage,
189 m_statusBar, &DolphinStatusBar::setText);
190 connect(m_view, &DolphinView::statusBarTextChanged,
191 m_statusBar, &DolphinStatusBar::setDefaultText);
192 connect(m_view, &DolphinView::statusBarTextChanged,
193 m_statusBar, &DolphinStatusBar::resetToDefaultText);
194 connect(m_statusBar, &DolphinStatusBar::stopPressed,
195 this, &DolphinViewContainer::stopDirectoryLoading);
196 connect(m_statusBar, &DolphinStatusBar::zoomLevelChanged,
197 this, &DolphinViewContainer::slotStatusBarZoomLevelChanged);
198
199 m_statusBarTimer = new QTimer(this);
200 m_statusBarTimer->setSingleShot(true);
201 m_statusBarTimer->setInterval(300);
202 connect(m_statusBarTimer, &QTimer::timeout, this, &DolphinViewContainer::updateStatusBar);
203
204 KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self();
205 connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished,
206 this, &DolphinViewContainer::delayedStatusBarUpdate);
207
208 m_topLayout->addWidget(m_searchBox, positionFor.searchBox, 0);
209 m_topLayout->addWidget(m_messageWidget, positionFor.messageWidget, 0);
210 m_topLayout->addWidget(m_view, positionFor.view, 0);
211 m_topLayout->addWidget(m_filterBar, positionFor.filterBar, 0);
212 m_topLayout->addWidget(m_statusBar, positionFor.statusBar, 0);
213
214 setSearchModeEnabled(isSearchUrl(url));
215
216 connect(DetailsModeSettings::self(), &KCoreConfigSkeleton::configChanged, this, [=]() {
217 if (view()->viewMode() == DolphinView::Mode::DetailsView) {
218 view()->reload();
219 }
220 });
221
222 KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel();
223 connect(placesModel, &KFilePlacesModel::dataChanged,
224 this, &DolphinViewContainer::slotPlacesModelChanged);
225 connect(placesModel, &KFilePlacesModel::rowsInserted,
226 this, &DolphinViewContainer::slotPlacesModelChanged);
227 connect(placesModel, &KFilePlacesModel::rowsRemoved,
228 this, &DolphinViewContainer::slotPlacesModelChanged);
229
230 connect(this, &DolphinViewContainer::searchModeEnabledChanged,
231 this, &DolphinViewContainer::captionChanged);
232
233 // Initialize kactivities resource instance
234
235 #if HAVE_KACTIVITIES
236 m_activityResourceInstance = new KActivities::ResourceInstance(window()->winId(), url);
237 m_activityResourceInstance->setParent(this);
238 #endif
239 }
240
241 DolphinViewContainer::~DolphinViewContainer()
242 {
243 }
244
245 QUrl DolphinViewContainer::url() const
246 {
247 return m_view->url();
248 }
249
250 void DolphinViewContainer::setActive(bool active)
251 {
252 m_searchBox->setActive(active);
253 if (m_urlNavigatorConnected) {
254 m_urlNavigatorConnected->setActive(active);
255 }
256 m_view->setActive(active);
257
258 #if HAVE_KACTIVITIES
259 if (active) {
260 m_activityResourceInstance->notifyFocusedIn();
261 } else {
262 m_activityResourceInstance->notifyFocusedOut();
263 }
264 #endif
265 }
266
267 bool DolphinViewContainer::isActive() const
268 {
269 return m_view->isActive();
270 }
271
272 void DolphinViewContainer::setAutoGrabFocus(bool grab)
273 {
274 m_autoGrabFocus = grab;
275 }
276
277 bool DolphinViewContainer::autoGrabFocus() const
278 {
279 return m_autoGrabFocus;
280 }
281
282 QString DolphinViewContainer::currentSearchText() const
283 {
284 return m_searchBox->text();
285 }
286
287 const DolphinStatusBar* DolphinViewContainer::statusBar() const
288 {
289 return m_statusBar;
290 }
291
292 DolphinStatusBar* DolphinViewContainer::statusBar()
293 {
294 return m_statusBar;
295 }
296
297 const DolphinUrlNavigator* DolphinViewContainer::urlNavigator() const
298 {
299 return m_urlNavigatorConnected;
300 }
301
302 DolphinUrlNavigator* DolphinViewContainer::urlNavigator()
303 {
304 return m_urlNavigatorConnected;
305 }
306
307 const DolphinUrlNavigator *DolphinViewContainer::urlNavigatorInternalWithHistory() const
308 {
309 return m_urlNavigator.get();
310 }
311
312 DolphinUrlNavigator *DolphinViewContainer::urlNavigatorInternalWithHistory()
313 {
314 return m_urlNavigator.get();
315 }
316
317 const DolphinView* DolphinViewContainer::view() const
318 {
319 return m_view;
320 }
321
322 DolphinView* DolphinViewContainer::view()
323 {
324 return m_view;
325 }
326
327 void DolphinViewContainer::connectUrlNavigator(DolphinUrlNavigator *urlNavigator)
328 {
329 Q_CHECK_PTR(urlNavigator);
330 Q_ASSERT(!m_urlNavigatorConnected);
331 Q_ASSERT(m_urlNavigator.get() != urlNavigator);
332 Q_CHECK_PTR(m_view);
333
334 urlNavigator->setLocationUrl(m_view->url());
335 urlNavigator->setShowHiddenFolders(m_view->hiddenFilesShown());
336 urlNavigator->setSortHiddenFoldersLast(m_view->sortHiddenLast());
337 if (m_urlNavigatorVisualState) {
338 urlNavigator->setVisualState(*m_urlNavigatorVisualState.get());
339 m_urlNavigatorVisualState.reset();
340 }
341 urlNavigator->setActive(isActive());
342
343 // Url changes are still done via m_urlNavigator.
344 connect(urlNavigator, &DolphinUrlNavigator::urlChanged,
345 m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
346 connect(urlNavigator, &DolphinUrlNavigator::urlsDropped,
347 this, [=](const QUrl &destination, QDropEvent *event) {
348 m_view->dropUrls(destination, event, urlNavigator->dropWidget());
349 });
350 // Aside from these, only visual things need to be connected.
351 connect(m_view, &DolphinView::urlChanged,
352 urlNavigator, &DolphinUrlNavigator::setLocationUrl);
353 connect(urlNavigator, &DolphinUrlNavigator::activated,
354 this, &DolphinViewContainer::activate);
355
356 m_urlNavigatorConnected = urlNavigator;
357 }
358
359 void DolphinViewContainer::disconnectUrlNavigator()
360 {
361 if (!m_urlNavigatorConnected) {
362 return;
363 }
364
365 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlChanged,
366 m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
367 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlsDropped,
368 this, nullptr);
369 disconnect(m_view, &DolphinView::urlChanged,
370 m_urlNavigatorConnected, &DolphinUrlNavigator::setLocationUrl);
371 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::activated,
372 this, &DolphinViewContainer::activate);
373
374 m_urlNavigatorVisualState = m_urlNavigatorConnected->visualState();
375 m_urlNavigatorConnected = nullptr;
376 }
377
378 void DolphinViewContainer::setSelectionModeEnabled(bool enabled, KActionCollection *actionCollection, SelectionMode::BottomBar::Contents bottomBarContents)
379 {
380 const bool wasEnabled = m_view->selectionMode();
381 m_view->setSelectionModeEnabled(enabled);
382
383 if (!enabled) {
384 if (!wasEnabled) {
385 return; // nothing to do here
386 }
387 Q_CHECK_PTR(m_selectionModeTopBar); // there is no point in disabling selectionMode when it wasn't even enabled once.
388 Q_CHECK_PTR(m_selectionModeBottomBar);
389 m_selectionModeTopBar->setVisible(false, WithAnimation);
390 m_selectionModeBottomBar->setVisible(false, WithAnimation);
391 Q_EMIT selectionModeChanged(false);
392 return;
393 }
394
395 if (!m_selectionModeTopBar) {
396 // Changing the location will disable selection mode.
397 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlChanged, this, [this]() {
398 setSelectionModeEnabled(false);
399 });
400
401 m_selectionModeTopBar = new SelectionMode::TopBar(this); // will be created hidden
402 connect(m_selectionModeTopBar, &SelectionMode::TopBar::selectionModeLeavingRequested, this, [this]() {
403 setSelectionModeEnabled(false);
404 });
405 m_topLayout->addWidget(m_selectionModeTopBar, positionFor.selectionModeTopBar, 0);
406 }
407
408 if (!m_selectionModeBottomBar) {
409 m_selectionModeBottomBar = new SelectionMode::BottomBar(actionCollection, this);
410 connect(m_view, &DolphinView::selectionChanged, this, [this](const KFileItemList &selection) {
411 m_selectionModeBottomBar->slotSelectionChanged(selection, m_view->url());
412 });
413 connect(m_selectionModeBottomBar, &SelectionMode::BottomBar::error, this, [this](const QString &errorMessage) {
414 showErrorMessage(errorMessage);
415 });
416 connect(m_selectionModeBottomBar, &SelectionMode::BottomBar::selectionModeLeavingRequested, this, [this]() {
417 setSelectionModeEnabled(false);
418 });
419 m_topLayout->addWidget(m_selectionModeBottomBar, positionFor.selectionModeBottomBar, 0);
420 }
421 m_selectionModeBottomBar->resetContents(bottomBarContents);
422 if (bottomBarContents == SelectionMode::BottomBar::GeneralContents) {
423 m_selectionModeBottomBar->slotSelectionChanged(m_view->selectedItems(), m_view->url());
424 }
425
426 if (!wasEnabled) {
427 m_selectionModeTopBar->setVisible(true, WithAnimation);
428 m_selectionModeBottomBar->setVisible(true, WithAnimation);
429 Q_EMIT selectionModeChanged(true);
430 }
431 }
432
433 bool DolphinViewContainer::isSelectionModeEnabled() const
434 {
435 const bool isEnabled = m_view->selectionMode();
436 Q_ASSERT((!isEnabled
437 // We can't assert that the bars are invisible only because the selection mode is disabled because the hide animation might still be playing.
438 && (!m_selectionModeBottomBar || !m_selectionModeBottomBar->isEnabled() ||
439 !m_selectionModeBottomBar->isVisible() || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::PasteContents))
440 || ( isEnabled
441 && m_selectionModeTopBar && m_selectionModeTopBar->isVisible()
442 // The bottom bar is either visible or was hidden because it has nothing to show in GeneralContents mode e.g. because no items are selected.
443 && m_selectionModeBottomBar
444 && (m_selectionModeBottomBar->isVisible() || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::GeneralContents)));
445 return isEnabled;
446 }
447
448 void DolphinViewContainer::slotSplitTabDisabled()
449 {
450 if (m_selectionModeBottomBar) {
451 m_selectionModeBottomBar->slotSplitTabDisabled();
452 }
453 }
454
455
456 void DolphinViewContainer::showMessage(const QString& msg, MessageType type)
457 {
458 if (msg.isEmpty()) {
459 return;
460 }
461
462 m_messageWidget->setText(msg);
463
464 // TODO: wrap at arbitrary character positions once QLabel can do this
465 // https://bugreports.qt.io/browse/QTBUG-1276
466 m_messageWidget->setWordWrap(true);
467
468 switch (type) {
469 case Information: m_messageWidget->setMessageType(KMessageWidget::Information); break;
470 case Warning: m_messageWidget->setMessageType(KMessageWidget::Warning); break;
471 case Error: m_messageWidget->setMessageType(KMessageWidget::Error); break;
472 default:
473 Q_ASSERT(false);
474 break;
475 }
476
477 m_messageWidget->setWordWrap(false);
478 const int unwrappedWidth = m_messageWidget->sizeHint().width();
479 m_messageWidget->setWordWrap(unwrappedWidth > size().width());
480
481 if (m_messageWidget->isVisible()) {
482 m_messageWidget->hide();
483 }
484 m_messageWidget->animatedShow();
485 }
486
487 void DolphinViewContainer::readSettings()
488 {
489 // The startup settings should (only) get applied if they have been
490 // modified by the user. Otherwise keep the (possibly) different current
491 // setting of the filterbar.
492 if (GeneralSettings::modifiedStartupSettings()) {
493 setFilterBarVisible(GeneralSettings::filterBar());
494 }
495
496 m_view->readSettings();
497 m_statusBar->readSettings();
498 }
499
500 bool DolphinViewContainer::isFilterBarVisible() const
501 {
502 return m_filterBar->isVisible();
503 }
504
505 void DolphinViewContainer::setSearchModeEnabled(bool enabled)
506 {
507 m_searchBox->setVisible(enabled);
508
509 if (enabled) {
510 const QUrl& locationUrl = m_urlNavigator->locationUrl();
511 m_searchBox->fromSearchUrl(locationUrl);
512 }
513
514 if (enabled == isSearchModeEnabled()) {
515 if (enabled && !m_searchBox->hasFocus()) {
516 m_searchBox->setFocus();
517 m_searchBox->selectAll();
518 }
519 return;
520 }
521
522 if (!enabled) {
523 m_view->setViewPropertiesContext(QString());
524
525 // Restore the URL for the URL navigator. If Dolphin has been
526 // started with a search-URL, the home URL is used as fallback.
527 QUrl url = m_searchBox->searchPath();
528 if (url.isEmpty() || !url.isValid() || isSearchUrl(url)) {
529 url = Dolphin::homeUrl();
530 }
531 m_urlNavigatorConnected->setLocationUrl(url);
532 }
533
534 m_searchModeEnabled = enabled;
535
536 Q_EMIT searchModeEnabledChanged(enabled);
537 }
538
539 bool DolphinViewContainer::isSearchModeEnabled() const
540 {
541 return m_searchModeEnabled;
542 }
543
544 QString DolphinViewContainer::placesText() const
545 {
546 QString text;
547
548 if (isSearchModeEnabled()) {
549 text = i18n("Search for %1 in %2", m_searchBox->text(), m_searchBox->searchPath().fileName());
550 } else {
551 text = url().adjusted(QUrl::StripTrailingSlash).fileName();
552 if (text.isEmpty()) {
553 text = url().host();
554 }
555 if (text.isEmpty()) {
556 text = url().scheme();
557 }
558 }
559
560 return text;
561 }
562
563 void DolphinViewContainer::reload()
564 {
565 view()->reload();
566 m_messageWidget->hide();
567 }
568
569 QString DolphinViewContainer::captionWindowTitle() const
570 {
571 if (GeneralSettings::showFullPathInTitlebar() && !isSearchModeEnabled()) {
572 if (!url().isLocalFile()) {
573 return url().adjusted(QUrl::StripTrailingSlash).toString();
574 }
575 return url().adjusted(QUrl::StripTrailingSlash).path();
576 } else {
577 return DolphinViewContainer::caption();
578 }
579 }
580
581 QString DolphinViewContainer::caption() const
582 {
583 if (isSearchModeEnabled()) {
584 if (currentSearchText().isEmpty()){
585 return i18n("Search");
586 } else {
587 return i18n("Search for %1", currentSearchText());
588 }
589 }
590
591 KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel();
592 const QString pattern = url().adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/?");
593 const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, QRegularExpression::anchoredPattern(pattern), 1, Qt::MatchRegularExpression);
594
595 if (!matchedPlaces.isEmpty()) {
596 return placesModel->text(matchedPlaces.first());
597 }
598
599
600 if (!url().isLocalFile()) {
601 QUrl adjustedUrl = url().adjusted(QUrl::StripTrailingSlash);
602 QString caption;
603 if (!adjustedUrl.fileName().isEmpty()) {
604 caption = adjustedUrl.fileName();
605 } else if (!adjustedUrl.path().isEmpty() && adjustedUrl.path() != "/") {
606 caption = adjustedUrl.path();
607 } else if (!adjustedUrl.host().isEmpty()) {
608 caption = adjustedUrl.host();
609 } else {
610 caption = adjustedUrl.toString();
611 }
612 return caption;
613 }
614
615 QString fileName = url().adjusted(QUrl::StripTrailingSlash).fileName();
616 if (fileName.isEmpty()) {
617 fileName = '/';
618 }
619
620 return fileName;
621 }
622
623 void DolphinViewContainer::setUrl(const QUrl& newUrl)
624 {
625 if (newUrl != m_urlNavigator->locationUrl()) {
626 m_urlNavigator->setLocationUrl(newUrl);
627 }
628
629 #if HAVE_KACTIVITIES
630 m_activityResourceInstance->setUri(newUrl);
631 #endif
632 }
633
634 void DolphinViewContainer::setFilterBarVisible(bool visible)
635 {
636 Q_ASSERT(m_filterBar);
637 if (visible) {
638 m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly);
639 m_filterBar->show();
640 m_filterBar->setFocus();
641 m_filterBar->selectAll();
642 } else {
643 closeFilterBar();
644 }
645 }
646
647 void DolphinViewContainer::delayedStatusBarUpdate()
648 {
649 if (m_statusBarTimer->isActive() && (m_statusBarTimestamp.elapsed() > 2000)) {
650 // No update of the statusbar has been done during the last 2 seconds,
651 // although an update has been requested. Trigger an immediate update.
652 m_statusBarTimer->stop();
653 updateStatusBar();
654 } else {
655 // Invoke updateStatusBar() with a small delay. This assures that
656 // when a lot of delayedStatusBarUpdates() are done in a short time,
657 // no bottleneck is given.
658 m_statusBarTimer->start();
659 }
660 }
661
662 void DolphinViewContainer::updateStatusBar()
663 {
664 m_statusBarTimestamp.start();
665 m_view->requestStatusBarText();
666 }
667
668 void DolphinViewContainer::updateDirectoryLoadingProgress(int percent)
669 {
670 if (m_statusBar->progressText().isEmpty()) {
671 m_statusBar->setProgressText(i18nc("@info:progress", "Loading folder..."));
672 }
673 m_statusBar->setProgress(percent);
674 }
675
676 void DolphinViewContainer::updateDirectorySortingProgress(int percent)
677 {
678 if (m_statusBar->progressText().isEmpty()) {
679 m_statusBar->setProgressText(i18nc("@info:progress", "Sorting..."));
680 }
681 m_statusBar->setProgress(percent);
682 }
683
684 void DolphinViewContainer::slotDirectoryLoadingStarted()
685 {
686 if (isSearchUrl(url())) {
687 // Search KIO-slaves usually don't provide any progress information. Give
688 // a hint to the user that a searching is done:
689 updateStatusBar();
690 m_statusBar->setProgressText(i18nc("@info", "Searching..."));
691 m_statusBar->setProgress(-1);
692 } else {
693 // Trigger an undetermined progress indication. The progress
694 // information in percent will be triggered by the percent() signal
695 // of the directory lister later.
696 m_statusBar->setProgressText(QString());
697 updateDirectoryLoadingProgress(-1);
698 }
699 }
700
701 void DolphinViewContainer::slotDirectoryLoadingCompleted()
702 {
703 if (!m_statusBar->progressText().isEmpty()) {
704 m_statusBar->setProgressText(QString());
705 m_statusBar->setProgress(100);
706 }
707
708 if (isSearchUrl(url()) && m_view->itemsCount() == 0) {
709 // The dir lister has been completed on a Baloo-URI and no items have been found. Instead
710 // of showing the default status bar information ("0 items") a more helpful information is given:
711 m_statusBar->setText(i18nc("@info:status", "No items found."));
712 } else {
713 updateStatusBar();
714 }
715 }
716
717 void DolphinViewContainer::slotDirectoryLoadingCanceled()
718 {
719 if (!m_statusBar->progressText().isEmpty()) {
720 m_statusBar->setProgressText(QString());
721 m_statusBar->setProgress(100);
722 }
723
724 m_statusBar->setText(QString());
725 }
726
727 void DolphinViewContainer::slotUrlIsFileError(const QUrl& url)
728 {
729 const KFileItem item(url);
730
731 // Find out if the file can be opened in the view (for example, this is the
732 // case if the file is an archive). The mime type must be known for that.
733 item.determineMimeType();
734 const QUrl& folderUrl = DolphinView::openItemAsFolderUrl(item, true);
735 if (!folderUrl.isEmpty()) {
736 setUrl(folderUrl);
737 } else {
738 slotItemActivated(item);
739 }
740 }
741
742 void DolphinViewContainer::slotItemActivated(const KFileItem &item)
743 {
744 // It is possible to activate items on inactive views by
745 // drag & drop operations. Assure that activating an item always
746 // results in an active view.
747 m_view->setActive(true);
748
749 const QUrl& url = DolphinView::openItemAsFolderUrl(item, GeneralSettings::browseThroughArchives());
750 if (!url.isEmpty()) {
751 const auto modifiers = QGuiApplication::keyboardModifiers();
752 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
753 if (modifiers & Qt::ControlModifier && modifiers & Qt::ShiftModifier) {
754 Q_EMIT activeTabRequested(url);
755 } else if (modifiers & Qt::ControlModifier) {
756 Q_EMIT tabRequested(url);
757 } else if (modifiers & Qt::ShiftModifier) {
758 Dolphin::openNewWindow({KFilePlacesModel::convertedUrl(url)}, this);
759 } else {
760 setUrl(url);
761 }
762 return;
763 }
764
765 KIO::OpenUrlJob *job = new KIO::OpenUrlJob(item.targetUrl(), item.mimetype());
766 #if KIO_VERSION >= QT_VERSION_CHECK(5, 98, 0)
767 job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, this));
768 #else
769 job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, this));
770 #endif
771 job->setShowOpenOrExecuteDialog(true);
772 connect(job, &KIO::OpenUrlJob::finished, this, &DolphinViewContainer::slotOpenUrlFinished);
773 job->start();
774 }
775
776 void DolphinViewContainer::slotItemsActivated(const KFileItemList& items)
777 {
778 Q_ASSERT(items.count() >= 2);
779
780 KFileItemActions fileItemActions(this);
781 fileItemActions.runPreferredApplications(items);
782 }
783
784 void DolphinViewContainer::showItemInfo(const KFileItem& item)
785 {
786 if (item.isNull()) {
787 m_statusBar->resetToDefaultText();
788 } else {
789 m_statusBar->setText(item.getStatusBarInfo());
790 }
791 }
792
793 void DolphinViewContainer::closeFilterBar()
794 {
795 m_filterBar->closeFilterBar();
796 m_view->setFocus();
797 Q_EMIT showFilterBarChanged(false);
798 }
799
800 void DolphinViewContainer::clearFilterBar()
801 {
802 m_filterBar->clearIfUnlocked();
803 }
804
805 void DolphinViewContainer::setNameFilter(const QString& nameFilter)
806 {
807 m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly);
808 m_view->setNameFilter(nameFilter);
809 delayedStatusBarUpdate();
810 }
811
812 void DolphinViewContainer::activate()
813 {
814 setActive(true);
815 }
816
817 void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl&)
818 {
819 saveViewState();
820 }
821
822 void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl& url)
823 {
824 if (m_urlNavigatorConnected) {
825 m_urlNavigatorConnected->slotReturnPressed();
826 }
827
828 if (KProtocolManager::supportsListing(url)) {
829 setSearchModeEnabled(isSearchUrl(url));
830 m_view->setUrl(url);
831 tryRestoreViewState();
832
833 if (m_autoGrabFocus && isActive() && !isSearchUrl(url)) {
834 // When an URL has been entered, the view should get the focus.
835 // The focus must be requested asynchronously, as changing the URL might create
836 // a new view widget.
837 QTimer::singleShot(0, this, &DolphinViewContainer::requestFocus);
838 }
839 } else if (KProtocolManager::isSourceProtocol(url)) {
840 if (url.scheme().startsWith(QLatin1String("http"))) {
841 showMessage(i18nc("@info:status", // krazy:exclude=qmethods
842 "Dolphin does not support web pages, the web browser has been launched"),
843 Information);
844 } else {
845 showMessage(i18nc("@info:status",
846 "Protocol not supported by Dolphin, default application has been launched"),
847 Information);
848 }
849
850 QDesktopServices::openUrl(url);
851 redirect(QUrl(), m_urlNavigator->locationUrl(1));
852 } else {
853 showMessage(i18nc("@info:status", "Invalid protocol"), Error);
854 m_urlNavigator->goBack();
855 }
856 }
857
858 void DolphinViewContainer::slotUrlSelectionRequested(const QUrl& url)
859 {
860 m_view->markUrlsAsSelected({url});
861 m_view->markUrlAsCurrent(url); // makes the item scroll into view
862 }
863
864 void DolphinViewContainer::disableUrlNavigatorSelectionRequests()
865 {
866 disconnect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested,
867 this, &DolphinViewContainer::slotUrlSelectionRequested);
868 }
869
870 void DolphinViewContainer::enableUrlNavigatorSelectionRequests()
871 {
872 connect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested,
873 this, &DolphinViewContainer::slotUrlSelectionRequested);
874 }
875
876 void DolphinViewContainer::redirect(const QUrl& oldUrl, const QUrl& newUrl)
877 {
878 Q_UNUSED(oldUrl)
879 const bool block = m_urlNavigator->signalsBlocked();
880 m_urlNavigator->blockSignals(true);
881
882 // Assure that the location state is reset for redirection URLs. This
883 // allows to skip redirection URLs when going back or forward in the
884 // URL history.
885 m_urlNavigator->saveLocationState(QByteArray());
886 m_urlNavigator->setLocationUrl(newUrl);
887 setSearchModeEnabled(isSearchUrl(newUrl));
888
889 m_urlNavigator->blockSignals(block);
890 }
891
892 void DolphinViewContainer::requestFocus()
893 {
894 m_view->setFocus();
895 }
896
897 void DolphinViewContainer::startSearching()
898 {
899 Q_CHECK_PTR(m_urlNavigatorConnected);
900 const QUrl url = m_searchBox->urlForSearching();
901 if (url.isValid() && !url.isEmpty()) {
902 m_view->setViewPropertiesContext(QStringLiteral("search"));
903 m_urlNavigatorConnected->setLocationUrl(url);
904 }
905 }
906
907 void DolphinViewContainer::closeSearchBox()
908 {
909 setSearchModeEnabled(false);
910 }
911
912 void DolphinViewContainer::stopDirectoryLoading()
913 {
914 m_view->stopLoading();
915 m_statusBar->setProgress(100);
916 }
917
918 void DolphinViewContainer::slotStatusBarZoomLevelChanged(int zoomLevel)
919 {
920 m_view->setZoomLevel(zoomLevel);
921 }
922
923 void DolphinViewContainer::showErrorMessage(const QString& msg)
924 {
925 showMessage(msg, Error);
926 }
927
928 void DolphinViewContainer::slotPlacesModelChanged()
929 {
930 if (!GeneralSettings::showFullPathInTitlebar() && !isSearchModeEnabled()) {
931 Q_EMIT captionChanged();
932 }
933 }
934
935 void DolphinViewContainer::slotHiddenFilesShownChanged(bool showHiddenFiles)
936 {
937 if (m_urlNavigatorConnected) {
938 m_urlNavigatorConnected->setShowHiddenFolders(showHiddenFiles);
939 }
940 }
941
942 void DolphinViewContainer::slotSortHiddenLastChanged(bool hiddenLast)
943 {
944 if (m_urlNavigatorConnected) {
945 m_urlNavigatorConnected->setSortHiddenFoldersLast(hiddenLast);
946 }
947 }
948
949 void DolphinViewContainer::slotCurrentDirectoryRemoved()
950 {
951 const QString location(url().toDisplayString(QUrl::PreferLocalFile));
952 if (url().isLocalFile()) {
953 const QString dirPath = url().toLocalFile();
954 const QString newPath = getNearestExistingAncestorOfPath(dirPath);
955 const QUrl newUrl = QUrl::fromLocalFile(newPath);
956 setUrl(newUrl);
957 }
958
959 showMessage(xi18n("Current location changed, <filename>%1</filename> is no longer accessible.", location), Warning);
960 }
961
962 void DolphinViewContainer::slotOpenUrlFinished(KJob *job)
963 {
964 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
965 showErrorMessage(job->errorString());
966 }
967 }
968
969 bool DolphinViewContainer::isSearchUrl(const QUrl& url) const
970 {
971 return url.scheme().contains(QLatin1String("search"));
972 }
973
974 void DolphinViewContainer::saveViewState()
975 {
976 QByteArray locationState;
977 QDataStream stream(&locationState, QIODevice::WriteOnly);
978 m_view->saveState(stream);
979 m_urlNavigator->saveLocationState(locationState);
980 }
981
982 void DolphinViewContainer::tryRestoreViewState()
983 {
984 QByteArray locationState = m_urlNavigator->locationState();
985 if (!locationState.isEmpty()) {
986 QDataStream stream(&locationState, QIODevice::ReadOnly);
987 m_view->restoreState(stream);
988 }
989 }
990
991 QString DolphinViewContainer::getNearestExistingAncestorOfPath(const QString& path) const
992 {
993 QDir dir(path);
994 do {
995 dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral(".."))));
996 }
997 while (!dir.exists() && !dir.isRoot());
998
999 return dir.exists() ? dir.path() : QString{};
1000 }