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