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