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
= tabPageAt(currentIndex());
329 DolphinViewContainer
*activeViewContainer
= currentTabPage()->activeViewContainer();
330 if (!tabPage
->splitViewEnabled() || activeViewContainer
->view()->selectedItems().isEmpty()) {
334 if (tabPage
->primaryViewActive()) {
335 // copy from left panel to right
336 activeViewContainer
->view()->copySelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->secondaryViewContainer()->url());
338 // copy from right panel to left
339 activeViewContainer
->view()->copySelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->primaryViewContainer()->url());
343 void DolphinTabWidget::moveToInactiveSplitView()
345 const DolphinTabPage
*tabPage
= tabPageAt(currentIndex());
346 DolphinViewContainer
*activeViewContainer
= currentTabPage()->activeViewContainer();
347 if (!tabPage
->splitViewEnabled() || activeViewContainer
->view()->selectedItems().isEmpty()) {
351 if (tabPage
->primaryViewActive()) {
352 // move from left panel to right
353 activeViewContainer
->view()->moveSelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->secondaryViewContainer()->url());
355 // move from right panel to left
356 activeViewContainer
->view()->moveSelectedItems(activeViewContainer
->view()->selectedItems(), tabPage
->primaryViewContainer()->url());
360 void DolphinTabWidget::detachTab(int index
)
362 Q_ASSERT(index
>= 0);
366 const DolphinTabPage
*tabPage
= tabPageAt(index
);
367 args
<< tabPage
->primaryViewContainer()->url().url();
368 if (tabPage
->splitViewEnabled()) {
369 args
<< tabPage
->secondaryViewContainer()->url().url();
370 args
<< QStringLiteral("--split");
372 args
<< QStringLiteral("--new-window");
374 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
375 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
381 void DolphinTabWidget::openNewActivatedTab(int index
)
383 Q_ASSERT(index
>= 0);
384 const DolphinTabPage
*tabPage
= tabPageAt(index
);
385 openNewActivatedTab(tabPage
->activeViewContainer()->url());
388 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
*event
)
391 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
392 view
->dropUrls(view
->url(), event
, view
);
394 const auto urls
= event
->mimeData()->urls();
396 for (const QUrl
&url
: urls
) {
397 auto *job
= KIO::statDetails(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
398 connect(job
, &KJob::result
, this, [this, job
]() {
399 if (!job
->error() && job
->statResult().isDir()) {
400 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
407 void DolphinTabWidget::tabUrlChanged(const QUrl
&url
)
409 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
411 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
412 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
413 if (tabBar()->isVisible()) {
414 // ensure the path url ends with a slash to have proper folder icon for remote folders
415 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
416 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
418 // Mark as dirty, actually load once the tab bar actually gets shown
419 tabBar()->setTabIcon(index
, QIcon());
422 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
423 if (index
== currentIndex()) {
424 Q_EMIT
currentUrlChanged(url
);
429 void DolphinTabWidget::currentTabChanged(int index
)
431 DolphinTabPage
*tabPage
= tabPageAt(index
);
432 if (tabPage
== m_lastViewedTab
) {
435 if (m_lastViewedTab
) {
436 m_lastViewedTab
->disconnectNavigators();
437 m_lastViewedTab
->setActive(false);
439 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
440 m_navigatorsWidget
->createSecondaryUrlNavigator();
442 DolphinViewContainer
*viewContainer
= tabPage
->activeViewContainer();
443 Q_EMIT
activeViewChanged(viewContainer
);
444 Q_EMIT
currentUrlChanged(viewContainer
->url());
445 tabPage
->setActive(true);
446 tabPage
->connectNavigators(m_navigatorsWidget
);
447 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
448 m_lastViewedTab
= tabPage
;
451 void DolphinTabWidget::tabInserted(int index
)
453 QTabWidget::tabInserted(index
);
456 // Resolve all pending tab icons
457 for (int i
= 0; i
< count(); ++i
) {
458 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
459 if (tabBar()->tabIcon(i
).isNull()) {
460 // ensure the path url ends with a slash to have proper folder icon for remote folders
461 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
462 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
464 if (tabBar()->tabToolTip(i
).isEmpty()) {
465 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
472 Q_EMIT
tabCountChanged(count());
475 void DolphinTabWidget::tabRemoved(int index
)
477 QTabWidget::tabRemoved(index
);
479 // If only one tab is left, then remove the tab entry so that
480 // closing the last tab is not possible.
485 Q_EMIT
tabCountChanged(count());
488 QString
DolphinTabWidget::tabName(DolphinTabPage
*tabPage
) const
495 if (tabPage
->splitViewEnabled()) {
496 if (tabPage
->primaryViewActive()) {
497 // 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
498 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
499 name
= i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
501 // 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
502 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
503 name
= i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage
->primaryViewContainer()->caption(), tabPage
->secondaryViewContainer()->caption());
506 name
= tabPage
->activeViewContainer()->caption();
510 // Make sure that a '&' inside the directory name is displayed correctly
511 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
512 return name
.replace('&', QLatin1String("&&"));
515 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
517 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
521 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
524 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
526 activateTab(viewIndex
.tabIndex
);
527 auto viewContainer
= viewContainerAt(viewIndex
);
528 if (!viewContainer
) {
531 viewContainer
->setActive(true);
532 return viewContainer
;
535 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
&directory
) const
537 int i
= currentIndex();
541 // loop over the tabs starting from the current one
543 const auto tabPage
= tabPageAt(i
);
544 if (tabPage
->primaryViewContainer()->url() == directory
) {
545 return std::optional(ViewIndex
{i
, true});
548 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
549 return std::optional(ViewIndex
{i
, false});
552 i
= (i
+ 1) % count();
553 } while (i
!= currentIndex());
558 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewShowingItem(const QUrl
&item
) const
560 // The item might not be loaded yet even though it exists. So instead
561 // we check if the folder containing the item is showing its contents.
562 const QUrl
dirContainingItem(item
.adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
));
564 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
565 // Is dirContainingitem the base url of a view?
566 auto viewOpenAtContainingDirectory
= viewOpenAtDirectory(dirContainingItem
);
567 if (viewOpenAtContainingDirectory
.has_value()) {
568 return viewOpenAtContainingDirectory
;
571 // Is dirContainingItem expanded in some tree-style view?
572 // The rest of this method is about figuring this out.
574 int i
= currentIndex();
578 // loop over the tabs starting from the current one
580 const auto tabPage
= tabPageAt(i
);
581 if (tabPage
->primaryViewContainer()->url().isParentOf(item
)) {
582 const KFileItem fileItemContainingItem
= tabPage
->primaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
583 if (!fileItemContainingItem
.isNull() && tabPage
->primaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
584 return std::optional(ViewIndex
{i
, true});
588 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url().isParentOf(item
)) {
589 const KFileItem fileItemContainingItem
= tabPage
->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem
);
590 if (!fileItemContainingItem
.isNull() && tabPage
->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem
)) {
591 return std::optional(ViewIndex
{i
, false});
595 i
= (i
+ 1) % count();
596 } while (i
!= currentIndex());