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 <kio/global.h>
20 #include <QApplication>
23 DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction
*navigatorsWidget
, QWidget
*parent
)
25 , m_lastViewedTab(nullptr)
26 , m_navigatorsWidget
{navigatorsWidget
}
28 KAcceleratorManager::setNoAccel(this);
30 connect(this, &DolphinTabWidget::tabCloseRequested
, this, QOverload
<int>::of(&DolphinTabWidget::closeTab
));
31 connect(this, &DolphinTabWidget::currentChanged
, this, &DolphinTabWidget::currentTabChanged
);
33 DolphinTabBar
*tabBar
= new DolphinTabBar(this);
34 connect(tabBar
, &DolphinTabBar::openNewActivatedTab
, this, QOverload
<int>::of(&DolphinTabWidget::openNewActivatedTab
));
35 connect(tabBar
, &DolphinTabBar::tabDropEvent
, this, &DolphinTabWidget::tabDropEvent
);
36 connect(tabBar
, &DolphinTabBar::tabDetachRequested
, this, &DolphinTabWidget::detachTab
);
40 setDocumentMode(true);
41 setElideMode(Qt::ElideRight
);
42 setUsesScrollButtons(true);
45 DolphinTabPage
*DolphinTabWidget::currentTabPage() const
47 return tabPageAt(currentIndex());
50 DolphinTabPage
*DolphinTabWidget::nextTabPage() const
52 const int index
= currentIndex() + 1;
53 return tabPageAt(index
< count() ? index
: 0);
56 DolphinTabPage
*DolphinTabWidget::prevTabPage() const
58 const int index
= currentIndex() - 1;
59 return tabPageAt(index
>= 0 ? index
: (count() - 1));
62 DolphinTabPage
*DolphinTabWidget::tabPageAt(const int index
) const
64 return static_cast<DolphinTabPage
*>(widget(index
));
67 void DolphinTabWidget::saveProperties(KConfigGroup
&group
) const
69 const int tabCount
= count();
70 group
.writeEntry("Tab Count", tabCount
);
71 group
.writeEntry("Active Tab Index", currentIndex());
73 for (int i
= 0; i
< tabCount
; ++i
) {
74 const DolphinTabPage
*tabPage
= tabPageAt(i
);
75 group
.writeEntry("Tab Data " % QString::number(i
), tabPage
->saveState());
79 void DolphinTabWidget::readProperties(const KConfigGroup
&group
)
81 const int tabCount
= group
.readEntry("Tab Count", 0);
82 for (int i
= 0; i
< tabCount
; ++i
) {
84 openNewActivatedTab();
86 const QByteArray state
= group
.readEntry("Tab Data " % QString::number(i
), QByteArray());
87 tabPageAt(i
)->restoreState(state
);
90 const int index
= group
.readEntry("Active Tab Index", 0);
91 setCurrentIndex(index
);
94 void DolphinTabWidget::refreshViews()
96 // Left-elision is better when showing full paths, since you care most
97 // about the current directory which is on the right
98 if (GeneralSettings::showFullPathInTitlebar()) {
99 setElideMode(Qt::ElideLeft
);
101 setElideMode(Qt::ElideRight
);
104 const int tabCount
= count();
105 for (int i
= 0; i
< tabCount
; ++i
) {
106 tabBar()->setTabText(i
, tabName(tabPageAt(i
)));
107 tabPageAt(i
)->refreshViews();
111 bool DolphinTabWidget::isUrlOpen(const QUrl
&url
) const
113 return viewOpenAtDirectory(url
).has_value();
116 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl
&urlOfItem
) const
118 return viewShowingItem(urlOfItem
).has_value();
121 void DolphinTabWidget::openNewActivatedTab()
123 std::unique_ptr
<DolphinUrlNavigator::VisualState
> oldNavigatorState
;
124 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget
->secondaryUrlNavigator()) {
125 oldNavigatorState
= m_navigatorsWidget
->primaryUrlNavigator()->visualState();
127 oldNavigatorState
= m_navigatorsWidget
->secondaryUrlNavigator()->visualState();
130 const DolphinViewContainer
*oldActiveViewContainer
= currentTabPage()->activeViewContainer();
131 Q_ASSERT(oldActiveViewContainer
);
133 openNewActivatedTab(oldActiveViewContainer
->url());
135 DolphinViewContainer
*newActiveViewContainer
= currentTabPage()->activeViewContainer();
136 Q_ASSERT(newActiveViewContainer
);
138 // The URL navigator of the new tab should have the same editable state
139 // as the current tab
140 newActiveViewContainer
->urlNavigator()->setVisualState(*oldNavigatorState
.get());
142 // Always focus the new tab's view
143 newActiveViewContainer
->view()->setFocus();
146 void DolphinTabWidget::openNewActivatedTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
)
148 openNewTab(primaryUrl
, secondaryUrl
);
149 if (GeneralSettings::openNewTabAfterLastTab()) {
150 setCurrentIndex(count() - 1);
152 setCurrentIndex(currentIndex() + 1);
156 void DolphinTabWidget::openNewTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
, DolphinTabWidget::NewTabPosition position
)
158 QWidget
*focusWidget
= QApplication::focusWidget();
160 DolphinTabPage
*tabPage
= new DolphinTabPage(primaryUrl
, secondaryUrl
, this);
161 tabPage
->setActive(false);
162 connect(tabPage
, &DolphinTabPage::activeViewChanged
, this, &DolphinTabWidget::activeViewChanged
);
163 connect(tabPage
, &DolphinTabPage::activeViewUrlChanged
, this, &DolphinTabWidget::tabUrlChanged
);
164 connect(tabPage
->activeViewContainer(), &DolphinViewContainer::captionChanged
, this, [this, tabPage
]() {
165 const int tabIndex
= indexOf(tabPage
);
166 Q_ASSERT(tabIndex
>= 0);
167 tabBar()->setTabText(tabIndex
, tabName(tabPage
));
170 if (position
== NewTabPosition::FollowSetting
) {
171 if (GeneralSettings::openNewTabAfterLastTab()) {
172 position
= NewTabPosition::AtEnd
;
174 position
= NewTabPosition::AfterCurrent
;
178 int newTabIndex
= -1;
179 if (position
== NewTabPosition::AfterCurrent
|| (position
== NewTabPosition::FollowSetting
&& !GeneralSettings::openNewTabAfterLastTab())) {
180 newTabIndex
= currentIndex() + 1;
183 insertTab(newTabIndex
, tabPage
, QIcon() /* loaded in tabInserted */, tabName(tabPage
));
186 // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened
187 // in background, assure that the previous focused widget gets the focus back.
188 focusWidget
->setFocus();
192 void DolphinTabWidget::openDirectories(const QList
<QUrl
> &dirs
, bool splitView
)
194 Q_ASSERT(dirs
.size() > 0);
196 bool somethingWasAlreadyOpen
= false;
198 QList
<QUrl
>::const_iterator it
= dirs
.constBegin();
199 while (it
!= dirs
.constEnd()) {
200 const QUrl
&primaryUrl
= *(it
++);
201 const std::optional
<ViewIndex
> viewIndexAtDirectory
= viewOpenAtDirectory(primaryUrl
);
203 // When the user asks for a URL that's already open,
204 // activate it instead of opening a new tab
205 if (viewIndexAtDirectory
.has_value()) {
206 somethingWasAlreadyOpen
= true;
207 activateViewContainerAt(viewIndexAtDirectory
.value());
208 } else if (splitView
&& (it
!= dirs
.constEnd())) {
209 const QUrl
&secondaryUrl
= *(it
++);
210 if (somethingWasAlreadyOpen
) {
211 openNewTab(primaryUrl
, secondaryUrl
);
213 openNewActivatedTab(primaryUrl
, secondaryUrl
);
216 if (somethingWasAlreadyOpen
) {
217 openNewTab(primaryUrl
);
219 openNewActivatedTab(primaryUrl
);
225 void DolphinTabWidget::openFiles(const QList
<QUrl
> &files
, bool splitView
)
227 Q_ASSERT(files
.size() > 0);
229 // Get all distinct directories from 'files'.
230 QList
<QUrl
> dirsThatNeedToBeOpened
;
231 QList
<QUrl
> dirsThatWereAlreadyOpen
;
232 for (const QUrl
&file
: files
) {
233 const QUrl
dir(file
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
234 if (dirsThatNeedToBeOpened
.contains(dir
) || dirsThatWereAlreadyOpen
.contains(dir
)) {
238 // The selecting of files that we do later will not work in views that already have items selected.
239 // So we check if dir is already open and clear the selection if it is. BUG: 417230
240 // We also make sure the view will be activated.
241 auto viewIndex
= viewShowingItem(file
);
242 if (viewIndex
.has_value()) {
243 viewContainerAt(viewIndex
.value())->view()->clearSelection();
244 activateViewContainerAt(viewIndex
.value());
245 dirsThatWereAlreadyOpen
.append(dir
);
247 dirsThatNeedToBeOpened
.append(dir
);
251 const int oldTabCount
= count();
252 // Open a tab for each directory. If the "split view" option is enabled,
253 // two directories are shown inside one tab (see openDirectories()).
254 if (dirsThatNeedToBeOpened
.size() > 0) {
255 openDirectories(dirsThatNeedToBeOpened
, splitView
);
257 const int tabCount
= count();
259 // Select the files. Although the files can be split between several
260 // tabs, there is no need to split 'files' accordingly, as
261 // the DolphinView will just ignore invalid selections.
262 for (int i
= 0; i
< tabCount
; ++i
) {
263 DolphinTabPage
*tabPage
= tabPageAt(i
);
264 tabPage
->markUrlsAsSelected(files
);
265 tabPage
->markUrlAsCurrent(files
.first());
266 if (i
< oldTabCount
) {
267 // Force selection of file if directory was already open, BUG: 417230
268 tabPage
->activeViewContainer()->view()->updateViewState();
273 void DolphinTabWidget::closeTab()
275 closeTab(currentIndex());
278 void DolphinTabWidget::closeTab(const int index
)
280 Q_ASSERT(index
>= 0);
281 Q_ASSERT(index
< count());
284 // Close Dolphin when closing the last tab.
285 parentWidget()->close();
289 DolphinTabPage
*tabPage
= tabPageAt(index
);
290 Q_EMIT
rememberClosedTab(tabPage
->activeViewContainer()->url(), tabPage
->saveState());
293 tabPage
->deleteLater();
296 void DolphinTabWidget::activateTab(const int index
)
298 if (index
< count()) {
299 setCurrentIndex(index
);
303 void DolphinTabWidget::activateLastTab()
305 setCurrentIndex(count() - 1);
308 void DolphinTabWidget::activateNextTab()
310 const int index
= currentIndex() + 1;
311 setCurrentIndex(index
< count() ? index
: 0);
314 void DolphinTabWidget::activatePrevTab()
316 const int index
= currentIndex() - 1;
317 setCurrentIndex(index
>= 0 ? index
: (count() - 1));
320 void DolphinTabWidget::restoreClosedTab(const QByteArray
&state
)
322 openNewActivatedTab();
323 currentTabPage()->restoreState(state
);
326 void DolphinTabWidget::copyToInactiveSplitView()
328 const DolphinTabPage
*tabPage
= currentTabPage();
329 if (!tabPage
->splitViewEnabled()) {
333 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
334 if (selectedItems
.isEmpty()) {
338 DolphinView
*inactiveView
;
339 if (tabPage
->primaryViewActive()) {
340 inactiveView
= tabPage
->secondaryViewContainer()->view();
342 inactiveView
= tabPage
->primaryViewContainer()->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
*inactiveView
;
360 if (tabPage
->primaryViewActive()) {
361 inactiveView
= tabPage
->secondaryViewContainer()->view();
363 inactiveView
= tabPage
->primaryViewContainer()->view();
365 inactiveView
->moveSelectedItems(selectedItems
, inactiveView
->url());
368 void DolphinTabWidget::detachTab(int index
)
370 Q_ASSERT(index
>= 0);
374 const DolphinTabPage
*tabPage
= tabPageAt(index
);
375 args
<< tabPage
->primaryViewContainer()->url().url();
376 if (tabPage
->splitViewEnabled()) {
377 args
<< tabPage
->secondaryViewContainer()->url().url();
378 args
<< QStringLiteral("--split");
380 args
<< QStringLiteral("--new-window");
382 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
383 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
389 void DolphinTabWidget::openNewActivatedTab(int index
)
391 Q_ASSERT(index
>= 0);
392 const DolphinTabPage
*tabPage
= tabPageAt(index
);
393 openNewActivatedTab(tabPage
->activeViewContainer()->url());
396 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
*event
)
399 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
400 view
->dropUrls(view
->url(), event
, view
);
402 const auto urls
= event
->mimeData()->urls();
404 for (const QUrl
&url
: urls
) {
405 auto *job
= KIO::statDetails(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
406 connect(job
, &KJob::result
, this, [this, job
]() {
407 if (!job
->error() && job
->statResult().isDir()) {
408 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
415 void DolphinTabWidget::tabUrlChanged(const QUrl
&url
)
417 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
419 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
420 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
421 if (tabBar()->isVisible()) {
422 // ensure the path url ends with a slash to have proper folder icon for remote folders
423 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
424 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
426 // Mark as dirty, actually load once the tab bar actually gets shown
427 tabBar()->setTabIcon(index
, QIcon());
430 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
431 if (index
== currentIndex()) {
432 Q_EMIT
currentUrlChanged(url
);
437 void DolphinTabWidget::currentTabChanged(int index
)
439 DolphinTabPage
*tabPage
= tabPageAt(index
);
440 if (tabPage
== m_lastViewedTab
) {
443 if (m_lastViewedTab
) {
444 m_lastViewedTab
->disconnectNavigators();
445 m_lastViewedTab
->setActive(false);
447 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
448 m_navigatorsWidget
->createSecondaryUrlNavigator();
450 DolphinViewContainer
*viewContainer
= tabPage
->activeViewContainer();
451 Q_EMIT
activeViewChanged(viewContainer
);
452 Q_EMIT
currentUrlChanged(viewContainer
->url());
453 tabPage
->setActive(true);
454 tabPage
->connectNavigators(m_navigatorsWidget
);
455 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
456 m_lastViewedTab
= tabPage
;
459 void DolphinTabWidget::tabInserted(int index
)
461 QTabWidget::tabInserted(index
);
464 // Resolve all pending tab icons
465 for (int i
= 0; i
< count(); ++i
) {
466 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
467 if (tabBar()->tabIcon(i
).isNull()) {
468 // ensure the path url ends with a slash to have proper folder icon for remote folders
469 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
470 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
472 if (tabBar()->tabToolTip(i
).isEmpty()) {
473 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
480 Q_EMIT
tabCountChanged(count());
483 void DolphinTabWidget::tabRemoved(int index
)
485 QTabWidget::tabRemoved(index
);
487 // If only one tab is left, then remove the tab entry so that
488 // closing the last tab is not possible.
493 Q_EMIT
tabCountChanged(count());
496 QString
DolphinTabWidget::tabName(DolphinTabPage
*tabPage
) const
503 if (tabPage
->splitViewEnabled()) {
504 if (tabPage
->primaryViewActive()) {
505 // 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
506 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
507 name
= i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
509 // 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
510 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
511 name
= i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
514 name
= tabPage
->activeViewContainer()->caption();
518 // Make sure that a '&' inside the directory name is displayed correctly
519 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
520 return name
.replace('&', QLatin1String("&&"));
523 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
525 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
529 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
532 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
534 activateTab(viewIndex
.tabIndex
);
535 auto viewContainer
= viewContainerAt(viewIndex
);
536 if (!viewContainer
) {
539 viewContainer
->setActive(true);
540 return viewContainer
;
543 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
&directory
) const
545 int i
= currentIndex();
549 // loop over the tabs starting from the current one
551 const auto tabPage
= tabPageAt(i
);
552 if (tabPage
->primaryViewContainer()->url() == directory
) {
553 return std::optional(ViewIndex
{i
, true});
556 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
557 return std::optional(ViewIndex
{i
, false});
560 i
= (i
+ 1) % count();
561 } while (i
!= currentIndex());
566 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewShowingItem(const QUrl
&item
) const
568 // The item might not be loaded yet even though it exists. So instead
569 // we check if the folder containing the item is showing its contents.
570 const QUrl
dirContainingItem(item
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
572 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
573 // Is dirContainingitem the base url of a view?
574 auto viewOpenAtContainingDirectory
= viewOpenAtDirectory(dirContainingItem
);
575 if (viewOpenAtContainingDirectory
.has_value()) {
576 return viewOpenAtContainingDirectory
;
579 // Is dirContainingItem expanded in some tree-style view?
580 // The rest of this method is about figuring this out.
582 int i
= currentIndex();
586 // loop over the tabs starting from the current one
588 const auto tabPage
= tabPageAt(i
);
589 if (tabPage
->primaryViewContainer()->url().isParentOf(item
)) {
590 const KFileItem fileItemContainingItem
= tabPage
->primaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
591 if (!fileItemContainingItem
.isNull() && tabPage
->primaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
592 return std::optional(ViewIndex
{i
, true});
596 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url().isParentOf(item
)) {
597 const KFileItem fileItemContainingItem
= tabPage
->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
598 if (!fileItemContainingItem
.isNull() && tabPage
->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
599 return std::optional(ViewIndex
{i
, false});
603 i
= (i
+ 1) % count();
604 } while (i
!= currentIndex());