]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphintabwidget.cpp
Use both split view names in tab names
[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 <KConfigGroup>
14 #include <KShell>
15 #include <kio/global.h>
16 #include <KIO/CommandLauncherJob>
17 #include <KAcceleratorManager>
18 #include <KLocalizedString>
19
20 #include <QApplication>
21 #include <QDropEvent>
22
23 DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction *navigatorsWidget, QWidget* parent) :
24 QTabWidget(parent),
25 m_lastViewedTab(nullptr),
26 m_navigatorsWidget{navigatorsWidget}
27 {
28 KAcceleratorManager::setNoAccel(this);
29
30 connect(this, &DolphinTabWidget::tabCloseRequested,
31 this, QOverload<int>::of(&DolphinTabWidget::closeTab));
32 connect(this, &DolphinTabWidget::currentChanged,
33 this, &DolphinTabWidget::currentTabChanged);
34
35 DolphinTabBar* tabBar = new DolphinTabBar(this);
36 connect(tabBar, &DolphinTabBar::openNewActivatedTab,
37 this, QOverload<int>::of(&DolphinTabWidget::openNewActivatedTab));
38 connect(tabBar, &DolphinTabBar::tabDropEvent,
39 this, &DolphinTabWidget::tabDropEvent);
40 connect(tabBar, &DolphinTabBar::tabDetachRequested,
41 this, &DolphinTabWidget::detachTab);
42 tabBar->hide();
43
44 setTabBar(tabBar);
45 setDocumentMode(true);
46 setElideMode(Qt::ElideRight);
47 setUsesScrollButtons(true);
48 }
49
50 DolphinTabPage* DolphinTabWidget::currentTabPage() const
51 {
52 return tabPageAt(currentIndex());
53 }
54
55 DolphinTabPage* DolphinTabWidget::nextTabPage() const
56 {
57 const int index = currentIndex() + 1;
58 return tabPageAt(index < count() ? index : 0);
59 }
60
61 DolphinTabPage* DolphinTabWidget::prevTabPage() const
62 {
63 const int index = currentIndex() - 1;
64 return tabPageAt(index >= 0 ? index : (count() - 1));
65 }
66
67 DolphinTabPage* DolphinTabWidget::tabPageAt(const int index) const
68 {
69 return static_cast<DolphinTabPage*>(widget(index));
70 }
71
72 void DolphinTabWidget::saveProperties(KConfigGroup& group) const
73 {
74 const int tabCount = count();
75 group.writeEntry("Tab Count", tabCount);
76 group.writeEntry("Active Tab Index", currentIndex());
77
78 for (int i = 0; i < tabCount; ++i) {
79 const DolphinTabPage* tabPage = tabPageAt(i);
80 group.writeEntry("Tab Data " % QString::number(i), tabPage->saveState());
81 }
82 }
83
84 void DolphinTabWidget::readProperties(const KConfigGroup& group)
85 {
86 const int tabCount = group.readEntry("Tab Count", 0);
87 for (int i = 0; i < tabCount; ++i) {
88 if (i >= count()) {
89 openNewActivatedTab();
90 }
91 const QByteArray state = group.readEntry("Tab Data " % QString::number(i), QByteArray());
92 tabPageAt(i)->restoreState(state);
93 }
94
95 const int index = group.readEntry("Active Tab Index", 0);
96 setCurrentIndex(index);
97 }
98
99 void DolphinTabWidget::refreshViews()
100 {
101 // Left-elision is better when showing full paths, since you care most
102 // about the current directory which is on the right
103 if (GeneralSettings::showFullPathInTitlebar()) {
104 setElideMode(Qt::ElideLeft);
105 } else {
106 setElideMode(Qt::ElideRight);
107 }
108
109 const int tabCount = count();
110 for (int i = 0; i < tabCount; ++i) {
111 tabBar()->setTabText(i, tabName(tabPageAt(i)));
112 tabPageAt(i)->refreshViews();
113 }
114 }
115
116 bool DolphinTabWidget::isUrlOpen(const QUrl &url) const
117 {
118 return viewOpenAtDirectory(url).has_value();
119 }
120
121 bool DolphinTabWidget::isItemVisibleInAnyView(const QUrl &urlOfItem) const
122 {
123 return viewShowingItem(urlOfItem).has_value();
124 }
125
126 void DolphinTabWidget::openNewActivatedTab()
127 {
128 std::unique_ptr<DolphinUrlNavigator::VisualState> oldNavigatorState;
129 if (currentTabPage()->primaryViewActive() || !m_navigatorsWidget->secondaryUrlNavigator()) {
130 oldNavigatorState = m_navigatorsWidget->primaryUrlNavigator()->visualState();
131 } else {
132 oldNavigatorState = m_navigatorsWidget->secondaryUrlNavigator()->visualState();
133 }
134
135 const DolphinViewContainer* oldActiveViewContainer = currentTabPage()->activeViewContainer();
136 Q_ASSERT(oldActiveViewContainer);
137
138 openNewActivatedTab(oldActiveViewContainer->url());
139
140 DolphinViewContainer* newActiveViewContainer = currentTabPage()->activeViewContainer();
141 Q_ASSERT(newActiveViewContainer);
142
143 // The URL navigator of the new tab should have the same editable state
144 // as the current tab
145 newActiveViewContainer->urlNavigator()->setVisualState(*oldNavigatorState.get());
146
147 // Always focus the new tab's view
148 newActiveViewContainer->view()->setFocus();
149 }
150
151 void DolphinTabWidget::openNewActivatedTab(const QUrl& primaryUrl, const QUrl& secondaryUrl)
152 {
153 openNewTab(primaryUrl, secondaryUrl);
154 if (GeneralSettings::openNewTabAfterLastTab()) {
155 setCurrentIndex(count() - 1);
156 } else {
157 setCurrentIndex(currentIndex() + 1);
158 }
159 }
160
161 void DolphinTabWidget::openNewTab(const QUrl& primaryUrl, const QUrl& secondaryUrl, DolphinTabWidget::NewTabPosition position)
162 {
163 QWidget* focusWidget = QApplication::focusWidget();
164
165 DolphinTabPage* tabPage = new DolphinTabPage(primaryUrl, secondaryUrl, this);
166 tabPage->setActive(false);
167 connect(tabPage, &DolphinTabPage::activeViewChanged,
168 this, &DolphinTabWidget::activeViewChanged);
169 connect(tabPage, &DolphinTabPage::activeViewUrlChanged,
170 this, &DolphinTabWidget::tabUrlChanged);
171 connect(tabPage->activeViewContainer(), &DolphinViewContainer::captionChanged, this, [this, tabPage]() {
172 const int tabIndex = indexOf(tabPage);
173 Q_ASSERT(tabIndex >= 0);
174 tabBar()->setTabText(tabIndex, tabName(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 = tabPageAt(currentIndex());
336 DolphinViewContainer* activeViewContainer = currentTabPage()->activeViewContainer();
337 if (!tabPage->splitViewEnabled() || activeViewContainer->view()->selectedItems().isEmpty()) {
338 return;
339 }
340
341 if (tabPage->primaryViewActive()) {
342 // copy from left panel to right
343 activeViewContainer->view()->copySelectedItems(activeViewContainer->view()->selectedItems(), tabPage->secondaryViewContainer()->url());
344 } else {
345 // copy from right panel to left
346 activeViewContainer->view()->copySelectedItems(activeViewContainer->view()->selectedItems(), tabPage->primaryViewContainer()->url());
347 }
348 }
349
350 void DolphinTabWidget::moveToInactiveSplitView()
351 {
352 const DolphinTabPage* tabPage = tabPageAt(currentIndex());
353 DolphinViewContainer* activeViewContainer = currentTabPage()->activeViewContainer();
354 if (!tabPage->splitViewEnabled() || activeViewContainer->view()->selectedItems().isEmpty()) {
355 return;
356 }
357
358 if (tabPage->primaryViewActive()) {
359 // move from left panel to right
360 activeViewContainer->view()->moveSelectedItems(activeViewContainer->view()->selectedItems(), tabPage->secondaryViewContainer()->url());
361 } else {
362 // move from right panel to left
363 activeViewContainer->view()->moveSelectedItems(activeViewContainer->view()->selectedItems(), tabPage->primaryViewContainer()->url());
364 }
365 }
366
367 void DolphinTabWidget::detachTab(int index)
368 {
369 Q_ASSERT(index >= 0);
370
371 QStringList args;
372
373 const DolphinTabPage* tabPage = tabPageAt(index);
374 args << tabPage->primaryViewContainer()->url().url();
375 if (tabPage->splitViewEnabled()) {
376 args << tabPage->secondaryViewContainer()->url().url();
377 args << QStringLiteral("--split");
378 }
379 args << QStringLiteral("--new-window");
380
381 KIO::CommandLauncherJob *job = new KIO::CommandLauncherJob("dolphin", args, this);
382 job->setDesktopName(QStringLiteral("org.kde.dolphin"));
383 job->start();
384
385 closeTab(index);
386 }
387
388 void DolphinTabWidget::openNewActivatedTab(int index)
389 {
390 Q_ASSERT(index >= 0);
391 const DolphinTabPage* tabPage = tabPageAt(index);
392 openNewActivatedTab(tabPage->activeViewContainer()->url());
393 }
394
395 void DolphinTabWidget::tabDropEvent(int index, QDropEvent* event)
396 {
397 if (index >= 0) {
398 DolphinView* view = tabPageAt(index)->activeViewContainer()->view();
399 view->dropUrls(view->url(), event, view);
400 } else {
401 const auto urls = event->mimeData()->urls();
402
403 for (const QUrl &url : urls) {
404 auto *job = KIO::statDetails(url, KIO::StatJob::SourceSide, KIO::StatDetail::StatBasic, KIO::JobFlag::HideProgressInfo);
405 connect(job, &KJob::result, this, [this, job]() {
406 if (!job->error() && job->statResult().isDir()) {
407 openNewTab(job->url(), QUrl(), NewTabPosition::AtEnd);
408 }
409 });
410 }
411 }
412 }
413
414 void DolphinTabWidget::tabUrlChanged(const QUrl& url)
415 {
416 const int index = indexOf(qobject_cast<QWidget*>(sender()));
417 if (index >= 0) {
418 tabBar()->setTabText(index, tabName(tabPageAt(index)));
419 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
420 if (tabBar()->isVisible()) {
421 // ensure the path url ends with a slash to have proper folder icon for remote folders
422 const QUrl pathUrl = QUrl(url.adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/"));
423 tabBar()->setTabIcon(index, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl)));
424 } else {
425 // Mark as dirty, actually load once the tab bar actually gets shown
426 tabBar()->setTabIcon(index, QIcon());
427 }
428
429 // Emit the currentUrlChanged signal if the url of the current tab has been changed.
430 if (index == currentIndex()) {
431 Q_EMIT currentUrlChanged(url);
432 }
433 }
434 }
435
436 void DolphinTabWidget::currentTabChanged(int index)
437 {
438 DolphinTabPage *tabPage = tabPageAt(index);
439 if (tabPage == m_lastViewedTab) {
440 return;
441 }
442 if (m_lastViewedTab) {
443 m_lastViewedTab->disconnectNavigators();
444 m_lastViewedTab->setActive(false);
445 }
446 if (tabPage->splitViewEnabled() && !m_navigatorsWidget->secondaryUrlNavigator()) {
447 m_navigatorsWidget->createSecondaryUrlNavigator();
448 }
449 DolphinViewContainer* viewContainer = tabPage->activeViewContainer();
450 Q_EMIT activeViewChanged(viewContainer);
451 Q_EMIT currentUrlChanged(viewContainer->url());
452 tabPage->setActive(true);
453 tabPage->connectNavigators(m_navigatorsWidget);
454 m_navigatorsWidget->setSecondaryNavigatorVisible(tabPage->splitViewEnabled());
455 m_lastViewedTab = tabPage;
456 }
457
458 void DolphinTabWidget::tabInserted(int index)
459 {
460 QTabWidget::tabInserted(index);
461
462 if (count() > 1) {
463 // Resolve all pending tab icons
464 for (int i = 0; i < count(); ++i) {
465 const QUrl url = tabPageAt(i)->activeViewContainer()->url();
466 if (tabBar()->tabIcon(i).isNull()) {
467 // ensure the path url ends with a slash to have proper folder icon for remote folders
468 const QUrl pathUrl = QUrl(url.adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/"));
469 tabBar()->setTabIcon(i, QIcon::fromTheme(KIO::iconNameForUrl(pathUrl)));
470 }
471 if (tabBar()->tabToolTip(i).isEmpty()) {
472 tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile));
473 }
474 }
475
476 tabBar()->show();
477 }
478
479 Q_EMIT tabCountChanged(count());
480 }
481
482 void DolphinTabWidget::tabRemoved(int index)
483 {
484 QTabWidget::tabRemoved(index);
485
486 // If only one tab is left, then remove the tab entry so that
487 // closing the last tab is not possible.
488 if (count() < 2) {
489 tabBar()->hide();
490 }
491
492 Q_EMIT tabCountChanged(count());
493 }
494
495 QString DolphinTabWidget::tabName(DolphinTabPage* tabPage) const
496 {
497 if (!tabPage) {
498 return QString();
499 }
500
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
516 // Make sure that a '&' inside the directory name is displayed correctly
517 // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText()
518 return name.replace('&', QLatin1String("&&"));
519 }
520
521 DolphinViewContainer *DolphinTabWidget::viewContainerAt(DolphinTabWidget::ViewIndex viewIndex) const
522 {
523 const auto tabPage = tabPageAt(viewIndex.tabIndex);
524 if (!tabPage) {
525 return nullptr;
526 }
527 return viewIndex.isInPrimaryView ? tabPage->primaryViewContainer() : tabPage->secondaryViewContainer();
528 }
529
530 DolphinViewContainer *DolphinTabWidget::activateViewContainerAt(DolphinTabWidget::ViewIndex viewIndex)
531 {
532 activateTab(viewIndex.tabIndex);
533 auto viewContainer = viewContainerAt(viewIndex);
534 if (!viewContainer) {
535 return nullptr;
536 }
537 viewContainer->setActive(true);
538 return viewContainer;
539 }
540
541 const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl& directory) const
542 {
543 int i = currentIndex();
544 if (i < 0) {
545 return std::nullopt;
546 }
547 // loop over the tabs starting from the current one
548 do {
549 const auto tabPage = tabPageAt(i);
550 if (tabPage->primaryViewContainer()->url() == directory) {
551 return std::optional(ViewIndex{i, true});
552 }
553
554 if (tabPage->splitViewEnabled() && tabPage->secondaryViewContainer()->url() == directory) {
555 return std::optional(ViewIndex{i, false});
556 }
557
558 i = (i + 1) % count();
559 }
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 }
604 while (i != currentIndex());
605
606 return std::nullopt;
607 }