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