]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphintabwidget.cpp
Fix: closing split view doesn't update tab name
[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 }
431
432 void DolphinTabWidget::currentTabChanged(int index)
433 {
434 DolphinTabPage *tabPage = tabPageAt(index);
435 if (tabPage == m_lastViewedTab) {
436 return;
437 }
438 if (m_lastViewedTab) {
439 m_lastViewedTab->disconnectNavigators();
440 m_lastViewedTab->setActive(false);
441 }
442 if (tabPage->splitViewEnabled() && !m_navigatorsWidget->secondaryUrlNavigator()) {
443 m_navigatorsWidget->createSecondaryUrlNavigator();
444 }
445 DolphinViewContainer *viewContainer = tabPage->activeViewContainer();
446 Q_EMIT activeViewChanged(viewContainer);
447 Q_EMIT currentUrlChanged(viewContainer->url());
448 tabPage->setActive(true);
449 tabPage->connectNavigators(m_navigatorsWidget);
450 m_navigatorsWidget->setSecondaryNavigatorVisible(tabPage->splitViewEnabled());
451 m_lastViewedTab = tabPage;
452 }
453
454 void DolphinTabWidget::tabInserted(int index)
455 {
456 QTabWidget::tabInserted(index);
457
458 if (tabBar()->isVisible()) {
459 // Resolve all pending tab icons
460 for (int i = 0; i < count(); ++i) {
461 const QUrl url = tabPageAt(i)->activeViewContainer()->url();
462 if (tabBar()->tabIcon(i).isNull()) {
463 // ensure the path url ends with a slash to have proper folder icon for remote folders
464 const QUrl pathUrl = QUrl(url.adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/"));
465 tabBar()->setTabIcon(i, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl)));
466 }
467 if (tabBar()->tabToolTip(i).isEmpty()) {
468 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
469 }
470 }
471 }
472
473 Q_EMIT tabCountChanged(count());
474 }
475
476 void DolphinTabWidget::tabRemoved(int index)
477 {
478 QTabWidget::tabRemoved(index);
479
480 Q_EMIT tabCountChanged(count());
481 }
482
483 QString DolphinTabWidget::tabName(DolphinTabPage *tabPage) const
484 {
485 if (!tabPage) {
486 return QString();
487 }
488 // clang-format off
489 QString name;
490 if (tabPage->splitViewEnabled()) {
491 if (tabPage->primaryViewActive()) {
492 // 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
493 // left in the tab name. In right to left languages the primary view would be on the right so the tab name should match.
494 name = i18nc("@title:tab Active primary view | (Inactive secondary view)", "%1 | (%2)", tabPage->primaryViewContainer()->caption(), tabPage->secondaryViewContainer()->caption());
495 } else {
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 (Inactive primary view) | Active secondary view", "(%1) | %2", tabPage->primaryViewContainer()->caption(), tabPage->secondaryViewContainer()->caption());
499 }
500 } else {
501 name = tabPage->activeViewContainer()->caption();
502 }
503 // clang-format on
504
505 // Make sure that a '&' inside the directory name is displayed correctly
506 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
507 return KStringHandler::rsqueeze(name.replace('&', QLatin1String("&&")), 40 /* default maximum visible folder name visible */);
508 }
509
510 DolphinViewContainer *DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex) const
511 {
512 const auto tabPage = tabPageAt(viewIndex.tabIndex);
513 if (!tabPage) {
514 return nullptr;
515 }
516 return viewIndex.isInPrimaryView ? tabPage->primaryViewContainer() : tabPage->secondaryViewContainer();
517 }
518
519 DolphinViewContainer *DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex)
520 {
521 activateTab(viewIndex.tabIndex);
522 auto viewContainer = viewContainerAt(viewIndex);
523 if (!viewContainer) {
524 return nullptr;
525 }
526 viewContainer->setActive(true);
527 return viewContainer;
528 }
529
530 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl &directory) const
531 {
532 int i = currentIndex();
533 if (i < 0) {
534 return std::nullopt;
535 }
536 // loop over the tabs starting from the current one
537 do {
538 const auto tabPage = tabPageAt(i);
539 if (tabPage->primaryViewContainer()->url() == directory) {
540 return std::optional(ViewIndex{i, true});
541 }
542
543 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url() == directory) {
544 return std::optional(ViewIndex{i, false});
545 }
546
547 i = (i + 1) % count();
548 } while (i != currentIndex());
549
550 return std::nullopt;
551 }
552
553 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewShowingItem(const QUrl &item) const
554 {
555 // The item might not be loaded yet even though it exists. So instead
556 // we check if the folder containing the item is showing its contents.
557 const QUrl dirContainingItem(item.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash));
558
559 // The dirContainingItem is either open directly or expanded in a tree-style view mode.
560 // Is dirContainingitem the base url of a view?
561 auto viewOpenAtContainingDirectory = viewOpenAtDirectory(dirContainingItem);
562 if (viewOpenAtContainingDirectory.has_value()) {
563 return viewOpenAtContainingDirectory;
564 }
565
566 // Is dirContainingItem expanded in some tree-style view?
567 // The rest of this method is about figuring this out.
568
569 int i = currentIndex();
570 if (i < 0) {
571 return std::nullopt;
572 }
573 // loop over the tabs starting from the current one
574 do {
575 const auto tabPage = tabPageAt(i);
576 if (tabPage->primaryViewContainer()->url().isParentOf(item)) {
577 const KFileItem fileItemContainingItem = tabPage->primaryViewContainer()->view()->items().findByUrl(dirContainingItem);
578 if (!fileItemContainingItem.isNull() && tabPage->primaryViewContainer()->view()->isExpanded(fileItemContainingItem)) {
579 return std::optional(ViewIndex{i, true});
580 }
581 }
582
583 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url().isParentOf(item)) {
584 const KFileItem fileItemContainingItem = tabPage->secondaryViewContainer()->view()->items().findByUrl(dirContainingItem);
585 if (!fileItemContainingItem.isNull() && tabPage->secondaryViewContainer()->view()->isExpanded(fileItemContainingItem)) {
586 return std::optional(ViewIndex{i, false});
587 }
588 }
589
590 i = (i + 1) % count();
591 } while (i != currentIndex());
592
593 return std::nullopt;
594 }
595
596 #include "moc_dolphintabwidget.cpp"