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