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