File: panelmanager.cpp

package info (click to toggle)
krusader 2%3A2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,448 kB
  • sloc: cpp: 56,112; ansic: 1,187; xml: 811; sh: 23; makefile: 3
file content (617 lines) | stat: -rw-r--r-- 19,045 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/*
    SPDX-FileCopyrightText: 2002 Shie Erlich <erlich@users.sourceforge.net>
    SPDX-FileCopyrightText: 2002 Rafi Yanai <yanai@users.sourceforge.net>
    SPDX-FileCopyrightText: 2004-2022 Krusader Krew <https://krusader.org>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "panelmanager.h"

#include "Panel/PanelView/krview.h"
#include "Panel/PanelView/krviewfactory.h"
#include "Panel/listpanel.h"
#include "Panel/panelfunc.h"
#include "defaults.h"
#include "icon.h"
#include "kractions.h"
#include "krmainwindow.h"
#include "krusaderview.h"
#include "tabactions.h"

#include <assert.h>

// QtGui
#include <QImage>
// QtWidgets
#include <QGridLayout>
#include <QMenu>
#include <QStackedWidget>
#include <QToolButton>

#include <KConfig>
#include <KLocalizedString>

PanelManager::PanelManager(QWidget *parent, KrMainWindow *mainWindow, bool left)
    : QWidget(parent)
    , _otherManager(nullptr)
    , _actions(mainWindow->tabActions())
    , _layout(nullptr)
    , _left(left)
    , _currentPanel(nullptr)
{
    _layout = new QGridLayout(this);
    _layout->setContentsMargins(0, 0, 0, 0);
    _layout->setSpacing(0);
    _stack = new QStackedWidget(this);

    // new tab button
    _newTab = new QToolButton(this);
    _newTab->setAutoRaise(true);
    _newTab->setText(i18n("Open a new tab"));
    _newTab->setToolTip(i18n("Open a new tab"));
    _newTab->setIcon(Icon("tab-new"));
    _newTab->adjustSize();
    connect(_newTab, &QToolButton::clicked, this, &PanelManager::slotNewTabButton);

    // tab-bar
    _tabbar = new PanelTabBar(this, _actions);
    connect(_tabbar, &PanelTabBar::currentChanged, this, &PanelManager::slotCurrentTabChanged);
    connect(_tabbar, &PanelTabBar::tabCloseRequested, this, QOverload<int>::of(&PanelManager::slotCloseTab));
    connect(_tabbar, &PanelTabBar::closeCurrentTab, this, QOverload<>::of(&PanelManager::slotCloseTab));
    connect(_tabbar, &PanelTabBar::duplicateCurrentTab, this, &PanelManager::slotDuplicateTabLMB, Qt::QueuedConnection);
    connect(_tabbar, &PanelTabBar::newTab, this, [=](const QUrl &url) {
        slotNewTab(url);
    });
    connect(_tabbar, &PanelTabBar::draggingTab, this, &PanelManager::slotDraggingTab);
    connect(_tabbar, &PanelTabBar::draggingTabFinished, this, &PanelManager::slotDraggingTabFinished);

    auto *tabbarLayout = new QHBoxLayout;
    tabbarLayout->setSpacing(0);
    tabbarLayout->setContentsMargins(0, 0, 0, 0);

    tabbarLayout->addWidget(_tabbar);
    tabbarLayout->addWidget(_newTab);

    _layout->addWidget(_stack, 0, 0);
    _layout->addLayout(tabbarLayout, 1, 0);

    updateTabbarPos();

    setLayout(_layout);

    addPanel(true);

    tabsCountChanged();
}

void PanelManager::tabsCountChanged()
{
    const KConfigGroup cfg(krConfig, "Look&Feel");
    const bool showTabbar = _tabbar->count() > 1 || cfg.readEntry("Show Tab Bar On Single Tab", true);
    const bool showNewButton = showTabbar && cfg.readEntry("Show New Tab Button", true);
    const bool showCloseButtons = showTabbar && cfg.readEntry("Show Close Tab Buttons", true);

    _tabbar->setVisible(showTabbar);
    _newTab->setVisible(showNewButton);

    // disable close button if only 1 tab is left
    _tabbar->setTabsClosable(showCloseButtons && _tabbar->count() > 1);

    _actions->refreshActions();
}

void PanelManager::activate()
{
    assert(sender() == (currentPanel()->gui));
    emit setActiveManager(this);
    _actions->refreshActions();
}

void PanelManager::slotCurrentTabChanged(int index)
{
    ListPanel *panel = _tabbar->getPanel(index);

    if (!panel || panel == _currentPanel)
        return;

    ListPanel *previousPanel = _currentPanel;
    _currentPanel = panel;

    _stack->setCurrentWidget(_currentPanel);

    if (previousPanel) {
        previousPanel->slotFocusOnMe(false); // FIXME - necessary ?
    }
    _currentPanel->slotFocusOnMe(this == ACTIVE_MNG);

    emit pathChanged(panel);

    if (otherManager()) {
        otherManager()->currentPanel()->otherPanelChanged();
    }

    // go back to pinned url if tab is pinned and switched back to active
    if (panel->isPinned()) {
        panel->func->openUrl(panel->pinnedUrl());
    }
}

ListPanel *PanelManager::createPanel(const KConfigGroup &cfg)
{
    ListPanel *p = new ListPanel(_stack, this, cfg);
    connectPanel(p);
    return p;
}

void PanelManager::connectPanel(ListPanel *p)
{
    connect(p, &ListPanel::activate, this, &PanelManager::activate);
    connect(p, &ListPanel::pathChanged, this, [=]() {
        emit pathChanged(p);
    });
    connect(p, &ListPanel::pathChanged, this, [=]() {
        _tabbar->updateTab(p);
    });
}

void PanelManager::disconnectPanel(ListPanel *p)
{
    disconnect(p, &ListPanel::activate, this, nullptr);
    disconnect(p, &ListPanel::pathChanged, this, nullptr);
}

ListPanel *PanelManager::addPanel(bool setCurrent, const KConfigGroup &cfg, int insertIndex)
{
    // create the panel and add it into the widgetstack
    ListPanel *p = createPanel(cfg);
    _stack->addWidget(p);

    // now, create the corresponding tab
    int index = _tabbar->addPanel(p, setCurrent, insertIndex);
    tabsCountChanged();

    if (setCurrent)
        slotCurrentTabChanged(index);

    return p;
}

ListPanel *PanelManager::duplicatePanel(const KConfigGroup &cfg, KrPanel *nextTo, int insertIndex)
{
    // Search for the position where the passed panel is
    if (insertIndex == -1) {
        int quantOfPanels = _tabbar->count();
        for (int i = 0; i < quantOfPanels; i++) {
            if (_tabbar->getPanel(i) == nextTo) {
                insertIndex = i + 1;
                break;
            }
        }
    }

    return addPanel(true, cfg, insertIndex);
}

void PanelManager::saveSettings(KConfigGroup config, bool saveHistory)
{
    config.writeEntry("ActiveTab", activeTab());

    KConfigGroup grpTabs(&config, "Tabs");
    const auto tabGroups = grpTabs.groupList();
    for (const QString &grpTab : tabGroups)
        grpTabs.deleteGroup(grpTab);

    for (int i = 0; i < _tabbar->count(); i++) {
        ListPanel *panel = _tabbar->getPanel(i);
        KConfigGroup grpTab(&grpTabs, "Tab" + QString::number(i));
        panel->saveSettings(grpTab, saveHistory);
    }
}

void PanelManager::loadSettings(KConfigGroup config)
{
    KConfigGroup grpTabs(&config, "Tabs");
    int numTabsOld = _tabbar->count();
    qsizetype numTabsNew = grpTabs.groupList().count();

    for (int i = 0; i < numTabsNew; i++) {
        KConfigGroup grpTab(&grpTabs, "Tab" + QString::number(i));
        // TODO workaround for bug 371453. Remove this when bug is fixed
        if (grpTab.keyList().isEmpty())
            continue;

        ListPanel *panel = i < numTabsOld ? _tabbar->getPanel(i) : addPanel(false, grpTab, i);
        panel->restoreSettings(grpTab);
        _tabbar->updateTab(panel);
    }

    for (int i = numTabsOld - 1; i >= numTabsNew && i > 0; i--)
        slotCloseTab(i);

    setActiveTab(config.readEntry("ActiveTab", 0));

    // this is needed so that all tab labels get updated
    layoutTabs();
}

void PanelManager::layoutTabs()
{
    // delayed url refreshes may be pending -
    // delay the layout too so it happens after them
    QTimer::singleShot(0, _tabbar, &PanelTabBar::layoutTabs);
}

KrPanel *PanelManager::currentPanel() const
{
    return _currentPanel;
}

void PanelManager::moveTabToOtherSide()
{
    if (tabCount() < 2)
        return;

    ListPanel *p;
    _tabbar->removeCurrentPanel(p);
    _stack->removeWidget(p);
    disconnectPanel(p);

    p->reparent(_otherManager->_stack, _otherManager);
    _otherManager->connectPanel(p);
    _otherManager->_stack->addWidget(p);
    _otherManager->_tabbar->addPanel(p, true);

    _otherManager->tabsCountChanged();
    tabsCountChanged();

    p->slotFocusOnMe();
}

void PanelManager::moveTabToLeft()
{
    // don't move the leftmost tab - also skip a single tab, always leftmost
    if (_tabbar->currentIndex() == 0)
        return;

    _tabbar->moveTab(_tabbar->currentIndex(), _tabbar->currentIndex() - 1);
}

void PanelManager::moveTabToRight()
{
    // don't move the rightmost tab - also skip a single tab, always rightmost
    if (_tabbar->currentIndex() == tabCount() - 1)
        return;

    _tabbar->moveTab(_tabbar->currentIndex(), _tabbar->currentIndex() + 1);
}

void PanelManager::slotNewTab(const QUrl &url, bool setCurrent, int insertIndex)
{
    ListPanel *p = addPanel(setCurrent, KConfigGroup(), insertIndex);
    p->start(url);
}

void PanelManager::slotNewTabButton()
{
    KConfigGroup group(krConfig, "Look&Feel");
    int insertIndex = group.readEntry("Insert Tabs After Current", false) ? _tabbar->currentIndex() + 1 : _tabbar->count();

    if (group.readEntry("New Tab Button Duplicates", false)) {
        slotDuplicateTab(currentPanel()->virtualPath(), currentPanel(), insertIndex);
        _currentPanel->slotFocusOnMe();
    } else {
        slotNewTab(insertIndex);
    }
}

void PanelManager::slotNewTab(int insertIndex)
{
    slotNewTab(QUrl::fromLocalFile(QDir::home().absolutePath()), true, insertIndex);
    _currentPanel->slotFocusOnMe();
}

void PanelManager::slotDuplicateTab(const QUrl &url, KrPanel *nextTo, int insertIndex)
{
    ListPanel *p = duplicatePanel(KConfigGroup(), nextTo, insertIndex);
    if (nextTo && nextTo->gui) {
        // We duplicate tab settings by writing original settings to a temporary
        // group and making the new tab read settings from it. Duplicating
        // settings directly would add too much complexity.
        QString grpName = "PanelManager_" + QString::number(qApp->applicationPid());
        krConfig->deleteGroup(grpName); // make sure the group is empty
        KConfigGroup cfg(krConfig, grpName);

        nextTo->gui->saveSettings(cfg, true);
        // reset undesired duplicated settings
        cfg.writeEntry("Properties", 0);
        p->restoreSettings(cfg);
        krConfig->deleteGroup(grpName);
    }
    p->start(url);
}

void PanelManager::slotDuplicateTabLMB()
{
    slotDuplicateTab(currentPanel()->virtualPath(), currentPanel());
}

void PanelManager::slotCloseTab()
{
    slotCloseTab(_tabbar->currentIndex());
}

void PanelManager::slotCloseTab(int index)
{
    if (_tabbar->count() <= 1) /* if this is the last tab don't close it */
        return;

    // Back up some data that will be useful if the user wants to
    // undo the closing of the tab
    QByteArray backupData;
    QDataStream tabStream(&backupData, QIODevice::WriteOnly); // In order to serialize data
    tabStream << _left;
    tabStream << index;
    ListPanel *panel = static_cast<ListPanel *>(currentPanel());
    const QUrl urlTab = panel->virtualPath();
    tabStream << urlTab;
    tabStream << panel->getProperties();
    tabStream << panel->pinnedUrl();
    tabStream << panel->view->selectedUrls();

    QAction *actReopenTab = KrActions::actClosedTabsMenu->updateAfterClosingATab(urlTab, backupData, _actions);

    // Save settings of the tab. Note: The code is
    // based on the one of slotDuplicateTab()
    QString grpName = QString("closedTab_%1").arg(reinterpret_cast<qulonglong>(actReopenTab));
    krConfig->deleteGroup(grpName); // make sure the group is empty
    KConfigGroup cfg(krConfig, grpName);
    panel->gui->saveSettings(cfg, true);
    // reset undesired duplicated settings
    cfg.writeEntry("Properties", 0);

    _tabbar->removePanel(index, panel); // this automatically changes the current panel

    _stack->removeWidget(panel);
    deletePanel(panel);
    tabsCountChanged();
}

void PanelManager::slotUndoCloseTab()
{
    const int fixedMenuEntries = KrActions::actClosedTabsMenu->quantFixedMenuEntries;
    Q_ASSERT(KrActions::actClosedTabsMenu->menu()->actions().size() > fixedMenuEntries);
    // Performs the same action as when clicking on that menu item
    KrActions::actClosedTabsMenu->slotTriggered(KrActions::actClosedTabsMenu->menu()->actions().at(fixedMenuEntries));
}

void PanelManager::undoCloseTab(const QAction *action)
{
    QDataStream tabStream(action->data().toByteArray());
    // Deserialize data
    bool closedInTheLeftPan;
    tabStream >> closedInTheLeftPan;
    int insertIndex;
    tabStream >> insertIndex;
    QUrl urlClosedTab;
    tabStream >> urlClosedTab;
    int tabProperties;
    tabStream >> tabProperties;
    QUrl pinnedUrl;
    tabStream >> pinnedUrl;
    QList<QUrl> selectedUrls;
    tabStream >> selectedUrls;

    // This variable points to the PanelManager where the closed tab is going to be restored
    PanelManager *whereToUndo = closedInTheLeftPan ? LEFT_MNG : RIGHT_MNG;

    MAIN_VIEW->slotSetActiveManager(whereToUndo);
    // Open a new tab where to apply the planned changes
    whereToUndo->slotNewTab(urlClosedTab, true, insertIndex);

    // Restore settings of the tab. Note: The code is
    // based on the one of slotDuplicateTab()
    QString grpName = QString("closedTab_%1").arg(reinterpret_cast<qulonglong>(action));
    KConfigGroup cfg(krConfig, grpName);
    ListPanel *panel = static_cast<ListPanel *>(whereToUndo->currentPanel());
    panel->restoreSettings(cfg);
    krConfig->deleteGroup(grpName);
    panel->setProperties(tabProperties);
    panel->setPinnedUrl(pinnedUrl);
    // Note: In `void PanelManager::layoutTabs()` there was a similar `QTimer::singleShot(`
    // and a comment about it: "delayed url refreshes may be pending - delay the layout too
    // so it happens after them"
    QTimer::singleShot(1, this, [=] {
        panel->view->setSelectionUrls(selectedUrls);
    });
}

void PanelManager::delAllClosedTabs()
{
    const int quantFixedMenuEntries = KrActions::actClosedTabsMenu->quantFixedMenuEntries;
    RecentlyClosedTabsMenu *closedTabsMenu = KrActions::actClosedTabsMenu;
    if (closedTabsMenu) {
        const qsizetype quantActions = closedTabsMenu->menu()->actions().size();
        // Remove the actions (and related information) that follow the
        // fixed menu entries
        for (qsizetype x = quantActions - 1; x >= quantFixedMenuEntries; x--) {
            QAction *action = closedTabsMenu->menu()->actions().at(x);
            delClosedTab(action);
        }
    }
}

void PanelManager::delClosedTab(QAction *action)
{
    // Delete the settings of the closed tab.
    // Note: The code is based on the one of slotCloseTab()
    QString grpName = QString("closedTab_%1").arg(reinterpret_cast<qulonglong>(action));
    krConfig->deleteGroup(grpName);

    // Remove the menu entry and the rest of its information
    KrActions::actClosedTabsMenu->removeAction(action);
}

void PanelManager::updateTabbarPos()
{
    KConfigGroup group(krConfig, "Look&Feel");
    if (group.readEntry("Tab Bar Position", _TabBarPosition) == "top") {
        _layout->addWidget(_stack, 2, 0);
        _tabbar->setShape(QTabBar::RoundedNorth);
    } else {
        _layout->addWidget(_stack, 0, 0);
        _tabbar->setShape(QTabBar::RoundedSouth);
    }
}

int PanelManager::activeTab()
{
    return _tabbar->currentIndex();
}

void PanelManager::setActiveTab(int index)
{
    _tabbar->setCurrentIndex(index);
}

void PanelManager::slotRecreatePanels()
{
    updateTabbarPos();

    for (int i = 0; i != _tabbar->count(); i++) {
        QString grpName = "PanelManager_" + QString::number(qApp->applicationPid());
        krConfig->deleteGroup(grpName); // make sure the group is empty
        KConfigGroup cfg(krConfig, grpName);

        ListPanel *oldPanel = _tabbar->getPanel(i);
        oldPanel->view->setFileIconSize(oldPanel->view->defaultFileIconSize());
        oldPanel->saveSettings(cfg, true);
        disconnect(oldPanel);

        ListPanel *newPanel = createPanel(cfg);
        _stack->insertWidget(i, newPanel);
        _tabbar->changePanel(i, newPanel);

        if (_currentPanel == oldPanel) {
            _currentPanel = newPanel;
            _stack->setCurrentWidget(_currentPanel);
        }

        _stack->removeWidget(oldPanel);
        deletePanel(oldPanel);

        newPanel->restoreSettings(cfg);

        _tabbar->updateTab(newPanel);

        krConfig->deleteGroup(grpName);
    }
    tabsCountChanged();
    _currentPanel->slotFocusOnMe(this == ACTIVE_MNG);
    emit pathChanged(_currentPanel);
}

void PanelManager::slotNextTab()
{
    int currTab = _tabbar->currentIndex();
    int nextInd = (currTab == _tabbar->count() - 1 ? 0 : currTab + 1);
    _tabbar->setCurrentIndex(nextInd);
}

void PanelManager::slotPreviousTab()
{
    int currTab = _tabbar->currentIndex();
    int nextInd = (currTab == 0 ? _tabbar->count() - 1 : currTab - 1);
    _tabbar->setCurrentIndex(nextInd);
}

void PanelManager::reloadConfig()
{
    for (int i = 0; i < _tabbar->count(); i++) {
        ListPanel *panel = _tabbar->getPanel(i);
        if (panel) {
            panel->func->refresh();
        }
    }
}

void PanelManager::deletePanel(ListPanel *p)
{
    disconnect(p);
    delete p;
}

void PanelManager::slotCloseInactiveTabs()
{
    int i = 0;
    while (i < _tabbar->count()) {
        if (i == activeTab())
            i++;
        else
            slotCloseTab(i);
    }
}

void PanelManager::slotCloseDuplicatedTabs()
{
    int i = 0;
    while (i < _tabbar->count() - 1) {
        ListPanel *panel1 = _tabbar->getPanel(i);
        if (panel1 != nullptr) {
            for (int j = i + 1; j < _tabbar->count(); j++) {
                ListPanel *panel2 = _tabbar->getPanel(j);
                if (panel2 != nullptr && panel1->virtualPath().matches(panel2->virtualPath(), QUrl::StripTrailingSlash)) {
                    if (j == activeTab()) {
                        slotCloseTab(i);
                        i--;
                        break;
                    } else {
                        slotCloseTab(j);
                        j--;
                    }
                }
            }
        }
        i++;
    }
}

int PanelManager::findTab(QUrl url)
{
    url.setPath(QDir::cleanPath(url.path()));
    for (int i = 0; i < _tabbar->count(); i++) {
        if (_tabbar->getPanel(i)) {
            QUrl panelUrl = _tabbar->getPanel(i)->virtualPath();
            panelUrl.setPath(QDir::cleanPath(panelUrl.path()));
            if (panelUrl.matches(url, QUrl::StripTrailingSlash))
                return i;
        }
    }
    return -1;
}

void PanelManager::slotLockTab()
{
    ListPanel *panel = _currentPanel;
    panel->gui->setTabState(panel->gui->isLocked() ? ListPanel::TabState::DEFAULT : ListPanel::TabState::LOCKED);
    _actions->refreshActions();
    _tabbar->updateTab(panel);
}

void PanelManager::slotPinTab()
{
    ListPanel *panel = _currentPanel;
    panel->gui->setTabState(panel->gui->isPinned() ? ListPanel::TabState::DEFAULT : ListPanel::TabState::PINNED);
    if (panel->gui->isPinned()) {
        QUrl virtualPath = panel->virtualPath();
        panel->setPinnedUrl(virtualPath);
    }
    _actions->refreshActions();
    _tabbar->updateTab(panel);
}

void PanelManager::newTabs(const QStringList &urls)
{
    for (int i = 0; i < urls.count(); i++)
        slotNewTab(QUrl::fromUserInput(urls[i], QString(), QUrl::AssumeLocalFile));
}