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