]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphinviewcontainer.cpp
Merge branch 'master' into kf6
[dolphin.git] / src / dolphinviewcontainer.cpp
1 /*
2 * SPDX-FileCopyrightText: 2007 Peter Penz <peter.penz19@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "dolphinviewcontainer.h"
8
9 #include "dolphin_compactmodesettings.h"
10 #include "dolphin_contentdisplaysettings.h"
11 #include "dolphin_detailsmodesettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphin_iconsmodesettings.h"
14 #include "dolphindebug.h"
15 #include "dolphinplacesmodelsingleton.h"
16 #include "filterbar/filterbar.h"
17 #include "global.h"
18 #include "search/dolphinsearchbox.h"
19 #include "selectionmode/topbar.h"
20 #include "statusbar/dolphinstatusbar.h"
21
22 #include <KActionCollection>
23 #if HAVE_KACTIVITIES
24 #include <KActivities/ResourceInstance>
25 #endif
26 #include <KFileItemActions>
27 #include <KFilePlacesModel>
28 #include <KIO/JobUiDelegateFactory>
29 #include <KIO/OpenUrlJob>
30 #include <KLocalizedString>
31 #include <KMessageWidget>
32 #include <KProtocolManager>
33 #include <KShell>
34
35 #include <QApplication>
36 #include <QDesktopServices>
37 #include <QDropEvent>
38 #include <QGridLayout>
39 #include <QGuiApplication>
40 #include <QRegularExpression>
41 #include <QTimer>
42 #include <QUrl>
43
44 // An overview of the widgets contained by this ViewContainer
45 struct LayoutStructure {
46 int searchBox = 0;
47 int messageWidget = 1;
48 int selectionModeTopBar = 2;
49 int view = 3;
50 int selectionModeBottomBar = 4;
51 int filterBar = 5;
52 int statusBar = 6;
53 };
54 constexpr LayoutStructure positionFor;
55
56 DolphinViewContainer::DolphinViewContainer(const QUrl &url, QWidget *parent)
57 : QWidget(parent)
58 , m_topLayout(nullptr)
59 , m_urlNavigator{new DolphinUrlNavigator(url)}
60 , m_urlNavigatorConnected{nullptr}
61 , m_searchBox(nullptr)
62 , m_searchModeEnabled(false)
63 , m_messageWidget(nullptr)
64 , m_selectionModeTopBar{nullptr}
65 , m_view(nullptr)
66 , m_filterBar(nullptr)
67 , m_selectionModeBottomBar{nullptr}
68 , m_statusBar(nullptr)
69 , m_statusBarTimer(nullptr)
70 , m_statusBarTimestamp()
71 , m_autoGrabFocus(true)
72 #if HAVE_KACTIVITIES
73 , m_activityResourceInstance(nullptr)
74 #endif
75 {
76 hide();
77
78 m_topLayout = new QGridLayout(this);
79 m_topLayout->setSpacing(0);
80 m_topLayout->setContentsMargins(0, 0, 0, 0);
81
82 m_searchBox = new DolphinSearchBox(this);
83 m_searchBox->hide();
84 connect(m_searchBox, &DolphinSearchBox::activated, this, &DolphinViewContainer::activate);
85 connect(m_searchBox, &DolphinSearchBox::closeRequest, this, &DolphinViewContainer::closeSearchBox);
86 connect(m_searchBox, &DolphinSearchBox::searchRequest, this, &DolphinViewContainer::startSearching);
87 connect(m_searchBox, &DolphinSearchBox::focusViewRequest, this, &DolphinViewContainer::requestFocus);
88 m_searchBox->setWhatsThis(xi18nc("@info:whatsthis findbar",
89 "<para>This helps you find files and folders. Enter a <emphasis>"
90 "search term</emphasis> and specify search settings with the "
91 "buttons at the bottom:<list><item>Filename/Content: "
92 "Does the item you are looking for contain the search terms "
93 "within its filename or its contents?<nl/>The contents of images, "
94 "audio files and videos will not be searched.</item><item>"
95 "From Here/Everywhere: Do you want to search in this "
96 "folder and its sub-folders or everywhere?</item><item>"
97 "More Options: Click this to search by media type, access "
98 "time or rating.</item><item>More Search Tools: Install other "
99 "means to find an item.</item></list></para>"));
100
101 m_messageWidget = new KMessageWidget(this);
102 m_messageWidget->setCloseButtonVisible(true);
103 m_messageWidget->hide();
104
105 #ifndef Q_OS_WIN
106 if (getuid() == 0) {
107 // We must be logged in as the root user; show a big scary warning
108 showMessage(i18n("Running Dolphin as root can be dangerous. Please be careful."), Warning);
109 }
110 #endif
111
112 // Initialize filter bar
113 m_filterBar = new FilterBar(this);
114 m_filterBar->setVisible(GeneralSettings::filterBar());
115
116 connect(m_filterBar, &FilterBar::filterChanged, this, &DolphinViewContainer::setNameFilter);
117 connect(m_filterBar, &FilterBar::closeRequest, this, &DolphinViewContainer::closeFilterBar);
118 connect(m_filterBar, &FilterBar::focusViewRequest, this, &DolphinViewContainer::requestFocus);
119
120 // Initialize the main view
121 m_view = new DolphinView(url, this);
122 connect(m_view, &DolphinView::urlChanged, m_filterBar, &FilterBar::clearIfUnlocked);
123 connect(m_view, &DolphinView::urlChanged, m_messageWidget, &KMessageWidget::hide);
124 // m_urlNavigator stays in sync with m_view's location changes and
125 // keeps track of them so going back and forth in the history works.
126 connect(m_view, &DolphinView::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
127 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationChanged);
128 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlAboutToBeChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged);
129 connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
130 connect(m_view, &DolphinView::writeStateChanged, this, &DolphinViewContainer::writeStateChanged);
131 connect(m_view, &DolphinView::requestItemInfo, this, &DolphinViewContainer::showItemInfo);
132 connect(m_view, &DolphinView::itemActivated, this, &DolphinViewContainer::slotItemActivated);
133 connect(m_view, &DolphinView::itemsActivated, this, &DolphinViewContainer::slotItemsActivated);
134 connect(m_view, &DolphinView::redirection, this, &DolphinViewContainer::redirect);
135 connect(m_view, &DolphinView::directoryLoadingStarted, this, &DolphinViewContainer::slotDirectoryLoadingStarted);
136 connect(m_view, &DolphinView::directoryLoadingCompleted, this, &DolphinViewContainer::slotDirectoryLoadingCompleted);
137 connect(m_view, &DolphinView::directoryLoadingCanceled, this, &DolphinViewContainer::slotDirectoryLoadingCanceled);
138 connect(m_view, &DolphinView::itemCountChanged, this, &DolphinViewContainer::delayedStatusBarUpdate);
139 connect(m_view, &DolphinView::directoryLoadingProgress, this, &DolphinViewContainer::updateDirectoryLoadingProgress);
140 connect(m_view, &DolphinView::directorySortingProgress, this, &DolphinViewContainer::updateDirectorySortingProgress);
141 connect(m_view, &DolphinView::selectionChanged, this, &DolphinViewContainer::delayedStatusBarUpdate);
142 connect(m_view, &DolphinView::errorMessage, this, &DolphinViewContainer::showErrorMessage);
143 connect(m_view, &DolphinView::urlIsFileError, this, &DolphinViewContainer::slotUrlIsFileError);
144 connect(m_view, &DolphinView::activated, this, &DolphinViewContainer::activate);
145 connect(m_view, &DolphinView::hiddenFilesShownChanged, this, &DolphinViewContainer::slotHiddenFilesShownChanged);
146 connect(m_view, &DolphinView::sortHiddenLastChanged, this, &DolphinViewContainer::slotSortHiddenLastChanged);
147 connect(m_view, &DolphinView::currentDirectoryRemoved, this, &DolphinViewContainer::slotCurrentDirectoryRemoved);
148
149 // Initialize status bar
150 m_statusBar = new DolphinStatusBar(this);
151 m_statusBar->setUrl(m_view->url());
152 m_statusBar->setZoomLevel(m_view->zoomLevel());
153 connect(m_view, &DolphinView::urlChanged, m_statusBar, &DolphinStatusBar::setUrl);
154 connect(m_view, &DolphinView::zoomLevelChanged, m_statusBar, &DolphinStatusBar::setZoomLevel);
155 connect(m_view, &DolphinView::infoMessage, m_statusBar, &DolphinStatusBar::setText);
156 connect(m_view, &DolphinView::operationCompletedMessage, m_statusBar, &DolphinStatusBar::setText);
157 connect(m_view, &DolphinView::statusBarTextChanged, m_statusBar, &DolphinStatusBar::setDefaultText);
158 connect(m_view, &DolphinView::statusBarTextChanged, m_statusBar, &DolphinStatusBar::resetToDefaultText);
159 connect(m_statusBar, &DolphinStatusBar::stopPressed, this, &DolphinViewContainer::stopDirectoryLoading);
160 connect(m_statusBar, &DolphinStatusBar::zoomLevelChanged, this, &DolphinViewContainer::slotStatusBarZoomLevelChanged);
161
162 m_statusBarTimer = new QTimer(this);
163 m_statusBarTimer->setSingleShot(true);
164 m_statusBarTimer->setInterval(300);
165 connect(m_statusBarTimer, &QTimer::timeout, this, &DolphinViewContainer::updateStatusBar);
166
167 KIO::FileUndoManager *undoManager = KIO::FileUndoManager::self();
168 connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinViewContainer::delayedStatusBarUpdate);
169
170 m_topLayout->addWidget(m_searchBox, positionFor.searchBox, 0);
171 m_topLayout->addWidget(m_messageWidget, positionFor.messageWidget, 0);
172 m_topLayout->addWidget(m_view, positionFor.view, 0);
173 m_topLayout->addWidget(m_filterBar, positionFor.filterBar, 0);
174 m_topLayout->addWidget(m_statusBar, positionFor.statusBar, 0);
175
176 setSearchModeEnabled(isSearchUrl(url));
177
178 // Update view as the ContentDisplaySettings change
179 // this happens here and not in DolphinView as DolphinviewContainer and DolphinView are not in the same build target ATM
180 connect(ContentDisplaySettings::self(), &KCoreConfigSkeleton::configChanged, m_view, &DolphinView::reload);
181
182 KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel();
183 connect(placesModel, &KFilePlacesModel::dataChanged, this, &DolphinViewContainer::slotPlacesModelChanged);
184 connect(placesModel, &KFilePlacesModel::rowsInserted, this, &DolphinViewContainer::slotPlacesModelChanged);
185 connect(placesModel, &KFilePlacesModel::rowsRemoved, this, &DolphinViewContainer::slotPlacesModelChanged);
186
187 connect(this, &DolphinViewContainer::searchModeEnabledChanged, this, &DolphinViewContainer::captionChanged);
188
189 // Initialize kactivities resource instance
190
191 #if HAVE_KACTIVITIES
192 m_activityResourceInstance = new KActivities::ResourceInstance(window()->winId(), url);
193 m_activityResourceInstance->setParent(this);
194 #endif
195 }
196
197 DolphinViewContainer::~DolphinViewContainer()
198 {
199 }
200
201 QUrl DolphinViewContainer::url() const
202 {
203 return m_view->url();
204 }
205
206 KFileItem DolphinViewContainer::rootItem() const
207 {
208 return m_view->rootItem();
209 }
210
211 void DolphinViewContainer::setActive(bool active)
212 {
213 m_searchBox->setActive(active);
214 if (m_urlNavigatorConnected) {
215 m_urlNavigatorConnected->setActive(active);
216 }
217 m_view->setActive(active);
218
219 #if HAVE_KACTIVITIES
220 if (active) {
221 m_activityResourceInstance->notifyFocusedIn();
222 } else {
223 m_activityResourceInstance->notifyFocusedOut();
224 }
225 #endif
226 }
227
228 bool DolphinViewContainer::isActive() const
229 {
230 return m_view->isActive();
231 }
232
233 void DolphinViewContainer::setAutoGrabFocus(bool grab)
234 {
235 m_autoGrabFocus = grab;
236 }
237
238 bool DolphinViewContainer::autoGrabFocus() const
239 {
240 return m_autoGrabFocus;
241 }
242
243 QString DolphinViewContainer::currentSearchText() const
244 {
245 return m_searchBox->text();
246 }
247
248 const DolphinStatusBar *DolphinViewContainer::statusBar() const
249 {
250 return m_statusBar;
251 }
252
253 DolphinStatusBar *DolphinViewContainer::statusBar()
254 {
255 return m_statusBar;
256 }
257
258 const DolphinUrlNavigator *DolphinViewContainer::urlNavigator() const
259 {
260 return m_urlNavigatorConnected;
261 }
262
263 DolphinUrlNavigator *DolphinViewContainer::urlNavigator()
264 {
265 return m_urlNavigatorConnected;
266 }
267
268 const DolphinUrlNavigator *DolphinViewContainer::urlNavigatorInternalWithHistory() const
269 {
270 return m_urlNavigator.get();
271 }
272
273 DolphinUrlNavigator *DolphinViewContainer::urlNavigatorInternalWithHistory()
274 {
275 return m_urlNavigator.get();
276 }
277
278 const DolphinView *DolphinViewContainer::view() const
279 {
280 return m_view;
281 }
282
283 DolphinView *DolphinViewContainer::view()
284 {
285 return m_view;
286 }
287
288 void DolphinViewContainer::connectUrlNavigator(DolphinUrlNavigator *urlNavigator)
289 {
290 Q_CHECK_PTR(urlNavigator);
291 Q_ASSERT(!m_urlNavigatorConnected);
292 Q_ASSERT(m_urlNavigator.get() != urlNavigator);
293 Q_CHECK_PTR(m_view);
294
295 urlNavigator->setLocationUrl(m_view->url());
296 urlNavigator->setShowHiddenFolders(m_view->hiddenFilesShown());
297 urlNavigator->setSortHiddenFoldersLast(m_view->sortHiddenLast());
298 if (m_urlNavigatorVisualState) {
299 urlNavigator->setVisualState(*m_urlNavigatorVisualState.get());
300 m_urlNavigatorVisualState.reset();
301 }
302 urlNavigator->setActive(isActive());
303
304 // Url changes are still done via m_urlNavigator.
305 connect(urlNavigator, &DolphinUrlNavigator::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
306 connect(urlNavigator, &DolphinUrlNavigator::urlsDropped, this, [=](const QUrl &destination, QDropEvent *event) {
307 m_view->dropUrls(destination, event, urlNavigator->dropWidget());
308 });
309 // Aside from these, only visual things need to be connected.
310 connect(m_view, &DolphinView::urlChanged, urlNavigator, &DolphinUrlNavigator::setLocationUrl);
311 connect(urlNavigator, &DolphinUrlNavigator::activated, this, &DolphinViewContainer::activate);
312
313 m_urlNavigatorConnected = urlNavigator;
314 }
315
316 void DolphinViewContainer::disconnectUrlNavigator()
317 {
318 if (!m_urlNavigatorConnected) {
319 return;
320 }
321
322 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
323 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlsDropped, this, nullptr);
324 disconnect(m_view, &DolphinView::urlChanged, m_urlNavigatorConnected, &DolphinUrlNavigator::setLocationUrl);
325 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::activated, this, &DolphinViewContainer::activate);
326
327 m_urlNavigatorVisualState = m_urlNavigatorConnected->visualState();
328 m_urlNavigatorConnected = nullptr;
329 }
330
331 void DolphinViewContainer::setSelectionModeEnabled(bool enabled, KActionCollection *actionCollection, SelectionMode::BottomBar::Contents bottomBarContents)
332 {
333 const bool wasEnabled = m_view->selectionMode();
334 m_view->setSelectionModeEnabled(enabled);
335
336 if (!enabled) {
337 if (!wasEnabled) {
338 return; // nothing to do here
339 }
340 Q_CHECK_PTR(m_selectionModeTopBar); // there is no point in disabling selectionMode when it wasn't even enabled once.
341 Q_CHECK_PTR(m_selectionModeBottomBar);
342 if (m_selectionModeTopBar->isAncestorOf(QApplication::focusWidget()) || m_selectionModeBottomBar->isAncestorOf(QApplication::focusWidget())) {
343 m_view->setFocus();
344 }
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 job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, this));
728 job->setShowOpenOrExecuteDialog(true);
729 connect(job, &KIO::OpenUrlJob::finished, this, &DolphinViewContainer::slotOpenUrlFinished);
730 job->start();
731 }
732
733 void DolphinViewContainer::slotItemsActivated(const KFileItemList &items)
734 {
735 Q_ASSERT(items.count() >= 2);
736
737 KFileItemActions fileItemActions(this);
738 fileItemActions.runPreferredApplications(items);
739 }
740
741 void DolphinViewContainer::showItemInfo(const KFileItem &item)
742 {
743 if (item.isNull()) {
744 m_statusBar->resetToDefaultText();
745 } else {
746 m_statusBar->setText(item.getStatusBarInfo());
747 }
748 }
749
750 void DolphinViewContainer::closeFilterBar()
751 {
752 m_filterBar->closeFilterBar();
753 m_view->setFocus();
754 Q_EMIT showFilterBarChanged(false);
755 }
756
757 void DolphinViewContainer::clearFilterBar()
758 {
759 m_filterBar->clearIfUnlocked();
760 }
761
762 void DolphinViewContainer::setNameFilter(const QString &nameFilter)
763 {
764 m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly);
765 m_view->setNameFilter(nameFilter);
766 delayedStatusBarUpdate();
767 }
768
769 void DolphinViewContainer::activate()
770 {
771 setActive(true);
772 }
773
774 void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl &)
775 {
776 saveViewState();
777 }
778
779 void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl &url)
780 {
781 if (m_urlNavigatorConnected) {
782 m_urlNavigatorConnected->slotReturnPressed();
783 }
784
785 if (KProtocolManager::supportsListing(url)) {
786 setSearchModeEnabled(isSearchUrl(url));
787 m_view->setUrl(url);
788 tryRestoreViewState();
789
790 if (m_autoGrabFocus && isActive() && !isSearchUrl(url)) {
791 // When an URL has been entered, the view should get the focus.
792 // The focus must be requested asynchronously, as changing the URL might create
793 // a new view widget.
794 QTimer::singleShot(0, this, &DolphinViewContainer::requestFocus);
795 }
796 } else if (KProtocolManager::isSourceProtocol(url)) {
797 if (url.scheme().startsWith(QLatin1String("http"))) {
798 showMessage(i18nc("@info:status", // krazy:exclude=qmethods
799 "Dolphin does not support web pages, the web browser has been launched"),
800 Information);
801 } else {
802 showMessage(i18nc("@info:status", "Protocol not supported by Dolphin, default application has been launched"), Information);
803 }
804
805 QDesktopServices::openUrl(url);
806 redirect(QUrl(), m_urlNavigator->locationUrl(1));
807 } else {
808 showMessage(i18nc("@info:status", "Invalid protocol"), Error);
809 m_urlNavigator->goBack();
810 }
811 }
812
813 void DolphinViewContainer::slotUrlSelectionRequested(const QUrl &url)
814 {
815 m_view->markUrlsAsSelected({url});
816 m_view->markUrlAsCurrent(url); // makes the item scroll into view
817 }
818
819 void DolphinViewContainer::disableUrlNavigatorSelectionRequests()
820 {
821 disconnect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
822 }
823
824 void DolphinViewContainer::enableUrlNavigatorSelectionRequests()
825 {
826 connect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
827 }
828
829 void DolphinViewContainer::redirect(const QUrl &oldUrl, const QUrl &newUrl)
830 {
831 Q_UNUSED(oldUrl)
832 const bool block = m_urlNavigator->signalsBlocked();
833 m_urlNavigator->blockSignals(true);
834
835 // Assure that the location state is reset for redirection URLs. This
836 // allows to skip redirection URLs when going back or forward in the
837 // URL history.
838 m_urlNavigator->saveLocationState(QByteArray());
839 m_urlNavigator->setLocationUrl(newUrl);
840 setSearchModeEnabled(isSearchUrl(newUrl));
841
842 m_urlNavigator->blockSignals(block);
843 }
844
845 void DolphinViewContainer::requestFocus()
846 {
847 m_view->setFocus();
848 }
849
850 void DolphinViewContainer::startSearching()
851 {
852 Q_CHECK_PTR(m_urlNavigatorConnected);
853 const QUrl url = m_searchBox->urlForSearching();
854 if (url.isValid() && !url.isEmpty()) {
855 m_view->setViewPropertiesContext(QStringLiteral("search"));
856 m_urlNavigatorConnected->setLocationUrl(url);
857 }
858 }
859
860 void DolphinViewContainer::closeSearchBox()
861 {
862 setSearchModeEnabled(false);
863 }
864
865 void DolphinViewContainer::stopDirectoryLoading()
866 {
867 m_view->stopLoading();
868 m_statusBar->setProgress(100);
869 }
870
871 void DolphinViewContainer::slotStatusBarZoomLevelChanged(int zoomLevel)
872 {
873 m_view->setZoomLevel(zoomLevel);
874 }
875
876 void DolphinViewContainer::showErrorMessage(const QString &msg)
877 {
878 showMessage(msg, Error);
879 }
880
881 void DolphinViewContainer::slotPlacesModelChanged()
882 {
883 if (!GeneralSettings::showFullPathInTitlebar() && !isSearchModeEnabled()) {
884 Q_EMIT captionChanged();
885 }
886 }
887
888 void DolphinViewContainer::slotHiddenFilesShownChanged(bool showHiddenFiles)
889 {
890 if (m_urlNavigatorConnected) {
891 m_urlNavigatorConnected->setShowHiddenFolders(showHiddenFiles);
892 }
893 }
894
895 void DolphinViewContainer::slotSortHiddenLastChanged(bool hiddenLast)
896 {
897 if (m_urlNavigatorConnected) {
898 m_urlNavigatorConnected->setSortHiddenFoldersLast(hiddenLast);
899 }
900 }
901
902 void DolphinViewContainer::slotCurrentDirectoryRemoved()
903 {
904 const QString location(url().toDisplayString(QUrl::PreferLocalFile));
905 if (url().isLocalFile()) {
906 const QString dirPath = url().toLocalFile();
907 const QString newPath = getNearestExistingAncestorOfPath(dirPath);
908 const QUrl newUrl = QUrl::fromLocalFile(newPath);
909 setUrl(newUrl);
910 }
911
912 showMessage(xi18n("Current location changed, <filename>%1</filename> is no longer accessible.", location), Warning);
913 }
914
915 void DolphinViewContainer::slotOpenUrlFinished(KJob *job)
916 {
917 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
918 showErrorMessage(job->errorString());
919 }
920 }
921
922 bool DolphinViewContainer::isSearchUrl(const QUrl &url) const
923 {
924 return url.scheme().contains(QLatin1String("search"));
925 }
926
927 void DolphinViewContainer::saveViewState()
928 {
929 QByteArray locationState;
930 QDataStream stream(&locationState, QIODevice::WriteOnly);
931 m_view->saveState(stream);
932 m_urlNavigator->saveLocationState(locationState);
933 }
934
935 void DolphinViewContainer::tryRestoreViewState()
936 {
937 QByteArray locationState = m_urlNavigator->locationState();
938 if (!locationState.isEmpty()) {
939 QDataStream stream(&locationState, QIODevice::ReadOnly);
940 m_view->restoreState(stream);
941 }
942 }
943
944 QString DolphinViewContainer::getNearestExistingAncestorOfPath(const QString &path) const
945 {
946 QDir dir(path);
947 do {
948 dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral(".."))));
949 } while (!dir.exists() && !dir.isRoot());
950
951 return dir.exists() ? dir.path() : QString{};
952 }
953
954 #include "moc_dolphinviewcontainer.cpp"