]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphinviewcontainer.cpp
Have "Replace Location" toggle focus of the view
[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
313 urlNavigator->setReadOnlyBadgeVisible(rootItem().isLocalFile() && !rootItem().isWritable());
314
315 m_urlNavigatorConnected = urlNavigator;
316 }
317
318 void DolphinViewContainer::disconnectUrlNavigator()
319 {
320 if (!m_urlNavigatorConnected) {
321 return;
322 }
323
324 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl);
325 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlsDropped, this, nullptr);
326 disconnect(m_view, &DolphinView::urlChanged, m_urlNavigatorConnected, &DolphinUrlNavigator::setLocationUrl);
327 disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::activated, this, &DolphinViewContainer::activate);
328
329 m_urlNavigatorVisualState = m_urlNavigatorConnected->visualState();
330 m_urlNavigatorConnected = nullptr;
331 }
332
333 void DolphinViewContainer::setSelectionModeEnabled(bool enabled, KActionCollection *actionCollection, SelectionMode::BottomBar::Contents bottomBarContents)
334 {
335 const bool wasEnabled = m_view->selectionMode();
336 m_view->setSelectionModeEnabled(enabled);
337
338 if (!enabled) {
339 if (!wasEnabled) {
340 return; // nothing to do here
341 }
342 Q_CHECK_PTR(m_selectionModeTopBar); // there is no point in disabling selectionMode when it wasn't even enabled once.
343 Q_CHECK_PTR(m_selectionModeBottomBar);
344 m_selectionModeTopBar->setVisible(false, WithAnimation);
345 m_selectionModeBottomBar->setVisible(false, WithAnimation);
346 Q_EMIT selectionModeChanged(false);
347
348 if (!QApplication::focusWidget() || m_selectionModeTopBar->isAncestorOf(QApplication::focusWidget())
349 || m_selectionModeBottomBar->isAncestorOf(QApplication::focusWidget())) {
350 m_view->setFocus();
351 }
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, &DolphinViewContainer::showErrorMessage);
374 connect(m_selectionModeBottomBar, &SelectionMode::BottomBar::selectionModeLeavingRequested, this, [this]() {
375 setSelectionModeEnabled(false);
376 });
377 m_topLayout->addWidget(m_selectionModeBottomBar, positionFor.selectionModeBottomBar, 0);
378 }
379 m_selectionModeBottomBar->resetContents(bottomBarContents);
380 if (bottomBarContents == SelectionMode::BottomBar::GeneralContents) {
381 m_selectionModeBottomBar->slotSelectionChanged(m_view->selectedItems(), m_view->url());
382 }
383
384 if (!wasEnabled) {
385 m_selectionModeTopBar->setVisible(true, WithAnimation);
386 m_selectionModeBottomBar->setVisible(true, WithAnimation);
387 Q_EMIT selectionModeChanged(true);
388 }
389 }
390
391 bool DolphinViewContainer::isSelectionModeEnabled() const
392 {
393 const bool isEnabled = m_view->selectionMode();
394 Q_ASSERT((!isEnabled
395 // We can't assert that the bars are invisible only because the selection mode is disabled because the hide animation might still be playing.
396 && (!m_selectionModeBottomBar || !m_selectionModeBottomBar->isEnabled() || !m_selectionModeBottomBar->isVisible()
397 || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::PasteContents))
398 || (isEnabled && m_selectionModeTopBar
399 && m_selectionModeTopBar->isVisible()
400 // 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.
401 && m_selectionModeBottomBar
402 && (m_selectionModeBottomBar->isVisible() || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::GeneralContents)));
403 return isEnabled;
404 }
405
406 void DolphinViewContainer::slotSplitTabDisabled()
407 {
408 if (m_selectionModeBottomBar) {
409 m_selectionModeBottomBar->slotSplitTabDisabled();
410 }
411 }
412
413 void DolphinViewContainer::showMessage(const QString &message, KMessageWidget::MessageType messageType, std::initializer_list<QAction *> buttonActions)
414 {
415 if (message.isEmpty()) {
416 return;
417 }
418
419 m_messageWidget->setText(message);
420
421 // TODO: wrap at arbitrary character positions once QLabel can do this
422 // https://bugreports.qt.io/browse/QTBUG-1276
423 m_messageWidget->setWordWrap(true);
424 m_messageWidget->setMessageType(messageType);
425
426 const QList<QAction *> previousMessageWidgetActions = m_messageWidget->actions();
427 for (auto action : previousMessageWidgetActions) {
428 m_messageWidget->removeAction(action);
429 }
430 for (QAction *action : buttonActions) {
431 m_messageWidget->addAction(action);
432 }
433
434 m_messageWidget->setWordWrap(false);
435 const int unwrappedWidth = m_messageWidget->sizeHint().width();
436 m_messageWidget->setWordWrap(unwrappedWidth > size().width());
437
438 if (m_messageWidget->isVisible()) {
439 m_messageWidget->hide();
440 }
441 m_messageWidget->animatedShow();
442
443 #ifndef QT_NO_ACCESSIBILITY
444 if (QAccessible::isActive() && isActive()) {
445 // 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
446 // to the KMessageWidget. Instead we setFocus() on the KMessageWidget and trust that it has set correct focus handling.
447 m_messageWidget->setFocus();
448 }
449 #endif
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->isEnabled(); // Gets disabled in AnimatedHeightWidget while animating towards a hidden state.
468 }
469
470 void DolphinViewContainer::setSearchModeEnabled(bool enabled)
471 {
472 m_searchBox->setVisible(enabled, WithAnimation);
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 // see KUrlNavigatorPrivate::firstButtonText().
549 if (url().path().isEmpty() || url().path() == QLatin1Char('/')) {
550 QUrlQuery query(url());
551 const QString title = query.queryItemValue(QStringLiteral("title"));
552 if (!title.isEmpty()) {
553 return title;
554 }
555 }
556
557 if (isSearchModeEnabled()) {
558 if (currentSearchText().isEmpty()) {
559 return i18n("Search");
560 } else {
561 return i18n("Search for %1", currentSearchText());
562 }
563 }
564
565 KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel();
566
567 QModelIndex url_index = placesModel->closestItem(url());
568
569 if (url_index.isValid() && placesModel->url(url_index).matches(url(), QUrl::StripTrailingSlash)) {
570 return placesModel->text(url_index);
571 }
572
573 if (!url().isLocalFile()) {
574 QUrl adjustedUrl = url().adjusted(QUrl::StripTrailingSlash);
575 QString caption;
576 if (!adjustedUrl.fileName().isEmpty()) {
577 caption = adjustedUrl.fileName();
578 } else if (!adjustedUrl.path().isEmpty() && adjustedUrl.path() != "/") {
579 caption = adjustedUrl.path();
580 } else if (!adjustedUrl.host().isEmpty()) {
581 caption = adjustedUrl.host();
582 } else {
583 caption = adjustedUrl.toString();
584 }
585 return caption;
586 }
587
588 QString fileName = url().adjusted(QUrl::StripTrailingSlash).fileName();
589 if (fileName.isEmpty()) {
590 fileName = '/';
591 }
592
593 return fileName;
594 }
595
596 void DolphinViewContainer::setUrl(const QUrl &newUrl)
597 {
598 if (newUrl != m_urlNavigator->locationUrl()) {
599 m_urlNavigator->setLocationUrl(newUrl);
600 }
601 }
602
603 void DolphinViewContainer::setFilterBarVisible(bool visible)
604 {
605 Q_ASSERT(m_filterBar);
606 if (visible) {
607 m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly);
608 m_filterBar->setVisible(true, WithAnimation);
609 m_filterBar->setFocus();
610 m_filterBar->selectAll();
611 } else {
612 closeFilterBar();
613 }
614 }
615
616 void DolphinViewContainer::delayedStatusBarUpdate()
617 {
618 if (m_statusBarTimer->isActive() && (m_statusBarTimestamp.elapsed() > 2000)) {
619 // No update of the statusbar has been done during the last 2 seconds,
620 // although an update has been requested. Trigger an immediate update.
621 m_statusBarTimer->stop();
622 updateStatusBar();
623 } else {
624 // Invoke updateStatusBar() with a small delay. This assures that
625 // when a lot of delayedStatusBarUpdates() are done in a short time,
626 // no bottleneck is given.
627 m_statusBarTimer->start();
628 }
629 }
630
631 void DolphinViewContainer::updateStatusBar()
632 {
633 m_statusBarTimestamp.start();
634 m_view->requestStatusBarText();
635 }
636
637 void DolphinViewContainer::slotDirectoryLoadingStarted()
638 {
639 if (isSearchUrl(url())) {
640 // Search KIO-slaves usually don't provide any progress information. Give
641 // a hint to the user that a searching is done:
642 updateStatusBar();
643 m_statusBar->showProgress(i18nc("@info", "Searching…"), -1);
644 } else {
645 // Trigger an undetermined progress indication. The progress
646 // information in percent will be triggered by the percent() signal
647 // of the directory lister later.
648 m_statusBar->showProgress(QString(), -1);
649 }
650
651 if (m_urlNavigatorConnected) {
652 m_urlNavigatorConnected->setReadOnlyBadgeVisible(false);
653 }
654 }
655
656 void DolphinViewContainer::slotDirectoryLoadingCompleted()
657 {
658 m_statusBar->showProgress(QString(), 100);
659
660 if (isSearchUrl(url()) && m_view->itemsCount() == 0) {
661 // The dir lister has been completed on a Baloo-URI and no items have been found. Instead
662 // of showing the default status bar information ("0 items") a more helpful information is given:
663 m_statusBar->setText(i18nc("@info:status", "No items found."));
664 } else {
665 updateStatusBar();
666 }
667
668 if (m_urlNavigatorConnected) {
669 m_urlNavigatorConnected->setReadOnlyBadgeVisible(rootItem().isLocalFile() && !rootItem().isWritable());
670 }
671
672 // Update admin bar visibility
673 if (m_view->url().scheme() == QStringLiteral("admin")) {
674 if (!m_adminBar) {
675 m_adminBar = new Admin::Bar(this);
676 m_topLayout->addWidget(m_adminBar, positionFor.adminBar, 0);
677 }
678 m_adminBar->setVisible(true, WithAnimation);
679 } else if (m_adminBar) {
680 m_adminBar->setVisible(false, WithAnimation);
681 }
682 }
683
684 void DolphinViewContainer::slotDirectoryLoadingCanceled()
685 {
686 m_statusBar->showProgress(QString(), 100);
687 m_statusBar->setText(QString());
688 }
689
690 void DolphinViewContainer::slotUrlIsFileError(const QUrl &url)
691 {
692 const KFileItem item(url);
693
694 // Find out if the file can be opened in the view (for example, this is the
695 // case if the file is an archive). The mime type must be known for that.
696 item.determineMimeType();
697 const QUrl &folderUrl = DolphinView::openItemAsFolderUrl(item, true);
698 if (!folderUrl.isEmpty()) {
699 setUrl(folderUrl);
700 } else {
701 slotItemActivated(item);
702 }
703 }
704
705 void DolphinViewContainer::slotItemActivated(const KFileItem &item)
706 {
707 // It is possible to activate items on inactive views by
708 // drag & drop operations. Assure that activating an item always
709 // results in an active view.
710 m_view->setActive(true);
711
712 const QUrl &url = DolphinView::openItemAsFolderUrl(item, GeneralSettings::browseThroughArchives());
713 if (!url.isEmpty()) {
714 const auto modifiers = QGuiApplication::keyboardModifiers();
715 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
716 if (modifiers & Qt::ControlModifier && modifiers & Qt::ShiftModifier) {
717 Q_EMIT activeTabRequested(url);
718 } else if (modifiers & Qt::ControlModifier) {
719 Q_EMIT tabRequested(url);
720 } else if (modifiers & Qt::ShiftModifier) {
721 Dolphin::openNewWindow({KFilePlacesModel::convertedUrl(url)}, this);
722 } else {
723 setUrl(url);
724 }
725 return;
726 }
727
728 KIO::OpenUrlJob *job = new KIO::OpenUrlJob(item.targetUrl(), item.mimetype());
729 // Auto*Warning*Handling, errors are put in a KMessageWidget by us in slotOpenUrlFinished.
730 job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoWarningHandlingEnabled, this));
731 job->setShowOpenOrExecuteDialog(true);
732 connect(job, &KIO::OpenUrlJob::finished, this, &DolphinViewContainer::slotOpenUrlFinished);
733 job->start();
734 }
735
736 void DolphinViewContainer::slotfileMiddleClickActivated(const KFileItem &item)
737 {
738 KService::List services = KApplicationTrader::queryByMimeType(item.mimetype());
739
740 int indexOfAppToOpenFileWith = 1;
741
742 // executable scripts
743 auto mimeType = item.currentMimeType();
744 if (item.isLocalFile() && mimeType.inherits(QStringLiteral("application/x-executable")) && mimeType.inherits(QStringLiteral("text/plain"))
745 && QFileInfo(item.localPath()).isExecutable()) {
746 KConfigGroup cfgGroup(KSharedConfig::openConfig(QStringLiteral("kiorc")), QStringLiteral("Executable scripts"));
747 const QString value = cfgGroup.readEntry("behaviourOnLaunch", "alwaysAsk");
748
749 // in case KIO::WidgetsOpenOrExecuteFileHandler::promptUserOpenOrExecute would not open the file
750 if (value != QLatin1String("open")) {
751 indexOfAppToOpenFileWith = 0;
752 }
753 }
754
755 if (services.length() >= indexOfAppToOpenFileWith + 1) {
756 auto service = services.at(indexOfAppToOpenFileWith);
757
758 KIO::ApplicationLauncherJob *job = new KIO::ApplicationLauncherJob(service, this);
759 job->setUrls({item.url()});
760
761 job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, this));
762 connect(job, &KIO::OpenUrlJob::finished, this, &DolphinViewContainer::slotOpenUrlFinished);
763 job->start();
764 } else {
765 // If no 2nd service available, try to open archives in new tabs, regardless of the "Open archives as folder" setting.
766 const QUrl &url = DolphinView::openItemAsFolderUrl(item);
767 const auto modifiers = QGuiApplication::keyboardModifiers();
768 if (!url.isEmpty()) {
769 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
770 if (modifiers & Qt::ShiftModifier) {
771 Q_EMIT activeTabRequested(url);
772 } else {
773 Q_EMIT tabRequested(url);
774 }
775 }
776 }
777 }
778
779 void DolphinViewContainer::slotItemsActivated(const KFileItemList &items)
780 {
781 Q_ASSERT(items.count() >= 2);
782
783 KFileItemActions fileItemActions(this);
784 fileItemActions.runPreferredApplications(items);
785 }
786
787 void DolphinViewContainer::showItemInfo(const KFileItem &item)
788 {
789 if (item.isNull()) {
790 m_statusBar->resetToDefaultText();
791 } else {
792 m_statusBar->setText(item.getStatusBarInfo());
793 }
794 }
795
796 void DolphinViewContainer::closeFilterBar()
797 {
798 m_filterBar->closeFilterBar();
799 m_view->setFocus();
800 Q_EMIT showFilterBarChanged(false);
801 }
802
803 void DolphinViewContainer::clearFilterBar()
804 {
805 m_filterBar->clearIfUnlocked();
806 }
807
808 void DolphinViewContainer::setNameFilter(const QString &nameFilter)
809 {
810 m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly);
811 m_view->setNameFilter(nameFilter);
812 delayedStatusBarUpdate();
813 }
814
815 void DolphinViewContainer::activate()
816 {
817 setActive(true);
818 }
819
820 void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl &)
821 {
822 saveViewState();
823 }
824
825 void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl &url)
826 {
827 if (m_urlNavigatorConnected) {
828 m_urlNavigatorConnected->slotReturnPressed();
829 }
830
831 if (KProtocolManager::supportsListing(url)) {
832 const bool searchBoxInitialized = isSearchModeEnabled() && m_searchBox->text().isEmpty();
833 setSearchModeEnabled(isSearchUrl(url) || searchBoxInitialized);
834
835 m_view->setUrl(url);
836 tryRestoreViewState();
837
838 if (m_autoGrabFocus && isActive() && !isSearchModeEnabled()) {
839 // When an URL has been entered, the view should get the focus.
840 // The focus must be requested asynchronously, as changing the URL might create
841 // a new view widget.
842 QTimer::singleShot(0, this, &DolphinViewContainer::requestFocus);
843 }
844 } else if (KProtocolManager::isSourceProtocol(url)) {
845 if (url.scheme().startsWith(QLatin1String("http"))) {
846 showMessage(i18nc("@info:status", // krazy:exclude=qmethods
847 "Dolphin does not support web pages, the web browser has been launched"),
848 KMessageWidget::Information);
849 } else {
850 showMessage(i18nc("@info:status", "Protocol not supported by Dolphin, default application has been launched"), KMessageWidget::Information);
851 }
852
853 QDesktopServices::openUrl(url);
854 redirect(QUrl(), m_urlNavigator->locationUrl(1));
855 } else {
856 if (!url.scheme().isEmpty()) {
857 showMessage(i18nc("@info:status", "Invalid protocol '%1'", url.scheme()), KMessageWidget::Error);
858 } else {
859 showMessage(i18nc("@info:status", "Invalid protocol"), KMessageWidget::Error);
860 }
861 m_urlNavigator->goBack();
862 }
863 }
864
865 void DolphinViewContainer::slotUrlSelectionRequested(const QUrl &url)
866 {
867 // 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
868
869 m_view->markUrlAsCurrent(url); // makes the item scroll into view
870 }
871
872 void DolphinViewContainer::disableUrlNavigatorSelectionRequests()
873 {
874 disconnect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
875 }
876
877 void DolphinViewContainer::enableUrlNavigatorSelectionRequests()
878 {
879 connect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested);
880 }
881
882 void DolphinViewContainer::redirect(const QUrl &oldUrl, const QUrl &newUrl)
883 {
884 Q_UNUSED(oldUrl)
885 const bool block = m_urlNavigator->signalsBlocked();
886 m_urlNavigator->blockSignals(true);
887
888 // Assure that the location state is reset for redirection URLs. This
889 // allows to skip redirection URLs when going back or forward in the
890 // URL history.
891 m_urlNavigator->saveLocationState(QByteArray());
892 m_urlNavigator->setLocationUrl(newUrl);
893 setSearchModeEnabled(isSearchUrl(newUrl));
894
895 m_urlNavigator->blockSignals(block);
896 }
897
898 void DolphinViewContainer::requestFocus()
899 {
900 m_view->setFocus();
901 }
902
903 void DolphinViewContainer::startSearching()
904 {
905 Q_CHECK_PTR(m_urlNavigatorConnected);
906 const QUrl url = m_searchBox->urlForSearching();
907 if (url.isValid() && !url.isEmpty()) {
908 m_view->setViewPropertiesContext(QStringLiteral("search"));
909 m_urlNavigatorConnected->setLocationUrl(url);
910 }
911 }
912
913 void DolphinViewContainer::openSearchBox()
914 {
915 setSearchModeEnabled(true);
916 }
917
918 void DolphinViewContainer::closeSearchBox()
919 {
920 setSearchModeEnabled(false);
921 }
922
923 void DolphinViewContainer::stopDirectoryLoading()
924 {
925 m_view->stopLoading();
926 m_statusBar->showProgress(QString(), 100);
927 }
928
929 void DolphinViewContainer::slotStatusBarZoomLevelChanged(int zoomLevel)
930 {
931 m_view->setZoomLevel(zoomLevel);
932 }
933
934 void DolphinViewContainer::slotErrorMessageFromView(const QString &message, const int kioErrorCode)
935 {
936 if (kioErrorCode == KIO::ERR_CANNOT_ENTER_DIRECTORY && m_view->url().scheme() == QStringLiteral("file")
937 && KProtocolInfo::isKnownProtocol(QStringLiteral("admin")) && !rootItem().isReadable()) {
938 // Explain to users that they need authentication to see the folder contents.
939 if (!m_authorizeToEnterFolderAction) { // This code is similar to parts of Admin::Bar::hideTheNextTimeAuthorizationExpires().
940 // We should not simply use the actAsAdminAction() itself here because that one always refers to the active view instead of this->m_view.
941 auto actAsAdminAction = Admin::WorkerIntegration::FriendAccess::actAsAdminAction();
942 m_authorizeToEnterFolderAction = new QAction{actAsAdminAction->icon(), actAsAdminAction->text(), this};
943 m_authorizeToEnterFolderAction->setToolTip(actAsAdminAction->toolTip());
944 m_authorizeToEnterFolderAction->setWhatsThis(actAsAdminAction->whatsThis());
945 connect(m_authorizeToEnterFolderAction, &QAction::triggered, this, [this, actAsAdminAction]() {
946 setActive(true);
947 actAsAdminAction->trigger();
948 });
949 }
950 showMessage(i18nc("@info", "Authorization required to enter this folder."), KMessageWidget::Error, {m_authorizeToEnterFolderAction});
951 return;
952 }
953 Q_EMIT showErrorMessage(message);
954 }
955
956 void DolphinViewContainer::showErrorMessage(const QString &message)
957 {
958 showMessage(message, KMessageWidget::Error);
959 }
960
961 void DolphinViewContainer::slotPlacesModelChanged()
962 {
963 if (!GeneralSettings::showFullPathInTitlebar() && !isSearchModeEnabled()) {
964 Q_EMIT captionChanged();
965 }
966 }
967
968 void DolphinViewContainer::slotHiddenFilesShownChanged(bool showHiddenFiles)
969 {
970 if (m_urlNavigatorConnected) {
971 m_urlNavigatorConnected->setShowHiddenFolders(showHiddenFiles);
972 }
973 }
974
975 void DolphinViewContainer::slotSortHiddenLastChanged(bool hiddenLast)
976 {
977 if (m_urlNavigatorConnected) {
978 m_urlNavigatorConnected->setSortHiddenFoldersLast(hiddenLast);
979 }
980 }
981
982 void DolphinViewContainer::slotCurrentDirectoryRemoved()
983 {
984 const QString location(url().toDisplayString(QUrl::PreferLocalFile));
985 if (url().isLocalFile()) {
986 const QString dirPath = url().toLocalFile();
987 const QString newPath = getNearestExistingAncestorOfPath(dirPath);
988 const QUrl newUrl = QUrl::fromLocalFile(newPath);
989 // #473377: Delay changing the url to avoid modifying KCoreDirLister before KCoreDirListerCache::deleteDir() returns.
990 QTimer::singleShot(0, this, [&, newUrl, location] {
991 setUrl(newUrl);
992 showMessage(xi18n("Current location changed, <filename>%1</filename> is no longer accessible.", location), KMessageWidget::Warning);
993 });
994 } else
995 showMessage(xi18n("Current location changed, <filename>%1</filename> is no longer accessible.", location), KMessageWidget::Warning);
996 }
997
998 void DolphinViewContainer::slotOpenUrlFinished(KJob *job)
999 {
1000 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
1001 showErrorMessage(job->errorString());
1002 }
1003 }
1004
1005 bool DolphinViewContainer::isSearchUrl(const QUrl &url) const
1006 {
1007 return url.scheme().contains(QLatin1String("search"));
1008 }
1009
1010 void DolphinViewContainer::saveViewState()
1011 {
1012 QByteArray locationState;
1013 QDataStream stream(&locationState, QIODevice::WriteOnly);
1014 m_view->saveState(stream);
1015 m_urlNavigator->saveLocationState(locationState);
1016 }
1017
1018 void DolphinViewContainer::tryRestoreViewState()
1019 {
1020 QByteArray locationState = m_urlNavigator->locationState();
1021 if (!locationState.isEmpty()) {
1022 QDataStream stream(&locationState, QIODevice::ReadOnly);
1023 m_view->restoreState(stream);
1024 }
1025 }
1026
1027 QString DolphinViewContainer::getNearestExistingAncestorOfPath(const QString &path) const
1028 {
1029 QDir dir(path);
1030 do {
1031 dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral(".."))));
1032 } while (!dir.exists() && !dir.isRoot());
1033
1034 return dir.exists() ? dir.path() : QString{};
1035 }
1036
1037 #include "moc_dolphinviewcontainer.cpp"