Debian Codegraph @

kysdk-qtwidgets/src/kcustomtabbar.cpp

raw
1 /*
2 * libkysdk-qtwidgets's Library
3 *
4 * Copyright (C) 2023, KylinSoft Co., Ltd.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this library. If not, see <https://www.gnu.org/licenses/>.
18 *
19 * Authors: Zhenyu Wang <[email protected]>
20 *
21 */
22
23 // #include "gui_g.h"
24
25 // #include <QtWidgets/private/qtwidgetsglobal_p.h>
26 #include "kcustomtabbar.h"
27 // #include "private/qwidget_p.h"
28
29 #include <QDebug>
30 #include <QIcon>
31 #include <QToolButton>
32 // #if QT_CONFIG(animation)
33 #include <QVariantAnimation>
34 // #endif
35
36 #include <QStyleOption>
37
38 // #include "private/qlayoutengine_p.h"
39 // #if QT_CONFIG(itemviews)
40 // #include "qabstractitemdelegate.h"
41 // #endif
42
43 #include <QAbstractButton>
44 #include <QApplication>
45 #include <QBitmap>
46 #include <QCursor>
47 #include <QEvent>
48 #include <QPainter>
49 #include <QStyle>
50 #include <QStylePainter>
51 // #include <QCustomLayoutStruct>
52 #include <QAbstractItemDelegate>
53
54 // #if QT_CONFIG(tabwidget)
55 #include <QTabWidget>
56 // #endif
57 #include <QToolTip>
58 // #if QT_CONFIG(whatsthis)
59 #include <QWhatsThis>
60 // #endif
61 // #ifndef QT_NO_ACCESSIBILITY
62 #include <QAccessible>
63 // #endif
64 // #ifdef Q_OS_OSX
65 // #include <qpa/qplatformnativeinterface.h>
66 // #endif
67 #include <QDebug>
68 // #include "qdebug.h"
69 // #include "private/KCustomTabBar_p.h"
70
71 // #if 0 // Used to be included in Qt4 for Q_WS_MAC
72 // #include <private/qt_mac_p.h>
73 // #include <private/qt_cocoa_helpers_mac_p.h>
74 // #endif
75
76 #define ANIMATION_DURATION 250
77 typedef qint64 Fixed64;
78 static inline Fixed64 toFixed(int i)
79 {
80 return (Fixed64)i * 256;
81 }
82 static inline int fRound(Fixed64 i)
83 {
84 return (i % 256 < 128) ? i / 256 : 1 + i / 256;
85 }
86 struct QCustomLayoutStruct
87 {
88 inline void init(int stretchFactor = 0, int minSize = 0)
89 {
90 stretch = stretchFactor;
91 minimumSize = sizeHint = minSize;
92 maximumSize = QLAYOUTSIZE_MAX;
93 expansive = false;
94 empty = true;
95 spacing = 0;
96 }
97
98 int smartSizeHint()
99 {
100 return (stretch > 0) ? minimumSize : sizeHint;
101 }
102 int effectiveSpacer(int uniformSpacer) const
103 {
104 Q_ASSERT(uniformSpacer >= 0 || spacing >= 0);
105 return (uniformSpacer >= 0) ? uniformSpacer : spacing;
106 }
107
108 // parameters
109 int stretch;
110 int sizeHint;
111 int maximumSize;
112 int minimumSize;
113 int spacing;
114 bool expansive;
115 bool empty;
116
117 // temporary storage
118 bool done;
119
120 // result
121 int pos;
122 int size;
123 };
124
125 class Q_DECL_HIDDEN KCustomMovableTabWidget : public QWidget
126 {
127 public:
128 explicit KCustomMovableTabWidget(QWidget *parent = nullptr);
129 void setPixmap(const QPixmap &pixmap);
130
131 protected:
132 void paintEvent(QPaintEvent *e) override;
133
134 private:
135 QPixmap m_pixmap;
136 };
137
138 class Q_DECL_HIDDEN KCustomTabBarPrivate
139 {
140 Q_DECLARE_PUBLIC(KCustomTabBar)
141 public:
142 KCustomTabBarPrivate(KCustomTabBar *parent);
143 Q_WIDGETS_EXPORT void qGeomCalc(QVector<QCustomLayoutStruct> &chain, int start, int count,
144 int pos, int space, int spacer = -1);
145
146 int currentIndex;
147 int pressedIndex;
148 KCustomTabBar::Shape shape;
149 bool layoutDirty;
150 bool drawBase;
151 int scrollOffset;
152
153 struct Tab
154 {
155 inline Tab(const QIcon &ico, const QString &txt)
156 : enabled(true)
157 , shortcutId(0)
158 , text(txt)
159 , icon(ico)
160 , leftWidget(0)
161 , rightWidget(0)
162 , lastTab(-1)
163 , dragOffset(0)
164 #if QT_CONFIG(animation)
165 , animation(0)
166 #endif // animation
167 {
168 }
169 bool operator==(const Tab &other) const
170 {
171 return &other == this;
172 }
173 bool enabled;
174 int shortcutId;
175 QString text;
176 #ifndef QT_NO_TOOLTIP
177 QString toolTip;
178 #endif
179 #if QT_CONFIG(whatsthis)
180 QString whatsThis;
181 #endif
182 QIcon icon;
183 QRect rect;
184 QRect minRect;
185 QRect maxRect;
186
187 QColor textColor;
188 QVariant data;
189 QWidget *leftWidget;
190 QWidget *rightWidget;
191 int lastTab;
192 int dragOffset;
193 #ifndef QT_NO_ACCESSIBILITY
194 QString accessibleName;
195 #endif
196
197 #if QT_CONFIG(animation)
198 ~Tab()
199 {
200 delete animation;
201 }
202 struct TabBarAnimation : public QVariantAnimation
203 {
204 TabBarAnimation(Tab *t, KCustomTabBarPrivate *_priv)
205 : tab(t)
206 , priv(_priv)
207 {
208 setEasingCurve(QEasingCurve::InOutQuad);
209 }
210
211 void updateCurrentValue(const QVariant &current) override;
212
213 void updateState(State newState, State) override;
214
215 private:
216 // these are needed for the callbacks
217 Tab *tab;
218 KCustomTabBarPrivate *priv;
219 } *animation;
220
221 void startAnimation(KCustomTabBarPrivate *priv, int duration)
222 {
223 if (!priv->isAnimated()) {
224 priv->moveTabFinished(priv->tabList.indexOf(*this));
225 return;
226 }
227 if (!animation)
228 animation = new TabBarAnimation(this, priv);
229 animation->setStartValue(dragOffset);
230 animation->setEndValue(0);
231 animation->setDuration(duration);
232 animation->start();
233 }
234 #else
235 void startAnimation(KCustomTabBarPrivate *priv, int duration)
236 {
237 Q_UNUSED(duration);
238 priv->moveTabFinished(priv->tabList.indexOf(*this));
239 }
240 #endif // animation
241 };
242 QList<Tab> tabList;
243 mutable QHash<QString, QSize> textSizes;
244
245 int calculateNewPosition(int from, int to, int index) const;
246 void slide(int from, int to);
247 void init();
248
249 Tab *at(int index);
250 const Tab *at(int index) const;
251
252 int indexAtPos(const QPoint &p) const;
253
254 inline bool isAnimated() const
255 {
256 Q_Q(const KCustomTabBar);
257 return q->style()->styleHint(QStyle::SH_Widget_Animation_Duration, 0, q) > 0;
258 }
259 inline bool validIndex(int index) const
260 {
261 return index >= 0 && index < tabList.count();
262 }
263 void setCurrentNextEnabledIndex(int offset);
264
265 QToolButton *rightB; // right or bottom
266 QToolButton *leftB; // left or top
267
268 void moveTab(int index, int offset);
269 void moveTabFinished(int index);
270 QRect hoverRect;
271 int hoverIndex;
272
273 void refresh();
274 void layoutTabs();
275 void layoutWidgets(int start = 0);
276 void layoutTab(int index);
277 void updateMacBorderMetrics();
278 bool isTabInMacUnifiedToolbarArea() const;
279 void setupMovableTab();
280 void autoHideTabs();
281 QRect normalizedScrollRect(int index = -1);
282 int hoveredTabIndex() const;
283
284 void initBasicStyleOption(QStyleOptionTab *option, int tabIndex) const;
285
286 void makeVisible(int index);
287 QSize iconSize;
288 Qt::TextElideMode elideMode;
289 bool elideModeSetByUser;
290 bool useScrollButtons;
291 bool useScrollButtonsSetByUser;
292
293 bool expanding;
294 bool closeButtonOnTabs;
295 KCustomTabBar::SelectionBehavior selectionBehaviorOnRemove;
296
297 QPoint dragStartPosition;
298 bool paintWithOffsets;
299 bool movable;
300 bool dragInProgress;
301 bool documentMode;
302 bool autoHide;
303 bool changeCurrentOnDrag;
304
305 int switchTabCurrentIndex;
306 int switchTabTimerId;
307
308 KCustomMovableTabWidget *movingTab;
309
310 // shared by tabwidget and KCustomTabBar
311 static void initStyleBaseOption(QStyleOptionTabBarBase *optTabBase, KCustomTabBar *tabbar, QSize size)
312 {
313 QStyleOptionTab tabOverlap;
314 tabOverlap.shape = static_cast<const QTabBar::Shape>(tabbar->shape());
315 int overlap = tabbar->style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, &tabOverlap, tabbar);
316 QWidget *theParent = tabbar->parentWidget();
317 optTabBase->initFrom(tabbar);
318 optTabBase->shape = static_cast<const QTabBar::Shape>(tabbar->shape());
319 optTabBase->documentMode = tabbar->documentMode();
320 if (theParent && overlap > 0) {
321 QRect rect;
322 switch (tabOverlap.shape) {
323 case KCustomTabBar::RoundedNorth:
324 case KCustomTabBar::TriangularNorth:
325 rect.setRect(0, size.height() - overlap, size.width(), overlap);
326 break;
327 case KCustomTabBar::RoundedSouth:
328 case KCustomTabBar::TriangularSouth:
329 rect.setRect(0, 0, size.width(), overlap);
330 break;
331 case KCustomTabBar::RoundedEast:
332 case KCustomTabBar::TriangularEast:
333 rect.setRect(0, 0, overlap, size.height());
334 break;
335 case KCustomTabBar::RoundedWest:
336 case KCustomTabBar::TriangularWest:
337 rect.setRect(size.width() - overlap, 0, overlap, size.height());
338 break;
339 }
340 optTabBase->rect = rect;
341 }
342 }
343
344 void killSwitchTabTimer();
345
346 private:
347 KCustomTabBar *const q_ptr;
348 };
349
350 namespace
351 {
352 class Q_DECL_HIDDEN CloseButton : public QAbstractButton
353 {
354 Q_OBJECT
355
356 public:
357 explicit CloseButton(QWidget *parent = 0);
358
359 QSize sizeHint() const override;
360 QSize minimumSizeHint() const override;
361 void enterEvent(QEnterEvent *event) override;
362 void leaveEvent(QEvent *event) override;
363 void paintEvent(QPaintEvent *event) override;
364 };
365 }
366
367 KCustomMovableTabWidget::KCustomMovableTabWidget(QWidget *parent)
368 : QWidget(parent)
369 {
370 }
371
372 void KCustomMovableTabWidget::setPixmap(const QPixmap &pixmap)
373 {
374 m_pixmap = pixmap;
375 update();
376 }
377
378 void KCustomMovableTabWidget::paintEvent(QPaintEvent *e)
379 {
380 Q_UNUSED(e);
381 QPainter p(this);
382 p.drawPixmap(0, 0, m_pixmap);
383 }
384
385 inline static bool verticalTabs(KCustomTabBar::Shape shape)
386 {
387 return shape == KCustomTabBar::RoundedWest
388 || shape == KCustomTabBar::RoundedEast
389 || shape == KCustomTabBar::TriangularWest
390 || shape == KCustomTabBar::TriangularEast;
391 }
392
393 void KCustomTabBarPrivate::updateMacBorderMetrics()
394 {
395 #if defined(Q_OS_OSX)
396 Q_Q(KCustomTabBar);
397 // Extend the unified title and toolbar area to cover the tab bar iff
398 // 1) the tab bar is in document mode
399 // 2) the tab bar is directly below an "unified" area.
400 // The extending itself is done in the Cocoa platform plugin and Mac style,
401 // this function registers geometry and visibility state for the tab bar.
402
403 // Calculate geometry
404 int upper, lower;
405 if (documentMode) {
406 QPoint windowPos = q->mapTo(q->window(), QPoint(0, 0));
407 upper = windowPos.y();
408 int tabStripHeight = q->tabSizeHint(0).height();
409 int pixelTweak = -3;
410 lower = upper + tabStripHeight + pixelTweak;
411 } else {
412 upper = 0;
413 lower = 0;
414 }
415
416 QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
417 quintptr identifier = reinterpret_cast<quintptr>(q);
418
419 // Set geometry
420 QPlatformNativeInterface::NativeResourceForIntegrationFunction function =
421 nativeInterface->nativeResourceFunctionForIntegration("registerContentBorderArea");
422 if (!function)
423 return; // Not Cocoa platform plugin.
424 typedef void (*RegisterContentBorderAreaFunction)(QWindow *window, quintptr identifier, int upper, int lower);
425 (reinterpret_cast<RegisterContentBorderAreaFunction>(function))(q->window()->windowHandle(), identifier, upper, lower);
426
427 // Set visibility state
428 function = nativeInterface->nativeResourceFunctionForIntegration("setContentBorderAreaEnabled");
429 if (!function)
430 return;
431 typedef void (*SetContentBorderAreaEnabledFunction)(QWindow *window, quintptr identifier, bool enable);
432 (reinterpret_cast<SetContentBorderAreaEnabledFunction>(function))(q->window()->windowHandle(), identifier, q->isVisible());
433 #endif
434 }
435
436 /*!
437 \internal
438 This is basically KCustomTabBar::initStyleOption() but
439 without the expensive QFontMetrics::elidedText() call.
440 */
441
442 void KCustomTabBarPrivate::initBasicStyleOption(QStyleOptionTab *option, int tabIndex) const
443 {
444 Q_Q(const KCustomTabBar);
445 const int totalTabs = tabList.size();
446
447 if (!option || (tabIndex < 0 || tabIndex >= totalTabs))
448 return;
449
450 const KCustomTabBarPrivate::Tab &tab = tabList.at(tabIndex);
451 option->initFrom(q);
452 option->state &= ~(QStyle::State_HasFocus | QStyle::State_MouseOver);
453 option->rect = q->tabRect(tabIndex);
454 const bool isCurrent = tabIndex == currentIndex;
455 option->row = 0;
456 if (tabIndex == pressedIndex)
457 option->state |= QStyle::State_Sunken;
458 if (isCurrent)
459 option->state |= QStyle::State_Selected;
460 if (isCurrent && q->hasFocus())
461 option->state |= QStyle::State_HasFocus;
462 if (!tab.enabled)
463 option->state &= ~QStyle::State_Enabled;
464 if (q->isActiveWindow())
465 option->state |= QStyle::State_Active;
466 if (!dragInProgress && option->rect == hoverRect)
467 option->state |= QStyle::State_MouseOver;
468 option->shape = static_cast<const QTabBar::Shape>(shape);
469 option->text = tab.text;
470
471 if (tab.textColor.isValid())
472 option->palette.setColor(q->foregroundRole(), tab.textColor);
473 option->icon = tab.icon;
474 option->iconSize = q->iconSize(); // Will get the default value then.
475
476 option->leftButtonSize = tab.leftWidget ? tab.leftWidget->size() : QSize();
477 option->rightButtonSize = tab.rightWidget ? tab.rightWidget->size() : QSize();
478 option->documentMode = documentMode;
479
480 if (tabIndex > 0 && tabIndex - 1 == currentIndex)
481 option->selectedPosition = QStyleOptionTab::PreviousIsSelected;
482 else if (tabIndex + 1 < totalTabs && tabIndex + 1 == currentIndex)
483 option->selectedPosition = QStyleOptionTab::NextIsSelected;
484 else
485 option->selectedPosition = QStyleOptionTab::NotAdjacent;
486
487 const bool paintBeginning = (tabIndex == 0) || (dragInProgress && tabIndex == pressedIndex + 1);
488 const bool paintEnd = (tabIndex == totalTabs - 1) || (dragInProgress && tabIndex == pressedIndex - 1);
489 if (paintBeginning) {
490 if (paintEnd)
491 option->position = QStyleOptionTab::OnlyOneTab;
492 else
493 option->position = QStyleOptionTab::Beginning;
494 } else if (paintEnd) {
495 option->position = QStyleOptionTab::End;
496 } else {
497 option->position = QStyleOptionTab::Middle;
498 }
499
500 #if QT_CONFIG(tabwidget)
501 if (const QTabWidget *tw = qobject_cast<const QTabWidget *>(q->parentWidget())) {
502 option->features |= QStyleOptionTab::HasFrame;
503 if (tw->cornerWidget(Qt::TopLeftCorner) || tw->cornerWidget(Qt::BottomLeftCorner))
504 option->cornerWidgets |= QStyleOptionTab::LeftCornerWidget;
505 if (tw->cornerWidget(Qt::TopRightCorner) || tw->cornerWidget(Qt::BottomRightCorner))
506 option->cornerWidgets |= QStyleOptionTab::RightCornerWidget;
507 }
508 #endif
509 }
510
511 /*!
512 Initialize \a option with the values from the tab at \a tabIndex. This method
513 is useful for subclasses when they need a QStyleOptionTab,
514 but don't want to fill in all the information themselves.
515
516 \sa QStyleOption::initFrom(), QTabWidget::initStyleOption()
517 */
518 void KCustomTabBar::initStyleOption(QStyleOptionTab *option, int tabIndex) const
519 {
520 Q_D(const KCustomTabBar);
521 d->initBasicStyleOption(option, tabIndex);
522
523 QRect textRect = style()->subElementRect(QStyle::SE_TabBarTabText, option, this);
524
525 option->text = fontMetrics().elidedText(option->text, d->elideMode, textRect.width(),
526 Qt::TextShowMnemonic);
527 }
528
529 void KCustomTabBarPrivate::init()
530 {
531 Q_Q(KCustomTabBar);
532 leftB = new QToolButton(q);
533 leftB->setAutoRepeat(true);
534 // QObject::connect(leftB, SIGNAL(clicked()), q, SLOT(scrollTabs()));
535 QObject::connect(leftB, &QToolButton::clicked, q, [=] {
536 q->leftScrollTabs();
537 });
538 leftB->hide();
539 rightB = new QToolButton(q);
540 rightB->setAutoRepeat(true);
541 // QObject::connect(rightB, SIGNAL(clicked()), q, SLOT(scrollTabs()));
542 QObject::connect(rightB, &QToolButton::clicked, q, [=] {
543 q->rightScrollTabs();
544 });
545 rightB->hide();
546 #ifdef QT_KEYPAD_NAVIGATION
547 if (QApplication::keypadNavigationEnabled()) {
548 leftB->setFocusPolicy(Qt::NoFocus);
549 rightB->setFocusPolicy(Qt::NoFocus);
550 q->setFocusPolicy(Qt::NoFocus);
551 } else
552 #endif
553 q->setFocusPolicy(Qt::TabFocus);
554
555 #ifndef QT_NO_ACCESSIBILITY
556 leftB->setAccessibleName(KCustomTabBar::tr("Scroll Left"));
557 rightB->setAccessibleName(KCustomTabBar::tr("Scroll Right"));
558 #endif
559 q->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
560 elideMode = Qt::TextElideMode(q->style()->styleHint(QStyle::SH_TabBar_ElideMode, 0, q));
561 useScrollButtons = !q->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, 0, q);
562 }
563
564 KCustomTabBarPrivate::Tab *KCustomTabBarPrivate::at(int index)
565 {
566 return validIndex(index) ? &tabList[index] : 0;
567 }
568
569 const KCustomTabBarPrivate::Tab *KCustomTabBarPrivate::at(int index) const
570 {
571 return validIndex(index) ? &tabList[index] : 0;
572 }
573
574 int KCustomTabBarPrivate::indexAtPos(const QPoint &p) const
575 {
576 Q_Q(const KCustomTabBar);
577 if (q->tabRect(currentIndex).contains(p))
578 return currentIndex;
579 for (int i = 0; i < tabList.count(); ++i)
580 if (tabList.at(i).enabled && q->tabRect(i).contains(p))
581 return i;
582 return -1;
583 }
584
585 void KCustomTabBarPrivate::layoutTabs()
586 {
587 Q_Q(KCustomTabBar);
588 layoutDirty = false;
589 QSize size = q->size();
590 int last, available;
591 int maxExtent;
592 int i;
593 bool vertTabs = verticalTabs(shape);
594 int tabChainIndex = 0;
595
596 Qt::Alignment tabAlignment = Qt::Alignment(q->style()->styleHint(QStyle::SH_TabBar_Alignment, 0, q));
597 QVector<QCustomLayoutStruct> tabChain(tabList.count() + 2);
598
599 // We put an empty item at the front and back and set its expansive attribute
600 // depending on tabAlignment and expanding.
601 tabChain[tabChainIndex].init();
602 tabChain[tabChainIndex].expansive = (!expanding)
603 && (tabAlignment != Qt::AlignLeft)
604 && (tabAlignment != Qt::AlignJustify);
605 tabChain[tabChainIndex].empty = true;
606 ++tabChainIndex;
607
608 // We now go through our list of tabs and set the minimum size and the size hint
609 // This will allow us to elide text if necessary. Since we don't set
610 // a maximum size, tabs will EXPAND to fill up the empty space.
611 // Since tab widget is rather *ahem* strict about keeping the geometry of the
612 // tab bar to its absolute minimum, this won't bleed through, but will show up
613 // if you use tab bar on its own (a.k.a. not a bug, but a feature).
614 // Update: if expanding is false, we DO set a maximum size to prevent the tabs
615 // being wider than necessary.
616 if (!vertTabs) {
617 int minx = 0;
618 int x = 0;
619 int maxHeight = 0;
620 for (i = 0; i < tabList.count(); ++i, ++tabChainIndex) {
621 QSize sz = q->tabSizeHint(i);
622 tabList[i].maxRect = QRect(x, 0, sz.width(), sz.height());
623 x += sz.width();
624 maxHeight = qMax(maxHeight, sz.height());
625 sz = q->minimumTabSizeHint(i);
626 tabList[i].minRect = QRect(minx, 0, sz.width(), sz.height());
627 minx += sz.width();
628 tabChain[tabChainIndex].init();
629 tabChain[tabChainIndex].sizeHint = tabList.at(i).maxRect.width();
630 tabChain[tabChainIndex].minimumSize = sz.width();
631 tabChain[tabChainIndex].empty = false;
632 tabChain[tabChainIndex].expansive = true;
633
634 if (!expanding)
635 tabChain[tabChainIndex].maximumSize = tabChain[tabChainIndex].sizeHint;
636 }
637
638 last = minx;
639 available = size.width();
640 maxExtent = maxHeight;
641 } else {
642 int miny = 0;
643 int y = 0;
644 int maxWidth = 0;
645 for (i = 0; i < tabList.count(); ++i, ++tabChainIndex) {
646 QSize sz = q->tabSizeHint(i);
647 tabList[i].maxRect = QRect(0, y, sz.width(), sz.height());
648 y += sz.height();
649 maxWidth = qMax(maxWidth, sz.width());
650 sz = q->minimumTabSizeHint(i);
651 tabList[i].minRect = QRect(0, miny, sz.width(), sz.height());
652 miny += sz.height();
653 tabChain[tabChainIndex].init();
654 tabChain[tabChainIndex].sizeHint = tabList.at(i).maxRect.height();
655 tabChain[tabChainIndex].minimumSize = sz.height();
656 tabChain[tabChainIndex].empty = false;
657 tabChain[tabChainIndex].expansive = true;
658
659 if (!expanding)
660 tabChain[tabChainIndex].maximumSize = tabChain[tabChainIndex].sizeHint;
661 }
662
663 last = miny;
664 available = size.height();
665 maxExtent = maxWidth;
666 }
667
668 // Mirror our front item.
669 tabChain[tabChainIndex].init();
670 tabChain[tabChainIndex].expansive = (!expanding)
671 && (tabAlignment != Qt::AlignRight)
672 && (tabAlignment != Qt::AlignJustify);
673 tabChain[tabChainIndex].empty = true;
674 Q_ASSERT(tabChainIndex == tabChain.count() - 1); // add an assert just to make sure.
675
676 // Do the calculation
677 qGeomCalc(tabChain, 0, tabChain.count(), 0, qMax(available, last), 0);
678
679 // Use the results
680 for (i = 0; i < tabList.count(); ++i) {
681 const QCustomLayoutStruct &lstruct = tabChain.at(i + 1);
682 if (!vertTabs)
683 tabList[i].rect.setRect(lstruct.pos, 0, lstruct.size, maxExtent);
684 else
685 tabList[i].rect.setRect(0, lstruct.pos, maxExtent, lstruct.size);
686 }
687
688 if (useScrollButtons && tabList.count() && last > available) {
689 const QRect scrollRect = normalizedScrollRect(0);
690 scrollOffset = -scrollRect.left();
691
692 Q_Q(KCustomTabBar);
693 QStyleOption opt;
694 opt.initFrom(q);
695 QRect scrollButtonLeftRect = q->style()->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, q);
696 QRect scrollButtonRightRect = q->style()->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, q);
697 int scrollButtonWidth = q->style()->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, &opt, q);
698
699 // Normally SE_TabBarScrollLeftButton should have the same width as PM_TabBarScrollButtonWidth.
700 // But if that is not the case, we set the actual button width to PM_TabBarScrollButtonWidth, and
701 // use the extra space from SE_TabBarScrollLeftButton as margins towards the tabs.
702 if (vertTabs) {
703 scrollButtonLeftRect.setHeight(scrollButtonWidth);
704 scrollButtonRightRect.setY(scrollButtonRightRect.bottom() + 1 - scrollButtonWidth);
705 scrollButtonRightRect.setHeight(scrollButtonWidth);
706 leftB->setArrowType(Qt::UpArrow);
707 rightB->setArrowType(Qt::DownArrow);
708 } else if (q->layoutDirection() == Qt::RightToLeft) {
709 scrollButtonRightRect.setWidth(scrollButtonWidth);
710 scrollButtonLeftRect.setX(scrollButtonLeftRect.right() + 1 - scrollButtonWidth);
711 scrollButtonLeftRect.setWidth(scrollButtonWidth);
712 leftB->setArrowType(Qt::RightArrow);
713 rightB->setArrowType(Qt::LeftArrow);
714 } else {
715 scrollButtonLeftRect.setWidth(scrollButtonWidth);
716 scrollButtonRightRect.setX(scrollButtonRightRect.right() + 1 - scrollButtonWidth);
717 scrollButtonRightRect.setWidth(scrollButtonWidth);
718 leftB->setArrowType(Qt::LeftArrow);
719 rightB->setArrowType(Qt::RightArrow);
720 }
721
722 leftB->setGeometry(scrollButtonLeftRect);
723 leftB->setEnabled(false);
724 leftB->show();
725
726 rightB->setGeometry(scrollButtonRightRect);
727 rightB->setEnabled(last - scrollOffset > scrollRect.x() + scrollRect.width());
728 rightB->show();
729 } else {
730 scrollOffset = 0;
731 rightB->hide();
732 leftB->hide();
733 }
734
735 layoutWidgets();
736 q->tabLayoutChange();
737 }
738
739 QRect KCustomTabBarPrivate::normalizedScrollRect(int index)
740 {
741 // "Normalized scroll rect" means return the free space on the tab bar
742 // that doesn't overlap with scroll buttons or tear indicators, and
743 // always return the rect as horizontal Qt::LeftToRight, even if the
744 // tab bar itself is in a different orientation.
745
746 Q_Q(KCustomTabBar);
747 QStyleOptionTab opt;
748 q->initStyleOption(&opt, currentIndex);
749 opt.rect = q->rect();
750
751 QRect scrollButtonLeftRect = q->style()->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, q);
752 QRect scrollButtonRightRect = q->style()->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, q);
753 QRect tearLeftRect = q->style()->subElementRect(QStyle::SE_TabBarTearIndicatorLeft, &opt, q);
754 QRect tearRightRect = q->style()->subElementRect(QStyle::SE_TabBarTearIndicatorRight, &opt, q);
755
756 if (verticalTabs(shape)) {
757 int topEdge, bottomEdge;
758 bool leftButtonIsOnTop = scrollButtonLeftRect.y() < q->height() / 2;
759 bool rightButtonIsOnTop = scrollButtonRightRect.y() < q->height() / 2;
760
761 if (leftButtonIsOnTop && rightButtonIsOnTop) {
762 topEdge = scrollButtonRightRect.bottom() + 1;
763 bottomEdge = q->height();
764 } else if (!leftButtonIsOnTop && !rightButtonIsOnTop) {
765 topEdge = 0;
766 bottomEdge = scrollButtonLeftRect.top();
767 } else {
768 topEdge = scrollButtonLeftRect.bottom() + 1;
769 bottomEdge = scrollButtonRightRect.top();
770 }
771
772 bool tearTopVisible = index != 0 && topEdge != -scrollOffset;
773 bool tearBottomVisible = index != tabList.size() - 1 && bottomEdge != tabList.constLast().rect.bottom() + 1 - scrollOffset;
774 if (tearTopVisible && !tearLeftRect.isNull())
775 topEdge = tearLeftRect.bottom() + 1;
776 if (tearBottomVisible && !tearRightRect.isNull())
777 bottomEdge = tearRightRect.top();
778
779 return QRect(topEdge, 0, bottomEdge - topEdge, q->height());
780 } else {
781 if (q->layoutDirection() == Qt::RightToLeft) {
782 scrollButtonLeftRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), scrollButtonLeftRect);
783 scrollButtonRightRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), scrollButtonRightRect);
784 tearLeftRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), tearLeftRect);
785 tearRightRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), tearRightRect);
786 }
787
788 int leftEdge, rightEdge;
789 bool leftButtonIsOnLeftSide = scrollButtonLeftRect.x() < q->width() / 2;
790 bool rightButtonIsOnLeftSide = scrollButtonRightRect.x() < q->width() / 2;
791
792 if (leftButtonIsOnLeftSide && rightButtonIsOnLeftSide) {
793 leftEdge = scrollButtonRightRect.right() + 1;
794 rightEdge = q->width();
795 } else if (!leftButtonIsOnLeftSide && !rightButtonIsOnLeftSide) {
796 leftEdge = 0;
797 rightEdge = scrollButtonLeftRect.left();
798 } else {
799 leftEdge = scrollButtonLeftRect.right() + 1;
800 rightEdge = scrollButtonRightRect.left();
801 }
802
803 bool tearLeftVisible = index != 0 && leftEdge != -scrollOffset;
804 bool tearRightVisible = index != tabList.size() - 1 && rightEdge != tabList.constLast().rect.right() + 1 - scrollOffset;
805 if (tearLeftVisible && !tearLeftRect.isNull())
806 leftEdge = tearLeftRect.right() + 1;
807 if (tearRightVisible && !tearRightRect.isNull())
808 rightEdge = tearRightRect.left();
809
810 return QRect(leftEdge, 0, rightEdge - leftEdge, q->height());
811 }
812 }
813
814 int KCustomTabBarPrivate::hoveredTabIndex() const
815 {
816 if (dragInProgress)
817 return currentIndex;
818 if (hoverIndex >= 0)
819 return hoverIndex;
820 return -1;
821 }
822
823 void KCustomTabBarPrivate::makeVisible(int index)
824 {
825 Q_Q(KCustomTabBar);
826 if (!validIndex(index) || leftB->isHidden())
827 return;
828
829 const QRect tabRect = tabList.at(index).rect;
830 const int oldScrollOffset = scrollOffset;
831 const bool horiz = !verticalTabs(shape);
832 const int tabStart = horiz ? tabRect.left() : tabRect.top();
833 const int tabEnd = horiz ? tabRect.right() : tabRect.bottom();
834 const int lastTabEnd = horiz ? tabList.constLast().rect.right() : tabList.constLast().rect.bottom();
835 const QRect scrollRect = normalizedScrollRect(index);
836 const int scrolledTabBarStart = qMax(1, scrollRect.left() + scrollOffset);
837 const int scrolledTabBarEnd = qMin(lastTabEnd - 1, scrollRect.right() + scrollOffset);
838
839 if (tabStart < scrolledTabBarStart) {
840 // Tab is outside on the left, so scroll left.
841 scrollOffset = tabStart - scrollRect.left();
842 } else if (tabEnd > scrolledTabBarEnd) {
843 // Tab is outside on the right, so scroll right.
844 scrollOffset = tabEnd - scrollRect.right();
845 }
846
847 leftB->setEnabled(scrollOffset > -scrollRect.left());
848 emit q->leftBStatus(scrollOffset > -scrollRect.left());
849 rightB->setEnabled(scrollOffset < lastTabEnd - scrollRect.right());
850 emit q->rightBStatus(scrollOffset < lastTabEnd - scrollRect.right());
851
852 if (oldScrollOffset != scrollOffset) {
853 q->update();
854 layoutWidgets();
855 }
856 }
857
858 void KCustomTabBarPrivate::killSwitchTabTimer()
859 {
860 Q_Q(KCustomTabBar);
861 if (switchTabTimerId) {
862 q->killTimer(switchTabTimerId);
863 switchTabTimerId = 0;
864 }
865 switchTabCurrentIndex = -1;
866 }
867
868 void KCustomTabBarPrivate::layoutTab(int index)
869 {
870 Q_Q(KCustomTabBar);
871 Q_ASSERT(index >= 0);
872
873 Tab &tab = tabList[index];
874 bool vertical = verticalTabs(shape);
875 if (!(tab.leftWidget || tab.rightWidget))
876 return;
877
878 QStyleOptionTab opt;
879 q->initStyleOption(&opt, index);
880 if (tab.leftWidget) {
881 QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabLeftButton, &opt, q);
882 QPoint p = rect.topLeft();
883 if ((index == pressedIndex) || paintWithOffsets) {
884 if (vertical)
885 p.setY(p.y() + tabList[index].dragOffset);
886 else
887 p.setX(p.x() + tabList[index].dragOffset);
888 }
889 tab.leftWidget->move(p);
890 }
891 if (tab.rightWidget) {
892 QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabRightButton, &opt, q);
893 QPoint p = rect.topLeft();
894 if ((index == pressedIndex) || paintWithOffsets) {
895 if (vertical)
896 p.setY(p.y() + tab.dragOffset);
897 else
898 p.setX(p.x() + tab.dragOffset);
899 }
900 tab.rightWidget->move(p);
901 }
902 }
903
904 void KCustomTabBarPrivate::layoutWidgets(int start)
905 {
906 Q_Q(KCustomTabBar);
907 for (int i = start; i < q->count(); ++i) {
908 layoutTab(i);
909 }
910 }
911
912 void KCustomTabBarPrivate::autoHideTabs()
913 {
914 Q_Q(KCustomTabBar);
915
916 if (autoHide)
917 q->setVisible(q->count() > 1);
918 }
919
920 void KCustomTabBar::closeTab()
921 {
922 Q_D(KCustomTabBar);
923 QObject *object = sender();
924 int tabToClose = -1;
925 KCustomTabBar::ButtonPosition closeSide = (KCustomTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, this);
926 for (int i = 0; i < d->tabList.count(); ++i) {
927 if (closeSide == KCustomTabBar::LeftSide) {
928 if (d->tabList.at(i).leftWidget == object) {
929 tabToClose = i;
930 break;
931 }
932 } else {
933 if (d->tabList.at(i).rightWidget == object) {
934 tabToClose = i;
935 break;
936 }
937 }
938 }
939 if (tabToClose != -1)
940 emit tabCloseRequested(tabToClose);
941 }
942
943 // void KCustomTabBar::scrollTabs()
944 //{
945
946 // if (sender1 == d->leftB) {
947
948 // } else if (sender1 == d->rightB) {
949
950 // }
951 //}
952
953 void KCustomTabBar::leftScrollTabs()
954 {
955 Q_D(KCustomTabBar);
956 // const QObject *sender1 = sender();
957
958 const bool horizontal = !verticalTabs(d->shape);
959 const QRect scrollRect = d->normalizedScrollRect();
960 int i = -1;
961 for (i = d->tabList.count() - 1; i >= 0; --i) {
962
963 int start = horizontal ? d->tabList.at(i).rect.left() : d->tabList.at(i).rect.top();
964 if (start < scrollRect.left() + d->scrollOffset) {
965 d->makeVisible(i);
966 return;
967 }
968 }
969 }
970
971 void KCustomTabBar::rightScrollTabs()
972 {
973 Q_D(KCustomTabBar);
974
975 // const QObject *sender1 = sender();
976 const bool horizontal = !verticalTabs(d->shape);
977 const QRect scrollRect = d->normalizedScrollRect();
978 int i = -1;
979 for (i = 0; i < d->tabList.count(); ++i) {
980
981 int end = horizontal ? d->tabList.at(i).rect.right() : d->tabList.at(i).rect.bottom();
982
983 if (end > scrollRect.right() + d->scrollOffset) {
984 d->makeVisible(i);
985 return;
986 }
987 }
988 }
989
990 void KCustomTabBarPrivate::refresh()
991 {
992 Q_Q(KCustomTabBar);
993
994 // be safe in case a subclass is also handling move with the tabs
995 if (pressedIndex != -1
996 && movable
997 && QApplication::mouseButtons() == Qt::NoButton) {
998 moveTabFinished(pressedIndex);
999 if (!validIndex(pressedIndex))
1000 pressedIndex = -1;
1001 }
1002
1003 if (!q->isVisible()) {
1004 layoutDirty = true;
1005 } else {
1006 layoutTabs();
1007 makeVisible(currentIndex);
1008 q->update();
1009 q->updateGeometry();
1010 }
1011 }
1012
1013 /*!
1014 Creates a new tab bar with the given \a parent.
1015 */
1016 KCustomTabBar::KCustomTabBar(QWidget *parent)
1017 : QWidget(parent)
1018 , d_ptr(new KCustomTabBarPrivate(this))
1019 {
1020 Q_D(KCustomTabBar);
1021 d->init();
1022 }
1023
1024 /*!
1025 Destroys the tab bar.
1026 */
1027 KCustomTabBar::~KCustomTabBar()
1028 {
1029 }
1030
1031 /*!
1032 \property KCustomTabBar::shape
1033 \brief the shape of the tabs in the tab bar
1034
1035 Possible values for this property are described by the Shape enum.
1036 */
1037
1038 KCustomTabBar::Shape KCustomTabBar::shape() const
1039 {
1040 Q_D(const KCustomTabBar);
1041 return d->shape;
1042 }
1043
1044 void KCustomTabBar::setShape(Shape shape)
1045 {
1046 Q_D(KCustomTabBar);
1047 if (d->shape == shape)
1048 return;
1049 d->shape = shape;
1050 d->refresh();
1051 }
1052
1053 /*!
1054 \property KCustomTabBar::drawBase
1055 \brief defines whether or not tab bar should draw its base.
1056
1057 If true then KCustomTabBar draws a base in relation to the styles overlab.
1058 Otherwise only the tabs are drawn.
1059
1060 \sa QStyle::pixelMetric(), QStyle::PM_TabBarBaseOverlap, QStyleOptionTabBarBase
1061 */
1062
1063 void KCustomTabBar::setDrawBase(bool drawBase)
1064 {
1065 Q_D(KCustomTabBar);
1066 if (d->drawBase == drawBase)
1067 return;
1068 d->drawBase = drawBase;
1069 update();
1070 }
1071
1072 bool KCustomTabBar::drawBase() const
1073 {
1074 Q_D(const KCustomTabBar);
1075 return d->drawBase;
1076 }
1077
1078 /*!
1079 Adds a new tab with text \a text. Returns the new
1080 tab's index.
1081 */
1082 int KCustomTabBar::addTab(const QString &text)
1083 {
1084 return insertTab(-1, text);
1085 }
1086
1087 /*!
1088 \overload
1089
1090 Adds a new tab with icon \a icon and text \a
1091 text. Returns the new tab's index.
1092 */
1093 int KCustomTabBar::addTab(const QIcon &icon, const QString &text)
1094 {
1095 return insertTab(-1, icon, text);
1096 }
1097
1098 /*!
1099 Inserts a new tab with text \a text at position \a index. If \a
1100 index is out of range, the new tab is appened. Returns the new
1101 tab's index.
1102 */
1103 int KCustomTabBar::insertTab(int index, const QString &text)
1104 {
1105 return insertTab(index, QIcon(), text);
1106 }
1107
1108 /*!\overload
1109
1110 Inserts a new tab with icon \a icon and text \a text at position
1111 \a index. If \a index is out of range, the new tab is
1112 appended. Returns the new tab's index.
1113
1114 If the KCustomTabBar was empty before this function is called, the inserted tab
1115 becomes the current tab.
1116
1117 Inserting a new tab at an index less than or equal to the current index
1118 will increment the current index, but keep the current tab.
1119 */
1120 int KCustomTabBar::insertTab(int index, const QIcon &icon, const QString &text)
1121 {
1122 Q_D(KCustomTabBar);
1123 if (!d->validIndex(index)) {
1124 index = d->tabList.count();
1125 d->tabList.append(KCustomTabBarPrivate::Tab(icon, text));
1126 } else {
1127 d->tabList.insert(index, KCustomTabBarPrivate::Tab(icon, text));
1128 }
1129 #ifndef QT_NO_SHORTCUT
1130 d->tabList[index].shortcutId = grabShortcut(QKeySequence::mnemonic(text));
1131 #endif
1132 d->refresh();
1133 if (d->tabList.count() == 1)
1134 setCurrentIndex(index);
1135 else if (index <= d->currentIndex)
1136 ++d->currentIndex;
1137
1138 if (d->closeButtonOnTabs) {
1139 QStyleOptionTab opt;
1140 initStyleOption(&opt, index);
1141 ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, this);
1142 QAbstractButton *closeButton = new CloseButton(this);
1143 // connect(closeButton, SIGNAL(clicked()), this, SLOT(_q_closeTab()));
1144 connect(closeButton, &QAbstractButton::clicked, this, [=] {
1145 closeTab();
1146 });
1147 setTabButton(index, closeSide, closeButton);
1148 }
1149
1150 for (int i = 0; i < d->tabList.count(); ++i) {
1151 if (d->tabList[i].lastTab >= index)
1152 ++d->tabList[i].lastTab;
1153 }
1154
1155 tabInserted(index);
1156 d->autoHideTabs();
1157
1158 return index;
1159 }
1160
1161 /*!
1162 Removes the tab at position \a index.
1163
1164 \sa SelectionBehavior
1165 */
1166 void KCustomTabBar::removeTab(int index)
1167 {
1168 Q_D(KCustomTabBar);
1169 if (d->validIndex(index)) {
1170 if (d->dragInProgress)
1171 d->moveTabFinished(d->pressedIndex);
1172
1173 #ifndef QT_NO_SHORTCUT
1174 releaseShortcut(d->tabList.at(index).shortcutId);
1175 #endif
1176 if (d->tabList[index].leftWidget) {
1177 d->tabList[index].leftWidget->hide();
1178 d->tabList[index].leftWidget->deleteLater();
1179 d->tabList[index].leftWidget = 0;
1180 }
1181 if (d->tabList[index].rightWidget) {
1182 d->tabList[index].rightWidget->hide();
1183 d->tabList[index].rightWidget->deleteLater();
1184 d->tabList[index].rightWidget = 0;
1185 }
1186
1187 int newIndex = d->tabList[index].lastTab;
1188 d->tabList.removeAt(index);
1189 for (int i = 0; i < d->tabList.count(); ++i) {
1190 if (d->tabList[i].lastTab == index)
1191 d->tabList[i].lastTab = -1;
1192 if (d->tabList[i].lastTab > index)
1193 --d->tabList[i].lastTab;
1194 }
1195 if (index == d->currentIndex) {
1196 // The current tab is going away, in order to make sure
1197 // we emit that "current has changed", we need to reset this
1198 // around.
1199 d->currentIndex = -1;
1200 if (d->tabList.size() > 0) {
1201 switch (d->selectionBehaviorOnRemove) {
1202 case SelectPreviousTab:
1203 if (newIndex > index)
1204 newIndex--;
1205 if (d->validIndex(newIndex))
1206 break;
1207 Q_FALLTHROUGH();
1208 case SelectRightTab:
1209 newIndex = index;
1210 if (newIndex >= d->tabList.size())
1211 newIndex = d->tabList.size() - 1;
1212 break;
1213 case SelectLeftTab:
1214 newIndex = index - 1;
1215 if (newIndex < 0)
1216 newIndex = 0;
1217 break;
1218 default:
1219 break;
1220 }
1221
1222 if (d->validIndex(newIndex)) {
1223 // don't loose newIndex's old through setCurrentIndex
1224 int bump = d->tabList[newIndex].lastTab;
1225 setCurrentIndex(newIndex);
1226 d->tabList[newIndex].lastTab = bump;
1227 }
1228 } else {
1229 emit currentChanged(-1);
1230 }
1231 } else if (index < d->currentIndex) {
1232 setCurrentIndex(d->currentIndex - 1);
1233 }
1234 d->refresh();
1235 d->autoHideTabs();
1236 if (!d->hoverRect.isEmpty()) {
1237 for (int i = 0; i < d->tabList.count(); ++i) {
1238 const QRect area = tabRect(i);
1239 if (area.contains(mapFromGlobal(QCursor::pos()))) {
1240 d->hoverIndex = i;
1241 d->hoverRect = area;
1242 break;
1243 }
1244 }
1245 update(d->hoverRect);
1246 }
1247 tabRemoved(index);
1248 }
1249 }
1250
1251 /*!
1252 Returns \c true if the tab at position \a index is enabled; otherwise
1253 returns \c false.
1254 */
1255 bool KCustomTabBar::isTabEnabled(int index) const
1256 {
1257 Q_D(const KCustomTabBar);
1258 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1259 return tab->enabled;
1260 return false;
1261 }
1262
1263 /*!
1264 If \a enabled is true then the tab at position \a index is
1265 enabled; otherwise the item at position \a index is disabled.
1266 */
1267 void KCustomTabBar::setTabEnabled(int index, bool enabled)
1268 {
1269 Q_D(KCustomTabBar);
1270 if (KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1271 tab->enabled = enabled;
1272 #ifndef QT_NO_SHORTCUT
1273 setShortcutEnabled(tab->shortcutId, enabled);
1274 #endif
1275 update();
1276 if (!enabled && index == d->currentIndex)
1277 setCurrentIndex(d->validIndex(index + 1) ? index + 1 : 0);
1278 else if (enabled && !d->validIndex(d->currentIndex))
1279 setCurrentIndex(index);
1280 }
1281 }
1282
1283 /*!
1284 Returns the text of the tab at position \a index, or an empty
1285 string if \a index is out of range.
1286 */
1287 QString KCustomTabBar::tabText(int index) const
1288 {
1289 Q_D(const KCustomTabBar);
1290 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1291 return tab->text;
1292 return QString();
1293 }
1294
1295 /*!
1296 Sets the text of the tab at position \a index to \a text.
1297 */
1298 void KCustomTabBar::setTabText(int index, const QString &text)
1299 {
1300 Q_D(KCustomTabBar);
1301 if (KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1302 d->textSizes.remove(tab->text);
1303 tab->text = text;
1304 #ifndef QT_NO_SHORTCUT
1305 releaseShortcut(tab->shortcutId);
1306 tab->shortcutId = grabShortcut(QKeySequence::mnemonic(text));
1307 setShortcutEnabled(tab->shortcutId, tab->enabled);
1308 #endif
1309 d->refresh();
1310 }
1311 }
1312
1313 void KCustomTabBar::setTabContent(int index, const QString &text)
1314 {
1315 Q_D(KCustomTabBar);
1316 if (KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1317 d->textSizes.remove(tab->text);
1318 tab->text = text;
1319 #ifndef QT_NO_SHORTCUT
1320 releaseShortcut(tab->shortcutId);
1321 tab->shortcutId = grabShortcut(QKeySequence::mnemonic(text));
1322 setShortcutEnabled(tab->shortcutId, tab->enabled);
1323 #endif
1324 }
1325 }
1326
1327 /*!
1328 Returns the text color of the tab with the given \a index, or a invalid
1329 color if \a index is out of range.
1330
1331 \sa setTabTextColor()
1332 */
1333 QColor KCustomTabBar::tabTextColor(int index) const
1334 {
1335 Q_D(const KCustomTabBar);
1336 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1337 return tab->textColor;
1338 return QColor();
1339 }
1340
1341 /*!
1342 Sets the color of the text in the tab with the given \a index to the specified \a color.
1343
1344 If an invalid color is specified, the tab will use the KCustomTabBar foreground role instead.
1345
1346 \sa tabTextColor()
1347 */
1348 void KCustomTabBar::setTabTextColor(int index, const QColor &color)
1349 {
1350 Q_D(KCustomTabBar);
1351 if (KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1352 tab->textColor = color;
1353 update(tabRect(index));
1354 }
1355 }
1356
1357 /*!
1358 Returns the icon of the tab at position \a index, or a null icon
1359 if \a index is out of range.
1360 */
1361 QIcon KCustomTabBar::tabIcon(int index) const
1362 {
1363 Q_D(const KCustomTabBar);
1364 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1365 return tab->icon;
1366 return QIcon();
1367 }
1368
1369 /*!
1370 Sets the icon of the tab at position \a index to \a icon.
1371 */
1372 void KCustomTabBar::setTabIcon(int index, const QIcon &icon)
1373 {
1374 Q_D(KCustomTabBar);
1375 if (KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1376 bool simpleIconChange = (!icon.isNull() && !tab->icon.isNull());
1377 tab->icon = icon;
1378 if (simpleIconChange)
1379 update(tabRect(index));
1380 else
1381 d->refresh();
1382 }
1383 }
1384
1385 #ifndef QT_NO_TOOLTIP
1386 /*!
1387 Sets the tool tip of the tab at position \a index to \a tip.
1388 */
1389 void KCustomTabBar::setTabToolTip(int index, const QString &tip)
1390 {
1391 Q_D(KCustomTabBar);
1392 if (KCustomTabBarPrivate::Tab *tab = d->at(index))
1393 tab->toolTip = tip;
1394 }
1395
1396 /*!
1397 Returns the tool tip of the tab at position \a index, or an empty
1398 string if \a index is out of range.
1399 */
1400 QString KCustomTabBar::tabToolTip(int index) const
1401 {
1402 Q_D(const KCustomTabBar);
1403 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1404 return tab->toolTip;
1405 return QString();
1406 }
1407 #endif // QT_NO_TOOLTIP
1408
1409 #if QT_CONFIG(whatsthis)
1410 /*!
1411 \since 4.1
1412
1413 Sets the What's This help text of the tab at position \a index
1414 to \a text.
1415 */
1416 void KCustomTabBar::setTabWhatsThis(int index, const QString &text)
1417 {
1418 Q_D(KCustomTabBar);
1419 if (KCustomTabBarPrivate::Tab *tab = d->at(index))
1420 tab->whatsThis = text;
1421 }
1422
1423 /*!
1424 \since 4.1
1425
1426 Returns the What's This help text of the tab at position \a index,
1427 or an empty string if \a index is out of range.
1428 */
1429 QString KCustomTabBar::tabWhatsThis(int index) const
1430 {
1431 Q_D(const KCustomTabBar);
1432 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1433 return tab->whatsThis;
1434 return QString();
1435 }
1436
1437 #endif // QT_CONFIG(whatsthis)
1438
1439 /*!
1440 Sets the data of the tab at position \a index to \a data.
1441 */
1442 void KCustomTabBar::setTabData(int index, const QVariant &data)
1443 {
1444 Q_D(KCustomTabBar);
1445 if (KCustomTabBarPrivate::Tab *tab = d->at(index))
1446 tab->data = data;
1447 }
1448
1449 /*!
1450 Returns the data of the tab at position \a index, or a null
1451 variant if \a index is out of range.
1452 */
1453 QVariant KCustomTabBar::tabData(int index) const
1454 {
1455 Q_D(const KCustomTabBar);
1456 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
1457 return tab->data;
1458 return QVariant();
1459 }
1460
1461 /*!
1462 Returns the visual rectangle of the tab at position \a
1463 index, or a null rectangle if \a index is out of range.
1464 */
1465 QRect KCustomTabBar::tabRect(int index) const
1466 {
1467 Q_D(const KCustomTabBar);
1468 if (const KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1469 if (d->layoutDirty)
1470 const_cast<KCustomTabBarPrivate *>(d)->layoutTabs();
1471 QRect r = tab->rect;
1472 if (verticalTabs(d->shape))
1473 r.translate(0, -d->scrollOffset);
1474 else
1475 r.translate(-d->scrollOffset, 0);
1476 if (!verticalTabs(d->shape))
1477 r = QStyle::visualRect(layoutDirection(), rect(), r);
1478 return r;
1479 }
1480 return QRect();
1481 }
1482
1483 /*!
1484 \since 4.3
1485 Returns the index of the tab that covers \a position or -1 if no
1486 tab covers \a position;
1487 */
1488
1489 int KCustomTabBar::tabAt(const QPoint &position) const
1490 {
1491 Q_D(const KCustomTabBar);
1492 if (d->validIndex(d->currentIndex)
1493 && tabRect(d->currentIndex).contains(position)) {
1494 return d->currentIndex;
1495 }
1496 const int max = d->tabList.size();
1497 for (int i = 0; i < max; ++i) {
1498 if (tabRect(i).contains(position)) {
1499 return i;
1500 }
1501 }
1502 return -1;
1503 }
1504
1505 /*!
1506 \property KCustomTabBar::currentIndex
1507 \brief the index of the tab bar's visible tab
1508
1509 The current index is -1 if there is no current tab.
1510 */
1511
1512 int KCustomTabBar::currentIndex() const
1513 {
1514 Q_D(const KCustomTabBar);
1515 if (d->validIndex(d->currentIndex))
1516 return d->currentIndex;
1517 return -1;
1518 }
1519
1520 void KCustomTabBar::setCurrentIndex(int index)
1521 {
1522 Q_D(KCustomTabBar);
1523 if (d->dragInProgress && d->pressedIndex != -1)
1524 return;
1525
1526 int oldIndex = d->currentIndex;
1527 if (d->validIndex(index) && d->currentIndex != index) {
1528 d->currentIndex = index;
1529 update();
1530 d->makeVisible(index);
1531 d->tabList[index].lastTab = oldIndex;
1532 if (oldIndex >= 0 && oldIndex < count())
1533 d->layoutTab(oldIndex);
1534 d->layoutTab(index);
1535 #ifndef QT_NO_ACCESSIBILITY
1536 if (QAccessible::isActive()) {
1537 if (hasFocus()) {
1538 QAccessibleEvent focusEvent(this, QAccessible::Focus);
1539 focusEvent.setChild(index);
1540 QAccessible::updateAccessibility(&focusEvent);
1541 }
1542 QAccessibleEvent selectionEvent(this, QAccessible::Selection);
1543 selectionEvent.setChild(index);
1544 QAccessible::updateAccessibility(&selectionEvent);
1545 }
1546 #endif
1547 emit currentChanged(index);
1548 }
1549 }
1550
1551 /*!
1552 \property KCustomTabBar::iconSize
1553 \brief The size for icons in the tab bar
1554 \since 4.1
1555
1556 The default value is style-dependent. \c iconSize is a maximum
1557 size; icons that are smaller are not scaled up.
1558
1559 \sa QTabWidget::iconSize
1560 */
1561 QSize KCustomTabBar::iconSize() const
1562 {
1563 Q_D(const KCustomTabBar);
1564 if (d->iconSize.isValid())
1565 return d->iconSize;
1566 int iconExtent = style()->pixelMetric(QStyle::PM_TabBarIconSize, 0, this);
1567 return QSize(iconExtent, iconExtent);
1568 }
1569
1570 void KCustomTabBar::setIconSize(const QSize &size)
1571 {
1572 Q_D(KCustomTabBar);
1573 d->iconSize = size;
1574 d->layoutDirty = true;
1575 update();
1576 updateGeometry();
1577 }
1578
1579 /*!
1580 \property KCustomTabBar::count
1581 \brief the number of tabs in the tab bar
1582 */
1583
1584 int KCustomTabBar::count() const
1585 {
1586 Q_D(const KCustomTabBar);
1587 return d->tabList.count();
1588 }
1589
1590 /*!\reimp
1591 */
1592 QSize KCustomTabBar::sizeHint() const
1593 {
1594 Q_D(const KCustomTabBar);
1595 if (d->layoutDirty)
1596 const_cast<KCustomTabBarPrivate *>(d)->layoutTabs();
1597 QRect r;
1598 for (int i = 0; i < d->tabList.count(); ++i)
1599 r = r.united(d->tabList.at(i).maxRect);
1600 return r.size();
1601 }
1602
1603 /*!\reimp
1604 */
1605 QSize KCustomTabBar::minimumSizeHint() const
1606 {
1607 Q_D(const KCustomTabBar);
1608 if (d->layoutDirty)
1609 const_cast<KCustomTabBarPrivate *>(d)->layoutTabs();
1610 if (!d->useScrollButtons) {
1611 QRect r;
1612 for (int i = 0; i < d->tabList.count(); ++i)
1613 r = r.united(d->tabList.at(i).minRect);
1614 return r.size();
1615 }
1616 if (verticalTabs(d->shape))
1617 return QSize(sizeHint().width(), d->rightB->sizeHint().height() * 2 + 75);
1618 else
1619 return QSize(d->rightB->sizeHint().width() * 2 + 75, sizeHint().height());
1620 }
1621
1622 // Compute the most-elided possible text, for minimumSizeHint
1623 static QString computeElidedText(Qt::TextElideMode mode, const QString &text)
1624 {
1625 if (text.length() <= 3)
1626 return text;
1627
1628 static const QLatin1String Ellipses("...");
1629 QString ret;
1630 switch (mode) {
1631 case Qt::ElideRight:
1632 ret = text.left(2) + Ellipses;
1633 break;
1634 case Qt::ElideMiddle:
1635 ret = text.left(1) + Ellipses + text.right(1);
1636 break;
1637 case Qt::ElideLeft:
1638 ret = Ellipses + text.right(2);
1639 break;
1640 case Qt::ElideNone:
1641 ret = text;
1642 break;
1643 }
1644 return ret;
1645 }
1646
1647 /*!
1648 Returns the minimum tab size hint for the tab at position \a index.
1649 \since 5.0
1650 */
1651
1652 QSize KCustomTabBar::minimumTabSizeHint(int index) const
1653 {
1654 Q_D(const KCustomTabBar);
1655 KCustomTabBarPrivate::Tab &tab = const_cast<KCustomTabBarPrivate::Tab &>(d->tabList[index]);
1656 QString oldText = tab.text;
1657 tab.text = computeElidedText(d->elideMode, oldText);
1658 QSize size = tabSizeHint(index);
1659 tab.text = oldText;
1660 return size;
1661 }
1662
1663 /*!
1664 Returns the size hint for the tab at position \a index.
1665 */
1666 QSize KCustomTabBar::tabSizeHint(int index) const
1667 {
1668 // Note: this must match with the computations in QCommonStylePrivate::tabLayout
1669 Q_D(const KCustomTabBar);
1670 if (const KCustomTabBarPrivate::Tab *tab = d->at(index)) {
1671 QStyleOptionTab opt;
1672 d->initBasicStyleOption(&opt, index);
1673 opt.text = d->tabList.at(index).text;
1674 QSize iconSize = tab->icon.isNull() ? QSize(0, 0) : opt.iconSize;
1675 int hframe = style()->pixelMetric(QStyle::PM_TabBarTabHSpace, &opt, this);
1676 int vframe = style()->pixelMetric(QStyle::PM_TabBarTabVSpace, &opt, this);
1677 const QFontMetrics fm = fontMetrics();
1678
1679 int maxWidgetHeight = qMax(opt.leftButtonSize.height(), opt.rightButtonSize.height());
1680 int maxWidgetWidth = qMax(opt.leftButtonSize.width(), opt.rightButtonSize.width());
1681
1682 int widgetWidth = 0;
1683 int widgetHeight = 0;
1684 int padding = 0;
1685 if (!opt.leftButtonSize.isEmpty()) {
1686 padding += 4;
1687 widgetWidth += opt.leftButtonSize.width();
1688 widgetHeight += opt.leftButtonSize.height();
1689 }
1690 if (!opt.rightButtonSize.isEmpty()) {
1691 padding += 4;
1692 widgetWidth += opt.rightButtonSize.width();
1693 widgetHeight += opt.rightButtonSize.height();
1694 }
1695 if (!opt.icon.isNull())
1696 padding += 4;
1697
1698 QHash<QString, QSize>::iterator it = d->textSizes.find(tab->text);
1699 if (it == d->textSizes.end())
1700 it = d->textSizes.insert(tab->text, fm.size(Qt::TextShowMnemonic, tab->text));
1701 const int textWidth = it.value().width();
1702 QSize csz;
1703 if (verticalTabs(d->shape)) {
1704 csz = QSize(qMax(maxWidgetWidth, qMax(fm.height(), iconSize.height())) + vframe,
1705 textWidth + iconSize.width() + hframe + widgetHeight + padding);
1706 } else {
1707 csz = QSize(textWidth + iconSize.width() + hframe + widgetWidth + padding,
1708 qMax(maxWidgetHeight, qMax(fm.height(), iconSize.height())) + vframe);
1709 }
1710
1711 QSize retSize = style()->sizeFromContents(QStyle::CT_TabBarTab, &opt, csz, this);
1712 return retSize;
1713 }
1714 return QSize();
1715 }
1716
1717 /*!
1718 This virtual handler is called after a new tab was added or
1719 inserted at position \a index.
1720
1721 \sa tabRemoved()
1722 */
1723 void KCustomTabBar::tabInserted(int index)
1724 {
1725 Q_UNUSED(index)
1726 }
1727
1728 /*!
1729 This virtual handler is called after a tab was removed from
1730 position \a index.
1731
1732 \sa tabInserted()
1733 */
1734 void KCustomTabBar::tabRemoved(int index)
1735 {
1736 Q_UNUSED(index)
1737 }
1738
1739 /*!
1740 This virtual handler is called whenever the tab layout changes.
1741
1742 \sa tabRect()
1743 */
1744 void KCustomTabBar::tabLayoutChange()
1745 {
1746 }
1747
1748 /*!\reimp
1749 */
1750 void KCustomTabBar::showEvent(QShowEvent *)
1751 {
1752 Q_D(KCustomTabBar);
1753 if (d->layoutDirty)
1754 d->refresh();
1755 if (!d->validIndex(d->currentIndex))
1756 setCurrentIndex(0);
1757 d->updateMacBorderMetrics();
1758 }
1759
1760 /*!\reimp
1761 */
1762 void KCustomTabBar::hideEvent(QHideEvent *)
1763 {
1764 Q_D(KCustomTabBar);
1765 d->updateMacBorderMetrics();
1766 }
1767
1768 /*!\reimp
1769 */
1770 bool KCustomTabBar::event(QEvent *event)
1771 {
1772 Q_D(KCustomTabBar);
1773 if (event->type() == QEvent::HoverMove
1774 || event->type() == QEvent::HoverEnter) {
1775 QHoverEvent *he = static_cast<QHoverEvent *>(event);
1776 if (!d->hoverRect.contains(he->pos())) {
1777 QRect oldHoverRect = d->hoverRect;
1778 bool cursorOverTabs = false;
1779 for (int i = 0; i < d->tabList.count(); ++i) {
1780 QRect area = tabRect(i);
1781 if (area.contains(he->pos())) {
1782 d->hoverIndex = i;
1783 d->hoverRect = area;
1784 cursorOverTabs = true;
1785 break;
1786 }
1787 }
1788 if (!cursorOverTabs) {
1789 d->hoverIndex = -1;
1790 d->hoverRect = QRect();
1791 }
1792 if (he->oldPos() != QPoint(-1, -1))
1793 update(oldHoverRect);
1794 update(d->hoverRect);
1795 }
1796 return true;
1797 } else if (event->type() == QEvent::HoverLeave) {
1798 QRect oldHoverRect = d->hoverRect;
1799 d->hoverIndex = -1;
1800 d->hoverRect = QRect();
1801 update(oldHoverRect);
1802 return true;
1803 #ifndef QT_NO_TOOLTIP
1804 } else if (event->type() == QEvent::ToolTip) {
1805 if (const KCustomTabBarPrivate::Tab *tab = d->at(tabAt(static_cast<QHelpEvent *>(event)->pos()))) {
1806 if (!tab->toolTip.isEmpty()) {
1807 QToolTip::showText(static_cast<QHelpEvent *>(event)->globalPos(), tab->toolTip, this);
1808 return true;
1809 }
1810 }
1811 #endif // QT_NO_TOOLTIP
1812 #if QT_CONFIG(whatsthis)
1813 } else if (event->type() == QEvent::QueryWhatsThis) {
1814 const KCustomTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent *>(event)->pos()));
1815 if (!tab || tab->whatsThis.isEmpty())
1816 event->ignore();
1817 return true;
1818 } else if (event->type() == QEvent::WhatsThis) {
1819 if (const KCustomTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent *>(event)->pos()))) {
1820 if (!tab->whatsThis.isEmpty()) {
1821 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(),
1822 tab->whatsThis, this);
1823 return true;
1824 }
1825 }
1826 #endif // QT_CONFIG(whatsthis)
1827 #ifndef QT_NO_SHORTCUT
1828 } else if (event->type() == QEvent::Shortcut) {
1829 QShortcutEvent *se = static_cast<QShortcutEvent *>(event);
1830 for (int i = 0; i < d->tabList.count(); ++i) {
1831 const KCustomTabBarPrivate::Tab *tab = &d->tabList.at(i);
1832 if (tab->shortcutId == se->shortcutId()) {
1833 setCurrentIndex(i);
1834 return true;
1835 }
1836 }
1837 #endif
1838 } else if (event->type() == QEvent::MouseButtonDblClick) { // ### fixme Qt 6: move to mouseDoubleClickEvent(), here for BC reasons.
1839 const QPoint pos = static_cast<const QMouseEvent *>(event)->pos();
1840 const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
1841 || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
1842 if (!isEventInCornerButtons)
1843 emit tabBarDoubleClicked(tabAt(pos));
1844 } else if (event->type() == QEvent::Move) {
1845 d->updateMacBorderMetrics();
1846 return QWidget::event(event);
1847
1848 #if QT_CONFIG(draganddrop)
1849 } else if (event->type() == QEvent::DragEnter) {
1850 if (d->changeCurrentOnDrag)
1851 event->accept();
1852 } else if (event->type() == QEvent::DragMove) {
1853 if (d->changeCurrentOnDrag) {
1854 const int tabIndex = tabAt(static_cast<QDragMoveEvent *>(event)->pos());
1855 if (isTabEnabled(tabIndex) && d->switchTabCurrentIndex != tabIndex) {
1856 d->switchTabCurrentIndex = tabIndex;
1857 if (d->switchTabTimerId)
1858 killTimer(d->switchTabTimerId);
1859 d->switchTabTimerId = startTimer(style()->styleHint(QStyle::SH_TabBar_ChangeCurrentDelay));
1860 }
1861 event->ignore();
1862 }
1863 } else if (event->type() == QEvent::DragLeave || event->type() == QEvent::Drop) {
1864 d->killSwitchTabTimer();
1865 event->ignore();
1866 #endif
1867 }
1868 return QWidget::event(event);
1869 }
1870
1871 /*!\reimp
1872 */
1873 void KCustomTabBar::resizeEvent(QResizeEvent *)
1874 {
1875 Q_D(KCustomTabBar);
1876 if (d->layoutDirty)
1877 updateGeometry();
1878 d->layoutTabs();
1879
1880 d->makeVisible(d->currentIndex);
1881 }
1882
1883 /*!\reimp
1884 */
1885 void KCustomTabBar::paintEvent(QPaintEvent *)
1886 {
1887 Q_D(KCustomTabBar);
1888 QStyleOptionTabBarBase optTabBase;
1889 KCustomTabBarPrivate::initStyleBaseOption(&optTabBase, this, size());
1890
1891 QStylePainter p(this);
1892 int selected = -1;
1893 int cutLeft = -1;
1894 int cutRight = -1;
1895 bool vertical = verticalTabs(d->shape);
1896 QStyleOptionTab cutTabLeft;
1897 QStyleOptionTab cutTabRight;
1898 selected = d->currentIndex;
1899 if (d->dragInProgress)
1900 selected = d->pressedIndex;
1901 const QRect scrollRect = d->normalizedScrollRect();
1902
1903 for (int i = 0; i < d->tabList.count(); ++i)
1904 optTabBase.tabBarRect |= tabRect(i);
1905
1906 optTabBase.selectedTabRect = tabRect(selected);
1907
1908 if (d->drawBase)
1909 p.drawPrimitive(QStyle::PE_FrameTabBarBase, optTabBase);
1910
1911 for (int i = 0; i < d->tabList.count(); ++i) {
1912 QStyleOptionTab tab;
1913 initStyleOption(&tab, i);
1914 if (d->paintWithOffsets && d->tabList[i].dragOffset != 0) {
1915 if (vertical) {
1916 tab.rect.moveTop(tab.rect.y() + d->tabList[i].dragOffset);
1917 } else {
1918 tab.rect.moveLeft(tab.rect.x() + d->tabList[i].dragOffset);
1919 }
1920 }
1921 if (!(tab.state & QStyle::State_Enabled)) {
1922 tab.palette.setCurrentColorGroup(QPalette::Disabled);
1923 }
1924
1925 // If this tab is partially obscured, make a note of it so that we can pass the information
1926 // along when we draw the tear.
1927 QRect tabRect = d->tabList[i].rect;
1928 int tabStart = vertical ? tabRect.top() : tabRect.left();
1929 int tabEnd = vertical ? tabRect.bottom() : tabRect.right();
1930 if (tabStart < scrollRect.left() + d->scrollOffset) {
1931 cutLeft = i;
1932 cutTabLeft = tab;
1933 } else if (tabEnd > scrollRect.right() + d->scrollOffset) {
1934 cutRight = i;
1935 cutTabRight = tab;
1936 }
1937
1938 // Don't bother drawing a tab if the entire tab is outside of the visible tab bar.
1939 if ((!vertical && (tab.rect.right() < 0 || tab.rect.left() > width()))
1940 || (vertical && (tab.rect.bottom() < 0 || tab.rect.top() > height())))
1941 continue;
1942
1943 optTabBase.tabBarRect |= tab.rect;
1944 if (i == selected)
1945 continue;
1946
1947 p.drawControl(QStyle::CE_TabBarTab, tab);
1948 }
1949
1950 // Draw the selected tab last to get it "on top"
1951 if (selected >= 0) {
1952 QStyleOptionTab tab;
1953 initStyleOption(&tab, selected);
1954 if (d->paintWithOffsets && d->tabList[selected].dragOffset != 0) {
1955 if (vertical)
1956 tab.rect.moveTop(tab.rect.y() + d->tabList[selected].dragOffset);
1957 else
1958 tab.rect.moveLeft(tab.rect.x() + d->tabList[selected].dragOffset);
1959 }
1960 if (!d->dragInProgress)
1961 p.drawControl(QStyle::CE_TabBarTab, tab);
1962 else {
1963 int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0, this);
1964 if (verticalTabs(d->shape))
1965 d->movingTab->setGeometry(tab.rect.adjusted(0, -taboverlap, 0, taboverlap));
1966 else
1967 d->movingTab->setGeometry(tab.rect.adjusted(-taboverlap, 0, taboverlap, 0));
1968 }
1969 }
1970
1971 // Only draw the tear indicator if necessary. Most of the time we don't need too.
1972 if (d->leftB->isVisible() && cutLeft >= 0) {
1973 cutTabLeft.rect = rect();
1974 cutTabLeft.rect = style()->subElementRect(QStyle::SE_TabBarTearIndicatorLeft, &cutTabLeft, this);
1975 p.drawPrimitive(QStyle::PE_IndicatorTabTearLeft, cutTabLeft);
1976 }
1977
1978 if (d->rightB->isVisible() && cutRight >= 0) {
1979 cutTabRight.rect = rect();
1980 cutTabRight.rect = style()->subElementRect(QStyle::SE_TabBarTearIndicatorRight, &cutTabRight, this);
1981 p.drawPrimitive(QStyle::PE_IndicatorTabTearRight, cutTabRight);
1982 }
1983 }
1984
1985 /*
1986 Given that index at position from moved to position to where return where index goes.
1987 */
1988 KCustomTabBarPrivate::KCustomTabBarPrivate(KCustomTabBar *parent)
1989 : q_ptr(parent)
1990 , currentIndex(-1)
1991 , pressedIndex(-1)
1992 , shape(KCustomTabBar::RoundedNorth)
1993 , layoutDirty(false)
1994 , drawBase(true)
1995 , scrollOffset(0)
1996 , hoverIndex(-1)
1997 , elideModeSetByUser(false)
1998 , useScrollButtonsSetByUser(false)
1999 , expanding(true)
2000 , closeButtonOnTabs(false)
2001 , selectionBehaviorOnRemove(KCustomTabBar::SelectRightTab)
2002 , paintWithOffsets(true)
2003 , movable(false)
2004 , dragInProgress(false)
2005 , documentMode(false)
2006 , autoHide(false)
2007 , changeCurrentOnDrag(false)
2008 , switchTabCurrentIndex(-1)
2009 , switchTabTimerId(0)
2010 , movingTab(0)
2011 {
2012 }
2013
2014 void KCustomTabBarPrivate::qGeomCalc(QVector<QCustomLayoutStruct> &chain, int start, int count, int pos, int space, int spacer)
2015 {
2016 int cHint = 0;
2017 int cMin = 0;
2018 int cMax = 0;
2019 int sumStretch = 0;
2020 int sumSpacing = 0;
2021 int expandingCount = 0;
2022
2023 bool allEmptyNonstretch = true;
2024 int pendingSpacing = -1;
2025 int spacerCount = 0;
2026 int i;
2027
2028 for (i = start; i < start + count; i++) {
2029 QCustomLayoutStruct *data = &chain[i];
2030
2031 data->done = false;
2032 cHint += data->smartSizeHint();
2033 cMin += data->minimumSize;
2034 cMax += data->maximumSize;
2035 sumStretch += data->stretch;
2036 if (!data->empty) {
2037 /*
2038 Using pendingSpacing, we ensure that the spacing for the last
2039 (non-empty) item is ignored.
2040 */
2041 if (pendingSpacing >= 0) {
2042 sumSpacing += pendingSpacing;
2043 ++spacerCount;
2044 }
2045 pendingSpacing = data->effectiveSpacer(spacer);
2046 }
2047 if (data->expansive)
2048 expandingCount++;
2049 allEmptyNonstretch = allEmptyNonstretch && data->empty && !data->expansive && data->stretch <= 0;
2050 }
2051
2052 int extraspace = 0;
2053
2054 if (space < cMin + sumSpacing) {
2055 /*
2056 Less space than minimumSize; take from the biggest first
2057 */
2058
2059 int minSize = cMin + sumSpacing;
2060
2061 // shrink the spacers proportionally
2062 if (spacer >= 0) {
2063 spacer = minSize > 0 ? spacer * space / minSize : 0;
2064 sumSpacing = spacer * spacerCount;
2065 }
2066
2067 QVarLengthArray<int, 32> minimumSizes;
2068 minimumSizes.reserve(count);
2069
2070 for (i = start; i < start + count; i++)
2071 minimumSizes << chain.at(i).minimumSize;
2072
2073 std::sort(minimumSizes.begin(), minimumSizes.end());
2074
2075 int space_left = space - sumSpacing;
2076
2077 int sum = 0;
2078 int idx = 0;
2079 int space_used = 0;
2080 int current = 0;
2081 while (idx < count && space_used < space_left) {
2082 current = minimumSizes.at(idx);
2083 space_used = sum + current * (count - idx);
2084 sum += current;
2085 ++idx;
2086 }
2087 --idx;
2088 int deficit = space_used - space_left;
2089
2090 int items = count - idx;
2091 /*
2092 * If we truncate all items to "current", we would get "deficit" too many pixels. Therefore, we have to remove
2093 * deficit/items from each item bigger than maxval. The actual value to remove is deficitPerItem + remainder/items
2094 * "rest" is the accumulated error from using integer arithmetic.
2095 */
2096 int deficitPerItem = deficit / items;
2097 int remainder = deficit % items;
2098 int maxval = current - deficitPerItem;
2099
2100 int rest = 0;
2101 for (i = start; i < start + count; i++) {
2102 int maxv = maxval;
2103 rest += remainder;
2104 if (rest >= items) {
2105 maxv--;
2106 rest -= items;
2107 }
2108 QCustomLayoutStruct *data = &chain[i];
2109 data->size = qMin(data->minimumSize, maxv);
2110 data->done = true;
2111 }
2112 } else if (space < cHint + sumSpacing) {
2113 /*
2114 Less space than smartSizeHint(), but more than minimumSize.
2115 Currently take space equally from each, as in Qt 2.x.
2116 Commented-out lines will give more space to stretchier
2117 items.
2118 */
2119 int n = count;
2120 int space_left = space - sumSpacing;
2121 int overdraft = cHint - space_left;
2122
2123 // first give to the fixed ones:
2124 for (i = start; i < start + count; i++) {
2125 QCustomLayoutStruct *data = &chain[i];
2126 if (!data->done
2127 && data->minimumSize >= data->smartSizeHint()) {
2128 data->size = data->smartSizeHint();
2129 data->done = true;
2130 space_left -= data->smartSizeHint();
2131 // sumStretch -= data->stretch;
2132 n--;
2133 }
2134 }
2135 bool finished = n == 0;
2136 while (!finished) {
2137 finished = true;
2138 Fixed64 fp_over = toFixed(overdraft);
2139 Fixed64 fp_w = 0;
2140
2141 for (i = start; i < start + count; i++) {
2142 QCustomLayoutStruct *data = &chain[i];
2143 if (data->done)
2144 continue;
2145 // if (sumStretch <= 0)
2146 fp_w += fp_over / n;
2147 // else
2148 // fp_w += (fp_over * data->stretch) / sumStretch;
2149 int w = fRound(fp_w);
2150 data->size = data->smartSizeHint() - w;
2151 fp_w -= toFixed(w); // give the difference to the next
2152 if (data->size < data->minimumSize) {
2153 data->done = true;
2154 data->size = data->minimumSize;
2155 finished = false;
2156 overdraft -= data->smartSizeHint() - data->minimumSize;
2157 // sumStretch -= data->stretch;
2158 n--;
2159 break;
2160 }
2161 }
2162 }
2163 } else { // extra space
2164 int n = count;
2165 int space_left = space - sumSpacing;
2166 // first give to the fixed ones, and handle non-expansiveness
2167 for (i = start; i < start + count; i++) {
2168 QCustomLayoutStruct *data = &chain[i];
2169 if (!data->done
2170 && (data->maximumSize <= data->smartSizeHint()
2171 || (!allEmptyNonstretch && data->empty && !data->expansive && data->stretch == 0))) {
2172 data->size = data->smartSizeHint();
2173 data->done = true;
2174 space_left -= data->size;
2175 sumStretch -= data->stretch;
2176 if (data->expansive)
2177 expandingCount--;
2178 n--;
2179 }
2180 }
2181 extraspace = space_left;
2182
2183 /*
2184 Do a trial distribution and calculate how much it is off.
2185 If there are more deficit pixels than surplus pixels, give
2186 the minimum size items what they need, and repeat.
2187 Otherwise give to the maximum size items, and repeat.
2188
2189 Paul Olav Tvete has a wonderful mathematical proof of the
2190 correctness of this principle, but unfortunately this
2191 comment is too small to contain it.
2192 */
2193 int surplus, deficit;
2194 do {
2195 surplus = deficit = 0;
2196 Fixed64 fp_space = toFixed(space_left);
2197 Fixed64 fp_w = 0;
2198 for (i = start; i < start + count; i++) {
2199 QCustomLayoutStruct *data = &chain[i];
2200 if (data->done)
2201 continue;
2202 extraspace = 0;
2203 if (sumStretch > 0) {
2204 fp_w += (fp_space * data->stretch) / sumStretch;
2205 } else if (expandingCount > 0) {
2206 fp_w += (fp_space * (data->expansive ? 1 : 0)) / expandingCount;
2207 } else {
2208 fp_w += fp_space * 1 / n;
2209 }
2210 int w = fRound(fp_w);
2211 data->size = w;
2212 fp_w -= toFixed(w); // give the difference to the next
2213 if (w < data->smartSizeHint()) {
2214 deficit += data->smartSizeHint() - w;
2215 } else if (w > data->maximumSize) {
2216 surplus += w - data->maximumSize;
2217 }
2218 }
2219 if (deficit > 0 && surplus <= deficit) {
2220 // give to the ones that have too little
2221 for (i = start; i < start + count; i++) {
2222 QCustomLayoutStruct *data = &chain[i];
2223 if (!data->done && data->size < data->smartSizeHint()) {
2224 data->size = data->smartSizeHint();
2225 data->done = true;
2226 space_left -= data->smartSizeHint();
2227 sumStretch -= data->stretch;
2228 if (data->expansive)
2229 expandingCount--;
2230 n--;
2231 }
2232 }
2233 }
2234 if (surplus > 0 && surplus >= deficit) {
2235 // take from the ones that have too much
2236 for (i = start; i < start + count; i++) {
2237 QCustomLayoutStruct *data = &chain[i];
2238 if (!data->done && data->size > data->maximumSize) {
2239 data->size = data->maximumSize;
2240 data->done = true;
2241 space_left -= data->maximumSize;
2242 sumStretch -= data->stretch;
2243 if (data->expansive)
2244 expandingCount--;
2245 n--;
2246 }
2247 }
2248 }
2249 } while (n > 0 && surplus != deficit);
2250 if (n == 0)
2251 extraspace = space_left;
2252 }
2253
2254 /*
2255 As a last resort, we distribute the unwanted space equally
2256 among the spacers (counting the start and end of the chain). We
2257 could, but don't, attempt a sub-pixel allocation of the extra
2258 space.
2259 */
2260 int extra = extraspace / (spacerCount + 2);
2261 int p = pos + extra;
2262 for (i = start; i < start + count; i++) {
2263 QCustomLayoutStruct *data = &chain[i];
2264 data->pos = p;
2265 p += data->size;
2266 if (!data->empty)
2267 p += data->effectiveSpacer(spacer) + extra;
2268 }
2269
2270 #ifdef QLAYOUT_EXTRA_DEBUG
2271 qDebug() << "qGeomCalc"
2272 << "start" << start << "count" << count << "pos" << pos
2273 << "space" << space << "spacer" << spacer;
2274 for (i = start; i < start + count; ++i) {
2275 qDebug() << i << ':' << chain[i].minimumSize << chain[i].smartSizeHint()
2276 << chain[i].maximumSize << "stretch" << chain[i].stretch
2277 << "empty" << chain[i].empty << "expansive" << chain[i].expansive
2278 << "spacing" << chain[i].spacing;
2279 qDebug() << "result pos" << chain[i].pos << "size" << chain[i].size;
2280 }
2281 #endif
2282 }
2283
2284 int KCustomTabBarPrivate::calculateNewPosition(int from, int to, int index) const
2285 {
2286 if (index == from)
2287 return to;
2288
2289 int start = qMin(from, to);
2290 int end = qMax(from, to);
2291 if (index >= start && index <= end)
2292 index += (from < to) ? -1 : 1;
2293 return index;
2294 }
2295
2296 /*!
2297 Moves the item at index position \a from to index position \a to.
2298 \since 4.5
2299
2300 \sa tabMoved(), tabLayoutChange()
2301 */
2302 void KCustomTabBar::moveTab(int from, int to)
2303 {
2304 Q_D(KCustomTabBar);
2305 if (from == to
2306 || !d->validIndex(from)
2307 || !d->validIndex(to))
2308 return;
2309
2310 bool vertical = verticalTabs(d->shape);
2311 int oldPressedPosition = 0;
2312 if (d->pressedIndex != -1) {
2313 // Record the position of the pressed tab before reordering the tabs.
2314 oldPressedPosition = vertical ? d->tabList[d->pressedIndex].rect.y()
2315 : d->tabList[d->pressedIndex].rect.x();
2316 }
2317
2318 // Update the locations of the tabs first
2319 int start = qMin(from, to);
2320 int end = qMax(from, to);
2321 int width = vertical ? d->tabList[from].rect.height() : d->tabList[from].rect.width();
2322 if (from < to)
2323 width *= -1;
2324 bool rtl = isRightToLeft();
2325 for (int i = start; i <= end; ++i) {
2326 if (i == from)
2327 continue;
2328 if (vertical)
2329 d->tabList[i].rect.moveTop(d->tabList[i].rect.y() + width);
2330 else
2331 d->tabList[i].rect.moveLeft(d->tabList[i].rect.x() + width);
2332 int direction = -1;
2333 if (rtl && !vertical)
2334 direction *= -1;
2335 if (d->tabList[i].dragOffset != 0)
2336 d->tabList[i].dragOffset += (direction * width);
2337 }
2338
2339 if (vertical) {
2340 if (from < to)
2341 d->tabList[from].rect.moveTop(d->tabList[to].rect.bottom() + 1);
2342 else
2343 d->tabList[from].rect.moveTop(d->tabList[to].rect.top() - width);
2344 } else {
2345 if (from < to)
2346 d->tabList[from].rect.moveLeft(d->tabList[to].rect.right() + 1);
2347 else
2348 d->tabList[from].rect.moveLeft(d->tabList[to].rect.left() - width);
2349 }
2350
2351 // Move the actual data structures
2352 d->tabList.move(from, to);
2353
2354 // update lastTab locations
2355 for (int i = 0; i < d->tabList.count(); ++i)
2356 d->tabList[i].lastTab = d->calculateNewPosition(from, to, d->tabList[i].lastTab);
2357
2358 // update external variables
2359 int previousIndex = d->currentIndex;
2360 d->currentIndex = d->calculateNewPosition(from, to, d->currentIndex);
2361
2362 // If we are in the middle of a drag update the dragStartPosition
2363 if (d->pressedIndex != -1) {
2364 d->pressedIndex = d->calculateNewPosition(from, to, d->pressedIndex);
2365 int newPressedPosition = vertical ? d->tabList[d->pressedIndex].rect.top() : d->tabList[d->pressedIndex].rect.left();
2366 int diff = oldPressedPosition - newPressedPosition;
2367 if (isRightToLeft() && !vertical)
2368 diff *= -1;
2369 if (vertical)
2370 d->dragStartPosition.setY(d->dragStartPosition.y() - diff);
2371 else
2372 d->dragStartPosition.setX(d->dragStartPosition.x() - diff);
2373 }
2374
2375 d->layoutWidgets(start);
2376 update();
2377 emit tabMoved(from, to);
2378 if (previousIndex != d->currentIndex)
2379 emit currentChanged(d->currentIndex);
2380 emit tabLayoutChange();
2381 }
2382
2383 void KCustomTabBarPrivate::slide(int from, int to)
2384 {
2385 Q_Q(KCustomTabBar);
2386 if (from == to
2387 || !validIndex(from)
2388 || !validIndex(to))
2389 return;
2390 bool vertical = verticalTabs(shape);
2391 int preLocation = vertical ? q->tabRect(from).y() : q->tabRect(from).x();
2392 q->setUpdatesEnabled(false);
2393 q->moveTab(from, to);
2394 q->setUpdatesEnabled(true);
2395 int postLocation = vertical ? q->tabRect(to).y() : q->tabRect(to).x();
2396 int length = postLocation - preLocation;
2397 tabList[to].dragOffset -= length;
2398 tabList[to].startAnimation(this, ANIMATION_DURATION);
2399 }
2400
2401 void KCustomTabBarPrivate::moveTab(int index, int offset)
2402 {
2403 if (!validIndex(index))
2404 return;
2405 tabList[index].dragOffset = offset;
2406 layoutTab(index); // Make buttons follow tab
2407 q_func()->update();
2408 }
2409
2410 /*!\reimp
2411 */
2412 void KCustomTabBar::mousePressEvent(QMouseEvent *event)
2413 {
2414 Q_D(KCustomTabBar);
2415
2416 const QPoint pos = event->pos();
2417 const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
2418 || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
2419 if (!isEventInCornerButtons) {
2420 const int index = d->indexAtPos(pos);
2421 emit tabBarClicked(index);
2422 }
2423
2424 if (event->button() != Qt::LeftButton) {
2425 event->ignore();
2426 return;
2427 }
2428 // Be safe!
2429 if (d->pressedIndex != -1 && d->movable)
2430 d->moveTabFinished(d->pressedIndex);
2431
2432 d->pressedIndex = d->indexAtPos(event->pos());
2433
2434 if (d->validIndex(d->pressedIndex)) {
2435 QStyleOptionTabBarBase optTabBase;
2436 optTabBase.initFrom(this);
2437 optTabBase.documentMode = d->documentMode;
2438 if (event->type() == style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this))
2439 setCurrentIndex(d->pressedIndex);
2440 else
2441 repaint(tabRect(d->pressedIndex));
2442 if (d->movable) {
2443 d->dragStartPosition = event->pos();
2444 }
2445 }
2446 }
2447
2448 /*!\reimp
2449 */
2450 void KCustomTabBar::mouseMoveEvent(QMouseEvent *event)
2451 {
2452 Q_D(KCustomTabBar);
2453 if (d->movable) {
2454 // Be safe!
2455 if (d->pressedIndex != -1
2456 && event->buttons() == Qt::NoButton)
2457 d->moveTabFinished(d->pressedIndex);
2458
2459 // Start drag
2460 if (!d->dragInProgress && d->pressedIndex != -1) {
2461 if ((event->pos() - d->dragStartPosition).manhattanLength() > QApplication::startDragDistance()) {
2462 d->dragInProgress = true;
2463 d->setupMovableTab();
2464 }
2465 }
2466
2467 if (event->buttons() == Qt::LeftButton
2468 && d->dragInProgress
2469 && d->validIndex(d->pressedIndex)) {
2470 bool vertical = verticalTabs(d->shape);
2471 int dragDistance;
2472 if (vertical) {
2473 dragDistance = (event->pos().y() - d->dragStartPosition.y());
2474 } else {
2475 dragDistance = (event->pos().x() - d->dragStartPosition.x());
2476 }
2477 d->tabList[d->pressedIndex].dragOffset = dragDistance;
2478
2479 QRect startingRect = tabRect(d->pressedIndex);
2480 if (vertical)
2481 startingRect.moveTop(startingRect.y() + dragDistance);
2482 else
2483 startingRect.moveLeft(startingRect.x() + dragDistance);
2484
2485 int overIndex;
2486 if (dragDistance < 0)
2487 overIndex = tabAt(startingRect.topLeft());
2488 else
2489 overIndex = tabAt(startingRect.topRight());
2490
2491 if (overIndex != d->pressedIndex && overIndex != -1) {
2492 int offset = 1;
2493 if (isRightToLeft() && !vertical)
2494 offset *= -1;
2495 if (dragDistance < 0) {
2496 dragDistance *= -1;
2497 offset *= -1;
2498 }
2499 for (int i = d->pressedIndex;
2500 offset > 0 ? i < overIndex : i > overIndex;
2501 i += offset) {
2502 QRect overIndexRect = tabRect(overIndex);
2503 int needsToBeOver = (vertical ? overIndexRect.height() : overIndexRect.width()) / 2;
2504 if (dragDistance > needsToBeOver)
2505 d->slide(i + offset, d->pressedIndex);
2506 }
2507 }
2508 // Buttons needs to follow the dragged tab
2509 d->layoutTab(d->pressedIndex);
2510
2511 update();
2512 }
2513 }
2514
2515 if (event->buttons() != Qt::LeftButton) {
2516 event->ignore();
2517 return;
2518 }
2519 }
2520
2521 void KCustomTabBarPrivate::setupMovableTab()
2522 {
2523 Q_Q(KCustomTabBar);
2524 if (!movingTab)
2525 movingTab = new KCustomMovableTabWidget(q);
2526
2527 int taboverlap = q->style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0, q);
2528 QRect grabRect = q->tabRect(pressedIndex);
2529 if (verticalTabs(shape))
2530 grabRect.adjust(0, -taboverlap, 0, taboverlap);
2531 else
2532 grabRect.adjust(-taboverlap, 0, taboverlap, 0);
2533
2534 QPixmap grabImage(grabRect.size() * q->devicePixelRatioF());
2535 grabImage.setDevicePixelRatio(q->devicePixelRatioF());
2536 grabImage.fill(Qt::transparent);
2537 QStylePainter p(&grabImage, q);
2538
2539 QStyleOptionTab tab;
2540 q->initStyleOption(&tab, pressedIndex);
2541 tab.position = QStyleOptionTab::OnlyOneTab;
2542 if (verticalTabs(shape))
2543 tab.rect.moveTopLeft(QPoint(0, taboverlap));
2544 else
2545 tab.rect.moveTopLeft(QPoint(taboverlap, 0));
2546 p.drawControl(QStyle::CE_TabBarTab, tab);
2547 p.end();
2548
2549 movingTab->setPixmap(grabImage);
2550 movingTab->setGeometry(grabRect);
2551 movingTab->raise();
2552
2553 // Re-arrange widget order to avoid overlaps
2554 if (tabList[pressedIndex].leftWidget)
2555 tabList[pressedIndex].leftWidget->raise();
2556 if (tabList[pressedIndex].rightWidget)
2557 tabList[pressedIndex].rightWidget->raise();
2558 if (leftB)
2559 leftB->raise();
2560 if (rightB)
2561 rightB->raise();
2562 movingTab->setVisible(true);
2563 }
2564
2565 void KCustomTabBarPrivate::moveTabFinished(int index)
2566 {
2567 Q_Q(KCustomTabBar);
2568 bool cleanup = (pressedIndex == index) || (pressedIndex == -1) || !validIndex(index);
2569 bool allAnimationsFinished = true;
2570 #if QT_CONFIG(animation)
2571 for (int i = 0; allAnimationsFinished && i < tabList.count(); ++i) {
2572 const Tab &t = tabList.at(i);
2573 if (t.animation && t.animation->state() == QAbstractAnimation::Running)
2574 allAnimationsFinished = false;
2575 }
2576 #endif // animation
2577 if (allAnimationsFinished && cleanup) {
2578 if (movingTab)
2579 movingTab->setVisible(false); // We might not get a mouse release
2580 for (int i = 0; i < tabList.count(); ++i) {
2581 tabList[i].dragOffset = 0;
2582 }
2583 if (pressedIndex != -1 && movable) {
2584 pressedIndex = -1;
2585 dragInProgress = false;
2586 dragStartPosition = QPoint();
2587 }
2588 layoutWidgets();
2589 } else {
2590 if (!validIndex(index))
2591 return;
2592 tabList[index].dragOffset = 0;
2593 }
2594 q->update();
2595 }
2596
2597 /*!\reimp
2598 */
2599 void KCustomTabBar::mouseReleaseEvent(QMouseEvent *event)
2600 {
2601 Q_D(KCustomTabBar);
2602 if (event->button() != Qt::LeftButton) {
2603 event->ignore();
2604 return;
2605 }
2606 if (d->movable && d->dragInProgress && d->validIndex(d->pressedIndex)) {
2607 int length = d->tabList[d->pressedIndex].dragOffset;
2608 int width = verticalTabs(d->shape)
2609 ? tabRect(d->pressedIndex).height()
2610 : tabRect(d->pressedIndex).width();
2611 int duration = qMin(ANIMATION_DURATION,
2612 (qAbs(length) * ANIMATION_DURATION) / width);
2613 d->tabList[d->pressedIndex].startAnimation(d, duration);
2614 d->dragInProgress = false;
2615 d->movingTab->setVisible(false);
2616 d->dragStartPosition = QPoint();
2617 }
2618
2619 int i = d->indexAtPos(event->pos()) == d->pressedIndex ? d->pressedIndex : -1;
2620 d->pressedIndex = -1;
2621 QStyleOptionTabBarBase optTabBase;
2622 optTabBase.initFrom(this);
2623 optTabBase.documentMode = d->documentMode;
2624 const bool selectOnRelease =
2625 (style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this) == QEvent::MouseButtonRelease);
2626 if (selectOnRelease)
2627 setCurrentIndex(i);
2628 if (!selectOnRelease || !d->validIndex(i) || d->currentIndex == i)
2629 repaint(tabRect(i));
2630 }
2631
2632 /*!\reimp
2633 */
2634 void KCustomTabBar::keyPressEvent(QKeyEvent *event)
2635 {
2636 Q_D(KCustomTabBar);
2637 if (event->key() != Qt::Key_Left && event->key() != Qt::Key_Right) {
2638 event->ignore();
2639 return;
2640 }
2641 int offset = event->key() == (isRightToLeft() ? Qt::Key_Right : Qt::Key_Left) ? -1 : 1;
2642 d->setCurrentNextEnabledIndex(offset);
2643 }
2644
2645 /*!\reimp
2646 */
2647 #if QT_CONFIG(wheelevent)
2648 void KCustomTabBar::wheelEvent(QWheelEvent *event)
2649 {
2650 #ifndef Q_OS_MAC
2651 Q_D(KCustomTabBar);
2652 int offset = event->angleDelta().y() > 0 ? -1 : 1;
2653 d->setCurrentNextEnabledIndex(offset);
2654 QWidget::wheelEvent(event);
2655 #else
2656 Q_UNUSED(event)
2657 #endif
2658 }
2659 #endif // QT_CONFIG(wheelevent)
2660
2661 void KCustomTabBarPrivate::setCurrentNextEnabledIndex(int offset)
2662 {
2663 Q_Q(KCustomTabBar);
2664 for (int index = currentIndex + offset; validIndex(index); index += offset) {
2665 if (tabList.at(index).enabled) {
2666 q->setCurrentIndex(index);
2667 break;
2668 }
2669 }
2670 }
2671
2672 /*!\reimp
2673 */
2674 void KCustomTabBar::changeEvent(QEvent *event)
2675 {
2676 Q_D(KCustomTabBar);
2677 switch (event->type()) {
2678 case QEvent::StyleChange:
2679 if (!d->elideModeSetByUser)
2680 d->elideMode = Qt::TextElideMode(style()->styleHint(QStyle::SH_TabBar_ElideMode, 0, this));
2681 if (!d->useScrollButtonsSetByUser)
2682 d->useScrollButtons = !style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, 0, this);
2683 Q_FALLTHROUGH();
2684 case QEvent::FontChange:
2685 d->textSizes.clear();
2686 d->refresh();
2687 break;
2688 default:
2689 break;
2690 }
2691
2692 QWidget::changeEvent(event);
2693 }
2694
2695 /*!
2696 \reimp
2697 */
2698 void KCustomTabBar::timerEvent(QTimerEvent *event)
2699 {
2700 Q_D(KCustomTabBar);
2701 if (event->timerId() == d->switchTabTimerId) {
2702 killTimer(d->switchTabTimerId);
2703 d->switchTabTimerId = 0;
2704 setCurrentIndex(d->switchTabCurrentIndex);
2705 d->switchTabCurrentIndex = -1;
2706 }
2707 QWidget::timerEvent(event);
2708 }
2709
2710 /*!
2711 \property KCustomTabBar::elideMode
2712 \brief how to elide text in the tab bar
2713 \since 4.2
2714
2715 This property controls how items are elided when there is not
2716 enough space to show them for a given tab bar size.
2717
2718 By default the value is style dependent.
2719
2720 \sa QTabWidget::elideMode, usesScrollButtons, QStyle::SH_TabBar_ElideMode
2721 */
2722
2723 Qt::TextElideMode KCustomTabBar::elideMode() const
2724 {
2725 Q_D(const KCustomTabBar);
2726 return d->elideMode;
2727 }
2728
2729 void KCustomTabBar::setElideMode(Qt::TextElideMode mode)
2730 {
2731 Q_D(KCustomTabBar);
2732 d->elideMode = mode;
2733 d->elideModeSetByUser = true;
2734 d->textSizes.clear();
2735 d->refresh();
2736 }
2737
2738 /*!
2739 \property KCustomTabBar::usesScrollButtons
2740 \brief Whether or not a tab bar should use buttons to scroll tabs when it
2741 has many tabs.
2742 \since 4.2
2743
2744 When there are too many tabs in a tab bar for its size, the tab bar can either choose
2745 to expand its size or to add buttons that allow you to scroll through the tabs.
2746
2747 By default the value is style dependant.
2748
2749 \sa elideMode, QTabWidget::usesScrollButtons, QStyle::SH_TabBar_PreferNoArrows
2750 */
2751 bool KCustomTabBar::usesScrollButtons() const
2752 {
2753 return d_func()->useScrollButtons;
2754 }
2755
2756 void KCustomTabBar::setUsesScrollButtons(bool useButtons)
2757 {
2758 Q_D(KCustomTabBar);
2759 d->useScrollButtonsSetByUser = true;
2760 if (d->useScrollButtons == useButtons)
2761 return;
2762 d->useScrollButtons = useButtons;
2763 d->refresh();
2764 }
2765
2766 /*!
2767 \property KCustomTabBar::tabsClosable
2768 \brief Whether or not a tab bar should place close buttons on each tab
2769 \since 4.5
2770
2771 When tabsClosable is set to true a close button will appear on the tab on
2772 either the left or right hand side depending upon the style. When the button
2773 is clicked the tab the signal tabCloseRequested will be emitted.
2774
2775 By default the value is false.
2776
2777 \sa setTabButton(), tabRemoved()
2778 */
2779
2780 bool KCustomTabBar::tabsClosable() const
2781 {
2782 Q_D(const KCustomTabBar);
2783 return d->closeButtonOnTabs;
2784 }
2785
2786 void KCustomTabBar::setTabsClosable(bool closable)
2787 {
2788 Q_D(KCustomTabBar);
2789 if (d->closeButtonOnTabs == closable)
2790 return;
2791 d->closeButtonOnTabs = closable;
2792 ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, this);
2793 if (!closable) {
2794 for (int i = 0; i < d->tabList.count(); ++i) {
2795 if (closeSide == LeftSide && d->tabList[i].leftWidget) {
2796 d->tabList[i].leftWidget->deleteLater();
2797 d->tabList[i].leftWidget = 0;
2798 }
2799 if (closeSide == RightSide && d->tabList[i].rightWidget) {
2800 d->tabList[i].rightWidget->deleteLater();
2801 d->tabList[i].rightWidget = 0;
2802 }
2803 }
2804 } else {
2805 bool newButtons = false;
2806 for (int i = 0; i < d->tabList.count(); ++i) {
2807 if (tabButton(i, closeSide))
2808 continue;
2809 newButtons = true;
2810 QAbstractButton *closeButton = new CloseButton(this);
2811 // connect(closeButton, SIGNAL(clicked()), this, SLOT(_q_closeTab()));
2812 connect(closeButton, &QAbstractButton::clicked, this, [=] {
2813 closeTab();
2814 });
2815 setTabButton(i, closeSide, closeButton);
2816 }
2817 if (newButtons)
2818 d->layoutTabs();
2819 }
2820 update();
2821 }
2822
2823 /*!
2824 \enum KCustomTabBar::ButtonPosition
2825 \since 4.5
2826
2827 This enum type lists the location of the widget on a tab.
2828
2829 \value LeftSide Left side of the tab.
2830
2831 \value RightSide Right side of the tab.
2832
2833 */
2834
2835 /*!
2836 \enum KCustomTabBar::SelectionBehavior
2837 \since 4.5
2838
2839 This enum type lists the behavior of KCustomTabBar when a tab is removed
2840 and the tab being removed is also the current tab.
2841
2842 \value SelectLeftTab Select the tab to the left of the one being removed.
2843
2844 \value SelectRightTab Select the tab to the right of the one being removed.
2845
2846 \value SelectPreviousTab Select the previously selected tab.
2847
2848 */
2849
2850 /*!
2851 \property KCustomTabBar::selectionBehaviorOnRemove
2852 \brief What tab should be set as current when removeTab is called if
2853 the removed tab is also the current tab.
2854 \since 4.5
2855
2856 By default the value is SelectRightTab.
2857
2858 \sa removeTab()
2859 */
2860
2861 KCustomTabBar::SelectionBehavior KCustomTabBar::selectionBehaviorOnRemove() const
2862 {
2863 Q_D(const KCustomTabBar);
2864 return d->selectionBehaviorOnRemove;
2865 }
2866
2867 void KCustomTabBar::setSelectionBehaviorOnRemove(KCustomTabBar::SelectionBehavior behavior)
2868 {
2869 Q_D(KCustomTabBar);
2870 d->selectionBehaviorOnRemove = behavior;
2871 }
2872
2873 /*!
2874 \property KCustomTabBar::expanding
2875 \brief When expanding is true KCustomTabBar will expand the tabs to use the empty space.
2876 \since 4.5
2877
2878 By default the value is true.
2879
2880 \sa QTabWidget::documentMode
2881 */
2882
2883 bool KCustomTabBar::expanding() const
2884 {
2885 Q_D(const KCustomTabBar);
2886 return d->expanding;
2887 }
2888
2889 void KCustomTabBar::setExpanding(bool enabled)
2890 {
2891 Q_D(KCustomTabBar);
2892 if (d->expanding == enabled)
2893 return;
2894 d->expanding = enabled;
2895 d->layoutTabs();
2896 }
2897
2898 /*!
2899 \property KCustomTabBar::movable
2900 \brief This property holds whether the user can move the tabs
2901 within the tabbar area.
2902
2903 \since 4.5
2904
2905 By default, this property is \c false;
2906 */
2907
2908 bool KCustomTabBar::isMovable() const
2909 {
2910 Q_D(const KCustomTabBar);
2911 return d->movable;
2912 }
2913
2914 void KCustomTabBar::setMovable(bool movable)
2915 {
2916 Q_D(KCustomTabBar);
2917 d->movable = movable;
2918 }
2919
2920 /*!
2921 \property KCustomTabBar::documentMode
2922 \brief Whether or not the tab bar is rendered in a mode suitable for the main window.
2923 \since 4.5
2924
2925 This property is used as a hint for styles to draw the tabs in a different
2926 way then they would normally look in a tab widget. On \macos this will
2927 look similar to the tabs in Safari or Sierra's Terminal.app.
2928
2929 \sa QTabWidget::documentMode
2930 */
2931 bool KCustomTabBar::documentMode() const
2932 {
2933 return d_func()->documentMode;
2934 }
2935
2936 void KCustomTabBar::setDocumentMode(bool enabled)
2937 {
2938 Q_D(KCustomTabBar);
2939
2940 d->documentMode = enabled;
2941 d->updateMacBorderMetrics();
2942 }
2943
2944 /*!
2945 \property KCustomTabBar::autoHide
2946 \brief If true, the tab bar is automatically hidden when it contains less
2947 than 2 tabs.
2948 \since 5.4
2949
2950 By default, this property is false.
2951
2952 \sa QWidget::visible
2953 */
2954
2955 bool KCustomTabBar::autoHide() const
2956 {
2957 Q_D(const KCustomTabBar);
2958 return d->autoHide;
2959 }
2960
2961 void KCustomTabBar::setAutoHide(bool hide)
2962 {
2963 Q_D(KCustomTabBar);
2964 if (d->autoHide == hide)
2965 return;
2966
2967 d->autoHide = hide;
2968 if (hide)
2969 d->autoHideTabs();
2970 else
2971 setVisible(true);
2972 }
2973
2974 /*!
2975 \property KCustomTabBar::changeCurrentOnDrag
2976 \brief If true, then the current tab is automatically changed when dragging
2977 over the tabbar.
2978 \since 5.4
2979
2980 \note You should also set acceptDrops property to true to make this feature
2981 work.
2982
2983 By default, this property is false.
2984 */
2985
2986 bool KCustomTabBar::changeCurrentOnDrag() const
2987 {
2988 Q_D(const KCustomTabBar);
2989 return d->changeCurrentOnDrag;
2990 }
2991
2992 void KCustomTabBar::setChangeCurrentOnDrag(bool change)
2993 {
2994 Q_D(KCustomTabBar);
2995 d->changeCurrentOnDrag = change;
2996 if (!change)
2997 d->killSwitchTabTimer();
2998 }
2999
3000 /*!
3001 Sets \a widget on the tab \a index. The widget is placed
3002 on the left or right hand side depending upon the \a position.
3003 \since 4.5
3004
3005 Any previously set widget in \a position is hidden.
3006
3007 The tab bar will take ownership of the widget and so all widgets set here
3008 will be deleted by the tab bar when it is destroyed unless you separately
3009 reparent the widget after setting some other widget (or 0).
3010
3011 \sa tabsClosable()
3012 */
3013 void KCustomTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget)
3014 {
3015 Q_D(KCustomTabBar);
3016 if (index < 0 || index >= d->tabList.count())
3017 return;
3018 if (widget) {
3019 widget->setParent(this);
3020 // make sure our left and right widgets stay on top
3021 widget->lower();
3022 widget->show();
3023 }
3024 if (position == LeftSide) {
3025 if (d->tabList[index].leftWidget)
3026 d->tabList[index].leftWidget->hide();
3027 d->tabList[index].leftWidget = widget;
3028 } else {
3029 if (d->tabList[index].rightWidget)
3030 d->tabList[index].rightWidget->hide();
3031 d->tabList[index].rightWidget = widget;
3032 }
3033 d->layoutTabs();
3034 d->refresh();
3035 update();
3036 }
3037
3038 /*!
3039 Returns the widget set a tab \a index and \a position or 0 if
3040 one is not set.
3041 */
3042 QWidget *KCustomTabBar::tabButton(int index, ButtonPosition position) const
3043 {
3044 Q_D(const KCustomTabBar);
3045 if (index < 0 || index >= d->tabList.count())
3046 return 0;
3047 if (position == LeftSide)
3048 return d->tabList.at(index).leftWidget;
3049 else
3050 return d->tabList.at(index).rightWidget;
3051 }
3052
3053 #ifndef QT_NO_ACCESSIBILITY
3054 /*!
3055 Sets the accessibleName of the tab at position \a index to \a name.
3056 */
3057 void KCustomTabBar::setAccessibleTabName(int index, const QString &name)
3058 {
3059 Q_D(KCustomTabBar);
3060 if (KCustomTabBarPrivate::Tab *tab = d->at(index)) {
3061 tab->accessibleName = name;
3062 QAccessibleEvent event(this, QAccessible::NameChanged);
3063 event.setChild(index);
3064 QAccessible::updateAccessibility(&event);
3065 }
3066 }
3067
3068 /*!
3069 Returns the accessibleName of the tab at position \a index, or an empty
3070 string if \a index is out of range.
3071 */
3072 QString KCustomTabBar::accessibleTabName(int index) const
3073 {
3074 Q_D(const KCustomTabBar);
3075 if (const KCustomTabBarPrivate::Tab *tab = d->at(index))
3076 return tab->accessibleName;
3077 return QString();
3078 }
3079 #endif // QT_NO_ACCESSIBILITY
3080
3081 CloseButton::CloseButton(QWidget *parent)
3082 : QAbstractButton(parent)
3083 {
3084 setFocusPolicy(Qt::NoFocus);
3085 #ifndef QT_NO_CURSOR
3086 setCursor(Qt::ArrowCursor);
3087 #endif
3088 #ifndef QT_NO_TOOLTIP
3089 setToolTip(tr("Close Tab"));
3090 #endif
3091 resize(sizeHint());
3092 }
3093
3094 QSize CloseButton::sizeHint() const
3095 {
3096 ensurePolished();
3097 int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, this);
3098 int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, this);
3099 return QSize(width, height);
3100 }
3101
3102 QSize CloseButton::minimumSizeHint() const
3103 {
3104 return sizeHint();
3105 }
3106
3107 void CloseButton::enterEvent(QEnterEvent *event)
3108 {
3109 if (isEnabled())
3110 update();
3111 QAbstractButton::enterEvent(event);
3112 }
3113
3114 void CloseButton::leaveEvent(QEvent *event)
3115 {
3116 if (isEnabled())
3117 update();
3118 QAbstractButton::leaveEvent(event);
3119 }
3120
3121 void CloseButton::paintEvent(QPaintEvent *)
3122 {
3123 QPainter p(this);
3124 QStyleOption opt;
3125 opt.initFrom(this);
3126 opt.state |= QStyle::State_AutoRaise;
3127 if (isEnabled() && underMouse() && !isChecked() && !isDown())
3128 opt.state |= QStyle::State_Raised;
3129 if (isChecked())
3130 opt.state |= QStyle::State_On;
3131 if (isDown())
3132 opt.state |= QStyle::State_Sunken;
3133
3134 if (const KCustomTabBar *tb = qobject_cast<const KCustomTabBar *>(parent())) {
3135 int index = tb->currentIndex();
3136 KCustomTabBar::ButtonPosition position = (KCustomTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, tb);
3137 if (tb->tabButton(index, position) == this)
3138 opt.state |= QStyle::State_Selected;
3139 }
3140
3141 style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
3142 }
3143
3144 #if QT_CONFIG(animation)
3145 void KCustomTabBarPrivate::Tab::TabBarAnimation::updateCurrentValue(const QVariant &current)
3146 {
3147 priv->moveTab(priv->tabList.indexOf(*tab), current.toInt());
3148 }
3149
3150 void KCustomTabBarPrivate::Tab::TabBarAnimation::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State)
3151 {
3152 if (newState == Stopped)
3153 priv->moveTabFinished(priv->tabList.indexOf(*tab));
3154 }
3155 #endif
3156
3157 QT_END_NAMESPACE
3158
3159 #include "kcustomtabbar.moc"
3160 #include "moc_kcustomtabbar.cpp"