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"
13 #include <KAcceleratorManager>
14 #include <KConfigGroup>
15 #include <KIO/CommandLauncherJob>
16 #include <KLocalizedString>
18 #include <KStringHandler>
19 #include <kio/global.h>
21 #include <QApplication>
24 DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction
*navigatorsWidget
, QWidget
*parent
)
26 , m_lastViewedTab(nullptr)
27 , m_navigatorsWidget
{navigatorsWidget
}
29 KAcceleratorManager::setNoAccel(this);
31 connect(this, &DolphinTabWidget::tabCloseRequested
, this, QOverload
<int>::of(&DolphinTabWidget::closeTab
));
32 connect(this, &DolphinTabWidget::currentChanged
, this, &DolphinTabWidget::currentTabChanged
);
34 DolphinTabBar
*tabBar
= new DolphinTabBar(this);
35 connect(tabBar
, &DolphinTabBar::openNewActivatedTab
, this, QOverload
<int>::of(&DolphinTabWidget::openNewActivatedTab
));
36 connect(tabBar
, &DolphinTabBar::tabDropEvent
, this, &DolphinTabWidget::tabDropEvent
);
37 connect(tabBar
, &DolphinTabBar::tabDetachRequested
, this, &DolphinTabWidget::detachTab
);
40 setDocumentMode(true);
41 setElideMode(Qt::ElideRight
);
42 setUsesScrollButtons(true);
43 setTabBarAutoHide(true);
46 DolphinTabPage
*DolphinTabWidget::currentTabPage() const
48 return tabPageAt(currentIndex());
51 DolphinTabPage
*DolphinTabWidget::nextTabPage() const
53 const int index
= currentIndex() + 1;
54 return tabPageAt(index
< count() ? index
: 0);
57 DolphinTabPage
*DolphinTabWidget::prevTabPage() const
59 const int index
= currentIndex() - 1;
60 return tabPageAt(index
>= 0 ? index
: (count() - 1));
63 DolphinTabPage
*DolphinTabWidget::tabPageAt(const int index
) const
65 return static_cast<DolphinTabPage
*>(widget(index
));
68 void DolphinTabWidget::saveProperties(KConfigGroup
&group
) const
70 const int tabCount
= count();
71 group
.writeEntry("Tab Count", tabCount
);
72 group
.writeEntry("Active Tab Index", currentIndex());
74 for (int i
= 0; i
< tabCount
; ++i
) {
75 const DolphinTabPage
*tabPage
= tabPageAt(i
);
76 group
.writeEntry("Tab Data " % QString::number(i
), tabPage
->saveState());
80 void DolphinTabWidget::readProperties(const KConfigGroup
&group
)
82 const int tabCount
= group
.readEntry("Tab Count", 0);
83 for (int i
= 0; i
< tabCount
; ++i
) {
85 openNewActivatedTab();
87 const QByteArray state
= group
.readEntry("Tab Data " % QString::number(i
), QByteArray());
88 tabPageAt(i
)->restoreState(state
);
91 const int index
= group
.readEntry("Active Tab Index", 0);
92 setCurrentIndex(index
);
95 void DolphinTabWidget::refreshViews()
97 // Left-elision is better when showing full paths, since you care most
98 // about the current directory which is on the right
99 if (GeneralSettings::showFullPathInTitlebar()) {
100 setElideMode(Qt::ElideLeft
);
102 setElideMode(Qt::ElideRight
);
105 const int tabCount
= count();
106 for (int i
= 0; i
< tabCount
; ++i
) {
108 tabPageAt(i
)->refreshViews();
112 void DolphinTabWidget::updateTabName(int index
)
114 Q_ASSERT(index
>= 0);
115 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
118 bool DolphinTabWidget::isUrlOpen(const QUrl
&url
) const
120 return viewOpenAtDirectory(url
).has_value();
123 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl
&urlOfItem
) const
125 return viewShowingItem(urlOfItem
).has_value();
128 void DolphinTabWidget::openNewActivatedTab()
130 std::unique_ptr
<DolphinUrlNavigator::VisualState
> oldNavigatorState
;
131 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget
->secondaryUrlNavigator()) {
132 oldNavigatorState
= m_navigatorsWidget
->primaryUrlNavigator()->visualState();
134 oldNavigatorState
= m_navigatorsWidget
->secondaryUrlNavigator()->visualState();
137 const DolphinViewContainer
*oldActiveViewContainer
= currentTabPage()->activeViewContainer();
138 Q_ASSERT(oldActiveViewContainer
);
140 openNewActivatedTab(oldActiveViewContainer
->url());
142 DolphinViewContainer
*newActiveViewContainer
= currentTabPage()->activeViewContainer();
143 Q_ASSERT(newActiveViewContainer
);
145 // The URL navigator of the new tab should have the same editable state
146 // as the current tab
147 newActiveViewContainer
->urlNavigator()->setVisualState(*oldNavigatorState
.get());
149 // Always focus the new tab's view
150 newActiveViewContainer
->view()->setFocus();
153 void DolphinTabWidget::openNewActivatedTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
)
155 openNewTab(primaryUrl
, secondaryUrl
);
156 if (GeneralSettings::openNewTabAfterLastTab()) {
157 setCurrentIndex(count() - 1);
159 setCurrentIndex(currentIndex() + 1);
163 void DolphinTabWidget::openNewTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
, DolphinTabWidget::NewTabPosition position
)
165 QWidget
*focusWidget
= QApplication::focusWidget();
167 DolphinTabPage
*tabPage
= new DolphinTabPage(primaryUrl
, secondaryUrl
, this);
168 tabPage
->setActive(false);
169 connect(tabPage
, &DolphinTabPage::activeViewChanged
, this, &DolphinTabWidget::activeViewChanged
);
170 connect(tabPage
, &DolphinTabPage::activeViewUrlChanged
, this, &DolphinTabWidget::tabUrlChanged
);
171 connect(tabPage
->activeViewContainer(), &DolphinViewContainer::captionChanged
, this, [this, tabPage
]() {
172 updateTabName(indexOf(tabPage
));
175 if (position
== NewTabPosition::FollowSetting
) {
176 if (GeneralSettings::openNewTabAfterLastTab()) {
177 position
= NewTabPosition::AtEnd
;
179 position
= NewTabPosition::AfterCurrent
;
183 int newTabIndex
= -1;
184 if (position
== NewTabPosition::AfterCurrent
|| (position
== NewTabPosition::FollowSetting
&& !GeneralSettings::openNewTabAfterLastTab())) {
185 newTabIndex
= currentIndex() + 1;
188 insertTab(newTabIndex
, tabPage
, QIcon() /* loaded in tabInserted */, tabName(tabPage
));
191 // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened
192 // in background, assure that the previous focused widget gets the focus back.
193 focusWidget
->setFocus();
197 void DolphinTabWidget::openDirectories(const QList
<QUrl
> &dirs
, bool splitView
)
199 Q_ASSERT(dirs
.size() > 0);
201 bool somethingWasAlreadyOpen
= false;
203 QList
<QUrl
>::const_iterator it
= dirs
.constBegin();
204 while (it
!= dirs
.constEnd()) {
205 const QUrl
&primaryUrl
= *(it
++);
206 const std::optional
<ViewIndex
> viewIndexAtDirectory
= viewOpenAtDirectory(primaryUrl
);
208 // When the user asks for a URL that's already open,
209 // activate it instead of opening a new tab
210 if (viewIndexAtDirectory
.has_value()) {
211 somethingWasAlreadyOpen
= true;
212 activateViewContainerAt(viewIndexAtDirectory
.value());
213 } else if (splitView
&& (it
!= dirs
.constEnd())) {
214 const QUrl
&secondaryUrl
= *(it
++);
215 if (somethingWasAlreadyOpen
) {
216 openNewTab(primaryUrl
, secondaryUrl
);
218 openNewActivatedTab(primaryUrl
, secondaryUrl
);
221 if (somethingWasAlreadyOpen
) {
222 openNewTab(primaryUrl
);
224 openNewActivatedTab(primaryUrl
);
230 void DolphinTabWidget::openFiles(const QList
<QUrl
> &files
, bool splitView
)
232 Q_ASSERT(files
.size() > 0);
234 // Get all distinct directories from 'files'.
235 QList
<QUrl
> dirsThatNeedToBeOpened
;
236 QList
<QUrl
> dirsThatWereAlreadyOpen
;
237 for (const QUrl
&file
: files
) {
238 const QUrl
dir(file
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
239 if (dirsThatNeedToBeOpened
.contains(dir
) || dirsThatWereAlreadyOpen
.contains(dir
)) {
243 // The selecting of files that we do later will not work in views that already have items selected.
244 // So we check if dir is already open and clear the selection if it is. BUG: 417230
245 // We also make sure the view will be activated.
246 auto viewIndex
= viewShowingItem(file
);
247 if (viewIndex
.has_value()) {
248 viewContainerAt(viewIndex
.value())->view()->clearSelection();
249 activateViewContainerAt(viewIndex
.value());
250 dirsThatWereAlreadyOpen
.append(dir
);
252 dirsThatNeedToBeOpened
.append(dir
);
256 const int oldTabCount
= count();
257 // Open a tab for each directory. If the "split view" option is enabled,
258 // two directories are shown inside one tab (see openDirectories()).
259 if (dirsThatNeedToBeOpened
.size() > 0) {
260 openDirectories(dirsThatNeedToBeOpened
, splitView
);
262 const int tabCount
= count();
264 // Select the files. Although the files can be split between several
265 // tabs, there is no need to split 'files' accordingly, as
266 // the DolphinView will just ignore invalid selections.
267 for (int i
= 0; i
< tabCount
; ++i
) {
268 DolphinTabPage
*tabPage
= tabPageAt(i
);
269 tabPage
->markUrlsAsSelected(files
);
270 tabPage
->markUrlAsCurrent(files
.first());
271 if (i
< oldTabCount
) {
272 // Force selection of file if directory was already open, BUG: 417230
273 tabPage
->activeViewContainer()->view()->updateViewState();
278 void DolphinTabWidget::closeTab()
280 closeTab(currentIndex());
283 void DolphinTabWidget::closeTab(const int index
)
285 Q_ASSERT(index
>= 0);
286 Q_ASSERT(index
< count());
289 // Close Dolphin when closing the last tab.
290 parentWidget()->close();
294 DolphinTabPage
*tabPage
= tabPageAt(index
);
295 Q_EMIT
rememberClosedTab(tabPage
->activeViewContainer()->url(), tabPage
->saveState());
298 tabPage
->deleteLater();
301 void DolphinTabWidget::activateTab(const int index
)
303 if (index
< count()) {
304 setCurrentIndex(index
);
308 void DolphinTabWidget::activateLastTab()
310 setCurrentIndex(count() - 1);
313 void DolphinTabWidget::activateNextTab()
315 const int index
= currentIndex() + 1;
316 setCurrentIndex(index
< count() ? index
: 0);
319 void DolphinTabWidget::activatePrevTab()
321 const int index
= currentIndex() - 1;
322 setCurrentIndex(index
>= 0 ? index
: (count() - 1));
325 void DolphinTabWidget::restoreClosedTab(const QByteArray
&state
)
327 openNewActivatedTab();
328 currentTabPage()->restoreState(state
);
331 void DolphinTabWidget::copyToInactiveSplitView()
333 const DolphinTabPage
*tabPage
= currentTabPage();
334 if (!tabPage
->splitViewEnabled()) {
338 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
339 if (selectedItems
.isEmpty()) {
343 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
344 inactiveView
->copySelectedItems(selectedItems
, inactiveView
->url());
347 void DolphinTabWidget::moveToInactiveSplitView()
349 const DolphinTabPage
*tabPage
= currentTabPage();
350 if (!tabPage
->splitViewEnabled()) {
354 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
355 if (selectedItems
.isEmpty()) {
359 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
360 inactiveView
->moveSelectedItems(selectedItems
, inactiveView
->url());
363 void DolphinTabWidget::detachTab(int index
)
365 Q_ASSERT(index
>= 0);
369 const DolphinTabPage
*tabPage
= tabPageAt(index
);
370 args
<< tabPage
->primaryViewContainer()->url().url();
371 if (tabPage
->splitViewEnabled()) {
372 args
<< tabPage
->secondaryViewContainer()->url().url();
373 args
<< QStringLiteral("--split");
375 args
<< QStringLiteral("--new-window");
377 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
378 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
384 void DolphinTabWidget::openNewActivatedTab(int index
)
386 Q_ASSERT(index
>= 0);
387 const DolphinTabPage
*tabPage
= tabPageAt(index
);
388 openNewActivatedTab(tabPage
->activeViewContainer()->url());
391 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
*event
)
394 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
395 view
->dropUrls(view
->url(), event
, view
);
397 const auto urls
= event
->mimeData()->urls();
399 for (const QUrl
&url
: urls
) {
400 auto *job
= KIO::stat(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
401 connect(job
, &KJob::result
, this, [this, job
]() {
402 if (!job
->error() && job
->statResult().isDir()) {
403 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
410 void DolphinTabWidget::tabUrlChanged(const QUrl
&url
)
412 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
414 updateTabName(index
);
415 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
416 if (tabBar()->isVisible()) {
417 // ensure the path url ends with a slash to have proper folder icon for remote folders
418 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
419 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
421 // Mark as dirty, actually load once the tab bar actually gets shown
422 tabBar()->setTabIcon(index
, QIcon());
425 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
426 if (index
== currentIndex()) {
427 Q_EMIT
currentUrlChanged(url
);
430 Q_EMIT
urlChanged(url
);
434 void DolphinTabWidget::currentTabChanged(int index
)
436 DolphinTabPage
*tabPage
= tabPageAt(index
);
437 if (tabPage
== m_lastViewedTab
) {
440 if (m_lastViewedTab
) {
441 m_lastViewedTab
->disconnectNavigators();
442 m_lastViewedTab
->setActive(false);
444 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
445 m_navigatorsWidget
->createSecondaryUrlNavigator();
447 DolphinViewContainer
*viewContainer
= tabPage
->activeViewContainer();
448 Q_EMIT
activeViewChanged(viewContainer
);
449 Q_EMIT
currentUrlChanged(viewContainer
->url());
450 tabPage
->setActive(true);
451 tabPage
->connectNavigators(m_navigatorsWidget
);
452 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
453 m_lastViewedTab
= tabPage
;
456 void DolphinTabWidget::tabInserted(int index
)
458 QTabWidget::tabInserted(index
);
460 if (tabBar()->isVisible()) {
461 // Resolve all pending tab icons
462 for (int i
= 0; i
< count(); ++i
) {
463 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
464 if (tabBar()->tabIcon(i
).isNull()) {
465 // ensure the path url ends with a slash to have proper folder icon for remote folders
466 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
467 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
469 if (tabBar()->tabToolTip(i
).isEmpty()) {
470 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
475 Q_EMIT
tabCountChanged(count());
478 void DolphinTabWidget::tabRemoved(int index
)
480 QTabWidget::tabRemoved(index
);
482 Q_EMIT
tabCountChanged(count());
485 QString
DolphinTabWidget::tabName(DolphinTabPage
*tabPage
) const
492 if (tabPage
->splitViewEnabled()) {
493 if (tabPage
->primaryViewActive()) {
494 // 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
495 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
496 name
= i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
498 // 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
499 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
500 name
= i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
503 name
= tabPage
->activeViewContainer()->caption();
507 // Make sure that a '&' inside the directory name is displayed correctly
508 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
509 return KStringHandler::rsqueeze(name
.replace('&', QLatin1String("&&")), 40 /* default maximum visible folder name visible */);
512 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
514 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
518 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
521 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
523 activateTab(viewIndex
.tabIndex
);
524 auto viewContainer
= viewContainerAt(viewIndex
);
525 if (!viewContainer
) {
528 viewContainer
->setActive(true);
529 return viewContainer
;
532 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
&directory
) const
534 int i
= currentIndex();
538 // loop over the tabs starting from the current one
540 const auto tabPage
= tabPageAt(i
);
541 if (tabPage
->primaryViewContainer()->url() == directory
) {
542 return std::optional(ViewIndex
{i
, true});
545 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
546 return std::optional(ViewIndex
{i
, false});
549 i
= (i
+ 1) % count();
550 } while (i
!= currentIndex());
555 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewShowingItem(const QUrl
&item
) const
557 // The item might not be loaded yet even though it exists. So instead
558 // we check if the folder containing the item is showing its contents.
559 const QUrl
dirContainingItem(item
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
561 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
562 // Is dirContainingitem the base url of a view?
563 auto viewOpenAtContainingDirectory
= viewOpenAtDirectory(dirContainingItem
);
564 if (viewOpenAtContainingDirectory
.has_value()) {
565 return viewOpenAtContainingDirectory
;
568 // Is dirContainingItem expanded in some tree-style view?
569 // The rest of this method is about figuring this out.
571 int i
= currentIndex();
575 // loop over the tabs starting from the current one
577 const auto tabPage
= tabPageAt(i
);
578 if (tabPage
->primaryViewContainer()->url().isParentOf(item
)) {
579 const KFileItem fileItemContainingItem
= tabPage
->primaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
580 if (!fileItemContainingItem
.isNull() && tabPage
->primaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
581 return std::optional(ViewIndex
{i
, true});
585 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url().isParentOf(item
)) {
586 const KFileItem fileItemContainingItem
= tabPage
->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
587 if (!fileItemContainingItem
.isNull() && tabPage
->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
588 return std::optional(ViewIndex
{i
, false});
592 i
= (i
+ 1) % count();
593 } while (i
!= currentIndex());
598 #include "moc_dolphintabwidget.cpp"