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