summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm
blob: 7bda1506824010cc1eaffbf03e73a0eef821bde2 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
/*
 * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
 * Copyright (C) 2008, 2009 Google, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#import "third_party/blink/renderer/core/layout/layout_theme_mac.h"

#import <AvailabilityMacros.h>
#import <Carbon/Carbon.h>
#import <Cocoa/Cocoa.h>
#import <math.h>

#import "base/mac/mac_util.h"
#import "third_party/blink/public/platform/mac/web_sandbox_support.h"
#import "third_party/blink/public/platform/platform.h"
#import "third_party/blink/public/resources/grit/blink_resources.h"
#import "third_party/blink/public/strings/grit/blink_strings.h"
#import "third_party/blink/renderer/core/css_value_keywords.h"
#import "third_party/blink/renderer/core/fileapi/file.h"
#import "third_party/blink/renderer/core/html_names.h"
#import "third_party/blink/renderer/core/layout/layout_progress.h"
#import "third_party/blink/renderer/core/layout/layout_theme_default.h"
#import "third_party/blink/renderer/core/layout/layout_view.h"
#import "third_party/blink/renderer/core/style/shadow_list.h"
#import "third_party/blink/renderer/platform/data_resource_helper.h"
#import "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#import "third_party/blink/renderer/platform/mac/block_exceptions.h"
#import "third_party/blink/renderer/platform/mac/color_mac.h"
#import "third_party/blink/renderer/platform/mac/web_core_ns_cell_extras.h"
#import "third_party/blink/renderer/platform/runtime_enabled_features.h"
#import "third_party/blink/renderer/platform/web_test_support.h"
#include "ui/base/ui_base_features.h"
#include "ui/native_theme/native_theme.h"

// This is a view whose sole purpose is to tell AppKit that it's flipped.
@interface BlinkFlippedControl : NSControl
@end

@implementation BlinkFlippedControl

- (BOOL)isFlipped {
  return YES;
}

- (NSText*)currentEditor {
  return nil;
}

- (BOOL)_automaticFocusRingDisabled {
  return YES;
}

@end
// The methods in this file are specific to the Mac OS X platform.

@interface BlinkLayoutThemeNotificationObserver : NSObject {
  blink::LayoutTheme* _theme;
}

- (id)initWithTheme:(blink::LayoutTheme*)theme;
- (void)systemColorsDidChange:(NSNotification*)notification;

@end

@implementation BlinkLayoutThemeNotificationObserver

- (id)initWithTheme:(blink::LayoutTheme*)theme {
  if (!(self = [super init]))
    return nil;

  _theme = theme;
  return self;
}

- (void)systemColorsDidChange:(NSNotification*)unusedNotification {
  DCHECK([[unusedNotification name]
      isEqualToString:NSSystemColorsDidChangeNotification]);
  _theme->PlatformColorsDidChange();
}

@end

@interface NSTextFieldCell (WKDetails)
- (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame
                                        inView:(NSView*)controlView
                                  includeFocus:(BOOL)includeFocus;
@end

@interface BlinkTextFieldCell : NSTextFieldCell
- (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame
                                        inView:(NSView*)controlView
                                  includeFocus:(BOOL)includeFocus;
@end

@implementation BlinkTextFieldCell
- (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame
                                        inView:(NSView*)controlView
                                  includeFocus:(BOOL)includeFocus {
  // FIXME: This is a post-Lion-only workaround for <rdar://problem/11385461>.
  // When that bug is resolved, we should remove this code.
  CFMutableDictionaryRef coreUIDrawOptions = CFDictionaryCreateMutableCopy(
      NULL, 0, [super _coreUIDrawOptionsWithFrame:cellFrame
                                           inView:controlView
                                     includeFocus:includeFocus]);
  CFDictionarySetValue(coreUIDrawOptions, @"borders only", kCFBooleanTrue);
  return (CFDictionaryRef)[NSMakeCollectable(coreUIDrawOptions) autorelease];
}
@end

@interface BlinkFlippedView : NSView
@end

@implementation BlinkFlippedView

- (BOOL)isFlipped {
  return YES;
}

- (NSText*)currentEditor {
  return nil;
}

@end

namespace blink {

namespace {

class LayoutThemeMacRefresh final : public LayoutThemeDefault {
 public:
  static scoped_refptr<LayoutTheme> Create() {
    return base::AdoptRef(new LayoutThemeMacRefresh());
  }

  Color PlatformActiveSelectionBackgroundColor(
      WebColorScheme color_scheme) const override;
  Color PlatformInactiveSelectionBackgroundColor(
      WebColorScheme color_scheme) const override;
  Color PlatformActiveSelectionForegroundColor(
      WebColorScheme color_scheme) const override;
  Color PlatformSpellingMarkerUnderlineColor() const override;
  Color PlatformGrammarMarkerUnderlineColor() const override;
  Color FocusRingColor() const override;
  String DisplayNameForFile(const File& file) const override {
    if (file.GetUserVisibility() == File::kIsUserVisible)
      return [[NSFileManager defaultManager] displayNameAtPath:file.GetPath()];
    return file.name();
  }
  bool PopsMenuByArrowKeys() const override;
  bool PopsMenuByReturnKey() const override;
  bool SupportsSelectionForegroundColors() const override { return false; }

 protected:
  // Controls color values returned from FocusRingColor().
  bool UsesTestModeFocusRingColor() const;
  bool IsAccentColorCustomized(WebColorScheme color_scheme) const;
};

// Inflate an IntRect to account for specific padding around margins.
enum { kTopMargin = 0, kRightMargin = 1, kBottomMargin = 2, kLeftMargin = 3 };

bool FontSizeMatchesToControlSize(const ComputedStyle& style) {
  int font_size = style.FontSize();
  if (font_size == [NSFont systemFontSizeForControlSize:NSRegularControlSize])
    return true;
  if (font_size == [NSFont systemFontSizeForControlSize:NSSmallControlSize])
    return true;
  if (font_size == [NSFont systemFontSizeForControlSize:NSMiniControlSize])
    return true;
  return false;
}

Color GetSystemColor(MacSystemColorID color_id, WebColorScheme color_scheme) {
  // In tests, a WebSandboxSupport may not be set up. Just return a dummy
  // color, in this case, black.
  auto* sandbox_support = Platform::Current()->GetSandboxSupport();
  if (!sandbox_support)
    return Color();
  return sandbox_support->GetSystemColor(color_id, color_scheme);
}

// Helper functions used by a bunch of different control parts.
NSControlSize ControlSizeForFont(const FontDescription& font_description) {
  int font_size = font_description.ComputedPixelSize();
  if (font_size >= 16)
    return NSRegularControlSize;
  if (font_size >= 11)
    return NSSmallControlSize;
  return NSMiniControlSize;
}

LengthSize SizeFromNSControlSize(NSControlSize ns_control_size,
                                 const LengthSize& zoomed_size,
                                 float zoom_factor,
                                 const IntSize* sizes) {
  IntSize control_size = sizes[ns_control_size];
  if (zoom_factor != 1.0f)
    control_size = IntSize(control_size.Width() * zoom_factor,
                           control_size.Height() * zoom_factor);
  LengthSize result = zoomed_size;
  if (zoomed_size.Width().IsIntrinsicOrAuto() && control_size.Width() > 0)
    result.SetWidth(Length::Fixed(control_size.Width()));
  if (zoomed_size.Height().IsIntrinsicOrAuto() && control_size.Height() > 0)
    result.SetHeight(Length::Fixed(control_size.Height()));
  return result;
}

LengthSize SizeFromFont(const FontDescription& font_description,
                        const LengthSize& zoomed_size,
                        float zoom_factor,
                        const IntSize* sizes) {
  return SizeFromNSControlSize(ControlSizeForFont(font_description),
                               zoomed_size, zoom_factor, sizes);
}

}  // namespace

LayoutThemeMac::LayoutThemeMac()
    : LayoutTheme(),
      notification_observer_(
          [[BlinkLayoutThemeNotificationObserver alloc] initWithTheme:this]),
      painter_(*this) {
  [[NSNotificationCenter defaultCenter]
      addObserver:notification_observer_
         selector:@selector(systemColorsDidChange:)
             name:NSSystemColorsDidChangeNotification
           object:nil];
}

LayoutThemeMac::~LayoutThemeMac() {
  [[NSNotificationCenter defaultCenter] removeObserver:notification_observer_];
}

Color LayoutThemeMac::PlatformActiveSelectionBackgroundColor(
    WebColorScheme color_scheme) const {
  return GetSystemColor(MacSystemColorID::kSelectedTextBackground,
                        color_scheme);
}

Color LayoutThemeMac::PlatformInactiveSelectionBackgroundColor(
    WebColorScheme color_scheme) const {
  return GetSystemColor(MacSystemColorID::kSecondarySelectedControl,
                        color_scheme);
}

Color LayoutThemeMac::PlatformActiveSelectionForegroundColor(
    WebColorScheme color_scheme) const {
  return Color::kBlack;
}

Color LayoutThemeMac::PlatformActiveListBoxSelectionBackgroundColor(
    WebColorScheme color_scheme) const {
  return GetSystemColor(MacSystemColorID::kAlternateSelectedControl,
                        color_scheme);
}

Color LayoutThemeMac::PlatformActiveListBoxSelectionForegroundColor(
    WebColorScheme color_scheme) const {
  return Color::kWhite;
}

Color LayoutThemeMac::PlatformInactiveListBoxSelectionForegroundColor(
    WebColorScheme color_scheme) const {
  return Color::kBlack;
}

Color LayoutThemeMac::PlatformSpellingMarkerUnderlineColor() const {
  return Color(251, 45, 29);
}

Color LayoutThemeMac::PlatformGrammarMarkerUnderlineColor() const {
  return Color(107, 107, 107);
}

Color LayoutThemeMac::PlatformFocusRingColor() const {
  static const RGBA32 kOldAquaFocusRingColor = 0xFF7DADD9;
  if (UsesTestModeFocusRingColor())
    return kOldAquaFocusRingColor;

  // TODO(crbug.com/929098) Need to pass an appropriate color scheme here.
  return SystemColor(CSSValueID::kWebkitFocusRingColor,
                     ComputedStyle::InitialStyle().UsedColorScheme());
}

Color LayoutThemeMac::PlatformInactiveListBoxSelectionBackgroundColor(
    WebColorScheme color_scheme) const {
  return PlatformInactiveSelectionBackgroundColor(color_scheme);
}

Color LayoutThemeMacRefresh::PlatformActiveSelectionBackgroundColor(
    WebColorScheme color_scheme) const {
  return GetSystemColor(MacSystemColorID::kSelectedTextBackground,
                        color_scheme);
}

Color LayoutThemeMacRefresh::PlatformInactiveSelectionBackgroundColor(
    WebColorScheme color_scheme) const {
  return GetSystemColor(MacSystemColorID::kSecondarySelectedControl,
                        color_scheme);
}

Color LayoutThemeMacRefresh::PlatformActiveSelectionForegroundColor(
    WebColorScheme color_scheme) const {
  return Color::kBlack;
}

Color LayoutThemeMacRefresh::PlatformSpellingMarkerUnderlineColor() const {
  return Color(251, 45, 29);
}

Color LayoutThemeMacRefresh::PlatformGrammarMarkerUnderlineColor() const {
  return Color(107, 107, 107);
}

bool LayoutThemeMacRefresh::IsAccentColorCustomized(
    WebColorScheme color_scheme) const {
  if (@available(macOS 10.14, *)) {
    static const Color kControlBlueAccentColor =
        GetSystemColor(MacSystemColorID::kControlAccentBlueColor, color_scheme);
    if (kControlBlueAccentColor ==
        GetSystemColor(MacSystemColorID::kControlAccentColor, color_scheme)) {
      return false;
    }
  } else {
    if (NSBlueControlTint == [[NSUserDefaults standardUserDefaults]
                                 integerForKey:@"AppleAquaColorVariant"]) {
      return false;
    }
  }
  return true;
}

Color LayoutThemeMacRefresh::FocusRingColor() const {
  static const RGBA32 kDefaultFocusRingColor = 0xFF101010;
  if (UsesTestModeFocusRingColor()) {
    return HasCustomFocusRingColor() ? GetCustomFocusRingColor()
                                     : kDefaultFocusRingColor;
  }

  if (ui::NativeTheme::GetInstanceForWeb()->UsesHighContrastColors()) {
    // When high contrast is enabled, #101010 should be used.
    return Color(0xFF101010);
  }

  // TODO(crbug.com/929098) Need to pass an appropriate color scheme here.
  WebColorScheme color_scheme = ComputedStyle::InitialStyle().UsedColorScheme();

  Color keyboard_focus_indicator =
      GetSystemColor(MacSystemColorID::kKeyboardFocusIndicator, color_scheme);
  // Take the RGB values from the keyboard_focus_indicator color, but use a
  // different alpha value to avoid having a color too light.
  Color focus_ring =
      Color(keyboard_focus_indicator.Red(), keyboard_focus_indicator.Green(),
            keyboard_focus_indicator.Blue(), /*alpha=*/166);
  if (!HasCustomFocusRingColor())
    return focus_ring;
  // Use the custom focus ring color when the system accent color wasn't
  // changed.
  if (!IsAccentColorCustomized(color_scheme))
    return GetCustomFocusRingColor();
  return focus_ring;
}

bool LayoutThemeMacRefresh::UsesTestModeFocusRingColor() const {
  return WebTestSupport::IsRunningWebTest();
}

bool LayoutThemeMacRefresh::PopsMenuByArrowKeys() const {
  return true;
}

bool LayoutThemeMacRefresh::PopsMenuByReturnKey() const {
  return false;
}

static FontSelectionValue ToFontWeight(NSInteger app_kit_font_weight) {
  DCHECK_GT(app_kit_font_weight, 0);
  DCHECK_LT(app_kit_font_weight, 15);
  if (app_kit_font_weight > 14)
    app_kit_font_weight = 14;
  else if (app_kit_font_weight < 1)
    app_kit_font_weight = 1;

  static FontSelectionValue font_weights[] = {
      FontSelectionValue(100), FontSelectionValue(100), FontSelectionValue(200),
      FontSelectionValue(300), FontSelectionValue(400), FontSelectionValue(500),
      FontSelectionValue(600), FontSelectionValue(600), FontSelectionValue(700),
      FontSelectionValue(800), FontSelectionValue(800), FontSelectionValue(900),
      FontSelectionValue(900), FontSelectionValue(900)};
  return font_weights[app_kit_font_weight - 1];
}

static inline NSFont* SystemNSFont(CSSValueID system_font_id) {
  switch (system_font_id) {
    case CSSValueID::kSmallCaption:
      return [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
    case CSSValueID::kMenu:
      return [NSFont menuFontOfSize:[NSFont systemFontSize]];
    case CSSValueID::kStatusBar:
      return [NSFont labelFontOfSize:[NSFont labelFontSize]];
    case CSSValueID::kWebkitMiniControl:
      return [NSFont
          systemFontOfSize:[NSFont
                               systemFontSizeForControlSize:NSMiniControlSize]];
    case CSSValueID::kWebkitSmallControl:
      return [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:
                                                  NSSmallControlSize]];
    case CSSValueID::kWebkitControl:
      return [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:
                                                  NSRegularControlSize]];
    default:
      return [NSFont systemFontOfSize:[NSFont systemFontSize]];
  }
}

void LayoutThemeMac::SystemFont(CSSValueID system_font_id,
                                FontSelectionValue& font_slope,
                                FontSelectionValue& font_weight,
                                float& font_size,
                                AtomicString& font_family) const {
  NSFont* font = SystemNSFont(system_font_id);
  if (!font)
    return;

  NSFontManager* font_manager = [NSFontManager sharedFontManager];
  font_slope = ([font_manager traitsOfFont:font] & NSItalicFontMask)
                   ? ItalicSlopeValue()
                   : NormalSlopeValue();
  font_weight = ToFontWeight([font_manager weightOfFont:font]);
  font_size = [font pointSize];
  font_family = font_family_names::kSystemUi;
}

Color LayoutThemeMac::SystemColor(CSSValueID css_value_id,
                                  WebColorScheme color_scheme) const {
  if (!Platform::Current()->GetSandboxSupport())
    return LayoutTheme::SystemColor(css_value_id, color_scheme);

  switch (css_value_id) {
    case CSSValueID::kActiveborder:
      return GetSystemColor(MacSystemColorID::kKeyboardFocusIndicator,
                            color_scheme);
    case CSSValueID::kActivecaption:
      return GetSystemColor(MacSystemColorID::kWindowFrameText, color_scheme);
    case CSSValueID::kAppworkspace:
      return GetSystemColor(MacSystemColorID::kHeader, color_scheme);
    case CSSValueID::kBackground:
      // Use theme independent default.
      break;
    case CSSValueID::kButtonface:
      return GetSystemColor(MacSystemColorID::kControlBackground, color_scheme);
    case CSSValueID::kButtonhighlight:
      return GetSystemColor(MacSystemColorID::kControlHighlight, color_scheme);
    case CSSValueID::kButtonshadow:
      return GetSystemColor(MacSystemColorID::kControlShadow, color_scheme);
    case CSSValueID::kButtontext:
      return GetSystemColor(MacSystemColorID::kControlText, color_scheme);
    case CSSValueID::kCaptiontext:
      return GetSystemColor(MacSystemColorID::kText, color_scheme);
    case CSSValueID::kField:
      return GetSystemColor(MacSystemColorID::kControlBackground, color_scheme);
    case CSSValueID::kFieldtext:
      return GetSystemColor(MacSystemColorID::kText, color_scheme);
    case CSSValueID::kGraytext:
      return GetSystemColor(MacSystemColorID::kDisabledControlText,
                            color_scheme);
    case CSSValueID::kHighlight:
      return GetSystemColor(MacSystemColorID::kSelectedTextBackground,
                            color_scheme);
    case CSSValueID::kHighlighttext:
      return GetSystemColor(MacSystemColorID::kSelectedText, color_scheme);
    case CSSValueID::kInactiveborder:
      return GetSystemColor(MacSystemColorID::kControlBackground, color_scheme);
    case CSSValueID::kInactivecaption:
      return GetSystemColor(MacSystemColorID::kControlBackground, color_scheme);
    case CSSValueID::kInactivecaptiontext:
      return GetSystemColor(MacSystemColorID::kText, color_scheme);
    case CSSValueID::kInfobackground:
      // There is no corresponding NSColor for this so we use a hard coded
      // value.
      return 0xFFFBFCC5;
    case CSSValueID::kInfotext:
      return GetSystemColor(MacSystemColorID::kText, color_scheme);
    case CSSValueID::kMenu:
      return GetSystemColor(MacSystemColorID::kMenuBackground, color_scheme);
    case CSSValueID::kMenutext:
      return GetSystemColor(MacSystemColorID::kSelectedMenuItemText,
                            color_scheme);
    case CSSValueID::kScrollbar:
      return GetSystemColor(MacSystemColorID::kScrollBar, color_scheme);
    case CSSValueID::kText:
      return GetSystemColor(MacSystemColorID::kText, color_scheme);
    case CSSValueID::kThreeddarkshadow:
      return GetSystemColor(MacSystemColorID::kControlDarkShadow, color_scheme);
    case CSSValueID::kThreedshadow:
      return GetSystemColor(MacSystemColorID::kShadow, color_scheme);
    case CSSValueID::kThreedface:
      // We use this value instead of NSColor's controlColor to avoid website
      // incompatibilities. We may want to change this to use the NSColor in
      // future.
      return 0xFFC0C0C0;
    case CSSValueID::kThreedhighlight:
      return GetSystemColor(MacSystemColorID::kHighlight, color_scheme);
    case CSSValueID::kThreedlightshadow:
      return GetSystemColor(MacSystemColorID::kControlLightHighlight,
                            color_scheme);
    case CSSValueID::kWebkitFocusRingColor:
      return GetSystemColor(MacSystemColorID::kKeyboardFocusIndicator,
                            color_scheme);
    case CSSValueID::kWindow:
    case CSSValueID::kCanvas:
      return GetSystemColor(MacSystemColorID::kWindowBackground, color_scheme);
    case CSSValueID::kWindowframe:
      return GetSystemColor(MacSystemColorID::kWindowFrame, color_scheme);
    case CSSValueID::kWindowtext:
      return GetSystemColor(MacSystemColorID::kWindowFrameText, color_scheme);
    case CSSValueID::kCanvastext:
      return GetSystemColor(MacSystemColorID::kText, color_scheme);
    default:
      break;
  }

  return LayoutTheme::SystemColor(css_value_id, color_scheme);
}

bool LayoutThemeMac::IsControlStyled(ControlPart part,
                                     const ComputedStyle& style) const {
  if (part == kTextFieldPart || part == kTextAreaPart)
    return style.HasAuthorBorder() || style.BoxShadow();

  if (part == kMenulistPart) {
    // FIXME: This is horrible, but there is not much else that can be done.
    // Menu lists cannot draw properly when scaled. They can't really draw
    // properly when transformed either. We can't detect the transform case
    // at style adjustment time so that will just have to stay broken.  We
    // can however detect that we're zooming. If zooming is in effect we
    // treat it like the control is styled.
    if (style.EffectiveZoom() != 1.0f)
      return true;
    if (!FontSizeMatchesToControlSize(style))
      return true;
    if (style.GetFontDescription().Family().Family() !=
        font_family_names::kSystemUi)
      return true;
    if (!style.Height().IsIntrinsicOrAuto())
      return true;
  }
  // Some other cells don't work well when scaled.
  if (style.EffectiveZoom() != 1) {
    switch (part) {
      case kButtonPart:
      case kPushButtonPart:
      case kSearchFieldPart:
      case kSquareButtonPart:
        return true;
      default:
        break;
    }
  }
  return LayoutTheme::IsControlStyled(part, style);
}

void LayoutThemeMac::AddVisualOverflow(const Node* node,
                                       const ComputedStyle& style,
                                       IntRect& rect) {
  ControlPart part = style.EffectiveAppearance();
  switch (part) {
    case kCheckboxPart:
    case kRadioPart:
    case kPushButtonPart:
    case kSquareButtonPart:
    case kButtonPart:
    case kInnerSpinButtonPart:
      return AddVisualOverflowHelper(part, ControlStatesForNode(node, style),
                                     style.EffectiveZoom(), rect);
    default:
      break;
  }

  float zoom_level = style.EffectiveZoom();

  if (part == kMenulistPart) {
    SetPopupButtonCellState(node, style, rect);
    IntSize size = PopupButtonSizes()[[PopupButton() controlSize]];
    size.SetHeight(size.Height() * zoom_level);
    size.SetWidth(rect.Width());
    rect = InflateRect(rect, size, PopupButtonMargins(), zoom_level);
  } else if (part == kSliderThumbHorizontalPart ||
             part == kSliderThumbVerticalPart) {
    rect.SetHeight(rect.Height() + kSliderThumbShadowBlur);
  }
}

void LayoutThemeMac::UpdateCheckedState(NSCell* cell, const Node* node) {
  bool old_indeterminate = [cell state] == NSMixedState;
  bool indeterminate = IsIndeterminate(node);
  bool checked = IsChecked(node);

  if (old_indeterminate != indeterminate) {
    [cell setState:indeterminate ? NSMixedState
                                 : (checked ? NSOnState : NSOffState)];
    return;
  }

  bool old_checked = [cell state] == NSOnState;
  if (checked != old_checked)
    [cell setState:checked ? NSOnState : NSOffState];
}

void LayoutThemeMac::UpdateEnabledState(NSCell* cell, const Node* node) {
  bool old_enabled = [cell isEnabled];
  bool enabled = IsEnabled(node);
  if (enabled != old_enabled)
    [cell setEnabled:enabled];
}

void LayoutThemeMac::UpdateFocusedState(NSCell* cell,
                                        const Node* node,
                                        const ComputedStyle& style) {
  bool old_focused = [cell showsFirstResponder];
  bool focused = IsFocused(node) && style.OutlineStyleIsAuto();
  if (focused != old_focused)
    [cell setShowsFirstResponder:focused];
}

void LayoutThemeMac::UpdatePressedState(NSCell* cell, const Node* node) {
  bool old_pressed = [cell isHighlighted];
  bool pressed = node && node->IsActive();
  if (pressed != old_pressed)
    [cell setHighlighted:pressed];
}

NSControlSize LayoutThemeMac::ControlSizeForFont(
    const ComputedStyle& style) const {
  int font_size = style.FontSize();
  if (font_size >= 16)
    return NSRegularControlSize;
  if (font_size >= 11)
    return NSSmallControlSize;
  return NSMiniControlSize;
}

void LayoutThemeMac::SetControlSize(NSCell* cell,
                                    const IntSize* sizes,
                                    const IntSize& min_size,
                                    float zoom_level) {
  NSControlSize size;
  if (min_size.Width() >=
          static_cast<int>(sizes[NSRegularControlSize].Width() * zoom_level) &&
      min_size.Height() >=
          static_cast<int>(sizes[NSRegularControlSize].Height() * zoom_level))
    size = NSRegularControlSize;
  else if (min_size.Width() >=
               static_cast<int>(sizes[NSSmallControlSize].Width() *
                                zoom_level) &&
           min_size.Height() >=
               static_cast<int>(sizes[NSSmallControlSize].Height() *
                                zoom_level))
    size = NSSmallControlSize;
  else
    size = NSMiniControlSize;
  // Only update if we have to, since AppKit does work even if the size is the
  // same.
  if (size != [cell controlSize])
    [cell setControlSize:size];
}

IntSize LayoutThemeMac::SizeForFont(const ComputedStyle& style,
                                    const IntSize* sizes) const {
  if (style.EffectiveZoom() != 1.0f) {
    IntSize result = sizes[ControlSizeForFont(style)];
    return IntSize(result.Width() * style.EffectiveZoom(),
                   result.Height() * style.EffectiveZoom());
  }
  return sizes[ControlSizeForFont(style)];
}

IntSize LayoutThemeMac::SizeForSystemFont(const ComputedStyle& style,
                                          const IntSize* sizes) const {
  if (style.EffectiveZoom() != 1.0f) {
    IntSize result = sizes[ControlSizeForSystemFont(style)];
    return IntSize(result.Width() * style.EffectiveZoom(),
                   result.Height() * style.EffectiveZoom());
  }
  return sizes[ControlSizeForSystemFont(style)];
}

void LayoutThemeMac::SetSizeFromFont(ComputedStyle& style,
                                     const IntSize* sizes) const {
  // FIXME: Check is flawed, since it doesn't take min-width/max-width into
  // account.
  IntSize size = SizeForFont(style, sizes);
  if (style.Width().IsIntrinsicOrAuto() && size.Width() > 0)
    style.SetWidth(Length::Fixed(size.Width()));
  if (style.Height().IsAuto() && size.Height() > 0)
    style.SetHeight(Length::Fixed(size.Height()));
}

void LayoutThemeMac::SetFontFromControlSize(ComputedStyle& style,
                                            NSControlSize control_size) const {
  FontDescription font_description;
  font_description.SetIsAbsoluteSize(true);
  font_description.SetGenericFamily(FontDescription::kSerifFamily);

  NSFont* font = [NSFont
      systemFontOfSize:[NSFont systemFontSizeForControlSize:control_size]];
  font_description.FirstFamily().SetFamily(font_family_names::kSystemUi);
  font_description.SetComputedSize([font pointSize] * style.EffectiveZoom());
  font_description.SetSpecifiedSize([font pointSize] * style.EffectiveZoom());

  // Reset line height.
  style.SetLineHeight(ComputedStyleInitialValues::InitialLineHeight());

  style.SetFontDescription(font_description);
}

NSControlSize LayoutThemeMac::ControlSizeForSystemFont(
    const ComputedStyle& style) const {
  float font_size = style.FontSize();
  float zoom_level = style.EffectiveZoom();
  if (zoom_level != 1)
    font_size /= zoom_level;
  if (font_size >= [NSFont systemFontSizeForControlSize:NSRegularControlSize])
    return NSRegularControlSize;
  if (font_size >= [NSFont systemFontSizeForControlSize:NSSmallControlSize])
    return NSSmallControlSize;
  return NSMiniControlSize;
}

const int* LayoutThemeMac::PopupButtonMargins() const {
  static const int kMargins[3][4] = {{0, 3, 1, 3}, {0, 3, 2, 3}, {0, 1, 0, 1}};
  return kMargins[[PopupButton() controlSize]];
}

const IntSize* LayoutThemeMac::PopupButtonSizes() const {
  static const IntSize kSizes[3] = {IntSize(0, 21), IntSize(0, 18),
                                    IntSize(0, 15)};
  return kSizes;
}

const int* LayoutThemeMac::PopupButtonPadding(NSControlSize size) const {
  static const int kPadding[3][4] = {
      {2, 26, 3, 8}, {2, 23, 3, 8}, {2, 22, 3, 10}};
  return kPadding[size];
}

const int* LayoutThemeMac::ProgressBarHeights() const {
  static const int kSizes[3] = {20, 12, 12};
  return kSizes;
}

constexpr base::TimeDelta LayoutThemeMac::kProgressAnimationFrameRate;

base::TimeDelta LayoutThemeMac::AnimationRepeatIntervalForProgressBar() const {
  return kProgressAnimationFrameRate;
}

base::TimeDelta LayoutThemeMac::AnimationDurationForProgressBar() const {
  return kProgressAnimationNumFrames * kProgressAnimationFrameRate;
}

static const IntSize* MenuListButtonSizes() {
  static const IntSize kSizes[3] = {IntSize(0, 21), IntSize(0, 18),
                                    IntSize(0, 15)};
  return kSizes;
}

void LayoutThemeMac::AdjustMenuListStyle(ComputedStyle& style,
                                         Element* e) const {
  LayoutTheme::AdjustMenuListStyle(style, e);
  NSControlSize control_size = ControlSizeForFont(style);

  style.ResetBorder();
  style.ResetPadding();

  // Height is locked to auto.
  style.SetHeight(Length::Auto());

  // White-space is locked to pre.
  style.SetWhiteSpace(EWhiteSpace::kPre);

  // Set the foreground color to black or gray when we have the aqua look.
  // Cast to RGB32 is to work around a compiler bug.
  style.SetColor(e && !e->IsDisabledFormControl()
                     ? static_cast<RGBA32>(Color::kBlack)
                     : Color::kDarkGray);

  // Set the button's vertical size.
  SetSizeFromFont(style, MenuListButtonSizes());

  // Our font is locked to the appropriate system font size for the
  // control. To clarify, we first use the CSS-specified font to figure out a
  // reasonable control size, but once that control size is determined, we
  // throw that font away and use the appropriate system font for the control
  // size instead.
  SetFontFromControlSize(style, control_size);
}

static const int kBaseBorderRadius = 5;
static const int kStyledPopupPaddingStart = 8;
static const int kStyledPopupPaddingTop = 1;
static const int kStyledPopupPaddingBottom = 2;

// These functions are called with MenuListPart or MenulistButtonPart appearance
// by LayoutMenuList.
int LayoutThemeMac::PopupInternalPaddingStart(
    const ComputedStyle& style) const {
  if (style.EffectiveAppearance() == kMenulistPart)
    return PopupButtonPadding(ControlSizeForFont(style))[kLeftMargin] *
           style.EffectiveZoom();
  if (style.EffectiveAppearance() == kMenulistButtonPart)
    return kStyledPopupPaddingStart * style.EffectiveZoom();
  return 0;
}

int LayoutThemeMac::PopupInternalPaddingEnd(LocalFrame*,
                                            const ComputedStyle& style) const {
  if (style.EffectiveAppearance() == kMenulistPart)
    return PopupButtonPadding(ControlSizeForFont(style))[kRightMargin] *
           style.EffectiveZoom();
  if (style.EffectiveAppearance() != kMenulistButtonPart)
    return 0;
  float font_scale = style.FontSize() / kBaseFontSize;
  float arrow_width = kMenuListBaseArrowWidth * font_scale;
  return static_cast<int>(ceilf(
      arrow_width + (kMenuListArrowPaddingStart + kMenuListArrowPaddingEnd) *
                        style.EffectiveZoom()));
}

int LayoutThemeMac::PopupInternalPaddingTop(const ComputedStyle& style) const {
  if (style.EffectiveAppearance() == kMenulistPart)
    return PopupButtonPadding(ControlSizeForFont(style))[kTopMargin] *
           style.EffectiveZoom();
  if (style.EffectiveAppearance() == kMenulistButtonPart)
    return kStyledPopupPaddingTop * style.EffectiveZoom();
  return 0;
}

int LayoutThemeMac::PopupInternalPaddingBottom(
    const ComputedStyle& style) const {
  if (style.EffectiveAppearance() == kMenulistPart)
    return PopupButtonPadding(ControlSizeForFont(style))[kBottomMargin] *
           style.EffectiveZoom();
  if (style.EffectiveAppearance() == kMenulistButtonPart)
    return kStyledPopupPaddingBottom * style.EffectiveZoom();
  return 0;
}

void LayoutThemeMac::AdjustMenuListButtonStyle(ComputedStyle& style,
                                               Element*) const {
  float font_scale = style.FontSize() / kBaseFontSize;

  style.ResetPadding();
  style.SetBorderRadius(
      IntSize(int(kBaseBorderRadius + font_scale - 1),
              int(kBaseBorderRadius + font_scale - 1)));  // FIXME: Round up?

  const int kMinHeight = 15;
  style.SetMinHeight(Length::Fixed(kMinHeight));

  style.SetLineHeight(ComputedStyleInitialValues::InitialLineHeight());
}

void LayoutThemeMac::SetPopupButtonCellState(const Node* node,
                                             const ComputedStyle& style,
                                             const IntRect& rect) {
  NSPopUpButtonCell* popup_button = this->PopupButton();

  // Set the control size based off the rectangle we're painting into.
  SetControlSize(popup_button, PopupButtonSizes(), rect.Size(),
                 style.EffectiveZoom());

  // Update the various states we respond to.
  UpdateActiveState(popup_button, node);
  UpdateCheckedState(popup_button, node);
  UpdateEnabledState(popup_button, node);
  UpdatePressedState(popup_button, node);

  popup_button.userInterfaceLayoutDirection =
      style.Direction() == TextDirection::kLtr
          ? NSUserInterfaceLayoutDirectionLeftToRight
          : NSUserInterfaceLayoutDirectionRightToLeft;
}

const IntSize* LayoutThemeMac::MenuListSizes() const {
  static const IntSize kSizes[3] = {IntSize(9, 0), IntSize(5, 0),
                                    IntSize(0, 0)};
  return kSizes;
}

int LayoutThemeMac::MinimumMenuListSize(const ComputedStyle& style) const {
  return SizeForSystemFont(style, MenuListSizes()).Width();
}

void LayoutThemeMac::SetSearchCellState(const Node* node,
                                        const ComputedStyle& style,
                                        const IntRect&) {
  NSSearchFieldCell* search = this->Search();

  // Update the various states we respond to.
  UpdateActiveState(search, node);
  UpdateEnabledState(search, node);
  UpdateFocusedState(search, node, style);
}

const IntSize* LayoutThemeMac::SearchFieldSizes() const {
  static const IntSize kSizes[3] = {IntSize(0, 22), IntSize(0, 19),
                                    IntSize(0, 15)};
  return kSizes;
}

static const int* SearchFieldHorizontalPaddings() {
  static const int kSizes[3] = {3, 2, 1};
  return kSizes;
}

void LayoutThemeMac::SetSearchFieldSize(ComputedStyle& style) const {
  // If the width and height are both specified, then we have nothing to do.
  if (!style.Width().IsIntrinsicOrAuto() && !style.Height().IsAuto())
    return;

  // Use the font size to determine the intrinsic width of the control.
  SetSizeFromFont(style, SearchFieldSizes());
}

const uint8_t kSearchFieldBorderWidth = 2;
void LayoutThemeMac::AdjustSearchFieldStyle(ComputedStyle& style) const {
  // Override border.
  style.ResetBorder();
  const float border_width = kSearchFieldBorderWidth * style.EffectiveZoom();
  style.SetBorderLeftWidth(border_width);
  style.SetBorderLeftStyle(EBorderStyle::kInset);
  style.SetBorderRightWidth(border_width);
  style.SetBorderRightStyle(EBorderStyle::kInset);
  style.SetBorderBottomWidth(border_width);
  style.SetBorderBottomStyle(EBorderStyle::kInset);
  style.SetBorderTopWidth(border_width);
  style.SetBorderTopStyle(EBorderStyle::kInset);

  // Override height.
  style.SetHeight(Length::Auto());
  SetSearchFieldSize(style);

  NSControlSize control_size = ControlSizeForFont(style);

  // Override padding size to match AppKit text positioning.
  const int vertical_padding = 1 * style.EffectiveZoom();
  const int horizontal_padding =
      SearchFieldHorizontalPaddings()[control_size] * style.EffectiveZoom();
  style.SetPaddingLeft(Length::Fixed(horizontal_padding));
  style.SetPaddingRight(Length::Fixed(horizontal_padding));
  style.SetPaddingTop(Length::Fixed(vertical_padding));
  style.SetPaddingBottom(Length::Fixed(vertical_padding));

  SetFontFromControlSize(style, control_size);

  style.SetBoxShadow(nullptr);
}

const IntSize* LayoutThemeMac::CancelButtonSizes() const {
  static const IntSize kSizes[3] = {IntSize(14, 14), IntSize(11, 11),
                                    IntSize(9, 9)};
  return kSizes;
}

void LayoutThemeMac::AdjustSearchFieldCancelButtonStyle(
    ComputedStyle& style) const {
  IntSize size = SizeForSystemFont(style, CancelButtonSizes());
  style.SetWidth(Length::Fixed(size.Width()));
  style.SetHeight(Length::Fixed(size.Height()));
  style.SetBoxShadow(nullptr);
}

IntSize LayoutThemeMac::SliderTickSize() const {
  return IntSize(1, 3);
}

int LayoutThemeMac::SliderTickOffsetFromTrackCenter() const {
  return -9;
}

void LayoutThemeMac::AdjustProgressBarBounds(ComputedStyle& style) const {
  float zoom_level = style.EffectiveZoom();
  NSControlSize control_size = ControlSizeForFont(style);
  int height = ProgressBarHeights()[control_size] * zoom_level;

  // Now inflate it to account for the shadow.
  style.SetMinHeight(Length::Fixed(height + zoom_level));
}

void LayoutThemeMac::AdjustSliderThumbSize(ComputedStyle& style) const {
  float zoom_level = style.EffectiveZoom();
  if (style.EffectiveAppearance() == kSliderThumbHorizontalPart ||
      style.EffectiveAppearance() == kSliderThumbVerticalPart) {
    style.SetWidth(
        Length::Fixed(static_cast<int>(kSliderThumbWidth * zoom_level)));
    style.SetHeight(
        Length::Fixed(static_cast<int>(kSliderThumbHeight * zoom_level)));
  }
}

NSPopUpButtonCell* LayoutThemeMac::PopupButton() const {
  if (!popup_button_) {
    popup_button_.reset([[NSPopUpButtonCell alloc] initTextCell:@""
                                                      pullsDown:NO]);
    [popup_button_ setUsesItemFromMenu:NO];
    [popup_button_ setFocusRingType:NSFocusRingTypeExterior];
  }

  return popup_button_;
}

NSSearchFieldCell* LayoutThemeMac::Search() const {
  if (!search_) {
    search_.reset([[NSSearchFieldCell alloc] initTextCell:@""]);
    [search_ setBezelStyle:NSTextFieldRoundedBezel];
    [search_ setBezeled:YES];
    [search_ setEditable:YES];
    [search_ setFocusRingType:NSFocusRingTypeExterior];

    // Suppress NSSearchFieldCell's default placeholder text. Prior to OS10.11,
    // this is achieved by calling |setCenteredLook| with NO. In OS10.11 and
    // later, instead call |setPlaceholderString| with an empty string.
    // See https://crbug.com/752362.
    if (base::mac::IsAtMostOS10_10()) {
      SEL sel = @selector(setCenteredLook:);
      if ([search_ respondsToSelector:sel]) {
        BOOL bool_value = NO;
        NSMethodSignature* signature =
            [NSSearchFieldCell instanceMethodSignatureForSelector:sel];
        NSInvocation* invocation =
            [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:search_];
        [invocation setSelector:sel];
        [invocation setArgument:&bool_value atIndex:2];
        [invocation invoke];
      }
    } else {
      [search_ setPlaceholderString:@""];
    }
  }

  return search_;
}

NSTextFieldCell* LayoutThemeMac::TextField() const {
  if (!text_field_) {
    text_field_.reset([[BlinkTextFieldCell alloc] initTextCell:@""]);
    [text_field_ setBezeled:YES];
    [text_field_ setEditable:YES];
    [text_field_ setFocusRingType:NSFocusRingTypeExterior];
    [text_field_ setDrawsBackground:YES];
    [text_field_ setBackgroundColor:[NSColor whiteColor]];
  }

  return text_field_;
}

String LayoutThemeMac::DisplayNameForFile(const File& file) const {
  if (file.GetUserVisibility() == File::kIsUserVisible)
    return [[NSFileManager defaultManager] displayNameAtPath:file.GetPath()];
  return file.name();
}

NSView* FlippedView() {
  static NSView* view = [[BlinkFlippedView alloc] init];
  return view;
}

LayoutTheme& LayoutTheme::NativeTheme() {
  if (features::IsFormControlsRefreshEnabled()) {
    DEFINE_STATIC_REF(LayoutTheme, layout_theme,
                      (LayoutThemeMacRefresh::Create()));
    return *layout_theme;
  } else {
    DEFINE_STATIC_REF(LayoutTheme, layout_theme, (LayoutThemeMac::Create()));
    return *layout_theme;
  }
}

scoped_refptr<LayoutTheme> LayoutThemeMac::Create() {
  return base::AdoptRef(new LayoutThemeMac);
}

bool LayoutThemeMac::UsesTestModeFocusRingColor() const {
  return WebTestSupport::IsRunningWebTest() ||
         !Platform::Current()->GetSandboxSupport();
}

NSView* LayoutThemeMac::DocumentView() const {
  return FlippedView();
}

// Updates the control tint (a.k.a. active state) of |cell| (from |o|).  In the
// Chromium port, the layoutObject runs as a background process and controls'
// NSCell(s) lack a parent NSView. Therefore controls don't have their tint
// color updated correctly when the application is activated/deactivated.
// FocusController's setActive() is called when the application is
// activated/deactivated, which causes a paint invalidation at which time this
// code is called.
// This function should be called before drawing any NSCell-derived controls,
// unless you're sure it isn't needed.
void LayoutThemeMac::UpdateActiveState(NSCell* cell, const Node* node) {
  NSControlTint old_tint = [cell controlTint];
  NSControlTint tint = IsActive(node)
                           ? [NSColor currentControlTint]
                           : static_cast<NSControlTint>(NSClearControlTint);

  if (tint != old_tint)
    [cell setControlTint:tint];
}

String LayoutThemeMac::ExtraFullscreenStyleSheet() {
  // FIXME: Chromium may wish to style its default media controls differently in
  // fullscreen.
  return String();
}

String LayoutThemeMac::ExtraDefaultStyleSheet() {
  return LayoutTheme::ExtraDefaultStyleSheet() +
         UncompressResourceAsASCIIString(
             IDR_UASTYLE_THEME_INPUT_MULTIPLE_FIELDS_CSS) +
         UncompressResourceAsASCIIString(IDR_UASTYLE_THEME_MAC_CSS);
}

bool LayoutThemeMac::ThemeDrawsFocusRing(const ComputedStyle& style) const {
  if (ShouldUseFallbackTheme(style))
    return false;
  switch (style.EffectiveAppearance()) {
    case kCheckboxPart:
    case kRadioPart:
    case kPushButtonPart:
    case kSquareButtonPart:
    case kButtonPart:
    case kMenulistPart:
    case kSliderThumbHorizontalPart:
    case kSliderThumbVerticalPart:
      return true;

    // Actually, they don't support native focus rings, but this function
    // returns true for them in order to prevent Blink from drawing focus rings.
    // SliderThumb*Part have focus rings, and we don't need to draw two focus
    // rings for single slider.
    case kSliderHorizontalPart:
    case kSliderVerticalPart:
      return true;

    default:
      return false;
  }
}

bool LayoutThemeMac::ShouldUseFallbackTheme(const ComputedStyle& style) const {
  ControlPart part = style.EffectiveAppearance();
  if (part == kCheckboxPart || part == kRadioPart)
    return style.EffectiveZoom() != 1;
  return false;
}

// We don't use controlSizeForFont() for steppers because the stepper height
// should be equal to or less than the corresponding text field height,
static NSControlSize StepperControlSizeForFont(
    const FontDescription& font_description) {
  int font_size = font_description.ComputedPixelSize();
  if (font_size >= 27)
    return NSRegularControlSize;
  if (font_size >= 22)
    return NSSmallControlSize;
  return NSMiniControlSize;
}

NSControlSize LayoutThemeMac::ControlSizeFromPixelSize(
    const IntSize* sizes,
    const IntSize& min_zoomed_size,
    float zoom_factor) {
  if (min_zoomed_size.Width() >=
          static_cast<int>(sizes[NSRegularControlSize].Width() * zoom_factor) &&
      min_zoomed_size.Height() >=
          static_cast<int>(sizes[NSRegularControlSize].Height() * zoom_factor))
    return NSRegularControlSize;
  if (min_zoomed_size.Width() >=
          static_cast<int>(sizes[NSSmallControlSize].Width() * zoom_factor) &&
      min_zoomed_size.Height() >=
          static_cast<int>(sizes[NSSmallControlSize].Height() * zoom_factor))
    return NSSmallControlSize;
  return NSMiniControlSize;
}

static void SetControlSizeThemeMac(NSCell* cell,
                                   const IntSize* sizes,
                                   const IntSize& min_zoomed_size,
                                   float zoom_factor) {
  ControlSize size = LayoutThemeMac::ControlSizeFromPixelSize(
      sizes, min_zoomed_size, zoom_factor);
  // Only update if we have to, since AppKit does work even if the size is the
  // same.
  if (size != [cell controlSize])
    [cell setControlSize:(NSControlSize)size];
}

static void UpdateStates(NSCell* cell, ControlStates states) {
  // Hover state is not supported by Aqua.

  // Pressed state
  bool old_pressed = [cell isHighlighted];
  bool pressed = states & kPressedControlState;
  if (pressed != old_pressed)
    [cell setHighlighted:pressed];

  // Enabled state
  bool old_enabled = [cell isEnabled];
  bool enabled = states & kEnabledControlState;
  if (enabled != old_enabled)
    [cell setEnabled:enabled];

  // Checked and Indeterminate
  bool old_indeterminate = [cell state] == NSMixedState;
  bool indeterminate = (states & kIndeterminateControlState);
  bool checked = states & kCheckedControlState;
  bool old_checked = [cell state] == NSOnState;
  if (old_indeterminate != indeterminate || checked != old_checked)
    [cell setState:indeterminate ? NSMixedState
                                 : (checked ? NSOnState : NSOffState)];

  // Window inactive state does not need to be checked explicitly, since we
  // paint parented to a view in a window whose key state can be detected.
}

// Return a fake NSView whose sole purpose is to tell AppKit that it's flipped.
NSView* LayoutThemeMac::EnsuredView(const IntSize& size) {
  // Use a fake flipped view.
  static NSView* flipped_view = [[BlinkFlippedControl alloc] init];
  [flipped_view setFrameSize:NSSizeFromCGSize(CGSize(size))];

  return flipped_view;
}

LayoutUnit LayoutThemeMac::BaselinePositionAdjustment(
    const ComputedStyle& style) const {
  ControlPart part = style.EffectiveAppearance();
  if (part == kCheckboxPart || part == kRadioPart)
    return LayoutUnit(style.EffectiveZoom() * -2);
  return LayoutTheme::BaselinePositionAdjustment(style);
}

FontDescription LayoutThemeMac::ControlFont(
    ControlPart part,
    const FontDescription& font_description,
    float zoom_factor) const {
  using ::blink::ControlSizeForFont;
  switch (part) {
    case kPushButtonPart: {
      FontDescription result;
      result.SetIsAbsoluteSize(true);
      result.SetGenericFamily(FontDescription::kSerifFamily);

      NSFont* ns_font = [NSFont
          systemFontOfSize:[NSFont systemFontSizeForControlSize:
                                       ControlSizeForFont(font_description)]];
      result.FirstFamily().SetFamily(font_family_names::kSystemUi);
      result.SetComputedSize([ns_font pointSize] * zoom_factor);
      result.SetSpecifiedSize([ns_font pointSize] * zoom_factor);
      return result;
    }
    default:
      return LayoutTheme::ControlFont(part, font_description, zoom_factor);
  }
}

LengthSize LayoutThemeMac::GetControlSize(
    ControlPart part,
    const FontDescription& font_description,
    const LengthSize& zoomed_size,
    float zoom_factor) const {
  switch (part) {
    case kCheckboxPart:
      return CheckboxSize(font_description, zoomed_size, zoom_factor);
    case kRadioPart:
      return RadioSize(font_description, zoomed_size, zoom_factor);
    case kPushButtonPart:
      // Height is reset to auto so that specified heights can be ignored.
      return SizeFromFont(font_description,
                          LengthSize(zoomed_size.Width(), Length()),
                          zoom_factor, ButtonSizes());
    case kInnerSpinButtonPart:
      if (!zoomed_size.Width().IsIntrinsicOrAuto() &&
          !zoomed_size.Height().IsIntrinsicOrAuto())
        return zoomed_size;
      return SizeFromNSControlSize(StepperControlSizeForFont(font_description),
                                   zoomed_size, zoom_factor, StepperSizes());
    default:
      return zoomed_size;
  }
}

LengthSize LayoutThemeMac::MinimumControlSize(
    ControlPart part,
    const FontDescription& font_description,
    float zoom_factor,
    const ComputedStyle& style) const {
  switch (part) {
    case kSquareButtonPart:
    case kButtonPart:
      return LengthSize(style.MinWidth().Zoom(zoom_factor),
                        Length::Fixed(static_cast<int>(15 * zoom_factor)));
    case kInnerSpinButtonPart: {
      IntSize base = StepperSizes()[NSMiniControlSize];
      return LengthSize(
          Length::Fixed(static_cast<int>(base.Width() * zoom_factor)),
          Length::Fixed(static_cast<int>(base.Height() * zoom_factor)));
    }
    default:
      return LayoutTheme::MinimumControlSize(part, font_description,
                                             zoom_factor, style);
  }
}

LengthBox LayoutThemeMac::ControlPadding(
    ControlPart part,
    const FontDescription& font_description,
    const Length& zoomed_box_top,
    const Length& zoomed_box_right,
    const Length& zoomed_box_bottom,
    const Length& zoomed_box_left,
    float zoom_factor) const {
  switch (part) {
    case kPushButtonPart: {
      // Just use 8px.  AppKit wants to use 11px for mini buttons, but that
      // padding is just too large for real-world Web sites (creating a huge
      // necessary minimum width for buttons whose space is by definition
      // constrained, since we select mini only for small cramped environments.
      // This also guarantees the HTML <button> will match our rendering by
      // default, since we're using a consistent padding.
      const int padding = 8 * zoom_factor;
      return LengthBox(2, padding, 3, padding);
    }
    default:
      return LayoutTheme::ControlPadding(part, font_description, zoomed_box_top,
                                         zoomed_box_right, zoomed_box_bottom,
                                         zoomed_box_left, zoom_factor);
  }
}

LengthBox LayoutThemeMac::ControlBorder(ControlPart part,
                                        const FontDescription& font_description,
                                        const LengthBox& zoomed_box,
                                        float zoom_factor) const {
  switch (part) {
    case kSquareButtonPart:
      return LengthBox(0, zoomed_box.Right().Value(), 0,
                       zoomed_box.Left().Value());
    default:
      return LayoutTheme::ControlBorder(part, font_description, zoomed_box,
                                        zoom_factor);
  }
}

void LayoutThemeMac::AddVisualOverflowHelper(ControlPart part,
                                             ControlStates states,
                                             float zoom_factor,
                                             IntRect& zoomed_rect) const {
  BEGIN_BLOCK_OBJC_EXCEPTIONS
  switch (part) {
    case kCheckboxPart: {
      // We inflate the rect as needed to account for padding included in the
      // cell to accommodate the checkbox shadow" and the check.  We don't
      // consider this part of the bounds of the control in WebKit.
      NSCell* cell = Checkbox(states, zoomed_rect, zoom_factor);
      NSControlSize control_size = [cell controlSize];
      IntSize zoomed_size = CheckboxSizes()[control_size];
      zoomed_size.SetHeight(zoomed_size.Height() * zoom_factor);
      zoomed_size.SetWidth(zoomed_size.Width() * zoom_factor);
      zoomed_rect = InflateRect(zoomed_rect, zoomed_size,
                                CheckboxMargins(control_size), zoom_factor);
      break;
    }
    case kRadioPart: {
      // We inflate the rect as needed to account for padding included in the
      // cell to accommodate the radio button shadow".  We don't consider this
      // part of the bounds of the control in WebKit.
      NSCell* cell = Radio(states, zoomed_rect, zoom_factor);
      NSControlSize control_size = [cell controlSize];
      IntSize zoomed_size = RadioSizes()[control_size];
      zoomed_size.SetHeight(zoomed_size.Height() * zoom_factor);
      zoomed_size.SetWidth(zoomed_size.Width() * zoom_factor);
      zoomed_rect = InflateRect(zoomed_rect, zoomed_size,
                                RadioMargins(control_size), zoom_factor);
      break;
    }
    case kPushButtonPart:
    case kButtonPart: {
      NSButtonCell* cell = Button(part, states, zoomed_rect, zoom_factor);
      NSControlSize control_size = [cell controlSize];

      // We inflate the rect as needed to account for the Aqua button's shadow.
      if ([cell bezelStyle] == NSRoundedBezelStyle) {
        IntSize zoomed_size = ButtonSizes()[control_size];
        zoomed_size.SetHeight(zoomed_size.Height() * zoom_factor);
        // Buttons don't ever constrain width, so the zoomed width can just be
        // honored.
        zoomed_size.SetWidth(zoomed_rect.Width());
        zoomed_rect = InflateRect(zoomed_rect, zoomed_size,
                                  ButtonMargins(control_size), zoom_factor);
      }
      break;
    }
    case kInnerSpinButtonPart: {
      static const int kStepperMargin[4] = {0, 0, 0, 0};
      ControlSize control_size = ControlSizeFromPixelSize(
          StepperSizes(), zoomed_rect.Size(), zoom_factor);
      IntSize zoomed_size = StepperSizes()[control_size];
      zoomed_size.SetHeight(zoomed_size.Height() * zoom_factor);
      zoomed_size.SetWidth(zoomed_size.Width() * zoom_factor);
      zoomed_rect =
          InflateRect(zoomed_rect, zoomed_size, kStepperMargin, zoom_factor);
      break;
    }
    default:
      break;
  }
  END_BLOCK_OBJC_EXCEPTIONS
}

void LayoutThemeMac::AdjustControlPartStyle(ComputedStyle& style) {
  ControlPart part = style.EffectiveAppearance();
  switch (part) {
    case kCheckboxPart:
    case kInnerSpinButtonPart:
    case kRadioPart:
    case kPushButtonPart:
    case kSquareButtonPart:
    case kButtonPart: {
      // Border
      LengthBox border_box(style.BorderTopWidth(), style.BorderRightWidth(),
                           style.BorderBottomWidth(), style.BorderLeftWidth());
      border_box = ControlBorder(part, style.GetFont().GetFontDescription(),
                                 border_box, style.EffectiveZoom());
      if (border_box.Top().Value() !=
          static_cast<int>(style.BorderTopWidth())) {
        if (border_box.Top().Value())
          style.SetBorderTopWidth(border_box.Top().Value());
        else
          style.ResetBorderTop();
      }
      if (border_box.Right().Value() !=
          static_cast<int>(style.BorderRightWidth())) {
        if (border_box.Right().Value())
          style.SetBorderRightWidth(border_box.Right().Value());
        else
          style.ResetBorderRight();
      }
      if (border_box.Bottom().Value() !=
          static_cast<int>(style.BorderBottomWidth())) {
        style.SetBorderBottomWidth(border_box.Bottom().Value());
        if (border_box.Bottom().Value())
          style.SetBorderBottomWidth(border_box.Bottom().Value());
        else
          style.ResetBorderBottom();
      }
      if (border_box.Left().Value() !=
          static_cast<int>(style.BorderLeftWidth())) {
        style.SetBorderLeftWidth(border_box.Left().Value());
        if (border_box.Left().Value())
          style.SetBorderLeftWidth(border_box.Left().Value());
        else
          style.ResetBorderLeft();
      }

      // Padding
      LengthBox padding_box = ControlPadding(
          part, style.GetFont().GetFontDescription(), style.PaddingTop(),
          style.PaddingRight(), style.PaddingBottom(), style.PaddingLeft(),
          style.EffectiveZoom());
      if (!style.PaddingEqual(padding_box))
        style.SetPadding(padding_box);

      // Whitespace
      if (ControlRequiresPreWhiteSpace(part))
        style.SetWhiteSpace(EWhiteSpace::kPre);

      // Width / Height
      // The width and height here are affected by the zoom.
      LengthSize control_size = GetControlSize(
          part, style.GetFont().GetFontDescription(),
          LengthSize(style.Width(), style.Height()), style.EffectiveZoom());

      LengthSize min_control_size =
          MinimumControlSize(part, style.GetFont().GetFontDescription(),
                             style.EffectiveZoom(), style);

      // Only potentially set min-size to |control_size| for these parts.
      if (part == kCheckboxPart || part == kRadioPart)
        SetMinimumSize(style, &control_size, &min_control_size);
      else
        SetMinimumSize(style, nullptr, &min_control_size);

      if (control_size.Width() != style.Width())
        style.SetWidth(control_size.Width());
      if (control_size.Height() != style.Height())
        style.SetHeight(control_size.Height());

      // Font
      FontDescription control_font = ControlFont(
          part, style.GetFont().GetFontDescription(), style.EffectiveZoom());
      if (control_font != style.GetFont().GetFontDescription()) {
        // Reset our line-height
        style.SetLineHeight(ComputedStyleInitialValues::InitialLineHeight());

        // Now update our font.
        style.SetFontDescription(control_font);
      }
      break;
    }
    case kProgressBarPart:
      AdjustProgressBarBounds(style);
      break;
    default:
      break;
  }
}

// static
IntRect LayoutThemeMac::InflateRect(const IntRect& zoomed_rect,
                                    const IntSize& zoomed_size,
                                    const int* margins,
                                    float zoom_factor) {
  // Only do the inflation if the available width/height are too small.
  // Otherwise try to fit the glow/check space into the available box's
  // width/height.
  int width_delta = zoomed_rect.Width() -
                    (zoomed_size.Width() + margins[kLeftMargin] * zoom_factor +
                     margins[kRightMargin] * zoom_factor);
  int height_delta = zoomed_rect.Height() -
                     (zoomed_size.Height() + margins[kTopMargin] * zoom_factor +
                      margins[kBottomMargin] * zoom_factor);
  IntRect result(zoomed_rect);
  if (width_delta < 0) {
    result.SetX(result.X() - margins[kLeftMargin] * zoom_factor);
    result.SetWidth(result.Width() - width_delta);
  }
  if (height_delta < 0) {
    result.SetY(result.Y() - margins[kTopMargin] * zoom_factor);
    result.SetHeight(result.Height() - height_delta);
  }
  return result;
}

// static
IntRect LayoutThemeMac::InflateRectForFocusRing(const IntRect& rect) {
  // Just put a margin of 16 units around the rect. The UI elements that use
  // this don't appropriately scale their focus rings appropriately (e.g, paint
  // pickers), or switch to non-native widgets when scaled (e.g, check boxes
  // and radio buttons).
  const int kMargin = 16;
  IntRect result;
  result.SetX(rect.X() - kMargin);
  result.SetY(rect.Y() - kMargin);
  result.SetWidth(rect.Width() + 2 * kMargin);
  result.SetHeight(rect.Height() + 2 * kMargin);
  return result;
}

// Checkboxes

const IntSize* LayoutThemeMac::CheckboxSizes() {
  static const IntSize kSizes[3] = {IntSize(14, 14), IntSize(12, 12),
                                    IntSize(10, 10)};
  return kSizes;
}

const int* LayoutThemeMac::CheckboxMargins(NSControlSize control_size) {
  static const int kMargins[3][4] = {
      {3, 4, 4, 2},
      {4, 3, 3, 3},
      {4, 3, 3, 3},
  };
  return kMargins[control_size];
}

LengthSize LayoutThemeMac::CheckboxSize(const FontDescription& font_description,
                                        const LengthSize& zoomed_size,
                                        float zoom_factor) {
  // If the width and height are both specified, then we have nothing to do.
  if (!zoomed_size.Width().IsIntrinsicOrAuto() &&
      !zoomed_size.Height().IsIntrinsicOrAuto())
    return zoomed_size;

  // Use the font size to determine the intrinsic width of the control.
  return SizeFromFont(font_description, zoomed_size, zoom_factor,
                      CheckboxSizes());
}

NSButtonCell* LayoutThemeMac::Checkbox(ControlStates states,
                                       const IntRect& zoomed_rect,
                                       float zoom_factor) {
  static NSButtonCell* checkbox_cell;
  if (!checkbox_cell) {
    checkbox_cell = [[NSButtonCell alloc] init];
    [checkbox_cell setButtonType:NSSwitchButton];
    [checkbox_cell setTitle:nil];
    [checkbox_cell setAllowsMixedState:YES];
    [checkbox_cell setFocusRingType:NSFocusRingTypeExterior];
  }

  // Set the control size based off the rectangle we're painting into.
  SetControlSizeThemeMac(checkbox_cell, CheckboxSizes(), zoomed_rect.Size(),
                         zoom_factor);

  // Update the various states we respond to.
  UpdateStates(checkbox_cell, states);

  return checkbox_cell;
}

const IntSize* LayoutThemeMac::RadioSizes() {
  static const IntSize kSizes[3] = {IntSize(14, 15), IntSize(12, 13),
                                    IntSize(10, 10)};
  return kSizes;
}

const int* LayoutThemeMac::RadioMargins(NSControlSize control_size) {
  static const int kMargins[3][4] = {
      {2, 2, 4, 2},
      {3, 2, 3, 2},
      {1, 0, 2, 0},
  };
  return kMargins[control_size];
}

LengthSize LayoutThemeMac::RadioSize(const FontDescription& font_description,
                                     const LengthSize& zoomed_size,
                                     float zoom_factor) {
  // If the width and height are both specified, then we have nothing to do.
  if (!zoomed_size.Width().IsIntrinsicOrAuto() &&
      !zoomed_size.Height().IsIntrinsicOrAuto())
    return zoomed_size;

  // Use the font size to determine the intrinsic width of the control.
  return SizeFromFont(font_description, zoomed_size, zoom_factor, RadioSizes());
}

NSButtonCell* LayoutThemeMac::Radio(ControlStates states,
                                    const IntRect& zoomed_rect,
                                    float zoom_factor) {
  static NSButtonCell* radio_cell;
  if (!radio_cell) {
    radio_cell = [[NSButtonCell alloc] init];
    [radio_cell setButtonType:NSRadioButton];
    [radio_cell setTitle:nil];
    [radio_cell setFocusRingType:NSFocusRingTypeExterior];
  }

  // Set the control size based off the rectangle we're painting into.
  SetControlSizeThemeMac(radio_cell, RadioSizes(), zoomed_rect.Size(),
                         zoom_factor);

  // Update the various states we respond to.
  // Cocoa draws NSMixedState NSRadioButton as NSOnState so we don't want that.
  states &= ~kIndeterminateControlState;
  UpdateStates(radio_cell, states);

  return radio_cell;
}

// Buttons really only constrain height. They respect width.
const IntSize* LayoutThemeMac::ButtonSizes() {
  static const IntSize kSizes[3] = {IntSize(0, 21), IntSize(0, 18),
                                    IntSize(0, 15)};
  return kSizes;
}

const int* LayoutThemeMac::ButtonMargins(NSControlSize control_size) {
  static const int kMargins[3][4] = {
      {4, 6, 7, 6},
      {4, 5, 6, 5},
      {0, 1, 1, 1},
  };
  return kMargins[control_size];
}

static void SetUpButtonCell(NSButtonCell* cell,
                            ControlPart part,
                            ControlStates states,
                            const IntRect& zoomed_rect,
                            float zoom_factor) {
  // Set the control size based off the rectangle we're painting into.
  const IntSize* sizes = LayoutThemeMac::ButtonSizes();
  if (part == kSquareButtonPart ||
      zoomed_rect.Height() >
          LayoutThemeMac::ButtonSizes()[NSRegularControlSize].Height() *
              zoom_factor) {
    // Use the square button
    if ([cell bezelStyle] != NSShadowlessSquareBezelStyle)
      [cell setBezelStyle:NSShadowlessSquareBezelStyle];
  } else if ([cell bezelStyle] != NSRoundedBezelStyle)
    [cell setBezelStyle:NSRoundedBezelStyle];

  SetControlSizeThemeMac(cell, sizes, zoomed_rect.Size(), zoom_factor);

  // Update the various states we respond to.
  UpdateStates(cell, states);
}

NSButtonCell* LayoutThemeMac::Button(ControlPart part,
                                     ControlStates states,
                                     const IntRect& zoomed_rect,
                                     float zoom_factor) {
  static NSButtonCell* cell = nil;
  if (!cell) {
    cell = [[NSButtonCell alloc] init];
    [cell setTitle:nil];
    [cell setButtonType:NSMomentaryPushInButton];
  }
  SetUpButtonCell(cell, part, states, zoomed_rect, zoom_factor);
  return cell;
}

const IntSize* LayoutThemeMac::StepperSizes() {
  static const IntSize kSizes[3] = {IntSize(19, 27), IntSize(15, 22),
                                    IntSize(13, 15)};
  return kSizes;
}

}  // namespace blink