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