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