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
);
41 setDocumentMode(true);
42 setElideMode(Qt::ElideRight
);
43 setUsesScrollButtons(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
) {
107 tabBar()->setTabText(i
, tabName(tabPageAt(i
)));
108 tabPageAt(i
)->refreshViews();
112 bool DolphinTabWidget::isUrlOpen(const QUrl
&url
) const
114 return viewOpenAtDirectory(url
).has_value();
117 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl
&urlOfItem
) const
119 return viewShowingItem(urlOfItem
).has_value();
122 void DolphinTabWidget::openNewActivatedTab()
124 std::unique_ptr
<DolphinUrlNavigator::VisualState
> oldNavigatorState
;
125 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget
->secondaryUrlNavigator()) {
126 oldNavigatorState
= m_navigatorsWidget
->primaryUrlNavigator()->visualState();
128 oldNavigatorState
= m_navigatorsWidget
->secondaryUrlNavigator()->visualState();
131 const DolphinViewContainer
*oldActiveViewContainer
= currentTabPage()->activeViewContainer();
132 Q_ASSERT(oldActiveViewContainer
);
134 openNewActivatedTab(oldActiveViewContainer
->url());
136 DolphinViewContainer
*newActiveViewContainer
= currentTabPage()->activeViewContainer();
137 Q_ASSERT(newActiveViewContainer
);
139 // The URL navigator of the new tab should have the same editable state
140 // as the current tab
141 newActiveViewContainer
->urlNavigator()->setVisualState(*oldNavigatorState
.get());
143 // Always focus the new tab's view
144 newActiveViewContainer
->view()->setFocus();
147 void DolphinTabWidget::openNewActivatedTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
)
149 openNewTab(primaryUrl
, secondaryUrl
);
150 if (GeneralSettings::openNewTabAfterLastTab()) {
151 setCurrentIndex(count() - 1);
153 setCurrentIndex(currentIndex() + 1);
157 void DolphinTabWidget::openNewTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
, DolphinTabWidget::NewTabPosition position
)
159 QWidget
*focusWidget
= QApplication::focusWidget();
161 DolphinTabPage
*tabPage
= new DolphinTabPage(primaryUrl
, secondaryUrl
, this);
162 tabPage
->setActive(false);
163 connect(tabPage
, &DolphinTabPage::activeViewChanged
, this, &DolphinTabWidget::activeViewChanged
);
164 connect(tabPage
, &DolphinTabPage::activeViewUrlChanged
, this, &DolphinTabWidget::tabUrlChanged
);
165 connect(tabPage
->activeViewContainer(), &DolphinViewContainer::captionChanged
, this, [this, tabPage
]() {
166 const int tabIndex
= indexOf(tabPage
);
167 Q_ASSERT(tabIndex
>= 0);
168 tabBar()->setTabText(tabIndex
, tabName(tabPage
));
171 if (position
== NewTabPosition::FollowSetting
) {
172 if (GeneralSettings::openNewTabAfterLastTab()) {
173 position
= NewTabPosition::AtEnd
;
175 position
= NewTabPosition::AfterCurrent
;
179 int newTabIndex
= -1;
180 if (position
== NewTabPosition::AfterCurrent
|| (position
== NewTabPosition::FollowSetting
&& !GeneralSettings::openNewTabAfterLastTab())) {
181 newTabIndex
= currentIndex() + 1;
184 insertTab(newTabIndex
, tabPage
, QIcon() /* loaded in tabInserted */, tabName(tabPage
));
187 // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened
188 // in background, assure that the previous focused widget gets the focus back.
189 focusWidget
->setFocus();
193 void DolphinTabWidget::openDirectories(const QList
<QUrl
> &dirs
, bool splitView
)
195 Q_ASSERT(dirs
.size() > 0);
197 bool somethingWasAlreadyOpen
= false;
199 QList
<QUrl
>::const_iterator it
= dirs
.constBegin();
200 while (it
!= dirs
.constEnd()) {
201 const QUrl
&primaryUrl
= *(it
++);
202 const std::optional
<ViewIndex
> viewIndexAtDirectory
= viewOpenAtDirectory(primaryUrl
);
204 // When the user asks for a URL that's already open,
205 // activate it instead of opening a new tab
206 if (viewIndexAtDirectory
.has_value()) {
207 somethingWasAlreadyOpen
= true;
208 activateViewContainerAt(viewIndexAtDirectory
.value());
209 } else if (splitView
&& (it
!= dirs
.constEnd())) {
210 const QUrl
&secondaryUrl
= *(it
++);
211 if (somethingWasAlreadyOpen
) {
212 openNewTab(primaryUrl
, secondaryUrl
);
214 openNewActivatedTab(primaryUrl
, secondaryUrl
);
217 if (somethingWasAlreadyOpen
) {
218 openNewTab(primaryUrl
);
220 openNewActivatedTab(primaryUrl
);
226 void DolphinTabWidget::openFiles(const QList
<QUrl
> &files
, bool splitView
)
228 Q_ASSERT(files
.size() > 0);
230 // Get all distinct directories from 'files'.
231 QList
<QUrl
> dirsThatNeedToBeOpened
;
232 QList
<QUrl
> dirsThatWereAlreadyOpen
;
233 for (const QUrl
&file
: files
) {
234 const QUrl
dir(file
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
235 if (dirsThatNeedToBeOpened
.contains(dir
) || dirsThatWereAlreadyOpen
.contains(dir
)) {
239 // The selecting of files that we do later will not work in views that already have items selected.
240 // So we check if dir is already open and clear the selection if it is. BUG: 417230
241 // We also make sure the view will be activated.
242 auto viewIndex
= viewShowingItem(file
);
243 if (viewIndex
.has_value()) {
244 viewContainerAt(viewIndex
.value())->view()->clearSelection();
245 activateViewContainerAt(viewIndex
.value());
246 dirsThatWereAlreadyOpen
.append(dir
);
248 dirsThatNeedToBeOpened
.append(dir
);
252 const int oldTabCount
= count();
253 // Open a tab for each directory. If the "split view" option is enabled,
254 // two directories are shown inside one tab (see openDirectories()).
255 if (dirsThatNeedToBeOpened
.size() > 0) {
256 openDirectories(dirsThatNeedToBeOpened
, splitView
);
258 const int tabCount
= count();
260 // Select the files. Although the files can be split between several
261 // tabs, there is no need to split 'files' accordingly, as
262 // the DolphinView will just ignore invalid selections.
263 for (int i
= 0; i
< tabCount
; ++i
) {
264 DolphinTabPage
*tabPage
= tabPageAt(i
);
265 tabPage
->markUrlsAsSelected(files
);
266 tabPage
->markUrlAsCurrent(files
.first());
267 if (i
< oldTabCount
) {
268 // Force selection of file if directory was already open, BUG: 417230
269 tabPage
->activeViewContainer()->view()->updateViewState();
274 void DolphinTabWidget::closeTab()
276 closeTab(currentIndex());
279 void DolphinTabWidget::closeTab(const int index
)
281 Q_ASSERT(index
>= 0);
282 Q_ASSERT(index
< count());
285 // Close Dolphin when closing the last tab.
286 parentWidget()->close();
290 DolphinTabPage
*tabPage
= tabPageAt(index
);
291 Q_EMIT
rememberClosedTab(tabPage
->activeViewContainer()->url(), tabPage
->saveState());
294 tabPage
->deleteLater();
297 void DolphinTabWidget::activateTab(const int index
)
299 if (index
< count()) {
300 setCurrentIndex(index
);
304 void DolphinTabWidget::activateLastTab()
306 setCurrentIndex(count() - 1);
309 void DolphinTabWidget::activateNextTab()
311 const int index
= currentIndex() + 1;
312 setCurrentIndex(index
< count() ? index
: 0);
315 void DolphinTabWidget::activatePrevTab()
317 const int index
= currentIndex() - 1;
318 setCurrentIndex(index
>= 0 ? index
: (count() - 1));
321 void DolphinTabWidget::restoreClosedTab(const QByteArray
&state
)
323 openNewActivatedTab();
324 currentTabPage()->restoreState(state
);
327 void DolphinTabWidget::copyToInactiveSplitView()
329 const DolphinTabPage
*tabPage
= currentTabPage();
330 if (!tabPage
->splitViewEnabled()) {
334 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
335 if (selectedItems
.isEmpty()) {
339 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
340 inactiveView
->copySelectedItems(selectedItems
, inactiveView
->url());
343 void DolphinTabWidget::moveToInactiveSplitView()
345 const DolphinTabPage
*tabPage
= currentTabPage();
346 if (!tabPage
->splitViewEnabled()) {
350 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
351 if (selectedItems
.isEmpty()) {
355 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
356 inactiveView
->moveSelectedItems(selectedItems
, inactiveView
->url());
359 void DolphinTabWidget::detachTab(int index
)
361 Q_ASSERT(index
>= 0);
365 const DolphinTabPage
*tabPage
= tabPageAt(index
);
366 args
<< tabPage
->primaryViewContainer()->url().url();
367 if (tabPage
->splitViewEnabled()) {
368 args
<< tabPage
->secondaryViewContainer()->url().url();
369 args
<< QStringLiteral("--split");
371 args
<< QStringLiteral("--new-window");
373 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
374 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
380 void DolphinTabWidget::openNewActivatedTab(int index
)
382 Q_ASSERT(index
>= 0);
383 const DolphinTabPage
*tabPage
= tabPageAt(index
);
384 openNewActivatedTab(tabPage
->activeViewContainer()->url());
387 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
*event
)
390 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
391 view
->dropUrls(view
->url(), event
, view
);
393 const auto urls
= event
->mimeData()->urls();
395 for (const QUrl
&url
: urls
) {
396 auto *job
= KIO::stat(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
397 connect(job
, &KJob::result
, this, [this, job
]() {
398 if (!job
->error() && job
->statResult().isDir()) {
399 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
406 void DolphinTabWidget::tabUrlChanged(const QUrl
&url
)
408 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
410 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
411 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
412 if (tabBar()->isVisible()) {
413 // ensure the path url ends with a slash to have proper folder icon for remote folders
414 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
415 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
417 // Mark as dirty, actually load once the tab bar actually gets shown
418 tabBar()->setTabIcon(index
, QIcon());
421 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
422 if (index
== currentIndex()) {
423 Q_EMIT
currentUrlChanged(url
);
428 void DolphinTabWidget::currentTabChanged(int index
)
430 DolphinTabPage
*tabPage
= tabPageAt(index
);
431 if (tabPage
== m_lastViewedTab
) {
434 if (m_lastViewedTab
) {
435 m_lastViewedTab
->disconnectNavigators();
436 m_lastViewedTab
->setActive(false);
438 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
439 m_navigatorsWidget
->createSecondaryUrlNavigator();
441 DolphinViewContainer
*viewContainer
= tabPage
->activeViewContainer();
442 Q_EMIT
activeViewChanged(viewContainer
);
443 Q_EMIT
currentUrlChanged(viewContainer
->url());
444 tabPage
->setActive(true);
445 tabPage
->connectNavigators(m_navigatorsWidget
);
446 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
447 m_lastViewedTab
= tabPage
;
450 void DolphinTabWidget::tabInserted(int index
)
452 QTabWidget::tabInserted(index
);
455 // Resolve all pending tab icons
456 for (int i
= 0; i
< count(); ++i
) {
457 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
458 if (tabBar()->tabIcon(i
).isNull()) {
459 // ensure the path url ends with a slash to have proper folder icon for remote folders
460 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
461 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
463 if (tabBar()->tabToolTip(i
).isEmpty()) {
464 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
471 Q_EMIT
tabCountChanged(count());
474 void DolphinTabWidget::tabRemoved(int index
)
476 QTabWidget::tabRemoved(index
);
478 // If only one tab is left, then remove the tab entry so that
479 // closing the last tab is not possible.
484 Q_EMIT
tabCountChanged(count());
487 QString
DolphinTabWidget::tabName(DolphinTabPage
*tabPage
) const
494 if (tabPage
->splitViewEnabled()) {
495 if (tabPage
->primaryViewActive()) {
496 // 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
497 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
498 name
= i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
500 // 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
501 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
502 name
= i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
505 name
= tabPage
->activeViewContainer()->caption();
509 // Make sure that a '&' inside the directory name is displayed correctly
510 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
511 return KStringHandler::rsqueeze(name
.replace('&', QLatin1String("&&")), 40 /* default maximum visible folder name visible */);
514 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
516 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
520 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
523 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
525 activateTab(viewIndex
.tabIndex
);
526 auto viewContainer
= viewContainerAt(viewIndex
);
527 if (!viewContainer
) {
530 viewContainer
->setActive(true);
531 return viewContainer
;
534 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
&directory
) const
536 int i
= currentIndex();
540 // loop over the tabs starting from the current one
542 const auto tabPage
= tabPageAt(i
);
543 if (tabPage
->primaryViewContainer()->url() == directory
) {
544 return std::optional(ViewIndex
{i
, true});
547 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
548 return std::optional(ViewIndex
{i
, false});
551 i
= (i
+ 1) % count();
552 } while (i
!= currentIndex());
557 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewShowingItem(const QUrl
&item
) const
559 // The item might not be loaded yet even though it exists. So instead
560 // we check if the folder containing the item is showing its contents.
561 const QUrl
dirContainingItem(item
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
563 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
564 // Is dirContainingitem the base url of a view?
565 auto viewOpenAtContainingDirectory
= viewOpenAtDirectory(dirContainingItem
);
566 if (viewOpenAtContainingDirectory
.has_value()) {
567 return viewOpenAtContainingDirectory
;
570 // Is dirContainingItem expanded in some tree-style view?
571 // The rest of this method is about figuring this out.
573 int i
= currentIndex();
577 // loop over the tabs starting from the current one
579 const auto tabPage
= tabPageAt(i
);
580 if (tabPage
->primaryViewContainer()->url().isParentOf(item
)) {
581 const KFileItem fileItemContainingItem
= tabPage
->primaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
582 if (!fileItemContainingItem
.isNull() && tabPage
->primaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
583 return std::optional(ViewIndex
{i
, true});
587 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url().isParentOf(item
)) {
588 const KFileItem fileItemContainingItem
= tabPage
->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
589 if (!fileItemContainingItem
.isNull() && tabPage
->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
590 return std::optional(ViewIndex
{i
, false});
594 i
= (i
+ 1) % count();
595 } while (i
!= currentIndex());
600 #include "moc_dolphintabwidget.cpp"