]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphintabwidget.cpp
Remove popout action from toolbar when split screen is closed
[dolphin.git] / src / dolphintabwidget.cpp
1 /*
2 * SPDX-FileCopyrightText: 2014 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "dolphintabwidget.h"
8
9 #include "dolphin_generalsettings.h"
10 #include "dolphintabbar.h"
11 #include "dolphinviewcontainer.h"
12
13 #include <KAcceleratorManager>
14 #include <KConfigGroup>
15 #include <KIO/CommandLauncherJob>
16 #include <KLocalizedString>
17 #include <KShell>
18 #include <KStringHandler>
19 #include <kio/global.h>
20
21 #include <QApplication>
22 #include <QDropEvent>
23
24 DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction *navigatorsWidget, QWidget *parent)
25 : QTabWidget(parent)
26 , m_lastViewedTab(nullptr)
27 , m_navigatorsWidget{navigatorsWidget}
28 {
29 KAcceleratorManager::setNoAccel(this);
30
31 connect(this, &DolphinTabWidget::tabCloseRequested, this, QOverload<int>::of(&DolphinTabWidget::closeTab));
32 connect(this, &DolphinTabWidget::currentChanged, this, &DolphinTabWidget::currentTabChanged);
33
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);
38
39 setTabBar(tabBar);
40 setDocumentMode(true);
41 setElideMode(Qt::ElideRight);
42 setUsesScrollButtons(true);
43 setTabBarAutoHide(true);
44 }
45
46 DolphinTabPage *DolphinTabWidget::currentTabPage() const
47 {
48 return tabPageAt(currentIndex());
49 }
50
51 DolphinTabPage *DolphinTabWidget::nextTabPage() const
52 {
53 const int index = currentIndex() + 1;
54 return tabPageAt(index < count() ? index : 0);
55 }
56
57 DolphinTabPage *DolphinTabWidget::prevTabPage() const
58 {
59 const int index = currentIndex() - 1;
60 return tabPageAt(index >= 0 ? index : (count() - 1));
61 }
62
63 DolphinTabPage *DolphinTabWidget::tabPageAt(const int index) const
64 {
65 return static_cast<DolphinTabPage *>(widget(index));
66 }
67
68 void DolphinTabWidget::saveProperties(KConfigGroup &group) const
69 {
70 const int tabCount = count();
71 group.writeEntry("Tab Count", tabCount);
72 group.writeEntry("Active Tab Index", currentIndex());
73
74 for (int i = 0; i < tabCount; ++i) {
75 const DolphinTabPage *tabPage = tabPageAt(i);
76 group.writeEntry("Tab Data " % QString::number(i), tabPage->saveState());
77 }
78 }
79
80 void DolphinTabWidget::readProperties(const KConfigGroup &group)
81 {
82 const int tabCount = group.readEntry("Tab Count", 0);
83 for (int i = 0; i < tabCount; ++i) {
84 if (i >= count()) {
85 openNewActivatedTab();
86 }
87 const QByteArray state = group.readEntry("Tab Data " % QString::number(i), QByteArray());
88 tabPageAt(i)->restoreState(state);
89 }
90
91 const int index = group.readEntry("Active Tab Index", 0);
92 setCurrentIndex(index);
93 }
94
95 void DolphinTabWidget::refreshViews()
96 {
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);
101 } else {
102 setElideMode(Qt::ElideRight);
103 }
104
105 const int tabCount = count();
106 for (int i = 0; i < tabCount; ++i) {
107 updateTabName(i);
108 tabPageAt(i)->refreshViews();
109 }
110 }
111
112 void DolphinTabWidget::updateTabName(int index)
113 {
114 Q_ASSERT(index >= 0);
115 tabBar()->setTabText(index, tabName(tabPageAt(index)));
116 }
117
118 bool DolphinTabWidget::isUrlOpen(const QUrl &url) const
119 {
120 return viewOpenAtDirectory(url).has_value();
121 }
122
123 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl &urlOfItem) const
124 {
125 return viewShowingItem(urlOfItem).has_value();
126 }
127
128 void DolphinTabWidget::openNewActivatedTab()
129 {
130 std::unique_ptr<DolphinUrlNavigator::VisualState> oldNavigatorState;
131 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget->secondaryUrlNavigator()) {
132 oldNavigatorState = m_navigatorsWidget->primaryUrlNavigator()->visualState();
133 } else {
134 oldNavigatorState = m_navigatorsWidget->secondaryUrlNavigator()->visualState();
135 }
136
137 const DolphinViewContainer *oldActiveViewContainer = currentTabPage()->activeViewContainer();
138 Q_ASSERT(oldActiveViewContainer);
139
140 openNewActivatedTab(oldActiveViewContainer->url());
141
142 DolphinViewContainer *newActiveViewContainer = currentTabPage()->activeViewContainer();
143 Q_ASSERT(newActiveViewContainer);
144
145 // The URL navigator of the new tab should have the same editable state
146 // as the current tab
147 newActiveViewContainer->urlNavigator()->setVisualState(*oldNavigatorState.get());
148
149 // Always focus the new tab's view
150 newActiveViewContainer->view()->setFocus();
151 }
152
153 void DolphinTabWidget::openNewActivatedTab(const QUrl &primaryUrl, const QUrl &secondaryUrl)
154 {
155 openNewTab(primaryUrl, secondaryUrl);
156 if (GeneralSettings::openNewTabAfterLastTab()) {
157 setCurrentIndex(count() - 1);
158 } else {
159 setCurrentIndex(currentIndex() + 1);
160 }
161 }
162
163 void DolphinTabWidget::openNewTab(const QUrl &primaryUrl, const QUrl &secondaryUrl, DolphinTabWidget::NewTabPosition position)
164 {
165 QWidget *focusWidget = QApplication::focusWidget();
166
167 DolphinTabPage *tabPage = new DolphinTabPage(primaryUrl, secondaryUrl, this);
168 tabPage->setActive(false);
169 connect(tabPage, &DolphinTabPage::activeViewChanged, this, &DolphinTabWidget::activeViewChanged);
170 connect(tabPage, &DolphinTabPage::activeViewUrlChanged, this, &DolphinTabWidget::tabUrlChanged);
171 connect(tabPage->activeViewContainer(), &DolphinViewContainer::captionChanged, this, [this, tabPage]() {
172 updateTabName(indexOf(tabPage));
173 });
174
175 if (position == NewTabPosition::FollowSetting) {
176 if (GeneralSettings::openNewTabAfterLastTab()) {
177 position = NewTabPosition::AtEnd;
178 } else {
179 position = NewTabPosition::AfterCurrent;
180 }
181 }
182
183 int newTabIndex = -1;
184 if (position == NewTabPosition::AfterCurrent || (position == NewTabPosition::FollowSetting && !GeneralSettings::openNewTabAfterLastTab())) {
185 newTabIndex = currentIndex() + 1;
186 }
187
188 insertTab(newTabIndex, tabPage, QIcon() /* loaded in tabInserted */, tabName(tabPage));
189
190 if (focusWidget) {
191 // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened
192 // in background, assure that the previous focused widget gets the focus back.
193 focusWidget->setFocus();
194 }
195 }
196
197 void DolphinTabWidget::openDirectories(const QList<QUrl> &dirs, bool splitView)
198 {
199 Q_ASSERT(dirs.size() > 0);
200
201 bool somethingWasAlreadyOpen = false;
202
203 QList<QUrl>::const_iterator it = dirs.constBegin();
204 while (it != dirs.constEnd()) {
205 const QUrl &primaryUrl = *(it++);
206 const std::optional<ViewIndex> viewIndexAtDirectory = viewOpenAtDirectory(primaryUrl);
207
208 // When the user asks for a URL that's already open,
209 // activate it instead of opening a new tab
210 if (viewIndexAtDirectory.has_value()) {
211 somethingWasAlreadyOpen = true;
212 activateViewContainerAt(viewIndexAtDirectory.value());
213 } else if (splitView && (it != dirs.constEnd())) {
214 const QUrl &secondaryUrl = *(it++);
215 if (somethingWasAlreadyOpen) {
216 openNewTab(primaryUrl, secondaryUrl);
217 } else {
218 openNewActivatedTab(primaryUrl, secondaryUrl);
219 }
220 } else {
221 if (somethingWasAlreadyOpen) {
222 openNewTab(primaryUrl);
223 } else {
224 openNewActivatedTab(primaryUrl);
225 }
226 }
227 }
228 }
229
230 void DolphinTabWidget::openFiles(const QList<QUrl> &files, bool splitView)
231 {
232 Q_ASSERT(files.size() > 0);
233
234 // Get all distinct directories from 'files'.
235 QList<QUrl> dirsThatNeedToBeOpened;
236 QList<QUrl> dirsThatWereAlreadyOpen;
237 for (const QUrl &file : files) {
238 const QUrl dir(file.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash));
239 if (dirsThatNeedToBeOpened.contains(dir) || dirsThatWereAlreadyOpen.contains(dir)) {
240 continue;
241 }
242
243 // The selecting of files that we do later will not work in views that already have items selected.
244 // So we check if dir is already open and clear the selection if it is. BUG: 417230
245 // We also make sure the view will be activated.
246 auto viewIndex = viewShowingItem(file);
247 if (viewIndex.has_value()) {
248 viewContainerAt(viewIndex.value())->view()->clearSelection();
249 activateViewContainerAt(viewIndex.value());
250 dirsThatWereAlreadyOpen.append(dir);
251 } else {
252 dirsThatNeedToBeOpened.append(dir);
253 }
254 }
255
256 const int oldTabCount = count();
257 // Open a tab for each directory. If the "split view" option is enabled,
258 // two directories are shown inside one tab (see openDirectories()).
259 if (dirsThatNeedToBeOpened.size() > 0) {
260 openDirectories(dirsThatNeedToBeOpened, splitView);
261 }
262 const int tabCount = count();
263
264 // Select the files. Although the files can be split between several
265 // tabs, there is no need to split 'files' accordingly, as
266 // the DolphinView will just ignore invalid selections.
267 for (int i = 0; i < tabCount; ++i) {
268 DolphinTabPage *tabPage = tabPageAt(i);
269 tabPage->markUrlsAsSelected(files);
270 tabPage->markUrlAsCurrent(files.first());
271 if (i < oldTabCount) {
272 // Force selection of file if directory was already open, BUG: 417230
273 tabPage->activeViewContainer()->view()->updateViewState();
274 }
275 }
276 }
277
278 void DolphinTabWidget::closeTab()
279 {
280 closeTab(currentIndex());
281 }
282
283 void DolphinTabWidget::closeTab(const int index)
284 {
285 Q_ASSERT(index >= 0);
286 Q_ASSERT(index < count());
287
288 if (count() < 2) {
289 // Close Dolphin when closing the last tab.
290 parentWidget()->close();
291 return;
292 }
293
294 DolphinTabPage *tabPage = tabPageAt(index);
295 Q_EMIT rememberClosedTab(tabPage->activeViewContainer()->url(), tabPage->saveState());
296
297 removeTab(index);
298 tabPage->deleteLater();
299 }
300
301 void DolphinTabWidget::activateTab(const int index)
302 {
303 if (index < count()) {
304 setCurrentIndex(index);
305 }
306 }
307
308 void DolphinTabWidget::activateLastTab()
309 {
310 setCurrentIndex(count() - 1);
311 }
312
313 void DolphinTabWidget::activateNextTab()
314 {
315 const int index = currentIndex() + 1;
316 setCurrentIndex(index < count() ? index : 0);
317 }
318
319 void DolphinTabWidget::activatePrevTab()
320 {
321 const int index = currentIndex() - 1;
322 setCurrentIndex(index >= 0 ? index : (count() - 1));
323 }
324
325 void DolphinTabWidget::restoreClosedTab(const QByteArray &state)
326 {
327 openNewActivatedTab();
328 currentTabPage()->restoreState(state);
329 }
330
331 void DolphinTabWidget::copyToInactiveSplitView()
332 {
333 const DolphinTabPage *tabPage = currentTabPage();
334 if (!tabPage->splitViewEnabled()) {
335 return;
336 }
337
338 const KFileItemList selectedItems = tabPage->activeViewContainer()->view()->selectedItems();
339 if (selectedItems.isEmpty()) {
340 return;
341 }
342
343 DolphinView *const inactiveView = tabPage->inactiveViewContainer()->view();
344 inactiveView->copySelectedItems(selectedItems, inactiveView->url());
345 }
346
347 void DolphinTabWidget::moveToInactiveSplitView()
348 {
349 const DolphinTabPage *tabPage = currentTabPage();
350 if (!tabPage->splitViewEnabled()) {
351 return;
352 }
353
354 const KFileItemList selectedItems = tabPage->activeViewContainer()->view()->selectedItems();
355 if (selectedItems.isEmpty()) {
356 return;
357 }
358
359 DolphinView *const inactiveView = tabPage->inactiveViewContainer()->view();
360 inactiveView->moveSelectedItems(selectedItems, inactiveView->url());
361 }
362
363 void DolphinTabWidget::detachTab(int index)
364 {
365 Q_ASSERT(index >= 0);
366
367 QStringList args;
368
369 const DolphinTabPage *tabPage = tabPageAt(index);
370 args << tabPage->primaryViewContainer()->url().url();
371 if (tabPage->splitViewEnabled()) {
372 args << tabPage->secondaryViewContainer()->url().url();
373 args << QStringLiteral("--split");
374 }
375 args << QStringLiteral("--new-window");
376
377 KIO::CommandLauncherJob *job = new KIO::CommandLauncherJob("dolphin", args, this);
378 job->setDesktopName(QStringLiteral("org.kde.dolphin"));
379 job->start();
380
381 closeTab(index);
382 }
383
384 void DolphinTabWidget::openNewActivatedTab(int index)
385 {
386 Q_ASSERT(index >= 0);
387 const DolphinTabPage *tabPage = tabPageAt(index);
388 openNewActivatedTab(tabPage->activeViewContainer()->url());
389 }
390
391 void DolphinTabWidget::tabDropEvent(int index, QDropEvent *event)
392 {
393 if (index >= 0) {
394 DolphinView *view = tabPageAt(index)->activeViewContainer()->view();
395 view->dropUrls(view->url(), event, view);
396 } else {
397 const auto urls = event->mimeData()->urls();
398
399 for (const QUrl &url : urls) {
400 auto *job = KIO::stat(url, KIO::StatJob::SourceSide, KIO::StatDetail::StatBasic, KIO::JobFlag::HideProgressInfo);
401 connect(job, &KJob::result, this, [this, job]() {
402 if (!job->error() && job->statResult().isDir()) {
403 openNewTab(job->url(), QUrl(), NewTabPosition::AtEnd);
404 }
405 });
406 }
407 }
408 }
409
410 void DolphinTabWidget::tabUrlChanged(const QUrl &url)
411 {
412 const int index = indexOf(qobject_cast<QWidget *>(sender()));
413 if (index >= 0) {
414 updateTabName(index);
415 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
416 if (tabBar()->isVisible()) {
417 // ensure the path url ends with a slash to have proper folder icon for remote folders
418 const QUrl pathUrl = QUrl(url.adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/"));
419 tabBar()->setTabIcon(index, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl)));
420 } else {
421 // Mark as dirty, actually load once the tab bar actually gets shown
422 tabBar()->setTabIcon(index, QIcon());
423 }
424
425 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
426 if (index == currentIndex()) {
427 Q_EMIT currentUrlChanged(url);
428 }
429
430 Q_EMIT urlChanged(url);
431 }
432 }
433
434 void DolphinTabWidget::currentTabChanged(int index)
435 {
436 DolphinTabPage *tabPage = tabPageAt(index);
437 if (tabPage == m_lastViewedTab) {
438 return;
439 }
440 if (m_lastViewedTab) {
441 m_lastViewedTab->disconnectNavigators();
442 m_lastViewedTab->setActive(false);
443 }
444 if (tabPage->splitViewEnabled() && !m_navigatorsWidget->secondaryUrlNavigator()) {
445 m_navigatorsWidget->createSecondaryUrlNavigator();
446 }
447 DolphinViewContainer *viewContainer = tabPage->activeViewContainer();
448 Q_EMIT activeViewChanged(viewContainer);
449 Q_EMIT currentUrlChanged(viewContainer->url());
450 tabPage->setActive(true);
451 tabPage->connectNavigators(m_navigatorsWidget);
452 m_navigatorsWidget->setSecondaryNavigatorVisible(tabPage->splitViewEnabled());
453 m_lastViewedTab = tabPage;
454 }
455
456 void DolphinTabWidget::tabInserted(int index)
457 {
458 QTabWidget::tabInserted(index);
459
460 if (tabBar()->isVisible()) {
461 // Resolve all pending tab icons
462 for (int i = 0; i < count(); ++i) {
463 const QUrl url = tabPageAt(i)->activeViewContainer()->url();
464 if (tabBar()->tabIcon(i).isNull()) {
465 // ensure the path url ends with a slash to have proper folder icon for remote folders
466 const QUrl pathUrl = QUrl(url.adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/"));
467 tabBar()->setTabIcon(i, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl)));
468 }
469 if (tabBar()->tabToolTip(i).isEmpty()) {
470 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
471 }
472 }
473 }
474
475 Q_EMIT tabCountChanged(count());
476 }
477
478 void DolphinTabWidget::tabRemoved(int index)
479 {
480 QTabWidget::tabRemoved(index);
481
482 Q_EMIT tabCountChanged(count());
483 }
484
485 QString DolphinTabWidget::tabName(DolphinTabPage *tabPage) const
486 {
487 if (!tabPage) {
488 return QString();
489 }
490 // clang-format off
491 QString name;
492 if (tabPage->splitViewEnabled()) {
493 if (tabPage->primaryViewActive()) {
494 // 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
495 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
496 name = i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage->primaryViewContainer()->caption(), tabPage->secondaryViewContainer()->caption());
497 } else {
498 // 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
499 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
500 name = i18nc("@title:tab (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage->primaryViewContainer()->caption(), tabPage->secondaryViewContainer()->caption());
501 }
502 } else {
503 name = tabPage->activeViewContainer()->caption();
504 }
505 // clang-format on
506
507 // Make sure that a '&' inside the directory name is displayed correctly
508 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
509 return KStringHandler::rsqueeze(name.replace('&', QLatin1String("&&")), 40 /* default maximum visible folder name visible */);
510 }
511
512 DolphinViewContainer *DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex) const
513 {
514 const auto tabPage = tabPageAt(viewIndex.tabIndex);
515 if (!tabPage) {
516 return nullptr;
517 }
518 return viewIndex.isInPrimaryView ? tabPage->primaryViewContainer() : tabPage->secondaryViewContainer();
519 }
520
521 DolphinViewContainer *DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex)
522 {
523 activateTab(viewIndex.tabIndex);
524 auto viewContainer = viewContainerAt(viewIndex);
525 if (!viewContainer) {
526 return nullptr;
527 }
528 viewContainer->setActive(true);
529 return viewContainer;
530 }
531
532 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl &directory) const
533 {
534 int i = currentIndex();
535 if (i < 0) {
536 return std::nullopt;
537 }
538 // loop over the tabs starting from the current one
539 do {
540 const auto tabPage = tabPageAt(i);
541 if (tabPage->primaryViewContainer()->url() == directory) {
542 return std::optional(ViewIndex{i, true});
543 }
544
545 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url() == directory) {
546 return std::optional(ViewIndex{i, false});
547 }
548
549 i = (i + 1) % count();
550 } while (i != currentIndex());
551
552 return std::nullopt;
553 }
554
555 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewShowingItem(const QUrl &item) const
556 {
557 // The item might not be loaded yet even though it exists. So instead
558 // we check if the folder containing the item is showing its contents.
559 const QUrl dirContainingItem(item.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash));
560
561 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
562 // Is dirContainingitem the base url of a view?
563 auto viewOpenAtContainingDirectory = viewOpenAtDirectory(dirContainingItem);
564 if (viewOpenAtContainingDirectory.has_value()) {
565 return viewOpenAtContainingDirectory;
566 }
567
568 // Is dirContainingItem expanded in some tree-style view?
569 // The rest of this method is about figuring this out.
570
571 int i = currentIndex();
572 if (i < 0) {
573 return std::nullopt;
574 }
575 // loop over the tabs starting from the current one
576 do {
577 const auto tabPage = tabPageAt(i);
578 if (tabPage->primaryViewContainer()->url().isParentOf(item)) {
579 const KFileItem fileItemContainingItem = tabPage->primaryViewContainer()->view()->items().findByUrl(dirContainingItem);
580 if (!fileItemContainingItem.isNull() && tabPage->primaryViewContainer()->view()->isExpanded(fileItemContainingItem)) {
581 return std::optional(ViewIndex{i, true});
582 }
583 }
584
585 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url().isParentOf(item)) {
586 const KFileItem fileItemContainingItem = tabPage->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem);
587 if (!fileItemContainingItem.isNull() && tabPage->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem)) {
588 return std::optional(ViewIndex{i, false});
589 }
590 }
591
592 i = (i + 1) % count();
593 } while (i != currentIndex());
594
595 return std::nullopt;
596 }
597
598 #include "moc_dolphintabwidget.cpp"