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