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