2 * SPDX-FileCopyrightText: 2014 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "dolphintabwidget.h"
9 #include "dolphin_generalsettings.h"
10 #include "dolphintabbar.h"
11 #include "dolphinviewcontainer.h"
12 #include "views/draganddrophelper.h"
14 #include <KAcceleratorManager>
15 #include <KConfigGroup>
16 #include <KIO/CommandLauncherJob>
17 #include <KLocalizedString>
19 #include <KStringHandler>
20 #include <kio/global.h>
22 #include <QApplication>
24 #include <QStackedWidget>
26 DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction
*navigatorsWidget
, QWidget
*parent
)
28 , m_lastViewedTab(nullptr)
29 , m_navigatorsWidget
{navigatorsWidget
}
31 KAcceleratorManager::setNoAccel(this);
33 connect(this, &DolphinTabWidget::tabCloseRequested
, this, QOverload
<int>::of(&DolphinTabWidget::closeTab
));
34 connect(this, &DolphinTabWidget::currentChanged
, this, &DolphinTabWidget::currentTabChanged
);
36 DolphinTabBar
*tabBar
= new DolphinTabBar(this);
37 connect(tabBar
, &DolphinTabBar::openNewActivatedTab
, this, QOverload
<int>::of(&DolphinTabWidget::openNewActivatedTab
));
38 connect(tabBar
, &DolphinTabBar::tabDragMoveEvent
, this, &DolphinTabWidget::tabDragMoveEvent
);
39 connect(tabBar
, &DolphinTabBar::tabDropEvent
, this, &DolphinTabWidget::tabDropEvent
);
40 connect(tabBar
, &DolphinTabBar::tabDetachRequested
, this, &DolphinTabWidget::detachTab
);
41 connect(tabBar
, &DolphinTabBar::tabRenamed
, this, &DolphinTabWidget::renameTab
);
44 setDocumentMode(true);
45 setElideMode(Qt::ElideRight
);
46 setUsesScrollButtons(true);
47 setTabBarAutoHide(true);
49 auto stackWidget
{findChild
<QStackedWidget
*>()};
50 // i18n: This accessible name will be announced any time the user moves keyboard focus e.g. from the toolbar or the places panel towards the main working
51 // area of Dolphin. It gives structure. This container does not only contain the main view but also the status bar, the search panel, filter, and selection
52 // mode bars, so calling it just a "View" is a bit wrong, but hopefully still gets the point across.
53 stackWidget
->setAccessibleName(i18nc("accessible name of Dolphin's view container", "Location View")); // Without this call, the non-descript Qt provided
54 // "Layered Pane" role is announced.
57 DolphinTabPage
*DolphinTabWidget::currentTabPage() const
59 return tabPageAt(currentIndex());
62 DolphinTabPage
*DolphinTabWidget::nextTabPage() const
64 const int index
= currentIndex() + 1;
65 return tabPageAt(index
< count() ? index
: 0);
68 DolphinTabPage
*DolphinTabWidget::prevTabPage() const
70 const int index
= currentIndex() - 1;
71 return tabPageAt(index
>= 0 ? index
: (count() - 1));
74 DolphinTabPage
*DolphinTabWidget::tabPageAt(const int index
) const
76 return static_cast<DolphinTabPage
*>(widget(index
));
79 void DolphinTabWidget::saveProperties(KConfigGroup
&group
) const
81 const int tabCount
= count();
82 group
.writeEntry("Tab Count", tabCount
);
83 group
.writeEntry("Active Tab Index", currentIndex());
85 for (int i
= 0; i
< tabCount
; ++i
) {
86 const DolphinTabPage
*tabPage
= tabPageAt(i
);
87 group
.writeEntry("Tab Data " % QString::number(i
), tabPage
->saveState());
91 void DolphinTabWidget::readProperties(const KConfigGroup
&group
)
93 const int tabCount
= group
.readEntry("Tab Count", 0);
94 for (int i
= 0; i
< tabCount
; ++i
) {
96 openNewActivatedTab();
98 const QByteArray state
= group
.readEntry("Tab Data " % QString::number(i
), QByteArray());
99 tabPageAt(i
)->restoreState(state
);
102 const int index
= group
.readEntry("Active Tab Index", 0);
103 setCurrentIndex(index
);
106 void DolphinTabWidget::refreshViews()
108 // Left-elision is better when showing full paths, since you care most
109 // about the current directory which is on the right
110 if (GeneralSettings::showFullPathInTitlebar()) {
111 setElideMode(Qt::ElideLeft
);
113 setElideMode(Qt::ElideRight
);
116 const int tabCount
= count();
117 for (int i
= 0; i
< tabCount
; ++i
) {
119 tabPageAt(i
)->refreshViews();
123 void DolphinTabWidget::updateTabName(int index
)
125 Q_ASSERT(index
>= 0);
127 if (!tabPageAt(index
)->customLabel().isEmpty()) {
128 QString name
= tabPageAt(index
)->customLabel();
129 tabBar()->setTabText(index
, name
);
133 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
136 bool DolphinTabWidget::isUrlOpen(const QUrl
&url
) const
138 return viewOpenAtDirectory(url
).has_value();
141 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl
&urlOfItem
) const
143 return viewShowingItem(urlOfItem
).has_value();
146 void DolphinTabWidget::openNewActivatedTab()
148 std::unique_ptr
<DolphinUrlNavigator::VisualState
> oldNavigatorState
;
149 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget
->secondaryUrlNavigator()) {
150 oldNavigatorState
= m_navigatorsWidget
->primaryUrlNavigator()->visualState();
152 oldNavigatorState
= m_navigatorsWidget
->secondaryUrlNavigator()->visualState();
155 const DolphinViewContainer
*oldActiveViewContainer
= currentTabPage()->activeViewContainer();
156 Q_ASSERT(oldActiveViewContainer
);
158 openNewActivatedTab(oldActiveViewContainer
->url());
160 DolphinViewContainer
*newActiveViewContainer
= currentTabPage()->activeViewContainer();
161 Q_ASSERT(newActiveViewContainer
);
163 // The URL navigator of the new tab should have the same editable state
164 // as the current tab
165 newActiveViewContainer
->urlNavigator()->setVisualState(*oldNavigatorState
.get());
167 // Always focus the new tab's view
168 newActiveViewContainer
->view()->setFocus();
171 void DolphinTabWidget::openNewActivatedTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
)
173 openNewTab(primaryUrl
, secondaryUrl
);
174 if (GeneralSettings::openNewTabAfterLastTab()) {
175 setCurrentIndex(count() - 1);
177 setCurrentIndex(currentIndex() + 1);
181 DolphinTabPage
*DolphinTabWidget::openNewTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
, DolphinTabWidget::NewTabPosition position
)
183 QWidget
*focusWidget
= QApplication::focusWidget();
185 DolphinTabPage
*tabPage
= new DolphinTabPage(primaryUrl
, secondaryUrl
, this);
186 tabPage
->setActive(false);
187 connect(tabPage
, &DolphinTabPage::activeViewChanged
, this, &DolphinTabWidget::activeViewChanged
);
188 connect(tabPage
, &DolphinTabPage::activeViewUrlChanged
, this, &DolphinTabWidget::tabUrlChanged
);
189 connect(tabPage
->activeViewContainer(), &DolphinViewContainer::captionChanged
, this, [this, tabPage
]() {
190 updateTabName(indexOf(tabPage
));
193 if (position
== NewTabPosition::FollowSetting
) {
194 if (GeneralSettings::openNewTabAfterLastTab()) {
195 position
= NewTabPosition::AtEnd
;
197 position
= NewTabPosition::AfterCurrent
;
201 int newTabIndex
= -1;
202 if (position
== NewTabPosition::AfterCurrent
|| (position
== NewTabPosition::FollowSetting
&& !GeneralSettings::openNewTabAfterLastTab())) {
203 newTabIndex
= currentIndex() + 1;
206 insertTab(newTabIndex
, tabPage
, QIcon() /* loaded in tabInserted */, tabName(tabPage
));
209 // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened
210 // in background, assure that the previous focused widget gets the focus back.
211 focusWidget
->setFocus();
216 void DolphinTabWidget::openDirectories(const QList
<QUrl
> &dirs
, bool splitView
)
218 Q_ASSERT(dirs
.size() > 0);
220 bool somethingWasAlreadyOpen
= false;
222 QList
<QUrl
>::const_iterator it
= dirs
.constBegin();
223 while (it
!= dirs
.constEnd()) {
224 const QUrl
&primaryUrl
= *(it
++);
225 const std::optional
<ViewIndex
> viewIndexAtDirectory
= viewOpenAtDirectory(primaryUrl
);
227 // When the user asks for a URL that's already open,
228 // activate it instead of opening a new tab
229 if (viewIndexAtDirectory
.has_value()) {
230 somethingWasAlreadyOpen
= true;
231 activateViewContainerAt(viewIndexAtDirectory
.value());
232 } else if (splitView
&& (it
!= dirs
.constEnd())) {
233 const QUrl
&secondaryUrl
= *(it
++);
234 if (somethingWasAlreadyOpen
) {
235 openNewTab(primaryUrl
, secondaryUrl
);
237 openNewActivatedTab(primaryUrl
, secondaryUrl
);
240 if (somethingWasAlreadyOpen
) {
241 openNewTab(primaryUrl
);
243 openNewActivatedTab(primaryUrl
);
249 void DolphinTabWidget::openFiles(const QList
<QUrl
> &files
, bool splitView
)
251 Q_ASSERT(files
.size() > 0);
253 // Get all distinct directories from 'files'.
254 QList
<QUrl
> dirsThatNeedToBeOpened
;
255 QList
<QUrl
> dirsThatWereAlreadyOpen
;
256 for (const QUrl
&file
: files
) {
257 const QUrl
dir(file
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
258 if (dirsThatNeedToBeOpened
.contains(dir
) || dirsThatWereAlreadyOpen
.contains(dir
)) {
262 // The selecting of files that we do later will not work in views that already have items selected.
263 // So we check if dir is already open and clear the selection if it is. BUG: 417230
264 // We also make sure the view will be activated.
265 auto viewIndex
= viewShowingItem(file
);
266 if (viewIndex
.has_value()) {
267 viewContainerAt(viewIndex
.value())->view()->clearSelection();
268 activateViewContainerAt(viewIndex
.value());
269 dirsThatWereAlreadyOpen
.append(dir
);
271 dirsThatNeedToBeOpened
.append(dir
);
275 const int oldTabCount
= count();
276 // Open a tab for each directory. If the "split view" option is enabled,
277 // two directories are shown inside one tab (see openDirectories()).
278 if (dirsThatNeedToBeOpened
.size() > 0) {
279 openDirectories(dirsThatNeedToBeOpened
, splitView
);
281 const int tabCount
= count();
283 // Select the files. Although the files can be split between several
284 // tabs, there is no need to split 'files' accordingly, as
285 // the DolphinView will just ignore invalid selections.
286 for (int i
= 0; i
< tabCount
; ++i
) {
287 DolphinTabPage
*tabPage
= tabPageAt(i
);
288 tabPage
->markUrlsAsSelected(files
);
289 tabPage
->markUrlAsCurrent(files
.first());
290 if (i
< oldTabCount
) {
291 // Force selection of file if directory was already open, BUG: 417230
292 tabPage
->activeViewContainer()->view()->updateViewState();
297 void DolphinTabWidget::closeTab()
299 closeTab(currentIndex());
302 void DolphinTabWidget::closeTab(const int index
)
304 Q_ASSERT(index
>= 0);
305 Q_ASSERT(index
< count());
308 // Close Dolphin when closing the last tab.
309 parentWidget()->close();
313 DolphinTabPage
*tabPage
= tabPageAt(index
);
314 Q_EMIT
rememberClosedTab(tabPage
->activeViewContainer()->url(), tabPage
->saveState());
317 tabPage
->deleteLater();
320 void DolphinTabWidget::activateTab(const int index
)
322 if (index
< count()) {
323 setCurrentIndex(index
);
327 void DolphinTabWidget::activateLastTab()
329 setCurrentIndex(count() - 1);
332 void DolphinTabWidget::activateNextTab()
334 const int index
= currentIndex() + 1;
335 setCurrentIndex(index
< count() ? index
: 0);
338 void DolphinTabWidget::activatePrevTab()
340 const int index
= currentIndex() - 1;
341 setCurrentIndex(index
>= 0 ? index
: (count() - 1));
344 void DolphinTabWidget::restoreClosedTab(const QByteArray
&state
)
346 openNewActivatedTab();
347 currentTabPage()->restoreState(state
);
350 void DolphinTabWidget::copyToInactiveSplitView()
352 const DolphinTabPage
*tabPage
= currentTabPage();
353 if (!tabPage
->splitViewEnabled()) {
357 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
358 if (selectedItems
.isEmpty()) {
362 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
363 inactiveView
->copySelectedItems(selectedItems
, inactiveView
->url());
366 void DolphinTabWidget::moveToInactiveSplitView()
368 const DolphinTabPage
*tabPage
= currentTabPage();
369 if (!tabPage
->splitViewEnabled()) {
373 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
374 if (selectedItems
.isEmpty()) {
378 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
379 inactiveView
->moveSelectedItems(selectedItems
, inactiveView
->url());
382 void DolphinTabWidget::detachTab(int index
)
384 Q_ASSERT(index
>= 0);
388 const DolphinTabPage
*tabPage
= tabPageAt(index
);
389 args
<< tabPage
->primaryViewContainer()->url().url();
390 if (tabPage
->splitViewEnabled()) {
391 args
<< tabPage
->secondaryViewContainer()->url().url();
392 args
<< QStringLiteral("--split");
394 args
<< QStringLiteral("--new-window");
396 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
397 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
403 void DolphinTabWidget::openNewActivatedTab(int index
)
405 Q_ASSERT(index
>= 0);
406 const DolphinTabPage
*tabPage
= tabPageAt(index
);
407 openNewActivatedTab(tabPage
->activeViewContainer()->url());
410 void DolphinTabWidget::tabDragMoveEvent(int index
, QDragMoveEvent
*event
)
413 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
414 DragAndDropHelper::updateDropAction(event
, view
->url());
418 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
*event
)
421 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
422 view
->dropUrls(view
->url(), event
, view
);
424 const auto urls
= event
->mimeData()->urls();
426 for (const QUrl
&url
: urls
) {
427 auto *job
= KIO::stat(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
428 connect(job
, &KJob::result
, this, [this, job
]() {
429 if (!job
->error() && job
->statResult().isDir()) {
430 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
437 void DolphinTabWidget::tabUrlChanged(const QUrl
&url
)
439 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
441 updateTabName(index
);
442 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
443 if (tabBar()->isVisible()) {
444 // ensure the path url ends with a slash to have proper folder icon for remote folders
445 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
446 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
448 // Mark as dirty, actually load once the tab bar actually gets shown
449 tabBar()->setTabIcon(index
, QIcon());
452 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
453 if (index
== currentIndex()) {
454 Q_EMIT
currentUrlChanged(url
);
457 Q_EMIT
urlChanged(url
);
461 void DolphinTabWidget::currentTabChanged(int index
)
463 DolphinTabPage
*tabPage
= tabPageAt(index
);
464 if (tabPage
== m_lastViewedTab
) {
467 if (m_lastViewedTab
) {
468 m_lastViewedTab
->disconnectNavigators();
469 m_lastViewedTab
->setActive(false);
471 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
472 m_navigatorsWidget
->createSecondaryUrlNavigator();
474 DolphinViewContainer
*viewContainer
= tabPage
->activeViewContainer();
475 Q_EMIT
activeViewChanged(viewContainer
);
476 Q_EMIT
currentUrlChanged(viewContainer
->url());
477 tabPage
->setActive(true);
478 tabPage
->connectNavigators(m_navigatorsWidget
);
479 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
480 m_lastViewedTab
= tabPage
;
483 void DolphinTabWidget::renameTab(int index
, const QString
&name
)
485 tabPageAt(index
)->setCustomLabel(name
);
486 updateTabName(index
);
489 void DolphinTabWidget::tabInserted(int index
)
491 QTabWidget::tabInserted(index
);
493 if (tabBar()->isVisible()) {
494 // Resolve all pending tab icons
495 for (int i
= 0; i
< count(); ++i
) {
496 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
497 if (tabBar()->tabIcon(i
).isNull()) {
498 // ensure the path url ends with a slash to have proper folder icon for remote folders
499 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
500 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
502 if (tabBar()->tabToolTip(i
).isEmpty()) {
503 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
508 Q_EMIT
tabCountChanged(count());
511 void DolphinTabWidget::tabRemoved(int index
)
513 QTabWidget::tabRemoved(index
);
515 Q_EMIT
tabCountChanged(count());
518 QString
DolphinTabWidget::tabName(DolphinTabPage
*tabPage
) const
525 if (tabPage
->splitViewEnabled()) {
526 if (tabPage
->primaryViewActive()) {
527 // i18n: %1 is the primary view and %2 the secondary view. For left to right languages the primary view is on the left so we also want it to be on the
528 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
529 name
= i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
531 // i18n: %1 is the primary view and %2 the secondary view. For left to right languages the primary view is on the left so we also want it to be on the
532 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
533 name
= i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
536 name
= tabPage
->activeViewContainer()->caption();
540 // Make sure that a '&' inside the directory name is displayed correctly
541 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
542 return KStringHandler::rsqueeze(name
.replace('&', QLatin1String("&&")), 40 /* default maximum visible folder name visible */);
545 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
547 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
551 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
554 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
556 activateTab(viewIndex
.tabIndex
);
557 auto viewContainer
= viewContainerAt(viewIndex
);
558 if (!viewContainer
) {
561 viewContainer
->setActive(true);
562 return viewContainer
;
565 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
&directory
) const
567 int i
= currentIndex();
571 // loop over the tabs starting from the current one
573 const auto tabPage
= tabPageAt(i
);
574 if (tabPage
->primaryViewContainer()->url() == directory
) {
575 return std::optional(ViewIndex
{i
, true});
578 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
579 return std::optional(ViewIndex
{i
, false});
582 i
= (i
+ 1) % count();
583 } while (i
!= currentIndex());
588 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewShowingItem(const QUrl
&item
) const
590 // The item might not be loaded yet even though it exists. So instead
591 // we check if the folder containing the item is showing its contents.
592 const QUrl
dirContainingItem(item
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
594 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
595 // Is dirContainingitem the base url of a view?
596 auto viewOpenAtContainingDirectory
= viewOpenAtDirectory(dirContainingItem
);
597 if (viewOpenAtContainingDirectory
.has_value()) {
598 return viewOpenAtContainingDirectory
;
601 // Is dirContainingItem expanded in some tree-style view?
602 // The rest of this method is about figuring this out.
604 int i
= currentIndex();
608 // loop over the tabs starting from the current one
610 const auto tabPage
= tabPageAt(i
);
611 if (tabPage
->primaryViewContainer()->url().isParentOf(item
)) {
612 const KFileItem fileItemContainingItem
= tabPage
->primaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
613 if (!fileItemContainingItem
.isNull() && tabPage
->primaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
614 return std::optional(ViewIndex
{i
, true});
618 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url().isParentOf(item
)) {
619 const KFileItem fileItemContainingItem
= tabPage
->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
620 if (!fileItemContainingItem
.isNull() && tabPage
->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
621 return std::optional(ViewIndex
{i
, false});
625 i
= (i
+ 1) % count();
626 } while (i
!= currentIndex());
631 #include "moc_dolphintabwidget.cpp"