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