]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphinviewcontainer.cpp
Remove deprecated, ifdef'd code for old KIO versions
[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/JobUiDelegateFactory>
26 #include <KIO/OpenUrlJob>
27 #include <KLocalizedString>
28 #include <KMessageWidget>
29 #include <KProtocolManager>
30 #include <KShell>
31
32 #include <QDesktopServices>
33 #include <QDropEvent>
34 #include <QGridLayout>
35 #include <QGuiApplication>
36 #include <QRegularExpression>
37 #include <QTimer>
38 #include <QUrl>
39
40 // An overview of the widgets contained by this ViewContainer
41 struct LayoutStructure {
42 int searchBox = 0;
43 int messageWidget = 1;
44 int selectionModeTopBar = 2;
45 int view = 3;
46 int selectionModeBottomBar = 4;
47 int filterBar = 5;
48 int statusBar = 6;
49 };
50 constexpr LayoutStructure positionFor;
51
52 DolphinViewContainer::DolphinViewContainer(const QUrl &url, QWidget *parent)
53 : QWidget(parent)
54 , m_topLayout(nullptr)
55 , m_urlNavigator{new DolphinUrlNavigator(url)}
56 , m_urlNavigatorConnected{nullptr}
57 , m_searchBox(nullptr)
58 , m_searchModeEnabled(false)
59 , m_messageWidget(nullptr)
60 , m_selectionModeTopBar{nullptr}
61 , m_view(nullptr)
62 , m_filterBar(nullptr)
63 , m_selectionModeBottomBar{nullptr}
64 , m_statusBar(nullptr)
65 , m_statusBarTimer(nullptr)
66 , m_statusBarTimestamp()
67 , m_autoGrabFocus(true)
68 #if HAVE_KACTIVITIES
69 , m_activityResourceInstance(nullptr)
70 #endif
71 {
72 hide();
73
74 m_topLayout = new QGridLayout(this);
75 m_topLayout->setSpacing(0);
76 m_topLayout->setContentsMargins(0, 0, 0, 0);
77
78 m_searchBox = new DolphinSearchBox(this);
79 m_searchBox->hide();
80 connect(m_searchBox, &DolphinSearchBox::activated, this, &DolphinViewContainer::activate);
81 connect(m_searchBox, &DolphinSearchBox::closeRequest, this, &DolphinViewContainer::closeSearchBox);
82 connect(m_searchBox, &DolphinSearchBox::searchRequest, this, &DolphinViewContainer::startSearching);
83 connect(m_searchBox, &DolphinSearchBox::focusViewRequest, this, &DolphinViewContainer::requestFocus);
84 m_searchBox->setWhatsThis(xi18nc("@info:whatsthis findbar",
85 "<para>This helps you find files and folders. Enter a <emphasis>"
86 "search term</emphasis> and specify search settings with the "
87 "buttons at the bottom:<list><item>Filename/Content: "
88 "Does the item you are looking for contain the search terms "
89 "within its filename or its contents?<nl/>The contents of images, "
90 "audio files and videos will not be searched.</item><item>"
91 "From Here/Everywhere: Do you want to search in this "
92 "folder and its sub-folders or everywhere?</item><item>"
93 "More Options: Click this to search by media type, access "
94 "time or rating.</item><item>More Search Tools: Install other "
95 "means to find an item.</item></list></para>"));
96
97 m_messageWidget = new KMessageWidget(this);
98 m_messageWidget->setCloseButtonVisible(true);
99 m_messageWidget->hide();
100
101 #ifndef Q_OS_WIN
102 if (getuid() == 0) {
103 // We must be logged in as the root user; show a big scary warning
104 showMessage(i18n("Running Dolphin as root can be dangerous. Please be careful."), Warning);
105 }
106 #endif
107
108 // Initialize filter bar
109 m_filterBar = new FilterBar(this);
110 m_filterBar->setVisible(GeneralSettings::filterBar());
111
112 connect(m_filterBar, &FilterBar::filterChanged, this, &DolphinViewContainer::setNameFilter);
113 connect(m_filterBar, &FilterBar::closeRequest, this, &DolphinViewContainer::closeFilterBar);
114 connect(m_filterBar, &FilterBar::focusViewRequest, this, &DolphinViewContainer::requestFocus);
115
116 // Initialize the main view
117 m_view = new DolphinView(url, this);
118 connect(m_view, &DolphinView::urlChanged, m_filterBar, &FilterBar::clearIfUnlocked);
119 connect(m_view, &DolphinView::urlChanged, m_messageWidget, &KMessageWidget::hide);
120 // m_urlNavigator stays in sync with m_view's location changes and
121 // keeps track of them so going back and forth in the history works.
122 connect(m_view, &DolphinView::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
123 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationChanged);
124 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlAboutToBeChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged);
125 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
126 connect(m_view, &DolphinView::writeStateChanged, this, &DolphinViewContainer::writeStateChanged);
127 connect(m_view, &DolphinView::requestItemInfo, this, &DolphinViewContainer::showItemInfo);
128 connect(m_view, &DolphinView::itemActivated, this, &DolphinViewContainer::slotItemActivated);
129 connect(m_view, &DolphinView::itemsActivated, this, &DolphinViewContainer::slotItemsActivated);
130 connect(m_view, &DolphinView::redirection, this, &DolphinViewContainer::redirect);
131 connect(m_view, &DolphinView::directoryLoadingStarted, this, &DolphinViewContainer::slotDirectoryLoadingStarted);
132 connect(m_view, &DolphinView::directoryLoadingCompleted, this, &DolphinViewContainer::slotDirectoryLoadingCompleted);
133 connect(m_view, &DolphinView::directoryLoadingCanceled, this, &DolphinViewContainer::slotDirectoryLoadingCanceled);
134 connect(m_view, &DolphinView::itemCountChanged, this, &DolphinViewContainer::delayedStatusBarUpdate);
135 connect(m_view, &DolphinView::directoryLoadingProgress, this, &DolphinViewContainer::updateDirectoryLoadingProgress);
136 connect(m_view, &DolphinView::directorySortingProgress, this, &DolphinViewContainer::updateDirectorySortingProgress);
137 connect(m_view, &DolphinView::selectionChanged, this, &DolphinViewContainer::delayedStatusBarUpdate);
138 connect(m_view, &DolphinView::errorMessage, this, &DolphinViewContainer::showErrorMessage);
139 connect(m_view, &DolphinView::urlIsFileError, this, &DolphinViewContainer::slotUrlIsFileError);
140 connect(m_view, &DolphinView::activated, this, &DolphinViewContainer::activate);
141 connect(m_view, &DolphinView::hiddenFilesShownChanged, this, &DolphinViewContainer::slotHiddenFilesShownChanged);
142 connect(m_view, &DolphinView::sortHiddenLastChanged, this, &DolphinViewContainer::slotSortHiddenLastChanged);
143 connect(m_view, &DolphinView::currentDirectoryRemoved, this, &DolphinViewContainer::slotCurrentDirectoryRemoved);
144
145 // Initialize status bar
146 m_statusBar = new DolphinStatusBar(this);
147 m_statusBar->setUrl(m_view->url());
148 m_statusBar->setZoomLevel(m_view->zoomLevel());
149 connect(m_view, &DolphinView::urlChanged, m_statusBar, &DolphinStatusBar::setUrl);
150 connect(m_view, &DolphinView::zoomLevelChanged, m_statusBar, &DolphinStatusBar::setZoomLevel);
151 connect(m_view, &DolphinView::infoMessage, m_statusBar, &DolphinStatusBar::setText);
152 connect(m_view, &DolphinView::operationCompletedMessage, m_statusBar, &DolphinStatusBar::setText);
153 connect(m_view, &DolphinView::statusBarTextChanged, m_statusBar, &DolphinStatusBar::setDefaultText);
154 connect(m_view, &DolphinView::statusBarTextChanged, m_statusBar, &DolphinStatusBar::resetToDefaultText);
155 connect(m_statusBar, &DolphinStatusBar::stopPressed, this, &DolphinViewContainer::stopDirectoryLoading);
156 connect(m_statusBar, &DolphinStatusBar::zoomLevelChanged, this, &DolphinViewContainer::slotStatusBarZoomLevelChanged);
157
158 m_statusBarTimer = new QTimer(this);
159 m_statusBarTimer->setSingleShot(true);
160 m_statusBarTimer->setInterval(300);
161 connect(m_statusBarTimer, &QTimer::timeout, this, &DolphinViewContainer::updateStatusBar);
162
163 KIO::FileUndoManager *undoManager = KIO::FileUndoManager::self();
164 connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinViewContainer::delayedStatusBarUpdate);
165
166 m_topLayout->addWidget(m_searchBox, positionFor.searchBox, 0);
167 m_topLayout->addWidget(m_messageWidget, positionFor.messageWidget, 0);
168 m_topLayout->addWidget(m_view, positionFor.view, 0);
169 m_topLayout->addWidget(m_filterBar, positionFor.filterBar, 0);
170 m_topLayout->addWidget(m_statusBar, positionFor.statusBar, 0);
171
172 setSearchModeEnabled(isSearchUrl(url));
173
174 connect(DetailsModeSettings::self(), &KCoreConfigSkeleton::configChanged, this, [=]() {
175 if (view()->viewMode() == DolphinView::Mode::DetailsView) {
176 view()->reload();
177 }
178 });
179
180 KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel();
181 connect(placesModel, &KFilePlacesModel::dataChanged, this, &DolphinViewContainer::slotPlacesModelChanged);
182 connect(placesModel, &KFilePlacesModel::rowsInserted, this, &DolphinViewContainer::slotPlacesModelChanged);
183 connect(placesModel, &KFilePlacesModel::rowsRemoved, this, &DolphinViewContainer::slotPlacesModelChanged);
184
185 connect(this, &DolphinViewContainer::searchModeEnabledChanged, this, &DolphinViewContainer::captionChanged);
186
187 // Initialize kactivities resource instance
188
189 #if HAVE_KACTIVITIES
190 m_activityResourceInstance = new KActivities::ResourceInstance(window()->winId(), url);
191 m_activityResourceInstance->setParent(this);
192 #endif
193 }
194
195 DolphinViewContainer::~DolphinViewContainer()
196 {
197 }
198
199 QUrl DolphinViewContainer::url() const
200 {
201 return m_view->url();
202 }
203
204 KFileItem DolphinViewContainer::rootItem() const
205 {
206 return m_view->rootItem();
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 job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, this));
723 job->setShowOpenOrExecuteDialog(true);
724 connect(job, &KIO::OpenUrlJob::finished, this, &DolphinViewContainer::slotOpenUrlFinished);
725 job->start();
726 }
727
728 void DolphinViewContainer::slotItemsActivated(const KFileItemList &items)
729 {
730 Q_ASSERT(items.count() >= 2);
731
732 KFileItemActions fileItemActions(this);
733 fileItemActions.runPreferredApplications(items);
734 }
735
736 void DolphinViewContainer::showItemInfo(const KFileItem &item)
737 {
738 if (item.isNull()) {
739 m_statusBar->resetToDefaultText();
740 } else {
741 m_statusBar->setText(item.getStatusBarInfo());
742 }
743 }
744
745 void DolphinViewContainer::closeFilterBar()
746 {
747 m_filterBar->closeFilterBar();
748 m_view->setFocus();
749 Q_EMIT showFilterBarChanged(false);
750 }
751
752 void DolphinViewContainer::clearFilterBar()
753 {
754 m_filterBar->clearIfUnlocked();
755 }
756
757 void DolphinViewContainer::setNameFilter(const QString &nameFilter)
758 {
759 m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly);
760 m_view->setNameFilter(nameFilter);
761 delayedStatusBarUpdate();
762 }
763
764 void DolphinViewContainer::activate()
765 {
766 setActive(true);
767 }
768
769 void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl &)
770 {
771 saveViewState();
772 }
773
774 void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl &url)
775 {
776 if (m_urlNavigatorConnected) {
777 m_urlNavigatorConnected->slotReturnPressed();
778 }
779
780 if (KProtocolManager::supportsListing(url)) {
781 setSearchModeEnabled(isSearchUrl(url));
782 m_view->setUrl(url);
783 tryRestoreViewState();
784
785 if (m_autoGrabFocus && isActive() && !isSearchUrl(url)) {
786 // When an URL has been entered, the view should get the focus.
787 // The focus must be requested asynchronously, as changing the URL might create
788 // a new view widget.
789 QTimer::singleShot(0, this, &DolphinViewContainer::requestFocus);
790 }
791 } else if (KProtocolManager::isSourceProtocol(url)) {
792 if (url.scheme().startsWith(QLatin1String("http"))) {
793 showMessage(i18nc("@info:status", // krazy:exclude=qmethods
794 "Dolphin does not support web pages, the web browser has been launched"),
795 Information);
796 } else {
797 showMessage(i18nc("@info:status", "Protocol not supported by Dolphin, default application has been launched"), Information);
798 }
799
800 QDesktopServices::openUrl(url);
801 redirect(QUrl(), m_urlNavigator->locationUrl(1));
802 } else {
803 showMessage(i18nc("@info:status", "Invalid protocol"), Error);
804 m_urlNavigator->goBack();
805 }
806 }
807
808 void DolphinViewContainer::slotUrlSelectionRequested(const QUrl &url)
809 {
810 m_view->markUrlsAsSelected({url});
811 m_view->markUrlAsCurrent(url); // makes the item scroll into view
812 }
813
814 void DolphinViewContainer::disableUrlNavigatorSelectionRequests()
815 {
816 disconnect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
817 }
818
819 void DolphinViewContainer::enableUrlNavigatorSelectionRequests()
820 {
821 connect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
822 }
823
824 void DolphinViewContainer::redirect(const QUrl &oldUrl, const QUrl &newUrl)
825 {
826 Q_UNUSED(oldUrl)
827 const bool block = m_urlNavigator->signalsBlocked();
828 m_urlNavigator->blockSignals(true);
829
830 // Assure that the location state is reset for redirection URLs. This
831 // allows to skip redirection URLs when going back or forward in the
832 // URL history.
833 m_urlNavigator->saveLocationState(QByteArray());
834 m_urlNavigator->setLocationUrl(newUrl);
835 setSearchModeEnabled(isSearchUrl(newUrl));
836
837 m_urlNavigator->blockSignals(block);
838 }
839
840 void DolphinViewContainer::requestFocus()
841 {
842 m_view->setFocus();
843 }
844
845 void DolphinViewContainer::startSearching()
846 {
847 Q_CHECK_PTR(m_urlNavigatorConnected);
848 const QUrl url = m_searchBox->urlForSearching();
849 if (url.isValid() && !url.isEmpty()) {
850 m_view->setViewPropertiesContext(QStringLiteral("search"));
851 m_urlNavigatorConnected->setLocationUrl(url);
852 }
853 }
854
855 void DolphinViewContainer::closeSearchBox()
856 {
857 setSearchModeEnabled(false);
858 }
859
860 void DolphinViewContainer::stopDirectoryLoading()
861 {
862 m_view->stopLoading();
863 m_statusBar->setProgress(100);
864 }
865
866 void DolphinViewContainer::slotStatusBarZoomLevelChanged(int zoomLevel)
867 {
868 m_view->setZoomLevel(zoomLevel);
869 }
870
871 void DolphinViewContainer::showErrorMessage(const QString &msg)
872 {
873 showMessage(msg, Error);
874 }
875
876 void DolphinViewContainer::slotPlacesModelChanged()
877 {
878 if (!GeneralSettings::showFullPathInTitlebar() && !isSearchModeEnabled()) {
879 Q_EMIT captionChanged();
880 }
881 }
882
883 void DolphinViewContainer::slotHiddenFilesShownChanged(bool showHiddenFiles)
884 {
885 if (m_urlNavigatorConnected) {
886 m_urlNavigatorConnected->setShowHiddenFolders(showHiddenFiles);
887 }
888 }
889
890 void DolphinViewContainer::slotSortHiddenLastChanged(bool hiddenLast)
891 {
892 if (m_urlNavigatorConnected) {
893 m_urlNavigatorConnected->setSortHiddenFoldersLast(hiddenLast);
894 }
895 }
896
897 void DolphinViewContainer::slotCurrentDirectoryRemoved()
898 {
899 const QString location(url().toDisplayString(QUrl::PreferLocalFile));
900 if (url().isLocalFile()) {
901 const QString dirPath = url().toLocalFile();
902 const QString newPath = getNearestExistingAncestorOfPath(dirPath);
903 const QUrl newUrl = QUrl::fromLocalFile(newPath);
904 setUrl(newUrl);
905 }
906
907 showMessage(xi18n("Current location changed, <filename>%1</filename> is no longer accessible.", location), Warning);
908 }
909
910 void DolphinViewContainer::slotOpenUrlFinished(KJob *job)
911 {
912 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
913 showErrorMessage(job->errorString());
914 }
915 }
916
917 bool DolphinViewContainer::isSearchUrl(const QUrl &url) const
918 {
919 return url.scheme().contains(QLatin1String("search"));
920 }
921
922 void DolphinViewContainer::saveViewState()
923 {
924 QByteArray locationState;
925 QDataStream stream(&locationState, QIODevice::WriteOnly);
926 m_view->saveState(stream);
927 m_urlNavigator->saveLocationState(locationState);
928 }
929
930 void DolphinViewContainer::tryRestoreViewState()
931 {
932 QByteArray locationState = m_urlNavigator->locationState();
933 if (!locationState.isEmpty()) {
934 QDataStream stream(&locationState, QIODevice::ReadOnly);
935 m_view->restoreState(stream);
936 }
937 }
938
939 QString DolphinViewContainer::getNearestExistingAncestorOfPath(const QString &path) const
940 {
941 QDir dir(path);
942 do {
943 dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral(".."))));
944 } while (!dir.exists() && !dir.isRoot());
945
946 return dir.exists() ? dir.path() : QString{};
947 }