]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphintabwidget.cpp
Merge branch 'master' into kf6
[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 tabBar->hide();
39
40 setTabBar(tabBar);
41 setDocumentMode(true);
42 setElideMode(Qt::ElideRight);
43 setUsesScrollButtons(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 tabBar()->setTabText(i, tabName(tabPageAt(i)));
108 tabPageAt(i)->refreshViews();
109 }
110 }
111
112 bool DolphinTabWidget::isUrlOpen(const QUrl &url) const
113 {
114 return viewOpenAtDirectory(url).has_value();
115 }
116
117 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl &urlOfItem) const
118 {
119 return viewShowingItem(urlOfItem).has_value();
120 }
121
122 void DolphinTabWidget::openNewActivatedTab()
123 {
124 std::unique_ptr<DolphinUrlNavigator::VisualState> oldNavigatorState;
125 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget->secondaryUrlNavigator()) {
126 oldNavigatorState = m_navigatorsWidget->primaryUrlNavigator()->visualState();
127 } else {
128 oldNavigatorState = m_navigatorsWidget->secondaryUrlNavigator()->visualState();
129 }
130
131 const DolphinViewContainer *oldActiveViewContainer = currentTabPage()->activeViewContainer();
132 Q_ASSERT(oldActiveViewContainer);
133
134 openNewActivatedTab(oldActiveViewContainer->url());
135
136 DolphinViewContainer *newActiveViewContainer = currentTabPage()->activeViewContainer();
137 Q_ASSERT(newActiveViewContainer);
138
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());
142
143 // Always focus the new tab's view
144 newActiveViewContainer->view()->setFocus();
145 }
146
147 void DolphinTabWidget::openNewActivatedTab(const QUrl &primaryUrl, const QUrl &secondaryUrl)
148 {
149 openNewTab(primaryUrl, secondaryUrl);
150 if (GeneralSettings::openNewTabAfterLastTab()) {
151 setCurrentIndex(count() - 1);
152 } else {
153 setCurrentIndex(currentIndex() + 1);
154 }
155 }
156
157 void DolphinTabWidget::openNewTab(const QUrl &primaryUrl, const QUrl &secondaryUrl, DolphinTabWidget::NewTabPosition position)
158 {
159 QWidget *focusWidget = QApplication::focusWidget();
160
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));
169 });
170
171 if (position == NewTabPosition::FollowSetting) {
172 if (GeneralSettings::openNewTabAfterLastTab()) {
173 position = NewTabPosition::AtEnd;
174 } else {
175 position = NewTabPosition::AfterCurrent;
176 }
177 }
178
179 int newTabIndex = -1;
180 if (position == NewTabPosition::AfterCurrent || (position == NewTabPosition::FollowSetting && !GeneralSettings::openNewTabAfterLastTab())) {
181 newTabIndex = currentIndex() + 1;
182 }
183
184 insertTab(newTabIndex, tabPage, QIcon() /* loaded in tabInserted */, tabName(tabPage));
185
186 if (focusWidget) {
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();
190 }
191 }
192
193 void DolphinTabWidget::openDirectories(const QList<QUrl> &dirs, bool splitView)
194 {
195 Q_ASSERT(dirs.size() > 0);
196
197 bool somethingWasAlreadyOpen = false;
198
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);
203
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);
213 } else {
214 openNewActivatedTab(primaryUrl, secondaryUrl);
215 }
216 } else {
217 if (somethingWasAlreadyOpen) {
218 openNewTab(primaryUrl);
219 } else {
220 openNewActivatedTab(primaryUrl);
221 }
222 }
223 }
224 }
225
226 void DolphinTabWidget::openFiles(const QList<QUrl> &files, bool splitView)
227 {
228 Q_ASSERT(files.size() > 0);
229
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)) {
236 continue;
237 }
238
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);
247 } else {
248 dirsThatNeedToBeOpened.append(dir);
249 }
250 }
251
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);
257 }
258 const int tabCount = count();
259
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();
270 }
271 }
272 }
273
274 void DolphinTabWidget::closeTab()
275 {
276 closeTab(currentIndex());
277 }
278
279 void DolphinTabWidget::closeTab(const int index)
280 {
281 Q_ASSERT(index >= 0);
282 Q_ASSERT(index < count());
283
284 if (count() < 2) {
285 // Close Dolphin when closing the last tab.
286 parentWidget()->close();
287 return;
288 }
289
290 DolphinTabPage *tabPage = tabPageAt(index);
291 Q_EMIT rememberClosedTab(tabPage->activeViewContainer()->url(), tabPage->saveState());
292
293 removeTab(index);
294 tabPage->deleteLater();
295 }
296
297 void DolphinTabWidget::activateTab(const int index)
298 {
299 if (index < count()) {
300 setCurrentIndex(index);
301 }
302 }
303
304 void DolphinTabWidget::activateLastTab()
305 {
306 setCurrentIndex(count() - 1);
307 }
308
309 void DolphinTabWidget::activateNextTab()
310 {
311 const int index = currentIndex() + 1;
312 setCurrentIndex(index < count() ? index : 0);
313 }
314
315 void DolphinTabWidget::activatePrevTab()
316 {
317 const int index = currentIndex() - 1;
318 setCurrentIndex(index >= 0 ? index : (count() - 1));
319 }
320
321 void DolphinTabWidget::restoreClosedTab(const QByteArray &state)
322 {
323 openNewActivatedTab();
324 currentTabPage()->restoreState(state);
325 }
326
327 void DolphinTabWidget::copyToInactiveSplitView()
328 {
329 const DolphinTabPage *tabPage = currentTabPage();
330 if (!tabPage->splitViewEnabled()) {
331 return;
332 }
333
334 const KFileItemList selectedItems = tabPage->activeViewContainer()->view()->selectedItems();
335 if (selectedItems.isEmpty()) {
336 return;
337 }
338
339 DolphinView *const inactiveView = tabPage->inactiveViewContainer()->view();
340 inactiveView->copySelectedItems(selectedItems, inactiveView->url());
341 }
342
343 void DolphinTabWidget::moveToInactiveSplitView()
344 {
345 const DolphinTabPage *tabPage = currentTabPage();
346 if (!tabPage->splitViewEnabled()) {
347 return;
348 }
349
350 const KFileItemList selectedItems = tabPage->activeViewContainer()->view()->selectedItems();
351 if (selectedItems.isEmpty()) {
352 return;
353 }
354
355 DolphinView *const inactiveView = tabPage->inactiveViewContainer()->view();
356 inactiveView->moveSelectedItems(selectedItems, inactiveView->url());
357 }
358
359 void DolphinTabWidget::detachTab(int index)
360 {
361 Q_ASSERT(index >= 0);
362
363 QStringList args;
364
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");
370 }
371 args << QStringLiteral("--new-window");
372
373 KIO::CommandLauncherJob *job = new KIO::CommandLauncherJob("dolphin", args, this);
374 job->setDesktopName(QStringLiteral("org.kde.dolphin"));
375 job->start();
376
377 closeTab(index);
378 }
379
380 void DolphinTabWidget::openNewActivatedTab(int index)
381 {
382 Q_ASSERT(index >= 0);
383 const DolphinTabPage *tabPage = tabPageAt(index);
384 openNewActivatedTab(tabPage->activeViewContainer()->url());
385 }
386
387 void DolphinTabWidget::tabDropEvent(int index, QDropEvent *event)
388 {
389 if (index >= 0) {
390 DolphinView *view = tabPageAt(index)->activeViewContainer()->view();
391 view->dropUrls(view->url(), event, view);
392 } else {
393 const auto urls = event->mimeData()->urls();
394
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);
400 }
401 });
402 }
403 }
404 }
405
406 void DolphinTabWidget::tabUrlChanged(const QUrl &url)
407 {
408 const int index = indexOf(qobject_cast<QWidget *>(sender()));
409 if (index >= 0) {
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)));
416 } else {
417 // Mark as dirty, actually load once the tab bar actually gets shown
418 tabBar()->setTabIcon(index, QIcon());
419 }
420
421 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
422 if (index == currentIndex()) {
423 Q_EMIT currentUrlChanged(url);
424 }
425 }
426 }
427
428 void DolphinTabWidget::currentTabChanged(int index)
429 {
430 DolphinTabPage *tabPage = tabPageAt(index);
431 if (tabPage == m_lastViewedTab) {
432 return;
433 }
434 if (m_lastViewedTab) {
435 m_lastViewedTab->disconnectNavigators();
436 m_lastViewedTab->setActive(false);
437 }
438 if (tabPage->splitViewEnabled() && !m_navigatorsWidget->secondaryUrlNavigator()) {
439 m_navigatorsWidget->createSecondaryUrlNavigator();
440 }
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;
448 }
449
450 void DolphinTabWidget::tabInserted(int index)
451 {
452 QTabWidget::tabInserted(index);
453
454 if (count() > 1) {
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)));
462 }
463 if (tabBar()->tabToolTip(i).isEmpty()) {
464 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
465 }
466 }
467
468 tabBar()->show();
469 }
470
471 Q_EMIT tabCountChanged(count());
472 }
473
474 void DolphinTabWidget::tabRemoved(int index)
475 {
476 QTabWidget::tabRemoved(index);
477
478 // If only one tab is left, then remove the tab entry so that
479 // closing the last tab is not possible.
480 if (count() < 2) {
481 tabBar()->hide();
482 }
483
484 Q_EMIT tabCountChanged(count());
485 }
486
487 QString DolphinTabWidget::tabName(DolphinTabPage *tabPage) const
488 {
489 if (!tabPage) {
490 return QString();
491 }
492 // clang-format off
493 QString name;
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());
499 } else {
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());
503 }
504 } else {
505 name = tabPage->activeViewContainer()->caption();
506 }
507 // clang-format on
508
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 */);
512 }
513
514 DolphinViewContainer *DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex) const
515 {
516 const auto tabPage = tabPageAt(viewIndex.tabIndex);
517 if (!tabPage) {
518 return nullptr;
519 }
520 return viewIndex.isInPrimaryView ? tabPage->primaryViewContainer() : tabPage->secondaryViewContainer();
521 }
522
523 DolphinViewContainer *DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex)
524 {
525 activateTab(viewIndex.tabIndex);
526 auto viewContainer = viewContainerAt(viewIndex);
527 if (!viewContainer) {
528 return nullptr;
529 }
530 viewContainer->setActive(true);
531 return viewContainer;
532 }
533
534 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl &directory) const
535 {
536 int i = currentIndex();
537 if (i < 0) {
538 return std::nullopt;
539 }
540 // loop over the tabs starting from the current one
541 do {
542 const auto tabPage = tabPageAt(i);
543 if (tabPage->primaryViewContainer()->url() == directory) {
544 return std::optional(ViewIndex{i, true});
545 }
546
547 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url() == directory) {
548 return std::optional(ViewIndex{i, false});
549 }
550
551 i = (i + 1) % count();
552 } while (i != currentIndex());
553
554 return std::nullopt;
555 }
556
557 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewShowingItem(const QUrl &item) const
558 {
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));
562
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;
568 }
569
570 // Is dirContainingItem expanded in some tree-style view?
571 // The rest of this method is about figuring this out.
572
573 int i = currentIndex();
574 if (i < 0) {
575 return std::nullopt;
576 }
577 // loop over the tabs starting from the current one
578 do {
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});
584 }
585 }
586
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});
591 }
592 }
593
594 i = (i + 1) % count();
595 } while (i != currentIndex());
596
597 return std::nullopt;
598 }
599
600 #include "moc_dolphintabwidget.cpp"