]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphintabwidget.cpp
Handle deprecation of QGuiApplication::paletteChanged
[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_dragAndDropHelper{this}
27 , m_lastViewedTab(nullptr)
28 , m_navigatorsWidget{navigatorsWidget}
29 {
30 KAcceleratorManager::setNoAccel(this);
31
32 connect(this, &DolphinTabWidget::tabCloseRequested, this, QOverload<int>::of(&DolphinTabWidget::closeTab));
33 connect(this, &DolphinTabWidget::currentChanged, this, &DolphinTabWidget::currentTabChanged);
34
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);
40
41 setTabBar(tabBar);
42 setDocumentMode(true);
43 setElideMode(Qt::ElideRight);
44 setUsesScrollButtons(true);
45 setTabBarAutoHide(true);
46 }
47
48 DolphinTabPage *DolphinTabWidget::currentTabPage() const
49 {
50 return tabPageAt(currentIndex());
51 }
52
53 DolphinTabPage *DolphinTabWidget::nextTabPage() const
54 {
55 const int index = currentIndex() + 1;
56 return tabPageAt(index < count() ? index : 0);
57 }
58
59 DolphinTabPage *DolphinTabWidget::prevTabPage() const
60 {
61 const int index = currentIndex() - 1;
62 return tabPageAt(index >= 0 ? index : (count() - 1));
63 }
64
65 DolphinTabPage *DolphinTabWidget::tabPageAt(const int index) const
66 {
67 return static_cast<DolphinTabPage *>(widget(index));
68 }
69
70 void DolphinTabWidget::saveProperties(KConfigGroup &group) const
71 {
72 const int tabCount = count();
73 group.writeEntry("Tab Count", tabCount);
74 group.writeEntry("Active Tab Index", currentIndex());
75
76 for (int i = 0; i < tabCount; ++i) {
77 const DolphinTabPage *tabPage = tabPageAt(i);
78 group.writeEntry("Tab Data " % QString::number(i), tabPage->saveState());
79 }
80 }
81
82 void DolphinTabWidget::readProperties(const KConfigGroup &group)
83 {
84 const int tabCount = group.readEntry("Tab Count", 0);
85 for (int i = 0; i < tabCount; ++i) {
86 if (i >= count()) {
87 openNewActivatedTab();
88 }
89 const QByteArray state = group.readEntry("Tab Data " % QString::number(i), QByteArray());
90 tabPageAt(i)->restoreState(state);
91 }
92
93 const int index = group.readEntry("Active Tab Index", 0);
94 setCurrentIndex(index);
95 }
96
97 void DolphinTabWidget::refreshViews()
98 {
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);
103 } else {
104 setElideMode(Qt::ElideRight);
105 }
106
107 const int tabCount = count();
108 for (int i = 0; i < tabCount; ++i) {
109 updateTabName(i);
110 tabPageAt(i)->refreshViews();
111 }
112 }
113
114 void DolphinTabWidget::updateTabName(int index)
115 {
116 Q_ASSERT(index >= 0);
117 tabBar()->setTabText(index, tabName(tabPageAt(index)));
118 }
119
120 bool DolphinTabWidget::isUrlOpen(const QUrl &url) const
121 {
122 return viewOpenAtDirectory(url).has_value();
123 }
124
125 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl &urlOfItem) const
126 {
127 return viewShowingItem(urlOfItem).has_value();
128 }
129
130 void DolphinTabWidget::openNewActivatedTab()
131 {
132 std::unique_ptr<DolphinUrlNavigator::VisualState> oldNavigatorState;
133 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget->secondaryUrlNavigator()) {
134 oldNavigatorState = m_navigatorsWidget->primaryUrlNavigator()->visualState();
135 } else {
136 oldNavigatorState = m_navigatorsWidget->secondaryUrlNavigator()->visualState();
137 }
138
139 const DolphinViewContainer *oldActiveViewContainer = currentTabPage()->activeViewContainer();
140 Q_ASSERT(oldActiveViewContainer);
141
142 openNewActivatedTab(oldActiveViewContainer->url());
143
144 DolphinViewContainer *newActiveViewContainer = currentTabPage()->activeViewContainer();
145 Q_ASSERT(newActiveViewContainer);
146
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());
150
151 // Always focus the new tab's view
152 newActiveViewContainer->view()->setFocus();
153 }
154
155 void DolphinTabWidget::openNewActivatedTab(const QUrl &primaryUrl, const QUrl &secondaryUrl)
156 {
157 openNewTab(primaryUrl, secondaryUrl);
158 if (GeneralSettings::openNewTabAfterLastTab()) {
159 setCurrentIndex(count() - 1);
160 } else {
161 setCurrentIndex(currentIndex() + 1);
162 }
163 }
164
165 void DolphinTabWidget::openNewTab(const QUrl &primaryUrl, const QUrl &secondaryUrl, DolphinTabWidget::NewTabPosition position)
166 {
167 QWidget *focusWidget = QApplication::focusWidget();
168
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));
175 });
176
177 if (position == NewTabPosition::FollowSetting) {
178 if (GeneralSettings::openNewTabAfterLastTab()) {
179 position = NewTabPosition::AtEnd;
180 } else {
181 position = NewTabPosition::AfterCurrent;
182 }
183 }
184
185 int newTabIndex = -1;
186 if (position == NewTabPosition::AfterCurrent || (position == NewTabPosition::FollowSetting && !GeneralSettings::openNewTabAfterLastTab())) {
187 newTabIndex = currentIndex() + 1;
188 }
189
190 insertTab(newTabIndex, tabPage, QIcon() /* loaded in tabInserted */, tabName(tabPage));
191
192 if (focusWidget) {
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();
196 }
197 }
198
199 void DolphinTabWidget::openDirectories(const QList<QUrl> &dirs, bool splitView)
200 {
201 Q_ASSERT(dirs.size() > 0);
202
203 bool somethingWasAlreadyOpen = false;
204
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);
209
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);
219 } else {
220 openNewActivatedTab(primaryUrl, secondaryUrl);
221 }
222 } else {
223 if (somethingWasAlreadyOpen) {
224 openNewTab(primaryUrl);
225 } else {
226 openNewActivatedTab(primaryUrl);
227 }
228 }
229 }
230 }
231
232 void DolphinTabWidget::openFiles(const QList<QUrl> &files, bool splitView)
233 {
234 Q_ASSERT(files.size() > 0);
235
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)) {
242 continue;
243 }
244
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);
253 } else {
254 dirsThatNeedToBeOpened.append(dir);
255 }
256 }
257
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);
263 }
264 const int tabCount = count();
265
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();
276 }
277 }
278 }
279
280 void DolphinTabWidget::closeTab()
281 {
282 closeTab(currentIndex());
283 }
284
285 void DolphinTabWidget::closeTab(const int index)
286 {
287 Q_ASSERT(index >= 0);
288 Q_ASSERT(index < count());
289
290 if (count() < 2) {
291 // Close Dolphin when closing the last tab.
292 parentWidget()->close();
293 return;
294 }
295
296 DolphinTabPage *tabPage = tabPageAt(index);
297 Q_EMIT rememberClosedTab(tabPage->activeViewContainer()->url(), tabPage->saveState());
298
299 removeTab(index);
300 tabPage->deleteLater();
301 }
302
303 void DolphinTabWidget::activateTab(const int index)
304 {
305 if (index < count()) {
306 setCurrentIndex(index);
307 }
308 }
309
310 void DolphinTabWidget::activateLastTab()
311 {
312 setCurrentIndex(count() - 1);
313 }
314
315 void DolphinTabWidget::activateNextTab()
316 {
317 const int index = currentIndex() + 1;
318 setCurrentIndex(index < count() ? index : 0);
319 }
320
321 void DolphinTabWidget::activatePrevTab()
322 {
323 const int index = currentIndex() - 1;
324 setCurrentIndex(index >= 0 ? index : (count() - 1));
325 }
326
327 void DolphinTabWidget::restoreClosedTab(const QByteArray &state)
328 {
329 openNewActivatedTab();
330 currentTabPage()->restoreState(state);
331 }
332
333 void DolphinTabWidget::copyToInactiveSplitView()
334 {
335 const DolphinTabPage *tabPage = currentTabPage();
336 if (!tabPage->splitViewEnabled()) {
337 return;
338 }
339
340 const KFileItemList selectedItems = tabPage->activeViewContainer()->view()->selectedItems();
341 if (selectedItems.isEmpty()) {
342 return;
343 }
344
345 DolphinView *const inactiveView = tabPage->inactiveViewContainer()->view();
346 inactiveView->copySelectedItems(selectedItems, inactiveView->url());
347 }
348
349 void DolphinTabWidget::moveToInactiveSplitView()
350 {
351 const DolphinTabPage *tabPage = currentTabPage();
352 if (!tabPage->splitViewEnabled()) {
353 return;
354 }
355
356 const KFileItemList selectedItems = tabPage->activeViewContainer()->view()->selectedItems();
357 if (selectedItems.isEmpty()) {
358 return;
359 }
360
361 DolphinView *const inactiveView = tabPage->inactiveViewContainer()->view();
362 inactiveView->moveSelectedItems(selectedItems, inactiveView->url());
363 }
364
365 void DolphinTabWidget::detachTab(int index)
366 {
367 Q_ASSERT(index >= 0);
368
369 QStringList args;
370
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");
376 }
377 args << QStringLiteral("--new-window");
378
379 KIO::CommandLauncherJob *job = new KIO::CommandLauncherJob("dolphin", args, this);
380 job->setDesktopName(QStringLiteral("org.kde.dolphin"));
381 job->start();
382
383 closeTab(index);
384 }
385
386 void DolphinTabWidget::openNewActivatedTab(int index)
387 {
388 Q_ASSERT(index >= 0);
389 const DolphinTabPage *tabPage = tabPageAt(index);
390 openNewActivatedTab(tabPage->activeViewContainer()->url());
391 }
392
393 void DolphinTabWidget::tabDragMoveEvent(int index, QDragMoveEvent *event)
394 {
395 if (index >= 0) {
396 DolphinView *view = tabPageAt(index)->activeViewContainer()->view();
397 m_dragAndDropHelper.updateDropAction(event, view->url());
398 }
399 }
400
401 void DolphinTabWidget::tabDropEvent(int index, QDropEvent *event)
402 {
403 if (index >= 0) {
404 DolphinView *view = tabPageAt(index)->activeViewContainer()->view();
405 view->dropUrls(view->url(), event, view);
406 } else {
407 const auto urls = event->mimeData()->urls();
408
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);
414 }
415 });
416 }
417 }
418 }
419
420 void DolphinTabWidget::tabUrlChanged(const QUrl &url)
421 {
422 const int index = indexOf(qobject_cast<QWidget *>(sender()));
423 if (index >= 0) {
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)));
430 } else {
431 // Mark as dirty, actually load once the tab bar actually gets shown
432 tabBar()->setTabIcon(index, QIcon());
433 }
434
435 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
436 if (index == currentIndex()) {
437 Q_EMIT currentUrlChanged(url);
438 }
439
440 Q_EMIT urlChanged(url);
441 }
442 }
443
444 void DolphinTabWidget::currentTabChanged(int index)
445 {
446 DolphinTabPage *tabPage = tabPageAt(index);
447 if (tabPage == m_lastViewedTab) {
448 return;
449 }
450 if (m_lastViewedTab) {
451 m_lastViewedTab->disconnectNavigators();
452 m_lastViewedTab->setActive(false);
453 }
454 if (tabPage->splitViewEnabled() && !m_navigatorsWidget->secondaryUrlNavigator()) {
455 m_navigatorsWidget->createSecondaryUrlNavigator();
456 }
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;
464 }
465
466 void DolphinTabWidget::tabInserted(int index)
467 {
468 QTabWidget::tabInserted(index);
469
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)));
478 }
479 if (tabBar()->tabToolTip(i).isEmpty()) {
480 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
481 }
482 }
483 }
484
485 Q_EMIT tabCountChanged(count());
486 }
487
488 void DolphinTabWidget::tabRemoved(int index)
489 {
490 QTabWidget::tabRemoved(index);
491
492 Q_EMIT tabCountChanged(count());
493 }
494
495 QString DolphinTabWidget::tabName(DolphinTabPage *tabPage) const
496 {
497 if (!tabPage) {
498 return QString();
499 }
500 // clang-format off
501 QString name;
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());
507 } else {
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());
511 }
512 } else {
513 name = tabPage->activeViewContainer()->caption();
514 }
515 // clang-format on
516
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 */);
520 }
521
522 DolphinViewContainer *DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex) const
523 {
524 const auto tabPage = tabPageAt(viewIndex.tabIndex);
525 if (!tabPage) {
526 return nullptr;
527 }
528 return viewIndex.isInPrimaryView ? tabPage->primaryViewContainer() : tabPage->secondaryViewContainer();
529 }
530
531 DolphinViewContainer *DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex)
532 {
533 activateTab(viewIndex.tabIndex);
534 auto viewContainer = viewContainerAt(viewIndex);
535 if (!viewContainer) {
536 return nullptr;
537 }
538 viewContainer->setActive(true);
539 return viewContainer;
540 }
541
542 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl &directory) const
543 {
544 int i = currentIndex();
545 if (i < 0) {
546 return std::nullopt;
547 }
548 // loop over the tabs starting from the current one
549 do {
550 const auto tabPage = tabPageAt(i);
551 if (tabPage->primaryViewContainer()->url() == directory) {
552 return std::optional(ViewIndex{i, true});
553 }
554
555 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url() == directory) {
556 return std::optional(ViewIndex{i, false});
557 }
558
559 i = (i + 1) % count();
560 } while (i != currentIndex());
561
562 return std::nullopt;
563 }
564
565 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewShowingItem(const QUrl &item) const
566 {
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));
570
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;
576 }
577
578 // Is dirContainingItem expanded in some tree-style view?
579 // The rest of this method is about figuring this out.
580
581 int i = currentIndex();
582 if (i < 0) {
583 return std::nullopt;
584 }
585 // loop over the tabs starting from the current one
586 do {
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});
592 }
593 }
594
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});
599 }
600 }
601
602 i = (i + 1) % count();
603 } while (i != currentIndex());
604
605 return std::nullopt;
606 }
607
608 #include "moc_dolphintabwidget.cpp"