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_dragAndDropHelper
{this}
27 , m_lastViewedTab(nullptr)
28 , m_navigatorsWidget
{navigatorsWidget
}
30 KAcceleratorManager::setNoAccel(this);
32 connect(this, &DolphinTabWidget::tabCloseRequested
, this, QOverload
<int>::of(&DolphinTabWidget::closeTab
));
33 connect(this, &DolphinTabWidget::currentChanged
, this, &DolphinTabWidget::currentTabChanged
);
35 DolphinTabBar
*tabBar
= new DolphinTabBar(this);
36 connect(tabBar
, &DolphinTabBar::openNewActivatedTab
, this, QOverload
<int>::of(&DolphinTabWidget::openNewActivatedTab
));
37 connect(tabBar
, &DolphinTabBar::tabDragMoveEvent
, this, &DolphinTabWidget::tabDragMoveEvent
);
38 connect(tabBar
, &DolphinTabBar::tabDropEvent
, this, &DolphinTabWidget::tabDropEvent
);
39 connect(tabBar
, &DolphinTabBar::tabDetachRequested
, this, &DolphinTabWidget::detachTab
);
42 setDocumentMode(true);
43 setElideMode(Qt::ElideRight
);
44 setUsesScrollButtons(true);
45 setTabBarAutoHide(true);
48 DolphinTabPage
*DolphinTabWidget::currentTabPage() const
50 return tabPageAt(currentIndex());
53 DolphinTabPage
*DolphinTabWidget::nextTabPage() const
55 const int index
= currentIndex() + 1;
56 return tabPageAt(index
< count() ? index
: 0);
59 DolphinTabPage
*DolphinTabWidget::prevTabPage() const
61 const int index
= currentIndex() - 1;
62 return tabPageAt(index
>= 0 ? index
: (count() - 1));
65 DolphinTabPage
*DolphinTabWidget::tabPageAt(const int index
) const
67 return static_cast<DolphinTabPage
*>(widget(index
));
70 void DolphinTabWidget::saveProperties(KConfigGroup
&group
) const
72 const int tabCount
= count();
73 group
.writeEntry("Tab Count", tabCount
);
74 group
.writeEntry("Active Tab Index", currentIndex());
76 for (int i
= 0; i
< tabCount
; ++i
) {
77 const DolphinTabPage
*tabPage
= tabPageAt(i
);
78 group
.writeEntry("Tab Data " % QString::number(i
), tabPage
->saveState());
82 void DolphinTabWidget::readProperties(const KConfigGroup
&group
)
84 const int tabCount
= group
.readEntry("Tab Count", 0);
85 for (int i
= 0; i
< tabCount
; ++i
) {
87 openNewActivatedTab();
89 const QByteArray state
= group
.readEntry("Tab Data " % QString::number(i
), QByteArray());
90 tabPageAt(i
)->restoreState(state
);
93 const int index
= group
.readEntry("Active Tab Index", 0);
94 setCurrentIndex(index
);
97 void DolphinTabWidget::refreshViews()
99 // Left-elision is better when showing full paths, since you care most
100 // about the current directory which is on the right
101 if (GeneralSettings::showFullPathInTitlebar()) {
102 setElideMode(Qt::ElideLeft
);
104 setElideMode(Qt::ElideRight
);
107 const int tabCount
= count();
108 for (int i
= 0; i
< tabCount
; ++i
) {
110 tabPageAt(i
)->refreshViews();
114 void DolphinTabWidget::updateTabName(int index
)
116 Q_ASSERT(index
>= 0);
117 tabBar()->setTabText(index
, tabName(tabPageAt(index
)));
120 bool DolphinTabWidget::isUrlOpen(const QUrl
&url
) const
122 return viewOpenAtDirectory(url
).has_value();
125 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl
&urlOfItem
) const
127 return viewShowingItem(urlOfItem
).has_value();
130 void DolphinTabWidget::openNewActivatedTab()
132 std::unique_ptr
<DolphinUrlNavigator::VisualState
> oldNavigatorState
;
133 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget
->secondaryUrlNavigator()) {
134 oldNavigatorState
= m_navigatorsWidget
->primaryUrlNavigator()->visualState();
136 oldNavigatorState
= m_navigatorsWidget
->secondaryUrlNavigator()->visualState();
139 const DolphinViewContainer
*oldActiveViewContainer
= currentTabPage()->activeViewContainer();
140 Q_ASSERT(oldActiveViewContainer
);
142 openNewActivatedTab(oldActiveViewContainer
->url());
144 DolphinViewContainer
*newActiveViewContainer
= currentTabPage()->activeViewContainer();
145 Q_ASSERT(newActiveViewContainer
);
147 // The URL navigator of the new tab should have the same editable state
148 // as the current tab
149 newActiveViewContainer
->urlNavigator()->setVisualState(*oldNavigatorState
.get());
151 // Always focus the new tab's view
152 newActiveViewContainer
->view()->setFocus();
155 void DolphinTabWidget::openNewActivatedTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
)
157 openNewTab(primaryUrl
, secondaryUrl
);
158 if (GeneralSettings::openNewTabAfterLastTab()) {
159 setCurrentIndex(count() - 1);
161 setCurrentIndex(currentIndex() + 1);
165 void DolphinTabWidget::openNewTab(const QUrl
&primaryUrl
, const QUrl
&secondaryUrl
, DolphinTabWidget::NewTabPosition position
)
167 QWidget
*focusWidget
= QApplication::focusWidget();
169 DolphinTabPage
*tabPage
= new DolphinTabPage(primaryUrl
, secondaryUrl
, this);
170 tabPage
->setActive(false);
171 connect(tabPage
, &DolphinTabPage::activeViewChanged
, this, &DolphinTabWidget::activeViewChanged
);
172 connect(tabPage
, &DolphinTabPage::activeViewUrlChanged
, this, &DolphinTabWidget::tabUrlChanged
);
173 connect(tabPage
->activeViewContainer(), &DolphinViewContainer::captionChanged
, this, [this, tabPage
]() {
174 updateTabName(indexOf(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
= currentTabPage();
336 if (!tabPage
->splitViewEnabled()) {
340 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
341 if (selectedItems
.isEmpty()) {
345 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
346 inactiveView
->copySelectedItems(selectedItems
, inactiveView
->url());
349 void DolphinTabWidget::moveToInactiveSplitView()
351 const DolphinTabPage
*tabPage
= currentTabPage();
352 if (!tabPage
->splitViewEnabled()) {
356 const KFileItemList selectedItems
= tabPage
->activeViewContainer()->view()->selectedItems();
357 if (selectedItems
.isEmpty()) {
361 DolphinView
*const inactiveView
= tabPage
->inactiveViewContainer()->view();
362 inactiveView
->moveSelectedItems(selectedItems
, inactiveView
->url());
365 void DolphinTabWidget::detachTab(int index
)
367 Q_ASSERT(index
>= 0);
371 const DolphinTabPage
*tabPage
= tabPageAt(index
);
372 args
<< tabPage
->primaryViewContainer()->url().url();
373 if (tabPage
->splitViewEnabled()) {
374 args
<< tabPage
->secondaryViewContainer()->url().url();
375 args
<< QStringLiteral("--split");
377 args
<< QStringLiteral("--new-window");
379 KIO::CommandLauncherJob
*job
= new KIO::CommandLauncherJob("dolphin", args
, this);
380 job
->setDesktopName(QStringLiteral("org.kde.dolphin"));
386 void DolphinTabWidget::openNewActivatedTab(int index
)
388 Q_ASSERT(index
>= 0);
389 const DolphinTabPage
*tabPage
= tabPageAt(index
);
390 openNewActivatedTab(tabPage
->activeViewContainer()->url());
393 void DolphinTabWidget::tabDragMoveEvent(int index
, QDragMoveEvent
*event
)
396 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
397 m_dragAndDropHelper
.updateDropAction(event
, view
->url());
401 void DolphinTabWidget::tabDropEvent(int index
, QDropEvent
*event
)
404 DolphinView
*view
= tabPageAt(index
)->activeViewContainer()->view();
405 view
->dropUrls(view
->url(), event
, view
);
407 const auto urls
= event
->mimeData()->urls();
409 for (const QUrl
&url
: urls
) {
410 auto *job
= KIO::stat(url
, KIO::StatJob::SourceSide
, KIO::StatDetail::StatBasic
, KIO::JobFlag::HideProgressInfo
);
411 connect(job
, &KJob::result
, this, [this, job
]() {
412 if (!job
->error() && job
->statResult().isDir()) {
413 openNewTab(job
->url(), QUrl(), NewTabPosition::AtEnd
);
420 void DolphinTabWidget::tabUrlChanged(const QUrl
&url
)
422 const int index
= indexOf(qobject_cast
<QWidget
*>(sender()));
424 updateTabName(index
);
425 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
426 if (tabBar()->isVisible()) {
427 // ensure the path url ends with a slash to have proper folder icon for remote folders
428 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
429 tabBar()->setTabIcon(index
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
431 // Mark as dirty, actually load once the tab bar actually gets shown
432 tabBar()->setTabIcon(index
, QIcon());
435 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
436 if (index
== currentIndex()) {
437 Q_EMIT
currentUrlChanged(url
);
440 Q_EMIT
urlChanged(url
);
444 void DolphinTabWidget::currentTabChanged(int index
)
446 DolphinTabPage
*tabPage
= tabPageAt(index
);
447 if (tabPage
== m_lastViewedTab
) {
450 if (m_lastViewedTab
) {
451 m_lastViewedTab
->disconnectNavigators();
452 m_lastViewedTab
->setActive(false);
454 if (tabPage
->splitViewEnabled() && !m_navigatorsWidget
->secondaryUrlNavigator()) {
455 m_navigatorsWidget
->createSecondaryUrlNavigator();
457 DolphinViewContainer
*viewContainer
= tabPage
->activeViewContainer();
458 Q_EMIT
activeViewChanged(viewContainer
);
459 Q_EMIT
currentUrlChanged(viewContainer
->url());
460 tabPage
->setActive(true);
461 tabPage
->connectNavigators(m_navigatorsWidget
);
462 m_navigatorsWidget
->setSecondaryNavigatorVisible(tabPage
->splitViewEnabled());
463 m_lastViewedTab
= tabPage
;
466 void DolphinTabWidget::tabInserted(int index
)
468 QTabWidget::tabInserted(index
);
470 if (tabBar()->isVisible()) {
471 // Resolve all pending tab icons
472 for (int i
= 0; i
< count(); ++i
) {
473 const QUrl url
= tabPageAt(i
)->activeViewContainer()->url();
474 if (tabBar()->tabIcon(i
).isNull()) {
475 // ensure the path url ends with a slash to have proper folder icon for remote folders
476 const QUrl pathUrl
= QUrl(url
.adjusted(QUrl::StripTrailingSlash
).toString(QUrl::FullyEncoded
).append("/"));
477 tabBar()->setTabIcon(i
, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl
)));
479 if (tabBar()->tabToolTip(i
).isEmpty()) {
480 tabBar()->setTabToolTip(index
, url
.toDisplayString(QUrl::PreferLocalFile
));
485 Q_EMIT
tabCountChanged(count());
488 void DolphinTabWidget::tabRemoved(int index
)
490 QTabWidget::tabRemoved(index
);
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();
517 // Make sure that a '&' inside the directory name is displayed correctly
518 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
519 return KStringHandler::rsqueeze(name
.replace('&', QLatin1String("&&")), 40 /* default maximum visible folder name visible */);
522 DolphinViewContainer
*DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex
) const
524 const auto tabPage
= tabPageAt(viewIndex
.tabIndex
);
528 return viewIndex
.isInPrimaryView
? tabPage
->primaryViewContainer() : tabPage
->secondaryViewContainer();
531 DolphinViewContainer
*DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex
)
533 activateTab(viewIndex
.tabIndex
);
534 auto viewContainer
= viewContainerAt(viewIndex
);
535 if (!viewContainer
) {
538 viewContainer
->setActive(true);
539 return viewContainer
;
542 const std::optional
<const DolphinTabWidget::ViewIndex
> DolphinTabWidget::viewOpenAtDirectory(const QUrl
&directory
) const
544 int i
= currentIndex();
548 // loop over the tabs starting from the current one
550 const auto tabPage
= tabPageAt(i
);
551 if (tabPage
->primaryViewContainer()->url() == directory
) {
552 return std::optional(ViewIndex
{i
, true});
555 if (tabPage
->splitViewEnabled() && tabPage
->secondaryViewContainer()->url() == directory
) {
556 return std::optional(ViewIndex
{i
, false});
559 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();
603 } while (i
!= currentIndex());
608 #include "moc_dolphintabwidget.cpp"