Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qmacstyle_mac.mm
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5/*
6 Note: The qdoc comments for QMacStyle are contained in
7 .../doc/src/qstyles.qdoc.
8*/
9
10#include <AppKit/AppKit.h>
11
14
15#define QMAC_QAQUASTYLE_SIZE_CONSTRAIN
16//#define DEBUG_SIZE_CONSTRAINT
17
18#include <QtCore/qoperatingsystemversion.h>
19#include <QtCore/qvariant.h>
20#include <QtCore/qvarlengtharray.h>
21#include <QtCore/qloggingcategory.h>
22
23#include <QtCore/private/qcore_mac_p.h>
24
25#include <QtGui/qpainterpath.h>
26#include <QtGui/qstylehints.h>
27#include <QtGui/private/qcoregraphics_p.h>
28#include <QtGui/private/qappleiconengine_p.h>
29#include <QtGui/private/qfontengine_p.h>
30#include <QtGui/qpa/qplatformfontdatabase.h>
31#include <QtGui/qpa/qplatformtheme.h>
32#include <QtGui/qpa/qplatformwindow_p.h>
33
34#include <QtWidgets/private/qstyleanimation_p.h>
35#include <QtWidgets/private/qmainwindowlayout_p.h>
36
37#if QT_CONFIG(mdiarea)
38#include <QtWidgets/qmdisubwindow.h>
39#endif
40#if QT_CONFIG(scrollbar)
41#include <QtWidgets/qscrollbar.h>
42#endif
43#if QT_CONFIG(tabbar)
44#include <QtWidgets/private/qtabbar_p.h>
45#endif
46#if QT_CONFIG(wizard)
47#include <QtWidgets/qwizard.h>
48#endif
49
50#include <QtGui/private/qmacstyle_p.h>
51
52#include <iterator>
53#include <cmath>
54
56
57Q_STATIC_LOGGING_CATEGORY(lcMacStyle, "qt.widgets.styles.macos");
58
59@interface QT_MANGLE_NAMESPACE(QIndeterminateProgressIndicator) : NSProgressIndicator
60
61@property (readonly, nonatomic) NSInteger animators;
62
63- (instancetype)init;
64
65- (void)startAnimation;
66- (void)stopAnimation;
67
68- (void)drawWithFrame:(CGRect)rect inView:(NSView *)view;
69
70@end
71
72QT_NAMESPACE_ALIAS_OBJC_CLASS(QIndeterminateProgressIndicator);
73
74@implementation QIndeterminateProgressIndicator
75
76- (instancetype)init
77{
78 if ((self = [super init])) {
79 _animators = 0;
80 self.indeterminate = YES;
81 self.usesThreadedAnimation = NO;
82 self.alphaValue = 0.0;
83 }
84
85 return self;
86}
87
88- (void)startAnimation
89{
90 if (_animators == 0) {
91 self.hidden = NO;
92 [super startAnimation:self];
93 }
94 ++_animators;
95}
96
97- (void)stopAnimation
98{
99 --_animators;
100 if (_animators == 0) {
101 [super stopAnimation:self];
102 self.hidden = YES;
103 [self removeFromSuperviewWithoutNeedingDisplay];
104 }
105}
106
107- (void)drawWithFrame:(CGRect)rect inView:(NSView *)view
108{
109 // The alphaValue change is not strictly necessary, but feels safer.
110 self.alphaValue = 1.0;
111 if (self.superview != view)
112 [view addSubview:self];
113 if (!CGRectEqualToRect(self.frame, rect))
114 self.frame = rect;
115 [self drawRect:rect];
116 self.alphaValue = 0.0;
117}
118
119@end
120
121@interface QT_MANGLE_NAMESPACE(QVerticalSplitView) : NSSplitView
122- (BOOL)isVertical;
123@end
124
125QT_NAMESPACE_ALIAS_OBJC_CLASS(QVerticalSplitView);
126
127@implementation QVerticalSplitView
128- (BOOL)isVertical
129{
130 return YES;
131}
132@end
133
134// See render code in drawPrimitive(PE_FrameTabWidget)
135@interface QT_MANGLE_NAMESPACE(QDarkNSBox) : NSBox
136@end
137
138QT_NAMESPACE_ALIAS_OBJC_CLASS(QDarkNSBox);
139
140@implementation QDarkNSBox
141- (instancetype)init
142{
143 if ((self = [super init])) {
144 self.title = @"";
145 self.titlePosition = NSNoTitle;
146 self.boxType = NSBoxCustom;
147 self.cornerRadius = 3;
148 if (qt_apple_runningWithLiquidGlass())
149 self.cornerRadius = 11;
150 self.borderColor = [NSColor.controlColor colorWithAlphaComponent:0.1];
151 self.fillColor = [NSColor.darkGrayColor colorWithAlphaComponent:0.2];
152 }
153
154 return self;
155}
156
157- (void)drawRect:(NSRect)rect
158{
159 [super drawRect:rect];
160}
161@end
162
163QT_BEGIN_NAMESPACE
164
165// The following constants are used for adjusting the size
166// of push buttons so that they are drawn inside their bounds.
167const int QMacStylePrivate::PushButtonLeftOffset = 6;
168const int QMacStylePrivate::PushButtonRightOffset = 12;
169const int QMacStylePrivate::PushButtonContentPadding = 6;
170
172 QMacStylePrivate::PushButtonLeftOffset, 5, 5
173};
174
175QVector<QPointer<QObject> > QMacStylePrivate::scrollBars;
176
177static inline bool isDarkMode()
178{
179 return QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark;
180}
181
182#if QT_CONFIG(tabwidget)
183/*
184 Since macOS 10.14 AppKit is using transparency more extensively, especially for the
185 dark theme. Inactive buttons, for example, are semi-transparent. And we use them to
186 draw tab widget's tab bar. The combination of NSBox (also a part of tab widget)
187 and these transparent buttons gives us an undesired side-effect: an outline of
188 NSBox is visible through transparent buttons. To avoid this, we have this hack below:
189 we clip the area where the line would be visible through the buttons. The area we
190 want to clip away can be described as an intersection of the option's rect and
191 the tab widget's tab bar rect. But some adjustments are required, since those rects
192 are anyway adjusted during the rendering and they are not exactly what you'll see on
193 the screen. Thus this switch-statement inside.
194*/
195static void clipTabBarFrame(const QStyleOption *option, const QMacStyle *style, CGContextRef ctx)
196{
197 Q_ASSERT(option);
198 Q_ASSERT(style);
199 Q_ASSERT(ctx);
200
201 if (isDarkMode() || qt_apple_runningWithLiquidGlass()) {
202 QTabWidget *tabWidget = qobject_cast<QTabWidget *>(option->styleObject);
203 Q_ASSERT(tabWidget);
204 QRect tabBarRect = style->subElementRect(QStyle::SE_TabWidgetTabBar, option, tabWidget);
205 if (!qt_apple_runningWithLiquidGlass())
206 tabBarRect.adjust(2, 0, -3, 0);
207 switch (tabWidget->tabPosition()) {
208 case QTabWidget::South:
209 tabBarRect.setY(tabBarRect.y() + tabBarRect.height() / 2);
210 if (qt_apple_runningWithLiquidGlass())
211 tabBarRect.adjust(0, 1, 0, 0);
212 break;
213 case QTabWidget::North:
214 case QTabWidget::West:
215 if (!qt_apple_runningWithLiquidGlass())
216 tabBarRect = tabBarRect.adjusted(0, 2, 0, -2);
217 break;
218 case QTabWidget::East:
219 tabBarRect = tabBarRect.adjusted(tabBarRect.width() / 2, 2, tabBarRect.width() / 2, -2);
220 if (qt_apple_runningWithLiquidGlass())
221 tabBarRect.adjust(1, -2, 0, 2);
222 }
223
224 // TODO: now that we also use it for light mode (Tahoe and above),
225 // find a better fitting clip path.
226 const QRegion clipPath = QRegion(option->rect) - tabBarRect;
227 QVarLengthArray<CGRect, 3> cgRects;
228 for (const QRect &qtRect : clipPath)
229 cgRects.push_back(qtRect.toCGRect());
230 if (cgRects.size())
231 CGContextClipToRects(ctx, &cgRects[0], size_t(cgRects.size()));
232 }
233}
234#endif
235
236static const QColor titlebarSeparatorLineActive(111, 111, 111);
237static const QColor titlebarSeparatorLineInactive(131, 131, 131);
238static const QColor darkModeSeparatorLine(88, 88, 88);
239
240static const int DisclosureOffset = 4;
241
245
246// Tab bar colors
247// active: window is active
248// selected: tab is selected
249// hovered: tab is hovered
250
251#if QT_CONFIG(tabbar)
252static const QColor lightTabBarTabBackgroundActive(190, 190, 190);
253static const QColor darkTabBarTabBackgroundActive(38, 38, 38);
254static const QColor tabBarTabBackgroundActive() { return isDarkMode() ? darkTabBarTabBackgroundActive : lightTabBarTabBackgroundActive; }
255
256static const QColor lightTabBarTabBackgroundActiveHovered(178, 178, 178);
257static const QColor darkTabBarTabBackgroundActiveHovered(32, 32, 32);
258static const QColor tabBarTabBackgroundActiveHovered() { return isDarkMode() ? darkTabBarTabBackgroundActiveHovered : lightTabBarTabBackgroundActiveHovered; }
259
260static const QColor lightTabBarTabBackgroundActiveSelected(211, 211, 211);
261static const QColor darkTabBarTabBackgroundActiveSelected(52, 52, 52);
262static const QColor tabBarTabBackgroundActiveSelected() { return isDarkMode() ? darkTabBarTabBackgroundActiveSelected : lightTabBarTabBackgroundActiveSelected; }
263
264static const QColor lightTabBarTabBackground(227, 227, 227);
265static const QColor darkTabBarTabBackground(38, 38, 38);
266static const QColor tabBarTabBackground() { return isDarkMode() ? darkTabBarTabBackground : lightTabBarTabBackground; }
267
268static const QColor lightTabBarTabBackgroundSelected(246, 246, 246);
269static const QColor darkTabBarTabBackgroundSelected(52, 52, 52);
270static const QColor tabBarTabBackgroundSelected() { return isDarkMode() ? darkTabBarTabBackgroundSelected : lightTabBarTabBackgroundSelected; }
271
272static const QColor lightTabBarTabLineActive(160, 160, 160);
273static const QColor darkTabBarTabLineActive(90, 90, 90);
274static const QColor tabBarTabLineActive() { return isDarkMode() ? darkTabBarTabLineActive : lightTabBarTabLineActive; }
275
276static const QColor lightTabBarTabLineActiveHovered(150, 150, 150);
277static const QColor darkTabBarTabLineActiveHovered(90, 90, 90);
278static const QColor tabBarTabLineActiveHovered() { return isDarkMode() ? darkTabBarTabLineActiveHovered : lightTabBarTabLineActiveHovered; }
279
280static const QColor lightTabBarTabLine(210, 210, 210);
281static const QColor darkTabBarTabLine(90, 90, 90);
282static const QColor tabBarTabLine() { return isDarkMode() ? darkTabBarTabLine : lightTabBarTabLine; }
283
284static const QColor lightTabBarTabLineSelected(189, 189, 189);
285static const QColor darkTabBarTabLineSelected(90, 90, 90);
286static const QColor tabBarTabLineSelected() { return isDarkMode() ? darkTabBarTabLineSelected : lightTabBarTabLineSelected; }
287
288static const QColor tabBarCloseButtonBackgroundHovered(162, 162, 162);
289static const QColor tabBarCloseButtonBackgroundPressed(153, 153, 153);
290static const QColor tabBarCloseButtonBackgroundSelectedHovered(192, 192, 192);
291static const QColor tabBarCloseButtonBackgroundSelectedPressed(181, 181, 181);
292static const QColor tabBarCloseButtonCross(100, 100, 100);
293static const QColor tabBarCloseButtonCrossSelected(115, 115, 115);
294
295static const int closeButtonSize = 14;
296static const qreal closeButtonCornerRadius = 2.0;
297#endif // QT_CONFIG(tabbar)
298
299// Geometry of the bezel an NSTextField draws with Liquid Glass. The same
300// values apply to all control sizes.
303
304// Starting with Tahoe's Liquid Glass, the rounded/square bezel of an NSTextField is
305// drawn using an opaque system material that does not respect NSTextFieldCell's
306// 'backgroundColor' in either 'Light' or 'Dark' mode, unlike before. If the widget
307// asks for a background color other than the system's default text background, we
308// have to paint that color ourselves, see drawTextFieldCustomBackground().
309static bool hasCustomTextFieldBackground(const QPalette &palette)
310{
311 if (!qt_apple_runningWithLiquidGlass())
312 return false;
313 return palette.brush(QPalette::Base).color() != qt_mac_toQColor(NSColor.textBackgroundColor);
314}
315
316// Paints 'color' inside the bezel drawn by an NSTextField, following the bezel's
317// rounded shape and leaving its border visible.
318static void drawTextFieldCustomBackground(QPainter *p, const QRect &rect, const QColor &color)
319{
320 const QRectF bgRect = QRectF(rect).adjusted(textFieldBezelBorderWidth, textFieldBezelBorderWidth,
321 -textFieldBezelBorderWidth, -textFieldBezelBorderWidth);
322 const qreal radius = textFieldBezelCornerRadius - textFieldBezelBorderWidth;
323 QPainterPath path;
324 path.addRoundedRect(bgRect, radius, radius);
325 p->save();
326 p->setRenderHint(QPainter::Antialiasing);
327 p->fillPath(path, color);
328 p->restore();
329}
330
331#if QT_CONFIG(accessibility) // This ifdef to avoid "unused function" warning.
332QBrush brushForToolButton(bool isOnKeyWindow)
333{
334 // When a toolbutton in a toolbar is in the 'ON' state, we draw a
335 // partially transparent background. The colors must be different
336 // for 'Aqua' and 'DarkAqua' appearances though.
337 if (isDarkMode())
338 return isOnKeyWindow ? QColor(73, 73, 73, 100) : QColor(56, 56, 56, 100);
339
340 return isOnKeyWindow ? QColor(0, 0, 0, 28) : QColor(0, 0, 0, 21);
341}
342#endif // QT_CONFIG(accessibility)
343
344static const int headerSectionArrowHeight = 6;
345static const int headerSectionSeparatorInset = 2;
346
347// One for each of QStyleHelper::WidgetSizePolicy
349 { 0.5, 2, 3.5, 4 },
350 { 0.5, 1, 2.5, 4 },
351 { 0.5, 1.5, 2.5, 3.5 }
352};
353
355 { 0.5, -1, 0.5, 2 },
356 { 0.5, -1.5, 0.5, 2.5 },
357 { 0.5, 0, 0.5, 1 }
358};
359
361 { 1.5, -1.5, 1.5, 4.5 },
362 { 1.5, -1, 1.5, 4 },
363 { 1.5, 0.5, 1.5, 2.5 }
364};
365
366void adjustPushButtonShadowMargins(QRectF &rect, QStyleHelper::WidgetSizePolicy size)
367{
368 if (qt_apple_runningWithLiquidGlass()) {
369 static const QMarginsF margins[3] = {{1.5, -2.5, 1.5, 1.5},
370 {1.5, -1, 1.5, 4.0},
371 {1.5, -0.5, 1.5, 2.5}};
372 rect -= margins[size];
373 } else {
374 rect -= pushButtonShadowMargins[size];
375 }
376}
377
378// These are frame heights as reported by Xcode 9's Interface Builder
379// and determined experimentally.
380
381static const qreal comboBoxDefaultHeight[3] = {
382 26, 22, 19
383};
384
386 32, 28, 24
387};
388
390 26, 22, 15
391};
392
393static const int toolButtonArrowSize = 7;
394static const int toolButtonArrowMargin = 2;
395
396static const qreal focusRingWidth = 3.5;
397
398static bool setupScroller(NSScroller *scroller, const QStyleOptionSlider *sb)
399{
400 const qreal length = sb->maximum - sb->minimum + sb->pageStep;
401 if (qFuzzyIsNull(length))
402 return false;
403 const qreal proportion = sb->pageStep / length;
404 const qreal range = qreal(sb->maximum - sb->minimum);
405 qreal value = range ? qreal(sb->sliderValue - sb->minimum) / range : 0;
406 if (sb->orientation == Qt::Horizontal && sb->direction == Qt::RightToLeft)
407 value = 1.0 - value;
408
409 scroller.frame = sb->rect.toCGRect();
410 scroller.floatValue = value;
411 scroller.knobProportion = proportion;
412 return true;
413}
414
415static bool setupSlider(NSSlider *slider, const QStyleOptionSlider *sl)
416{
417 if (sl->minimum >= sl->maximum)
418 return false;
419
420 NSSliderCell *cell = static_cast<NSSliderCell *>(slider.cell);
421 const auto oldRect = [cell knobRectFlipped:slider.isFlipped];
422 const auto oldValue = slider.intValue;
423 slider.frame = sl->rect.toCGRect();
424
425 slider.minValue = sl->minimum;
426 slider.maxValue = sl->maximum;
427 slider.intValue = sl->sliderPosition;
428 slider.enabled = sl->state & QStyle::State_Enabled;
429 if (sl->tickPosition != QSlider::NoTicks) {
430 // Set numberOfTickMarks, but TicksBothSides will be treated differently
431 int interval = sl->tickInterval;
432 if (interval == 0) {
433 interval = sl->pageStep;
434 if (interval == 0)
435 interval = sl->singleStep;
436 if (interval == 0)
437 interval = 1; // return false?
438 }
439 slider.numberOfTickMarks = 1 + ((sl->maximum - sl->minimum) / interval);
440
441 const bool ticksAbove = sl->tickPosition == QSlider::TicksAbove;
442 if (sl->orientation == Qt::Horizontal)
443 slider.tickMarkPosition = ticksAbove ? NSTickMarkPositionAbove : NSTickMarkPositionBelow;
444 else
445 slider.tickMarkPosition = ticksAbove ? NSTickMarkPositionLeading : NSTickMarkPositionTrailing;
446 } else {
447 slider.numberOfTickMarks = 0;
448 }
449
450 // Ensure the values set above are reflected when asking
451 // the cell for its metrics and to draw itself.
452 [slider layoutSubtreeIfNeeded];
453 const auto updatedRect = [cell knobRectFlipped:slider.isFlipped];
454 if (CGRectEqualToRect(oldRect, updatedRect) && slider.intValue != oldValue) {
455 // Apparently, some stale cached geometry ...
456 slider.cell = [cell copy];
457 }
458
459 return true;
460}
461
462static bool isInMacUnifiedToolbarArea(QWidget *widget, int windowY)
463{
464 auto *mainWindow = qobject_cast<QMainWindow *>(widget);
465 if (!mainWindow || !mainWindow->unifiedTitleAndToolBarOnMac())
466 return false;
467
468 QMainWindowLayout *layout = static_cast<QMainWindowLayout*>(mainWindow->layout());
469 return layout->testUnifiedToolBarAreaPosition(windowY);
470}
471
472#if QT_CONFIG(tabbar)
473static void drawTabCloseButton(QPainter *p, bool hover, bool selected, bool pressed, bool documentMode)
474{
475 p->setRenderHints(QPainter::Antialiasing);
476 QRect rect(0, 0, closeButtonSize, closeButtonSize);
477 const int width = rect.width();
478 const int height = rect.height();
479
480 if (hover) {
481 // draw background circle
482 QColor background;
483 if (selected) {
484 if (documentMode)
485 background = pressed ? tabBarCloseButtonBackgroundSelectedPressed : tabBarCloseButtonBackgroundSelectedHovered;
486 else
487 background = QColor(255, 255, 255, pressed ? 150 : 100); // Translucent white
488 } else {
489 background = pressed ? tabBarCloseButtonBackgroundPressed : tabBarCloseButtonBackgroundHovered;
490 if (!documentMode)
491 background = background.lighter(pressed ? 135 : 140); // Lighter tab background, lighter color
492 }
493
494 p->setPen(Qt::transparent);
495 p->setBrush(background);
496 p->drawRoundedRect(rect, closeButtonCornerRadius, closeButtonCornerRadius);
497 }
498
499 // draw cross
500 const int margin = 3;
501 QPen crossPen;
502 crossPen.setColor(selected ? (documentMode ? tabBarCloseButtonCrossSelected : Qt::white) : tabBarCloseButtonCross);
503 crossPen.setWidthF(1.1);
504 crossPen.setCapStyle(Qt::FlatCap);
505 p->setPen(crossPen);
506 p->drawLine(margin, margin, width - margin, height - margin);
507 p->drawLine(margin, height - margin, width - margin, margin);
508}
509
510QRect rotateTabPainter(QPainter *p, QTabBar::Shape shape, QRect tabRect)
511{
512 const auto tabDirection = QMacStylePrivate::tabDirection(shape);
513 if (QMacStylePrivate::verticalTabs(tabDirection)) {
514 int newX, newY, newRot;
515 if (tabDirection == QMacStylePrivate::East) {
516 newX = tabRect.width();
517 newY = tabRect.y();
518 newRot = 90;
519 } else {
520 newX = 0;
521 newY = tabRect.y() + tabRect.height();
522 newRot = -90;
523 }
524 tabRect.setRect(0, 0, tabRect.height(), tabRect.width());
525 QTransform transform;
526 transform.translate(newX, newY);
527 transform.rotate(newRot);
528 p->setTransform(transform, true);
529 }
530 return tabRect;
531}
532
533void drawTabShape(QPainter *p, const QStyleOptionTab *tabOpt, bool isUnified, int tabOverlap)
534{
535 QRect rect = tabOpt->rect;
536 if (QMacStylePrivate::verticalTabs(QMacStylePrivate::tabDirection(tabOpt->shape)))
537 rect = rect.adjusted(-tabOverlap, 0, 0, 0);
538 else
539 rect = rect.adjusted(0, -tabOverlap, 0, 0);
540
541 p->translate(rect.x(), rect.y());
542 rect.moveLeft(0);
543 rect.moveTop(0);
544 const QRect tabRect = rotateTabPainter(p, tabOpt->shape, rect);
545
546 const int width = tabRect.width();
547 const int height = tabRect.height();
548 const bool active = (tabOpt->state & QStyle::State_Active);
549 const bool selected = (tabOpt->state & QStyle::State_Selected);
550
551 const QRect bodyRect(1, 2, width - 2, height - 3);
552 const QRect topLineRect(1, 0, width - 2, 1);
553 const QRect bottomLineRect(1, height - 1, width - 2, 1);
554 if (selected) {
555 // fill body
556 if (tabOpt->documentMode && isUnified) {
557 p->save();
558 p->setCompositionMode(QPainter::CompositionMode_Source);
559 p->fillRect(tabRect, QColor(Qt::transparent));
560 p->restore();
561 } else if (active) {
562 p->fillRect(bodyRect, tabBarTabBackgroundActiveSelected());
563 // top line
564 p->fillRect(topLineRect, tabBarTabLineSelected());
565 } else {
566 p->fillRect(bodyRect, tabBarTabBackgroundSelected());
567 }
568 } else {
569 // when the mouse is over non selected tabs they get a new color
570 const bool hover = (tabOpt->state & QStyle::State_MouseOver);
571 if (hover) {
572 // fill body
573 p->fillRect(bodyRect, tabBarTabBackgroundActiveHovered());
574 // bottom line
575 p->fillRect(bottomLineRect, isDarkMode() ? QColor(Qt::black) : tabBarTabLineActiveHovered());
576 }
577 }
578
579 // separator lines between tabs
580 const QRect leftLineRect(0, 1, 1, height - 2);
581 const QRect rightLineRect(width - 1, 1, 1, height - 2);
582 const QColor separatorLineColor = active ? tabBarTabLineActive() : tabBarTabLine();
583 p->fillRect(leftLineRect, separatorLineColor);
584 p->fillRect(rightLineRect, separatorLineColor);
585}
586
587void drawTabBase(QPainter *p, const QStyleOptionTabBarBase *tbb, const QWidget *w)
588{
589 QRect r = tbb->rect;
590 if (QMacStylePrivate::verticalTabs(QMacStylePrivate::tabDirection(tbb->shape)))
591 r.setWidth(w->width());
592 else
593 r.setHeight(w->height());
594
595 const QRect tabRect = rotateTabPainter(p, tbb->shape, r);
596 const int width = tabRect.width();
597 const int height = tabRect.height();
598 const bool active = (tbb->state & QStyle::State_Active);
599
600 // fill body
601 const QRect bodyRect(0, 1, width, height - 1);
602 const QColor bodyColor = active ? tabBarTabBackgroundActive() : tabBarTabBackground();
603 p->fillRect(bodyRect, bodyColor);
604
605 // top line
606 const QRect topLineRect(0, 0, width, 1);
607 const QColor topLineColor = active ? tabBarTabLineActive() : tabBarTabLine();
608 p->fillRect(topLineRect, topLineColor);
609
610 // bottom line
611 const QRect bottomLineRect(0, height - 1, width, 1);
612 bool isDocument = false;
613 if (const QTabBar *tabBar = qobject_cast<const QTabBar*>(w))
614 isDocument = tabBar->documentMode();
615 const QColor bottomLineColor = isDocument && isDarkMode() ? QColor(Qt::black) : active ? tabBarTabLineActive() : tabBarTabLine();
616 p->fillRect(bottomLineRect, bottomLineColor);
617}
618#endif
619
620void drawTickMarks(CGContextRef ctx, NSSlider *nsSlider, const QStyleOptionSlider *sliderOpt)
621{
622 // With the Liquid Glass enabled NSSliderCell -drawTickMarks
623 // seems to be a noop. This method never gets called by the
624 // AppKit, even if the UI compatibility was requested (so we call it
625 // explicitly in this case). Without compatibility mode enabled
626 // we manually draw ticks in a new style (tiny circles, not lines).
627
628 // FIXME: for now we ignore 'ticks both sides' option - such ticks don't
629 // exist natively and the old hack was quite ugly looking, it's not worth
630 // reproducing it.
631
632 Q_UNUSED(sliderOpt);
633
634 Q_ASSERT(ctx);
635 Q_ASSERT(nsSlider);
636 Q_ASSERT(sliderOpt);
637
638 NSSliderCell *cell = static_cast<NSSliderCell *>(nsSlider.cell);
639 if (!cell.numberOfTickMarks)
640 return;
641
642 Q_ASSERT(cell.numberOfTickMarks > 1); // See the logic in the 'setupSlider'.
643
644 CGContextSaveGState(ctx); // [PUSH ...
645
646 [[NSColor.grayColor colorWithAlphaComponent:0.6] setFill];
647 // NOTE: with the new style slider ticks start not on the
648 // left on the slider's bar, but in the mid X of the slider's knob
649 // when the knob is at the slider's minimum. We draw them in 'old style'
650 // coordinates.
651 const auto barRect = [cell barRectFlipped:nsSlider.isFlipped];
652 const auto knobRect = [cell knobRectFlipped:nsSlider.isFlipped];
653 auto tickRect = [cell rectOfTickMarkAtIndex:0];
654 CGFloat step = (barRect.size.width - tickRect.size.width) / (nsSlider.numberOfTickMarks - 1);
655 // Note: tick position seems to be ignored, it is always 'below'.
656 tickRect.origin.y = CGRectGetMidY(knobRect);
657
658 const auto tickPos = sliderOpt->tickPosition;
659 // Native slider does not have 'Both Sides' and with the new style such ticks make
660 // little sense, so treat them as 'Below'.
661 if (tickPos == QSlider::TicksBelow || tickPos == QSlider::TicksBothSides)
662 tickRect.origin.y += knobRect.size.height / 2 * 0.8; // The knob overlaps ticks.
663 else // Above or Left, does not matter.
664 tickRect.origin.y -= knobRect.size.height / 2 * 0.8;
665
666 tickRect.origin.x = barRect.origin.x + tickRect.size.width / 2.;
667
668 if (nsSlider.isVertical) {
669 tickRect.origin.y = barRect.origin.y + tickRect.size.height / 2.;
670
671 tickRect.origin.x = CGRectGetMidX(barRect);
672 if (tickPos == QSlider::TicksRight)
673 tickRect.origin.x += knobRect.size.width / 2 * 0.8;
674 else // Left or both sides.
675 tickRect.origin.x -= knobRect.size.width / 2 * 0.8;
676 step = (barRect.size.height - tickRect.size.height) / (nsSlider.numberOfTickMarks - 1);
677 }
678
679 CGContextBeginPath(ctx);
680 for (NSInteger i = 0; i < cell.numberOfTickMarks; ++i) {
681 CGContextAddEllipseInRect(ctx, tickRect);
682 nsSlider.isVertical ? tickRect.origin.y += step : tickRect.origin.x += step;
683 }
684
685 CGContextClosePath(ctx);
686 CGContextFillPath(ctx);
687
688 CGContextRestoreGState(ctx); // POP]
689}
690
691void drawSliderKnob(CGContextRef ctx, NSSlider *slider)
692{
693 // Slider's knob/thumb with macOS Tahoe has a shadow, which is clipped
694 // on the min/max ends of a slider. Resetting/extending the current clip
695 // improves this, but gives a side-effect - shadow residuals around the
696 // slider's bar/groove after moving a knob - this area is not repainted
697 // when the knob is moving.
698 // The only solution for now is to manually draw the knob trying to
699 // reduce the clipping artefacts.
700
701 Q_ASSERT(ctx);
702 Q_ASSERT(slider);
703
704 NSSliderCell *cell = static_cast<NSSliderCell *>(slider.cell);
705
706 CGContextSaveGState(ctx); // [PUSH ...
707 const CGFloat blur = 3.; // More or less good-looking shadow ...
708 CGContextSetShadowWithColor(ctx, {}, blur, NSColor.grayColor.CGColor);
709 CGColorRef knobColor = NSColor.whiteColor.CGColor;
710 CGContextSetFillColorWithColor(ctx, knobColor);
711
712 // For a legacy-style 'tick slider' its knob is less square/round and
713 // more elongated. The slider cell reports a new style rect though
714 // so we always draw as a 'new style' slider.
715 auto knobRect = [cell knobRectFlipped:slider.isFlipped];
716 // Slider's knob has a slight shadow around it and it's clipped.
717 // We make the knob rectangle a bit smaller.
718 knobRect = CGRectInset(knobRect, 0.4, 0.4);
719
720 auto radius = knobRect.size.height;
721 if (radius > knobRect.size.width)
722 radius = knobRect.size.width;
723 radius /= 2.;
724
725 CGContextBeginPath(ctx);
726 QCFType<CGPathRef> knobPath = CGPathCreateWithRoundedRect(knobRect, radius, radius, nullptr);
727 CGContextAddPath(ctx, knobPath);
728
729 CGContextFillPath(ctx);
730
731 CGContextRestoreGState(ctx); // POP]
732}
733
734static QStyleHelper::WidgetSizePolicy getControlSize(const QStyleOption *option, const QWidget *widget)
735{
736 const auto wsp = QStyleHelper::widgetSizePolicy(widget, option);
737 if (wsp == QStyleHelper::SizeDefault)
738 return QStyleHelper::SizeLarge;
739
740 return wsp;
741}
742
743#if QT_CONFIG(treeview)
744static inline bool isTreeView(const QWidget *widget)
745{
746 return (widget && widget->parentWidget() &&
747 qobject_cast<const QTreeView *>(widget->parentWidget()));
748}
749#endif
750
751static QString qt_mac_removeMnemonics(const QString &original)
752{
753 QString returnText(original.size(), QChar(0));
754 int finalDest = 0;
755 int currPos = 0;
756 int l = original.length();
757 while (l) {
758 if (original.at(currPos) == QLatin1Char('&')) {
759 ++currPos;
760 --l;
761 if (l == 0)
762 break;
763 } else if (original.at(currPos) == QLatin1Char('(') && l >= 4 &&
764 original.at(currPos + 1) == QLatin1Char('&') &&
765 original.at(currPos + 2) != QLatin1Char('&') &&
766 original.at(currPos + 3) == QLatin1Char(')')) {
767 /* remove mnemonics its format is "\s*(&X)" */
768 int n = 0;
769 while (finalDest > n && returnText.at(finalDest - n - 1).isSpace())
770 ++n;
771 finalDest -= n;
772 currPos += 4;
773 l -= 4;
774 continue;
775 }
776 returnText[finalDest] = original.at(currPos);
777 ++currPos;
778 ++finalDest;
779 --l;
780 }
781 returnText.truncate(finalDest);
782 return returnText;
783}
784
785static bool qt_macWindowMainWindow(const QWidget *window)
786{
787 if (QWindow *w = window->windowHandle()) {
788 if (auto *cocoaWindow = w->nativeInterface<QNativeInterface::Private::QCocoaWindow>()) {
789 if (NSWindow *nswindow = cocoaWindow->view().window) {
790 return [nswindow isMainWindow];
791 }
792 }
793 }
794 return false;
795}
796
798{
799 switch (direction) {
800 case Qt::LeftToRight:
801 return NSUserInterfaceLayoutDirectionLeftToRight;
802 case Qt::RightToLeft:
803 return NSUserInterfaceLayoutDirectionRightToLeft;
804 case Qt::LayoutDirectionAuto:
805 return [NSApp userInterfaceLayoutDirection];
806 }
807}
808
809/*****************************************************************************
810 QMacCGStyle globals
811 *****************************************************************************/
812const int macItemFrame = 2; // menu item frame width
813const int macItemHMargin = 3; // menu item hor text margin
814const int macRightBorder = 12; // right border on mac
815
816/*****************************************************************************
817 QMacCGStyle utility functions
818 *****************************************************************************/
819
863
864static const int qt_mac_aqua_metrics[] = {
865 // Values as of macOS 10.12.4 and Xcode 8.3.1
866 18 /* CheckBoxHeight */,
867 18 /* CheckBoxWidth */,
868 1 /* EditTextFrameOutset */,
869 4 /* FocusRectOutset */,
870 22 /* HSliderHeight */,
871 5 /* HSliderTickHeight */,
872 16 /* LargeProgressBarThickness */,
873 17 /* ListHeaderHeight */,
874 12 /* MenuSeparatorHeight, aka GetThemeMenuSeparatorHeight */,
875 11 /* MiniCheckBoxHeight */,
876 10 /* MiniCheckBoxWidth */,
877 12 /* MiniHSliderHeight */,
878 4 /* MiniHSliderTickHeight */,
879 15 /* MiniPopupButtonHeight */,
880 16 /* MiniPushButtonHeight */,
881 11 /* MiniRadioButtonHeight */,
882 10 /* MiniRadioButtonWidth */,
883 4 /* MiniVSliderTickWidth */,
884 12 /* MiniVSliderWidth */,
885 12 /* NormalProgressBarThickness */,
886 20 /* PopupButtonHeight */,
887 4 /* ProgressBarShadowOutset */,
888 20 /* PushButtonHeight */,
889 18 /* RadioButtonHeight */,
890 18 /* RadioButtonWidth */,
891 1 /* SeparatorSize */,
892 16 /* SmallCheckBoxHeight */,
893 14 /* SmallCheckBoxWidth */,
894 15 /* SmallHSliderHeight */,
895 4 /* SmallHSliderTickHeight */,
896 17 /* SmallPopupButtonHeight */,
897 2 /* SmallProgressBarShadowOutset */,
898 17 /* SmallPushButtonHeight */,
899 15 /* SmallRadioButtonHeight */,
900 14 /* SmallRadioButtonWidth */,
901 4 /* SmallVSliderTickWidth */,
902 15 /* SmallVSliderWidth */,
903 5 /* VSliderTickWidth */,
904 22 /* VSliderWidth */
905};
906
908{
909 if (qt_apple_runningWithLiquidGlass() && m == QAquaMetric::MiniRadioButtonWidth)
910 return 11;
911
912 return qt_mac_aqua_metrics[m];
913}
914
915static QSize qt_aqua_get_known_size(QStyle::ContentsType ct, const QStyleOption *opt,
916 const QWidget *widg, QSize szHint,
917 QStyleHelper::WidgetSizePolicy sz)
918{
919 QSize ret(-1, -1);
920 if (sz != QStyleHelper::SizeSmall && sz != QStyleHelper::SizeLarge && sz != QStyleHelper::SizeMini) {
921 qDebug("Not sure how to return this...");
922 return ret;
923 }
924 if ((widg && widg->testAttribute(Qt::WA_SetFont)) || !QApplication::desktopSettingsAware()) {
925 // If you're using a custom font and it's bigger than the default font,
926 // then no constraints for you. If you are smaller, we can try to help you out
927 QFont font = qt_app_fonts_hash()->value(widg->metaObject()->className(), QFont());
928 if (widg->font().pointSize() > font.pointSize())
929 return ret;
930 }
931
932 if (ct == QStyle::CT_CustomBase && widg) {
933#if QT_CONFIG(pushbutton)
934 if (qobject_cast<const QPushButton *>(widg))
935 ct = QStyle::CT_PushButton;
936#endif
937 else if (qobject_cast<const QRadioButton *>(widg))
938 ct = QStyle::CT_RadioButton;
939#if QT_CONFIG(checkbox)
940 else if (qobject_cast<const QCheckBox *>(widg))
941 ct = QStyle::CT_CheckBox;
942#endif
943#if QT_CONFIG(combobox)
944 else if (qobject_cast<const QComboBox *>(widg))
945 ct = QStyle::CT_ComboBox;
946#endif
947#if QT_CONFIG(toolbutton)
948 else if (qobject_cast<const QToolButton *>(widg))
949 ct = QStyle::CT_ToolButton;
950#endif
951 else if (qobject_cast<const QSlider *>(widg))
952 ct = QStyle::CT_Slider;
953#if QT_CONFIG(progressbar)
954 else if (qobject_cast<const QProgressBar *>(widg))
955 ct = QStyle::CT_ProgressBar;
956#endif
957#if QT_CONFIG(lineedit)
958 else if (qobject_cast<const QLineEdit *>(widg))
959 ct = QStyle::CT_LineEdit;
960#endif
961#if QT_CONFIG(itemviews)
962 else if (qobject_cast<const QHeaderView *>(widg))
963 ct = QStyle::CT_HeaderSection;
964#endif
965#if QT_CONFIG(menubar)
966 else if (qobject_cast<const QMenuBar *>(widg))
967 ct = QStyle::CT_MenuBar;
968#endif
969#if QT_CONFIG(sizegrip)
970 else if (qobject_cast<const QSizeGrip *>(widg))
971 ct = QStyle::CT_SizeGrip;
972#endif
973 else
974 return ret;
975 }
976
977 switch (ct) {
978#if QT_CONFIG(pushbutton)
979 case QStyle::CT_PushButton: {
980 const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt);
981 if (btn) {
982 QString buttonText = qt_mac_removeMnemonics(btn->text);
983 if (buttonText.contains(QLatin1Char('\n')))
984 ret = QSize(-1, -1);
985 else if (sz == QStyleHelper::SizeLarge)
986 ret = QSize(-1, qt_mac_aqua_get_metric(PushButtonHeight));
987 else if (sz == QStyleHelper::SizeSmall)
988 ret = QSize(-1, qt_mac_aqua_get_metric(SmallPushButtonHeight));
989 else if (sz == QStyleHelper::SizeMini)
990 ret = QSize(-1, qt_mac_aqua_get_metric(MiniPushButtonHeight));
991
992 if (!btn->icon.isNull()){
993 // If the button got an icon, and the icon is larger than the
994 // button, we can't decide on a default size
995 ret.setWidth(-1);
996 if (ret.height() < btn->iconSize.height())
997 ret.setHeight(-1);
998 }
999 else if (buttonText == QLatin1String("OK") || buttonText == QLatin1String("Cancel")){
1000 // Aqua Style guidelines restrict the size of OK and Cancel buttons to 68 pixels.
1001 // However, this doesn't work for German, therefore only do it for English,
1002 // I suppose it would be better to do some sort of lookups for languages
1003 // that like to have really long words.
1004 // FIXME This is not exactly true. Out of context, OK buttons have their
1005 // implicit size calculated the same way as any other button. Inside a
1006 // QDialogButtonBox, their size should be calculated such that the action
1007 // or accept button (i.e., rightmost) and cancel button have the same width.
1008 ret.setWidth(69);
1009 }
1010 }
1011#endif
1012#if 0 //Not sure we are applying the rules correctly for RadioButtons/CheckBoxes --Sam
1013 } else if (ct == QStyle::CT_RadioButton) {
1014 QRadioButton *rdo = static_cast<QRadioButton *>(widg);
1015 // Exception for case where multiline radio button text requires no size constrainment
1016 if (rdo->text().find('\n') != -1)
1017 return ret;
1018 if (sz == QStyleHelper::SizeLarge)
1019 ret = QSize(-1, qt_mac_aqua_get_metric(RadioButtonHeight));
1020 else if (sz == QStyleHelper::SizeSmall)
1021 ret = QSize(-1, qt_mac_aqua_get_metric(SmallRadioButtonHeight));
1022 else if (sz == QStyleHelper::SizeMini)
1023 ret = QSize(-1, qt_mac_aqua_get_metric(MiniRadioButtonHeight));
1024 } else if (ct == QStyle::CT_CheckBox) {
1025 if (sz == QStyleHelper::SizeLarge)
1026 ret = QSize(-1, qt_mac_aqua_get_metric(CheckBoxHeight));
1027 else if (sz == QStyleHelper::SizeSmall)
1028 ret = QSize(-1, qt_mac_aqua_get_metric(SmallCheckBoxHeight));
1029 else if (sz == QStyleHelper::SizeMini)
1030 ret = QSize(-1, qt_mac_aqua_get_metric(MiniCheckBoxHeight));
1031#endif
1032 break;
1033 }
1034 case QStyle::CT_SizeGrip:
1035 // Not HIG kosher: mimic what we were doing earlier until we support 4-edge resizing in MDI subwindows
1036 if (sz == QStyleHelper::SizeLarge || sz == QStyleHelper::SizeSmall) {
1037 int s = sz == QStyleHelper::SizeSmall ? 16 : 22; // large: pixel measured from HITheme, small: from my hat
1038 int width = 0;
1039#if QT_CONFIG(mdiarea)
1040 if (widg && qobject_cast<QMdiSubWindow *>(widg->parentWidget()))
1041 width = s;
1042#endif
1043 ret = QSize(width, s);
1044 }
1045 break;
1046 case QStyle::CT_ComboBox:
1047 switch (sz) {
1048 case QStyleHelper::SizeLarge:
1050 break;
1051 case QStyleHelper::SizeSmall:
1053 break;
1054 case QStyleHelper::SizeMini:
1056 break;
1057 default:
1058 break;
1059 }
1060 break;
1061 case QStyle::CT_ToolButton:
1062 if (sz == QStyleHelper::SizeSmall) {
1063 int width = 0, height = 0;
1064 if (szHint == QSize(-1, -1)) { //just 'guess'..
1065#if QT_CONFIG(toolbutton)
1066 const QStyleOptionToolButton *bt = qstyleoption_cast<const QStyleOptionToolButton *>(opt);
1067 // If this conversion fails then the widget was not what it claimed to be.
1068 if (bt) {
1069 if (!bt->icon.isNull()) {
1070 QSize iconSize = bt->iconSize;
1071 QSize pmSize = bt->icon.actualSize(QSize(32, 32), QIcon::Normal);
1072 width = qMax(width, qMax(iconSize.width(), pmSize.width()));
1073 height = qMax(height, qMax(iconSize.height(), pmSize.height()));
1074 }
1075 if (!bt->text.isNull() && bt->toolButtonStyle != Qt::ToolButtonIconOnly) {
1076 int text_width = bt->fontMetrics.horizontalAdvance(bt->text),
1077 text_height = bt->fontMetrics.height();
1078 if (bt->toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
1079 width = qMax(width, text_width);
1080 height += text_height;
1081 } else {
1082 width += text_width;
1083 width = qMax(height, text_height);
1084 }
1085 }
1086 } else
1087#endif
1088 {
1089 // Let's return the size hint...
1090 width = szHint.width();
1091 height = szHint.height();
1092 }
1093 } else {
1094 width = szHint.width();
1095 height = szHint.height();
1096 }
1097 width = qMax(20, width + 5); //border
1098 height = qMax(20, height + 5); //border
1099 ret = QSize(width, height);
1100 }
1101 break;
1102 case QStyle::CT_Slider: {
1103 int w = -1;
1104 const QStyleOptionSlider *sld = qstyleoption_cast<const QStyleOptionSlider *>(opt);
1105 // If this conversion fails then the widget was not what it claimed to be.
1106 if (sld) {
1107 if (sz == QStyleHelper::SizeLarge) {
1108 if (sld->orientation == Qt::Horizontal) {
1110 if (sld->tickPosition != QSlider::NoTicks)
1112 else
1113 w += 3;
1114 } else {
1116 if (sld->tickPosition != QSlider::NoTicks)
1118 }
1119 } else if (sz == QStyleHelper::SizeSmall) {
1120 if (sld->orientation == Qt::Horizontal) {
1122 if (sld->tickPosition != QSlider::NoTicks)
1124 } else {
1126 if (sld->tickPosition != QSlider::NoTicks)
1128 }
1129 } else if (sz == QStyleHelper::SizeMini) {
1130 if (sld->orientation == Qt::Horizontal) {
1132 if (sld->tickPosition != QSlider::NoTicks)
1134 } else {
1136 if (sld->tickPosition != QSlider::NoTicks)
1138 }
1139 }
1140 } else {
1141 // This is tricky, we were requested to find a size for a slider which is not
1142 // a slider. We don't know if this is vertical or horizontal or if we need to
1143 // have tick marks or not.
1144 // For this case we will return an horizontal slider without tick marks.
1147 }
1148 if (sld->orientation == Qt::Horizontal)
1149 ret.setHeight(w);
1150 else
1151 ret.setWidth(w);
1152 break;
1153 }
1154#if QT_CONFIG(progressbar)
1155 case QStyle::CT_ProgressBar: {
1156 int finalValue = -1;
1157 Qt::Orientation orient = Qt::Horizontal;
1158 if (const QProgressBar *pb = qobject_cast<const QProgressBar *>(widg))
1159 orient = pb->orientation();
1160
1161 if (sz == QStyleHelper::SizeLarge)
1162 finalValue = qt_mac_aqua_get_metric(LargeProgressBarThickness)
1163 + qt_mac_aqua_get_metric(ProgressBarShadowOutset);
1164 else
1165 finalValue = qt_mac_aqua_get_metric(NormalProgressBarThickness)
1166 + qt_mac_aqua_get_metric(SmallProgressBarShadowOutset);
1167 if (orient == Qt::Horizontal)
1168 ret.setHeight(finalValue);
1169 else
1170 ret.setWidth(finalValue);
1171 break;
1172 }
1173#endif
1174#if QT_CONFIG(combobox)
1175 case QStyle::CT_LineEdit:
1176 if (!widg || !qobject_cast<QComboBox *>(widg->parentWidget())) {
1177 //should I take into account the font dimensions of the lineedit? -Sam
1178 if (sz == QStyleHelper::SizeLarge)
1179 ret = QSize(-1, 21);
1180 else
1181 ret = QSize(-1, 19);
1182 }
1183 break;
1184#endif
1185 case QStyle::CT_HeaderSection:
1186#if QT_CONFIG(treeview)
1187 if (isTreeView(widg))
1188 ret = QSize(-1, qt_mac_aqua_get_metric(ListHeaderHeight));
1189#endif
1190 break;
1191 case QStyle::CT_MenuBar:
1192 if (sz == QStyleHelper::SizeLarge) {
1193 ret = QSize(-1, [[NSApp mainMenu] menuBarHeight]);
1194 // In the qt_mac_set_native_menubar(false) case,
1195 // we come it here with a zero-height main menu,
1196 // preventing the in-window menu from displaying.
1197 // Use 22 pixels for the height, by observation.
1198 if (ret.height() <= 0)
1199 ret.setHeight(22);
1200 }
1201 break;
1202 default:
1203 break;
1204 }
1205 return ret;
1206}
1207
1208static CGRect qt_alignmentRectForFrame(CGRect rect, QStyleHelper::WidgetSizePolicy size,
1209 QMacStylePrivate::CocoaControlType ct)
1210{
1211 // On macOS 26 with Liquid Glass, the NSView's -alignmentRectForFrame:
1212 // returns (for NSButton) the value of 'rect' unchanged, making
1213 // our focus ring too large and shifted vertically. All insets
1214 // are 0.
1215 // Here we don't touch horizontal coordinate/width - they are good as
1216 // they are.
1217
1218 if (ct != QMacStylePrivate::Button_PushButton && ct != QMacStylePrivate::Button_PopupButton
1219 && ct != QMacStylePrivate::Button_PullDown) {
1220 return rect;
1221 }
1222
1223 // Insets that we had from AppKit and that our focus calculations rely
1224 // on.
1225 // FIXME: further adjust them if needed in 'drawFocusRing'.
1226 static const NSEdgeInsets buttonInsets[] = {
1227 // top left bottom right
1228 {7., 0., 5., 0.}, // Regular
1229 {7., 0., 4., 0.}, // Small
1230 {2., 0., 1., 0.} // Mini
1231 // Large (missing on macOS 15)
1232 // ExtraLarge (missing on macOS 15)
1233 };
1234 // Button_PopupButton, Button_PullDown
1235 static const NSEdgeInsets popupButtonInsets[] = {
1236 // top left bottom right
1237 {4., 0., 1., 0.}, // Regular
1238 {4., 0., 2., 0.}, // Small
1239 {3., 0., 1., 0.} // Mini
1240 };
1241 static_assert(std::size(buttonInsets) == std::size(popupButtonInsets));
1242
1243 const auto *insets = ct == QMacStylePrivate::Button_PushButton ? buttonInsets : popupButtonInsets;
1244 // SizeLarge = 0, SizeSmall = 1, SizeMini = 2
1245 if (size >= 0 && size_t(size) < std::size(buttonInsets)) {
1246 const auto &inset = insets[size];
1247 rect.origin.y += inset.top;
1248 rect.size.height -= inset.top + inset.bottom;
1249 }
1250
1251 return rect;
1252}
1253
1254#if defined(QMAC_QAQUASTYLE_SIZE_CONSTRAIN) || defined(DEBUG_SIZE_CONSTRAINT)
1255static QStyleHelper::WidgetSizePolicy qt_aqua_guess_size(const QWidget *widg, QSize large, QSize small, QSize mini)
1256{
1257 Q_UNUSED(widg);
1258
1259 if (large == QSize(-1, -1)) {
1260 if (small != QSize(-1, -1))
1261 return QStyleHelper::SizeSmall;
1262 if (mini != QSize(-1, -1))
1263 return QStyleHelper::SizeMini;
1264 return QStyleHelper::SizeDefault;
1265 } else if (small == QSize(-1, -1)) {
1266 if (mini != QSize(-1, -1))
1267 return QStyleHelper::SizeMini;
1268 return QStyleHelper::SizeLarge;
1269 } else if (mini == QSize(-1, -1)) {
1270 return QStyleHelper::SizeLarge;
1271 }
1272
1273 if (qEnvironmentVariableIsSet("QWIDGET_ALL_SMALL"))
1274 return QStyleHelper::SizeSmall;
1275 else if (qEnvironmentVariableIsSet("QWIDGET_ALL_MINI"))
1276 return QStyleHelper::SizeMini;
1277
1278 return QStyleHelper::SizeLarge;
1279}
1280#endif
1281
1282void QMacStylePrivate::drawFocusRing(QPainter *p, const QRectF &targetRect, int hMargin, int vMargin, const CocoaControl &cw) const
1283{
1284 QPainterPath focusRingPath;
1285 focusRingPath.setFillRule(Qt::OddEvenFill);
1286
1287 qreal hOffset = 0.0;
1288 qreal vOffset = 0.0;
1289 switch (cw.type) {
1290 case Box:
1291 case Button_SquareButton:
1292 case SegmentedControl_Middle:
1293 case TextField: {
1294 auto innerRect = targetRect;
1295 qreal innerRadius = 0.0;
1296 if (cw.type == Button_SquareButton)
1297 innerRect = cw.adjustedControlFrame(targetRect.adjusted(hMargin, vMargin, -hMargin, -vMargin));
1298 if (cw.type == TextField) {
1299 innerRect = innerRect.adjusted(hMargin, vMargin, -hMargin, -vMargin).adjusted(0.5, 0.5, -0.5, -0.5);
1300 if (qt_apple_runningWithLiquidGlass())
1301 innerRadius = textFieldBezelCornerRadius - 0.5;
1302 }
1303 const auto outerRect = innerRect.adjusted(-focusRingWidth, -focusRingWidth, focusRingWidth, focusRingWidth);
1304 const auto outerRadius = innerRadius + focusRingWidth;
1305 if (innerRadius > 0.0)
1306 focusRingPath.addRoundedRect(innerRect, innerRadius, innerRadius);
1307 else
1308 focusRingPath.addRect(innerRect);
1309 focusRingPath.addRoundedRect(outerRect, outerRadius, outerRadius);
1310 break;
1311 }
1312 case Button_CheckBox: {
1313 const auto cbInnerRadius = (cw.size == QStyleHelper::SizeMini ? 2.0 : 3.0);
1314 const auto cbSize = cw.size == QStyleHelper::SizeLarge ? 13 :
1315 cw.size == QStyleHelper::SizeSmall ? 11 : 9; // As measured
1316 hOffset = hMargin + (cw.size == QStyleHelper::SizeLarge ? (qt_apple_runningWithLiquidGlass() ? 1.5 : 2.5) :
1317 cw.size == QStyleHelper::SizeSmall ? (qt_apple_runningWithLiquidGlass() ? 1.5 : 2.0) : 1.0); // As measured
1318 vOffset = 0.5 * qreal(targetRect.height() - cbSize);
1319 if (qt_apple_runningWithLiquidGlass()) {
1320 if (cw.size == QStyleHelper::SizeSmall)
1321 vOffset += 0.5;
1322 if (cw.size == QStyleHelper::SizeMini)
1323 vOffset -= 1.;
1324 }
1325 const auto cbInnerRect = QRectF(0, 0, cbSize, cbSize);
1326 const auto cbOuterRadius = cbInnerRadius + focusRingWidth;
1327 const auto cbOuterRect = cbInnerRect.adjusted(-focusRingWidth, -focusRingWidth, focusRingWidth, focusRingWidth);
1328 focusRingPath.addRoundedRect(cbOuterRect, cbOuterRadius, cbOuterRadius);
1329 focusRingPath.addRoundedRect(cbInnerRect, cbInnerRadius, cbInnerRadius);
1330 break;
1331 }
1332 case Button_RadioButton: {
1333 const auto rbSize = cw.size == QStyleHelper::SizeLarge ? 15 :
1334 cw.size == QStyleHelper::SizeSmall ? 13 : 9; // As measured
1335 hOffset = hMargin + (cw.size == QStyleHelper::SizeLarge ? (qt_apple_runningWithLiquidGlass() ? 0.5 : 1.5) :
1336 cw.size == QStyleHelper::SizeSmall ? (qt_apple_runningWithLiquidGlass() ? 0.5 : 1.0) : 1.0); // As measured
1337 vOffset = 0.5 * qreal(targetRect.height() - rbSize);
1338 const auto rbInnerRect = QRectF(0, 0, rbSize, rbSize);
1339 const auto rbOuterRect = rbInnerRect.adjusted(-focusRingWidth, -focusRingWidth, focusRingWidth, focusRingWidth);
1340 focusRingPath.addEllipse(rbInnerRect);
1341 focusRingPath.addEllipse(rbOuterRect);
1342 break;
1343 }
1344 case Button_PullDown:
1345 case Button_PushButton: {
1346 QRectF focusRect;
1347 auto *pb = static_cast<NSButton *>(cocoaControl(cw));
1348 const QRectF frameRect = cw.adjustedControlFrame(targetRect.adjusted(hMargin, vMargin, -hMargin, -vMargin));
1349 pb.frame = frameRect.toCGRect();
1350
1351 if (qt_apple_runningWithLiquidGlass())
1352 focusRect = QRectF::fromCGRect(qt_alignmentRectForFrame(pb.frame, cw.size, cw.type));
1353 else
1354 focusRect = QRectF::fromCGRect([pb alignmentRectForFrame:pb.frame]);
1355
1356 if (cw.type == QMacStylePrivate::Button_PushButton) {
1357 adjustPushButtonShadowMargins(focusRect, cw.size);
1358 if (cw.size == QStyleHelper::SizeMini)
1359 focusRect.adjust(0, 3, 0, -3);
1360 } else if (cw.type == QMacStylePrivate::Button_PullDown) {
1361 focusRect -= pullDownButtonShadowMargins[cw.size];
1362 //fix focus ring drawn slightly off for pull downs
1363 if (cw.size == QStyleHelper::SizeLarge)
1364 focusRect = focusRect.adjusted(0, 0, 0, -1);
1365 else if (cw.size == QStyleHelper::SizeMini)
1366 focusRect = focusRect.adjusted(0, -1, 0, 0);
1367 }
1368 focusRect = focusRect.translated(0, 1);
1369 const qreal innerRadius = cw.type == Button_PushButton ? 3 : 4;
1370 const qreal outerRadius = innerRadius + focusRingWidth;
1371 hOffset = focusRect.left();
1372 vOffset = focusRect.top();
1373 const auto innerRect = focusRect.translated(-focusRect.topLeft());
1374 const auto outerRect = innerRect.adjusted(-hMargin, -vMargin, hMargin, vMargin);
1375 focusRingPath.addRoundedRect(innerRect, innerRadius, innerRadius);
1376 focusRingPath.addRoundedRect(outerRect, outerRadius, outerRadius);
1377 break;
1378 }
1379 case Button_PopupButton:
1380 case SegmentedControl_Single: {
1381 QRectF focusRect = targetRect;
1382 // These adjustments look bad on Tahoe with L. Glass.
1383 if (!qt_apple_runningWithLiquidGlass())
1384 focusRect.translate(0, -1.5);
1385 const qreal innerRadius = cw.type == Button_PushButton ? 3 : 4;
1386 const qreal outerRadius = innerRadius + focusRingWidth;
1387 hOffset = focusRect.left();
1388 vOffset = focusRect.top();
1389 const auto innerRect = focusRect.translated(-focusRect.topLeft());
1390 const auto outerRect = innerRect.adjusted(-hMargin, -vMargin, hMargin, vMargin);
1391 focusRingPath.addRoundedRect(innerRect, innerRadius, innerRadius);
1392 focusRingPath.addRoundedRect(outerRect, outerRadius, outerRadius);
1393 break;
1394 }
1395 case ComboBox:
1396 case SegmentedControl_First:
1397 case SegmentedControl_Last: {
1398 hOffset = targetRect.left();
1399 vOffset = targetRect.top();
1400 const qreal innerRadius = 8;
1401 const qreal outerRadius = innerRadius + focusRingWidth;
1402 const auto innerRect = targetRect.translated(-targetRect.topLeft());
1403 const auto outerRect = innerRect.adjusted(-hMargin, -vMargin, hMargin, vMargin);
1404
1405 const auto cbFocusFramePath = [](const QRectF &rect, qreal tRadius, qreal bRadius) {
1406 QPainterPath path;
1407
1408 if (tRadius > 0) {
1409 const auto topLeftCorner = QRectF(rect.topLeft(), QSizeF(tRadius, tRadius));
1410 path.arcMoveTo(topLeftCorner, 180);
1411 path.arcTo(topLeftCorner, 180, -90);
1412 } else {
1413 path.moveTo(rect.topLeft());
1414 }
1415 const auto rightEdge = rect.right() - bRadius;
1416 path.arcTo(rightEdge, rect.top(), bRadius, bRadius, 90, -90);
1417 path.arcTo(rightEdge, rect.bottom() - bRadius, bRadius, bRadius, 0, -90);
1418 if (tRadius > 0)
1419 path.arcTo(rect.left(), rect.bottom() - tRadius, tRadius, tRadius, 270, -90);
1420 else
1421 path.lineTo(rect.bottomLeft());
1422 path.closeSubpath();
1423
1424 return path;
1425 };
1426
1427 const auto innerPath = cbFocusFramePath(innerRect, 0, innerRadius);
1428 focusRingPath.addPath(innerPath);
1429 const auto outerPath = cbFocusFramePath(outerRect, 2 * focusRingWidth, outerRadius);
1430 focusRingPath.addPath(outerPath);
1431 break;
1432 }
1433 default:
1434 Q_UNREACHABLE();
1435 }
1436
1437 auto focusRingColor = qt_mac_toQColor(NSColor.keyboardFocusIndicatorColor.CGColor);
1438 if (!isDarkMode()) {
1439 // This color already has alpha ~ 0.25, this value is too small - the ring is
1440 // very pale and nothing like the native one. 0.39 makes it better (not ideal
1441 // anyway). The color seems to be correct in dark more without any modification.
1442 focusRingColor.setAlphaF(0.39);
1443 }
1444
1445 p->save();
1446 p->setRenderHint(QPainter::Antialiasing);
1447
1448 if (cw.type == SegmentedControl_First) {
1449 // TODO Flip left-right
1450 }
1451 p->translate(hOffset, vOffset);
1452 p->fillPath(focusRingPath, focusRingColor);
1453 p->restore();
1454}
1455
1456QPainterPath QMacStylePrivate::windowPanelPath(const QRectF &r) const
1457{
1458 static const qreal CornerPointOffset = 5.5;
1459 static const qreal CornerControlOffset = 2.1;
1460
1461 QPainterPath path;
1462 // Top-left corner
1463 path.moveTo(r.left(), r.top() + CornerPointOffset);
1464 path.cubicTo(r.left(), r.top() + CornerControlOffset,
1465 r.left() + CornerControlOffset, r.top(),
1466 r.left() + CornerPointOffset, r.top());
1467 // Top-right corner
1468 path.lineTo(r.right() - CornerPointOffset, r.top());
1469 path.cubicTo(r.right() - CornerControlOffset, r.top(),
1470 r.right(), r.top() + CornerControlOffset,
1471 r.right(), r.top() + CornerPointOffset);
1472 // Bottom-right corner
1473 path.lineTo(r.right(), r.bottom() - CornerPointOffset);
1474 path.cubicTo(r.right(), r.bottom() - CornerControlOffset,
1475 r.right() - CornerControlOffset, r.bottom(),
1476 r.right() - CornerPointOffset, r.bottom());
1477 // Bottom-right corner
1478 path.lineTo(r.left() + CornerPointOffset, r.bottom());
1479 path.cubicTo(r.left() + CornerControlOffset, r.bottom(),
1480 r.left(), r.bottom() - CornerControlOffset,
1481 r.left(), r.bottom() - CornerPointOffset);
1482 path.lineTo(r.left(), r.top() + CornerPointOffset);
1483
1484 return path;
1485}
1486
1487QMacStylePrivate::CocoaControlType QMacStylePrivate::windowButtonCocoaControl(QStyle::SubControl sc) const
1488{
1489 struct WindowButtons {
1490 QStyle::SubControl sc;
1491 QMacStylePrivate::CocoaControlType ct;
1492 };
1493
1494 static const WindowButtons buttons[] = {
1495 { QStyle::SC_TitleBarCloseButton, QMacStylePrivate::Button_WindowClose },
1496 { QStyle::SC_TitleBarMinButton, QMacStylePrivate::Button_WindowMiniaturize },
1497 { QStyle::SC_TitleBarMaxButton, QMacStylePrivate::Button_WindowZoom }
1498 };
1499
1500 for (const auto &wb : buttons)
1501 if (wb.sc == sc)
1502 return wb.ct;
1503
1504 return NoControl;
1505}
1506
1507
1508#if QT_CONFIG(tabbar)
1509void QMacStylePrivate::tabLayout(const QStyleOptionTab *opt, const QWidget *widget, QRect *textRect, QRect *iconRect) const
1510{
1511 Q_ASSERT(textRect);
1512 Q_ASSERT(iconRect);
1513 QRect tr = opt->rect;
1514 const bool verticalTabs = opt->shape == QTabBar::RoundedEast
1515 || opt->shape == QTabBar::RoundedWest
1516 || opt->shape == QTabBar::TriangularEast
1517 || opt->shape == QTabBar::TriangularWest;
1518 if (verticalTabs)
1519 tr.setRect(0, 0, tr.height(), tr.width()); // 0, 0 as we will have a translate transform
1520
1521 int verticalShift = proxyStyle->pixelMetric(QStyle::PM_TabBarTabShiftVertical, opt, widget);
1522 int horizontalShift = proxyStyle->pixelMetric(QStyle::PM_TabBarTabShiftHorizontal, opt, widget);
1523 const int hpadding = 4;
1524 const int vpadding = proxyStyle->pixelMetric(QStyle::PM_TabBarTabVSpace, opt, widget) / 2;
1525 if (opt->shape == QTabBar::RoundedSouth || opt->shape == QTabBar::TriangularSouth)
1526 verticalShift = -verticalShift;
1527 tr.adjust(hpadding, verticalShift - vpadding, horizontalShift - hpadding, vpadding);
1528
1529 // left widget
1530 if (!opt->leftButtonSize.isEmpty()) {
1531 const int buttonSize = verticalTabs ? opt->leftButtonSize.height() : opt->leftButtonSize.width();
1532 tr.setLeft(tr.left() + 4 + buttonSize);
1533 // make text aligned to center
1534 if (opt->rightButtonSize.isEmpty())
1535 tr.setRight(tr.right() - 4 - buttonSize);
1536 }
1537 // right widget
1538 if (!opt->rightButtonSize.isEmpty()) {
1539 const int buttonSize = verticalTabs ? opt->rightButtonSize.height() : opt->rightButtonSize.width();
1540 tr.setRight(tr.right() - 4 - buttonSize);
1541 // make text aligned to center
1542 if (opt->leftButtonSize.isEmpty())
1543 tr.setLeft(tr.left() + 4 + buttonSize);
1544 }
1545
1546 // icon
1547 if (!opt->icon.isNull()) {
1548 QSize iconSize = opt->iconSize;
1549 if (!iconSize.isValid()) {
1550 int iconExtent = proxyStyle->pixelMetric(QStyle::PM_SmallIconSize);
1551 iconSize = QSize(iconExtent, iconExtent);
1552 }
1553 QSize tabIconSize = opt->icon.actualSize(iconSize,
1554 (opt->state & QStyle::State_Enabled) ? QIcon::Normal : QIcon::Disabled,
1555 (opt->state & QStyle::State_Selected) ? QIcon::On : QIcon::Off);
1556 // High-dpi icons do not need adjustment; make sure tabIconSize is not larger than iconSize
1557 tabIconSize = QSize(qMin(tabIconSize.width(), iconSize.width()), qMin(tabIconSize.height(), iconSize.height()));
1558
1559 const int stylePadding = proxyStyle->pixelMetric(QStyle::PM_TabBarTabHSpace, opt, widget) / 2 - hpadding;
1560
1561 if (opt->documentMode) {
1562 // documents show the icon as part of the the text
1563 const int textWidth =
1564 opt->fontMetrics.boundingRect(tr, Qt::AlignCenter | Qt::TextShowMnemonic, opt->text).width();
1565 *iconRect = QRect(tr.center().x() - textWidth / 2 - stylePadding - tabIconSize.width(),
1566 tr.center().y() - tabIconSize.height() / 2,
1567 tabIconSize.width(), tabIconSize.height());
1568 } else {
1569 *iconRect = QRect(tr.left() + stylePadding, tr.center().y() - tabIconSize.height() / 2,
1570 tabIconSize.width(), tabIconSize.height());
1571 }
1572 if (!verticalTabs)
1573 *iconRect = proxyStyle->visualRect(opt->direction, opt->rect, *iconRect);
1574
1575 tr.setLeft(tr.left() + stylePadding + tabIconSize.width() + 4);
1576 tr.setRight(tr.right() - stylePadding - tabIconSize.width() - 4);
1577 }
1578
1579 if (!verticalTabs)
1580 tr = proxyStyle->visualRect(opt->direction, opt->rect, tr);
1581
1582 *textRect = tr;
1583}
1584
1585QMacStylePrivate::Direction QMacStylePrivate::tabDirection(QTabBar::Shape shape)
1586{
1587 switch (shape) {
1588 case QTabBar::RoundedSouth:
1589 case QTabBar::TriangularSouth:
1590 return South;
1591 case QTabBar::RoundedNorth:
1592 case QTabBar::TriangularNorth:
1593 return North;
1594 case QTabBar::RoundedWest:
1595 case QTabBar::TriangularWest:
1596 return West;
1597 case QTabBar::RoundedEast:
1598 case QTabBar::TriangularEast:
1599 return East;
1600 }
1601}
1602
1603bool QMacStylePrivate::verticalTabs(QMacStylePrivate::Direction direction)
1604{
1605 return (direction == QMacStylePrivate::East
1606 || direction == QMacStylePrivate::West);
1607}
1608
1609#endif // QT_CONFIG(tabbar)
1610
1611QStyleHelper::WidgetSizePolicy QMacStylePrivate::effectiveAquaSizeConstrain(const QStyleOption *option,
1612 const QWidget *widg,
1613 QStyle::ContentsType ct,
1614 QSize szHint, QSize *insz) const
1615{
1616 QStyleHelper::WidgetSizePolicy sz = aquaSizeConstrain(option, widg, ct, szHint, insz);
1617 if (sz == QStyleHelper::SizeDefault)
1618 return QStyleHelper::SizeLarge;
1619 return sz;
1620}
1621
1622QStyleHelper::WidgetSizePolicy QMacStylePrivate::aquaSizeConstrain(const QStyleOption *option, const QWidget *widg,
1623 QStyle::ContentsType ct, QSize szHint, QSize *insz) const
1624{
1625#if defined(QMAC_QAQUASTYLE_SIZE_CONSTRAIN) || defined(DEBUG_SIZE_CONSTRAINT)
1626 if (option) {
1627 if (option->state & QStyle::State_Small)
1628 return QStyleHelper::SizeSmall;
1629 if (option->state & QStyle::State_Mini)
1630 return QStyleHelper::SizeMini;
1631 }
1632
1633 if (!widg) {
1634 if (insz)
1635 *insz = QSize();
1636 if (qEnvironmentVariableIsSet("QWIDGET_ALL_SMALL"))
1637 return QStyleHelper::SizeSmall;
1638 if (qEnvironmentVariableIsSet("QWIDGET_ALL_MINI"))
1639 return QStyleHelper::SizeMini;
1640 return QStyleHelper::SizeDefault;
1641 }
1642
1643 QSize large = qt_aqua_get_known_size(ct, option, widg, szHint, QStyleHelper::SizeLarge),
1644 small = qt_aqua_get_known_size(ct, option, widg, szHint, QStyleHelper::SizeSmall),
1645 mini = qt_aqua_get_known_size(ct, option, widg, szHint, QStyleHelper::SizeMini);
1646 bool guess_size = false;
1647 QStyleHelper::WidgetSizePolicy ret = QStyleHelper::SizeDefault;
1648 QStyleHelper::WidgetSizePolicy wsp = QStyleHelper::widgetSizePolicy(widg);
1649 if (wsp == QStyleHelper::SizeDefault)
1650 guess_size = true;
1651 else if (wsp == QStyleHelper::SizeMini)
1652 ret = QStyleHelper::SizeMini;
1653 else if (wsp == QStyleHelper::SizeSmall)
1654 ret = QStyleHelper::SizeSmall;
1655 else if (wsp == QStyleHelper::SizeLarge)
1656 ret = QStyleHelper::SizeLarge;
1657 if (guess_size)
1658 ret = qt_aqua_guess_size(widg, large, small, mini);
1659
1660 QSize *sz = nullptr;
1661 if (ret == QStyleHelper::SizeSmall)
1662 sz = &small;
1663 else if (ret == QStyleHelper::SizeLarge)
1664 sz = &large;
1665 else if (ret == QStyleHelper::SizeMini)
1666 sz = &mini;
1667 if (insz)
1668 *insz = sz ? *sz : QSize(-1, -1);
1669#ifdef DEBUG_SIZE_CONSTRAINT
1670 if (sz) {
1671 const char *size_desc = "Unknown";
1672 if (sz == &small)
1673 size_desc = "Small";
1674 else if (sz == &large)
1675 size_desc = "Large";
1676 else if (sz == &mini)
1677 size_desc = "Mini";
1678 qDebug("%s - %s: %s taken (%d, %d) [%d, %d]",
1679 widg ? widg->objectName().toLatin1().constData() : "*Unknown*",
1680 widg ? widg->metaObject()->className() : "*Unknown*", size_desc, widg->width(), widg->height(),
1681 sz->width(), sz->height());
1682 }
1683#endif
1684 return ret;
1685#else
1686 if (insz)
1687 *insz = QSize();
1688 Q_UNUSED(widg);
1689 Q_UNUSED(ct);
1690 Q_UNUSED(szHint);
1691 return QStyleHelper::SizeDefault;
1692#endif
1693}
1694
1695size_t qHash(const QMacStylePrivate::CocoaControl &cw, size_t seed = 0)
1696{
1697 return ((cw.type << 2) | cw.size) ^ seed;
1698}
1699
1700QMacStylePrivate::CocoaControl::CocoaControl()
1701 : type(NoControl), size(QStyleHelper::SizeDefault)
1702{
1703}
1704
1705QMacStylePrivate::CocoaControl::CocoaControl(CocoaControlType t, QStyleHelper::WidgetSizePolicy s)
1706 : type(t), size(s)
1707{
1708}
1709
1710bool QMacStylePrivate::CocoaControl::operator==(const CocoaControl &other) const
1711{
1712 return other.type == type && other.size == size;
1713}
1714
1715QSizeF QMacStylePrivate::CocoaControl::defaultFrameSize() const
1716{
1717 // We need this because things like NSView.alignmentRectInsets
1718 // or -[NSCell titleRectForBounds:] won't work unless the control
1719 // has a reasonable frame set. IOW, it's a chicken and egg problem.
1720 // These values are as observed in Xcode 9's Interface Builder.
1721
1722 if (type == Button_PushButton)
1723 return QSizeF(-1, pushButtonDefaultHeight[size]);
1724
1725 if (type == Button_PopupButton
1726 || type == Button_PullDown)
1727 return QSizeF(-1, popupButtonDefaultHeight[size]);
1728
1729 if (type == ComboBox)
1730 return QSizeF(-1, comboBoxDefaultHeight[size]);
1731
1732 return QSizeF();
1733}
1734
1735QRectF QMacStylePrivate::CocoaControl::adjustedControlFrame(const QRectF &rect) const
1736{
1737 QRectF frameRect;
1738 const auto frameSize = defaultFrameSize();
1739 if (type == QMacStylePrivate::Button_SquareButton) {
1740 frameRect = rect.adjusted(3, 1, -3, -1)
1741 .adjusted(focusRingWidth, focusRingWidth, -focusRingWidth, -focusRingWidth)
1742 .adjusted(-6.5, 0, 6.5, 0);
1743 } else if (type == QMacStylePrivate::Button_PushButton) {
1744 // Start from the style option's top-left corner.
1745 frameRect = QRectF(rect.topLeft(),
1746 QSizeF(rect.width(), frameSize.height()));
1747 if (size == QStyleHelper::SizeSmall)
1748 frameRect.translate(0, 0.5);
1749 else if (size == QStyleHelper::SizeMini)
1750 frameRect = frameRect.adjusted(0, 0, -8, 0).translated(4, -0.5);
1751 if (!qt_apple_runningWithLiquidGlass()) {
1752 // These adjustments needed because the actual button's bezel
1753 // prior to Tahoe with the Liquid Glass enabled was smaller than requested.
1754 // Starting from Tahoe the bezel exactly fits the rectangle we draw with.
1755 frameRect = frameRect.adjusted(-pushButtonBevelRectOffsets[size], 0,
1756 pushButtonBevelRectOffsets[size], 0);
1757 }
1758 } else {
1759 // Center in the style option's rect.
1760 frameRect = QRectF(QPointF(0, (rect.height() - frameSize.height()) / 2.0),
1761 QSizeF(rect.width(), frameSize.height()));
1762 frameRect = frameRect.translated(rect.topLeft());
1763 if (type == QMacStylePrivate::Button_PullDown || type == QMacStylePrivate::Button_PopupButton) {
1764 if (size == QStyleHelper::SizeLarge)
1765 frameRect = frameRect.adjusted(0, 0, -6, 0).translated(3, 0);
1766 else if (size == QStyleHelper::SizeSmall)
1767 frameRect = frameRect.adjusted(0, 0, -4, 0).translated(2, 1);
1768 else if (size == QStyleHelper::SizeMini)
1769 frameRect = frameRect.adjusted(0, 0, -9, 0).translated(5, 0);
1770 if (type == QMacStylePrivate::Button_PullDown)
1771 frameRect = frameRect.adjusted(-pushButtonBevelRectOffsets[size], 0,
1772 pushButtonBevelRectOffsets[size], 0);
1773 } else if (type == QMacStylePrivate::ComboBox) {
1774 frameRect = frameRect.adjusted(0, 0, -6, 0).translated(4, 0);
1775 }
1776 }
1777
1778 return frameRect;
1779}
1780
1781QMarginsF QMacStylePrivate::CocoaControl::titleMargins() const
1782{
1783 if (type == QMacStylePrivate::Button_PushButton) {
1784 if (size == QStyleHelper::SizeLarge) {
1785 if (qt_apple_runningWithLiquidGlass())
1786 return QMarginsF(12, 6, 12, 8);
1787 return QMarginsF(12, 5, 12, 9);
1788 }
1789 if (size == QStyleHelper::SizeSmall) {
1790 if (qt_apple_runningWithLiquidGlass())
1791 return QMarginsF(12, 6, 12, 7);
1792 return QMarginsF(12, 4, 12, 9);
1793 }
1794 if (size == QStyleHelper::SizeMini)
1795 return QMarginsF(10, 1, 10, 2);
1796 }
1797
1798 if (type == QMacStylePrivate::Button_PullDown) {
1799 if (size == QStyleHelper::SizeLarge)
1800 return QMarginsF(7.5, 2.5, 22.5, 5.5);
1801 if (size == QStyleHelper::SizeSmall)
1802 return QMarginsF(7.5, 2, 20.5, 4);
1803 if (size == QStyleHelper::SizeMini)
1804 return QMarginsF(4.5, 0, 16.5, 2);
1805 }
1806
1807 if (type == QMacStylePrivate::Button_SquareButton)
1808 return QMarginsF(6, 1, 6, 2);
1809
1810 return QMarginsF();
1811}
1812
1813bool QMacStylePrivate::CocoaControl::getCocoaButtonTypeAndBezelStyle(NSButtonType *buttonType, NSBezelStyle *bezelStyle) const
1814{
1815 switch (type) {
1816 case Button_CheckBox:
1817 *buttonType = NSButtonTypeSwitch;
1818 *bezelStyle = NSBezelStyleRegularSquare;
1819 break;
1820 case Button_Disclosure:
1821 *buttonType = NSButtonTypeOnOff;
1822 *bezelStyle = NSBezelStyleDisclosure;
1823 break;
1824 case Button_RadioButton:
1825 *buttonType = NSButtonTypeRadio;
1826 *bezelStyle = NSBezelStyleRegularSquare;
1827 break;
1828 case Button_SquareButton:
1829 *buttonType = NSButtonTypePushOnPushOff;
1830 *bezelStyle = NSBezelStyleShadowlessSquare;
1831 break;
1832 case Button_PushButton:
1833 *buttonType = NSButtonTypeMomentaryPushIn;
1834 *bezelStyle = NSBezelStyleRounded;
1835 break;
1836 default:
1837 return false;
1838 }
1839
1840 return true;
1841}
1842
1843QMacStylePrivate::CocoaControlType cocoaControlType(const QStyleOption *opt, const QWidget *w)
1844{
1845 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
1846 const bool hasMenu = btn->features & QStyleOptionButton::HasMenu;
1847 // Buttons that don't fit (or don't get filled by) the default bevel
1848 // will be made of square type, unless WA_MacNormalSize is not set.
1849 // Threshold used to be at 34, not 32.
1850 // Needs to be in sync with similar logic in CE_FocusFrame handling
1851 QStyleHelper::WidgetSizePolicy sizePolicy = QStyleHelper::widgetSizePolicy(w, opt);
1852 if (sizePolicy == QStyleHelper::SizeDefault)
1853 sizePolicy = QStyleHelper::SizeLarge;
1854 const bool isSquare = (btn->features & QStyleOptionButton::Flat)
1855 || (btn->rect.height() != pushButtonDefaultHeight[sizePolicy]);
1856 return (isSquare? QMacStylePrivate::Button_SquareButton :
1857 hasMenu ? QMacStylePrivate::Button_PullDown :
1858 QMacStylePrivate::Button_PushButton);
1859 }
1860
1861 if (const auto *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
1862 if (combo->editable)
1863 return QMacStylePrivate::ComboBox;
1864 // TODO Me may support square, non-editable combo boxes, but not more than that
1865 return QMacStylePrivate::Button_PopupButton;
1866 }
1867
1868 return QMacStylePrivate::NoControl;
1869}
1870
1871/**
1872 Carbon draws comboboxes (and other views) outside the rect given as argument. Use this function to obtain
1873 the corresponding inner rect for drawing the same combobox so that it stays inside the given outerBounds.
1874*/
1875CGRect QMacStylePrivate::comboboxInnerBounds(const CGRect &outerBounds, const CocoaControl &cocoaWidget)
1876{
1877 CGRect innerBounds = outerBounds;
1878 // Carbon draw parts of the view outside the rect.
1879 // So make the rect a bit smaller to compensate
1880 // (I wish HIThemeGetButtonBackgroundBounds worked)
1881 if (cocoaWidget.type == Button_PopupButton) {
1882 switch (cocoaWidget.size) {
1883 case QStyleHelper::SizeSmall:
1884 innerBounds.origin.x += 3;
1885 innerBounds.origin.y += 3;
1886 innerBounds.size.width -= 6;
1887 innerBounds.size.height -= 7;
1888 break;
1889 case QStyleHelper::SizeMini:
1890 innerBounds.origin.x += 2;
1891 innerBounds.origin.y += 2;
1892 innerBounds.size.width -= 5;
1893 innerBounds.size.height -= 6;
1894 break;
1895 case QStyleHelper::SizeLarge:
1896 case QStyleHelper::SizeDefault:
1897 innerBounds.origin.x += 2;
1898 innerBounds.origin.y += 2;
1899 innerBounds.size.width -= 5;
1900 innerBounds.size.height -= 6;
1901 }
1902 } else if (cocoaWidget.type == ComboBox) {
1903 switch (cocoaWidget.size) {
1904 case QStyleHelper::SizeSmall:
1905 innerBounds.origin.x += 3;
1906 innerBounds.origin.y += 3;
1907 innerBounds.size.width -= 7;
1908 innerBounds.size.height -= 8;
1909 break;
1910 case QStyleHelper::SizeMini:
1911 innerBounds.origin.x += 3;
1912 innerBounds.origin.y += 3;
1913 innerBounds.size.width -= 4;
1914 innerBounds.size.height -= 8;
1915 break;
1916 case QStyleHelper::SizeLarge:
1917 case QStyleHelper::SizeDefault:
1918 innerBounds.origin.x += 3;
1919 innerBounds.origin.y += 2;
1920 innerBounds.size.width -= 6;
1921 innerBounds.size.height -= 8;
1922 }
1923 }
1924
1925 return innerBounds;
1926}
1927
1928/**
1929 Inside a combobox Qt places a line edit widget. The size of this widget should depend on the kind
1930 of combobox we choose to draw. This function calculates and returns this size.
1931*/
1932QRectF QMacStylePrivate::comboboxEditBounds(const QRectF &outerBounds, const CocoaControl &cw)
1933{
1934 QRectF ret = outerBounds;
1935 if (cw.type == ComboBox) {
1936 static auto shift = [](QStyleHelper::WidgetSizePolicy size) {
1937 const double newButtonWs[] = {30, 25, 22};
1938 const double buttonWs[] = {25, 22, 19};
1939 static_assert(std::size(newButtonWs) == std::size(buttonWs));
1940 assert(size >= 0 && std::size_t(size) < std::size(newButtonWs));
1941 return qt_apple_runningWithLiquidGlass() ? newButtonWs[size] : buttonWs[size];
1942 };
1943 switch (cw.size) {
1944 case QStyleHelper::SizeLarge:
1945 ret = ret.adjusted(0, 0, -shift(cw.size), 0).translated(2, 4.5);
1946 ret.setHeight(16);
1947 break;
1948 case QStyleHelper::SizeSmall:
1949 ret = ret.adjusted(0, 0, -shift(cw.size), 0).translated(2, 3);
1950 ret.setHeight(14);
1951 break;
1952 case QStyleHelper::SizeMini:
1953 ret = ret.adjusted(0, 0, -shift(cw.size), 0).translated(2, 2.5);
1954 ret.setHeight(10.5);
1955 break;
1956 default:
1957 break;
1958 }
1959 } else if (cw.type == Button_PopupButton) {
1960 switch (cw.size) {
1961 case QStyleHelper::SizeLarge:
1962 ret.adjust(10, 1, -23, -4);
1963 break;
1964 case QStyleHelper::SizeSmall:
1965 ret.adjust(10, 4, -20, -3);
1966 break;
1967 case QStyleHelper::SizeMini:
1968 ret.adjust(9, 0, -19, 0);
1969 ret.setHeight(13);
1970 break;
1971 default:
1972 break;
1973 }
1974 }
1975 return ret;
1976}
1977
1978QMacStylePrivate::QMacStylePrivate()
1979 : backingStoreNSView(nil)
1980{
1981}
1982
1983QMacStylePrivate::~QMacStylePrivate()
1984{
1985 QMacAutoReleasePool pool;
1986 for (NSView *b : cocoaControls)
1987 [b release];
1988 for (NSCell *cell : cocoaCells)
1989 [cell release];
1990}
1991
1992NSView *QMacStylePrivate::cocoaControl(CocoaControl widget) const
1993{
1994 if (widget.type == QMacStylePrivate::NoControl
1995 || widget.size == QStyleHelper::SizeDefault)
1996 return nil;
1997
1998 if (widget.type == Box && isDarkMode()) {
1999 // See render code in drawPrimitive(PE_FrameTabWidget)
2000 widget.type = Box_Dark;
2001 }
2002
2003 NSView *bv = cocoaControls.value(widget, nil);
2004 if (!bv) {
2005 switch (widget.type) {
2006 case Box: {
2007 NSBox *box = [[NSBox alloc] init];
2008 bv = box;
2009 box.title = @"";
2010 box.titlePosition = NSNoTitle;
2011 break;
2012 }
2013 case Box_Dark:
2014 bv = [[QDarkNSBox alloc] init];
2015 break;
2016 case Button_CheckBox:
2017 case Button_Disclosure:
2018 case Button_PushButton:
2019 case Button_RadioButton:
2020 case Button_SquareButton: {
2021 NSButton *bc = [[NSButton alloc] init];
2022 bc.title = @"";
2023 // See below for style and bezel setting.
2024 bv = bc;
2025 break;
2026 }
2027 case Button_PopupButton:
2028 case Button_PullDown: {
2029 NSPopUpButton *bc = [[NSPopUpButton alloc] init];
2030 bc.title = @"";
2031 if (widget.type == Button_PullDown)
2032 bc.pullsDown = YES;
2033 bv = bc;
2034 break;
2035 }
2036 case Button_WindowClose:
2037 case Button_WindowMiniaturize:
2038 case Button_WindowZoom: {
2039 const NSWindowButton button = [=] {
2040 switch (widget.type) {
2041 case Button_WindowClose:
2042 return NSWindowCloseButton;
2043 case Button_WindowMiniaturize:
2044 return NSWindowMiniaturizeButton;
2045 case Button_WindowZoom:
2046 return NSWindowZoomButton;
2047 default:
2048 break;
2049 }
2050 Q_UNREACHABLE();
2051 } ();
2052 const auto styleMask = NSWindowStyleMaskTitled
2053 | NSWindowStyleMaskClosable
2054 | NSWindowStyleMaskMiniaturizable
2055 | NSWindowStyleMaskResizable;
2056 bv = [NSWindow standardWindowButton:button forStyleMask:styleMask];
2057 [bv retain];
2058 break;
2059 }
2060 case ComboBox:
2061 bv = [[NSComboBox alloc] init];
2062 break;
2063 case ProgressIndicator_Determinate:
2064 bv = [[NSProgressIndicator alloc] init];
2065 break;
2066 case ProgressIndicator_Indeterminate:
2067 bv = [[QIndeterminateProgressIndicator alloc] init];
2068 break;
2069 case Scroller_Horizontal:
2070 bv = [[NSScroller alloc] initWithFrame:NSMakeRect(0, 0, 200, 20)];
2071 break;
2072 case Scroller_Vertical:
2073 // Cocoa sets the orientation from the view's frame
2074 // at construction time, and it cannot be changed later.
2075 bv = [[NSScroller alloc] initWithFrame:NSMakeRect(0, 0, 20, 200)];
2076 break;
2077 case Slider_Horizontal:
2078 bv = [[NSSlider alloc] initWithFrame:NSMakeRect(0, 0, 200, 20)];
2079 break;
2080 case Slider_Vertical:
2081 // Cocoa sets the orientation from the view's frame
2082 // at construction time, and it cannot be changed later.
2083 bv = [[NSSlider alloc] initWithFrame:NSMakeRect(0, 0, 20, 200)];
2084 break;
2085 case SplitView_Horizontal:
2086 bv = [[NSSplitView alloc] init];
2087 break;
2088 case SplitView_Vertical:
2089 bv = [[QVerticalSplitView alloc] init];
2090 break;
2091 case TextField:
2092 bv = [[NSTextField alloc] init];
2093 break;
2094 default:
2095 break;
2096 }
2097
2098 if ([bv isKindOfClass:[NSControl class]]) {
2099 auto *ctrl = static_cast<NSControl *>(bv);
2100 switch (widget.size) {
2101 case QStyleHelper::SizeSmall:
2102 ctrl.controlSize = NSControlSizeSmall;
2103 break;
2104 case QStyleHelper::SizeMini:
2105 ctrl.controlSize = NSControlSizeMini;
2106 break;
2107 default:
2108 break;
2109 }
2110 } else if (widget.type == ProgressIndicator_Determinate ||
2111 widget.type == ProgressIndicator_Indeterminate) {
2112 auto *pi = static_cast<NSProgressIndicator *>(bv);
2113 pi.indeterminate = (widget.type == ProgressIndicator_Indeterminate);
2114 switch (widget.size) {
2115 case QStyleHelper::SizeSmall:
2116 pi.controlSize = NSControlSizeSmall;
2117 break;
2118 case QStyleHelper::SizeMini:
2119 pi.controlSize = NSControlSizeMini;
2120 break;
2121 default:
2122 break;
2123 }
2124 }
2125
2126 cocoaControls.insert(widget, bv);
2127 }
2128
2129 NSButtonType buttonType;
2130 NSBezelStyle bezelStyle;
2131 if (widget.getCocoaButtonTypeAndBezelStyle(&buttonType, &bezelStyle)) {
2132 // FIXME We need to reset the button's type and
2133 // bezel style properties, even when cached.
2134 auto *button = static_cast<NSButton *>(bv);
2135 button.buttonType = buttonType;
2136 button.bezelStyle = bezelStyle;
2137 if (widget.type == Button_CheckBox)
2138 button.allowsMixedState = YES;
2139 }
2140
2141 return bv;
2142}
2143
2144NSCell *QMacStylePrivate::cocoaCell(CocoaControl widget) const
2145{
2146 NSCell *cell = cocoaCells[widget];
2147 if (!cell) {
2148 switch (widget.type) {
2149 case Stepper:
2150 cell = [[NSStepperCell alloc] init];
2151 break;
2152 case Button_Disclosure: {
2153 NSButtonCell *bc = [[NSButtonCell alloc] init];
2154 bc.buttonType = NSButtonTypeOnOff;
2155 bc.bezelStyle = NSBezelStyleDisclosure;
2156 cell = bc;
2157 break;
2158 }
2159 default:
2160 break;
2161 }
2162
2163 switch (widget.size) {
2164 case QStyleHelper::SizeSmall:
2165 cell.controlSize = NSControlSizeSmall;
2166 break;
2167 case QStyleHelper::SizeMini:
2168 cell.controlSize = NSControlSizeMini;
2169 break;
2170 default:
2171 break;
2172 }
2173
2174 cocoaCells.insert(widget, cell);
2175 }
2176
2177 return cell;
2178}
2179
2180void QMacStylePrivate::drawNSViewInRect(NSView *view, const QRectF &rect, QPainter *p,
2181 __attribute__((noescape)) DrawRectBlock drawRectBlock) const
2182{
2183 QMacCGContext ctx(p);
2184 if (!ctx) {
2185 qCWarning(lcMacStyle) << "Invalid (nullptr) graphics context, cannot draw NSView.";
2186 return;
2187 }
2188 setupNSGraphicsContext(ctx, YES);
2189
2190 // FIXME: The rect that we get in is relative to the widget that we're drawing
2191 // style on behalf of, and doesn't take into account the offset of that widget
2192 // to the widget that owns the backingstore, which we are placing the native
2193 // view into below. This means most of the views are placed in the upper left
2194 // corner of backingStoreNSView, which does not map to where the actual widget
2195 // is, and which may cause problems such as triggering a setNeedsDisplay of the
2196 // backingStoreNSView for the wrong rect. We work around this by making the view
2197 // layer-backed, which prevents triggering display of the backingStoreNSView, but
2198 // but there may be other issues lurking here due to the wrong position. QTBUG-68023
2199 view.wantsLayer = YES;
2200
2201 // FIXME: We are also setting the frame of the incoming view a lot at the call
2202 // sites of this function, making it unclear who's actually responsible for
2203 // maintaining the size and position of the view. In theory the call sites
2204 // should ensure the _size_ of the view is correct, and then let this code
2205 // take care of _positioning_ the view at the right place inside backingStoreNSView.
2206 // For now we pass on the rect as is, to prevent any regressions until this
2207 // can be investigated properly.
2208 view.frame = rect.toCGRect();
2209
2210 [backingStoreNSView addSubview:view];
2211
2212 // FIXME: Based on the code below, this method isn't drawing an NSView into
2213 // a rect, it's drawing _part of the NSView_, defined by the incoming clip
2214 // or dirty rect, into the current graphics context. We're doing some manual
2215 // translations at the call sites that would indicate that this relationship
2216 // is a bit fuzzy.
2217 const CGRect dirtyRect = rect.toCGRect();
2218
2219 if (drawRectBlock)
2220 drawRectBlock(ctx, dirtyRect);
2221 else
2222 [view drawRect:dirtyRect];
2223
2224 [view removeFromSuperviewWithoutNeedingDisplay];
2225
2226 restoreNSGraphicsContext(ctx);
2227}
2228
2229void QMacStylePrivate::resolveCurrentNSView(QWindow *window) const
2230{
2231 backingStoreNSView = window ? (NSView *)window->winId() : nil;
2232}
2233
2234void QMacStylePrivate::drawProgressBar(QPainter* p, const QStyleOptionProgressBar *pb) const
2235{
2236 const qreal progress = pb->progress / double(pb->maximum - pb->minimum);
2237 const bool indeterminate = (pb->minimum == 0 && pb->maximum == 0);
2238 const bool vertical = !(pb->state & QStyle::State_Horizontal);
2239 const bool inverted = pb->invertedAppearance || (!vertical && (pb->direction == Qt::RightToLeft));
2240 QRect rect = pb->rect;
2241
2242 // The height of a (horizontal) progressbar is fixed, and is found to have
2243 // a value of 8 (from eyeballing an NSProgressIndicator in XCode 26)
2244 const qreal fixedSize = 8;
2245 const qreal radius = fixedSize / 2.;
2246
2247 QRectF groove;
2248 QRectF track;
2249
2250 if (vertical)
2251 groove = QRectF((rect.width() - fixedSize) / 2, rect.y(), fixedSize, rect.height());
2252 else
2253 groove = QRectF(rect.x(), (rect.height() - fixedSize) / 2, rect.width(), fixedSize);
2254
2255 if (indeterminate) {
2256 const qreal velocity = 100;
2257 const qreal minBlockSize = 15;
2258 const qreal maxBlockFraction = 0.25;
2259
2260 // We use a static timer to dermine the progress position, since
2261 // all indeterminate progressbars should animate in sync.
2262 static QElapsedTimer timer;
2263 if (!timer.isValid())
2264 timer.start();
2265
2266 const qreal time = (timer.elapsed() / (1000.0 / 60.0));
2267 const qreal normalizedPos = 0.5 - (0.5 * std::cos(time / velocity * 2 * M_PI)); // 0 -> 1
2268
2269 if (vertical) {
2270 const qreal maxBlockSize = rect.height() * maxBlockFraction;
2271 const qreal margin = (maxBlockSize - minBlockSize) / (2 * rect.height());
2272 const qreal pos = -margin + (normalizedPos * (1 + (margin * 2)));
2273 const qreal pixelPos = pos * rect.height();
2274 const qreal top = pixelPos > (maxBlockSize / 2) ? pixelPos - (maxBlockSize / 2) : 0;
2275 const qreal bottom = pixelPos > rect.height() - (maxBlockSize / 2)
2276 ? rect.height() : pixelPos + (maxBlockSize / 2);
2277 track = QRectF((rect.width() - fixedSize) / 2, top, fixedSize, bottom - top);
2278 } else {
2279 const qreal maxBlockSize = rect.width() * maxBlockFraction;
2280 const qreal margin = (maxBlockSize - minBlockSize) / (2 * rect.width());
2281 const qreal pos = -margin + (normalizedPos * (1 + (margin * 2)));
2282 const qreal pixelPos = pos * rect.width();
2283 const qreal left = pixelPos > (maxBlockSize / 2) ? pixelPos - (maxBlockSize / 2) : 0;
2284 const qreal right = pixelPos > rect.width() - (maxBlockSize / 2)
2285 ? rect.width() : pixelPos + (maxBlockSize / 2);
2286 track = QRectF(left, (rect.height() - fixedSize) / 2, right - left, fixedSize);
2287 }
2288 } else {
2289 if (vertical) {
2290 const qreal trackSize = rect.height() * progress;
2291 if (inverted)
2292 track = QRectF((rect.width() - fixedSize) / 2, rect.y(), fixedSize, trackSize);
2293 else
2294 track = QRectF((rect.width() - fixedSize) / 2, rect.height() - trackSize, fixedSize, trackSize);
2295 } else {
2296 const qreal trackSize = rect.width() * progress;
2297 if (inverted)
2298 track = QRectF(rect.width() - trackSize, (rect.height() - fixedSize) / 2, trackSize, fixedSize);
2299 else
2300 track = QRectF(rect.x(), (rect.height() - fixedSize) / 2, trackSize, fixedSize);
2301 }
2302 }
2303
2304 // Draw groove
2305 p->save();
2306 p->setRenderHint(QPainter::Antialiasing, true);
2307 if (@available(macOS 14.0, *)) { // silence compiler
2308 p->setPen(qt_mac_toQBrush([NSColor secondarySystemFillColor]).color());
2309 p->setBrush(qt_mac_toQBrush([NSColor tertiarySystemFillColor]).color());
2310 } else {
2311 p->setPen(Qt::NoPen);
2312 p->setBrush(qt_mac_toQBrush([NSColor controlColor]).color());
2313 }
2314 p->drawRoundedRect(groove, radius, radius);
2315
2316 // Draw track / progress
2317 p->setPen(Qt::NoPen);
2318 p->setBrush(pb->state & QStyle::State_Active ? pb->palette.accent().color() : Qt::lightGray);
2319 p->drawRoundedRect(track, radius, radius);
2320 p->restore();
2321}
2322
2324{
2325 return new QMacApperanceStyle<QMacStyle, QStyleOption, QStyleOptionComplex>;
2326}
2327
2328QMacStyle::QMacStyle()
2329 : QCommonStyle(*new QMacStylePrivate)
2330{
2331 QMacAutoReleasePool pool;
2332
2333 static QMacNotificationObserver scrollbarStyleObserver(nil,
2334 NSPreferredScrollerStyleDidChangeNotification, []() {
2335 // Purge destroyed scroll bars
2336 QMacStylePrivate::scrollBars.removeAll(QPointer<QObject>());
2337
2338 QEvent event(QEvent::StyleChange);
2339 for (const auto &o : QMacStylePrivate::scrollBars)
2340 QCoreApplication::sendEvent(o, &event);
2341 });
2342}
2343
2345{
2346}
2347
2348void QMacStyle::polish(QPalette &)
2349{
2350 Q_D(QMacStyle);
2351 for (NSView *b : d->cocoaControls)
2352 [b release];
2353 d->cocoaControls.clear();
2354}
2355
2356void QMacStyle::polish(QApplication *)
2357{
2358}
2359
2360void QMacStyle::unpolish(QApplication *)
2361{
2362}
2363
2364void QMacStyle::polish(QWidget* w)
2365{
2366 Q_D(QMacStyle);
2367 if (!d->smallSystemFont && QGuiApplicationPrivate::platformTheme()) {
2368 if (auto *ssf = QGuiApplicationPrivate::platformTheme()->font(QPlatformTheme::SmallFont))
2369 d->smallSystemFont = *ssf;
2370 else
2371 d->smallSystemFont = QFont();
2372 }
2373
2374 if (false
2375#if QT_CONFIG(menu)
2376 || qobject_cast<QMenu*>(w)
2377# if QT_CONFIG(combobox)
2378 || qobject_cast<QComboBoxPrivateContainer *>(w)
2379# endif
2380#endif
2381#if QT_CONFIG(mdiarea)
2382 || qobject_cast<QMdiSubWindow *>(w)
2383#endif
2384 ) {
2385 w->setAttribute(Qt::WA_TranslucentBackground, true);
2386 w->setAutoFillBackground(false);
2387 }
2388
2389#if QT_CONFIG(tabbar)
2390 if (QTabBar *tb = qobject_cast<QTabBar*>(w)) {
2391 if (tb->documentMode()) {
2392 w->setAttribute(Qt::WA_Hover);
2393 w->setFont(qt_app_fonts_hash()->value("QSmallFont", QFont()));
2394 QPalette p = w->palette();
2395 p.setColor(QPalette::WindowText, QColor(17, 17, 17));
2396 w->setPalette(p);
2397 w->setAttribute(Qt::WA_SetPalette, false);
2398 w->setAttribute(Qt::WA_SetFont, false);
2399 }
2400 }
2401#endif
2402
2403 QCommonStyle::polish(w);
2404
2405 if (QRubberBand *rubber = qobject_cast<QRubberBand*>(w)) {
2406 rubber->setWindowOpacity(0.25);
2407 rubber->setAttribute(Qt::WA_PaintOnScreen, false);
2408 rubber->setAttribute(Qt::WA_NoSystemBackground, false);
2409 }
2410
2411 if (qobject_cast<QScrollBar*>(w)) {
2412 w->setAttribute(Qt::WA_OpaquePaintEvent, false);
2413 w->setAttribute(Qt::WA_Hover, true);
2414 w->setMouseTracking(true);
2415 }
2416}
2417
2418void QMacStyle::unpolish(QWidget* w)
2419{
2420 if (
2421#if QT_CONFIG(menu)
2422 qobject_cast<QMenu*>(w) &&
2423#endif
2424 !w->testAttribute(Qt::WA_SetPalette))
2425 {
2426 w->setPalette(QPalette());
2427 w->setWindowOpacity(1.0);
2428 }
2429
2430#if QT_CONFIG(combobox)
2431 if (QComboBox *combo = qobject_cast<QComboBox *>(w)) {
2432 if (!combo->isEditable()) {
2433 if (QWidget *widget = combo->findChild<QComboBoxPrivateContainer *>())
2434 widget->setWindowOpacity(1.0);
2435 }
2436 }
2437#endif
2438
2439#if QT_CONFIG(tabbar)
2440 if (qobject_cast<QTabBar*>(w)) {
2441 if (!w->testAttribute(Qt::WA_SetFont))
2442 w->setFont(QFont());
2443 if (!w->testAttribute(Qt::WA_SetPalette))
2444 w->setPalette(QPalette());
2445 }
2446#endif
2447
2448 if (QRubberBand *rubber = qobject_cast<QRubberBand*>(w)) {
2449 rubber->setWindowOpacity(1.0);
2450 rubber->setAttribute(Qt::WA_PaintOnScreen, true);
2451 rubber->setAttribute(Qt::WA_NoSystemBackground, true);
2452 }
2453
2454 if (QFocusFrame *frame = qobject_cast<QFocusFrame *>(w))
2455 frame->setAttribute(Qt::WA_NoSystemBackground, true);
2456
2457 QCommonStyle::unpolish(w);
2458
2459 if (qobject_cast<QScrollBar*>(w)) {
2460 w->setAttribute(Qt::WA_OpaquePaintEvent, true);
2461 w->setAttribute(Qt::WA_Hover, false);
2462 w->setMouseTracking(false);
2463 }
2464}
2465
2466int QMacStyle::pixelMetric(PixelMetric metric, const QStyleOption *opt, const QWidget *widget) const
2467{
2468 Q_D(const QMacStyle);
2469 const int controlSize = getControlSize(opt, widget);
2470 int ret = 0;
2471
2472 switch (metric) {
2473#if QT_CONFIG(tabbar)
2474 case PM_TabCloseIndicatorWidth:
2475 case PM_TabCloseIndicatorHeight:
2476 ret = closeButtonSize;
2477 break;
2478#endif
2479 case PM_ToolBarIconSize:
2480 ret = proxy()->pixelMetric(PM_LargeIconSize);
2481 break;
2482 case PM_FocusFrameVMargin:
2483 case PM_FocusFrameHMargin:
2485 break;
2486
2487 case PM_MenuBarHMargin:
2488 ret = 8;
2489 break;
2490
2491 case PM_MenuBarVMargin:
2492 ret = 0;
2493 break;
2494
2495 case PM_MenuBarPanelWidth:
2496 ret = 0;
2497 break;
2498
2499 case PM_MenuButtonIndicator:
2500 ret = toolButtonArrowSize;
2501 break;
2502
2503 case QStyle::PM_MenuDesktopFrameWidth:
2504 ret = 5;
2505 break;
2506
2507 case PM_CheckBoxLabelSpacing:
2508 case PM_RadioButtonLabelSpacing:
2509 ret = [=] {
2510 if (opt) {
2511 if (opt->state & State_Mini)
2512 return 4;
2513 if (opt->state & State_Small)
2514 return 3;
2515 }
2516 return 2;
2517 } ();
2518 break;
2519 case PM_MenuScrollerHeight:
2520 ret = 15; // I hate having magic numbers in here...
2521 break;
2522 case PM_DefaultFrameWidth:
2523#if QT_CONFIG(mainwindow)
2524 if (widget && (widget->isWindow() || !widget->parentWidget()
2525 || (qobject_cast<const QMainWindow*>(widget->parentWidget())
2526 && static_cast<QMainWindow *>(widget->parentWidget())->centralWidget() == widget))
2527 && qobject_cast<const QAbstractScrollArea *>(widget))
2528 ret = 0;
2529 else
2530#endif
2531 // The combo box popup has no frame.
2532 if (qstyleoption_cast<const QStyleOptionComboBox *>(opt) != 0)
2533 ret = 0;
2534 else
2535 ret = 1;
2536 break;
2537 case PM_MaximumDragDistance:
2538 ret = -1;
2539 break;
2540 case PM_ScrollBarSliderMin:
2541 ret = 24;
2542 break;
2543 case PM_SpinBoxFrameWidth:
2545 break;
2546 case PM_ButtonShiftHorizontal:
2547 case PM_ButtonShiftVertical:
2548 ret = 0;
2549 break;
2550 case PM_SliderLength:
2551 ret = 17;
2552 break;
2553 // Returns the number of pixels to use for the business part of the
2554 // slider (i.e., the non-tickmark portion). The remaining space is shared
2555 // equally between the tickmark regions.
2556 case PM_SliderControlThickness:
2557 if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
2558 int space = (sl->orientation == Qt::Horizontal) ? sl->rect.height() : sl->rect.width();
2559 int ticks = sl->tickPosition;
2560 int n = 0;
2561 if (ticks & QSlider::TicksAbove)
2562 ++n;
2563 if (ticks & QSlider::TicksBelow)
2564 ++n;
2565 if (!n) {
2566 ret = space;
2567 break;
2568 }
2569
2570 int thick = 6; // Magic constant to get 5 + 16 + 5
2571 if (ticks != QSlider::TicksBothSides && ticks != QSlider::NoTicks)
2572 thick += proxy()->pixelMetric(PM_SliderLength, sl, widget) / 4;
2573
2574 space -= thick;
2575 if (space > 0)
2576 thick += (space * 2) / (n + 2);
2577 ret = thick;
2578 } else {
2579 ret = 0;
2580 }
2581 break;
2582 case PM_SmallIconSize:
2583 ret = int(QStyleHelper::dpiScaled(16., opt));
2584 break;
2585
2586 case PM_LargeIconSize:
2587 ret = int(QStyleHelper::dpiScaled(32., opt));
2588 break;
2589
2590 case PM_IconViewIconSize:
2591 ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget);
2592 break;
2593
2594 case PM_ButtonDefaultIndicator:
2595 ret = 0;
2596 break;
2597 case PM_TitleBarHeight: {
2598 NSUInteger style = NSWindowStyleMaskTitled;
2599 if (widget && ((widget->windowFlags() & Qt::Tool) == Qt::Tool))
2600 style |= NSWindowStyleMaskUtilityWindow;
2601 ret = int([NSWindow frameRectForContentRect:NSZeroRect
2602 styleMask:style].size.height);
2603 break; }
2604 case QStyle::PM_TabBarTabHSpace:
2605 switch (d->aquaSizeConstrain(opt, widget)) {
2606 case QStyleHelper::SizeLarge:
2607 ret = QCommonStyle::pixelMetric(metric, opt, widget);
2608 break;
2609 case QStyleHelper::SizeSmall:
2610 ret = 20;
2611 break;
2612 case QStyleHelper::SizeMini:
2613 ret = 16;
2614 break;
2615 case QStyleHelper::SizeDefault:
2616#if QT_CONFIG(tabbar)
2617 const QStyleOptionTab *tb = qstyleoption_cast<const QStyleOptionTab *>(opt);
2618 if (tb && tb->documentMode)
2619 ret = 30;
2620 else
2621#endif
2622 ret = QCommonStyle::pixelMetric(metric, opt, widget);
2623 break;
2624 }
2625 break;
2626 case PM_TabBarTabVSpace:
2627 ret = 4;
2628 break;
2629 case PM_TabBarTabShiftHorizontal:
2630 case PM_TabBarTabShiftVertical:
2631 ret = 0;
2632 break;
2633 case PM_TabBarBaseHeight:
2634 ret = 0;
2635 break;
2636 case PM_TabBarTabOverlap:
2637 ret = 1;
2638 break;
2639 case PM_TabBarBaseOverlap:
2640 switch (d->aquaSizeConstrain(opt, widget)) {
2641 case QStyleHelper::SizeDefault:
2642 case QStyleHelper::SizeLarge:
2643 ret = 11;
2644 break;
2645 case QStyleHelper::SizeSmall:
2646 ret = 8;
2647 break;
2648 case QStyleHelper::SizeMini:
2649 ret = 7;
2650 break;
2651 }
2652 break;
2653 case PM_ScrollBarExtent: {
2654 const QStyleHelper::WidgetSizePolicy size = d->effectiveAquaSizeConstrain(opt, widget);
2655 ret = static_cast<int>([NSScroller
2656 scrollerWidthForControlSize:static_cast<NSControlSize>(size)
2657 scrollerStyle:[NSScroller preferredScrollerStyle]]);
2658 break; }
2659 case PM_IndicatorHeight: {
2660 switch (d->aquaSizeConstrain(opt, widget)) {
2661 case QStyleHelper::SizeDefault:
2662 case QStyleHelper::SizeLarge:
2664 break;
2665 case QStyleHelper::SizeMini:
2667 break;
2668 case QStyleHelper::SizeSmall:
2670 break;
2671 }
2672 break; }
2673 case PM_IndicatorWidth: {
2674 switch (d->aquaSizeConstrain(opt, widget)) {
2675 case QStyleHelper::SizeDefault:
2676 case QStyleHelper::SizeLarge:
2678 break;
2679 case QStyleHelper::SizeMini:
2681 break;
2682 case QStyleHelper::SizeSmall:
2684 break;
2685 }
2686 ++ret;
2687 break; }
2688 case PM_ExclusiveIndicatorHeight: {
2689 switch (d->aquaSizeConstrain(opt, widget)) {
2690 case QStyleHelper::SizeDefault:
2691 case QStyleHelper::SizeLarge:
2693 break;
2694 case QStyleHelper::SizeMini:
2696 break;
2697 case QStyleHelper::SizeSmall:
2699 break;
2700 }
2701 break; }
2702 case PM_ExclusiveIndicatorWidth: {
2703 switch (d->aquaSizeConstrain(opt, widget)) {
2704 case QStyleHelper::SizeDefault:
2705 case QStyleHelper::SizeLarge:
2707 break;
2708 case QStyleHelper::SizeMini:
2710 break;
2711 case QStyleHelper::SizeSmall:
2713 break;
2714 }
2715 ++ret;
2716 break; }
2717 case PM_MenuVMargin:
2718 ret = 4;
2719 break;
2720 case PM_MenuPanelWidth:
2721 ret = 0;
2722 break;
2723 case PM_ToolTipLabelFrameWidth:
2724 ret = 0;
2725 break;
2726 case PM_SizeGripSize: {
2727 QStyleHelper::WidgetSizePolicy aSize;
2728 if (widget && widget->window()->windowType() == Qt::Tool)
2729 aSize = QStyleHelper::SizeSmall;
2730 else
2731 aSize = QStyleHelper::SizeLarge;
2732 const QSize size = qt_aqua_get_known_size(CT_SizeGrip, opt, widget, QSize(), aSize);
2733 ret = size.width();
2734 break; }
2735 case PM_MdiSubWindowFrameWidth:
2736 ret = 1;
2737 break;
2738 case PM_DockWidgetFrameWidth:
2739 ret = 0;
2740 break;
2741 case PM_DockWidgetTitleMargin:
2742 ret = 0;
2743 break;
2744 case PM_DockWidgetSeparatorExtent:
2745 ret = 1;
2746 break;
2747 case PM_ToolBarHandleExtent:
2748 ret = 11;
2749 break;
2750 case PM_ToolBarItemMargin:
2751 ret = 0;
2752 break;
2753 case PM_ToolBarItemSpacing:
2754 ret = 4;
2755 break;
2756 case PM_SplitterWidth:
2757 ret = 7;
2758 break;
2759 case PM_LayoutLeftMargin:
2760 case PM_LayoutTopMargin:
2761 case PM_LayoutRightMargin:
2762 case PM_LayoutBottomMargin:
2763 {
2764 bool isWindow = false;
2765 if (opt) {
2766 isWindow = (opt->state & State_Window);
2767 } else if (widget) {
2768 isWindow = widget->isWindow();
2769 }
2770
2771 if (isWindow) {
2772 /*
2773 AHIG would have (20, 8, 10) here but that makes
2774 no sense. It would also have 14 for the top margin
2775 but this contradicts both Builder and most
2776 applications.
2777 */
2778 return_SIZE(20, 10, 10); // AHIG
2779 } else {
2780 // hack to detect QTabWidget
2781 if (widget && widget->parentWidget()
2782 && widget->parentWidget()->sizePolicy().controlType() == QSizePolicy::TabWidget) {
2783 if (metric == PM_LayoutTopMargin) {
2784 /*
2785 Builder would have 14 (= 20 - 6) instead of 12,
2786 but that makes the tab look disproportionate.
2787 */
2788 return_SIZE(12, 6, 6); // guess
2789 } else {
2790 return_SIZE(20 /* Builder */, 8 /* guess */, 8 /* guess */);
2791 }
2792 } else {
2793 /*
2794 Child margins are highly inconsistent in AHIG and Builder.
2795 */
2796 return_SIZE(12, 8, 6); // guess
2797 }
2798 }
2799 }
2800 case PM_LayoutHorizontalSpacing:
2801 case PM_LayoutVerticalSpacing:
2802 return -1;
2803 case PM_MenuHMargin:
2804 ret = 0;
2805 break;
2806 case PM_ToolBarExtensionExtent:
2807 ret = 21;
2808 break;
2809 case PM_ToolBarFrameWidth:
2810 ret = 1;
2811 break;
2812 case PM_ScrollView_ScrollBarOverlap: {
2813 const QStyle *realStyle = widget ? widget->style() : proxy();
2814 ret = realStyle->styleHint(SH_ScrollBar_Transient, opt, widget)
2815 ? realStyle->pixelMetric(PM_ScrollBarExtent, opt, widget)
2816 : 0;
2817 break;
2818 }
2819 default:
2820 ret = QCommonStyle::pixelMetric(metric, opt, widget);
2821 break;
2822 }
2823 return ret;
2824}
2825
2827{
2828 auto platformTheme = QGuiApplicationPrivate::platformTheme();
2829 auto styleNames = platformTheme->themeHint(QPlatformTheme::StyleNames);
2830 if (styleNames.toStringList().contains("macOS"))
2831 return QPalette(); // Inherit everything from theme
2832 else
2833 return QStyle::standardPalette();
2834}
2835
2836int QMacStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
2837 QStyleHintReturn *hret) const
2838{
2839 QMacAutoReleasePool pool;
2840
2841 int ret = 0;
2842 switch (sh) {
2843 case SH_Slider_SnapToValue:
2844 case SH_PrintDialog_RightAlignButtons:
2845 case SH_FontDialog_SelectAssociatedText:
2846 case SH_MenuBar_MouseTracking:
2847 case SH_Menu_MouseTracking:
2848 case SH_ComboBox_ListMouseTracking:
2849 case SH_MainWindow_SpaceBelowMenuBar:
2850 case SH_ItemView_ChangeHighlightOnFocus:
2851 ret = 1;
2852 break;
2853 case SH_ToolBox_SelectedPageTitleBold:
2854 ret = 0;
2855 break;
2856 case SH_DialogButtonBox_ButtonsHaveIcons:
2857 ret = 0;
2858 break;
2859 case SH_Menu_KeyboardSearch:
2860 ret = true;
2861 break;
2862 case SH_Menu_SpaceActivatesItem:
2863 ret = true;
2864 break;
2865 case SH_Slider_AbsoluteSetButtons:
2866 ret = Qt::LeftButton|Qt::MiddleButton;
2867 break;
2868 case SH_Slider_PageSetButtons:
2869 ret = 0;
2870 break;
2871 case SH_ScrollBar_ContextMenu:
2872 ret = false;
2873 break;
2874 case SH_TitleBar_AutoRaise:
2875 ret = true;
2876 break;
2877 case SH_Menu_AllowActiveAndDisabled:
2878 ret = false;
2879 break;
2880 case SH_Menu_SubMenuPopupDelay:
2881 ret = 100;
2882 break;
2883 case SH_Menu_SubMenuUniDirection:
2884 ret = true;
2885 break;
2886 case SH_Menu_SubMenuSloppySelectOtherActions:
2887 ret = false;
2888 break;
2889 case SH_Menu_SubMenuResetWhenReenteringParent:
2890 ret = true;
2891 break;
2892 case SH_Menu_SubMenuDontStartSloppyOnLeave:
2893 ret = true;
2894 break;
2895
2896 case SH_ScrollBar_LeftClickAbsolutePosition: {
2897 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
2898 bool result = [defaults boolForKey:@"AppleScrollerPagingBehavior"];
2899 const QStyleOptionSlider *sliderOpt = qstyleoption_cast<const QStyleOptionSlider*>(opt);
2900 if (sliderOpt && sliderOpt->keyboardModifiers & Qt::AltModifier)
2901 ret = !result;
2902 else
2903 ret = result;
2904 break; }
2905 case SH_TabBar_PreferNoArrows:
2906 ret = true;
2907 break;
2908 /*
2909 case SH_DialogButtons_DefaultButton:
2910 ret = QDialogButtons::Reject;
2911 break;
2912 */
2913 case SH_GroupBox_TextLabelVerticalAlignment:
2914 ret = Qt::AlignTop;
2915 break;
2916 case SH_ScrollView_FrameOnlyAroundContents:
2917 ret = QCommonStyle::styleHint(sh, opt, w, hret);
2918 break;
2919 case SH_Menu_FillScreenWithScroll:
2920 ret = false;
2921 break;
2922 case SH_Menu_Scrollable:
2923 ret = true;
2924 break;
2925 case SH_RichText_FullWidthSelection:
2926 ret = true;
2927 break;
2928 case SH_BlinkCursorWhenTextSelected:
2929 ret = false;
2930 break;
2931 case SH_Slider_StopMouseOverSlider:
2932 ret = true;
2933 break;
2934 case SH_ListViewExpand_SelectMouseType:
2935 ret = QEvent::MouseButtonRelease;
2936 break;
2937 case SH_TabBar_SelectMouseType:
2938#if QT_CONFIG(tabbar)
2939 if (const QStyleOptionTabBarBase *opt2 = qstyleoption_cast<const QStyleOptionTabBarBase *>(opt)) {
2940 ret = opt2->documentMode ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease;
2941 } else
2942#endif
2943 {
2944 ret = QEvent::MouseButtonRelease;
2945 }
2946 break;
2947 case SH_ComboBox_Popup:
2948 if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt))
2949 ret = !cmb->editable;
2950 else
2951 ret = 0;
2952 break;
2953 case SH_Workspace_FillSpaceOnMaximize:
2954 ret = true;
2955 break;
2956 case SH_Widget_ShareActivation:
2957 ret = true;
2958 break;
2959 case SH_Header_ArrowAlignment:
2960 ret = Qt::AlignRight;
2961 break;
2962 case SH_TabBar_Alignment: {
2963#if QT_CONFIG(tabwidget)
2964 if (const QTabWidget *tab = qobject_cast<const QTabWidget*>(w)) {
2965 if (tab->documentMode()) {
2966 ret = Qt::AlignLeft;
2967 break;
2968 }
2969 }
2970#endif
2971#if QT_CONFIG(tabbar)
2972 if (const QTabBar *tab = qobject_cast<const QTabBar*>(w)) {
2973 if (tab->documentMode()) {
2974 ret = Qt::AlignLeft;
2975 break;
2976 }
2977 }
2978#endif
2979 ret = Qt::AlignCenter;
2980 } break;
2981 case SH_ToolTipLabel_Opacity:
2982 ret = 242; // About 95%
2983 break;
2984 case SH_Button_FocusPolicy:
2985 ret = Qt::TabFocus;
2986 break;
2987 case SH_EtchDisabledText:
2988 ret = false;
2989 break;
2990 case SH_FocusFrame_Mask: {
2991 ret = true;
2992 if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
2993 const uchar fillR = 192, fillG = 191, fillB = 190;
2994 QImage img;
2995
2996 QSize pixmapSize = opt->rect.size();
2997 if (!pixmapSize.isEmpty()) {
2998 QPixmap pix(pixmapSize);
2999 pix.fill(QColor(fillR, fillG, fillB));
3000 QPainter pix_paint(&pix);
3001 proxy()->drawControl(CE_FocusFrame, opt, &pix_paint, w);
3002 pix_paint.end();
3003 img = pix.toImage();
3004 }
3005
3006 const QRgb *sptr = (QRgb*)img.bits(), *srow;
3007 const qsizetype sbpl = img.bytesPerLine();
3008 const int w = sbpl/4, h = img.height();
3009
3010 QImage img_mask(img.width(), img.height(), QImage::Format_ARGB32);
3011 QRgb *dptr = (QRgb*)img_mask.bits(), *drow;
3012 const qsizetype dbpl = img_mask.bytesPerLine();
3013
3014 for (int y = 0; y < h; ++y) {
3015 srow = sptr+((y*sbpl)/4);
3016 drow = dptr+((y*dbpl)/4);
3017 for (int x = 0; x < w; ++x) {
3018 const int redDiff = qRed(*srow) - fillR;
3019 const int greenDiff = qGreen(*srow) - fillG;
3020 const int blueDiff = qBlue(*srow) - fillB;
3021 const int diff = (redDiff * redDiff) + (greenDiff * greenDiff) + (blueDiff * blueDiff);
3022 (*drow++) = (diff < 10) ? 0xffffffff : 0xff000000;
3023 ++srow;
3024 }
3025 }
3026 QBitmap qmask = QBitmap::fromImage(img_mask);
3027 mask->region = QRegion(qmask);
3028 }
3029 break; }
3030 case SH_TitleBar_NoBorder:
3031 ret = 1;
3032 break;
3033 case SH_RubberBand_Mask:
3034 ret = 0;
3035 break;
3036 case SH_ComboBox_LayoutDirection:
3037 ret = Qt::LeftToRight;
3038 break;
3039 case SH_ItemView_EllipsisLocation:
3040 ret = Qt::AlignHCenter;
3041 break;
3042 case SH_ItemView_ShowDecorationSelected:
3043 ret = true;
3044 break;
3045 case SH_TitleBar_ModifyNotification:
3046 ret = false;
3047 break;
3048 case SH_ScrollBar_RollBetweenButtons:
3049 ret = true;
3050 break;
3051 case SH_WindowFrame_Mask:
3052 ret = false;
3053 break;
3054 case SH_TabBar_ElideMode:
3055 ret = Qt::ElideRight;
3056 break;
3057#if QT_CONFIG(dialogbuttonbox)
3058 case SH_DialogButtonLayout:
3059 ret = QDialogButtonBox::MacLayout;
3060 break;
3061#endif
3062 case SH_FormLayoutWrapPolicy:
3063 ret = QFormLayout::DontWrapRows;
3064 break;
3065 case SH_FormLayoutFieldGrowthPolicy:
3066 ret = QFormLayout::FieldsStayAtSizeHint;
3067 break;
3068 case SH_FormLayoutFormAlignment:
3069 ret = Qt::AlignHCenter | Qt::AlignTop;
3070 break;
3071 case SH_FormLayoutLabelAlignment:
3072 ret = Qt::AlignRight;
3073 break;
3074 case SH_ComboBox_PopupFrameStyle:
3075 ret = QFrame::NoFrame;
3076 break;
3077 case SH_MessageBox_TextInteractionFlags:
3078 ret = Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse | Qt::TextSelectableByKeyboard;
3079 break;
3080 case SH_MessageBox_CenterButtons:
3081 ret = false;
3082 break;
3083 case SH_MenuBar_AltKeyNavigation:
3084 ret = false;
3085 break;
3086 case SH_ItemView_MovementWithoutUpdatingSelection:
3087 ret = false;
3088 break;
3089 case SH_FocusFrame_AboveWidget:
3090 ret = true;
3091 break;
3092#if QT_CONFIG(wizard)
3093 case SH_WizardStyle:
3094 ret = QWizard::MacStyle;
3095 break;
3096#endif
3097 case SH_ItemView_ArrowKeysNavigateIntoChildren:
3098 ret = false;
3099 break;
3100 case SH_Menu_FlashTriggeredItem:
3101 ret = true;
3102 break;
3103 case SH_Menu_FadeOutOnHide:
3104 ret = true;
3105 break;
3106 case SH_ItemView_PaintAlternatingRowColorsForEmptyArea:
3107 ret = true;
3108 break;
3109#if QT_CONFIG(tabbar)
3110 case SH_TabBar_CloseButtonPosition:
3111 ret = QTabBar::LeftSide;
3112 break;
3113#endif
3114 case SH_DockWidget_ButtonsHaveFrame:
3115 ret = false;
3116 break;
3117 case SH_ScrollBar_Transient:
3118 if ((qobject_cast<const QScrollBar *>(w) && w->parent() &&
3119 qobject_cast<QAbstractScrollArea*>(w->parent()->parent()))
3120#if QT_CONFIG(accessibility)
3121 || (opt && QStyleHelper::hasAncestor(opt->styleObject, QAccessible::ScrollBar))
3122#endif
3123 ) {
3124 ret = [NSScroller preferredScrollerStyle] == NSScrollerStyleOverlay;
3125 }
3126 break;
3127#if QT_CONFIG(itemviews)
3128 case SH_ItemView_ScrollMode:
3129 ret = QAbstractItemView::ScrollPerPixel;
3130 break;
3131#endif
3132 case SH_TitleBar_ShowToolTipsOnButtons:
3133 // min/max/close buttons on windows don't show tool tips
3134 ret = false;
3135 break;
3136 case SH_ComboBox_AllowWheelScrolling:
3137 ret = false;
3138 break;
3139 case SH_SpinBox_ButtonsInsideFrame:
3140 ret = false;
3141 break;
3142 case SH_Table_GridLineColor:
3143 ret = int(qt_mac_toQColor(NSColor.gridColor).rgba());
3144 break;
3145 case SH_TabBar_AllowWheelScrolling:
3146 ret = false;
3147 break;
3148 default:
3149 ret = QCommonStyle::styleHint(sh, opt, w, hret);
3150 break;
3151 }
3152 return ret;
3153}
3154
3155QPixmap QMacStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
3156 const QStyleOption *opt) const
3157{
3158 switch (iconMode) {
3159 case QIcon::Disabled: {
3160 QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
3161 int imgh = img.height();
3162 int imgw = img.width();
3163 QRgb pixel;
3164 for (int y = 0; y < imgh; ++y) {
3165 for (int x = 0; x < imgw; ++x) {
3166 pixel = img.pixel(x, y);
3167 img.setPixel(x, y, qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel),
3168 qAlpha(pixel) / 2));
3169 }
3170 }
3171 return QPixmap::fromImage(img);
3172 }
3173 default:
3174 ;
3175 }
3176 return QCommonStyle::generatedIconPixmap(iconMode, pixmap, opt);
3177}
3178
3179
3180QPixmap QMacStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
3181 const QWidget *widget) const
3182{
3183 // The default implementation of QStyle::standardIconImplementation() is to call standardPixmap()
3184 // I don't want infinite recursion so if we do get in that situation, just return the Window's
3185 // standard pixmap instead (since there is no mac-specific icon then). This should be fine until
3186 // someone changes how Windows standard
3187 // pixmap works.
3188 static bool recursionGuard = false;
3189
3190 if (recursionGuard)
3191 return QCommonStyle::standardPixmap(standardPixmap, opt, widget);
3192
3193 recursionGuard = true;
3194 QIcon icon = proxy()->standardIcon(standardPixmap, opt, widget);
3195 recursionGuard = false;
3196 int size;
3197 switch (standardPixmap) {
3198 default:
3199 size = 32;
3200 break;
3201 case SP_MessageBoxCritical:
3202 case SP_MessageBoxQuestion:
3203 case SP_MessageBoxInformation:
3204 case SP_MessageBoxWarning:
3205 size = 64;
3206 break;
3207 }
3208 qreal dpr = widget ? widget->devicePixelRatio() : qApp->devicePixelRatio();
3209 return icon.pixmap(QSize(size, size), dpr);
3210}
3211
3212QIcon QMacStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *option,
3213 const QWidget *widget) const
3214{
3215 switch (standardIcon) {
3216 case SP_ToolBarHorizontalExtensionButton:
3217 return QAppleIconEngine::fromTheme("chevron.forward.2");
3218 case SP_ToolBarVerticalExtensionButton:
3219 return QAppleIconEngine::fromTheme("chevron.down.2");
3220 default:
3221 break;
3222 }
3223
3224 return QCommonStyle::standardIcon(standardIcon, option, widget);
3225}
3226
3227void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
3228 const QWidget *w) const
3229{
3230 Q_D(const QMacStyle);
3231 QMacCGContext cg(p);
3232 if (!cg)
3233 qCWarning(lcMacStyle) << "drawPrimitive:" << pe << "invalid (nullptr) graphics context";
3234
3235 QWindow *window = w && w->window() ? w->window()->windowHandle() : nullptr;
3236 d->resolveCurrentNSView(window);
3237 switch (pe) {
3238 case PE_IndicatorArrowUp:
3239 case PE_IndicatorArrowDown:
3240 case PE_IndicatorArrowRight:
3241 case PE_IndicatorArrowLeft: {
3242 p->save();
3243 p->setRenderHint(QPainter::Antialiasing);
3244 const int xOffset = 1; // FIXME: opt->direction == Qt::LeftToRight ? 2 : -1;
3245 qreal halfSize = 0.5 * qMin(opt->rect.width(), opt->rect.height());
3246 const qreal penWidth = qMax(halfSize / 3.0, 1.25);
3247#if QT_CONFIG(toolbutton)
3248 if (const QToolButton *tb = qobject_cast<const QToolButton *>(w)) {
3249 // When stroking the arrow, make sure it fits in the tool button
3250 if (tb->arrowType() != Qt::NoArrow
3251 || tb->popupMode() == QToolButton::MenuButtonPopup)
3252 halfSize -= penWidth;
3253 }
3254#endif
3255
3256 QTransform transform;
3257 transform.translate(opt->rect.center().x() + xOffset, opt->rect.center().y() + 2);
3258 QPainterPath path;
3259 switch(pe) {
3260 default:
3261 case PE_IndicatorArrowDown:
3262 break;
3263 case PE_IndicatorArrowUp:
3264 transform.rotate(180);
3265 break;
3266 case PE_IndicatorArrowLeft:
3267 transform.rotate(90);
3268 break;
3269 case PE_IndicatorArrowRight:
3270 transform.rotate(-90);
3271 break;
3272 }
3273 p->setTransform(transform);
3274
3275 path.moveTo(-halfSize, -halfSize * 0.5);
3276 path.lineTo(0.0, halfSize * 0.5);
3277 path.lineTo(halfSize, -halfSize * 0.5);
3278
3279 const QPen arrowPen(opt->palette.text(), penWidth,
3280 Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
3281 p->strokePath(path, arrowPen);
3282 p->restore();
3283 break; }
3284#if QT_CONFIG(tabbar)
3285 case PE_FrameTabBarBase:
3286 if (const QStyleOptionTabBarBase *tbb
3287 = qstyleoption_cast<const QStyleOptionTabBarBase *>(opt)) {
3288 if (tbb->documentMode) {
3289 p->save();
3290 drawTabBase(p, tbb, w);
3291 p->restore();
3292 return;
3293 }
3294#if QT_CONFIG(tabwidget)
3295 QRegion region(tbb->rect);
3296 region -= tbb->tabBarRect.adjusted(3, 0, -3, 0);
3297 p->save();
3298 p->setClipRegion(region);
3299 QStyleOptionTabWidgetFrame twf;
3300 twf.QStyleOption::operator=(*tbb);
3301 twf.shape = tbb->shape;
3302 switch (QMacStylePrivate::tabDirection(twf.shape)) {
3303 case QMacStylePrivate::North:
3304 twf.rect = twf.rect.adjusted(0, 0, 0, 10);
3305 break;
3306 case QMacStylePrivate::South:
3307 twf.rect = twf.rect.adjusted(0, -10, 0, 0);
3308 break;
3309 case QMacStylePrivate::West:
3310 twf.rect = twf.rect.adjusted(0, 0, 10, 0);
3311 break;
3312 case QMacStylePrivate::East:
3313 twf.rect = twf.rect.adjusted(0, -10, 0, 0);
3314 break;
3315 }
3316 proxy()->drawPrimitive(PE_FrameTabWidget, &twf, p, w);
3317 p->restore();
3318#endif
3319 }
3320 break;
3321#endif
3322 case PE_PanelTipLabel:
3323 p->fillRect(opt->rect, opt->palette.brush(QPalette::ToolTipBase));
3324 break;
3325 case PE_FrameGroupBox:
3326 if (const auto *groupBox = qstyleoption_cast<const QStyleOptionFrame *>(opt))
3327 if (groupBox->features & QStyleOptionFrame::Flat) {
3328 QCommonStyle::drawPrimitive(pe, groupBox, p, w);
3329 break;
3330 }
3331#if QT_CONFIG(tabwidget)
3332 Q_FALLTHROUGH();
3333 case PE_FrameTabWidget:
3334#endif
3335 {
3336 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::Box, QStyleHelper::SizeLarge);
3337 auto *box = static_cast<NSBox *>(d->cocoaControl(cw));
3338 // FIXME Since macOS 10.14, simply calling drawRect: won't display anything anymore.
3339 // The AppKit team is aware of this and has proposed a couple of solutions.
3340 // The first solution was to call displayRectIgnoringOpacity:inContext: instead.
3341 // However, it doesn't seem to work on 10.13. More importantly, dark mode on 10.14
3342 // is extremely slow. Light mode works fine.
3343 // The second solution is to subclass NSBox and reimplement a trivial drawRect: which
3344 // would only call super. This works without any issue on 10.13, but a double border
3345 // shows on 10.14 in both light and dark modes.
3346 // The code below picks what works on each version and mode. On 10.13 and earlier, we
3347 // simply call drawRect: on a regular NSBox. On 10.14, we call displayRectIgnoringOpacity:
3348 // inContext:, but only in light mode. In dark mode, we use a custom NSBox subclass,
3349 // QDarkNSBox, of type NSBoxCustom. Its appearance is close enough to the real thing so
3350 // we can use this for now.
3351 auto adjustedRect = opt->rect;
3352 bool needTranslation = false;
3353 // FIXME: remove condition on macOS Mojave depending on the Qt's minimum version requirement.
3354 if (!qt_apple_runningWithLiquidGlass() && !isDarkMode()) {
3355 // In Aqua theme we have to use the 'default' NSBox (as opposite
3356 // to the 'custom' QDarkNSBox we use in dark theme). Since -drawRect:
3357 // does nothing in default NSBox, we call -displayRectIgnoringOpaticty:.
3358 // Unfortunately, the resulting box is smaller then the actual rect we
3359 // wanted. This can be seen, e.g. because tabs (buttons) are misaligned
3360 // vertically and even worse, if QTabWidget has autoFillBackground
3361 // set, this background overpaints NSBox making it to disappear.
3362 // We trick our NSBox to render in a larger rectangle, so that
3363 // the actual result (which is again smaller than requested),
3364 // more or less is what we really want. We'll have to adjust CTM
3365 // and translate accordingly.
3366 // NOTE: this adjustment is not needed on macOS Tahoe/Glass.
3367 adjustedRect.adjust(0, 0, 6, 6);
3368 needTranslation = true;
3369 }
3370 d->drawNSViewInRect(box, adjustedRect, p, ^(CGContextRef ctx, const CGRect &rect) {
3371#if QT_CONFIG(tabwidget)
3372 if (qobject_cast<QTabWidget *>(opt->styleObject))
3373 clipTabBarFrame(opt, this, ctx);
3374#endif
3375 CGContextTranslateCTM(ctx, 0, rect.origin.y + rect.size.height);
3376 CGContextScaleCTM(ctx, 1, -1);
3377 if ([box isMemberOfClass:QDarkNSBox.class]) {
3378 [box drawRect:rect];
3379 } else {
3380 if (needTranslation)
3381 CGContextTranslateCTM(ctx, -3.0, 5.0);
3382 [box displayRectIgnoringOpacity:box.bounds inContext:NSGraphicsContext.currentContext];
3383 }
3384 });
3385 break;
3386 }
3387 case PE_IndicatorToolBarSeparator: {
3388 QPainterPath path;
3389 if (opt->state & State_Horizontal) {
3390 int xpoint = opt->rect.center().x();
3391 path.moveTo(xpoint + 0.5, opt->rect.top() + 1);
3392 path.lineTo(xpoint + 0.5, opt->rect.bottom());
3393 } else {
3394 int ypoint = opt->rect.center().y();
3395 path.moveTo(opt->rect.left() + 2 , ypoint + 0.5);
3396 path.lineTo(opt->rect.right() + 1, ypoint + 0.5);
3397 }
3398 QPainterPathStroker theStroker;
3399 theStroker.setCapStyle(Qt::FlatCap);
3400 theStroker.setDashPattern(QVector<qreal>() << 1 << 2);
3401 path = theStroker.createStroke(path);
3402 const auto dark = isDarkMode() ? opt->palette.dark().color().darker()
3403 : QColor(0, 0, 0, 119);
3404 p->fillPath(path, dark);
3405 }
3406 break;
3407 case PE_FrameWindow:
3408 if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
3409 if (qobject_cast<const QMdiSubWindow*>(w)) {
3410 p->save();
3411 p->setPen(QPen(frame->palette.dark().color(), frame->lineWidth));
3412 p->setBrush(frame->palette.window());
3413 p->drawRect(frame->rect);
3414 p->restore();
3415 }
3416 }
3417 break;
3418 case PE_IndicatorDockWidgetResizeHandle: {
3419 // The docwidget resize handle is drawn as a one-pixel wide line.
3420 p->save();
3421 if (opt->state & State_Horizontal) {
3422 p->setPen(QColor(160, 160, 160));
3423 p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
3424 } else {
3425 p->setPen(QColor(145, 145, 145));
3426 p->drawLine(opt->rect.topRight(), opt->rect.bottomRight());
3427 }
3428 p->restore();
3429 } break;
3430 case PE_IndicatorToolBarHandle: {
3431 p->save();
3432 QPainterPath path;
3433 int x = opt->rect.x() + 6;
3434 int y = opt->rect.y() + 7;
3435 static const int RectHeight = 2;
3436 if (opt->state & State_Horizontal) {
3437 while (y < opt->rect.height() - RectHeight - 5) {
3438 path.moveTo(x, y);
3439 path.addEllipse(x, y, RectHeight, RectHeight);
3440 y += 6;
3441 }
3442 } else {
3443 while (x < opt->rect.width() - RectHeight - 5) {
3444 path.moveTo(x, y);
3445 path.addEllipse(x, y, RectHeight, RectHeight);
3446 x += 6;
3447 }
3448 }
3449 p->setPen(Qt::NoPen);
3450 QColor dark = opt->palette.dark().color().darker();
3451 dark.setAlphaF(0.50);
3452 p->fillPath(path, dark);
3453 p->restore();
3454
3455 break;
3456 }
3457 case PE_IndicatorHeaderArrow:
3458 if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
3459 // In HITheme, up is down, down is up and hamburgers eat people.
3460 if (header->sortIndicator != QStyleOptionHeader::None)
3461 proxy()->drawPrimitive(
3462 (header->sortIndicator == QStyleOptionHeader::SortDown) ?
3463 PE_IndicatorArrowUp : PE_IndicatorArrowDown, header, p, w);
3464 }
3465 break;
3466 case PE_IndicatorMenuCheckMark: {
3467 if (!cg) // CoreGraphics does not like nullptr contexts.
3468 break;
3469 QColor pc;
3470 if (opt->state & State_On)
3471 pc = opt->palette.highlightedText().color();
3472 else
3473 pc = opt->palette.text().color();
3474
3475 QCFType<CGColorRef> checkmarkColor = CGColorCreateGenericRGB(static_cast<CGFloat>(pc.redF()),
3476 static_cast<CGFloat>(pc.greenF()),
3477 static_cast<CGFloat>(pc.blueF()),
3478 static_cast<CGFloat>(pc.alphaF()));
3479 // kCTFontUIFontSystem and others give the same result
3480 // as kCTFontUIFontMenuItemMark. However, the latter is
3481 // more reminiscent to HITheme's kThemeMenuItemMarkFont.
3482 // See also the font for small- and mini-sized widgets,
3483 // where we end up using the generic system font type.
3484 const CTFontUIFontType fontType = (opt->state & State_Mini) ? kCTFontUIFontMiniSystem :
3485 (opt->state & State_Small) ? kCTFontUIFontSmallSystem :
3486 kCTFontUIFontMenuItemMark;
3487 // Similarly for the font size, where there is a small difference
3488 // between regular combobox and item view items, and and menu items.
3489 // However, we ignore any difference for small- and mini-sized widgets.
3490 const CGFloat fontSize = fontType == kCTFontUIFontMenuItemMark ? opt->fontMetrics.height() : 0.0;
3491 QCFType<CTFontRef> checkmarkFont = CTFontCreateUIFontForLanguage(fontType, fontSize, NULL);
3492
3493 CGContextSaveGState(cg);
3494 CGContextSetShouldSmoothFonts(cg, NO); // Same as HITheme and Cocoa menu checkmarks
3495
3496 // Baseline alignment tweaks for QComboBox and QMenu
3497 const CGFloat vOffset = (opt->state & State_Mini) ? 0.0 :
3498 (opt->state & State_Small) ? 1.0 :
3499 0.75;
3500
3501 CGContextTranslateCTM(cg, 0, opt->rect.bottom());
3502 CGContextScaleCTM(cg, 1, -1);
3503 // Translate back to the original position and add rect origin and offset
3504 CGContextTranslateCTM(cg, opt->rect.x(), vOffset);
3505
3506 // CTFont has severe difficulties finding the checkmark character among its
3507 // glyphs. Fortunately, CTLine knows its ways inside the Cocoa labyrinth.
3508 static const CFStringRef keys[] = { kCTFontAttributeName, kCTForegroundColorAttributeName };
3509 static const int numValues = sizeof(keys) / sizeof(keys[0]);
3510 const CFTypeRef values[] = { (CFTypeRef)checkmarkFont, (CFTypeRef)checkmarkColor };
3511 static_assert((sizeof(values) / sizeof(values[0])) == numValues);
3512 QCFType<CFDictionaryRef> attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void **)keys, (const void **)values,
3513 numValues, NULL, NULL);
3514 // U+2713: CHECK MARK
3515 QCFType<CFAttributedStringRef> checkmarkString = CFAttributedStringCreate(kCFAllocatorDefault, (CFStringRef)@"\u2713", attributes);
3516 QCFType<CTLineRef> line = CTLineCreateWithAttributedString(checkmarkString);
3517
3518 CTLineDraw((CTLineRef)line, cg);
3519 CGContextFlush(cg); // CTLineDraw's documentation says it doesn't flush
3520
3521 CGContextRestoreGState(cg);
3522 break; }
3523 case PE_IndicatorItemViewItemCheck:
3524 case PE_IndicatorRadioButton:
3525 case PE_IndicatorCheckBox: {
3526 const bool isEnabled = opt->state & State_Enabled;
3527 const bool isPressed = opt->state & State_Sunken;
3528 const bool isRadioButton = (pe == PE_IndicatorRadioButton);
3529 const auto ct = isRadioButton ? QMacStylePrivate::Button_RadioButton : QMacStylePrivate::Button_CheckBox;
3530 const auto cs = d->effectiveAquaSizeConstrain(opt, w);
3531 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
3532 auto *tb = static_cast<NSButton *>(d->cocoaControl(cw));
3533 tb.enabled = isEnabled;
3534 tb.state = (opt->state & State_NoChange) ? NSControlStateValueMixed :
3535 (opt->state & State_On) ? NSControlStateValueOn : NSControlStateValueOff;
3536 [tb highlight:isPressed];
3537 const auto vOffset = [=] {
3538 // As measured
3539 if (cs == QStyleHelper::SizeMini)
3540 return ct == QMacStylePrivate::Button_CheckBox ? -0.5 : 0.5;
3541
3542 return cs == QStyleHelper::SizeSmall ? 0.5 : 0.0;
3543 } ();
3544 d->drawNSViewInRect(tb, opt->rect, p, ^(CGContextRef ctx, const CGRect &rect) {
3545 CGContextTranslateCTM(ctx, rect.origin.x, rect.origin.y + vOffset);
3546 [tb.cell drawInteriorWithFrame:tb.bounds inView:tb];
3547 });
3548 break; }
3549 case PE_FrameFocusRect:
3550 // Use the our own focus widget stuff.
3551 break;
3552 case PE_IndicatorBranch: {
3553 if (!(opt->state & State_Children))
3554 break;
3555 if (!cg)
3556 break;
3557 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::Button_Disclosure, QStyleHelper::SizeLarge);
3558 NSButtonCell *triangleCell = static_cast<NSButtonCell *>(d->cocoaCell(cw));
3559 [triangleCell setState:(opt->state & State_Open) ? NSControlStateValueOn : NSControlStateValueOff];
3560 bool viewHasFocus = (w && w->hasFocus()) || (opt->state & State_HasFocus);
3561 [triangleCell setBackgroundStyle:((opt->state & State_Selected) && viewHasFocus) ? NSBackgroundStyleEmphasized : NSBackgroundStyleNormal];
3562 [triangleCell setUserInterfaceLayoutDirection:qt_macLayoutDirectionFromQt(opt->direction)];
3563
3564 d->setupNSGraphicsContext(cg, NO);
3565
3566 QRect qtRect = opt->rect.adjusted(DisclosureOffset, 0, -DisclosureOffset, 0);
3567 CGRect rect = CGRectMake(qtRect.x() + 1, qtRect.y(), qtRect.width(), qtRect.height());
3568 CGContextTranslateCTM(cg, rect.origin.x, rect.origin.y + rect.size.height);
3569 CGContextScaleCTM(cg, 1, -1);
3570 CGContextTranslateCTM(cg, -rect.origin.x, -rect.origin.y);
3571
3572 [triangleCell drawBezelWithFrame:NSRectFromCGRect(rect) inView:[triangleCell controlView]];
3573
3574 d->restoreNSGraphicsContext(cg);
3575 break; }
3576
3577 case PE_Frame: {
3578 QPen oldPen = p->pen();
3579 p->setPen(opt->palette.base().color().darker(140));
3580 p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
3581 p->setPen(opt->palette.base().color().darker(180));
3582 p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
3583 p->setPen(oldPen);
3584 break; }
3585
3586 case PE_FrameLineEdit:
3587 if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
3588 if (frame->state & State_Sunken) {
3589 const bool isEnabled = opt->state & State_Enabled;
3590 const bool isReadOnly = opt->state & State_ReadOnly;
3591 const bool isRounded = frame->features & QStyleOptionFrame::Rounded;
3592 const auto cs = d->effectiveAquaSizeConstrain(opt, w, CT_LineEdit);
3593 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::TextField, cs);
3594 auto *tf = static_cast<NSTextField *>(d->cocoaControl(cw));
3595 tf.enabled = isEnabled;
3596 tf.editable = !isReadOnly;
3597 const QColor bgColor = frame->palette.brush(QPalette::Base).color();
3598 const bool hasCustomBackground = hasCustomTextFieldBackground(frame->palette);
3599 tf.bezeled = YES;
3600 static_cast<NSTextFieldCell *>(tf.cell).bezelStyle = isRounded ? NSTextFieldRoundedBezel : NSTextFieldSquareBezel;
3601 tf.frame = opt->rect.toCGRect();
3602 d->drawNSViewInRect(tf, opt->rect, p, ^(CGContextRef, const CGRect &rect) {
3603 if (!isDarkMode() && !hasCustomBackground) {
3604 // In 'Dark' mode controls are transparent, so we do not over-paint
3605 // the color in the background. In 'Light' mode we have to care
3606 // about the correct background color.
3607 // See the comments below for PE_PanelLineEdit.
3608 // A custom background color is painted by us further below, since
3609 // the Liquid Glass bezel ignores the cell's background color.
3610 CGContextRef cgContext = NSGraphicsContext.currentContext.CGContext;
3611 // See QMacCGContext, here we expect bitmap context created with
3612 // color space 'kCGColorSpaceSRGB', if it's something else - we
3613 // give up.
3614 if (cgContext ? bool(CGBitmapContextGetColorSpace(cgContext)) : false) {
3615 tf.drawsBackground = YES;
3616 tf.backgroundColor = [NSColor colorWithSRGBRed:bgColor.redF()
3617 green:bgColor.greenF()
3618 blue:bgColor.blueF()
3619 alpha:bgColor.alphaF()];
3620 if (bgColor.alpha() != 255) {
3621 // No way we can have it bezeled and transparent ...
3622 tf.bordered = YES;
3623 }
3624 }
3625 }
3626
3627 CGRect fixedRect = rect;
3628 if (qt_apple_runningWithLiquidGlass() && tf.bezeled) {
3629 // Bezeled text edit cells are drawn with a little offset to the left and
3630 // the size increase compared to the 'rect' we want it to be drawn in. As a
3631 // result, the cell's 'outline' is clipped away. Adjusting the rectangle
3632 // for this, so that it's inside the clip rect, as it was before Tahoe.
3633 // This is not the case for non-bezeled/square rect cells.
3634 fixedRect = CGRectInset(rect, 1., 1.);
3635 }
3636 [tf.cell drawWithFrame:fixedRect inView:tf];
3637 });
3638 if (hasCustomBackground)
3639 drawTextFieldCustomBackground(p, opt->rect, bgColor);
3640 } else {
3641 QCommonStyle::drawPrimitive(pe, opt, p, w);
3642 }
3643 }
3644 break;
3645 case PE_PanelLineEdit:
3646 {
3647 const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(opt);
3648 // A custom background color must not be filled as a plain rectangle, it is
3649 // painted to follow the bezel's shape in PE_FrameLineEdit.
3650 const bool hasCustomBackground = panel && hasCustomTextFieldBackground(panel->palette);
3651 if ((panel && panel->lineWidth <= 0) || (isDarkMode() && !hasCustomBackground)) {
3652 // QCommonStyle::drawPrimitive(PE_PanelLineEdit) fill the background with
3653 // a proper color, defined in opt->palette and then, if lineWidth > 0, it
3654 // calls QMacStyle::drawPrimitive(PE_FrameLineEdit). We use NSTextFieldCell
3655 // to handle PE_FrameLineEdit, which will use system-default background.
3656 // In 'Dark' mode it's transparent and thus it's not over-painted.
3657 QCommonStyle::drawPrimitive(pe, opt, p, w);
3658 } else {
3659 // In 'Light' mode, if panel->lineWidth > 0, we have to use the correct
3660 // background color when drawing PE_FrameLineEdit, so let's call it
3661 // directly and set the proper color there.
3662 drawPrimitive(PE_FrameLineEdit, opt, p, w);
3663 }
3664
3665 // Draw the focus frame for widgets other than QLineEdit (e.g. for line edits in Webkit).
3666 // Focus frame is drawn outside the rectangle passed in the option-rect.
3667 if (panel) {
3668#if QT_CONFIG(lineedit)
3669 if ((opt->state & State_HasFocus) && !qobject_cast<const QLineEdit*>(w)) {
3670 int vmargin = pixelMetric(QStyle::PM_FocusFrameVMargin);
3671 int hmargin = pixelMetric(QStyle::PM_FocusFrameHMargin);
3672 QStyleOptionFrame focusFrame = *panel;
3673 focusFrame.rect = panel->rect.adjusted(-hmargin, -vmargin, hmargin, vmargin);
3674 drawControl(CE_FocusFrame, &focusFrame, p, w);
3675 }
3676#endif
3677 }
3678 }
3679 break;
3680 case PE_PanelScrollAreaCorner: {
3681 const QBrush brush(opt->palette.brush(QPalette::Base));
3682 p->fillRect(opt->rect, brush);
3683 p->setPen(QPen(QColor(217, 217, 217)));
3684 p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
3685 p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
3686 } break;
3687 case PE_FrameStatusBarItem:
3688 break;
3689#if QT_CONFIG(tabbar)
3690 case PE_IndicatorTabClose: {
3691 // Make close button visible only on the hovered tab.
3692 QTabBar *tabBar = qobject_cast<QTabBar*>(w->parentWidget());
3693 const QWidget *closeBtn = w;
3694 if (!tabBar) {
3695 // QStyleSheetStyle instead of CloseButton (which has
3696 // a QTabBar as a parent widget) uses the QTabBar itself:
3697 tabBar = qobject_cast<QTabBar *>(const_cast<QWidget*>(w));
3698 closeBtn = decltype(closeBtn)(property("_q_styleSheetRealCloseButton").value<void *>());
3699 }
3700 if (tabBar) {
3701 const bool documentMode = tabBar->documentMode();
3702 const QTabBarPrivate *tabBarPrivate = static_cast<QTabBarPrivate *>(QObjectPrivate::get(tabBar));
3703 const int hoveredTabIndex = tabBarPrivate->hoveredTabIndex();
3704 if (!documentMode ||
3705 (hoveredTabIndex != -1 && ((closeBtn == tabBar->tabButton(hoveredTabIndex, QTabBar::LeftSide)) ||
3706 (closeBtn == tabBar->tabButton(hoveredTabIndex, QTabBar::RightSide))))) {
3707 const bool hover = (opt->state & State_MouseOver);
3708 const bool selected = (opt->state & State_Selected);
3709 const bool pressed = (opt->state & State_Sunken);
3710 drawTabCloseButton(p, hover, selected, pressed, documentMode);
3711 }
3712 }
3713 } break;
3714#endif // QT_CONFIG(tabbar)
3715 case PE_PanelStatusBar: {
3716 p->fillRect(opt->rect, opt->palette.window());
3717
3718 // Draw the black separator line at the top of the status bar.
3719 if (w ? qt_macWindowMainWindow(w->window()) : (opt->state & QStyle::State_Active))
3720 p->setPen(titlebarSeparatorLineActive);
3721 else
3722 p->setPen(titlebarSeparatorLineInactive);
3723 p->drawLine(opt->rect.left(), opt->rect.top(), opt->rect.right(), opt->rect.top());
3724
3725 break;
3726 }
3727 case PE_PanelMenu: {
3728 p->save();
3729 p->fillRect(opt->rect, Qt::transparent);
3730 p->setPen(Qt::transparent);
3731 p->setBrush(opt->palette.window());
3732 p->setRenderHint(QPainter::Antialiasing, true);
3733 const QPainterPath path = d->windowPanelPath(opt->rect);
3734 p->drawPath(path);
3735 p->restore();
3736 } break;
3737
3738 default:
3739 QCommonStyle::drawPrimitive(pe, opt, p, w);
3740 break;
3741 }
3742}
3743
3744static QPixmap darkenPixmap(const QPixmap &pixmap)
3745{
3746 QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
3747 int imgh = img.height();
3748 int imgw = img.width();
3749 int h, s, v, a;
3750 QRgb pixel;
3751 for (int y = 0; y < imgh; ++y) {
3752 for (int x = 0; x < imgw; ++x) {
3753 pixel = img.pixel(x, y);
3754 a = qAlpha(pixel);
3755 QColor hsvColor(pixel);
3756 hsvColor.getHsv(&h, &s, &v);
3757 s = qMin(100, s * 2);
3758 v = v / 2;
3759 hsvColor.setHsv(h, s, v);
3760 pixel = hsvColor.rgb();
3761 img.setPixel(x, y, qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel), a));
3762 }
3763 }
3764 return QPixmap::fromImage(img);
3765}
3766
3767void QMacStylePrivate::setupVerticalInvertedXform(CGContextRef cg, bool reverse, bool vertical, const CGRect &rect) const
3768{
3769 if (vertical) {
3770 CGContextTranslateCTM(cg, rect.size.height, 0);
3771 CGContextRotateCTM(cg, M_PI_2);
3772 }
3773 if (vertical != reverse) {
3774 CGContextTranslateCTM(cg, rect.size.width, 0);
3775 CGContextScaleCTM(cg, -1, 1);
3776 }
3777}
3778
3779void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
3780 const QWidget *w) const
3781{
3782 Q_D(const QMacStyle);
3783 const QMacAutoReleasePool pool;
3784 QMacCGContext cg(p);
3785 if (!cg)
3786 qCWarning(lcMacStyle) << "drawControl:" << ce << "invalid (nullptr) graphics context";
3787
3788 QWindow *window = w && w->window() ? w->window()->windowHandle() : nullptr;
3789 d->resolveCurrentNSView(window);
3790 switch (ce) {
3791 case CE_HeaderSection:
3792 if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
3793 State flags = header->state;
3794 QRect ir = header->rect;
3795
3796
3797#if 0 // FIXME: What's this solving exactly?
3798 bool noVerticalHeader = true;
3799#if QT_CONFIG(tableview)
3800 if (w)
3801 if (const QTableView *table = qobject_cast<const QTableView *>(w->parentWidget()))
3802 noVerticalHeader = !table->verticalHeader()->isVisible();
3803#endif
3804
3805 const bool drawLeftBorder = header->orientation == Qt::Vertical
3806 || header->position == QStyleOptionHeader::OnlyOneSection
3807 || (header->position == QStyleOptionHeader::Beginning && noVerticalHeader);
3808#endif
3809
3810 const bool pressed = (flags & State_Sunken) && !(flags & State_On);
3811 p->fillRect(ir, pressed ? header->palette.dark() : header->palette.button());
3812 p->setPen(QPen(header->palette.dark(), 1.0));
3813 if (header->orientation == Qt::Horizontal)
3814 p->drawLine(QLineF(ir.right() + 0.5, ir.top() + headerSectionSeparatorInset,
3815 ir.right() + 0.5, ir.bottom() - headerSectionSeparatorInset));
3816 else
3817 p->drawLine(QLineF(ir.left() + headerSectionSeparatorInset, ir.bottom(),
3818 ir.right() - headerSectionSeparatorInset, ir.bottom()));
3819 }
3820
3821 break;
3822 case CE_ToolButtonLabel:
3823 if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
3824 QStyleOptionToolButton myTb = *tb;
3825 myTb.state &= ~State_AutoRaise;
3826#if QT_CONFIG(accessibility)
3827 if (QStyleHelper::hasAncestor(opt->styleObject, QAccessible::ToolBar)) {
3828 QRect cr = tb->rect;
3829 int shiftX = 0;
3830 int shiftY = 0;
3831 bool needText = false;
3832 int alignment = 0;
3833 bool down = tb->state & (State_Sunken | State_On);
3834 if (down) {
3835 shiftX = proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, w);
3836 shiftY = proxy()->pixelMetric(PM_ButtonShiftVertical, tb, w);
3837 }
3838 // The down state is special for QToolButtons in a toolbar on the Mac
3839 // The text is a bit bolder and gets a drop shadow and the icons are also darkened.
3840 // This doesn't really fit into any particular case in QIcon, so we
3841 // do the majority of the work ourselves.
3842 if (!(tb->features & QStyleOptionToolButton::Arrow)) {
3843 Qt::ToolButtonStyle tbstyle = tb->toolButtonStyle;
3844 if (tb->icon.isNull() && !tb->text.isEmpty())
3845 tbstyle = Qt::ToolButtonTextOnly;
3846
3847 switch (tbstyle) {
3848 case Qt::ToolButtonTextOnly: {
3849 needText = true;
3850 alignment = Qt::AlignCenter;
3851 break; }
3852 case Qt::ToolButtonIconOnly:
3853 case Qt::ToolButtonTextBesideIcon:
3854 case Qt::ToolButtonTextUnderIcon: {
3855 QRect pr = cr;
3856 QIcon::Mode iconMode = (tb->state & State_Enabled) ? QIcon::Normal
3857 : QIcon::Disabled;
3858 QIcon::State iconState = (tb->state & State_On) ? QIcon::On
3859 : QIcon::Off;
3860 QPixmap pixmap = tb->icon.pixmap(tb->rect.size().boundedTo(tb->iconSize), p->device()->devicePixelRatio(),
3861 iconMode, iconState);
3862
3863 // Draw the text if it's needed.
3864 if (tb->toolButtonStyle != Qt::ToolButtonIconOnly) {
3865 needText = true;
3866 QSizeF size = pixmap.deviceIndependentSize();
3867 if (tb->toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
3868 pr.setHeight(size.height() + 6);
3869 cr.adjust(0, pr.bottom(), 0, -3);
3870 alignment |= Qt::AlignCenter;
3871 } else {
3872 pr.setWidth(size.width() + 8);
3873 cr.adjust(pr.right(), 0, 0, 0);
3874 alignment |= Qt::AlignLeft | Qt::AlignVCenter;
3875 }
3876 }
3877 if (opt->state & State_Sunken) {
3878 pr.translate(shiftX, shiftY);
3879 pixmap = darkenPixmap(pixmap);
3880 }
3881 proxy()->drawItemPixmap(p, pr, Qt::AlignCenter, pixmap);
3882 break; }
3883 default:
3884 Q_ASSERT(false);
3885 break;
3886 }
3887
3888 if (needText) {
3889 QPalette pal = tb->palette;
3890 QPalette::ColorRole role = QPalette::NoRole;
3891 if (!proxy()->styleHint(SH_UnderlineShortcut, tb, w))
3892 alignment |= Qt::TextHideMnemonic;
3893 if (down)
3894 cr.translate(shiftX, shiftY);
3895 if (tbstyle == Qt::ToolButtonTextOnly
3896 || (tbstyle != Qt::ToolButtonTextOnly && !down)) {
3897 QPen pen = p->pen();
3898 QColor light = down || isDarkMode() ? Qt::black : Qt::white;
3899 light.setAlphaF(0.375f);
3900 p->setPen(light);
3901 p->drawText(cr.adjusted(0, 1, 0, 1), alignment, tb->text);
3902 p->setPen(pen);
3903 if (down && tbstyle == Qt::ToolButtonTextOnly) {
3904 pal = QApplication::palette("QMenu");
3905 pal.setCurrentColorGroup(tb->palette.currentColorGroup());
3906 role = QPalette::HighlightedText;
3907 }
3908 }
3909 proxy()->drawItemText(p, cr, alignment, pal,
3910 tb->state & State_Enabled, tb->text, role);
3911 }
3912 } else {
3913 QCommonStyle::drawControl(ce, &myTb, p, w);
3914 }
3915 } else
3916#endif // QT_CONFIG(accessibility)
3917 {
3918 QCommonStyle::drawControl(ce, &myTb, p, w);
3919 }
3920 }
3921 break;
3922 case CE_ToolBoxTabShape:
3923 QCommonStyle::drawControl(ce, opt, p, w);
3924 break;
3925 case CE_PushButtonBevel:
3926 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3927 if (!(btn->state & (State_Raised | State_Sunken | State_On)))
3928 break;
3929
3930 if (btn->features & QStyleOptionButton::CommandLinkButton) {
3931 QCommonStyle::drawControl(ce, opt, p, w);
3932 break;
3933 }
3934
3935 const bool hasFocus = btn->state & State_HasFocus;
3936 const bool isActive = btn->state & State_Active;
3937
3938 // a focused auto-default button within an active window
3939 // takes precedence over a normal default button
3940 if ((btn->features & QStyleOptionButton::AutoDefaultButton)
3941 && isActive && hasFocus)
3942 d->autoDefaultButton = btn->styleObject;
3943 else if (d->autoDefaultButton == btn->styleObject)
3944 d->autoDefaultButton = nullptr;
3945
3946 const bool isEnabled = btn->state & State_Enabled;
3947 const bool isPressed = btn->state & State_Sunken;
3948 const bool isHighlighted = isActive &&
3949 ((btn->state & State_On)
3950 || (btn->features & QStyleOptionButton::DefaultButton)
3951 || (btn->features & QStyleOptionButton::AutoDefaultButton
3952 && d->autoDefaultButton == btn->styleObject));
3953 const bool hasMenu = btn->features & QStyleOptionButton::HasMenu;
3954 const auto ct = cocoaControlType(btn, w);
3955 const auto cs = d->effectiveAquaSizeConstrain(btn, w);
3956 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
3957 auto *pb = static_cast<NSButton *>(d->cocoaControl(cw));
3958 // Ensure same size and location as we used to have with HITheme.
3959 // This is more convoluted than we initially thought. See for example
3960 // differences between plain and menu button frames.
3961 const QRectF frameRect = cw.adjustedControlFrame(btn->rect);
3962 pb.frame = frameRect.toCGRect();
3963
3964 pb.enabled = isEnabled;
3965
3966 // With the 'momentary push in' type this gives an impression of a
3967 // button in a 'pressed' state (the 'momentary push in' does
3968 // not show its state otherwise):
3969 [pb highlight:isPressed];
3970
3971
3972 if (cw.type == QMacStylePrivate::Button_SquareButton) {
3973 pb.state = isHighlighted && !isPressed ? NSControlStateValueOn : NSControlStateValueOff;
3974 } else {
3975 // For default/checked button this will give the required
3976 // button accent color:
3977 pb.keyEquivalent = isHighlighted ? @"\r" : @"";
3978 }
3979
3980 d->drawNSViewInRect(pb, frameRect, p, ^(CGContextRef, const CGRect &r) {
3981 [pb.cell drawBezelWithFrame:r inView:pb.superview];
3982 });
3983 [pb highlight:NO];
3984
3985 if (hasMenu && cw.type == QMacStylePrivate::Button_SquareButton) {
3986 // Using -[NSPopuButtonCell drawWithFrame:inView:] above won't do
3987 // it right because we don't set the text in the native button.
3988 const int mbi = proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, btn, w);
3989 const auto ir = frameRect.toRect();
3990 int arrowYOffset = 0;
3991#if 0
3992 // FIXME What's this for again?
3993 if (!w) {
3994 // adjustment for Qt Quick Controls
3995 arrowYOffset -= ir.top();
3996 if (cw.second == QStyleHelper::SizeSmall)
3997 arrowYOffset += 1;
3998 }
3999#endif
4000 const auto ar = visualRect(btn->direction, ir, QRect(ir.right() - mbi - 6, ir.height() / 2 - arrowYOffset, mbi, mbi));
4001
4002 QStyleOption arrowOpt = *opt;
4003 arrowOpt.rect = ar;
4004 proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, w);
4005 }
4006 }
4007 break;
4008 case CE_PushButtonLabel:
4009 if (const QStyleOptionButton *b = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
4010 QStyleOptionButton btn(*b);
4011 // We really don't want the label to be drawn the same as on
4012 // windows style if it has an icon and text, then it should be more like a
4013 // tab. So, cheat a little here. However, if it *is* only an icon
4014 // the windows style works great, so just use that implementation.
4015 const bool isEnabled = btn.state & State_Enabled;
4016 const bool hasMenu = btn.features & QStyleOptionButton::HasMenu;
4017 const bool hasIcon = !btn.icon.isNull();
4018 const bool hasText = !btn.text.isEmpty();
4019 const bool isActive = btn.state & State_Active;
4020 const bool isPressed = btn.state & State_Sunken;
4021 const bool isDefault = (btn.features & QStyleOptionButton::DefaultButton && !d->autoDefaultButton)
4022 || d->autoDefaultButton == btn.styleObject;
4023
4024 // cocoaControlType evaluates the type based on the control's geometry, not on the
4025 // label's geometry
4026 const QRect oldRect = btn.rect;
4027 if (w)
4028 btn.rect = w->rect();
4029 const auto ct = cocoaControlType(&btn, w);
4030 btn.rect = oldRect;
4031
4032 if (!hasMenu && ct != QMacStylePrivate::Button_SquareButton) {
4033 if (isPressed || (isActive && isEnabled && ((btn.state & State_On) || isDefault)))
4034 btn.palette.setColor(QPalette::ButtonText, Qt::white);
4035 }
4036
4037 if (isEnabled && !isDarkMode()) {
4038 if (!isDefault && !(btn.state & State_On)) {
4039 // It's a gray button, white text color (if set in the
4040 // previous statement) would be almost invisible.
4041 btn.palette.setColor(QPalette::ButtonText, Qt::black);
4042 }
4043 }
4044
4045 if ((!hasIcon && !hasMenu) || (hasIcon && !hasText)) {
4046 QCommonStyle::drawControl(ce, &btn, p, w);
4047 } else {
4048 QRect freeContentRect = btn.rect;
4049 QRect textRect = itemTextRect(
4050 btn.fontMetrics, freeContentRect, Qt::AlignCenter, isEnabled, btn.text);
4051 if (hasMenu) {
4052 if (ct == QMacStylePrivate::Button_SquareButton)
4053 textRect.moveTo(w ? 8 : 11, textRect.top());
4054 else
4055 textRect.moveTo(w ? (15 - pushButtonBevelRectOffsets[d->effectiveAquaSizeConstrain(b, w)])
4056 : 11, textRect.top()); // Supports Qt Quick Controls
4057 }
4058 // Draw the icon:
4059 if (hasIcon) {
4060 int contentW = textRect.width();
4061 if (hasMenu)
4062 contentW += proxy()->pixelMetric(PM_MenuButtonIndicator) + 4;
4063 QIcon::Mode mode = isEnabled ? QIcon::Normal : QIcon::Disabled;
4064 if (mode == QIcon::Normal && btn.state & State_HasFocus)
4065 mode = QIcon::Active;
4066 // Decide if the icon is should be on or off:
4067 QIcon::State state = QIcon::Off;
4068 if (btn.state & State_On)
4069 state = QIcon::On;
4070 QPixmap pixmap = btn.icon.pixmap(btn.iconSize, p->device()->devicePixelRatio(), mode, state);
4071 QSizeF pixmapSize = pixmap.deviceIndependentSize();
4072 contentW += pixmapSize.width() + QMacStylePrivate::PushButtonContentPadding;
4073 int iconLeftOffset = freeContentRect.x() + (freeContentRect.width() - contentW) / 2;
4074 int iconTopOffset = freeContentRect.y() + (freeContentRect.height() - pixmapSize.height()) / 2;
4075 QRect iconDestRect(iconLeftOffset, iconTopOffset, pixmapSize.width(), pixmapSize.height());
4076 QRect visualIconDestRect = visualRect(btn.direction, freeContentRect, iconDestRect);
4077 proxy()->drawItemPixmap(p, visualIconDestRect, Qt::AlignLeft | Qt::AlignVCenter, pixmap);
4078 int newOffset = iconDestRect.x() + iconDestRect.width()
4079 + QMacStylePrivate::PushButtonContentPadding - textRect.x();
4080 textRect.adjust(newOffset, 0, newOffset, 0);
4081 }
4082 // Draw the text:
4083 if (hasText) {
4084 textRect = visualRect(btn.direction, freeContentRect, textRect);
4085 proxy()->drawItemText(p, textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, btn.palette,
4086 isEnabled, btn.text, QPalette::ButtonText);
4087 }
4088 }
4089 }
4090 break;
4091#if QT_CONFIG(combobox)
4092 case CE_ComboBoxLabel:
4093 if (const auto *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
4094 auto comboCopy = *cb;
4095 comboCopy.direction = Qt::LeftToRight;
4096 // The rectangle will be adjusted to SC_ComboBoxEditField with comboboxEditBounds()
4097 QCommonStyle::drawControl(CE_ComboBoxLabel, &comboCopy, p, w);
4098 }
4099 break;
4100#endif // #if QT_CONFIG(combobox)
4101#if QT_CONFIG(tabbar)
4102 case CE_TabBarTabShape:
4103 if (const auto *tabOpt = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
4104 if (tabOpt->documentMode) {
4105 p->save();
4106 bool isUnified = false;
4107 if (w) {
4108 QRect tabRect = tabOpt->rect;
4109 QPoint windowTabStart = w->mapTo(w->window(), tabRect.topLeft());
4110 isUnified = isInMacUnifiedToolbarArea(w->window(), windowTabStart.y());
4111 }
4112
4113 const int tabOverlap = proxy()->pixelMetric(PM_TabBarTabOverlap, opt, w);
4114 drawTabShape(p, tabOpt, isUnified, tabOverlap);
4115
4116 p->restore();
4117 return;
4118 }
4119
4120 // We use NSButton and NSPopupButton (their 'cells') to draw bezels,
4121 // imitating tabs in a tab widget (looking similar to native segmented
4122 // control). Since native buttons are horizontally aligned, we have to
4123 // apply rotations and translations for the 'West' and 'East' tab positions
4124 // - which are also 'vertical' tabs (rotation by pi/2 and -pi/2).
4125 // 'needInactiveHack' means a tab is selected but its top-level window
4126 // is inactive (not key). In this state the tab must be visibly
4127 // different from other tabs (text color and bezel color).
4128 // NSButton is used if:
4129 // - the tab is a single tab (it's also selected) and window is active;
4130 // - the tab is selected and its window is active/key.
4131 // NSPopUpButton is used if:
4132 // - the tab is not a signle tab, and not selected
4133 // - the tab is a single tab and selected, but its window is not key
4134 // (aka needsInactiveHack).
4135 //
4136 // On macOS Tahoe button bezels are rendered within the rect we pass to
4137 // -drawWithFrame:inView:, so a left/right adjustment is not required.
4138 // To keep things simple we apply transformations as if
4139 // tabOpt->rect is ideal for our tabs (+ we have to increase a width
4140 // shift origin.x in case additional clipping required for 'Middle',
4141 // 'Beginning' and 'End' tabs).
4142
4143 const bool isActive = tabOpt->state & State_Active;
4144 const bool isEnabled = tabOpt->state & State_Enabled;
4145 const bool isPressed = tabOpt->state & State_Sunken;
4146 const bool isSelected = tabOpt->state & State_Selected;
4147 const auto tabDirection = QMacStylePrivate::tabDirection(tabOpt->shape);
4148 const bool verticalTabs = tabDirection == QMacStylePrivate::East
4149 || tabDirection == QMacStylePrivate::West;
4150
4151 QStyleOptionTab::TabPosition tp = tabOpt->position;
4152 QStyleOptionTab::SelectedPosition sp = tabOpt->selectedPosition;
4153 if (tabOpt->direction == Qt::RightToLeft && !verticalTabs) {
4154 if (tp == QStyleOptionTab::Beginning)
4155 tp = QStyleOptionTab::End;
4156 else if (tp == QStyleOptionTab::End)
4157 tp = QStyleOptionTab::Beginning;
4158
4159 if (sp == QStyleOptionTab::NextIsSelected)
4160 sp = QStyleOptionTab::PreviousIsSelected;
4161 else if (sp == QStyleOptionTab::PreviousIsSelected)
4162 sp = QStyleOptionTab::NextIsSelected;
4163 }
4164
4165 // Alas, NSSegmentedControl and NSSegmentedCell are letting us down.
4166 // We're not able to draw it at will, either calling -[drawSegment:
4167 // inFrame:withView:], -[drawRect:] or anything in between. Besides,
4168 // there's no public API do draw the pressed state, AFAICS. We'll use
4169 // a push NSButton instead and clip the CGContext.
4170
4171 const auto cs = d->effectiveAquaSizeConstrain(opt, w);
4172 // Extra hacks to get the proper pressed appreance when not selected or selected and inactive
4173 const bool needsInactiveHack = !isActive && isSelected;
4174 const auto ct = !needsInactiveHack && (isSelected || tp == QStyleOptionTab::OnlyOneTab) ?
4175 QMacStylePrivate::Button_PushButton :
4176 QMacStylePrivate::Button_PopupButton;
4177 const bool isPopupButton = ct == QMacStylePrivate::Button_PopupButton;
4178 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
4179 auto *pb = static_cast<NSButton *>(d->cocoaControl(cw));
4180 auto vOffset = 1;
4181
4182 if (tabDirection == QMacStylePrivate::East)
4183 vOffset -= 1;
4184 const auto outerAdjust = isPopupButton ? 1 : 4;
4185 const auto innerAdjust = isPopupButton ? 20 : 10;
4186 QRectF frameRect = tabOpt->rect;
4187 if (verticalTabs)
4188 frameRect = QRectF(frameRect.y(), frameRect.x(), frameRect.height(), frameRect.width());
4189 // Adjust before clipping
4190 frameRect = frameRect.translated(0, vOffset);
4191 switch (tp) {
4192 case QStyleOptionTab::Beginning:
4193 // Pressed state hack: tweak adjustments in preparation for flip below
4194 if (!isSelected && tabDirection == QMacStylePrivate::West)
4195 frameRect = frameRect.adjusted(-innerAdjust, 0, outerAdjust, 0);
4196 else
4197 frameRect = frameRect.adjusted(-outerAdjust, 0, innerAdjust, 0);
4198
4199 if (isSelected) {
4200 // 1 pixel of 'roundness' is still visible on the right
4201 // (the left is OK, it's rounded).
4202 frameRect = frameRect.adjusted(0, 0, 1, 0);
4203 }
4204 break;
4205 case QStyleOptionTab::Middle:
4206 frameRect = frameRect.adjusted(-innerAdjust, 0, innerAdjust, 0);
4207
4208 if (isSelected) {
4209 // 1 pixel of 'roundness' is still visible on both
4210 // sides - left and right.
4211 frameRect = frameRect.adjusted(-1, 0, 1, 0);
4212 }
4213 break;
4214 case QStyleOptionTab::Moving: // Moving tab treated like End
4215 case QStyleOptionTab::End:
4216 // Pressed state hack: tweak adjustments in preparation for flip below
4217 if (isSelected || tabDirection == QMacStylePrivate::West)
4218 frameRect = frameRect.adjusted(-innerAdjust, 0, outerAdjust, 0);
4219 else
4220 frameRect = frameRect.adjusted(-outerAdjust, 0, innerAdjust, 0);
4221
4222 if (isSelected) {
4223 // 1 pixel of 'roundness' is still visible on the left.
4224 frameRect = frameRect.adjusted(-1, 0, 0, 0);
4225 }
4226 break;
4227 case QStyleOptionTab::OnlyOneTab:
4228 frameRect = frameRect.adjusted(-outerAdjust, 0, outerAdjust, 0);
4229 break;
4230 }
4231 pb.frame = frameRect.toCGRect();
4232
4233 if (!isPopupButton) {
4234 // Note: these days we use 'momentary push in' for Button_PushButton,
4235 // but tabs are also rendered using NSButton/ButtonPushButton, and
4236 // here we need 'push on/off' to make it work (tab highlight colors).
4237 pb.buttonType = NSButtonTypePushOnPushOff;
4238 }
4239
4240 pb.enabled = isEnabled;
4241 [pb highlight:isPressed];
4242
4243 pb.state = (isActive && isSelected) ? NSControlStateValueOn : NSControlStateValueOff;
4244
4245 const auto drawBezelBlock = ^(CGContextRef ctx, const CGRect &r) {
4246 CGContextClipToRect(ctx, opt->rect.toCGRect());
4247 if (!isSelected || needsInactiveHack) {
4248 // Final stage of the pressed state hack: flip NSPopupButton rendering
4249 if (!verticalTabs && tp == QStyleOptionTab::End) {
4250 CGContextTranslateCTM(ctx, opt->rect.right(), 0);
4251 CGContextScaleCTM(ctx, -1, 1);
4252 CGContextTranslateCTM(ctx, -frameRect.left(), 0);
4253 } else if (tabDirection == QMacStylePrivate::West && tp == QStyleOptionTab::Beginning) {
4254 CGContextTranslateCTM(ctx, 0, opt->rect.top());
4255 CGContextScaleCTM(ctx, 1, -1);
4256 CGContextTranslateCTM(ctx, 0, -frameRect.right());
4257 } else if (tabDirection == QMacStylePrivate::East && tp == QStyleOptionTab::End) {
4258 CGContextTranslateCTM(ctx, 0, opt->rect.bottom());
4259 CGContextScaleCTM(ctx, 1, -1);
4260 CGContextTranslateCTM(ctx, 0, -frameRect.left());
4261 }
4262 }
4263
4264 // Rotate and translate CTM when vertical
4265 // On macOS: positive angle is CW, negative is CCW
4266 if (tabDirection == QMacStylePrivate::West) {
4267 CGContextTranslateCTM(ctx, 0, frameRect.right());
4268 CGContextRotateCTM(ctx, -M_PI_2);
4269 CGContextTranslateCTM(ctx, -frameRect.left(), 0);
4270 } else if (tabDirection == QMacStylePrivate::East) {
4271 CGContextTranslateCTM(ctx, opt->rect.right(), 0);
4272 CGContextRotateCTM(ctx, M_PI_2);
4273 }
4274
4275 // Now, if it's a trick with a popup button, it has an arrow
4276 // which makes no sense on tabs.
4277 NSPopUpArrowPosition oldPosition = NSPopUpArrowAtCenter;
4278 NSPopUpButtonCell *pbCell = nil;
4279 auto rAdjusted = r;
4280 if (isPopupButton) {
4281 // Note: starting from macOS BigSur NSPopupButton has this
4282 // arrow 'button' in a different place and it became
4283 // quite visible 'in between' inactive tabs.
4284 pbCell = static_cast<NSPopUpButtonCell *>(pb.cell);
4285 oldPosition = pbCell.arrowPosition;
4286 pbCell.arrowPosition = NSPopUpNoArrow;
4287 if (pb.state == NSControlStateValueOff) {
4288 // NSPopUpButton in this state is smaller.
4289 rAdjusted.origin.x -= 3;
4290 rAdjusted.size.width += 6;
4291 if (tp == QStyleOptionTab::End)
4292 rAdjusted.origin.x -= 2;
4293 }
4294 }
4295 if (qt_apple_runningWithLiquidGlass()) {
4296 // All Tahoe adjustments are here, in one place. We preserve
4297 // the previous rotations and translations applied in this lambda
4298 // and we know exactly where our button must be - inside the clip
4299 // bounding box (with cliiped off left/right ends if needed).
4300 // 'deltaW' is an arbitrary number here, but it's enough to move
4301 // one of the button's ends beyond clipping bounds (or even both ends -
4302 // for the option 'Middle'). A single tab does not require
4303 // any adjustment.
4304 const CGFloat deltaW = 20.0;
4305 rAdjusted = CGContextGetClipBoundingBox(ctx);
4306 if (tp == QStyleOptionTab::Beginning) {
4307 // Note: the 'Beginning' tab is on the left for horizontal tabs
4308 // and the first on the top for vertical tabs.
4309
4310 // This cuts a part from the left or right of the button:
4311 rAdjusted.size.width += deltaW;
4312
4313 if (tabDirection == QMacStylePrivate::West && isSelected && isActive) {
4314 // NSPopUpButton for non-selected or 'inactive hack' already
4315 // has the required transformations, for other cases, shift
4316 // the left end:
4317 rAdjusted.origin.x -= deltaW;
4318 }
4319 } else if (tp == QStyleOptionTab::Middle) {
4320 // Both left/right ends must be clipped:
4321 rAdjusted.origin.x -= deltaW;
4322 rAdjusted.size.width += deltaW * 2;
4323 } else if (tp == QStyleOptionTab::End) {
4324 if (isSelected && isActive && tabDirection != QMacStylePrivate::West)
4325 rAdjusted.origin.x -= deltaW;
4326 rAdjusted.size.width += deltaW;
4327 }
4328 }
4329
4330 [pb.cell drawBezelWithFrame:rAdjusted inView:pb.superview];
4331
4332 if (pbCell) // Restore, we may reuse it for a ComboBox.
4333 pbCell.arrowPosition = oldPosition;
4334 };
4335
4336 if (needsInactiveHack) {
4337 // First, render tab as non-selected tab on a pixamp
4338 const qreal pixelRatio = p->device()->devicePixelRatio();
4339 QImage tabPixmap(opt->rect.size() * pixelRatio, QImage::Format_ARGB32_Premultiplied);
4340 tabPixmap.setDevicePixelRatio(pixelRatio);
4341 tabPixmap.fill(Qt::transparent);
4342 QPainter tabPainter(&tabPixmap);
4343 d->drawNSViewInRect(pb, frameRect, &tabPainter, ^(CGContextRef ctx, const CGRect &r) {
4344 CGContextTranslateCTM(ctx, -opt->rect.left(), -opt->rect.top());
4345 drawBezelBlock(ctx, r);
4346 });
4347 tabPainter.end();
4348
4349 // Then, darken it with the proper shade of gray
4350 const qreal inactiveGray = 0.898; // As measured
4351 const int inactiveGray8 = qRound(inactiveGray * 255.0);
4352 const QRgb inactiveGrayRGB = qRgb(inactiveGray8, inactiveGray8, inactiveGray8);
4353 for (int l = 0; l < tabPixmap.height(); ++l) {
4354 auto *line = reinterpret_cast<QRgb*>(tabPixmap.scanLine(l));
4355 for (int i = 0; i < tabPixmap.width(); ++i) {
4356 if (qAlpha(line[i]) == 255) {
4357 line[i] = inactiveGrayRGB;
4358 } else if (qAlpha(line[i]) > 128) {
4359 const int g = qRound(inactiveGray * qRed(line[i]));
4360 line[i] = qRgba(g, g, g, qAlpha(line[i]));
4361 }
4362 }
4363 }
4364
4365 // Finally, draw the tab pixmap on the current painter
4366 p->drawImage(opt->rect, tabPixmap);
4367 } else {
4368 d->drawNSViewInRect(pb, frameRect, p, drawBezelBlock);
4369 }
4370
4371 if (!isSelected && sp != QStyleOptionTab::NextIsSelected
4372 && tp != QStyleOptionTab::End
4373 && tp != QStyleOptionTab::OnlyOneTab) {
4374 static const QPen separatorPen(Qt::black, 1.0);
4375 p->save();
4376 p->setOpacity(isEnabled ? 0.105 : 0.06); // As measured
4377 p->setPen(separatorPen);
4378 if (tabDirection == QMacStylePrivate::West) {
4379 p->drawLine(QLineF(opt->rect.left() + 1.5, opt->rect.bottom(),
4380 opt->rect.right() - 0.5, opt->rect.bottom()));
4381 } else if (tabDirection == QMacStylePrivate::East) {
4382 p->drawLine(QLineF(opt->rect.left(), opt->rect.bottom(),
4383 opt->rect.right() - 0.5, opt->rect.bottom()));
4384 } else {
4385 p->drawLine(QLineF(opt->rect.right(), opt->rect.top() + 1.0,
4386 opt->rect.right(), opt->rect.bottom() - 0.5));
4387 }
4388 p->restore();
4389 }
4390 }
4391 break;
4392 case CE_TabBarTabLabel:
4393 if (const auto *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
4394 QStyleOptionTab myTab = *tab;
4395 const auto foregroundRole = w ? w->foregroundRole() : QPalette::WindowText;
4396 const auto tabDirection = QMacStylePrivate::tabDirection(tab->shape);
4397 const bool verticalTabs = tabDirection == QMacStylePrivate::East
4398 || tabDirection == QMacStylePrivate::West;
4399
4400 // Check to see if we use have the same as the system font
4401 // (QComboMenuItem is internal and should never be seen by the
4402 // outside world, unless they read the source, in which case, it's
4403 // their own fault).
4404 const bool nonDefaultFont = p->font() != qt_app_fonts_hash()->value("QComboMenuItem");
4405
4406 if (!myTab.documentMode && (myTab.state & State_Selected) && (myTab.state & State_Active))
4407 if (const auto *tabBar = qobject_cast<const QTabBar *>(w))
4408 if (!tabBar->tabTextColor(tabBar->currentIndex()).isValid())
4409 myTab.palette.setColor(foregroundRole, Qt::white);
4410
4411 if (myTab.documentMode && isDarkMode()) {
4412 if (const auto *tabBar = qobject_cast<const QTabBar *>(w)) {
4413 if (!tabBar->tabTextColor(myTab.tabIndex).isValid()) {
4414 bool active = (myTab.state & State_Selected) && (myTab.state & State_Active);
4415 myTab.palette.setColor(foregroundRole, active ? Qt::white : Qt::gray);
4416 }
4417 }
4418 }
4419
4420 int heightOffset = 0;
4421 if (verticalTabs) {
4422 heightOffset = -1;
4423 } else if (nonDefaultFont) {
4424 if (p->fontMetrics().height() == myTab.rect.height())
4425 heightOffset = 2;
4426 }
4427 myTab.rect.setHeight(myTab.rect.height() + heightOffset);
4428
4429 QCommonStyle::drawControl(ce, &myTab, p, w);
4430 }
4431 break;
4432#endif
4433#if QT_CONFIG(dockwidget)
4434 case CE_DockWidgetTitle:
4435 if (const auto *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
4436 const bool isVertical = dwOpt->verticalTitleBar;
4437 const auto effectiveRect = isVertical ? opt->rect.transposed() : opt->rect;
4438 p->save();
4439 if (isVertical) {
4440 p->translate(effectiveRect.left(), effectiveRect.top() + effectiveRect.width());
4441 p->rotate(-90);
4442 p->translate(-effectiveRect.left(), -effectiveRect.top());
4443 }
4444
4445 // fill title bar background
4446 p->fillRect(effectiveRect, opt->palette.window());
4447
4448 // draw horizontal line at bottom
4449 p->setPen(opt->palette.dark().color());
4450 p->drawLine(effectiveRect.bottomLeft(), effectiveRect.bottomRight());
4451
4452 if (!dwOpt->title.isEmpty()) {
4453 auto titleRect = proxy()->subElementRect(SE_DockWidgetTitleBarText, opt, w);
4454 if (isVertical)
4455 titleRect = QRect(effectiveRect.left() + opt->rect.bottom() - titleRect.bottom(),
4456 effectiveRect.top() + titleRect.left() - opt->rect.left(),
4457 titleRect.height(),
4458 titleRect.width());
4459
4460 const auto text = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight, titleRect.width());
4461 proxy()->drawItemText(p, titleRect, Qt::AlignCenter | Qt::TextHideMnemonic, dwOpt->palette,
4462 dwOpt->state & State_Enabled, text, QPalette::WindowText);
4463 }
4464 p->restore();
4465 }
4466 break;
4467#endif
4468 case CE_FocusFrame: {
4469 const auto *ff = qobject_cast<const QFocusFrame *>(w);
4470 const auto *ffw = ff ? ff->widget() : nullptr;
4471 const auto ct = [=] {
4472 if (ffw) {
4473 if (qobject_cast<const QCheckBox*>(ffw))
4474 return QMacStylePrivate::Button_CheckBox;
4475 if (qobject_cast<const QRadioButton*>(ffw))
4476 return QMacStylePrivate::Button_RadioButton;
4477 if (qobject_cast<const QLineEdit*>(ffw) || qobject_cast<const QTextEdit*>(ffw))
4478 return QMacStylePrivate::TextField;
4479 if (const auto *pb = qobject_cast<const QPushButton *>(ffw)) {
4480 // keep in sync with cocoaControlType
4481 auto sizePolicy = QStyleHelper::widgetSizePolicy(ffw, opt);
4482 if (sizePolicy == QStyleHelper::SizeDefault)
4483 sizePolicy = QStyleHelper::SizeLarge;
4484 if (pb->isFlat()
4485 || (pb->rect().height() != pushButtonDefaultHeight[sizePolicy])) {
4486 return QMacStylePrivate::Button_SquareButton;
4487 }
4488 if (pb->menu() != nullptr)
4489 return QMacStylePrivate::Button_PullDown;
4490 return QMacStylePrivate::Button_PushButton;
4491 }
4492 }
4493
4494 return QMacStylePrivate::Box; // Not really, just make it the default
4495 } ();
4496 auto cs = QStyleHelper::widgetSizePolicy(ffw, opt);
4497 if (cs == QStyleHelper::SizeDefault)
4498 cs = QStyleHelper::SizeLarge;
4499 const int hMargin = proxy()->pixelMetric(QStyle::PM_FocusFrameHMargin, opt, w);
4500 const int vMargin = proxy()->pixelMetric(QStyle::PM_FocusFrameVMargin, opt, w);
4501 d->drawFocusRing(p, opt->rect, hMargin, vMargin, QMacStylePrivate::CocoaControl(ct, cs));
4502 break; }
4503 case CE_MenuEmptyArea:
4504 // for QComboBoxListView
4505 if (qobject_cast<const QAbstractItemView *>(w))
4506 proxy()->drawPrimitive(PE_PanelMenu, opt, p, w);
4507 // otherwise, PE_PanelMenu has already drawn everything
4508 break;
4509 case CE_MenuItem:
4510 case CE_MenuHMargin:
4511 case CE_MenuVMargin:
4512 case CE_MenuTearoff:
4513 case CE_MenuScroller:
4514 if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
4515 const bool active = mi->state & State_Selected;
4516 if (active)
4517 p->fillRect(mi->rect, mi->palette.highlight());
4518
4519 const QStyleHelper::WidgetSizePolicy widgetSize = d->aquaSizeConstrain(opt, w);
4520
4521 if (ce == CE_MenuTearoff) {
4522 p->setPen(QPen(mi->palette.dark().color(), 1, Qt::DashLine));
4523 p->drawLine(mi->rect.x() + 2, mi->rect.y() + mi->rect.height() / 2 - 1,
4524 mi->rect.x() + mi->rect.width() - 4,
4525 mi->rect.y() + mi->rect.height() / 2 - 1);
4526 p->setPen(QPen(mi->palette.light().color(), 1, Qt::DashLine));
4527 p->drawLine(mi->rect.x() + 2, mi->rect.y() + mi->rect.height() / 2,
4528 mi->rect.x() + mi->rect.width() - 4,
4529 mi->rect.y() + mi->rect.height() / 2);
4530 } else if (ce == CE_MenuScroller) {
4531 const QSize scrollerSize = QSize(10, 8);
4532 const int scrollerVOffset = 5;
4533 const int left = mi->rect.x() + (mi->rect.width() - scrollerSize.width()) / 2;
4534 const int right = left + scrollerSize.width();
4535 int top;
4536 int bottom;
4537 if (opt->state & State_DownArrow) {
4538 bottom = mi->rect.y() + scrollerVOffset;
4539 top = bottom + scrollerSize.height();
4540 } else {
4541 bottom = mi->rect.bottom() - scrollerVOffset;
4542 top = bottom - scrollerSize.height();
4543 }
4544 p->save();
4545 p->setRenderHint(QPainter::Antialiasing);
4546 QPainterPath path;
4547 path.moveTo(left, bottom);
4548 path.lineTo(right, bottom);
4549 path.lineTo((left + right) / 2, top);
4550 p->fillPath(path, opt->palette.buttonText());
4551 p->restore();
4552 } else if (ce != CE_MenuItem) {
4553 break;
4554 }
4555
4556 if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
4557 CGColorRef separatorColor = [NSColor quaternaryLabelColor].CGColor;
4558 const QRect separatorRect = QRect(mi->rect.left(), mi->rect.center().y(), mi->rect.width(), 2);
4559 p->fillRect(separatorRect, qt_mac_toQColor(separatorColor));
4560 break;
4561 }
4562
4563 const int maxpmw = mi->maxIconWidth;
4564 const bool enabled = mi->state & State_Enabled;
4565
4566 int xpos = mi->rect.x() + 18;
4567 int checkcol = maxpmw;
4568 if (!enabled)
4569 p->setPen(mi->palette.text().color());
4570 else if (active)
4571 p->setPen(mi->palette.highlightedText().color());
4572 else
4573 p->setPen(mi->palette.buttonText().color());
4574
4575 if (mi->checked) {
4576 QStyleOption checkmarkOpt;
4577 checkmarkOpt.initFrom(w);
4578
4579 const int mw = checkcol + macItemFrame;
4580 const int mh = mi->rect.height() + macItemFrame;
4581 const int xp = mi->rect.x() + macItemFrame;
4582 checkmarkOpt.rect = QRect(xp, mi->rect.y() - checkmarkOpt.fontMetrics.descent(), mw, mh);
4583
4584 checkmarkOpt.state.setFlag(State_On, active);
4585 checkmarkOpt.state.setFlag(State_Enabled, enabled);
4586 if (widgetSize == QStyleHelper::SizeMini)
4587 checkmarkOpt.state |= State_Mini;
4588 else if (widgetSize == QStyleHelper::SizeSmall)
4589 checkmarkOpt.state |= State_Small;
4590
4591 // We let drawPrimitive(PE_IndicatorMenuCheckMark) pick the right color
4592 checkmarkOpt.palette.setColor(QPalette::HighlightedText, p->pen().color());
4593 checkmarkOpt.palette.setColor(QPalette::Text, p->pen().color());
4594
4595 proxy()->drawPrimitive(PE_IndicatorMenuCheckMark, &checkmarkOpt, p, w);
4596 }
4597 if (!mi->icon.isNull()) {
4598 QIcon::Mode mode = (mi->state & State_Enabled) ? QIcon::Normal
4599 : QIcon::Disabled;
4600 // Always be normal or disabled to follow the Mac style.
4601 int smallIconSize = proxy()->pixelMetric(PM_SmallIconSize);
4602 QSize iconSize(smallIconSize, smallIconSize);
4603#if QT_CONFIG(combobox)
4604 if (const QComboBox *comboBox = qobject_cast<const QComboBox *>(w)) {
4605 iconSize = comboBox->iconSize();
4606 }
4607#endif
4608 QPixmap pixmap = mi->icon.pixmap(iconSize, p->device()->devicePixelRatio(), mode);
4609 QRect cr(xpos, mi->rect.y(), checkcol, mi->rect.height());
4610 QSize size = pixmap.deviceIndependentSize().toSize();
4611 QRect pmr(QPoint(0, 0), size);
4612 pmr.moveCenter(cr.center());
4613 p->drawPixmap(pmr.topLeft(), pixmap);
4614 xpos += size.width() + 6;
4615 }
4616
4617 QString s = mi->text;
4618 const auto text_flags = Qt::AlignVCenter | Qt::TextHideMnemonic
4619 | Qt::TextSingleLine | Qt::AlignAbsolute;
4620 int yPos = mi->rect.y();
4621 if (widgetSize == QStyleHelper::SizeMini)
4622 yPos += 1;
4623
4624 const bool isSubMenu = mi->menuItemType == QStyleOptionMenuItem::SubMenu;
4625 const int tabwidth = isSubMenu ? 9 : mi->reservedShortcutWidth;
4626
4627 QString rightMarginText;
4628 if (isSubMenu)
4629 rightMarginText = QStringLiteral("\u25b6\ufe0e"); // U+25B6 U+FE0E: BLACK RIGHT-POINTING TRIANGLE
4630
4631 // If present, save and remove embedded shorcut from text
4632 const int tabIndex = s.indexOf(QLatin1Char('\t'));
4633 if (tabIndex >= 0) {
4634 if (!isSubMenu) // ... but ignore it if it's a submenu.
4635 rightMarginText = s.mid(tabIndex + 1);
4636 s = s.left(tabIndex);
4637 }
4638
4639 p->save();
4640 if (!rightMarginText.isEmpty()) {
4641 p->setFont(qt_app_fonts_hash()->value("QMenuItem", p->font()));
4642 int xp = mi->rect.right() - tabwidth - macRightBorder + 2;
4643 if (isSubMenu) {
4644 p->drawText(xp, yPos, tabwidth, mi->rect.height(), text_flags | Qt::AlignRight, rightMarginText);
4645 } else {
4646 xp -= macItemHMargin + macItemFrame + 3; // Adjust for shortcut
4647 // try to render modifier part of shortcut string right aligned, key part left aligned
4648 const QKeySequence seq = QKeySequence::fromString(rightMarginText, QKeySequence::NativeText);
4649 if (seq.count() == 1) { // one-combo sequence, the right most character is the key
4650 // we don't know which key of all menu items is the widest, so use the widest possible
4651 const int maxKeyWidth = p->fontMetrics().maxWidth();
4652 const QChar key = rightMarginText.at(rightMarginText.length() - 1);
4653 const QString modifiers = rightMarginText.left(rightMarginText.size() - 1);
4654 p->drawText(xp + tabwidth - maxKeyWidth, yPos, maxKeyWidth, mi->rect.height(), text_flags, key);
4655 // don't clip the shortcuts; maxKeyWidth might be more than what we have been allotted by the menu
4656 p->drawText(xp, yPos, tabwidth - maxKeyWidth, mi->rect.height(),
4657 text_flags | Qt::AlignRight | Qt::TextDontClip, modifiers);
4658 } else { // draw the whole thing left-aligned for complex or unparsable cases
4659 p->drawText(xp, yPos, tabwidth, mi->rect.height(), text_flags, rightMarginText);
4660 }
4661 }
4662 }
4663
4664 if (!s.isEmpty()) {
4665 const int xm = macItemFrame + maxpmw + macItemHMargin;
4666 QFont myFont = mi->font;
4667 // myFont may not have any "hard" flags set. We override
4668 // the point size so that when it is resolved against the device, this font will win.
4669 // This is mainly to handle cases where someone sets the font on the window
4670 // and then the combo inherits it and passes it onward. At that point the resolve mask
4671 // is very, very weak. This makes it stonger.
4672 myFont.setPointSizeF(QFontInfo(mi->font).pointSizeF());
4673
4674 // QTBUG-65653: Our own text rendering doesn't look good enough, especially on non-retina
4675 // displays. Worked around here while waiting for a proper fix in QCoreTextFontEngine.
4676 // Only if we're not using QCoreTextFontEngine we do fallback to our own text rendering.
4677 const auto *fontEngine = QFontPrivate::get(myFont)->engineForScript(QChar::Script_Common);
4678 Q_ASSERT(fontEngine);
4679 if (fontEngine->type() == QFontEngine::Multi) {
4680 fontEngine = static_cast<const QFontEngineMulti *>(fontEngine)->engine(0);
4681 Q_ASSERT(fontEngine);
4682 }
4683 if (fontEngine->type() == QFontEngine::Mac) {
4684 NSFont *f = (NSFont *)(CTFontRef)fontEngine->handle();
4685
4686 // Respect the menu item palette as set in the style option.
4687 const auto pc = p->pen().color();
4688 NSColor *c = [NSColor colorWithSRGBRed:pc.redF()
4689 green:pc.greenF()
4690 blue:pc.blueF()
4691 alpha:pc.alphaF()];
4692
4693 s = qt_mac_removeMnemonics(s);
4694
4695 QMacCGContext cgCtx(p);
4696 d->setupNSGraphicsContext(cgCtx, YES);
4697
4698 // Draw at point instead of in rect, as the rect we've computed for the menu item
4699 // is based on the font metrics we got from HarfBuzz, so we may risk having CoreText
4700 // line-break the string if it doesn't fit the given rect. It's better to draw outside
4701 // the rect and possibly overlap something than to have part of the text disappear.
4702 [s.toNSString() drawAtPoint:CGPointMake(xpos, yPos)
4703 withAttributes:@{ NSFontAttributeName:f, NSForegroundColorAttributeName:c,
4704 NSObliquenessAttributeName: [NSNumber numberWithDouble: myFont.italic() ? 0.3 : 0.0],
4705 NSUnderlineStyleAttributeName: [NSNumber numberWithInt: myFont.underline() ? NSUnderlineStyleSingle
4706 : NSUnderlineStyleNone],
4707 NSStrikethroughStyleAttributeName: [NSNumber numberWithInt: myFont.strikeOut() ? NSUnderlineStyleSingle
4708 : NSUnderlineStyleNone]}];
4709
4710 d->restoreNSGraphicsContext(cgCtx);
4711 } else {
4712 p->setFont(myFont);
4713 p->drawText(xpos, yPos, mi->rect.width() - xm - tabwidth + 1,
4714 mi->rect.height(), text_flags, s);
4715 }
4716 }
4717 p->restore();
4718 }
4719 break;
4720 case CE_MenuBarItem:
4721 case CE_MenuBarEmptyArea:
4722 if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
4723 const bool selected = (opt->state & State_Selected) && (opt->state & State_Enabled) && (opt->state & State_Sunken);
4724 const QBrush bg = selected ? mi->palette.highlight() : mi->palette.window();
4725 p->fillRect(mi->rect, bg);
4726
4727 if (ce != CE_MenuBarItem)
4728 break;
4729
4730 if (!mi->icon.isNull()) {
4731 int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
4732 drawItemPixmap(p, mi->rect,
4733 Qt::AlignCenter | Qt::TextHideMnemonic | Qt::TextDontClip
4734 | Qt::TextSingleLine,
4735 mi->icon.pixmap(QSize(iconExtent, iconExtent), p->device()->devicePixelRatio(),
4736 (mi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled));
4737 } else {
4738 drawItemText(p, mi->rect,
4739 Qt::AlignCenter | Qt::TextHideMnemonic | Qt::TextDontClip
4740 | Qt::TextSingleLine,
4741 mi->palette, mi->state & State_Enabled,
4742 mi->text, selected ? QPalette::HighlightedText : QPalette::ButtonText);
4743 }
4744 }
4745 break;
4746 case CE_ProgressBarLabel:
4747 case CE_ProgressBarGroove:
4748 // Do nothing. All done in CE_ProgressBarContents. Only keep these for proxy style overrides.
4749 break;
4750 case CE_ProgressBarContents:
4751 if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
4752 const bool isIndeterminate = (pb->minimum == 0 && pb->maximum == 0);
4753 const bool vertical = !(pb->state & QStyle::State_Horizontal);
4754 const bool inverted = pb->invertedAppearance;
4755 bool reverse = (!vertical && (pb->direction == Qt::RightToLeft));
4756 if (inverted)
4757 reverse = !reverse;
4758 QRect rect = pb->rect;
4759
4760 const auto aquaSize = d->effectiveAquaSizeConstrain(opt, w);
4761 const QProgressStyleAnimation *animation = qobject_cast<QProgressStyleAnimation*>(d->animation(opt->styleObject));
4762 if (isIndeterminate) {
4763 // QIndeterminateProgressIndicator derives from NSProgressIndicator. We use a single
4764 // instance that we start animating as soon as one of the progress bars is indeterminate.
4765 // Since they will be in sync (as it's the case in Cocoa), we just need to draw it with
4766 // the right geometry when the animation triggers an update. However, we can't hide it
4767 // entirely between frames since that would stop the animation, so we just set its alpha
4768 // value to 0. Same if we remove it from its superview. See QIndeterminateProgressIndicator
4769 // implementation for details.
4770 if (!animation && opt->styleObject) {
4771 auto *animation = new QProgressStyleAnimation(d->animateSpeed(QMacStylePrivate::AquaProgressBar), opt->styleObject);
4772 // NSProgressIndicator is heavier to draw than the HITheme API, so we reduce the frame rate a couple notches.
4773 animation->setFrameRate(QStyleAnimation::FifteenFps);
4774 d->startAnimation(animation);
4775 }
4776
4777 if (qt_apple_runningWithLiquidGlass()) {
4778 d->drawProgressBar(p, pb);
4779 } else if (cg) {
4780 if (vertical)
4781 rect = rect.transposed();
4782 d->setupNSGraphicsContext(cg, NO);
4783 d->setupVerticalInvertedXform(cg, reverse, vertical, rect.toCGRect());
4784 if (auto *ipi
4785 = static_cast<QIndeterminateProgressIndicator *>(
4786 d->cocoaControl({ QMacStylePrivate::ProgressIndicator_Indeterminate, aquaSize }))) {
4787 [ipi startAnimation];
4788 [ipi drawWithFrame:rect.toCGRect() inView:d->backingStoreNSView];
4789 }
4790 d->restoreNSGraphicsContext(cg);
4791 }
4792 } else {
4793 if (animation) {
4794 d->stopAnimation(opt->styleObject);
4795 if (auto *ipi
4796 = static_cast<QIndeterminateProgressIndicator *>(
4797 d->cocoaControl({ QMacStylePrivate::ProgressIndicator_Indeterminate, aquaSize })))
4798 [ipi stopAnimation];
4799 }
4800 if (qt_apple_runningWithLiquidGlass()) {
4801 d->drawProgressBar(p, pb);
4802 } else {
4803 if (vertical)
4804 rect = rect.transposed();
4805 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::ProgressIndicator_Determinate, aquaSize);
4806 auto *pi = static_cast<NSProgressIndicator *>(d->cocoaControl(cw));
4807 d->drawNSViewInRect(pi, rect, p, ^(CGContextRef ctx, const CGRect &cgrect) {
4808 d->setupVerticalInvertedXform(ctx, reverse, vertical, cgrect);
4809 pi.minValue = pb->minimum;
4810 pi.maxValue = pb->maximum;
4811 pi.doubleValue = pb->progress;
4812 [pi drawRect:cgrect]; });
4813 }
4814 }
4815 }
4816 break;
4817 case CE_SizeGrip: {
4818 // This is not HIG kosher: Fall back to the old stuff until we decide what to do.
4819#ifndef QT_NO_MDIAREA
4820 if (!w || !qobject_cast<QMdiSubWindow *>(w->parentWidget()))
4821#endif
4822 break;
4823
4824 if (w->testAttribute(Qt::WA_MacOpaqueSizeGrip))
4825 p->fillRect(opt->rect, opt->palette.window());
4826
4827 QPen lineColor = QColor(82, 82, 82, 192);
4828 lineColor.setWidth(1);
4829 p->save();
4830 p->setRenderHint(QPainter::Antialiasing);
4831 p->setPen(lineColor);
4832 const Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : qApp->layoutDirection();
4833 const int NumLines = 3;
4834 for (int l = 0; l < NumLines; ++l) {
4835 const int offset = (l * 4 + 3);
4836 QPoint start, end;
4837 if (layoutDirection == Qt::LeftToRight) {
4838 start = QPoint(opt->rect.width() - offset, opt->rect.height() - 1);
4839 end = QPoint(opt->rect.width() - 1, opt->rect.height() - offset);
4840 } else {
4841 start = QPoint(offset, opt->rect.height() - 1);
4842 end = QPoint(1, opt->rect.height() - offset);
4843 }
4844 p->drawLine(start, end);
4845 }
4846 p->restore();
4847 break;
4848 }
4849 case CE_Splitter:
4850 if (opt->rect.width() > 1 && opt->rect.height() > 1) {
4851 const bool isVertical = !(opt->state & QStyle::State_Horizontal);
4852 // Qt refers to the layout orientation, while Cocoa refers to the divider's.
4853 const auto ct = isVertical ? QMacStylePrivate::SplitView_Horizontal : QMacStylePrivate::SplitView_Vertical;
4854 const auto cw = QMacStylePrivate::CocoaControl(ct, QStyleHelper::SizeLarge);
4855 auto *sv = static_cast<NSSplitView *>(d->cocoaControl(cw));
4856 sv.frame = opt->rect.toCGRect();
4857 d->drawNSViewInRect(sv, opt->rect, p, ^(CGContextRef, const CGRect &rect) {
4858 [sv drawDividerInRect:rect];
4859 });
4860 } else {
4861 QPen oldPen = p->pen();
4862 p->setPen(opt->palette.dark().color());
4863 if (opt->state & QStyle::State_Horizontal)
4864 p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
4865 else
4866 p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
4867 p->setPen(oldPen);
4868 }
4869 break;
4870 case CE_RubberBand:
4871 if (const QStyleOptionRubberBand *rubber = qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
4872 QColor fillColor(opt->palette.color(QPalette::Disabled, QPalette::Highlight));
4873 if (!rubber->opaque) {
4874 QColor strokeColor;
4875 // I retrieved these colors from the Carbon-Dev mailing list
4876 strokeColor.setHsvF(0, 0, 0.86, 1.0);
4877 fillColor.setHsvF(0, 0, 0.53, 0.25);
4878 if (opt->rect.width() * opt->rect.height() <= 3) {
4879 p->fillRect(opt->rect, strokeColor);
4880 } else {
4881 QPen oldPen = p->pen();
4882 QBrush oldBrush = p->brush();
4883 QPen pen(strokeColor);
4884 p->setPen(pen);
4885 p->setBrush(fillColor);
4886 QRect adjusted = opt->rect.adjusted(1, 1, -1, -1);
4887 if (adjusted.isValid())
4888 p->drawRect(adjusted);
4889 p->setPen(oldPen);
4890 p->setBrush(oldBrush);
4891 }
4892 } else {
4893 p->fillRect(opt->rect, fillColor);
4894 }
4895 }
4896 break;
4897#ifndef QT_NO_TOOLBAR
4898 case CE_ToolBar: {
4899 const QStyleOptionToolBar *toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(opt);
4900 const bool darkMode = isDarkMode();
4901 const QColor separatorColor = darkMode ? darkModeSeparatorLine : opt->palette.dark().color();
4902
4903 // Unified title and toolbar drawing. In this mode the cocoa platform plugin will
4904 // fill the top toolbar area part with a background gradient that "unifies" with
4905 // the title bar. The following code fills the toolBar area with transparent pixels
4906 // to make that gradient visible.
4907 if (w) {
4908#if QT_CONFIG(mainwindow)
4909 if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(w->window())) {
4910 if (toolBar && toolBar->toolBarArea == Qt::TopToolBarArea && mainWindow->unifiedTitleAndToolBarOnMac()) {
4911 // fill with transparent pixels.
4912 p->save();
4913 p->setCompositionMode(QPainter::CompositionMode_Source);
4914 p->fillRect(opt->rect, Qt::transparent);
4915 p->restore();
4916
4917 // Draw a horizontal separator line at the toolBar bottom if the "unified" area ends here.
4918 // There might be additional toolbars or other widgets such as tab bars in document
4919 // mode below. Determine this by making a unified toolbar area test for the row below
4920 // this toolbar.
4921 const QPoint windowToolbarEnd = w->mapTo(w->window(), opt->rect.bottomLeft());
4922 const bool isEndOfUnifiedArea = !isInMacUnifiedToolbarArea(w->window(), windowToolbarEnd.y() + 1);
4923 if (isEndOfUnifiedArea) {
4924 const int margin = qt_mac_aqua_get_metric(SeparatorSize);
4925 const auto separatorRect = QRect(opt->rect.left(), opt->rect.bottom(), opt->rect.width(), margin);
4926 p->fillRect(separatorRect, separatorColor);
4927 }
4928 break;
4929 }
4930 }
4931#endif
4932 }
4933
4934 p->fillRect(opt->rect, opt->palette.window());
4935
4936 p->save();
4937 p->setPen(separatorColor);
4938 QRect toolbarRect = darkMode ? opt->rect.adjusted(0, 0, 0, 1) : opt->rect;
4939 if (opt->state & State_Horizontal) {
4940 p->drawLine(toolbarRect.topLeft(), toolbarRect.topRight());
4941 p->drawLine(toolbarRect.bottomLeft(), toolbarRect.bottomRight());
4942 } else {
4943 p->drawLine(toolbarRect.topLeft(), toolbarRect.bottomLeft());
4944 p->drawLine(toolbarRect.topRight(), toolbarRect.bottomRight());
4945 }
4946 p->restore();
4947
4948
4949 } break;
4950#endif
4951 default:
4952 QCommonStyle::drawControl(ce, opt, p, w);
4953 break;
4954 }
4955}
4956
4957static void setLayoutItemMargins(int left, int top, int right, int bottom, QRect *rect, Qt::LayoutDirection dir)
4958{
4959 if (dir == Qt::RightToLeft) {
4960 rect->adjust(-right, top, -left, bottom);
4961 } else {
4962 rect->adjust(left, top, right, bottom);
4963 }
4964}
4965
4966QRect QMacStyle::subElementRect(SubElement sr, const QStyleOption *opt,
4967 const QWidget *widget) const
4968{
4969 Q_D(const QMacStyle);
4970 QRect rect;
4971 const int controlSize = getControlSize(opt, widget);
4972
4973 switch (sr) {
4974#if QT_CONFIG(itemviews)
4975 case SE_ItemViewItemText:
4976 if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
4977 int fw = proxy()->pixelMetric(PM_FocusFrameHMargin, opt, widget);
4978 // We add the focusframeargin between icon and text in commonstyle
4979 rect = QCommonStyle::subElementRect(sr, opt, widget);
4980 if (vopt->features & QStyleOptionViewItem::HasDecoration)
4981 rect.adjust(-fw, 0, 0, 0);
4982 }
4983 break;
4984#endif
4985 case SE_ToolBoxTabContents:
4986 rect = QCommonStyle::subElementRect(sr, opt, widget);
4987 break;
4988 case SE_PushButtonBevel:
4989 case SE_PushButtonContents:
4990 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
4991 // Comment from the old HITheme days:
4992 // "Unlike Carbon, we want the button to always be drawn inside its bounds.
4993 // Therefore, the button is a bit smaller, so that even if it got focus,
4994 // the focus 'shadow' will be inside. Adjust the content rect likewise."
4995 // In the future, we should consider using -[NSCell titleRectForBounds:].
4996 // Since it requires configuring the NSButton fully, i.e. frame, image,
4997 // title and font, we keep things more manual until we are more familiar
4998 // with side effects when changing NSButton state.
4999 const auto ct = cocoaControlType(btn, widget);
5000 const auto cs = d->effectiveAquaSizeConstrain(btn, widget);
5001 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
5002 auto frameRect = cw.adjustedControlFrame(btn->rect);
5003 if (sr == SE_PushButtonContents) {
5004 frameRect -= cw.titleMargins();
5005 } else if (cw.type != QMacStylePrivate::Button_SquareButton) {
5006 auto *pb = static_cast<NSButton *>(d->cocoaControl(cw));
5007 frameRect = QRectF::fromCGRect([pb alignmentRectForFrame:frameRect.toCGRect()]);
5008 if (cw.type == QMacStylePrivate::Button_PushButton)
5009 frameRect -= pushButtonShadowMargins[cw.size];
5010 else if (cw.type == QMacStylePrivate::Button_PullDown)
5011 frameRect -= pullDownButtonShadowMargins[cw.size];
5012 }
5013 rect = frameRect.toRect();
5014 }
5015 break;
5016 case SE_HeaderLabel: {
5017 int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, opt, widget);
5018 rect.setRect(opt->rect.x() + margin, opt->rect.y(),
5019 opt->rect.width() - margin * 2, opt->rect.height() - 2);
5020 if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
5021 // Subtract width needed for arrow, if there is one
5022 if (header->sortIndicator != QStyleOptionHeader::None) {
5023 if (opt->state & State_Horizontal)
5024 rect.setWidth(rect.width() - (headerSectionArrowHeight) - (margin * 2));
5025 else
5026 rect.setHeight(rect.height() - (headerSectionArrowHeight) - (margin * 2));
5027 }
5028 }
5029 rect = visualRect(opt->direction, opt->rect, rect);
5030 break;
5031 }
5032 case SE_HeaderArrow: {
5033 int h = opt->rect.height();
5034 int w = opt->rect.width();
5035 int x = opt->rect.x();
5036 int y = opt->rect.y();
5037 int margin = proxy()->pixelMetric(QStyle::PM_HeaderMargin, opt, widget);
5038
5039 if (opt->state & State_Horizontal) {
5040 rect.setRect(x + w - margin * 2 - headerSectionArrowHeight, y + 5,
5041 headerSectionArrowHeight, h - margin * 2 - 5);
5042 } else {
5043 rect.setRect(x + 5, y + h - margin * 2 - headerSectionArrowHeight,
5044 w - margin * 2 - 5, headerSectionArrowHeight);
5045 }
5046 rect = visualRect(opt->direction, opt->rect, rect);
5047 break;
5048 }
5049 case SE_ProgressBarGroove:
5050 // Wrong in the secondary dimension, but accurate enough in the main dimension.
5051 rect = opt->rect;
5052 break;
5053 case SE_ProgressBarLabel:
5054 break;
5055 case SE_ProgressBarContents:
5056 rect = opt->rect;
5057 break;
5058 case SE_TreeViewDisclosureItem: {
5059 rect = opt->rect;
5060 // As previously returned by HIThemeGetButtonContentBounds
5061 rect.setLeft(rect.left() + 2 + DisclosureOffset);
5062 break;
5063 }
5064#if QT_CONFIG(tabwidget)
5065 case SE_TabWidgetLeftCorner:
5066 if (const QStyleOptionTabWidgetFrame *twf
5067 = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
5068 switch (twf->shape) {
5069 case QTabBar::RoundedNorth:
5070 case QTabBar::TriangularNorth:
5071 rect = QRect(QPoint(0, 0), twf->leftCornerWidgetSize);
5072 break;
5073 case QTabBar::RoundedSouth:
5074 case QTabBar::TriangularSouth:
5075 rect = QRect(QPoint(0, twf->rect.height() - twf->leftCornerWidgetSize.height()),
5076 twf->leftCornerWidgetSize);
5077 break;
5078 default:
5079 break;
5080 }
5081 rect = visualRect(twf->direction, twf->rect, rect);
5082 }
5083 break;
5084 case SE_TabWidgetRightCorner:
5085 if (const QStyleOptionTabWidgetFrame *twf
5086 = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
5087 switch (twf->shape) {
5088 case QTabBar::RoundedNorth:
5089 case QTabBar::TriangularNorth:
5090 rect = QRect(QPoint(twf->rect.width() - twf->rightCornerWidgetSize.width(), 0),
5091 twf->rightCornerWidgetSize);
5092 break;
5093 case QTabBar::RoundedSouth:
5094 case QTabBar::TriangularSouth:
5095 rect = QRect(QPoint(twf->rect.width() - twf->rightCornerWidgetSize.width(),
5096 twf->rect.height() - twf->rightCornerWidgetSize.height()),
5097 twf->rightCornerWidgetSize);
5098 break;
5099 default:
5100 break;
5101 }
5102 rect = visualRect(twf->direction, twf->rect, rect);
5103 }
5104 break;
5105 case SE_TabWidgetTabContents:
5106 rect = QCommonStyle::subElementRect(sr, opt, widget);
5107 if (const auto *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
5108 if (twf->lineWidth != 0) {
5109 switch (QMacStylePrivate::tabDirection(twf->shape)) {
5110 case QMacStylePrivate::North:
5111 rect.adjust(+1, +14, -1, -1);
5112 break;
5113 case QMacStylePrivate::South:
5114 rect.adjust(+1, +1, -1, -14);
5115 break;
5116 case QMacStylePrivate::West:
5117 rect.adjust(+14, +1, -1, -1);
5118 break;
5119 case QMacStylePrivate::East:
5120 rect.adjust(+1, +1, -14, -1);
5121 }
5122 }
5123 }
5124 break;
5125 case SE_TabBarTabText:
5126 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
5127 QRect dummyIconRect;
5128 d->tabLayout(tab, widget, &rect, &dummyIconRect);
5129 }
5130 break;
5131 case SE_TabBarTabLeftButton:
5132 case SE_TabBarTabRightButton:
5133 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
5134 bool selected = tab->state & State_Selected;
5135 int verticalShift = proxy()->pixelMetric(QStyle::PM_TabBarTabShiftVertical, tab, widget);
5136 int horizontalShift = proxy()->pixelMetric(QStyle::PM_TabBarTabShiftHorizontal, tab, widget);
5137 int hpadding = 5;
5138
5139 bool verticalTabs = tab->shape == QTabBar::RoundedEast
5140 || tab->shape == QTabBar::RoundedWest
5141 || tab->shape == QTabBar::TriangularEast
5142 || tab->shape == QTabBar::TriangularWest;
5143
5144 QRect tr = tab->rect;
5145 if (tab->shape == QTabBar::RoundedSouth || tab->shape == QTabBar::TriangularSouth)
5146 verticalShift = -verticalShift;
5147 if (verticalTabs) {
5148 qSwap(horizontalShift, verticalShift);
5149 horizontalShift *= -1;
5150 verticalShift *= -1;
5151 }
5152 if (tab->shape == QTabBar::RoundedWest || tab->shape == QTabBar::TriangularWest)
5153 horizontalShift = -horizontalShift;
5154
5155 tr.adjust(0, 0, horizontalShift, verticalShift);
5156 if (selected)
5157 {
5158 tr.setBottom(tr.bottom() - verticalShift);
5159 tr.setRight(tr.right() - horizontalShift);
5160 }
5161
5162 QSize size = (sr == SE_TabBarTabLeftButton) ? tab->leftButtonSize : tab->rightButtonSize;
5163 int w = size.width();
5164 int h = size.height();
5165 int midHeight = static_cast<int>(qCeil(float(tr.height() - h) / 2));
5166 int midWidth = ((tr.width() - w) / 2);
5167
5168 bool atTheTop = true;
5169 switch (tab->shape) {
5170 case QTabBar::RoundedWest:
5171 case QTabBar::TriangularWest:
5172 atTheTop = (sr == SE_TabBarTabLeftButton);
5173 break;
5174 case QTabBar::RoundedEast:
5175 case QTabBar::TriangularEast:
5176 atTheTop = (sr == SE_TabBarTabRightButton);
5177 break;
5178 default:
5179 if (sr == SE_TabBarTabLeftButton)
5180 rect = QRect(tab->rect.x() + hpadding, midHeight, w, h);
5181 else
5182 rect = QRect(tab->rect.right() - w - hpadding, midHeight, w, h);
5183 rect = visualRect(tab->direction, tab->rect, rect);
5184 }
5185 if (verticalTabs) {
5186 if (atTheTop)
5187 rect = QRect(midWidth, tr.y() + tab->rect.height() - hpadding - h, w, h);
5188 else
5189 rect = QRect(midWidth, tr.y() + hpadding, w, h);
5190 }
5191 }
5192 break;
5193#endif
5194 case SE_LineEditContents:
5195 rect = QCommonStyle::subElementRect(sr, opt, widget);
5196#if QT_CONFIG(combobox)
5197 if (widget && qobject_cast<const QComboBox*>(widget->parentWidget()))
5198 rect.adjust(-1, -2, 0, 0);
5199 else
5200#endif
5201 rect.adjust(-1, -1, 0, +1);
5202 break;
5203 case SE_CheckBoxLayoutItem:
5204 rect = opt->rect;
5205 if (controlSize == QStyleHelper::SizeLarge) {
5206 setLayoutItemMargins(+2, +3, -9, -4, &rect, opt->direction);
5207 } else if (controlSize == QStyleHelper::SizeSmall) {
5208 setLayoutItemMargins(+1, +5, 0 /* fix */, -6, &rect, opt->direction);
5209 } else {
5210 setLayoutItemMargins(0, +7, 0 /* fix */, -6, &rect, opt->direction);
5211 }
5212 break;
5213 case SE_ComboBoxLayoutItem:
5214#ifndef QT_NO_TOOLBAR
5215 if (widget && qobject_cast<QToolBar *>(widget->parentWidget())) {
5216 // Do nothing, because QToolbar needs the entire widget rect.
5217 // Otherwise it will be clipped. Equivalent to
5218 // widget->setAttribute(Qt::WA_LayoutUsesWidgetRect), but without
5219 // all the hassle.
5220 } else
5221#endif
5222 {
5223 rect = opt->rect;
5224 if (controlSize == QStyleHelper::SizeLarge) {
5225 rect.adjust(+3, +2, -3, -4);
5226 } else if (controlSize == QStyleHelper::SizeSmall) {
5227 setLayoutItemMargins(+2, +1, -3, -4, &rect, opt->direction);
5228 } else {
5229 setLayoutItemMargins(+1, 0, -2, 0, &rect, opt->direction);
5230 }
5231 }
5232 break;
5233 case SE_LabelLayoutItem:
5234 rect = opt->rect;
5235 setLayoutItemMargins(+1, 0 /* SHOULD be -1, done for alignment */, 0, 0 /* SHOULD be -1, done for alignment */, &rect, opt->direction);
5236 break;
5237 case SE_ProgressBarLayoutItem: {
5238 rect = opt->rect;
5239 int bottom = SIZE(3, 8, 8);
5240 if (opt->state & State_Horizontal) {
5241 rect.adjust(0, +1, 0, -bottom);
5242 } else {
5243 setLayoutItemMargins(+1, 0, -bottom, 0, &rect, opt->direction);
5244 }
5245 break;
5246 }
5247 case SE_PushButtonLayoutItem:
5248 if (const QStyleOptionButton *buttonOpt
5249 = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
5250 if ((buttonOpt->features & QStyleOptionButton::Flat))
5251 break; // leave rect alone
5252 if ((buttonOpt->features & QStyleOptionButton::CommandLinkButton)) {
5253 rect = opt->rect;
5254 if (controlSize == QStyleHelper::SizeLarge)
5255 rect.adjust(+6, +4, -6, -8);
5256 else if (controlSize == QStyleHelper::SizeSmall)
5257 rect.adjust(+5, +4, -5, -6);
5258 else
5259 rect.adjust(+1, 0, -1, -2);
5260 break;
5261 }
5262 }
5263 rect = opt->rect;
5264 if (controlSize == QStyleHelper::SizeLarge) {
5265 rect.adjust(0, +4, 0, -8);
5266 } else if (controlSize == QStyleHelper::SizeSmall) {
5267 rect.adjust(0, +4, 0, -6);
5268 } else {
5269 rect.adjust(0, 0, 0, -2);
5270 }
5271 break;
5272 case SE_RadioButtonLayoutItem:
5273 rect = opt->rect;
5274 if (controlSize == QStyleHelper::SizeLarge) {
5275 setLayoutItemMargins(+2, +2 /* SHOULD BE +3, done for alignment */,
5276 0, -4 /* SHOULD BE -3, done for alignment */, &rect, opt->direction);
5277 } else if (controlSize == QStyleHelper::SizeSmall) {
5278 rect.adjust(0, +6, 0 /* fix */, -5);
5279 } else {
5280 rect.adjust(0, +6, 0 /* fix */, -7);
5281 }
5282 break;
5283 case SE_SliderLayoutItem:
5284 if (const QStyleOptionSlider *sliderOpt
5285 = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
5286 rect = opt->rect;
5287 if (sliderOpt->tickPosition == QSlider::NoTicks) {
5288 int above = SIZE(3, 0, 2);
5289 int below = SIZE(4, 3, 0);
5290 if (sliderOpt->orientation == Qt::Horizontal) {
5291 rect.adjust(0, +above, 0, -below);
5292 } else {
5293 rect.adjust(+above, 0, -below, 0); //### Seems that QSlider flip the position of the ticks in reverse mode.
5294 }
5295 } else if (sliderOpt->tickPosition == QSlider::TicksAbove) {
5296 int below = SIZE(3, 2, 0);
5297 if (sliderOpt->orientation == Qt::Horizontal) {
5298 rect.setHeight(rect.height() - below);
5299 } else {
5300 rect.setWidth(rect.width() - below);
5301 }
5302 } else if (sliderOpt->tickPosition == QSlider::TicksBelow) {
5303 int above = SIZE(3, 2, 0);
5304 if (sliderOpt->orientation == Qt::Horizontal) {
5305 rect.setTop(rect.top() + above);
5306 } else {
5307 rect.setLeft(rect.left() + above);
5308 }
5309 }
5310 }
5311 break;
5312 case SE_FrameLayoutItem:
5313 // hack because QStyleOptionFrame doesn't have a frameStyle member
5314 if (const QFrame *frame = qobject_cast<const QFrame *>(widget)) {
5315 rect = opt->rect;
5316 switch (frame->frameStyle() & QFrame::Shape_Mask) {
5317 case QFrame::HLine:
5318 rect.adjust(0, +1, 0, -1);
5319 break;
5320 case QFrame::VLine:
5321 rect.adjust(+1, 0, -1, 0);
5322 break;
5323 default:
5324 ;
5325 }
5326 }
5327 break;
5328 case SE_GroupBoxLayoutItem:
5329 rect = opt->rect;
5330 if (const QStyleOptionGroupBox *groupBoxOpt =
5331 qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
5332 /*
5333 AHIG is very inconsistent when it comes to group boxes.
5334 Basically, we make sure that (non-checkable) group boxes
5335 and tab widgets look good when laid out side by side.
5336 */
5337 if (groupBoxOpt->subControls & (QStyle::SC_GroupBoxCheckBox
5338 | QStyle::SC_GroupBoxLabel)) {
5339 int delta;
5340 if (groupBoxOpt->subControls & QStyle::SC_GroupBoxCheckBox) {
5341 delta = SIZE(8, 4, 4); // guess
5342 } else {
5343 delta = SIZE(15, 12, 12); // guess
5344 }
5345 rect.setTop(rect.top() + delta);
5346 }
5347 }
5348 rect.setBottom(rect.bottom() - 1);
5349 break;
5350#if QT_CONFIG(tabwidget)
5351 case SE_TabWidgetLayoutItem:
5352 if (const QStyleOptionTabWidgetFrame *tabWidgetOpt =
5353 qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
5354 /*
5355 AHIG specifies "12 or 14" as the distance from the window
5356 edge. We choose 14 and since the default top margin is 20,
5357 the overlap is 6.
5358 */
5359 rect = tabWidgetOpt->rect;
5360 if (tabWidgetOpt->shape == QTabBar::RoundedNorth)
5361 rect.setTop(rect.top() + SIZE(6 /* AHIG */, 3 /* guess */, 2 /* AHIG */));
5362 }
5363 break;
5364#endif
5365#if QT_CONFIG(dockwidget)
5366 case SE_DockWidgetCloseButton:
5367 case SE_DockWidgetFloatButton:
5368 case SE_DockWidgetTitleBarText:
5369 case SE_DockWidgetIcon: {
5370 int iconSize = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
5371 int buttonMargin = proxy()->pixelMetric(PM_DockWidgetTitleBarButtonMargin, opt, widget);
5372 QRect srect = opt->rect;
5373
5374 const QStyleOptionDockWidget *dwOpt
5375 = qstyleoption_cast<const QStyleOptionDockWidget*>(opt);
5376 bool canClose = dwOpt == 0 ? true : dwOpt->closable;
5377 bool canFloat = dwOpt == 0 ? false : dwOpt->floatable;
5378
5379 const bool verticalTitleBar = dwOpt->verticalTitleBar;
5380
5381 // If this is a vertical titlebar, we transpose and work as if it was
5382 // horizontal, then transpose again.
5383 if (verticalTitleBar)
5384 srect = srect.transposed();
5385
5386 do {
5387 int right = srect.right();
5388 int left = srect.left();
5389
5390 QRect closeRect;
5391 if (canClose) {
5392 QSize sz = proxy()->standardIcon(QStyle::SP_TitleBarCloseButton,
5393 opt, widget).actualSize(QSize(iconSize, iconSize));
5394 sz += QSize(buttonMargin, buttonMargin);
5395 if (verticalTitleBar)
5396 sz = sz.transposed();
5397 closeRect = QRect(left,
5398 srect.center().y() - sz.height()/2,
5399 sz.width(), sz.height());
5400 left = closeRect.right() + 1;
5401 }
5402 if (sr == SE_DockWidgetCloseButton) {
5403 rect = closeRect;
5404 break;
5405 }
5406
5407 QRect floatRect;
5408 if (canFloat) {
5409 QSize sz = proxy()->standardIcon(QStyle::SP_TitleBarNormalButton,
5410 opt, widget).actualSize(QSize(iconSize, iconSize));
5411 sz += QSize(buttonMargin, buttonMargin);
5412 if (verticalTitleBar)
5413 sz = sz.transposed();
5414 floatRect = QRect(left,
5415 srect.center().y() - sz.height()/2,
5416 sz.width(), sz.height());
5417 left = floatRect.right() + 1;
5418 }
5419 if (sr == SE_DockWidgetFloatButton) {
5420 rect = floatRect;
5421 break;
5422 }
5423
5424 QRect iconRect;
5425 if (const QDockWidget *dw = qobject_cast<const QDockWidget*>(widget)) {
5426 QIcon icon;
5427 if (dw->isFloating())
5428 icon = dw->windowIcon();
5429 if (!icon.isNull()
5430 && icon.cacheKey() != QApplication::windowIcon().cacheKey()) {
5431 QSize sz = icon.actualSize(QSize(rect.height(), rect.height()));
5432 if (verticalTitleBar)
5433 sz = sz.transposed();
5434 iconRect = QRect(right - sz.width(), srect.center().y() - sz.height()/2,
5435 sz.width(), sz.height());
5436 right = iconRect.left() - 1;
5437 }
5438 }
5439 if (sr == SE_DockWidgetIcon) {
5440 rect = iconRect;
5441 break;
5442 }
5443
5444 QRect textRect = QRect(left, srect.top(),
5445 right - left, srect.height());
5446 if (sr == SE_DockWidgetTitleBarText) {
5447 rect = textRect;
5448 break;
5449 }
5450 } while (false);
5451
5452 if (verticalTitleBar) {
5453 rect = QRect(srect.left() + rect.top() - srect.top(),
5454 srect.top() + srect.right() - rect.right(),
5455 rect.height(), rect.width());
5456 } else {
5457 rect = visualRect(opt->direction, srect, rect);
5458 }
5459 break;
5460 }
5461#endif
5462 default:
5463 rect = QCommonStyle::subElementRect(sr, opt, widget);
5464 break;
5465 }
5466 return rect;
5467}
5468
5469void QMacStylePrivate::drawToolbarButtonArrow(const QStyleOption *opt, QPainter *p) const
5470{
5471 Q_Q(const QMacStyle);
5472 QStyleOption arrowOpt = *opt;
5473 arrowOpt.rect = QRect(opt->rect.right() - (toolButtonArrowSize + toolButtonArrowMargin),
5474 opt->rect.bottom() - (toolButtonArrowSize + toolButtonArrowMargin),
5477 q->proxy()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &arrowOpt, p);
5478}
5479
5480void QMacStylePrivate::setupNSGraphicsContext(CGContextRef cg, bool flipped) const
5481{
5482 CGContextSaveGState(cg);
5483 [NSGraphicsContext saveGraphicsState];
5484
5485 [NSGraphicsContext setCurrentContext:
5486 [NSGraphicsContext graphicsContextWithCGContext:cg flipped:flipped]];
5487}
5488
5489void QMacStylePrivate::restoreNSGraphicsContext(CGContextRef cg) const
5490{
5491 [NSGraphicsContext restoreGraphicsState];
5492 CGContextRestoreGState(cg);
5493}
5494
5495void QMacStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
5496 const QWidget *widget) const
5497{
5498 Q_D(const QMacStyle);
5499 QMacCGContext cg(p);
5500 if (!cg)
5501 qCWarning(lcMacStyle) << "drawComplexControl:" << cc << "invalid (nullptr) graphics context";
5502 QWindow *window = widget && widget->window() ? widget->window()->windowHandle() : nullptr;
5503 d->resolveCurrentNSView(window);
5504 switch (cc) {
5505 case CC_ScrollBar:
5506 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
5507 if (!cg) // Scroll bar rendering is either using NSControl or CoreGraphics directly ...
5508 break;
5509 const bool drawTrack = sb->subControls & SC_ScrollBarGroove;
5510 const bool drawKnob = sb->subControls & SC_ScrollBarSlider && sb->minimum != sb->maximum;
5511 if (!drawTrack && !drawKnob)
5512 break;
5513
5514 const bool isHorizontal = sb->orientation == Qt::Horizontal;
5515
5516 if (opt && opt->styleObject && !QMacStylePrivate::scrollBars.contains(opt->styleObject))
5517 QMacStylePrivate::scrollBars.append(QPointer<QObject>(opt->styleObject));
5518
5519 static const CGFloat knobWidths[] = { 7.0, 5.0, 5.0 };
5520 static const CGFloat expandedKnobWidths[] = { 11.0, 9.0, 9.0 };
5521 const auto cocoaSize = d->effectiveAquaSizeConstrain(opt, widget);
5522 const CGFloat maxExpandScale = expandedKnobWidths[cocoaSize] / knobWidths[cocoaSize];
5523
5524 const QStyle *realStyle = widget ? widget->style() : proxy();
5525 const bool isTransient = realStyle->styleHint(SH_ScrollBar_Transient, opt, widget);
5526 if (!isTransient)
5527 d->stopAnimation(opt->styleObject);
5528 bool wasActive = false;
5529 CGFloat opacity = 0.0;
5530 CGFloat expandScale = 1.0;
5531 CGFloat expandOffset = 0.0;
5532 bool shouldExpand = false;
5533
5534 if (QObject *styleObject = opt->styleObject) {
5535 const int oldPos = styleObject->property("_q_stylepos").toInt();
5536 const int oldMin = styleObject->property("_q_stylemin").toInt();
5537 const int oldMax = styleObject->property("_q_stylemax").toInt();
5538 const QRect oldRect = styleObject->property("_q_stylerect").toRect();
5539 const QStyle::State oldState = static_cast<QStyle::State>(styleObject->property("_q_stylestate").value<QStyle::State::Int>());
5540 const uint oldActiveControls = styleObject->property("_q_stylecontrols").toUInt();
5541
5542 // a scrollbar is transient when the scrollbar itself and
5543 // its sibling are both inactive (ie. not pressed/hovered/moved)
5544 const bool transient = isTransient && !opt->activeSubControls && !(sb->state & State_On);
5545
5546 if (!transient ||
5547 oldPos != sb->sliderPosition ||
5548 oldMin != sb->minimum ||
5549 oldMax != sb->maximum ||
5550 oldRect != sb->rect ||
5551 oldState != sb->state ||
5552 oldActiveControls != sb->activeSubControls) {
5553
5554 // if the scrollbar is transient or its attributes, geometry or
5555 // state has changed, the opacity is reset back to 100% opaque
5556 opacity = 1.0;
5557
5558 styleObject->setProperty("_q_stylepos", sb->sliderPosition);
5559 styleObject->setProperty("_q_stylemin", sb->minimum);
5560 styleObject->setProperty("_q_stylemax", sb->maximum);
5561 styleObject->setProperty("_q_stylerect", sb->rect);
5562 styleObject->setProperty("_q_stylestate", static_cast<QStyle::State::Int>(sb->state));
5563 styleObject->setProperty("_q_stylecontrols", static_cast<uint>(sb->activeSubControls));
5564
5565 QScrollbarStyleAnimation *anim = qobject_cast<QScrollbarStyleAnimation *>(d->animation(styleObject));
5566 if (transient) {
5567 if (!anim) {
5568 anim = new QScrollbarStyleAnimation(QScrollbarStyleAnimation::Deactivating, styleObject);
5569 d->startAnimation(anim);
5570 } else if (anim->mode() == QScrollbarStyleAnimation::Deactivating) {
5571 // the scrollbar was already fading out while the
5572 // state changed -> restart the fade out animation
5573 anim->setCurrentTime(0);
5574 }
5575 } else if (anim && anim->mode() == QScrollbarStyleAnimation::Deactivating) {
5576 d->stopAnimation(styleObject);
5577 }
5578 }
5579
5580 QScrollbarStyleAnimation *anim = qobject_cast<QScrollbarStyleAnimation *>(d->animation(styleObject));
5581 if (anim && anim->mode() == QScrollbarStyleAnimation::Deactivating) {
5582 // once a scrollbar was active (hovered/pressed), it retains
5583 // the active look even if it's no longer active while fading out
5584 if (oldActiveControls)
5585 anim->setActive(true);
5586
5587 wasActive = anim->wasActive();
5588 opacity = anim->currentValue();
5589 }
5590
5591 shouldExpand = isTransient && (opt->activeSubControls || wasActive);
5592 if (shouldExpand) {
5593 if (!anim && !oldActiveControls) {
5594 // Start expand animation only once and when entering
5595 anim = new QScrollbarStyleAnimation(QScrollbarStyleAnimation::Activating, styleObject);
5596 d->startAnimation(anim);
5597 }
5598 if (anim && anim->mode() == QScrollbarStyleAnimation::Activating) {
5599 expandScale = 1.0 + (maxExpandScale - 1.0) * anim->currentValue();
5600 expandOffset = 5.5 * (1.0 - anim->currentValue());
5601 } else {
5602 // Keep expanded state after the animation ends, and when fading out
5603 expandScale = maxExpandScale;
5604 expandOffset = 0.0;
5605 }
5606 }
5607 }
5608
5609 d->setupNSGraphicsContext(cg, NO /* flipped */);
5610
5611 const auto controlType = isHorizontal ? QMacStylePrivate::Scroller_Horizontal : QMacStylePrivate::Scroller_Vertical;
5612 const auto cw = QMacStylePrivate::CocoaControl(controlType, cocoaSize);
5613 NSScroller *scroller = static_cast<NSScroller *>(d->cocoaControl(cw));
5614
5615 const QColor bgColor = QStyleHelper::backgroundColor(opt->palette, widget);
5616 const bool hasDarkBg = bgColor.red() < 128 && bgColor.green() < 128 && bgColor.blue() < 128;
5617 if (isTransient) {
5618 // macOS behavior: as soon as one color channel is >= 128,
5619 // the background is considered bright, scroller is dark.
5620 scroller.knobStyle = hasDarkBg? NSScrollerKnobStyleLight : NSScrollerKnobStyleDark;
5621 } else {
5622 scroller.knobStyle = NSScrollerKnobStyleDefault;
5623 }
5624
5625 scroller.scrollerStyle = isTransient ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
5626
5627 if (!setupScroller(scroller, sb))
5628 break;
5629
5630 if (isTransient) {
5631 CGContextBeginTransparencyLayerWithRect(cg, scroller.frame, nullptr);
5632 CGContextSetAlpha(cg, opacity);
5633 }
5634
5635 if (drawTrack) {
5636 // Draw the track when hovering. Expand by shifting the track rect.
5637 if (!isTransient || opt->activeSubControls || wasActive) {
5638 CGRect trackRect = scroller.bounds;
5639 if (isHorizontal)
5640 trackRect.origin.y += expandOffset;
5641 else
5642 trackRect.origin.x += expandOffset;
5643 [scroller drawKnobSlotInRect:trackRect highlight:NO];
5644 }
5645 }
5646
5647 if (drawKnob) {
5648 if (shouldExpand) {
5649 // -[NSScroller drawKnob] is not useful here because any scaling applied
5650 // will only be used to draw the hi-DPI artwork. And even if did scale,
5651 // the stretched knob would look wrong, actually. So we need to draw the
5652 // scroller manually when it's being hovered.
5653 const CGFloat scrollerWidth = [NSScroller scrollerWidthForControlSize:scroller.controlSize scrollerStyle:scroller.scrollerStyle];
5654 const CGFloat knobWidth = knobWidths[cocoaSize] * expandScale;
5655 // Cocoa can help get the exact knob length in the current orientation
5656 const CGRect scrollerKnobRect = CGRectInset([scroller rectForPart:NSScrollerKnob], 1, 1);
5657 const CGFloat knobLength = isHorizontal ? scrollerKnobRect.size.width : scrollerKnobRect.size.height;
5658 const CGFloat knobPos = isHorizontal ? scrollerKnobRect.origin.x : scrollerKnobRect.origin.y;
5659 const CGFloat knobOffset = qRound((scrollerWidth + expandOffset - knobWidth) / 2.0);
5660 const CGFloat knobRadius = knobWidth / 2.0;
5661 CGRect knobRect;
5662 if (isHorizontal)
5663 knobRect = CGRectMake(knobPos, knobOffset, knobLength, knobWidth);
5664 else
5665 knobRect = CGRectMake(knobOffset, knobPos, knobWidth, knobLength);
5666 QCFType<CGPathRef> knobPath = CGPathCreateWithRoundedRect(knobRect, knobRadius, knobRadius, nullptr);
5667 CGContextAddPath(cg, knobPath);
5668 CGContextSetAlpha(cg, 0.5);
5669 CGColorRef knobColor = hasDarkBg ? NSColor.whiteColor.CGColor : NSColor.blackColor.CGColor;
5670 CGContextSetFillColorWithColor(cg, knobColor);
5671 CGContextFillPath(cg);
5672 } else {
5673 [scroller drawKnob];
5674
5675 if (!isTransient && opt->activeSubControls) {
5676 // The knob should appear darker (going from 0.76 down to 0.49).
5677 // But no blending mode can help darken enough in a single pass,
5678 // so we resort to drawing the knob twice with a small help from
5679 // blending. This brings the gray level to a close enough 0.53.
5680 CGContextSetBlendMode(cg, kCGBlendModePlusDarker);
5681 [scroller drawKnob];
5682 }
5683 }
5684 }
5685
5686 if (isTransient)
5687 CGContextEndTransparencyLayer(cg);
5688
5689 d->restoreNSGraphicsContext(cg);
5690 }
5691 break;
5692 case CC_Slider:
5693 if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
5694 const bool isHorizontal = sl->orientation == Qt::Horizontal;
5695 const auto ct = isHorizontal ? QMacStylePrivate::Slider_Horizontal : QMacStylePrivate::Slider_Vertical;
5696 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
5697 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
5698 auto *slider = static_cast<NSSlider *>(d->cocoaControl(cw));
5699 if (!setupSlider(slider, sl))
5700 break;
5701
5702 const bool hasTicks = sl->tickPosition != QSlider::NoTicks;
5703 const bool hasDoubleTicks = sl->tickPosition == QSlider::TicksBothSides;
5704 const bool drawKnob = sl->subControls & SC_SliderHandle;
5705 const bool drawBar = sl->subControls & SC_SliderGroove;
5706 const bool drawTicks = sl->subControls & SC_SliderTickmarks;
5707 const bool isPressed = qt_apple_runningWithLiquidGlass() ? false : sl->state & State_Sunken;
5708
5709 CGPoint pressPoint;
5710 if (isPressed) {
5711 const CGRect knobRect = [slider.cell knobRectFlipped:slider.isFlipped];
5712 pressPoint.x = CGRectGetMidX(knobRect);
5713 pressPoint.y = CGRectGetMidY(knobRect);
5714
5715 // The only way to tell a NSSlider/NSSliderCell to render as pressed
5716 // is to start tracking. But this API has some weird behaviors that
5717 // we have to account for. First of all, the pressed state will not
5718 // be visually reflected unless we start tracking twice. And secondly
5719 // if we don't track twice, the state of one render-pass will affect
5720 // the render pass of other sliders, even if we set up the shared
5721 // NSSlider with a new slider value.
5722 //
5723 // Note: with the 'Liquid Glass' enabled, this trick is not working anymore (instead of pressed
5724 // state macOS has a nice 'lensing' effect for a pressed thumb, which we don't see anyway)
5725 // but potentially creates a problem for our baseline test, where the 'knob' is incorrectly
5726 // placed related to the slider's groove (its filled area).
5727
5728 [slider.cell startTrackingAt:pressPoint inView:slider];
5729 [slider.cell startTrackingAt:pressPoint inView:slider];
5730 }
5731
5732 d->drawNSViewInRect(slider, opt->rect, p, ^(CGContextRef ctx, const CGRect &rect) {
5733
5734 // Since the GC is flipped, upsideDown means *not* inverted when vertical.
5735 const bool verticalFlip = !isHorizontal && !sl->upsideDown; // FIXME: && !isSierraOrLater
5736
5737 if (isHorizontal) {
5738 if (sl->upsideDown) {
5739 CGContextTranslateCTM(ctx, rect.size.width, rect.origin.y);
5740 CGContextScaleCTM(ctx, -1, 1);
5741 } else {
5742 CGContextTranslateCTM(ctx, 0, rect.origin.y);
5743 }
5744 } else if (verticalFlip) {
5745 CGContextTranslateCTM(ctx, rect.origin.x, rect.size.height);
5746 CGContextScaleCTM(ctx, 1, -1);
5747 }
5748
5749 if (hasDoubleTicks) {
5750 // This ain't HIG kosher: eye-proved constants
5751 if (isHorizontal)
5752 CGContextTranslateCTM(ctx, 0, 4);
5753 else
5754 CGContextTranslateCTM(ctx, 1, 0);
5755 }
5756
5757#if 0
5758 // FIXME: Sadly, this part doesn't work. It seems to somehow pollute the
5759 // NSSlider's internal state and, when we need to use the "else" part,
5760 // the slider's frame is not in sync with its cell dimensions.
5761 const bool drawAllParts = drawKnob && drawBar && (!hasTicks || drawTicks);
5762 if (drawAllParts && !hasDoubleTicks && (!verticalFlip || drawTicks)) {
5763 // Draw eveything at once if we're going to, except for inverted vertical
5764 // sliders which need to be drawn part by part because of the shadow below
5765 // the knob. Same for two-sided tickmarks.
5766 if (verticalFlip && drawTicks) {
5767 // Since tickmarks are always rendered symmetrically, a vertically
5768 // flipped slider with tickmarks only needs to get its value flipped.
5769 slider.intValue = slider.maxValue - slider.intValue + slider.minValue;
5770 }
5771 [slider drawRect:CGRectZero];
5772 } else
5773#endif
5774 {
5775 NSSliderCell *cell = slider.cell;
5776
5777 const int numberOfTickMarks = slider.numberOfTickMarks;
5778 // This ain't HIG kosher: force tick-less bar position.
5779 if (hasDoubleTicks)
5780 slider.numberOfTickMarks = 0;
5781
5782 const CGRect barRect = [cell barRectFlipped:slider.isFlipped];
5783 if (drawBar) {
5784 if (!isHorizontal && !sl->upsideDown && (hasDoubleTicks || !hasTicks)) {
5785 // The logic behind verticalFlip and upsideDown is the twisted one.
5786 // Bar is the only part of the cell affected by this 'flipped'
5787 // parameter in the call below, all other parts (knob, etc.) 'fixed'
5788 // by scaling/translating. With ticks on one side it's not a problem
5789 // at all - the bar is gray anyway. Without ticks or with ticks on
5790 // the both sides, for inverted appearance and vertical orientation -
5791 // we must flip so that knob and blue filling work in accordance.
5792 [cell drawBarInside:barRect flipped:true];
5793 } else {
5794 [cell drawBarInside:barRect flipped:!verticalFlip];
5795 }
5796 // This ain't HIG kosher: force unfilled bar look.
5797 if (hasDoubleTicks)
5798 slider.numberOfTickMarks = numberOfTickMarks;
5799 }
5800
5801 if (hasTicks && drawTicks) {
5802 if (!drawBar && hasDoubleTicks)
5803 slider.numberOfTickMarks = numberOfTickMarks;
5804
5805 if (qt_apple_runningWithLiquidGlass())
5806 drawTickMarks(ctx, slider, sl);
5807 else
5808 [cell drawTickMarks];
5809
5810 if (hasDoubleTicks) {
5811 // This ain't HIG kosher: just slap a set of tickmarks on each side, like we used to.
5812 CGAffineTransform tickMarksFlip;
5813 const CGRect tickMarkRect = [cell rectOfTickMarkAtIndex:0];
5814 if (isHorizontal) {
5815 tickMarksFlip = CGAffineTransformMakeTranslation(0, rect.size.height - tickMarkRect.size.height - 3);
5816 tickMarksFlip = CGAffineTransformScale(tickMarksFlip, 1, -1);
5817 } else {
5818 tickMarksFlip = CGAffineTransformMakeTranslation(rect.size.width - tickMarkRect.size.width / 2, 0);
5819 tickMarksFlip = CGAffineTransformScale(tickMarksFlip, -1, 1);
5820 }
5821 CGContextConcatCTM(ctx, tickMarksFlip);
5822 [cell drawTickMarks];
5823 CGContextConcatCTM(ctx, CGAffineTransformInvert(tickMarksFlip));
5824 }
5825 }
5826
5827 if (drawKnob) {
5828 // This ain't HIG kosher: force round knob look.
5829 if (hasDoubleTicks)
5830 slider.numberOfTickMarks = 0;
5831 if (qt_apple_runningWithLiquidGlass())
5832 drawSliderKnob(ctx, slider);
5833 else
5834 [cell drawKnob];
5835 }
5836 }
5837 });
5838
5839 if (isPressed) {
5840 // We stop twice to be on the safe side, even if one seems to be enough.
5841 // See startTracking above for why we do this.
5842 [slider.cell stopTracking:pressPoint at:pressPoint inView:slider mouseIsUp:NO];
5843 [slider.cell stopTracking:pressPoint at:pressPoint inView:slider mouseIsUp:NO];
5844 }
5845 }
5846 break;
5847#if QT_CONFIG(spinbox)
5848 case CC_SpinBox:
5849 if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
5850 if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
5851 const auto lineEditRect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxEditField, widget);
5852 QStyleOptionFrame frame;
5853 static_cast<QStyleOption &>(frame) = *opt;
5854 frame.rect = lineEditRect;
5855 frame.state |= State_Sunken;
5856 frame.lineWidth = 1;
5857 frame.midLineWidth = 0;
5858 frame.features = QStyleOptionFrame::None;
5859 frame.frameShape = QFrame::Box;
5860 drawPrimitive(PE_FrameLineEdit, &frame, p, widget);
5861 }
5862 if (sb->subControls & (SC_SpinBoxUp | SC_SpinBoxDown)) {
5863 const QRect updown = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxUp, widget)
5864 | proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxDown, widget);
5865 if (!cg) // Using controls or CoreGraphics, needs a valid context.
5866 break;
5867 d->setupNSGraphicsContext(cg, NO);
5868
5869 const auto aquaSize = d->effectiveAquaSizeConstrain(opt, widget);
5870 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::Stepper, aquaSize);
5871 NSStepperCell *cell = static_cast<NSStepperCell *>(d->cocoaCell(cw));
5872 const auto controlSize = cell.controlSize;
5873 if (qt_apple_runningWithLiquidGlass())
5874 cell.controlSize = NSControlSizeMini;
5875 cell.enabled = (sb->state & State_Enabled);
5876
5877 const CGRect newRect = [cell drawingRectForBounds:updown.toCGRect()];
5878
5879 const bool upPressed = sb->activeSubControls == SC_SpinBoxUp && (sb->state & State_Sunken);
5880 const bool downPressed = sb->activeSubControls == SC_SpinBoxDown && (sb->state & State_Sunken);
5881 const CGFloat x = CGRectGetMidX(newRect);
5882 const CGFloat y = upPressed ? -3 : 3; // Weird coordinate shift going on. Verified with Hopper
5883 const CGPoint pressPoint = CGPointMake(x, y);
5884 // Pretend we're pressing the mouse on the right button. Unfortunately, NSStepperCell has no
5885 // API to highlight a specific button. The highlighted property works only on the down button.
5886 if (upPressed || downPressed)
5887 [cell startTrackingAt:pressPoint inView:d->backingStoreNSView];
5888
5889 [cell drawWithFrame:newRect inView:d->backingStoreNSView];
5890
5891 if (upPressed || downPressed)
5892 [cell stopTracking:pressPoint at:pressPoint inView:d->backingStoreNSView mouseIsUp:NO];
5893
5894 d->restoreNSGraphicsContext(cg);
5895 if (qt_apple_runningWithLiquidGlass())
5896 cell.controlSize = controlSize;
5897 }
5898 }
5899 break;
5900#endif
5901#if QT_CONFIG(combobox)
5902 case CC_ComboBox:
5903 if (const auto *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
5904 const bool isEnabled = combo->state & State_Enabled;
5905 const bool isPressed = combo->state & State_Sunken;
5906
5907 const auto ct = cocoaControlType(combo, widget);
5908 const auto cs = d->effectiveAquaSizeConstrain(combo, widget);
5909 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
5910 auto *cc = static_cast<NSControl *>(d->cocoaControl(cw));
5911 cc.enabled = isEnabled;
5912 QRectF frameRect = cw.adjustedControlFrame(combo->rect);
5913 if (cw.type == QMacStylePrivate::Button_PopupButton) {
5914 // Non-editable QComboBox
5915 auto *pb = static_cast<NSPopUpButton *>(cc);
5916 // FIXME Old offsets. Try to move to adjustedControlFrame()
5917 if (cw.size == QStyleHelper::SizeSmall) {
5918 frameRect = frameRect.translated(0, 1);
5919 } else if (cw.size == QStyleHelper::SizeMini) {
5920 // Same 0.5 pt misalignment as AppKit and fit the focus ring
5921 frameRect = frameRect.translated(2, -0.5);
5922 }
5923 pb.frame = frameRect.toCGRect();
5924 [pb highlight:isPressed];
5925 d->drawNSViewInRect(pb, frameRect, p, ^(CGContextRef, const CGRect &r) {
5926 [pb.cell drawBezelWithFrame:r inView:pb.superview];
5927 });
5928 } else if (cw.type == QMacStylePrivate::ComboBox) {
5929 // Editable QComboBox
5930 auto *cb = static_cast<NSComboBox *>(cc);
5931 const auto frameRect = cw.adjustedControlFrame(combo->rect);
5932 cb.frame = frameRect.toCGRect();
5933
5934 // This API was requested to Apple in rdar #36197888. We know it's safe to use up to macOS 10.13.3
5935 if (NSButtonCell *cell = static_cast<NSButtonCell *>([cc.cell qt_valueForPrivateKey:@"_buttonCell"])) {
5936 cell.highlighted = isPressed;
5937 } else {
5938 // TODO Render to pixmap and darken the button manually
5939 }
5940
5941 d->drawNSViewInRect(cb, frameRect, p, ^(CGContextRef, const CGRect &r) {
5942 // FIXME This is usually drawn in the control's superview, but we wouldn't get inactive look in this case
5943 [cb.cell drawWithFrame:r inView:cb];
5944 });
5945 }
5946
5947 if (combo->state & State_HasFocus) {
5948 // TODO Remove and use QFocusFrame instead.
5949 const int hMargin = proxy()->pixelMetric(QStyle::PM_FocusFrameHMargin, combo, widget);
5950 const int vMargin = proxy()->pixelMetric(QStyle::PM_FocusFrameVMargin, combo, widget);
5951 QRectF focusRect;
5952 if (cw.type == QMacStylePrivate::Button_PopupButton) {
5953 if (qt_apple_runningWithLiquidGlass())
5954 focusRect = QRectF::fromCGRect(qt_alignmentRectForFrame(cc.frame, cw.size, cw.type));
5955 else
5956 focusRect = QRectF::fromCGRect([cc alignmentRectForFrame:cc.frame]);
5957 focusRect -= pullDownButtonShadowMargins[cw.size];
5958 if (cw.size == QStyleHelper::SizeSmall)
5959 focusRect = focusRect.translated(0, 1);
5960 else if (cw.size == QStyleHelper::SizeMini)
5961 focusRect = focusRect.translated(2, -1);
5962 } else if (cw.type == QMacStylePrivate::ComboBox) {
5963 focusRect = frameRect - comboBoxFocusRingMargins[cw.size];
5964 }
5965 d->drawFocusRing(p, focusRect, hMargin, vMargin, cw);
5966 }
5967 }
5968 break;
5969#endif // QT_CONFIG(combobox)
5970 case CC_TitleBar:
5971 if (const auto *titlebar = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
5972 const bool isActive = (titlebar->state & State_Active)
5973 && (titlebar->titleBarState & State_Active);
5974
5975 p->fillRect(opt->rect, Qt::transparent);
5976 p->setRenderHint(QPainter::Antialiasing);
5977 p->setClipRect(opt->rect, Qt::IntersectClip);
5978
5979 // FIXME A single drawPath() with 0-sized pen
5980 // doesn't look as good as this double fillPath().
5981 const auto outerFrameRect = QRectF(opt->rect.adjusted(0, 0, 0, opt->rect.height()));
5982 QPainterPath outerFramePath = d->windowPanelPath(outerFrameRect);
5983 p->fillPath(outerFramePath, opt->palette.dark());
5984
5985 const auto frameAdjust = 1.0 / p->device()->devicePixelRatio();
5986 const auto innerFrameRect = outerFrameRect.adjusted(frameAdjust, frameAdjust, -frameAdjust, 0);
5987 QPainterPath innerFramePath = d->windowPanelPath(innerFrameRect);
5988 p->fillPath(innerFramePath, opt->palette.button());
5989
5990 if (titlebar->subControls & (SC_TitleBarCloseButton
5991 | SC_TitleBarMaxButton
5992 | SC_TitleBarMinButton
5993 | SC_TitleBarNormalButton)) {
5994 const bool isHovered = (titlebar->state & State_MouseOver);
5995 static const SubControl buttons[] = {
5996 SC_TitleBarCloseButton, SC_TitleBarMinButton, SC_TitleBarMaxButton
5997 };
5998 for (const auto sc : buttons) {
5999 const auto ct = d->windowButtonCocoaControl(sc);
6000 const auto cw = QMacStylePrivate::CocoaControl(ct, QStyleHelper::SizeLarge);
6001 auto *wb = static_cast<NSButton *>(d->cocoaControl(cw));
6002 wb.enabled = (sc & titlebar->subControls) && isActive;
6003 [wb highlight:(titlebar->state & State_Sunken) && (sc & titlebar->activeSubControls)];
6004 Q_UNUSED(isHovered); // FIXME No public API for this
6005
6006 const auto buttonRect = proxy()->subControlRect(CC_TitleBar, titlebar, sc, widget);
6007 d->drawNSViewInRect(wb, buttonRect, p, ^(CGContextRef, const CGRect &rect) {
6008 auto *wbCell = static_cast<NSButtonCell *>(wb.cell);
6009 [wbCell drawWithFrame:rect inView:wb];
6010 });
6011 }
6012 }
6013
6014 if (titlebar->subControls & SC_TitleBarLabel) {
6015 const auto tr = proxy()->subControlRect(CC_TitleBar, titlebar, SC_TitleBarLabel, widget);
6016 if (!titlebar->icon.isNull()) {
6017 const auto iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
6018 const auto iconSize = QSize(iconExtent, iconExtent);
6019 const auto iconPos = tr.x() - titlebar->icon.actualSize(iconSize).width() - qRound(titleBarIconTitleSpacing);
6020 // Only render the icon if it'll be fully visible
6021 if (iconPos < tr.right() - titleBarIconTitleSpacing)
6022 p->drawPixmap(iconPos, tr.y(), titlebar->icon.pixmap(iconSize, QIcon::Normal));
6023 }
6024
6025 if (!titlebar->text.isEmpty())
6026 drawItemText(p, tr, Qt::AlignCenter, opt->palette, isActive, titlebar->text, QPalette::Text);
6027 }
6028 }
6029 break;
6030 case CC_GroupBox:
6031 if (const QStyleOptionGroupBox *gb
6032 = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
6033
6034 QStyleOptionGroupBox groupBox(*gb);
6035 const bool flat = groupBox.features & QStyleOptionFrame::Flat;
6036 if (!flat)
6037 groupBox.state |= QStyle::State_Mini; // Force mini-sized checkbox to go with small-sized label
6038 else
6039 groupBox.subControls = groupBox.subControls & ~SC_GroupBoxFrame; // We don't like frames and ugly lines
6040
6041 const bool didSetFont = widget && widget->testAttribute(Qt::WA_SetFont);
6042 const bool didModifySubControls = !didSetFont && QApplication::desktopSettingsAware();
6043 if (didModifySubControls)
6044 groupBox.subControls = groupBox.subControls & ~SC_GroupBoxLabel;
6045 QCommonStyle::drawComplexControl(cc, &groupBox, p, widget);
6046 if (didModifySubControls) {
6047 const QRect rect = proxy()->subControlRect(CC_GroupBox, &groupBox, SC_GroupBoxLabel, widget);
6048 const bool rtl = groupBox.direction == Qt::RightToLeft;
6049 const int alignment = Qt::TextHideMnemonic | (rtl ? Qt::AlignRight : Qt::AlignLeft);
6050 const QFont savedFont = p->font();
6051 if (!flat && d->smallSystemFont)
6052 p->setFont(*d->smallSystemFont);
6053 proxy()->drawItemText(p, rect, alignment, groupBox.palette, groupBox.state & State_Enabled, groupBox.text, QPalette::WindowText);
6054 if (!flat)
6055 p->setFont(savedFont);
6056 }
6057 }
6058 break;
6059 case CC_ToolButton:
6060 if (const QStyleOptionToolButton *tb
6061 = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
6062#if QT_CONFIG(accessibility)
6063 if (QStyleHelper::hasAncestor(opt->styleObject, QAccessible::ToolBar)) {
6064 if (tb->subControls & SC_ToolButtonMenu) {
6065 QStyleOption arrowOpt = *tb;
6066 arrowOpt.rect = proxy()->subControlRect(cc, tb, SC_ToolButtonMenu, widget);
6067 arrowOpt.rect.setY(arrowOpt.rect.y() + arrowOpt.rect.height() / 2);
6068 arrowOpt.rect.setHeight(arrowOpt.rect.height() / 2);
6069 proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, widget);
6070 } else if ((tb->features & QStyleOptionToolButton::HasMenu)
6071 && (tb->toolButtonStyle != Qt::ToolButtonTextOnly && !tb->icon.isNull())) {
6072 d->drawToolbarButtonArrow(tb, p);
6073 }
6074 if (tb->state & State_On) {
6075 NSView *view = window ? (NSView *)window->winId() : nil;
6076 bool isKey = false;
6077 if (view)
6078 isKey = [view.window isKeyWindow];
6079
6080 QBrush brush(brushForToolButton(isKey));
6081 QPainterPath path;
6082 path.addRoundedRect(QRectF(tb->rect.x(), tb->rect.y(), tb->rect.width(), tb->rect.height() + 4), 4, 4);
6083 p->setRenderHint(QPainter::Antialiasing);
6084 p->fillPath(path, brush);
6085 }
6086 proxy()->drawControl(CE_ToolButtonLabel, opt, p, widget);
6087 } else
6088#endif // QT_CONFIG(accessibility)
6089 {
6090 auto bflags = tb->state;
6091 if (tb->subControls & SC_ToolButton)
6092 bflags |= State_Sunken;
6093 auto mflags = tb->state;
6094 if (tb->subControls & SC_ToolButtonMenu)
6095 mflags |= State_Sunken;
6096
6097 if (tb->subControls & SC_ToolButton) {
6098 if (bflags & (State_Sunken | State_On | State_Raised)) {
6099 const bool isEnabled = tb->state & State_Enabled;
6100 const bool isPressed = tb->state & State_Sunken;
6101 const bool isHighlighted = (tb->state & State_Active) && (tb->state & State_On);
6102 const auto ct = QMacStylePrivate::Button_PushButton;
6103 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
6104 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
6105 auto *pb = static_cast<NSButton *>(d->cocoaControl(cw));
6106 pb.bezelStyle = NSBezelStyleShadowlessSquare; // TODO Use NSTexturedRoundedBezelStyle in the future.
6107 pb.frame = opt->rect.toCGRect();
6108 pb.buttonType = NSButtonTypePushOnPushOff;
6109 pb.enabled = isEnabled;
6110 [pb highlight:isPressed];
6111 pb.state = isHighlighted && !isPressed ? NSControlStateValueOn : NSControlStateValueOff;
6112 const auto buttonRect = proxy()->subControlRect(cc, tb, SC_ToolButton, widget);
6113 d->drawNSViewInRect(pb, buttonRect, p, ^(CGContextRef, const CGRect &rect) {
6114 [pb.cell drawBezelWithFrame:rect inView:pb];
6115 });
6116 }
6117 }
6118
6119 if (tb->subControls & SC_ToolButtonMenu) {
6120 const auto menuRect = proxy()->subControlRect(cc, tb, SC_ToolButtonMenu, widget);
6121 QStyleOption arrowOpt = *tb;
6122 arrowOpt.rect = QRect(menuRect.x() + ((menuRect.width() - toolButtonArrowSize) / 2),
6123 menuRect.height() - (toolButtonArrowSize + toolButtonArrowMargin),
6126 proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, widget);
6127 } else if (tb->features & QStyleOptionToolButton::HasMenu) {
6128 d->drawToolbarButtonArrow(tb, p);
6129 }
6130 QRect buttonRect = proxy()->subControlRect(CC_ToolButton, tb, SC_ToolButton, widget);
6131 int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
6132 QStyleOptionToolButton label = *tb;
6133 label.rect = buttonRect.adjusted(fw, fw, -fw, -fw);
6134 proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget);
6135 }
6136 }
6137 break;
6138#if QT_CONFIG(dial)
6139 case CC_Dial:
6140 if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt))
6141 QStyleHelper::drawDial(dial, p);
6142 break;
6143#endif
6144 default:
6145 QCommonStyle::drawComplexControl(cc, opt, p, widget);
6146 break;
6147 }
6148}
6149
6151 const QStyleOptionComplex *opt,
6152 const QPoint &pt, const QWidget *widget) const
6153{
6154 Q_D(const QMacStyle);
6155 SubControl sc = QStyle::SC_None;
6156 switch (cc) {
6157 case CC_ComboBox:
6158 if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
6159 sc = QCommonStyle::hitTestComplexControl(cc, cmb, pt, widget);
6160 if (!cmb->editable && sc != QStyle::SC_None)
6161 sc = SC_ComboBoxArrow; // A bit of a lie, but what we want
6162 }
6163 break;
6164 case CC_Slider:
6165 if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6166 if (!sl->rect.contains(pt))
6167 break;
6168
6169 const bool hasTicks = sl->tickPosition != QSlider::NoTicks;
6170 const bool isHorizontal = sl->orientation == Qt::Horizontal;
6171 const auto ct = isHorizontal ? QMacStylePrivate::Slider_Horizontal : QMacStylePrivate::Slider_Vertical;
6172 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
6173 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
6174 auto *slider = static_cast<NSSlider *>(d->cocoaControl(cw));
6175 if (!setupSlider(slider, sl))
6176 break;
6177
6178 NSSliderCell *cell = slider.cell;
6179 const auto barRect = QRectF::fromCGRect([cell barRectFlipped:slider.isFlipped]);
6180 const auto knobRect = QRectF::fromCGRect([cell knobRectFlipped:slider.isFlipped]);
6181 if (knobRect.contains(pt)) {
6182 sc = SC_SliderHandle;
6183 } else if (barRect.contains(pt)) {
6184 sc = SC_SliderGroove;
6185 } else if (hasTicks) {
6186 sc = SC_SliderTickmarks;
6187 }
6188 }
6189 break;
6190 case CC_ScrollBar:
6191 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6192 if (!sb->rect.contains(pt)) {
6193 sc = SC_None;
6194 break;
6195 }
6196
6197 const bool isHorizontal = sb->orientation == Qt::Horizontal;
6198 const auto ct = isHorizontal ? QMacStylePrivate::Scroller_Horizontal : QMacStylePrivate::Scroller_Vertical;
6199 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
6200 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
6201 auto *scroller = static_cast<NSScroller *>(d->cocoaControl(cw));
6202 if (!setupScroller(scroller, sb)) {
6203 sc = SC_None;
6204 break;
6205 }
6206
6207 // Since -[NSScroller testPart:] doesn't want to cooperate, we do it the
6208 // straightforward way. In any case, macOS doesn't return line-sized changes
6209 // with NSScroller since 10.7, according to the aforementioned method's doc.
6210 const auto knobRect = QRectF::fromCGRect([scroller rectForPart:NSScrollerKnob]);
6211 if (isHorizontal) {
6212 const bool isReverse = sb->direction == Qt::RightToLeft;
6213 if (pt.x() < knobRect.left())
6214 sc = isReverse ? SC_ScrollBarAddPage : SC_ScrollBarSubPage;
6215 else if (pt.x() > knobRect.right())
6216 sc = isReverse ? SC_ScrollBarSubPage : SC_ScrollBarAddPage;
6217 else
6218 sc = SC_ScrollBarSlider;
6219 } else {
6220 if (pt.y() < knobRect.top())
6221 sc = SC_ScrollBarSubPage;
6222 else if (pt.y() > knobRect.bottom())
6223 sc = SC_ScrollBarAddPage;
6224 else
6225 sc = SC_ScrollBarSlider;
6226 }
6227 }
6228 break;
6229 default:
6230 sc = QCommonStyle::hitTestComplexControl(cc, opt, pt, widget);
6231 break;
6232 }
6233 return sc;
6234}
6235
6236QRect QMacStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
6237 const QWidget *widget) const
6238{
6239 Q_D(const QMacStyle);
6240 QRect ret;
6241 switch (cc) {
6242 case CC_ScrollBar:
6243 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6244 const bool isHorizontal = sb->orientation == Qt::Horizontal;
6245 const bool isReverseHorizontal = isHorizontal && (sb->direction == Qt::RightToLeft);
6246
6247 NSScrollerPart part = NSScrollerNoPart;
6248 if (sc == SC_ScrollBarSlider) {
6249 part = NSScrollerKnob;
6250 } else if (sc == SC_ScrollBarGroove) {
6251 part = NSScrollerKnobSlot;
6252 } else if (sc == SC_ScrollBarSubPage || sc == SC_ScrollBarAddPage) {
6253 if ((!isReverseHorizontal && sc == SC_ScrollBarSubPage)
6254 || (isReverseHorizontal && sc == SC_ScrollBarAddPage))
6255 part = NSScrollerDecrementPage;
6256 else
6257 part = NSScrollerIncrementPage;
6258 }
6259 // And nothing else since 10.7
6260
6261 if (part != NSScrollerNoPart) {
6262 const auto ct = isHorizontal ? QMacStylePrivate::Scroller_Horizontal : QMacStylePrivate::Scroller_Vertical;
6263 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
6264 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
6265 auto *scroller = static_cast<NSScroller *>(d->cocoaControl(cw));
6266 if (setupScroller(scroller, sb))
6267 ret = QRectF::fromCGRect([scroller rectForPart:part]).toRect();
6268 }
6269 }
6270 break;
6271 case CC_Slider:
6272 if (const QStyleOptionSlider *sl = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6273 const bool hasTicks = sl->tickPosition != QSlider::NoTicks;
6274 const bool isHorizontal = sl->orientation == Qt::Horizontal;
6275 const auto ct = isHorizontal ? QMacStylePrivate::Slider_Horizontal : QMacStylePrivate::Slider_Vertical;
6276 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
6277 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
6278 auto *slider = static_cast<NSSlider *>(d->cocoaControl(cw));
6279 if (!setupSlider(slider, sl))
6280 break;
6281
6282 NSSliderCell *cell = slider.cell;
6283 if (sc == SC_SliderHandle) {
6284 ret = QRectF::fromCGRect([cell knobRectFlipped:slider.isFlipped]).toRect();
6285 if (isHorizontal) {
6286 ret.setTop(sl->rect.top());
6287 ret.setBottom(sl->rect.bottom());
6288 } else {
6289 ret.setLeft(sl->rect.left());
6290 ret.setRight(sl->rect.right());
6291 }
6292 } else if (sc == SC_SliderGroove) {
6293 ret = QRectF::fromCGRect([cell barRectFlipped:slider.isFlipped]).toRect();
6294 } else if (hasTicks && sc == SC_SliderTickmarks) {
6295 const auto tickMarkRect = QRectF::fromCGRect([cell rectOfTickMarkAtIndex:0]);
6296 if (isHorizontal)
6297 ret = QRect(sl->rect.left(), tickMarkRect.top(), sl->rect.width(), tickMarkRect.height());
6298 else
6299 ret = QRect(tickMarkRect.left(), sl->rect.top(), tickMarkRect.width(), sl->rect.height());
6300 }
6301
6302 // Invert if needed and extend to the actual bounds of the slider
6303 if (isHorizontal) {
6304 if (sl->upsideDown) {
6305 ret = QRect(sl->rect.right() - ret.right(), sl->rect.top(), ret.width(), sl->rect.height());
6306 } else {
6307 ret.setTop(sl->rect.top());
6308 ret.setBottom(sl->rect.bottom());
6309 }
6310 } else {
6311 if (!sl->upsideDown) {
6312 ret = QRect(sl->rect.left(), sl->rect.bottom() - ret.bottom(), sl->rect.width(), ret.height());
6313 } else {
6314 ret.setLeft(sl->rect.left());
6315 ret.setRight(sl->rect.right());
6316 }
6317 }
6318 }
6319 break;
6320 case CC_TitleBar:
6321 if (const auto *titlebar = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
6322 // The title bar layout is as follows: close, min, zoom, icon, title
6323 // [ x _ + @ Window Title ]
6324 // Center the icon and title until it starts to overlap with the buttons.
6325 // The icon doesn't count towards SC_TitleBarLabel, but it's still rendered
6326 // next to the title text. See drawComplexControl().
6327 if (sc == SC_TitleBarLabel) {
6328 qreal labelWidth = titlebar->fontMetrics.horizontalAdvance(titlebar->text) + 1; // FIXME Rounding error?
6329 qreal labelHeight = titlebar->fontMetrics.height();
6330
6331 const auto lastButtonRect = proxy()->subControlRect(CC_TitleBar, titlebar, SC_TitleBarMaxButton, widget);
6332 qreal controlsSpacing = lastButtonRect.right() + titleBarButtonSpacing;
6333 if (!titlebar->icon.isNull()) {
6334 const auto iconSize = proxy()->pixelMetric(PM_SmallIconSize);
6335 const auto actualIconSize = titlebar->icon.actualSize(QSize(iconSize, iconSize)).width();
6336 controlsSpacing += actualIconSize + titleBarIconTitleSpacing;
6337 }
6338
6339 const qreal labelPos = qMax(controlsSpacing, (opt->rect.width() - labelWidth) / 2.0);
6340 labelWidth = qMin(labelWidth, opt->rect.width() - (labelPos + titleBarTitleRightMargin));
6341 ret = QRect(labelPos, (opt->rect.height() - labelHeight) / 2,
6342 labelWidth, labelHeight);
6343 } else {
6344 const auto currentButton = d->windowButtonCocoaControl(sc);
6345 if (currentButton == QMacStylePrivate::NoControl)
6346 break;
6347
6348 QPointF buttonPos = titlebar->rect.topLeft() + QPointF(titleBarButtonSpacing, 0);
6349 QSizeF buttonSize;
6350 for (int ct = QMacStylePrivate::Button_WindowClose; ct <= currentButton; ct++) {
6351 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::CocoaControlType(ct),
6352 QStyleHelper::SizeLarge);
6353 auto *wb = static_cast<NSButton *>(d->cocoaControl(cw));
6354 if (ct == currentButton)
6355 buttonSize = QSizeF::fromCGSize(wb.frame.size);
6356 else
6357 buttonPos.rx() += wb.frame.size.width + titleBarButtonSpacing;
6358 }
6359
6360 const auto vOffset = (opt->rect.height() - buttonSize.height()) / 2.0;
6361 ret = QRectF(buttonPos, buttonSize).translated(0, vOffset).toRect();
6362 }
6363 }
6364 break;
6365 case CC_ComboBox:
6366 if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
6367 const auto ct = cocoaControlType(combo, widget);
6368 const auto cs = d->effectiveAquaSizeConstrain(combo, widget);
6369 const auto cw = QMacStylePrivate::CocoaControl(ct, cs);
6370 const auto editRect = QMacStylePrivate::comboboxEditBounds(cw.adjustedControlFrame(combo->rect), cw);
6371
6372 switch (sc) {
6373 case SC_ComboBoxEditField:{
6374 ret = editRect.toAlignedRect();
6375 break; }
6376 case SC_ComboBoxArrow:{
6377 ret = editRect.toAlignedRect();
6378 ret.setX(ret.x() + ret.width());
6379 ret.setWidth(combo->rect.right() - ret.right());
6380 break; }
6381 case SC_ComboBoxListBoxPopup:{
6382 if (combo->editable) {
6383 const CGRect inner = QMacStylePrivate::comboboxInnerBounds(combo->rect.toCGRect(), cw);
6384 const int comboTop = combo->rect.top();
6385 ret = QRect(qRound(inner.origin.x),
6386 comboTop,
6387 qRound(inner.origin.x - combo->rect.left() + inner.size.width),
6388 editRect.bottom() - comboTop + 2);
6389 } else {
6390 ret = QRect(combo->rect.x() + 4 - 11,
6391 combo->rect.y() + 1,
6392 editRect.width() + 10 + 11,
6393 1);
6394 }
6395 break; }
6396 default:
6397 break;
6398 }
6399 }
6400 break;
6401 case CC_GroupBox:
6402 if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
6403 bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
6404 const bool flat = groupBox->features & QStyleOptionFrame::Flat;
6405 bool hasNoText = !checkable && groupBox->text.isEmpty();
6406 switch (sc) {
6407 case SC_GroupBoxLabel:
6408 case SC_GroupBoxCheckBox: {
6409 // Cheat and use the smaller font if we need to
6410 const bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
6411 const bool fontIsSet = (widget && widget->testAttribute(Qt::WA_SetFont))
6412 || !QApplication::desktopSettingsAware();
6413 const int margin = flat || hasNoText ? 0 : 9;
6414 ret = groupBox->rect.adjusted(margin, 0, -margin, 0);
6415
6416 const QFontMetricsF fm = flat || fontIsSet || !d->smallSystemFont
6417 ? QFontMetricsF(groupBox->fontMetrics)
6418 : QFontMetricsF(*d->smallSystemFont);
6419 const QSizeF s = fm.size(Qt::AlignHCenter | Qt::AlignVCenter, qt_mac_removeMnemonics(groupBox->text), 0, nullptr);
6420 const int tw = qCeil(s.width());
6421 const int h = qCeil(fm.height());
6422 ret.setHeight(h);
6423
6424 QRect labelRect = alignedRect(groupBox->direction, groupBox->textAlignment,
6425 QSize(tw, h), ret);
6426 if (flat && checkable)
6427 labelRect.moveLeft(labelRect.left() + 4);
6428 int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, opt, widget);
6429 bool rtl = groupBox->direction == Qt::RightToLeft;
6430 if (sc == SC_GroupBoxLabel) {
6431 if (checkable) {
6432 int newSum = indicatorWidth + 1;
6433 int newLeft = labelRect.left() + (rtl ? -newSum : newSum);
6434 labelRect.moveLeft(newLeft);
6435 if (flat)
6436 labelRect.moveTop(labelRect.top() + 3);
6437 else
6438 labelRect.moveTop(labelRect.top() + 4);
6439 } else if (flat) {
6440 int newLeft = labelRect.left() - (rtl ? 3 : -3);
6441 labelRect.moveLeft(newLeft);
6442 labelRect.moveTop(labelRect.top() + 3);
6443 } else {
6444 int newLeft = labelRect.left() - (rtl ? 3 : 2);
6445 labelRect.moveLeft(newLeft);
6446 labelRect.moveTop(labelRect.top() + 4);
6447 }
6448 ret = labelRect;
6449 }
6450
6451 if (sc == SC_GroupBoxCheckBox) {
6452 int left = rtl ? labelRect.right() - indicatorWidth : labelRect.left() - 1;
6453 int top = flat ? ret.top() + 1 : ret.top() + 5;
6454 ret.setRect(left, top,
6455 indicatorWidth, proxy()->pixelMetric(PM_IndicatorHeight, opt, widget));
6456 }
6457 break;
6458 }
6459 case SC_GroupBoxContents:
6460 case SC_GroupBoxFrame: {
6461 QFontMetrics fm = groupBox->fontMetrics;
6462 int yOffset = 3;
6463 if (!flat) {
6464 if (widget && !widget->testAttribute(Qt::WA_SetFont)
6465 && QApplication::desktopSettingsAware())
6466 fm = QFontMetrics(qt_app_fonts_hash()->value("QSmallFont", QFont()));
6467 yOffset = 5;
6468 }
6469
6470 if (hasNoText)
6471 yOffset = -qCeil(QFontMetricsF(fm).height());
6472 ret = opt->rect.adjusted(0, qCeil(QFontMetricsF(fm).height()) + yOffset, 0, 0);
6473 if (sc == SC_GroupBoxContents) {
6474 if (flat)
6475 ret.adjust(3, -5, -3, -4); // guess too
6476 else
6477 ret.adjust(3, 3, -3, -4); // guess
6478 }
6479 }
6480 break;
6481 default:
6482 ret = QCommonStyle::subControlRect(cc, groupBox, sc, widget);
6483 break;
6484 }
6485 }
6486 break;
6487#if QT_CONFIG(spinbox)
6488 case CC_SpinBox:
6489 if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
6490 QStyleHelper::WidgetSizePolicy aquaSize = d->effectiveAquaSizeConstrain(spin, widget);
6491 const auto fw = proxy()->pixelMetric(PM_SpinBoxFrameWidth, spin, widget);
6492 int spinner_w;
6493 int spinBoxSep;
6494 switch (aquaSize) {
6495 case QStyleHelper::SizeLarge:
6496 spinner_w = 14;
6497 spinBoxSep = 2;
6498 break;
6499 case QStyleHelper::SizeSmall:
6500 spinner_w = 12;
6501 spinBoxSep = 2;
6502 break;
6503 case QStyleHelper::SizeMini:
6504 spinner_w = 10;
6505 spinBoxSep = 1;
6506 break;
6507 default:
6508 Q_UNREACHABLE();
6509 }
6510
6511 switch (sc) {
6512 case SC_SpinBoxUp:
6513 case SC_SpinBoxDown: {
6514 if (spin->buttonSymbols == QAbstractSpinBox::NoButtons)
6515 break;
6516
6517 const int y = fw;
6518 const int x = spin->rect.width() - spinner_w;
6519 ret.setRect(x + spin->rect.x(), y + spin->rect.y(), spinner_w, spin->rect.height() - y * 2);
6520 int hackTranslateX;
6521 switch (aquaSize) {
6522 case QStyleHelper::SizeLarge:
6523 hackTranslateX = 0;
6524 break;
6525 case QStyleHelper::SizeSmall:
6526 hackTranslateX = -2;
6527 break;
6528 case QStyleHelper::SizeMini:
6529 hackTranslateX = -1;
6530 break;
6531 default:
6532 Q_UNREACHABLE();
6533 }
6534
6535 const auto cw = QMacStylePrivate::CocoaControl(QMacStylePrivate::Stepper, aquaSize);
6536 NSStepperCell *cell = static_cast<NSStepperCell *>(d->cocoaCell(cw));
6537 const CGRect outRect = [cell drawingRectForBounds:ret.toCGRect()];
6538 ret = QRectF::fromCGRect(outRect).toRect();
6539
6540 switch (sc) {
6541 case SC_SpinBoxUp:
6542 ret.setHeight(ret.height() / 2);
6543 break;
6544 case SC_SpinBoxDown:
6545 ret.setY(ret.y() + ret.height() / 2);
6546 break;
6547 default:
6548 Q_ASSERT(0);
6549 break;
6550 }
6551 ret.translate(hackTranslateX, 0); // hack: position the buttons correctly (weird that we need this)
6552 ret = visualRect(spin->direction, spin->rect, ret);
6553 break;
6554 }
6555 case SC_SpinBoxEditField:
6556 ret = spin->rect.adjusted(fw, fw, -fw, -fw);
6557 if (spin->buttonSymbols != QAbstractSpinBox::NoButtons) {
6558 ret.setWidth(spin->rect.width() - spinBoxSep - spinner_w);
6559 ret = visualRect(spin->direction, spin->rect, ret);
6560 }
6561 break;
6562 default:
6563 ret = QCommonStyle::subControlRect(cc, spin, sc, widget);
6564 break;
6565 }
6566 }
6567 break;
6568#endif
6569 case CC_ToolButton:
6570 ret = QCommonStyle::subControlRect(cc, opt, sc, widget);
6571 if (sc == SC_ToolButtonMenu) {
6572#if QT_CONFIG(accessibility)
6573 if (QStyleHelper::hasAncestor(opt->styleObject, QAccessible::ToolBar))
6574 ret.adjust(-toolButtonArrowMargin, 0, 0, 0);
6575#endif
6576 ret.adjust(-1, 0, 0, 0);
6577 }
6578 break;
6579 default:
6580 ret = QCommonStyle::subControlRect(cc, opt, sc, widget);
6581 break;
6582 }
6583 return ret;
6584}
6585
6586QSize QMacStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
6587 const QSize &csz, const QWidget *widget) const
6588{
6589 Q_D(const QMacStyle);
6590 QSize sz(csz);
6591 bool useAquaGuideline = true;
6592
6593 switch (ct) {
6594#if QT_CONFIG(spinbox)
6595 case CT_SpinBox:
6596 if (const QStyleOptionSpinBox *vopt = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
6597 const bool hasButtons = (vopt->buttonSymbols != QAbstractSpinBox::NoButtons);
6598 const int buttonWidth = hasButtons ? proxy()->subControlRect(CC_SpinBox, vopt, SC_SpinBoxUp, widget).width() : 0;
6599 sz += QSize(buttonWidth, 0);
6600 }
6601 break;
6602#endif
6603 case QStyle::CT_TabWidget:
6604 // the size between the pane and the "contentsRect" (+4,+4)
6605 // (the "contentsRect" is on the inside of the pane)
6606 sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
6607 /**
6608 This is supposed to show the relationship between the tabBar and
6609 the stack widget of a QTabWidget.
6610 Unfortunately ascii is not a good way of representing graphics.....
6611 PS: The '=' line is the painted frame.
6612
6613 top ---+
6614 |
6615 |
6616 |
6617 | vvv just outside the painted frame is the "pane"
6618 - -|- - - - - - - - - - <-+
6619 TAB BAR +=====^============ | +2 pixels
6620 - - -|- - -|- - - - - - - <-+
6621 | | ^ ^^^ just inside the painted frame is the "contentsRect"
6622 | | |
6623 | overlap |
6624 | | |
6625 bottom ------+ <-+ +14 pixels
6626 |
6627 v
6628 ------------------------------ <- top of stack widget
6629
6630
6631 To summarize:
6632 * 2 is the distance between the pane and the contentsRect
6633 * The 14 and the 1's are the distance from the contentsRect to the stack widget.
6634 (same value as used in SE_TabWidgetTabContents)
6635 * overlap is how much the pane should overlap the tab bar
6636 */
6637 // then add the size between the stackwidget and the "contentsRect"
6638#if QT_CONFIG(tabwidget)
6639 if (const QStyleOptionTabWidgetFrame *twf
6640 = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
6641 QSize extra(0,0);
6642 const int overlap = pixelMetric(PM_TabBarBaseOverlap, opt, widget);
6643 const int gapBetweenTabbarAndStackWidget = 2 + 14 - overlap;
6644
6645 const auto tabDirection = QMacStylePrivate::tabDirection(twf->shape);
6646 if (tabDirection == QMacStylePrivate::North
6647 || tabDirection == QMacStylePrivate::South) {
6648 extra = QSize(2, gapBetweenTabbarAndStackWidget + 1);
6649 } else {
6650 extra = QSize(gapBetweenTabbarAndStackWidget + 1, 2);
6651 }
6652 sz+= extra;
6653 }
6654#endif
6655 break;
6656#if QT_CONFIG(tabbar)
6657 case QStyle::CT_TabBarTab:
6658 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
6659 const bool differentFont = (widget && widget->testAttribute(Qt::WA_SetFont))
6660 || !QApplication::desktopSettingsAware();
6661 const auto tabDirection = QMacStylePrivate::tabDirection(tab->shape);
6662 const bool verticalTabs = tabDirection == QMacStylePrivate::East
6663 || tabDirection == QMacStylePrivate::West;
6664 if (verticalTabs)
6665 sz = sz.transposed();
6666
6667 int defaultTabHeight;
6668 const auto cs = d->effectiveAquaSizeConstrain(opt, widget);
6669 switch (cs) {
6670 case QStyleHelper::SizeLarge:
6671 if (tab->documentMode)
6672 defaultTabHeight = 24;
6673 else
6674 defaultTabHeight = 21;
6675
6676 if (qt_apple_runningWithLiquidGlass() && !tab->documentMode) {
6677 // We render tabs using NSButton and NSPopupButton. The control size
6678 // we use for tabs by default NSControlSizeRegular. With height 21
6679 // the button's bezel is partially clipped (by the clip rect with height 21),
6680 // which does not look good. Switching to NSControlSizeSmall has another
6681 // problem - different heights for NSButton vs. NSPopupButton, which is
6682 // quite visible (-2 pixels). 23 seems to work fine with the regular control
6683 // size. Document mode is not using native controls and thus stays unchanged.
6684 defaultTabHeight = 23;
6685 }
6686 break;
6687 case QStyleHelper::SizeSmall:
6688 defaultTabHeight = 18;
6689 break;
6690 case QStyleHelper::SizeMini:
6691 defaultTabHeight = 16;
6692 break;
6693 default:
6694 break;
6695 }
6696
6697 const bool widthSet = !differentFont && tab->icon.isNull();
6698 if (widthSet) {
6699 const auto textSize = opt->fontMetrics.size(Qt::TextShowMnemonic, tab->text);
6700 sz.rwidth() = textSize.width();
6701 sz.rheight() = qMax(defaultTabHeight, textSize.height());
6702 } else {
6703 sz.rheight() = qMax(defaultTabHeight, sz.height());
6704 }
6705 sz.rwidth() += proxy()->pixelMetric(PM_TabBarTabHSpace, tab, widget);
6706
6707 if (verticalTabs)
6708 sz = sz.transposed();
6709
6710 int maxWidgetHeight = qMax(tab->leftButtonSize.height(), tab->rightButtonSize.height());
6711 int maxWidgetWidth = qMax(tab->leftButtonSize.width(), tab->rightButtonSize.width());
6712
6713 int widgetWidth = 0;
6714 int widgetHeight = 0;
6715 int padding = 0;
6716 if (tab->leftButtonSize.isValid()) {
6717 padding += 8;
6718 widgetWidth += tab->leftButtonSize.width();
6719 widgetHeight += tab->leftButtonSize.height();
6720 }
6721 if (tab->rightButtonSize.isValid()) {
6722 padding += 8;
6723 widgetWidth += tab->rightButtonSize.width();
6724 widgetHeight += tab->rightButtonSize.height();
6725 }
6726
6727 if (verticalTabs) {
6728 sz.setWidth(qMax(sz.width(), maxWidgetWidth));
6729 sz.setHeight(sz.height() + widgetHeight + padding);
6730 } else {
6731 if (widthSet)
6732 sz.setWidth(sz.width() + widgetWidth + padding);
6733 sz.setHeight(qMax(sz.height(), maxWidgetHeight));
6734 }
6735 }
6736 break;
6737#endif
6738 case QStyle::CT_PushButton: {
6739 bool isFlat = false;
6740 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
6741 if (btn->features & QStyleOptionButton::CommandLinkButton)
6742 return QCommonStyle::sizeFromContents(ct, opt, sz, widget);
6743 isFlat = btn->features & QStyleOptionButton::Flat;
6744 }
6745
6746 // By default, we fit the contents inside a normal rounded push button.
6747 // Do this by add enough space around the contents so that rounded
6748 // borders (including highlighting when active) will show.
6749 QSize macsz;
6750 const auto controlSize = d->effectiveAquaSizeConstrain(opt, widget, CT_PushButton, sz, &macsz);
6751 // FIXME See comment in CT_PushButton case in qt_aqua_get_known_size().
6752 if (macsz.width() != -1)
6753 sz.setWidth(macsz.width());
6754 else
6755 sz.rwidth() += QMacStylePrivate::PushButtonLeftOffset + QMacStylePrivate::PushButtonRightOffset + 12;
6756 // All values as measured from HIThemeGetButtonBackgroundBounds()
6757 if (controlSize != QStyleHelper::SizeMini)
6758 sz.rwidth() += 12; // We like 12 over here.
6759
6760 if (controlSize == QStyleHelper::SizeLarge) {
6761 if (!isFlat)
6762 sz.rwidth() -= 12;
6763 if (sz.height() > 16)
6764 sz.rheight() += pushButtonDefaultHeight[QStyleHelper::SizeLarge] - 16;
6765 else
6766 sz.setHeight(pushButtonDefaultHeight[QStyleHelper::SizeLarge]);
6767 } else {
6768 if (!isFlat && !qt_apple_runningWithLiquidGlass())
6769 sz.rwidth() -= 10;
6770 if (controlSize == QStyleHelper::SizeMini)
6771 sz.setHeight(24);
6772 else
6773 sz.setHeight(pushButtonDefaultHeight[QStyleHelper::SizeSmall]);
6774 }
6775 if (isFlat)
6776 sz.rwidth() -= 13;
6777 break;
6778 }
6779 case QStyle::CT_MenuItem:
6780 if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
6781 int maxpmw = mi->maxIconWidth;
6782#if QT_CONFIG(combobox)
6783 const QComboBox *comboBox = qobject_cast<const QComboBox *>(widget);
6784#endif
6785 int w = sz.width(),
6786 h = sz.height();
6787 if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
6788 w = 10;
6790 } else {
6791 h = mi->fontMetrics.height() + 2;
6792 if (!mi->icon.isNull()) {
6793#if QT_CONFIG(combobox)
6794 if (comboBox) {
6795 const QSize &iconSize = comboBox->iconSize();
6796 h = qMax(h, iconSize.height() + 4);
6797 maxpmw = qMax(maxpmw, iconSize.width());
6798 } else
6799#endif
6800 {
6801 int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
6802 h = qMax(h, mi->icon.actualSize(QSize(iconExtent, iconExtent)).height() + 4);
6803 }
6804 }
6805 }
6806 if (mi->text.contains(QLatin1Char('\t')))
6807 w += 12;
6808 else if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
6809 w += 35; // Not quite exactly as it seems to depend on other factors
6810 if (maxpmw)
6811 w += maxpmw + 6;
6812 // add space for a check. All items have place for a check too.
6813 w += 20;
6814#if QT_CONFIG(combobox)
6815 if (comboBox && comboBox->isVisible()) {
6816 QStyleOptionComboBox cmb;
6817 cmb.initFrom(comboBox);
6818 cmb.editable = false;
6819 cmb.subControls = QStyle::SC_ComboBoxEditField;
6820 cmb.activeSubControls = QStyle::SC_None;
6821 w = qMax(w, subControlRect(QStyle::CC_ComboBox, &cmb,
6822 QStyle::SC_ComboBoxEditField,
6823 comboBox).width());
6824 } else
6825#endif
6826 {
6827 w += 12;
6828 }
6829 sz = QSize(w, h);
6830 }
6831 break;
6832 case CT_MenuBarItem:
6833 if (!sz.isEmpty())
6834 sz += QSize(12, 4); // Constants from QWindowsStyle
6835 break;
6836 case CT_ToolButton:
6837 sz.rwidth() += 10;
6838 sz.rheight() += 10;
6839 if (const auto *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt))
6840 if (tb->features & QStyleOptionToolButton::Menu)
6841 sz.rwidth() += toolButtonArrowMargin;
6842 return sz;
6843 case CT_ComboBox:
6844 if (const auto *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
6845 const auto controlSize = d->effectiveAquaSizeConstrain(opt, widget);
6846 if (!cb->editable) {
6847 // See CT_PushButton; we have to fit the focus
6848 // ring and a non-editable combo box is a NSPopUpButton.
6849 sz.rwidth() += QMacStylePrivate::PushButtonLeftOffset + QMacStylePrivate::PushButtonRightOffset + 24;
6850 // All values as measured from HIThemeGetButtonBackgroundBounds()
6851 if (controlSize != QStyleHelper::SizeMini)
6852 sz.rwidth() += 12; // We like 12 over here.
6853#if 0
6854 // TODO Maybe support square combo boxes
6855 if (controlSize == QStyleHelper::SizeLarge && sz.height() > 16)
6856 sz.rheight() += popupButtonDefaultHeight[QStyleHelper::SizeLarge] - 16;
6857 else
6858#endif
6859 } else {
6860 sz.rwidth() += 50; // FIXME Double check this
6861 }
6862
6863 // This should be enough to fit the focus ring
6864 if (controlSize == QStyleHelper::SizeMini)
6865 sz.setHeight(24); // FIXME Our previous HITheme-based logic returned this for CT_PushButton.
6866 else
6867 sz.setHeight(pushButtonDefaultHeight[controlSize]);
6868
6869 return sz;
6870 }
6871 break;
6872 case CT_Menu: {
6873 if (proxy() == this) {
6874 sz = csz;
6875 } else {
6876 QStyleHintReturnMask menuMask;
6877 QStyleOption myOption = *opt;
6878 myOption.rect.setSize(sz);
6879 if (proxy()->styleHint(SH_Menu_Mask, &myOption, widget, &menuMask))
6880 sz = menuMask.region.boundingRect().size();
6881 }
6882 break; }
6883 case CT_HeaderSection:{
6884 const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt);
6885 sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
6886 if (header->text.contains(QLatin1Char('\n')))
6887 useAquaGuideline = false;
6888 break; }
6889 case CT_ScrollBar :
6890 // Make sure that the scroll bar is large enough to display the thumb indicator.
6891 if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6892 const int minimumSize = 24; // Smallest knob size, but Cocoa doesn't seem to care
6893 if (slider->orientation == Qt::Horizontal)
6894 sz = sz.expandedTo(QSize(minimumSize, sz.height()));
6895 else
6896 sz = sz.expandedTo(QSize(sz.width(), minimumSize));
6897 }
6898 break;
6899#if QT_CONFIG(itemviews)
6900 case CT_ItemViewItem:
6901 if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
6902 sz = QCommonStyle::sizeFromContents(ct, vopt, csz, widget);
6903 sz.setHeight(sz.height() + 2);
6904 }
6905 break;
6906#endif
6907
6908 default:
6909 sz = QCommonStyle::sizeFromContents(ct, opt, csz, widget);
6910 }
6911
6912 if (useAquaGuideline && ct != CT_PushButton) {
6913 // TODO Probably going away at some point
6914 QSize macsz;
6915 if (d->aquaSizeConstrain(opt, widget, ct, sz, &macsz) != QStyleHelper::SizeDefault) {
6916 if (macsz.width() != -1)
6917 sz.setWidth(macsz.width());
6918 if (macsz.height() != -1)
6919 sz.setHeight(macsz.height());
6920 }
6921 }
6922
6923 // The sizes that Carbon and the guidelines gives us excludes the focus frame.
6924 // We compensate for this by adding some extra space here to make room for the frame when drawing:
6925 if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)){
6926 if (combo->editable) {
6927 const auto widgetSize = d->aquaSizeConstrain(opt, widget);
6928 QMacStylePrivate::CocoaControl cw;
6929 cw.type = combo->editable ? QMacStylePrivate::ComboBox : QMacStylePrivate::Button_PopupButton;
6930 cw.size = widgetSize;
6931 const CGRect diffRect = QMacStylePrivate::comboboxInnerBounds(CGRectZero, cw);
6932 sz.rwidth() -= qRound(diffRect.size.width);
6933 sz.rheight() -= qRound(diffRect.size.height);
6934 }
6935 }
6936 return sz;
6937}
6938
6939void QMacStyle::drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal,
6940 bool enabled, const QString &text, QPalette::ColorRole textRole) const
6941{
6942 if (flags & Qt::TextShowMnemonic)
6943 flags |= Qt::TextHideMnemonic;
6944 QCommonStyle::drawItemText(p, r, flags, pal, enabled, text, textRole);
6945}
6946
6947bool QMacStyle::event(QEvent *e)
6948{
6949 Q_D(QMacStyle);
6950 if (e->type() == QEvent::FocusIn) {
6951 QWidget *f = nullptr;
6952 QWidget *focusWidget = QApplication::focusWidget();
6953#if QT_CONFIG(graphicsview)
6954 if (QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(focusWidget)) {
6955 QGraphicsItem *focusItem = graphicsView->scene() ? graphicsView->scene()->focusItem() : 0;
6956 if (focusItem && focusItem->type() == QGraphicsProxyWidget::Type) {
6957 QGraphicsProxyWidget *proxy = static_cast<QGraphicsProxyWidget *>(focusItem);
6958 if (proxy->widget())
6959 focusWidget = proxy->widget()->focusWidget();
6960 }
6961 }
6962#endif
6963
6964 if (focusWidget && focusWidget->testAttribute(Qt::WA_MacShowFocusRect)) {
6965#if QT_CONFIG(spinbox)
6966 if (const auto sb = qobject_cast<QAbstractSpinBox *>(focusWidget))
6967 f = sb->property("_q_spinbox_lineedit").value<QWidget *>();
6968 else
6969#endif
6970 f = focusWidget;
6971 }
6972 if (f) {
6973 if (!d->focusWidget)
6974 d->focusWidget = new QFocusFrame(f);
6975 d->focusWidget->setWidget(f);
6976 } else if (d->focusWidget) {
6977 d->focusWidget->setWidget(0);
6978 }
6979 } else if (e->type() == QEvent::FocusOut) {
6980 if (d->focusWidget)
6981 d->focusWidget->setWidget(0);
6982 }
6983 return false;
6984}
6985
6986int QMacStyle::layoutSpacing(QSizePolicy::ControlType control1,
6987 QSizePolicy::ControlType control2,
6988 Qt::Orientation orientation,
6989 const QStyleOption *option,
6990 const QWidget *widget) const
6991{
6992 const int ButtonMask = QSizePolicy::ButtonBox | QSizePolicy::PushButton;
6993 const int controlSize = getControlSize(option, widget);
6994
6995 if (control2 == QSizePolicy::ButtonBox) {
6996 /*
6997 AHIG seems to prefer a 12-pixel margin between group
6998 boxes and the row of buttons. The 20 pixel comes from
6999 Builder.
7000 */
7001 if (control1 & (QSizePolicy::Frame // guess
7002 | QSizePolicy::GroupBox // (AHIG, guess, guess)
7003 | QSizePolicy::TabWidget // guess
7004 | ButtonMask)) { // AHIG
7005 return_SIZE(14, 8, 8);
7006 } else if (control1 == QSizePolicy::LineEdit) {
7007 return_SIZE(8, 8, 8); // Interface Builder
7008 } else {
7009 return_SIZE(20, 7, 7); // Interface Builder
7010 }
7011 }
7012
7013 if ((control1 | control2) & ButtonMask) {
7014 if (control1 == QSizePolicy::LineEdit)
7015 return_SIZE(8, 8, 8); // Interface Builder
7016 else if (control2 == QSizePolicy::LineEdit) {
7017 if (orientation == Qt::Vertical)
7018 return_SIZE(20, 7, 7); // Interface Builder
7019 else
7020 return_SIZE(20, 8, 8);
7021 }
7022 return_SIZE(14, 8, 8); // Interface Builder
7023 }
7024
7025 switch (CT2(control1, control2)) {
7026 case CT1(QSizePolicy::Label): // guess
7027 case CT2(QSizePolicy::Label, QSizePolicy::DefaultType): // guess
7028 case CT2(QSizePolicy::Label, QSizePolicy::CheckBox): // AHIG
7029 case CT2(QSizePolicy::Label, QSizePolicy::ComboBox): // AHIG
7030 case CT2(QSizePolicy::Label, QSizePolicy::LineEdit): // guess
7031 case CT2(QSizePolicy::Label, QSizePolicy::RadioButton): // AHIG
7032 case CT2(QSizePolicy::Label, QSizePolicy::Slider): // guess
7033 case CT2(QSizePolicy::Label, QSizePolicy::SpinBox): // guess
7034 case CT2(QSizePolicy::Label, QSizePolicy::ToolButton): // guess
7035 return_SIZE(8, 6, 5);
7036 case CT1(QSizePolicy::ToolButton):
7037 return 8; // AHIG
7038 case CT1(QSizePolicy::CheckBox):
7039 case CT2(QSizePolicy::CheckBox, QSizePolicy::RadioButton):
7040 case CT2(QSizePolicy::RadioButton, QSizePolicy::CheckBox):
7041 if (orientation == Qt::Vertical)
7042 return_SIZE(8, 8, 7); // AHIG and Builder
7043 break;
7044 case CT1(QSizePolicy::RadioButton):
7045 if (orientation == Qt::Vertical)
7046 return 5; // (Builder, guess, AHIG)
7047 }
7048
7049 if (orientation == Qt::Horizontal
7050 && (control2 & (QSizePolicy::CheckBox | QSizePolicy::RadioButton)))
7051 return_SIZE(12, 10, 8); // guess
7052
7053 if ((control1 | control2) & (QSizePolicy::Frame
7054 | QSizePolicy::GroupBox
7055 | QSizePolicy::TabWidget)) {
7056 /*
7057 These values were chosen so that nested container widgets
7058 look good side by side. Builder uses 8, which looks way
7059 too small, and AHIG doesn't say anything.
7060 */
7061 return_SIZE(16, 10, 10); // guess
7062 }
7063
7064 if ((control1 | control2) & (QSizePolicy::Line | QSizePolicy::Slider))
7065 return_SIZE(12, 10, 8); // AHIG
7066
7067 if ((control1 | control2) & QSizePolicy::LineEdit)
7068 return_SIZE(10, 8, 8); // AHIG
7069
7070 /*
7071 AHIG and Builder differ by up to 4 pixels for stacked editable
7072 comboboxes. We use some values that work fairly well in all
7073 cases.
7074 */
7075 if ((control1 | control2) & QSizePolicy::ComboBox)
7076 return_SIZE(10, 8, 7); // guess
7077
7078 /*
7079 Builder defaults to 8, 6, 5 in lots of cases, but most of the time the
7080 result looks too cramped.
7081 */
7082 return_SIZE(10, 8, 6); // guess
7083}
7084
7085QT_END_NAMESPACE
virtual void drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole=QPalette::NoRole) const
Draws the given text in the specified rectangle using the provided painter and palette.
int pixelMetric(PixelMetric pm, const QStyleOption *opt=0, const QWidget *widget=nullptr) const
\reimp
QSize sizeFromContents(ContentsType ct, const QStyleOption *opt, const QSize &contentsSize, const QWidget *w=nullptr) const
\reimp
void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p, const QWidget *w=nullptr) const
\reimp
virtual int styleHint(StyleHint sh, const QStyleOption *opt=0, const QWidget *w=nullptr, QStyleHintReturn *shret=nullptr) const
\reimp
QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const
QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget=nullptr) const
\reimp
QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc, const QWidget *w=nullptr) const
\reimp
SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, const QPoint &pt, const QWidget *w=nullptr) const
\reimp
void polish(QWidget *w)
\reimp
int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2, Qt::Orientation orientation, const QStyleOption *option=nullptr, const QWidget *widget=nullptr) const
\reimp
void unpolish(QWidget *w)
\reimp
QPalette standardPalette() const
Returns the style's standard palette.
void polish(QPalette &pal)
\reimp
bool event(QEvent *e)
This virtual function receives events to an object and should return true if the event e was recogniz...
QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const
\reimp
static QMacStyle * create()
virtual ~QMacStyle()
void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *w=nullptr) const
\reimp
QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *opt, const QWidget *widget=nullptr) const
\reimp
void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *w=nullptr) const
\reimp
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
const int macRightBorder
static QStyleHelper::WidgetSizePolicy getControlSize(const QStyleOption *option, const QWidget *widget)
#define QMAC_QAQUASTYLE_SIZE_CONSTRAIN
const int macItemFrame
static const int qt_mac_aqua_metrics[]
static QStyleHelper::WidgetSizePolicy qt_aqua_guess_size(const QWidget *widg, QSize large, QSize small, QSize mini)
static QSize qt_aqua_get_known_size(QStyle::ContentsType ct, const QStyleOption *opt, const QWidget *widg, QSize szHint, QStyleHelper::WidgetSizePolicy sz)
static NSUserInterfaceLayoutDirection qt_macLayoutDirectionFromQt(Qt::LayoutDirection direction)
void adjustPushButtonShadowMargins(QRectF &rect, QStyleHelper::WidgetSizePolicy size)
static bool setupSlider(NSSlider *slider, const QStyleOptionSlider *sl)
void drawTickMarks(CGContextRef ctx, NSSlider *nsSlider, const QStyleOptionSlider *sliderOpt)
static const int toolButtonArrowMargin
static CGRect qt_alignmentRectForFrame(CGRect rect, QStyleHelper::WidgetSizePolicy size, QMacStylePrivate::CocoaControlType ct)
static const QMarginsF comboBoxFocusRingMargins[3]
const int pushButtonBevelRectOffsets[3]
static void drawTextFieldCustomBackground(QPainter *p, const QRect &rect, const QColor &color)
static bool setupScroller(NSScroller *scroller, const QStyleOptionSlider *sb)
static bool isInMacUnifiedToolbarArea(QWidget *widget, int windowY)
static bool hasCustomTextFieldBackground(const QPalette &palette)
static QPixmap darkenPixmap(const QPixmap &pixmap)
static const QColor titlebarSeparatorLineActive(111, 111, 111)
void drawSliderKnob(CGContextRef ctx, NSSlider *slider)
size_t qHash(const QMacStylePrivate::CocoaControl &cw, size_t seed=0)
static const qreal textFieldBezelBorderWidth
static const QMarginsF pushButtonShadowMargins[3]
static const int headerSectionArrowHeight
static const qreal titleBarIconTitleSpacing
static const QMarginsF pullDownButtonShadowMargins[3]
QAquaMetric
@ SmallRadioButtonWidth
@ MiniVSliderWidth
@ SmallHSliderHeight
@ VSliderWidth
@ MiniCheckBoxWidth
@ EditTextFrameOutset
@ RadioButtonHeight
@ SmallProgressBarShadowOutset
@ SmallVSliderWidth
@ SeparatorSize
@ SmallRadioButtonHeight
@ MiniRadioButtonWidth
@ MiniHSliderTickHeight
@ CheckBoxWidth
@ MiniHSliderHeight
@ HSliderHeight
@ PushButtonHeight
@ FocusRectOutset
@ SmallCheckBoxHeight
@ MiniVSliderTickWidth
@ MiniPushButtonHeight
@ VSliderTickWidth
@ LargeProgressBarThickness
@ SmallHSliderTickHeight
@ MiniRadioButtonHeight
@ SmallCheckBoxWidth
@ SmallVSliderTickWidth
@ MenuSeparatorHeight
@ PopupButtonHeight
@ ListHeaderHeight
@ MiniCheckBoxHeight
@ RadioButtonWidth
@ CheckBoxHeight
@ MiniPopupButtonHeight
@ HSliderTickHeight
@ ProgressBarShadowOutset
@ SmallPopupButtonHeight
@ NormalProgressBarThickness
@ SmallPushButtonHeight
static const qreal titleBarButtonSpacing
QMacStylePrivate::CocoaControlType cocoaControlType(const QStyleOption *opt, const QWidget *w)
static const qreal popupButtonDefaultHeight[3]
const int macItemHMargin
static const int headerSectionSeparatorInset
static const qreal titleBarTitleRightMargin
static const qreal textFieldBezelCornerRadius
static const int DisclosureOffset
static QString qt_mac_removeMnemonics(const QString &original)
static void setLayoutItemMargins(int left, int top, int right, int bottom, QRect *rect, Qt::LayoutDirection dir)
static bool isDarkMode()
static int qt_mac_aqua_get_metric(QAquaMetric m)
static const qreal comboBoxDefaultHeight[3]
static const qreal pushButtonDefaultHeight[3]
static const qreal focusRingWidth
static const QColor darkModeSeparatorLine(88, 88, 88)
static const QColor titlebarSeparatorLineInactive(131, 131, 131)
static const int toolButtonArrowSize
static bool qt_macWindowMainWindow(const QWidget *window)
#define CT1(c)
#define return_SIZE(large, small, mini)
#define CT2(c1, c2)
#define SIZE(large, small, mini)
#define M_PI_2
Definition qmath.h:205
#define M_PI
Definition qmath.h:201