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