This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 305
/
nsNativeThemeCocoa.mm
2873 lines (2455 loc) · 97 KB
/
nsNativeThemeCocoa.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Mike Pinkerton (pinkerton@netscape.com).
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Vladimir Vukicevic <vladimir@pobox.com> (HITheme rewrite)
* Josh Aas <josh@mozilla.com>
* Colin Barrett <cbarrett@mozilla.com>
* Matthew Gregan <kinetik@flim.org>
* Markus Stange <mstange@themasta.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsNativeThemeCocoa.h"
#include "nsObjCExceptions.h"
#include "nsRenderingContext.h"
#include "nsRect.h"
#include "nsSize.h"
#include "nsThemeConstants.h"
#include "nsIPresShell.h"
#include "nsPresContext.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIFrame.h"
#include "nsIAtom.h"
#include "nsEventStates.h"
#include "nsINameSpaceManager.h"
#include "nsPresContext.h"
#include "nsGkAtoms.h"
#include "nsToolkit.h"
#include "nsCocoaWindow.h"
#include "nsNativeThemeColors.h"
#include "nsIScrollableFrame.h"
#include "nsIDOMHTMLProgressElement.h"
#include "gfxContext.h"
#include "gfxQuartzSurface.h"
#include "gfxQuartzNativeDrawing.h"
#define DRAW_IN_FRAME_DEBUG 0
#define SCROLLBARS_VISUAL_DEBUG 0
// private Quartz routines needed here
extern "C" {
CG_EXTERN void CGContextSetCTM(CGContextRef, CGAffineTransform);
}
// Workaround for NSCell control tint drawing
// Without this workaround, NSCells are always drawn with the clear control tint
// as long as they're not attached to an NSControl which is a subview of an active window.
// XXXmstange Why doesn't Webkit need this?
@implementation NSCell (ControlTintWorkaround)
- (int)_realControlTint { return [self controlTint]; }
@end
// The purpose of this class is to provide objects that can be used when drawing
// NSCells using drawWithFrame:inView: without causing any harm. The only
// messages that will be sent to such an object are "isFlipped" and
// "currentEditor": isFlipped needs to return YES in order to avoid drawing bugs
// on 10.4 (see bug 465069); currentEditor (which isn't even a method of
// NSView) will be called when drawing search fields, and we only provide it in
// order to prevent "unrecognized selector" exceptions.
// There's no need to pass the actual NSView that we're drawing into to
// drawWithFrame:inView:. What's more, doing so even causes unnecessary
// invalidations as soon as we draw a focusring!
@interface CellDrawView : NSView
@end;
@implementation CellDrawView
- (BOOL)isFlipped
{
return YES;
}
- (NSText*)currentEditor
{
return nil;
}
@end
/**
* NSProgressBarCell is used to draw progress bars of any size.
*/
@interface NSProgressBarCell : NSCell
{
/*All instance variables are private*/
double mValue;
double mMax;
bool mIsIndeterminate;
bool mIsHorizontal;
}
- (void)setValue:(double)value;
- (double)value;
- (void)setMax:(double)max;
- (double)max;
- (void)setIndeterminate:(bool)aIndeterminate;
- (bool)isIndeterminate;
- (void)setHorizontal:(bool)aIsHorizontal;
- (bool)isHorizontal;
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView;
@end
@implementation NSProgressBarCell
- (void)setMax:(double)aMax
{
mMax = aMax;
}
- (double)max
{
return mMax;
}
- (void)setValue:(double)aValue
{
mValue = aValue;
}
- (double)value
{
return mValue;
}
- (void)setIndeterminate:(bool)aIndeterminate
{
mIsIndeterminate = aIndeterminate;
}
- (bool)isIndeterminate
{
return mIsIndeterminate;
}
- (void)setHorizontal:(bool)aIsHorizontal
{
mIsHorizontal = aIsHorizontal;
}
- (bool)isHorizontal
{
return mIsHorizontal;
}
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
CGContext* cgContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
HIThemeTrackDrawInfo tdi;
tdi.version = 0;
tdi.min = 0;
tdi.value = PR_INT32_MAX * (mValue / mMax);
tdi.max = PR_INT32_MAX;
tdi.bounds = NSRectToCGRect(cellFrame);
tdi.attributes = mIsHorizontal ? kThemeTrackHorizontal : 0;
tdi.enableState = [self controlTint] == NSClearControlTint ? kThemeTrackInactive
: kThemeTrackActive;
NSControlSize size = [self controlSize];
if (size == NSRegularControlSize) {
tdi.kind = mIsIndeterminate ? kThemeLargeIndeterminateBar
: kThemeLargeProgressBar;
} else {
NS_ASSERTION(size == NSSmallControlSize,
"We shouldn't have another size than small and regular for the moment");
tdi.kind = mIsIndeterminate ? kThemeMediumIndeterminateBar
: kThemeMediumProgressBar;
}
PRInt32 stepsPerSecond = mIsIndeterminate ? 60 : 30;
PRInt32 milliSecondsPerStep = 1000 / stepsPerSecond;
tdi.trackInfo.progress.phase = PR_IntervalToMilliseconds(PR_IntervalNow()) /
milliSecondsPerStep % 32;
HIThemeDrawTrack(&tdi, NULL, cgContext, kHIThemeOrientationNormal);
}
@end
@interface ContextAwareSearchFieldCell : NSSearchFieldCell
{
nsIFrame* mContext;
}
// setContext: stores the searchfield nsIFrame so that it can be consulted
// during painting. Please reset this by calling setContext:nsnull as soon as
// you're done with painting because we don't want to keep a dangling pointer.
- (void)setContext:(nsIFrame*)aContext;
@end
@implementation ContextAwareSearchFieldCell
- (id)initTextCell:(NSString*)aString
{
if ((self = [super initTextCell:aString])) {
mContext = nsnull;
}
return self;
}
- (void)setContext:(nsIFrame*)aContext
{
mContext = aContext;
}
static BOOL IsToolbarStyleContainer(nsIFrame* aFrame)
{
nsIContent* content = aFrame->GetContent();
if (!content)
return NO;
if (content->Tag() == nsGkAtoms::toolbar ||
content->Tag() == nsGkAtoms::toolbox ||
content->Tag() == nsGkAtoms::statusbar)
return YES;
switch (aFrame->GetStyleDisplay()->mAppearance) {
case NS_THEME_TOOLBAR:
case NS_THEME_MOZ_MAC_UNIFIED_TOOLBAR:
case NS_THEME_STATUSBAR:
return YES;
default:
return NO;
}
}
- (BOOL)_isToolbarMode
{
// On 10.7, searchfields have two different styles, depending on whether
// the searchfield is on top of of window chrome. This function is called on
// 10.7 during drawing in order to determine which style to use.
for (nsIFrame* frame = mContext; frame; frame = frame->GetParent()) {
if (IsToolbarStyleContainer(frame)) {
return YES;
}
}
return NO;
}
@end
// Workaround for Bug 542048
// On 64-bit, NSSearchFieldCells don't draw focus rings.
#if defined(__x86_64__)
static void DrawFocusRing(NSRect rect, float radius)
{
NSSetFocusRingStyle(NSFocusRingOnly);
NSBezierPath* path = [NSBezierPath bezierPath];
rect = NSInsetRect(rect, radius, radius);
[path appendBezierPathWithArcWithCenter:NSMakePoint(NSMinX(rect), NSMinY(rect)) radius:radius startAngle:180.0 endAngle:270.0];
[path appendBezierPathWithArcWithCenter:NSMakePoint(NSMaxX(rect), NSMinY(rect)) radius:radius startAngle:270.0 endAngle:360.0];
[path appendBezierPathWithArcWithCenter:NSMakePoint(NSMaxX(rect), NSMaxY(rect)) radius:radius startAngle: 0.0 endAngle: 90.0];
[path appendBezierPathWithArcWithCenter:NSMakePoint(NSMinX(rect), NSMaxY(rect)) radius:radius startAngle: 90.0 endAngle:180.0];
[path closePath];
[path fill];
}
@interface SearchFieldCellWithFocusRing : ContextAwareSearchFieldCell {} @end
@implementation SearchFieldCellWithFocusRing
- (void)drawWithFrame:(NSRect)rect inView:(NSView*)controlView
{
[super drawWithFrame:rect inView:controlView];
if ([self showsFirstResponder]) {
DrawFocusRing(rect, NSHeight(rect) / 2);
}
}
@end
#endif
// Copied from nsLookAndFeel.h
// Apple hasn't defined a constant for scollbars with two arrows on each end, so we'll use this one.
static const int kThemeScrollBarArrowsBoth = 2;
#define HITHEME_ORIENTATION kHIThemeOrientationNormal
#define MAX_FOCUS_RING_WIDTH 4
// These enums are for indexing into the margin array.
enum {
leopardOS = 0
};
enum {
miniControlSize,
smallControlSize,
regularControlSize
};
enum {
leftMargin,
topMargin,
rightMargin,
bottomMargin
};
static int EnumSizeForCocoaSize(NSControlSize cocoaControlSize) {
if (cocoaControlSize == NSMiniControlSize)
return miniControlSize;
else if (cocoaControlSize == NSSmallControlSize)
return smallControlSize;
else
return regularControlSize;
}
static NSControlSize CocoaSizeForEnum(PRInt32 enumControlSize) {
if (enumControlSize == miniControlSize)
return NSMiniControlSize;
else if (enumControlSize == smallControlSize)
return NSSmallControlSize;
else
return NSRegularControlSize;
}
static NSString* CUIControlSizeForCocoaSize(NSControlSize aControlSize)
{
if (aControlSize == NSRegularControlSize)
return @"regular";
else if (aControlSize == NSSmallControlSize)
return @"small";
else
return @"mini";
}
static void InflateControlRect(NSRect* rect, NSControlSize cocoaControlSize, const float marginSet[][3][4])
{
if (!marginSet)
return;
static int osIndex = leopardOS;
int controlSize = EnumSizeForCocoaSize(cocoaControlSize);
const float* buttonMargins = marginSet[osIndex][controlSize];
rect->origin.x -= buttonMargins[leftMargin];
rect->origin.y -= buttonMargins[bottomMargin];
rect->size.width += buttonMargins[leftMargin] + buttonMargins[rightMargin];
rect->size.height += buttonMargins[bottomMargin] + buttonMargins[topMargin];
}
static NSWindow* NativeWindowForFrame(nsIFrame* aFrame,
nsIWidget** aTopLevelWidget = NULL)
{
if (!aFrame)
return nil;
nsIWidget* widget = aFrame->GetNearestWidget();
if (!widget)
return nil;
nsIWidget* topLevelWidget = widget->GetTopLevelWidget();
if (aTopLevelWidget)
*aTopLevelWidget = topLevelWidget;
return (NSWindow*)topLevelWidget->GetNativeData(NS_NATIVE_WINDOW);
}
static BOOL FrameIsInActiveWindow(nsIFrame* aFrame)
{
nsIWidget* topLevelWidget = NULL;
NSWindow* win = NativeWindowForFrame(aFrame, &topLevelWidget);
if (!topLevelWidget || !win)
return YES;
// XUL popups, e.g. the toolbar customization popup, can't become key windows,
// but controls in these windows should still get the active look.
nsWindowType windowType;
topLevelWidget->GetWindowType(windowType);
if (windowType == eWindowType_popup)
return YES;
if ([win isSheet])
return [win isKeyWindow];
return [win isMainWindow] && ![win attachedSheet];
}
// Toolbar controls and content controls respond to different window
// activeness states.
static BOOL IsActive(nsIFrame* aFrame, BOOL aIsToolbarControl)
{
if (aIsToolbarControl)
return [NativeWindowForFrame(aFrame) isMainWindow] || ![NSView focusView];
return FrameIsInActiveWindow(aFrame);
}
NS_IMPL_ISUPPORTS_INHERITED1(nsNativeThemeCocoa, nsNativeTheme, nsITheme)
nsNativeThemeCocoa::nsNativeThemeCocoa()
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
// provide a local autorelease pool, as this is called during startup
// before the main event-loop pool is in place
nsAutoreleasePool pool;
mPushButtonCell = [[NSButtonCell alloc] initTextCell:nil];
[mPushButtonCell setButtonType:NSMomentaryPushInButton];
[mPushButtonCell setHighlightsBy:NSPushInCellMask];
mRadioButtonCell = [[NSButtonCell alloc] initTextCell:nil];
[mRadioButtonCell setButtonType:NSRadioButton];
mCheckboxCell = [[NSButtonCell alloc] initTextCell:nil];
[mCheckboxCell setButtonType:NSSwitchButton];
[mCheckboxCell setAllowsMixedState:YES];
#if defined(__x86_64__)
mSearchFieldCell = [[SearchFieldCellWithFocusRing alloc] initTextCell:@""];
#else
mSearchFieldCell = [[ContextAwareSearchFieldCell alloc] initTextCell:@""];
#endif
[mSearchFieldCell setBezelStyle:NSTextFieldRoundedBezel];
[mSearchFieldCell setBezeled:YES];
[mSearchFieldCell setEditable:YES];
[mSearchFieldCell setFocusRingType:NSFocusRingTypeExterior];
mDropdownCell = [[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO];
mComboBoxCell = [[NSComboBoxCell alloc] initTextCell:@""];
[mComboBoxCell setBezeled:YES];
[mComboBoxCell setEditable:YES];
[mComboBoxCell setFocusRingType:NSFocusRingTypeExterior];
mProgressBarCell = [[NSProgressBarCell alloc] init];
mCellDrawView = [[CellDrawView alloc] init];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
nsNativeThemeCocoa::~nsNativeThemeCocoa()
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
[mProgressBarCell release];
[mPushButtonCell release];
[mRadioButtonCell release];
[mCheckboxCell release];
[mSearchFieldCell release];
[mDropdownCell release];
[mComboBoxCell release];
[mCellDrawView release];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
// Limit on the area of the target rect (in pixels^2) in
// DrawCellWithScaling(), DrawButton() and DrawScrollbar(), above which we
// don't draw the object into a bitmap buffer. This is to avoid crashes in
// [NSGraphicsContext graphicsContextWithGraphicsPort:flipped:] and
// CGContextDrawImage(), and also to avoid very poor drawing performance in
// CGContextDrawImage() when it scales the bitmap (particularly if xscale or
// yscale is less than but near 1 -- e.g. 0.9). This value was determined
// by trial and error, on OS X 10.4.11 and 10.5.4, and on systems with
// different amounts of RAM.
#define BITMAP_MAX_AREA 500000
/*
* Draw the given NSCell into the given cgContext.
*
* destRect - the size and position of the resulting control rectangle
* controlSize - the NSControlSize which will be given to the NSCell before
* asking it to render
* naturalSize - The natural dimensions of this control.
* If the control rect size is not equal to either of these, a scale
* will be applied to the context so that rendering the control at the
* natural size will result in it filling the destRect space.
* If a control has no natural dimensions in either/both axes, pass 0.0f.
* minimumSize - The minimum dimensions of this control.
* If the control rect size is less than the minimum for a given axis,
* a scale will be applied to the context so that the minimum is used
* for drawing. If a control has no minimum dimensions in either/both
* axes, pass 0.0f.
* marginSet - an array of margins; a multidimensional array of [2][3][4],
* with the first dimension being the OS version (Tiger or Leopard),
* the second being the control size (mini, small, regular), and the third
* being the 4 margin values (left, top, right, bottom).
* view - The NSView that we're drawing into. As far as I can tell, it doesn't
* matter if this is really the right view; it just has to return YES when
* asked for isFlipped. Otherwise we'll get drawing bugs on 10.4.
* mirrorHorizontal - whether to mirror the cell horizontally
*/
static void DrawCellWithScaling(NSCell *cell,
CGContextRef cgContext,
const HIRect& destRect,
NSControlSize controlSize,
NSSize naturalSize,
NSSize minimumSize,
const float marginSet[][3][4],
NSView* view,
BOOL mirrorHorizontal)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
NSRect drawRect = NSMakeRect(destRect.origin.x, destRect.origin.y, destRect.size.width, destRect.size.height);
if (naturalSize.width != 0.0f)
drawRect.size.width = naturalSize.width;
if (naturalSize.height != 0.0f)
drawRect.size.height = naturalSize.height;
// Keep aspect ratio when scaling if one dimension is free.
if (naturalSize.width == 0.0f && naturalSize.height != 0.0f)
drawRect.size.width = destRect.size.width * naturalSize.height / destRect.size.height;
if (naturalSize.height == 0.0f && naturalSize.width != 0.0f)
drawRect.size.height = destRect.size.height * naturalSize.width / destRect.size.width;
// Honor minimum sizes.
if (drawRect.size.width < minimumSize.width)
drawRect.size.width = minimumSize.width;
if (drawRect.size.height < minimumSize.height)
drawRect.size.height = minimumSize.height;
[NSGraphicsContext saveGraphicsState];
// Only skip the buffer if the area of our cell (in pixels^2) is too large.
if (drawRect.size.width * drawRect.size.height > BITMAP_MAX_AREA) {
// Inflate the rect Gecko gave us by the margin for the control.
InflateControlRect(&drawRect, controlSize, marginSet);
NSGraphicsContext* savedContext = [NSGraphicsContext currentContext];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:cgContext flipped:YES]];
[cell drawWithFrame:drawRect inView:view];
[NSGraphicsContext setCurrentContext:savedContext];
}
else {
float w = ceil(drawRect.size.width);
float h = ceil(drawRect.size.height);
NSRect tmpRect = NSMakeRect(MAX_FOCUS_RING_WIDTH, MAX_FOCUS_RING_WIDTH, w, h);
// inflate to figure out the frame we need to tell NSCell to draw in, to get something that's 0,0,w,h
InflateControlRect(&tmpRect, controlSize, marginSet);
// and then, expand by MAX_FOCUS_RING_WIDTH size to make sure we can capture any focus ring
w += MAX_FOCUS_RING_WIDTH * 2.0;
h += MAX_FOCUS_RING_WIDTH * 2.0;
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(NULL,
(int) w, (int) h,
8, (int) w * 4,
rgb, kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(rgb);
// We need to flip the image twice in order to avoid drawing bugs on 10.4, see bug 465069.
// This is the first flip transform, applied to cgContext.
CGContextScaleCTM(cgContext, 1.0f, -1.0f);
CGContextTranslateCTM(cgContext, 0.0f, -(2.0 * destRect.origin.y + destRect.size.height));
if (mirrorHorizontal) {
CGContextScaleCTM(cgContext, -1.0f, 1.0f);
CGContextTranslateCTM(cgContext, -(2.0 * destRect.origin.x + destRect.size.width), 0.0f);
}
NSGraphicsContext* savedContext = [NSGraphicsContext currentContext];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES]];
// This is the second flip transform, applied to ctx.
CGContextScaleCTM(ctx, 1.0f, -1.0f);
CGContextTranslateCTM(ctx, 0.0f, -(2.0 * tmpRect.origin.y + tmpRect.size.height));
[cell drawWithFrame:tmpRect inView:view];
[NSGraphicsContext setCurrentContext:savedContext];
CGImageRef img = CGBitmapContextCreateImage(ctx);
// Drop the image into the original destination rectangle, scaling to fit
// Only scale MAX_FOCUS_RING_WIDTH by xscale/yscale when the resulting rect
// doesn't extend beyond the overflow rect
float xscale = destRect.size.width / drawRect.size.width;
float yscale = destRect.size.height / drawRect.size.height;
float scaledFocusRingX = xscale < 1.0f ? MAX_FOCUS_RING_WIDTH * xscale : MAX_FOCUS_RING_WIDTH;
float scaledFocusRingY = yscale < 1.0f ? MAX_FOCUS_RING_WIDTH * yscale : MAX_FOCUS_RING_WIDTH;
CGContextDrawImage(cgContext, CGRectMake(destRect.origin.x - scaledFocusRingX,
destRect.origin.y - scaledFocusRingY,
destRect.size.width + scaledFocusRingX * 2,
destRect.size.height + scaledFocusRingY * 2),
img);
CGImageRelease(img);
CGContextRelease(ctx);
}
[NSGraphicsContext restoreGraphicsState];
#if DRAW_IN_FRAME_DEBUG
CGContextSetRGBFillColor(cgContext, 0.0, 0.0, 0.5, 0.25);
CGContextFillRect(cgContext, destRect);
#endif
NS_OBJC_END_TRY_ABORT_BLOCK;
}
struct CellRenderSettings {
// The natural dimensions of the control.
// If a control has no natural dimensions in either/both axes, set to 0.0f.
NSSize naturalSizes[3];
// The minimum dimensions of the control.
// If a control has no minimum dimensions in either/both axes, set to 0.0f.
NSSize minimumSizes[3];
// A three-dimensional array,
// with the first dimension being the OS version (only Leopard for the moment),
// the second being the control size (mini, small, regular), and the third
// being the 4 margin values (left, top, right, bottom).
float margins[1][3][4];
};
/*
* This is a helper method that returns the required NSControlSize given a size
* and the size of the three controls plus a tolerance.
* size - The width or the height of the element to draw.
* sizes - An array with the all the width/height of the element for its
* different sizes.
* tolerance - The tolerance as passed to DrawCellWithSnapping.
* NOTE: returns NSRegularControlSize if all values in 'sizes' are zero.
*/
static NSControlSize FindControlSize(CGFloat size, const CGFloat* sizes, CGFloat tolerance)
{
for (PRUint32 i = miniControlSize; i <= regularControlSize; ++i) {
if (sizes[i] == 0) {
continue;
}
CGFloat next = 0;
// Find next value.
for (PRUint32 j = i+1; j <= regularControlSize; ++j) {
if (sizes[j] != 0) {
next = sizes[j];
break;
}
}
// If it's the latest value, we pick it.
if (next == 0) {
return CocoaSizeForEnum(i);
}
if (size <= sizes[i] + tolerance && size < next) {
return CocoaSizeForEnum(i);
}
}
// If we are here, that means sizes[] was an array with only empty values
// or the algorithm above is wrong.
// The former can happen but the later would be wrong.
NS_ASSERTION(sizes[0] == 0 && sizes[1] == 0 && sizes[2] == 0,
"We found no control! We shouldn't be there!");
return CocoaSizeForEnum(regularControlSize);
}
/*
* Draw the given NSCell into the given cgContext with a nice control size.
*
* This function is similar to DrawCellWithScaling, but it decides what
* control size to use based on the destRect's size.
* Scaling is only applied when the difference between the destRect's size
* and the next smaller natural size is greater than snapTolerance. Otherwise
* it snaps to the next smaller control size without scaling because unscaled
* controls look nicer.
*/
static void DrawCellWithSnapping(NSCell *cell,
CGContextRef cgContext,
const HIRect& destRect,
const CellRenderSettings settings,
float verticalAlignFactor,
NSView* view,
BOOL mirrorHorizontal,
float snapTolerance = 2.0f)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
const float rectWidth = destRect.size.width, rectHeight = destRect.size.height;
const NSSize *sizes = settings.naturalSizes;
const NSSize miniSize = sizes[EnumSizeForCocoaSize(NSMiniControlSize)];
const NSSize smallSize = sizes[EnumSizeForCocoaSize(NSSmallControlSize)];
const NSSize regularSize = sizes[EnumSizeForCocoaSize(NSRegularControlSize)];
HIRect drawRect = destRect;
CGFloat controlWidths[3] = { miniSize.width, smallSize.width, regularSize.width };
NSControlSize controlSizeX = FindControlSize(rectWidth, controlWidths, snapTolerance);
CGFloat controlHeights[3] = { miniSize.height, smallSize.height, regularSize.height };
NSControlSize controlSizeY = FindControlSize(rectHeight, controlHeights, snapTolerance);
NSControlSize controlSize = NSRegularControlSize;
int sizeIndex = 0;
// At some sizes, don't scale but snap.
const NSControlSize smallerControlSize =
EnumSizeForCocoaSize(controlSizeX) < EnumSizeForCocoaSize(controlSizeY) ?
controlSizeX : controlSizeY;
const int smallerControlSizeIndex = EnumSizeForCocoaSize(smallerControlSize);
const NSSize size = sizes[smallerControlSizeIndex];
float diffWidth = size.width ? rectWidth - size.width : 0.0f;
float diffHeight = size.height ? rectHeight - size.height : 0.0f;
if (diffWidth >= 0.0f && diffHeight >= 0.0f &&
diffWidth <= snapTolerance && diffHeight <= snapTolerance) {
// Snap to the smaller control size.
controlSize = smallerControlSize;
sizeIndex = smallerControlSizeIndex;
// Resize and center the drawRect.
if (sizes[sizeIndex].width) {
drawRect.origin.x += ceil((destRect.size.width - sizes[sizeIndex].width) / 2);
drawRect.size.width = sizes[sizeIndex].width;
}
if (sizes[sizeIndex].height) {
drawRect.origin.y += floor((destRect.size.height - sizes[sizeIndex].height) * verticalAlignFactor);
drawRect.size.height = sizes[sizeIndex].height;
}
} else {
// Use the larger control size.
controlSize = EnumSizeForCocoaSize(controlSizeX) > EnumSizeForCocoaSize(controlSizeY) ?
controlSizeX : controlSizeY;
sizeIndex = EnumSizeForCocoaSize(controlSize);
}
[cell setControlSize:controlSize];
NSSize minimumSize = settings.minimumSizes ? settings.minimumSizes[sizeIndex] : NSZeroSize;
DrawCellWithScaling(cell, cgContext, drawRect, controlSize, sizes[sizeIndex],
minimumSize, settings.margins, view, mirrorHorizontal);
NS_OBJC_END_TRY_ABORT_BLOCK;
}
static float VerticalAlignFactor(nsIFrame *aFrame)
{
if (!aFrame)
return 0.5f; // default: center
const nsStyleCoord& va = aFrame->GetStyleTextReset()->mVerticalAlign;
PRUint8 intval = (va.GetUnit() == eStyleUnit_Enumerated)
? va.GetIntValue()
: NS_STYLE_VERTICAL_ALIGN_MIDDLE;
switch (intval) {
case NS_STYLE_VERTICAL_ALIGN_TOP:
case NS_STYLE_VERTICAL_ALIGN_TEXT_TOP:
return 0.0f;
case NS_STYLE_VERTICAL_ALIGN_SUB:
case NS_STYLE_VERTICAL_ALIGN_SUPER:
case NS_STYLE_VERTICAL_ALIGN_MIDDLE:
case NS_STYLE_VERTICAL_ALIGN_MIDDLE_WITH_BASELINE:
return 0.5f;
case NS_STYLE_VERTICAL_ALIGN_BASELINE:
case NS_STYLE_VERTICAL_ALIGN_TEXT_BOTTOM:
case NS_STYLE_VERTICAL_ALIGN_BOTTOM:
return 1.0f;
default:
NS_NOTREACHED("invalid vertical-align");
return 0.5f;
}
}
// These are the sizes that Gecko needs to request to draw if it wants
// to get a standard-sized Aqua radio button drawn. Note that the rects
// that draw these are actually a little bigger.
static const CellRenderSettings radioSettings = {
{
NSMakeSize(11, 11), // mini
NSMakeSize(13, 13), // small
NSMakeSize(16, 16) // regular
},
{
NSZeroSize, NSZeroSize, NSZeroSize
},
{
{ // Leopard
{0, 0, 0, 0}, // mini
{0, 1, 1, 1}, // small
{0, 0, 0, 0} // regular
}
}
};
static const CellRenderSettings checkboxSettings = {
{
NSMakeSize(11, 11), // mini
NSMakeSize(13, 13), // small
NSMakeSize(16, 16) // regular
},
{
NSZeroSize, NSZeroSize, NSZeroSize
},
{
{ // Leopard
{0, 1, 0, 0}, // mini
{0, 1, 0, 1}, // small
{0, 1, 0, 1} // regular
}
}
};
void
nsNativeThemeCocoa::DrawCheckboxOrRadio(CGContextRef cgContext, bool inCheckbox,
const HIRect& inBoxRect, bool inSelected,
nsEventStates inState, nsIFrame* aFrame)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
NSButtonCell *cell = inCheckbox ? mCheckboxCell : mRadioButtonCell;
NSCellStateValue state = inSelected ? NSOnState : NSOffState;
// Check if we have an indeterminate checkbox
if (inCheckbox && GetIndeterminate(aFrame))
state = NSMixedState;
[cell setEnabled:!IsDisabled(aFrame, inState)];
[cell setShowsFirstResponder:inState.HasState(NS_EVENT_STATE_FOCUS)];
[cell setState:state];
[cell setHighlighted:inState.HasAllStates(NS_EVENT_STATE_ACTIVE | NS_EVENT_STATE_HOVER)];
[cell setControlTint:(FrameIsInActiveWindow(aFrame) ? [NSColor currentControlTint] : NSClearControlTint)];
// Ensure that the control is square.
float length = NS_MIN(inBoxRect.size.width, inBoxRect.size.height);
HIRect drawRect = CGRectMake(inBoxRect.origin.x + (int)((inBoxRect.size.width - length) / 2.0f),
inBoxRect.origin.y + (int)((inBoxRect.size.height - length) / 2.0f),
length, length);
DrawCellWithSnapping(cell, cgContext, drawRect,
inCheckbox ? checkboxSettings : radioSettings,
VerticalAlignFactor(aFrame), mCellDrawView, NO);
NS_OBJC_END_TRY_ABORT_BLOCK;
}
static const CellRenderSettings searchFieldSettings = {
{
NSMakeSize(0, 16), // mini
NSMakeSize(0, 19), // small
NSMakeSize(0, 22) // regular
},
{
NSMakeSize(32, 0), // mini
NSMakeSize(38, 0), // small
NSMakeSize(44, 0) // regular
},
{
{ // Leopard
{0, 0, 0, 0}, // mini
{0, 0, 0, 0}, // small
{0, 0, 0, 0} // regular
}
}
};
void
nsNativeThemeCocoa::DrawSearchField(CGContextRef cgContext, const HIRect& inBoxRect,
nsIFrame* aFrame, nsEventStates inState)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
ContextAwareSearchFieldCell* cell = mSearchFieldCell;
[cell setContext:aFrame];
[cell setEnabled:!IsDisabled(aFrame, inState)];
// NOTE: this could probably use inState
[cell setShowsFirstResponder:IsFocused(aFrame)];
DrawCellWithSnapping(cell, cgContext, inBoxRect, searchFieldSettings,
VerticalAlignFactor(aFrame), mCellDrawView,
IsFrameRTL(aFrame));
[cell setContext:nsnull];
NS_OBJC_END_TRY_ABORT_BLOCK;
}
static const CellRenderSettings pushButtonSettings = {
{
NSMakeSize(0, 16), // mini
NSMakeSize(0, 19), // small
NSMakeSize(0, 22) // regular
},
{
NSMakeSize(18, 0), // mini
NSMakeSize(26, 0), // small
NSMakeSize(30, 0) // regular
},
{
{ // Leopard
{0, 0, 0, 0}, // mini
{4, 0, 4, 1}, // small
{5, 0, 5, 2} // regular
}
}
};
// The height at which we start doing square buttons instead of rounded buttons
// Rounded buttons look bad if drawn at a height greater than 26, so at that point
// we switch over to doing square buttons which looks fine at any size.
#define DO_SQUARE_BUTTON_HEIGHT 26
void
nsNativeThemeCocoa::DrawPushButton(CGContextRef cgContext, const HIRect& inBoxRect,
nsEventStates inState, nsIFrame* aFrame)
{
NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
BOOL isActive = FrameIsInActiveWindow(aFrame);
BOOL isDisabled = IsDisabled(aFrame, inState);
[mPushButtonCell setEnabled:!isDisabled];
[mPushButtonCell setHighlighted:isActive &&
inState.HasAllStates(NS_EVENT_STATE_ACTIVE | NS_EVENT_STATE_HOVER)];
[mPushButtonCell setShowsFirstResponder:inState.HasState(NS_EVENT_STATE_FOCUS) && !isDisabled && isActive];
// If the button is tall enough, draw the square button style so that buttons with
// non-standard content look good. Otherwise draw normal rounded aqua buttons.
if (inBoxRect.size.height > DO_SQUARE_BUTTON_HEIGHT) {
[mPushButtonCell setBezelStyle:NSShadowlessSquareBezelStyle];
DrawCellWithScaling(mPushButtonCell, cgContext, inBoxRect, NSRegularControlSize,
NSZeroSize, NSMakeSize(14, 0), NULL,
mCellDrawView, IsFrameRTL(aFrame));
} else {
[mPushButtonCell setBezelStyle:NSRoundedBezelStyle];
DrawCellWithSnapping(mPushButtonCell, cgContext, inBoxRect, pushButtonSettings,
0.5f, mCellDrawView, IsFrameRTL(aFrame), 1.0f);
}
#if DRAW_IN_FRAME_DEBUG
CGContextSetRGBFillColor(cgContext, 0.0, 0.0, 0.5, 0.25);
CGContextFillRect(cgContext, inBoxRect);
#endif
NS_OBJC_END_TRY_ABORT_BLOCK;
}
typedef void (*RenderHIThemeControlFunction)(CGContextRef cgContext, const HIRect& aRenderRect, void* aData);
static void
RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRect& aRect,
RenderHIThemeControlFunction aFunc, void* aData,
BOOL mirrorHorizontally = NO)
{
CGAffineTransform savedCTM = CGContextGetCTM(aCGContext);
CGContextTranslateCTM(aCGContext, aRect.origin.x, aRect.origin.y);
bool drawDirect;
HIRect drawRect = aRect;
drawRect.origin = CGPointZero;
if (!mirrorHorizontally && savedCTM.a == 1.0f && savedCTM.b == 0.0f &&
savedCTM.c == 0.0f && (savedCTM.d == 1.0f || savedCTM.d == -1.0f)) {
drawDirect = TRUE;
} else {
drawDirect = FALSE;
}
// Fall back to no bitmap buffer if the area of our control (in pixels^2)
// is too large.
if (drawDirect || (aRect.size.width * aRect.size.height > BITMAP_MAX_AREA)) {
aFunc(aCGContext, drawRect, aData);
} else {
// Inflate the buffer to capture focus rings.
int w = ceil(drawRect.size.width) + 2 * MAX_FOCUS_RING_WIDTH;
int h = ceil(drawRect.size.height) + 2 * MAX_FOCUS_RING_WIDTH;