File: katetabbar.cpp

package info (click to toggle)
kate 4:18.08.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 30,500 kB
  • sloc: xml: 87,988; cpp: 38,094; ansic: 1,805; sh: 95; makefile: 23
file content (595 lines) | stat: -rw-r--r-- 15,689 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
/*   This file is part of the KDE project
 *
 *   Copyright (C) 2014 Dominik Haumann <dhaumann@kde.org>
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Library General Public
 *   License as published by the Free Software Foundation; either
 *   version 2 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Library General Public License for more details.
 *
 *   You should have received a copy of the GNU Library General Public License
 *   along with this library; see the file COPYING.LIB.  If not, write to
 *   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *   Boston, MA 02110-1301, USA.
 */

#include "katetabbar.h"
#include "katetabbutton.h"

#include <math.h> // ceil

// #include <QDebug>
#include <QMimeData>
#include <QPainter>
#include <QResizeEvent>
#include <QStyleOptionTab>
#include <QWheelEvent>

class KateTabBarPrivate
{
public:
    // pointer to tabbar
    KateTabBar *q;

    // minimum and maximum tab width
    int minimumTabWidth;
    int maximumTabWidth;

    // current tab width: when closing tabs with the mouse, we keep
    // the tab width fixed until the mouse leaves the tab bar. This
    // way the user can keep clicking the close button without moving
    // the ouse.
    qreal currentTabWidth;
    bool keepTabWidth;

    bool isActive;

    QVector<KateTabButton *> tabButtons;
    QHash<int, KateTabButton *> idToTab;

    KateTabButton *activeButton;

    int nextID;

public: // functions
    /**
     * Set tab geometry. The tabs are animated only if @p animate is @e true.
     */
    void updateButtonPositions(bool animate = false)
    {
        // if there are no tabs there is nothing to do
        if (tabButtons.count() == 0) {
            return;
        }

        // check whether an animation is still running, in that case,
        // continue animations to avoid jumping tabs
        const int maxi = tabButtons.size();
        if (!animate) {
            for (int i = 0; i < maxi; ++i) {
                if (tabButtons.value(i)->geometryAnimationRunning()) {
                    animate = true;
                    break;
                }
            }
        }

        const int barWidth = q->width();
        const int maxCount = q->maxTabCount();

        // how many tabs do we show?
        const int visibleTabCount = qMin(q->count(), maxCount);

        // new tab width of each tab
        qreal tabWidth;
        const bool keepWidth = keepTabWidth && ceil(currentTabWidth) * visibleTabCount < barWidth;
        if (keepWidth) {
            // only keep tab width if the tabs still fit
            tabWidth = currentTabWidth;
        } else {
            tabWidth = qMin(static_cast<qreal>(barWidth) / visibleTabCount, static_cast<qreal>(maximumTabWidth));
        }

        // if the last tab was closed through the close button, make sure the
        // close button of the new tab is again under the mouse
        if (keepWidth) {
            const int xPos = q->mapFromGlobal(QCursor::pos()).x();
            if (tabWidth * visibleTabCount < xPos) {
                tabWidth = qMin(static_cast<qreal>(tabWidth * (visibleTabCount + 1.0)) / visibleTabCount, static_cast<qreal>(maximumTabWidth));
            }
        }

        // now save the current tab width for future adaptation
        currentTabWidth = tabWidth;

        // now set the sizes
        const int w = ceil(tabWidth);
        const int h = q->height();
        for (int i = 0; i < maxi; ++i) {
            KateTabButton *tabButton = tabButtons.value(i);
            if (i >= maxCount) {
                tabButton->hide();
            } else {
                QRect endGeometry(i * tabWidth, 0, w, h);
                if (i > 0) {
                    // make sure the tab button starts exactly next to the previous tab (avoid rounding errors)
                    endGeometry.setLeft((i-1) * tabWidth + w);
                }

                if (animate) {
                    const QRect startGeometry = tabButton->isVisible() ? tabButton->geometry()
                    : QRect(i * tabWidth, 0, 0, h);
                    tabButton->setAnimatedGeometry(startGeometry, endGeometry);
                } else {
                    // two times endGeometry. Takes care of stopping a running animation
                    tabButton->setAnimatedGeometry(endGeometry, endGeometry);
                }
                tabButton->show();
            }
        }
    }
};

/**
 * Creates a new tab bar with the given \a parent.
 */
KateTabBar::KateTabBar(QWidget *parent)
    : QWidget(parent)
    , d(new KateTabBarPrivate())
{
    d->q = this;
    d->minimumTabWidth = 150;
    d->maximumTabWidth = 350;
    d->currentTabWidth = 350;
    d->keepTabWidth = false;

    d->isActive = false;

    d->activeButton = nullptr;

    d->nextID = 0;

    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    setAcceptDrops(true);
}

/**
 * Destroys the tab bar.
 */
KateTabBar::~KateTabBar()
{
    delete d;
}

void KateTabBar::setActive(bool active)
{
    if (active != d->isActive) {
        d->isActive = active;
        update();
    }
}

bool KateTabBar::isActive() const
{
    return d->isActive;
}

int KateTabBar::addTab(const QString &text)
{
    return insertTab(d->tabButtons.size(), text);
}

int KateTabBar::insertTab(int position, const QString & text)
{
    Q_ASSERT(position <= d->tabButtons.size());

    // -1 is append
    if (position < 0) {
        position = d->tabButtons.size();
    }

    KateTabButton *tabButton = new KateTabButton(text, this);

    d->tabButtons.insert(position, tabButton);
    d->idToTab[d->nextID] = tabButton;
    connect(tabButton, &KateTabButton::activated, this, &KateTabBar::tabButtonActivated);
    connect(tabButton, &KateTabButton::closeRequest, this, &KateTabBar::tabButtonCloseRequest);

    // abort potential keeping of width
    d->keepTabWidth = false;

    d->updateButtonPositions(true);

    return d->nextID++;
}

int KateTabBar::currentTab() const
{
    return d->idToTab.key(d->activeButton, -1);
}

void KateTabBar::setCurrentTab(int id)
{
    Q_ASSERT(d->idToTab.contains(id));

    KateTabButton *tabButton = d->idToTab.value(id, nullptr);
    if (d->activeButton == tabButton) {
        return;
    }

    if (d->activeButton) {
        d->activeButton->setChecked(false);
    }

    d->activeButton = tabButton;
    if (d->activeButton) {
        d->activeButton->setChecked(true);
    }
}

int KateTabBar::prevTab() const
{
    const int curId = currentTab();

    if (curId >= 0) {
        KateTabButton *tabButton = d->idToTab.value(curId, nullptr);
        const int index = d->tabButtons.indexOf(tabButton);
        Q_ASSERT(index >= 0);

        if (index > 0) {
            return d->idToTab.key(d->tabButtons[index - 1], -1);
        } else if (count() > 1) {
            // cycle through tabbar
            return d->idToTab.key(d->tabButtons.last(), -1);
        }
    }

    return -1;
}

int KateTabBar::nextTab() const
{
    const int curId = currentTab();

    if (curId >= 0) {
        KateTabButton *tabButton = d->idToTab.value(curId, nullptr);
        const int index = d->tabButtons.indexOf(tabButton);
        Q_ASSERT(index >= 0);

        if (index < d->tabButtons.size() - 1) {
            return d->idToTab.key(d->tabButtons[index + 1], -1);
        } else if (count() > 1) {
            // cycle through tabbar
            return d->idToTab.key(d->tabButtons.first(), -1);
        }
    }

    return -1;
}

int KateTabBar::removeTab(int id)
{
    Q_ASSERT(d->idToTab.contains(id));

    KateTabButton *tabButton = d->idToTab.value(id, nullptr);

    if (tabButton == d->activeButton) {
        d->activeButton = Q_NULLPTR;
    }

    const int position = d->tabButtons.indexOf(tabButton);

    if (position != -1) {
        d->idToTab.remove(id);
        d->tabButtons.removeAt(position);
    }

    if (tabButton) {
        // delete the button with deleteLater() because the button itself might
        // have send a close-request. So the app-execution is still in the
        // button, a delete tabButton; would lead to a crash.
        tabButton->hide();
        tabButton->deleteLater();
    }

    d->updateButtonPositions(true);

    return position;
}

bool KateTabBar::containsTab(int id) const
{
    return d->idToTab.contains(id);
}

void KateTabBar::setTabText(int id, const QString &text)
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        tabButton->setText(text);
    }
}

QString KateTabBar::tabText(int id) const
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        return tabButton->text();
    }
    return QString();
}

void KateTabBar::setTabToolTip(int id, const QString &tip)
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        tabButton->setToolTip(tip);
    }
}

QString KateTabBar::tabToolTip(int id) const
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        return tabButton->toolTip();
    }
    return QString();
}

void KateTabBar::setTabUrl(int id, const QUrl &url)
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        tabButton->setUrl(url);
    }
}

QUrl KateTabBar::tabUrl(int id) const
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        return tabButton->url();
    }
    return QUrl();
}

void KateTabBar::setTabIcon(int id, const QIcon &icon)
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        tabButton->setIcon(icon);
    }
}

QIcon KateTabBar::tabIcon(int id) const
{
    Q_ASSERT(d->idToTab.contains(id));
    KateTabButton * tabButton = d->idToTab.value(id, nullptr);
    if (tabButton) {
        return tabButton->icon();
    }
    return QIcon();
}

int KateTabBar::count() const
{
    return d->tabButtons.count();
}

void KateTabBar::tabButtonActivated(KateTabButton *tabButton)
{
    if (!tabButton) {
        return;
    }

    if (tabButton == d->activeButton) {
        // make sure we are the currently active view space
        if (! isActive()) {
            emit activateViewSpaceRequested();
        }
        return;
    }

    if (d->activeButton) {
        d->activeButton->setChecked(false);
    }

    d->activeButton = tabButton;
    d->activeButton->setChecked(true);

    const int id = d->idToTab.key(d->activeButton, -1);
    Q_ASSERT(id >= 0);
    if (id >= 0) {
        emit currentChanged(id);
    }
}

void KateTabBar::tabButtonCloseRequest(KateTabButton *tabButton)
{
    // keep width
    if (underMouse()) {
        d->keepTabWidth = true;
    }

    const int id = d->idToTab.key(tabButton, -1);
    Q_ASSERT(id >= 0);
    if (id >= 0) {
        emit closeTabRequested(id);
    }
}

void KateTabBar::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event)

    // fix button positions
    if (!d->keepTabWidth || event->size().width() < event->oldSize().width()) {
        d->updateButtonPositions();
    }

    const int tabDiff = maxTabCount() - d->tabButtons.size();
    if (tabDiff > 0) {
        emit moreTabsRequested(tabDiff);
    } else if (tabDiff < 0) {
        emit lessTabsRequested(-tabDiff);
    }
}

int KateTabBar::maxTabCount() const
{
    return qMax(1, width() / d->minimumTabWidth);
}

void KateTabBar::mouseDoubleClickEvent(QMouseEvent *event)
{
    event->accept();
    emit newTabRequested();
}

void KateTabBar::mousePressEvent(QMouseEvent *event)
{
    if (! isActive()) {
        emit activateViewSpaceRequested();
    }
    QWidget::mousePressEvent(event);
}

void KateTabBar::leaveEvent(QEvent *event) 
{
    if (d->keepTabWidth) {
        d->keepTabWidth = false;
        d->updateButtonPositions(true);
    }

    QWidget::leaveEvent(event);
}

void KateTabBar::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    const int buttonCount = d->tabButtons.size();
    if (buttonCount < 1) {
        return;
    }

    // draw separators
    QStyleOption option;
    option.initFrom(d->tabButtons[0]);
    option.state |= QStyle::State_Horizontal;
    const int w = style()->pixelMetric(QStyle::PM_ToolBarSeparatorExtent, nullptr, this);
    const int offset = w / 2;
    option.rect.setWidth(w);
    option.rect.moveTop(0);

    QPainter painter(this);

    // first separator
    option.rect.moveLeft(d->tabButtons[0]->geometry().left() - offset);
    style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &option, &painter);

    // all other separators
    for (int i = 0; i < buttonCount; ++i) {
        option.rect.moveLeft(d->tabButtons[i]->geometry().right() - offset);
        style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &option, &painter);
    }
}

void KateTabBar::contextMenuEvent(QContextMenuEvent *ev)
{
    int id = -1;
    foreach (KateTabButton * button, d->tabButtons) {
        if (button->rect().contains(button->mapFromGlobal(ev->globalPos()))) {
            id = d->idToTab.key(button, -1);
            Q_ASSERT(id >= 0);
            break;
        }
    }

    if (id >= 0) {
        emit contextMenuRequest(id, ev->globalPos());
    }
}

void KateTabBar::wheelEvent(QWheelEvent * event)
{
    event->accept();

    // cycle through the tabs
    const int delta = event->angleDelta().x() + event->angleDelta().y();
    const int id = (delta > 0) ? prevTab() : nextTab();
    if (id >= 0) {
        Q_ASSERT(d->idToTab.contains(id));
        KateTabButton *tabButton = d->idToTab.value(id, nullptr);
        if (tabButton) {
            tabButtonActivated(tabButton);
        }
    }
}

void KateTabBar::dragEnterEvent(QDragEnterEvent *event)
{
    const bool sameApplication = event->source() != nullptr;
    if (sameApplication && event->mimeData()->hasFormat(QStringLiteral("application/x-dndkatetabbutton"))) {
        if (event->source()->parent() == this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            // possibly dragged from another tabbar (not yet implemented)
            event->ignore();
        }
    } else {
        event->ignore();
    }
}

void KateTabBar::dragMoveEvent(QDragMoveEvent *event)
{
    // first of all, make sure the dragged button is from this tabbar
    auto button = qobject_cast<KateTabButton *>(event->source());
    if (!button) {
        event->ignore();
        return;
    }

    // save old tab position
    const int oldButtonIndex = d->tabButtons.indexOf(button);
    d->tabButtons.removeAt(oldButtonIndex);

    // find new position
    const qreal currentPos = event->pos().x();
    int index = d->tabButtons.size();
    for (int i = 0; i < d->tabButtons.size(); ++i) {
        auto tab = d->tabButtons[i];
        if (tab->geometry().center().x() > currentPos) {
            index = i;
            break;
        }
    }
    d->tabButtons.insert(index, button);

    // trigger rearrange if required
    if (oldButtonIndex != index) {
        d->updateButtonPositions(true);
    }

    event->accept();
}

void KateTabBar::dropEvent(QDropEvent *event)
{
    // no action required
    event->acceptProposedAction();
}