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 <KConfigGroup>
15 #include <kio/global.h>
16 #include <KIO/CommandLauncherJob>
17 #include <KAcceleratorManager>
18 #include <KLocalizedString>
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
,
31 this, QOverload
<int>::of(&DolphinTabWidget::closeTab
));
32 connect(this, &DolphinTabWidget::currentChanged
,
33 this, &DolphinTabWidget::currentTabChanged
);
35 DolphinTabBar
* tabBar
= new DolphinTabBar(this);
36 connect(tabBar
, &DolphinTabBar::openNewActivatedTab
,
37 this, QOverload
<int>::of(&DolphinTabWidget::openNewActivatedTab
));
38 connect(tabBar
, &DolphinTabBar::tabDropEvent
,
39 this, &DolphinTabWidget::tabDropEvent
);
40 connect(tabBar
, &DolphinTabBar::tabDetachRequested
,
41 this, &DolphinTabWidget::detachTab
);
45 setDocumentMode(true);
46 setElideMode(Qt::ElideRight
);
47 setUsesScrollButtons(true);
50 DolphinTabPage
* DolphinTabWidget::currentTabPage() const
52 return tabPageAt(currentIndex());
55 DolphinTabPage
* DolphinTabWidget::nextTabPage() const
57 const int index
= currentIndex() + 1;
58 return tabPageAt(index
< count() ? index
: 0);
61 DolphinTabPage
* DolphinTabWidget::prevTabPage() const
63 const int index
= currentIndex() - 1;
64 return tabPageAt(index
>= 0 ? index
: (count() - 1));
67 DolphinTabPage
* DolphinTabWidget::tabPageAt(const int index
) const
69 return static_cast<DolphinTabPage
*>(widget(index
));
72 void DolphinTabWidget::saveProperties(KConfigGroup
& group
) const
74 const int tabCount
= count();
75 group
.writeEntry("Tab Count", tabCount
);
76 group
.writeEntry("Active Tab Index", currentIndex());
78 for (int i
= 0; i
< tabCount
; ++i
) {
79 const DolphinTabPage
* tabPage
= tabPageAt(i
);
80 group
.writeEntry("Tab Data " % QString::number(i
), tabPage
->saveState());
84 void DolphinTabWidget::readProperties(const KConfigGroup
& group
)
86 const int tabCount
= group
.readEntry("Tab Count", 0);
87 for (int i
= 0; i
< tabCount
; ++i
) {
89 openNewActivatedTab();
91 const QByteArray state
= group
.readEntry("Tab Data " % QString::number(i
), QByteArray());
92 tabPageAt(i
)->restoreState(state
);
95 const int index
= group
.readEntry("Active Tab Index", 0);
96 setCurrentIndex(index
);
99 void DolphinTabWidget::refreshViews()
101 // Left-elision is better when showing full paths, since you care most
102 // about the current directory which is on the right
103 if (GeneralSettings::showFullPathInTitlebar()) {
104 setElideMode(Qt::ElideLeft
);
106 setElideMode(Qt::ElideRight
);
109 const int tabCount
= count();
110 for (int i
= 0; i
< tabCount
; ++i
) {
111 tabBar()->setTabText(i
, tabName(tabPageAt(i
)));
112 tabPageAt(i
)->refreshViews();
116 bool DolphinTabWidget::isUrlOpen(const QUrl
&url
) const
118 return viewOpenAtDirectory(url
).has_value();
121 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl
&urlOfItem
) const
123 return viewShowingItem(urlOfItem
).has_value();
126 void DolphinTabWidget::openNewActivatedTab()
128 std::unique_ptr
<DolphinUrlNavigator::VisualState
> oldNavigatorState
;
129 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget
->secondaryUrlNavigator()) {
130 oldNavigatorState
= m_navigatorsWidget
->primaryUrlNavigator()->visualState();
132 oldNavigatorState
= m_navigatorsWidget
->secondaryUrlNavigator()->visualState();
135 const DolphinViewContainer
* oldActiveViewContainer
= currentTabPage()->activeViewContainer();
136 Q_ASSERT(oldActiveViewContainer
);
138 openNewActivatedTab(oldActiveViewContainer
->url());
140 DolphinViewContainer
* newActiveViewContainer
= currentTabPage()->activeViewContainer();
141 Q_ASSERT(newActiveViewContainer
);
143 // The URL navigator of the new tab should have the same editable state
144 // as the current tab
145 newActiveViewContainer
->urlNavigator()->setVisualState(*oldNavigatorState
.get());
147 // Always focus the new tab's view
148 newActiveViewContainer
->view()->setFocus();
151 void DolphinTabWidget::openNewActivatedTab(const QUrl
& primaryUrl
, const QUrl
& secondaryUrl
)
153 openNewTab(primaryUrl
, secondaryUrl
);
154 if (GeneralSettings::openNewTabAfterLastTab()) {
155 setCurrentIndex(count() - 1);
157 setCurrentIndex(currentIndex() + 1);
161 void DolphinTabWidget::openNewTab(const QUrl
& primaryUrl
, const QUrl
& secondaryUrl
, DolphinTabWidget::NewTabPosition position
)
163 QWidget
* focusWidget
= QApplication::focusWidget();
165 DolphinTabPage
* tabPage
= new DolphinTabPage(primaryUrl
, secondaryUrl
, this);
166 tabPage
->setActive(false);
167 connect(tabPage
, &DolphinTabPage::activeViewChanged
,
168 this, &DolphinTabWidget::activeViewChanged
);
169 connect(tabPage
, &DolphinTabPage::activeViewUrlChanged
,
170 this, &DolphinTabWidget::tabUrlChanged
);
171 connect(tabPage
->activeViewContainer(), &DolphinViewContainer::captionChanged
, this, [this, tabPage
]() {
172 const int tabIndex
= indexOf(tabPage
);
173 Q_ASSERT(tabIndex
>= 0);
174 tabBar()->setTabText(tabIndex
, tabName(tabPage
));
177 if (position
== NewTabPosition::FollowSetting
) {
178 if (GeneralSettings::openNewTabAfterLastTab()) {
179 position
= NewTabPosition::AtEnd
;
181 position
= NewTabPosition::AfterCurrent
;
185 int newTabIndex
= -1;
186 if (position
== NewTabPosition::AfterCurrent
|| (position
== NewTabPosition::FollowSetting
&& !GeneralSettings::openNewTabAfterLastTab())) {
187 newTabIndex
= currentIndex() + 1;
190 insertTab(newTabIndex
, tabPage
, QIcon() /* loaded in tabInserted */, tabName(tabPage
));
193 // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened
194 // in background, assure that the previous focused widget gets the focus back.
195 focusWidget
->setFocus();
199 void DolphinTabWidget::openDirectories(const QList
<QUrl
>& dirs
, bool splitView
)
201 Q_ASSERT(dirs
.size() > 0);
203 bool somethingWasAlreadyOpen
= false;
205 QList
<QUrl
>::const_iterator it
= dirs
.constBegin();
206 while (it
!= dirs
.constEnd()) {
207 const QUrl
& primaryUrl
= *(it
++);
208 const std::optional
<ViewIndex
> viewIndexAtDirectory
= viewOpenAtDirectory(primaryUrl
);
210 // When the user asks for a URL that's already open,
211 // activate it instead of opening a new tab
212 if (viewIndexAtDirectory
.has_value()) {
213 somethingWasAlreadyOpen
= true;
214 activateViewContainerAt(viewIndexAtDirectory
.value());
215 } else if (splitView
&& (it
!= dirs
.constEnd())) {
216 const QUrl
& secondaryUrl
= *(it
++);
217 if (somethingWasAlreadyOpen
) {
218 openNewTab(primaryUrl
, secondaryUrl
);
220 openNewActivatedTab(primaryUrl
, secondaryUrl
);
223 if (somethingWasAlreadyOpen
) {
224 openNewTab(primaryUrl
);
226 openNewActivatedTab(primaryUrl
);
232 void DolphinTabWidget::openFiles(const QList
<QUrl
>& files
, bool splitView
)
234 Q_ASSERT(files
.size() > 0);
236 // Get all distinct directories from 'files'.
237 QList
<QUrl
> dirsThatNeedToBeOpened
;
238 QList
<QUrl
> dirsThatWereAlreadyOpen
;
239 for (const QUrl
& file
: files
) {
240 const QUrl
dir(file
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
241 if (dirsThatNeedToBeOpened
.contains(dir
) || dirsThatWereAlreadyOpen
.contains(dir
)) {
245 // The selecting of files that we do later will not work in views that already have items selected.
246 // So we check if dir is already open and clear the selection if it is. BUG: 417230
247 // We also make sure the view will be activated.
248 auto viewIndex
= viewShowingItem(file
);
249 if (viewIndex
.has_value()) {
250 viewContainerAt(viewIndex
.value())->view()->clearSelection();
251 activateViewContainerAt(viewIndex
.value());
252 dirsThatWereAlreadyOpen
.append(dir
);
254 dirsThatNeedToBeOpened
.append(dir
);
258 const int oldTabCount
= count();
259 // Open a tab for each directory. If the "split view" option is enabled,
260 // two directories are shown inside one tab (see openDirectories()).
261 if (dirsThatNeedToBeOpened
.size() > 0) {
262 openDirectories(dirsThatNeedToBeOpened
, splitView
);
264 const int tabCount
= count();
266 // Select the files. Although the files can be split between several
267 // tabs, there is no need to split 'files' accordingly, as
268 // the DolphinView will just ignore invalid selections.
269 for (int i
= 0; i
< tabCount
; ++i
) {
270 DolphinTabPage
* tabPage
= tabPageAt(i
);
271 tabPage
->markUrlsAsSelected(files
);
272 tabPage
->markUrlAsCurrent(files
.first());
273 if (i
< oldTabCount
) {
274 // Force selection of file if directory was already open, BUG: 417230
275 tabPage
->activeViewContainer()->view()->updateViewState();
280 void DolphinTabWidget::closeTab()
282 closeTab(currentIndex());
285 void DolphinTabWidget::closeTab(const int index
)
287 Q_ASSERT(index
>= 0);
288 Q_ASSERT(index
< count());
291 // Close Dolphin when closing the last tab.
292 parentWidget()->close();
296 DolphinTabPage
* tabPage
= tabPageAt(index
);
297 Q_EMIT
rememberClosedTab(tabPage
->activeViewContainer()->url(), tabPage
->saveState());
300 tabPage
->deleteLater();
303 void DolphinTabWidget::activateTab(const int index
)
305 if (index
< count()) {
306 setCurrentIndex(index
);
310 void DolphinTabWidget::activateLastTab()
312 setCurrentIndex(count() - 1);
315 void DolphinTabWidget::activateNextTab()
317 const int index
= currentIndex() + 1;
318 setCurrentIndex(index
< count() ? index
: 0);
321 void DolphinTabWidget::activatePrevTab()
323 const int index
= currentIndex() - 1;
324 setCurrentIndex(index
>= 0 ? index
: (count() - 1));
327 void DolphinTabWidget::restoreClosedTab(const QByteArray
& state
)
329 openNewActivatedTab();
330 currentTabPage()->restoreState(state
);
333 void DolphinTabWidget::copyToInactiveSplitView()
335 const DolphinTabPage
* tabPage
= tabPageAt(currentIndex());
336 DolphinViewContainer
* activeViewContainer
= currentTabPage()->activeViewContainer();
337 if (!tabPage
->splitViewEnabled() || activeViewContainer
->view()->selectedItems().isEmpty()) {
341 if (tabPage
->primaryViewActive()) {
342 // copy from left panel to right
343 activeViewContainer
->view()->copySelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->secondaryViewContainer()->url());
345 // copy from right panel to left
346 activeViewContainer
->view()->copySelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->primaryViewContainer()->url());
350 void DolphinTabWidget::moveToInactiveSplitView()
352 const DolphinTabPage
* tabPage
= tabPageAt(currentIndex());
353 DolphinViewContainer
* activeViewContainer
= currentTabPage()->activeViewContainer();
354 if (!tabPage
->splitViewEnabled() || activeViewContainer
->view()->selectedItems().isEmpty()) {
358 if (tabPage
->primaryViewActive()) {
359 // move from left panel to right
360 activeViewContainer
->view()->moveSelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->secondaryViewContainer()->url());
362 // move from right panel to left
363 activeViewContainer
->view()->moveSelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->primaryViewContainer()->url());
367 void DolphinTabWidget::detachTab(int index
)
369 Q_ASSERT(index
>= 0);
373 const DolphinTabPage
* tabPage
= tabPageAt(index
);
374 args
<< tabPage
->primaryViewContainer()->url().url();
375 if (tabPage
->splitViewEnabled()) {
376 args
<< tabPage
->secondaryViewContainer()->url().url();
377 args
<< QStringLiteral("--split");
379 args
<< QStringLiteral("--new-window");
381 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
382 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
388 void DolphinTabWidget::openNewActivatedTab(int index
)
390 Q_ASSERT(index
>= 0);
391 const DolphinTabPage
* tabPage
= tabPageAt(index
);
392 openNewActivatedTab(tabPage
->activeViewContainer()->url());
395 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
* event
)
398 DolphinView
* view
= tabPageAt(index
)->activeViewContainer()->view();
399 view
->dropUrls(view
->url(), event
, view
);
401 const auto urls
= event
->mimeData()->urls();
403 for (const QUrl
&url
: urls
) {
404 auto *job
= KIO::statDetails(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
405 connect(job
, &KJob::result
, this, [this, job
]() {
406 if (!job
->error() && job
->statResult().isDir()) {
407 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
414 void DolphinTabWidget::tabUrlChanged(const QUrl
& url
)
416 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
418 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
419 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
420 if (tabBar()->isVisible()) {
421 // ensure the path url ends with a slash to have proper folder icon for remote folders
422 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
423 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
425 // Mark as dirty, actually load once the tab bar actually gets shown
426 tabBar()->setTabIcon(index
, QIcon());
429 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
430 if (index
== currentIndex()) {
431 Q_EMIT
currentUrlChanged(url
);
436 void DolphinTabWidget::currentTabChanged(int index
)
438 DolphinTabPage
*tabPage
= tabPageAt(index
);
439 if (tabPage
== m_lastViewedTab
) {
442 if (m_lastViewedTab
) {
443 m_lastViewedTab
->disconnectNavigators();
444 m_lastViewedTab
->setActive(false);
446 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
447 m_navigatorsWidget
->createSecondaryUrlNavigator();
449 DolphinViewContainer
* viewContainer
= tabPage
->activeViewContainer();
450 Q_EMIT
activeViewChanged(viewContainer
);
451 Q_EMIT
currentUrlChanged(viewContainer
->url());
452 tabPage
->setActive(true);
453 tabPage
->connectNavigators(m_navigatorsWidget
);
454 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
455 m_lastViewedTab
= tabPage
;
458 void DolphinTabWidget::tabInserted(int index
)
460 QTabWidget::tabInserted(index
);
463 // Resolve all pending tab icons
464 for (int i
= 0; i
< count(); ++i
) {
465 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
466 if (tabBar()->tabIcon(i
).isNull()) {
467 // ensure the path url ends with a slash to have proper folder icon for remote folders
468 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
469 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
471 if (tabBar()->tabToolTip(i
).isEmpty()) {
472 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
479 Q_EMIT
tabCountChanged(count());
482 void DolphinTabWidget::tabRemoved(int index
)
484 QTabWidget::tabRemoved(index
);
486 // If only one tab is left, then remove the tab entry so that
487 // closing the last tab is not possible.
492 Q_EMIT
tabCountChanged(count());
495 QString
DolphinTabWidget::tabName(DolphinTabPage
* tabPage
) const
502 if (tabPage
->splitViewEnabled()) {
503 if (tabPage
->primaryViewActive()) {
504 // 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
505 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
506 name
= i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
508 // 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
509 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
510 name
= i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
513 name
= tabPage
->activeViewContainer()->caption();
516 // Make sure that a '&' inside the directory name is displayed correctly
517 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
518 return name
.replace('&', QLatin1String("&&"));
521 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
523 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
527 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
530 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
532 activateTab(viewIndex
.tabIndex
);
533 auto viewContainer
= viewContainerAt(viewIndex
);
534 if (!viewContainer
) {
537 viewContainer
->setActive(true);
538 return viewContainer
;
541 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
& directory
) const
543 int i
= currentIndex();
547 // loop over the tabs starting from the current one
549 const auto tabPage
= tabPageAt(i
);
550 if (tabPage
->primaryViewContainer()->url() == directory
) {
551 return std::optional(ViewIndex
{i
, true});
554 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
555 return std::optional(ViewIndex
{i
, false});
558 i
= (i
+ 1) % count();
560 while (i
!= currentIndex());
565 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewShowingItem(const QUrl
& item
) const
567 // The item might not be loaded yet even though it exists. So instead
568 // we check if the folder containing the item is showing its contents.
569 const QUrl
dirContainingItem(item
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
571 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
572 // Is dirContainingitem the base url of a view?
573 auto viewOpenAtContainingDirectory
= viewOpenAtDirectory(dirContainingItem
);
574 if (viewOpenAtContainingDirectory
.has_value()) {
575 return viewOpenAtContainingDirectory
;
578 // Is dirContainingItem expanded in some tree-style view?
579 // The rest of this method is about figuring this out.
581 int i
= currentIndex();
585 // loop over the tabs starting from the current one
587 const auto tabPage
= tabPageAt(i
);
588 if (tabPage
->primaryViewContainer()->url().isParentOf(item
)) {
589 const KFileItem fileItemContainingItem
= tabPage
->primaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
590 if (!fileItemContainingItem
.isNull() && tabPage
->primaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
591 return std::optional(ViewIndex
{i
, true});
595 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url().isParentOf(item
)) {
596 const KFileItem fileItemContainingItem
= tabPage
->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
597 if (!fileItemContainingItem
.isNull() && tabPage
->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
598 return std::optional(ViewIndex
{i
, false});
602 i
= (i
+ 1) % count();
604 while (i
!= currentIndex());