summaryrefslogtreecommitdiffstats
path: root/src/gui/kernel/qwidget_mac.mm
blob: 00f658e1fad56e35548b89f9b2e72cdf4af62387 (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
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights.  These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/****************************************************************************
**
** Copyright (c) 2007-2008, Apple, Inc.
**
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
**   * Redistributions of source code must retain the above copyright notice,
**     this list of conditions and the following disclaimer.
**
**   * Redistributions in binary form must reproduce the above copyright notice,
**     this list of conditions and the following disclaimer in the documentation
**     and/or other materials provided with the distribution.
**
**   * Neither the name of Apple, Inc. nor the names of its contributors
**     may be used to endorse or promote products derived from this software
**     without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
****************************************************************************/
//#define QT_RASTER_PAINTENGINE

#include <private/qt_mac_p.h>
#include <private/qeventdispatcher_mac_p.h>

#include "qapplication.h"
#include "qapplication_p.h"
#include "qbitmap.h"
#include "qcursor.h"
#include "qdesktopwidget.h"
#include "qevent.h"
#include "qimage.h"
#include "qlayout.h"
#include "qmenubar.h"
#include <private/qbackingstore_p.h>
#ifdef QT_RASTER_PAINTENGINE
# include <private/qpaintengine_raster_p.h>
#endif
#include <private/qwindowsurface_mac_p.h>
#include <private/qpaintengine_mac_p.h>
#include "qpainter.h"
#include "qstyle.h"
#include "qtimer.h"
#include "qfocusframe.h"
#include "qdebug.h"
#include <private/qmainwindowlayout_p.h>

#include <private/qabstractscrollarea_p.h>
#include <qabstractscrollarea.h>
#include <ApplicationServices/ApplicationServices.h>
#include <limits.h>
#include <private/qt_cocoa_helpers_mac_p.h>
#include <private/qcocoaview_mac_p.h>
#include <private/qcocoawindow_mac_p.h>
#include <private/qcocoawindowdelegate_mac_p.h>
#include <private/qcocoapanel_mac_p.h>

#include "qwidget_p.h"
#include "qdnd_p.h"
#include <QtGui/qgraphicsproxywidget.h>

QT_BEGIN_NAMESPACE

#define XCOORD_MAX 16383
#define WRECT_MAX 8191

#ifndef QT_MAC_USE_COCOA

extern "C" {
    extern OSStatus _HIViewScrollRectWithOptions(HIViewRef, const HIRect *, CGFloat, CGFloat,
                                                 OptionBits);
}
#define kHIViewScrollRectAdjustInvalid 1
#define kHIViewScrollRectDontInvalidateRevealedArea 2
#endif


/*****************************************************************************
  QWidget debug facilities
 *****************************************************************************/
//#define DEBUG_WINDOW_RGNS
//#define DEBUG_WINDOW_CREATE
//#define DEBUG_WINDOW_STATE
//#define DEBUG_WIDGET_PAINT

/*****************************************************************************
  QWidget globals
 *****************************************************************************/
#ifndef QT_MAC_USE_COCOA
typedef QHash<Qt::WindowFlags, WindowGroupRef> WindowGroupHash;
Q_GLOBAL_STATIC(WindowGroupHash, qt_mac_window_groups)
const UInt32 kWidgetCreatorQt = kEventClassQt;
enum {
    kWidgetPropertyQWidget = 'QWId' //QWidget *
};
#endif

static bool qt_mac_raise_process = true;
static OSWindowRef qt_root_win = 0;
QWidget *mac_mouse_grabber = 0;
QWidget *mac_keyboard_grabber = 0;

#ifndef QT_MAC_USE_COCOA
#ifdef QT_NAMESPACE

// produce the string "com.trolltech.qt-namespace.widget", where "namespace" is the contents of QT_NAMESPACE.
#define SS(x) #x
#define S0(x) SS(x)
#define S "com.trolltech.qt-" S0(QT_NAMESPACE) ".widget"

static CFStringRef kObjectQWidget = CFSTR(S);

#undef SS
#undef S0
#undef S

#else
static CFStringRef kObjectQWidget = CFSTR("com.trolltech.qt.widget");
#endif // QT_NAMESPACE
#endif // QT_MAC_USE_COCOA

/*****************************************************************************
  Externals
 *****************************************************************************/
extern QWidget *qt_mac_modal_blocked(QWidget *); //qapplication_mac.mm
extern void qt_event_request_activate(QWidget *); //qapplication_mac.mm
extern bool qt_event_remove_activate(); //qapplication_mac.mm
extern void qt_mac_event_release(QWidget *w); //qapplication_mac.mm
extern void qt_event_request_showsheet(QWidget *); //qapplication_mac.mm
extern void qt_event_request_window_change(QWidget *); //qapplication_mac.mm
extern QPointer<QWidget> qt_mouseover; //qapplication_mac.mm
extern IconRef qt_mac_create_iconref(const QPixmap &); //qpixmap_mac.cpp
extern void qt_mac_set_cursor(const QCursor *, const QPoint &); //qcursor_mac.mm
extern void qt_mac_update_cursor(); //qcursor_mac.mm
extern bool qt_nograb();
extern CGImageRef qt_mac_create_cgimage(const QPixmap &, bool); //qpixmap_mac.cpp
extern RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
extern QRegion qt_mac_convert_mac_region(RgnHandle rgn); //qregion_mac.cpp

/*****************************************************************************
  QWidget utility functions
 *****************************************************************************/
void Q_GUI_EXPORT qt_mac_set_raise_process(bool b) { qt_mac_raise_process = b; }
static QSize qt_mac_desktopSize()
{
    int w = 0, h = 0;
    CGDisplayCount cg_count;
    CGGetActiveDisplayList(0, 0, &cg_count);
    QVector<CGDirectDisplayID> displays(cg_count);
    CGGetActiveDisplayList(cg_count, displays.data(), &cg_count);
    Q_ASSERT(cg_count == (CGDisplayCount)displays.size());
    for(int i = 0; i < (int)cg_count; ++i) {
        CGRect r = CGDisplayBounds(displays.at(i));
        w = qMax<int>(w, qRound(r.origin.x + r.size.width));
        h = qMax<int>(h, qRound(r.origin.y + r.size.height));
    }
    return QSize(w, h);
}

#ifdef QT_MAC_USE_COCOA
static NSDrawer *qt_mac_drawer_for(const QWidget *widget)
{
    // This only goes one level below the content view so start with the window.
    // This works fine for straight Qt stuff, but runs into problems if we are
    // embedding, but if that's the case, they probably want to be using
    // NSDrawer directly.
    NSView *widgetView = reinterpret_cast<NSView *>(widget->window()->winId());
    NSArray *windows = [NSApp windows];
    for (NSWindow *window in windows) {
        NSArray *drawers = [window drawers];
        for (NSDrawer *drawer in drawers) {
            NSArray *views = [[drawer contentView] subviews];
            for (NSView *view in views) {
                if (view == widgetView)
                    return drawer;
            }
        }
    }
    return 0;
}
#endif

static void qt_mac_destructView(OSViewRef view)
{
#ifdef QT_MAC_USE_COCOA
    [view removeFromSuperview];
    [view release];
#else
    HIViewRemoveFromSuperview(view);
    CFRelease(view);
#endif
}

static void qt_mac_destructWindow(OSWindowRef window)
{
#ifdef QT_MAC_USE_COCOA
    if ([window isVisible] && [window isSheet]){
        [NSApp endSheet:window];
        [window orderOut:window];
    }

    [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForWindow:window];
    [window release];
#else
    // Remove property to clean up memory:
    RemoveWindowProperty(window, kWidgetCreatorQt, kWidgetPropertyQWidget);
    CFRelease(window);
#endif
}

static void qt_mac_destructDrawer(NSDrawer *drawer)
{
#ifdef QT_MAC_USE_COCOA
    [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForDrawer:drawer];
    [drawer release];
#else
    Q_UNUSED(drawer);
#endif
}

bool qt_mac_can_clickThrough(const QWidget *w)
{
    static int qt_mac_carbon_clickthrough = -1;
    if (qt_mac_carbon_clickthrough < 0)
        qt_mac_carbon_clickthrough = !qgetenv("QT_MAC_NO_COCOA_CLICKTHROUGH").isEmpty();
    bool ret = !qt_mac_carbon_clickthrough;
    for ( ; w; w = w->parentWidget()) {
        if (w->testAttribute(Qt::WA_MacNoClickThrough)) {
            ret = false;
            break;
        }
    }
    return ret;
}

bool qt_mac_is_macsheet(const QWidget *w)
{
    if (!w)
        return false;

    Qt::WindowModality modality = w->windowModality();
    if (modality == Qt::ApplicationModal)
        return false;
    return w->parentWidget() && (modality == Qt::WindowModal || w->windowType() == Qt::Sheet);
}

bool qt_mac_is_macdrawer(const QWidget *w)
{
    return (w && w->parentWidget() && w->windowType() == Qt::Drawer);
}

bool qt_mac_set_drawer_preferred_edge(QWidget *w, Qt::DockWidgetArea where) //users of Qt for Mac OS X can use this..
{
    if(!qt_mac_is_macdrawer(w))
        return false;

#if QT_MAC_USE_COCOA
    NSDrawer *drawer = qt_mac_drawer_for(w);
    if (!drawer)
        return false;
	NSRectEdge	edge;
    if (where & Qt::LeftDockWidgetArea)
        edge = NSMinXEdge;
    else if (where & Qt::RightDockWidgetArea)
        edge = NSMaxXEdge;
    else if (where & Qt::TopDockWidgetArea)
		edge = NSMaxYEdge;
    else if (where & Qt::BottomDockWidgetArea)
        edge = NSMinYEdge;
    else
        return false;

    if (edge == [drawer preferredEdge]) //no-op
        return false;

    if (w->isVisible()) {
	    [drawer close];
	    [drawer openOnEdge:edge];
	}
	[drawer setPreferredEdge:edge];
#else
    OSWindowRef window = qt_mac_window_for(w);
    OptionBits edge;
    if(where & Qt::LeftDockWidgetArea)
        edge = kWindowEdgeLeft;
    else if(where & Qt::RightDockWidgetArea)
        edge = kWindowEdgeRight;
    else if(where & Qt::TopDockWidgetArea)
        edge = kWindowEdgeTop;
    else if(where & Qt::BottomDockWidgetArea)
        edge = kWindowEdgeBottom;
    else
        return false;

    if(edge == GetDrawerPreferredEdge(window)) //no-op
        return false;

    //do it
    SetDrawerPreferredEdge(window, edge);
    if(w->isVisible()) {
        CloseDrawer(window, false);
        OpenDrawer(window, edge, true);
    }
#endif
    return true;
}

#ifndef QT_MAC_USE_COCOA
Q_GUI_EXPORT
#endif
QPoint qt_mac_posInWindow(const QWidget *w)
{
    QPoint ret = w->data->wrect.topLeft();
    while(w && !w->isWindow()) {
        ret += w->pos();
        w =  w->parentWidget();
    }
    return ret;
}

//find a QWidget from a OSWindowRef
QWidget *qt_mac_find_window(OSWindowRef window)
{
#ifdef QT_MAC_USE_COCOA
    return [window QT_MANGLE_NAMESPACE(qt_qwidget)];
#else
    if(!window)
        return 0;

    QWidget *ret;
    if(GetWindowProperty(window, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(ret), 0, &ret) == noErr)
        return ret;
    return 0;
#endif
}

inline static void qt_mac_set_fullscreen_mode(bool b)
{
    extern bool qt_mac_app_fullscreen; //qapplication_mac.cpp
    if(qt_mac_app_fullscreen == b)
        return;
    qt_mac_app_fullscreen = b;
#if QT_MAC_USE_COCOA
    if(b)
        SetSystemUIMode(kUIModeAllHidden, kUIOptionAutoShowMenuBar);
    else
        SetSystemUIMode(kUIModeNormal, 0);
#else
    if(b)
        HideMenuBar();
    else
        ShowMenuBar();
#endif
}

Q_GUI_EXPORT OSViewRef qt_mac_nativeview_for(const QWidget *w)
{
    return reinterpret_cast<OSViewRef>(w->data->winid);
}

Q_GUI_EXPORT OSViewRef qt_mac_get_contentview_for(OSWindowRef w)
{
#ifdef QT_MAC_USE_COCOA
    return [w contentView];
#else
    HIViewRef contentView = 0;
    OSStatus err = GetRootControl(w, &contentView);  // Returns the window's content view (Apple QA1214)
    if (err == errUnknownControl) {
        contentView = HIViewGetRoot(w);
    } else if (err != noErr) {
        qWarning("Qt:Could not get content or root view of window! %s:%d [%ld]",
                 __FILE__, __LINE__, err);
    }
    return contentView;
#endif
}

bool qt_mac_sendMacEventToWidget(QWidget *widget, EventRef ref)
{
    return widget->macEvent(0, ref);
}

Q_GUI_EXPORT OSWindowRef qt_mac_window_for(OSViewRef view)
{
#ifdef QT_MAC_USE_COCOA
    if (view)
        return [view window];
    return 0;
#else
    return HIViewGetWindow(view);
#endif
}

static bool qt_isGenuineQWidget(OSViewRef ref)
{
#ifdef QT_MAC_USE_COCOA
    return [ref isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]];
#else
    return HIObjectIsOfClass(HIObjectRef(ref), kObjectQWidget);
#endif
}

bool qt_isGenuineQWidget(const QWidget *window)
{
    return window && qt_isGenuineQWidget(OSViewRef(window->winId()));
}

Q_GUI_EXPORT OSWindowRef qt_mac_window_for(const QWidget *w)
{
    OSViewRef hiview = qt_mac_nativeview_for(w);
    if (hiview){
        OSWindowRef window = qt_mac_window_for(hiview);
        if (!window && qt_isGenuineQWidget(hiview)) {
            QWidget *myWindow = w->window();
            // This is a workaround for NSToolbar. When a widget is hidden
            // by clicking the toolbar button, Cocoa reparents the widgets
            // to another window (but Qt doesn't know about it).
            // When we start showing them, it reparents back,
            // but at this point it's window is nil, but the window it's being brought
            // into (the Qt one) is for sure created.
            // This stops the hierarchy moving under our feet.
            if (myWindow != w && qt_mac_window_for(qt_mac_nativeview_for(myWindow)))
                return qt_mac_window_for(qt_mac_nativeview_for(myWindow));

            myWindow->d_func()->createWindow_sys();
            // Reget the hiview since the "create window could potentially move the view (I guess).
            hiview = qt_mac_nativeview_for(w);
            window = qt_mac_window_for(hiview);
        }
        return window;
    }
    return 0;
}
#ifndef QT_MAC_USE_COCOA
/*  Checks if the current group is a 'stay on top' group. If so, the
    group gets removed from the hash table */
static void qt_mac_release_stays_on_top_group(WindowGroupRef group)
{
    for (WindowGroupHash::iterator it = qt_mac_window_groups()->begin(); it != qt_mac_window_groups()->end(); ++it) {
        if (it.value() == group) {
            qt_mac_window_groups()->remove(it.key());
            return;
        }
    }
}

/* Use this function instead of ReleaseWindowGroup, this will be sure to release the
   stays on top window group (created with qt_mac_get_stays_on_top_group below) */
static void qt_mac_release_window_group(WindowGroupRef group)
{
    ReleaseWindowGroup(group);
    if (GetWindowGroupRetainCount(group) == 0)
        qt_mac_release_stays_on_top_group(group);
}
#define ReleaseWindowGroup(x) Are you sure you wanted to do that? (you wanted qt_mac_release_window_group)

SInt32 qt_mac_get_group_level(WindowClass wclass)
{
    SInt32 group_level;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
        CGWindowLevel tmpLevel;
        GetWindowGroupLevelOfType(GetWindowGroupOfClass(wclass), kWindowGroupLevelActive, &tmpLevel);
        group_level = tmpLevel;
    } else
#endif
    {
        GetWindowGroupLevel(GetWindowGroupOfClass(wclass), &group_level);
    }
    return group_level;
}
#endif

#ifndef QT_MAC_USE_COCOA
static void qt_mac_set_window_group(OSWindowRef window, Qt::WindowFlags flags, int level)
{
    WindowGroupRef group = 0;
    if (qt_mac_window_groups()->contains(flags)) {
        group = qt_mac_window_groups()->value(flags);
        RetainWindowGroup(group);
    } else {
        CreateWindowGroup(kWindowActivationScopeNone, &group);
        SetWindowGroupLevel(group, level);
        SetWindowGroupParent(group, GetWindowGroupOfClass(kAllWindowClasses));
        qt_mac_window_groups()->insert(flags, group);
    }
    SetWindowGroup(window, group);
}

inline static void qt_mac_set_window_group_to_stays_on_top(OSWindowRef window, Qt::WindowType type)
{
    // We create one static stays on top window group so that
    // all stays on top (aka popups) will fall into the same
    // group and be able to be raise()'d with releation to one another (from
    // within the same window group).
    qt_mac_set_window_group(window, type|Qt::WindowStaysOnTopHint, qt_mac_get_group_level(kOverlayWindowClass));
}

inline static void qt_mac_set_window_group_to_tooltip(OSWindowRef window)
{
    // Since new groups are created for 'stays on top' windows, the
    // same must be done for tooltips. Otherwise, tooltips would be drawn
    // below 'stays on top' widgets even tough they are on the same level.
    // Also, add 'two' to the group level to make sure they also get on top of popups.
    qt_mac_set_window_group(window, Qt::ToolTip, qt_mac_get_group_level(kHelpWindowClass)+2);
}

inline static void qt_mac_set_window_group_to_popup(OSWindowRef window)
{
    // In Qt, a popup is seen as a 'stay on top' window.
    // Since new groups are created for 'stays on top' windows, the
    // same must be done for popups. Otherwise, popups would be drawn
    // below 'stays on top' windows. Add 1 to get above pure stay-on-top windows.
    qt_mac_set_window_group(window, Qt::Popup, qt_mac_get_group_level(kOverlayWindowClass)+1);
}
#endif

inline static bool updateRedirectedToGraphicsProxyWidget(QWidget *widget, const QRect &rect)
{
    if (!widget)
        return false;

#ifndef QT_NO_GRAPHICSVIEW
    QWidget *tlw = widget->window();
    QWExtra *extra = qt_widget_private(tlw)->extra;
    if (extra && extra->proxyWidget) {
        extra->proxyWidget->update(rect.translated(widget->mapTo(tlw, QPoint())));
        return true;
    }
#endif

    return false;
}

inline static bool updateRedirectedToGraphicsProxyWidget(QWidget *widget, const QRegion &rgn)
{
    if (!widget)
        return false;

#ifndef QT_NO_GRAPHICSVIEW
    QWidget *tlw = widget->window();
    QWExtra *extra = qt_widget_private(tlw)->extra;
    if (extra && extra->proxyWidget) {
        const QPoint offset(widget->mapTo(tlw, QPoint()));
        const QVector<QRect> rects = rgn.rects();
        for (int i = 0; i < rects.size(); ++i)
            extra->proxyWidget->update(rects.at(i).translated(offset));
        return true;
    }
#endif

    return false;
}

void QWidgetPrivate::macUpdateIsOpaque()
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;
#ifndef QT_MAC_USE_COCOA
    HIViewFeatures bits;
    HIViewRef hiview = qt_mac_nativeview_for(q);
    HIViewGetFeatures(hiview, &bits);
    if ((bits & kHIViewIsOpaque) == isOpaque)
        return;
    if (isOpaque) {
        HIViewChangeFeatures(hiview, kHIViewIsOpaque, 0);
    } else {
        HIViewChangeFeatures(hiview, 0, kHIViewIsOpaque);
    }
    if (q->isVisible())
        HIViewReshapeStructure(qt_mac_nativeview_for(q));
#else
    if (isRealWindow() && !q->testAttribute(Qt::WA_MacBrushedMetal)) {
        bool opaque = isOpaque;
        if (extra && extra->imageMask)
            opaque = false; // we are never opaque when we have a mask.
        [qt_mac_window_for(q) setOpaque:opaque];
    }
#endif
}
#ifdef QT_MAC_USE_COCOA
static OSWindowRef qt_mac_create_window(QWidget *widget, WindowClass wclass,
                                        NSUInteger wattr, const QRect &crect)
{
    // Determine if we need to add in our "custom window" attribute. Cocoa is rather clever
    // in deciding if we need the maximize button or not (i.e., it's resizeable, so you
    // must need a maximize button). So, the only buttons we have control over are the
    // close and minimize buttons. If someone wants to customize and NOT have the maximize
    // button, then we have to do our hack. We only do it for these cases because otherwise
    // the window looks different when activated. This "QtMacCustomizeWindow" attribute is
    // intruding on a public space and WILL BREAK in the future.
    // One can hope that there is a more public API available by that time.
    Qt::WindowFlags flags = widget ? widget->windowFlags() : Qt::WindowFlags(0);
    if ((flags & Qt::CustomizeWindowHint)) {
        if ((flags & (Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint
                      | Qt::WindowMinimizeButtonHint | Qt::WindowTitleHint))
            && !(flags & Qt::WindowMaximizeButtonHint))
            wattr |= QtMacCustomizeWindow;
    }

    // If we haven't created the desktop widget, you have to pass the rectangle
    // in "cocoa coordinates" (i.e., top points to the lower left coordinate).
    // Otherwise, we do the conversion for you. Since we are the only ones that
    // create the desktop widget, this is OK (but confusing).
    NSRect geo = NSMakeRect(crect.left(),
                            (qt_root_win != 0) ? flipYCoordinate(crect.bottom() + 1) : crect.top(),
                            crect.width(), crect.height());
    QMacCocoaAutoReleasePool pool;
    OSWindowRef window;
    switch (wclass) {
    case kMovableModalWindowClass:
    case kModalWindowClass:
    case kSheetWindowClass:
    case kFloatingWindowClass:
    case kOverlayWindowClass:
    case kHelpWindowClass: {
        NSPanel *panel;
        BOOL needFloating = NO;
        BOOL worksWhenModal = widget && (widget->windowType() == Qt::Popup);
        // Add in the extra flags if necessary.
        switch (wclass) {
        case kSheetWindowClass:
            wattr |= NSDocModalWindowMask;
            break;
        case kFloatingWindowClass:
        case kHelpWindowClass:
            needFloating = YES;
            wattr |= NSUtilityWindowMask;
            break;
        default:
            break;
        }
        panel = [[QT_MANGLE_NAMESPACE(QCocoaPanel) alloc] QT_MANGLE_NAMESPACE(qt_initWithQWidget):widget contentRect:geo styleMask:wattr];
        [panel setFloatingPanel:needFloating];
        [panel setWorksWhenModal:worksWhenModal];
        window = panel;
        break;
    }
    case kDrawerWindowClass: {
        NSDrawer *drawer = [[NSDrawer alloc] initWithContentSize:geo.size preferredEdge:NSMinXEdge];
        [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] becomeDelegateForDrawer:drawer widget:widget];
        QWidget *parentWidget = widget->parentWidget();
        if (parentWidget)
            [drawer setParentWindow:qt_mac_window_for(parentWidget)];
        [drawer setLeadingOffset:0.0];
        [drawer setTrailingOffset:25.0];
        window = [[drawer contentView] window];  // Just to make sure we actually return a window
        break;
    }
    default:
        window = [[QT_MANGLE_NAMESPACE(QCocoaWindow) alloc] QT_MANGLE_NAMESPACE(qt_initWithQWidget):widget contentRect:geo styleMask:wattr];
        break;
    }
    qt_syncCocoaTitleBarButtons(window, widget);
    return window;
}
#else
static OSWindowRef qt_mac_create_window(QWidget *, WindowClass wclass, WindowAttributes wattr,
                                        const QRect &crect)
{
    OSWindowRef window;
    Rect geo;
    SetRect(&geo, crect.left(), crect.top(), crect.right() + 1, crect.bottom() + 1);
    OSStatus err;
    if(geo.right <= geo.left)		geo.right = geo.left + 1;
    if(geo.bottom <= geo.top)		geo.bottom = geo.top + 1;
    Rect null_rect;
	SetRect(&null_rect, 0, 0, 1, 1);
    err = CreateNewWindow(wclass, wattr, &null_rect, &window);
    if(err == noErr) {
        err = SetWindowBounds(window, kWindowContentRgn, &geo);
        if(err != noErr)
            qWarning("QWidget: Internal error (%s:%d)", __FILE__, __LINE__);
    }
    return window;
}

// window events
static EventTypeSpec window_events[] = {
    { kEventClassWindow, kEventWindowClose },
    { kEventClassWindow, kEventWindowExpanded },
    { kEventClassWindow, kEventWindowZoomed },
    { kEventClassWindow, kEventWindowCollapsed },
    { kEventClassWindow, kEventWindowToolbarSwitchMode },
    { kEventClassWindow, kEventWindowProxyBeginDrag },
    { kEventClassWindow, kEventWindowProxyEndDrag },
    { kEventClassWindow, kEventWindowResizeCompleted },
    { kEventClassWindow, kEventWindowBoundsChanging },
    { kEventClassWindow, kEventWindowBoundsChanged },
    { kEventClassWindow, kEventWindowGetRegion },
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    { kEventClassWindow, kEventWindowGetClickModality },
#endif
    { kEventClassWindow, kEventWindowTransitionCompleted },
    { kEventClassMouse, kEventMouseDown }
};
static EventHandlerUPP mac_win_eventUPP = 0;
static void cleanup_win_eventUPP()
{
    DisposeEventHandlerUPP(mac_win_eventUPP);
    mac_win_eventUPP = 0;
}
static const EventHandlerUPP make_win_eventUPP()
{
    if(mac_win_eventUPP)
        return mac_win_eventUPP;
    qAddPostRoutine(cleanup_win_eventUPP);
    return mac_win_eventUPP = NewEventHandlerUPP(QWidgetPrivate::qt_window_event);
}
OSStatus QWidgetPrivate::qt_window_event(EventHandlerCallRef er, EventRef event, void *)
{
    QScopedLoopLevelCounter loopLevelCounter(qApp->d_func()->threadData);
    bool handled_event = true;
    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
    switch(eclass) {
    case kEventClassWindow: {
        WindowRef wid = 0;
        GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
                          sizeof(WindowRef), 0, &wid);
        QWidget *widget = qt_mac_find_window(wid);
        if(!widget) {
            handled_event = false;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
        } else if(ekind == kEventWindowGetClickModality) {
            // Carbon will send us kEventWindowGetClickModality before every
            // mouse press / release event. By returning 'true', we tell Carbon
            // that we would like the event target to receive the mouse event even
            // if the target is modally shaddowed. In Qt, this makes sense when we
            // e.g. have a popup showing, as the popup will grab the event
            // and perhaps use it to close itself.
            // By also setting the current modal window back into the event, we
            // help Carbon determining which window is supposed to be raised.
            handled_event = qApp->activePopupWidget() ? true : false;
#endif
        } else if(ekind == kEventWindowClose) {
            widget->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
            QMenuBar::macUpdateMenuBar();
        } else if (ekind == kEventWindowTransitionCompleted) {
            WindowTransitionAction transitionAction;
            GetEventParameter(event, kEventParamWindowTransitionAction, typeWindowTransitionAction,
                              0, sizeof(transitionAction), 0, &transitionAction);
            if (transitionAction == kWindowHideTransitionAction)
                widget->hide();
        } else if(ekind == kEventWindowExpanded) {
            Qt::WindowStates currState = Qt::WindowStates(widget->data->window_state);
            Qt::WindowStates newState = currState;
            if (currState & Qt::WindowMinimized)
                newState &= ~Qt::WindowMinimized;
            if (!(currState & Qt::WindowActive))
                newState |= Qt::WindowActive;
            if (newState != currState) {
                // newState will differ from currState if the window
                // was expanded after clicking on the jewels (as opposed
                // to calling QWidget::setWindowState)
                widget->data->window_state = newState;
                QWindowStateChangeEvent e(currState);
                QApplication::sendSpontaneousEvent(widget, &e);
            }

            QShowEvent qse;
            QApplication::sendSpontaneousEvent(widget, &qse);
        } else if(ekind == kEventWindowZoomed) {
            WindowPartCode windowPart;
            GetEventParameter(event, kEventParamWindowPartCode,
                              typeWindowPartCode, 0, sizeof(windowPart), 0, &windowPart);
            if(windowPart == inZoomIn && widget->isMaximized()) {

                widget->data->window_state = widget->data->window_state & ~Qt::WindowMaximized;
                QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state | Qt::WindowMaximized));
                QApplication::sendSpontaneousEvent(widget, &e);
            } else if(windowPart == inZoomOut && !widget->isMaximized()) {
                widget->data->window_state = widget->data->window_state | Qt::WindowMaximized;
                QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state
                                                           & ~Qt::WindowMaximized));
                QApplication::sendSpontaneousEvent(widget, &e);
            }
            extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
            qt_button_down = 0;
        } else if(ekind == kEventWindowCollapsed) {
            if (!widget->isMinimized()) {
                widget->data->window_state = widget->data->window_state | Qt::WindowMinimized;
                QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state & ~Qt::WindowMinimized));
                QApplication::sendSpontaneousEvent(widget, &e);
            }

            // Deactivate this window:
            if (widget->isActiveWindow() && !(widget->windowType() == Qt::Popup)) {
                QWidget *w = 0;
                if (widget->parentWidget())
                    w = widget->parentWidget()->window();
                if (!w || (!w->isVisible() && !w->isMinimized())) {
                    for (WindowPtr wp = GetFrontWindowOfClass(kDocumentWindowClass, true);
                        wp; wp = GetNextWindowOfClass(wp, kDocumentWindowClass, true)) {
                        if ((w = qt_mac_find_window(wp)))
                            break;
                    }
                }
                if(!(w && w->isVisible() && !w->isMinimized()))
                    qApp->setActiveWindow(0);
            }

            //we send a hide to be like X11/Windows
            QEvent e(QEvent::Hide);
            QApplication::sendSpontaneousEvent(widget, &e);
            extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
            qt_button_down = 0;
        } else if(ekind == kEventWindowToolbarSwitchMode) {
            QToolBarChangeEvent ev(!(GetCurrentKeyModifiers() & cmdKey));
            QApplication::sendSpontaneousEvent(widget, &ev);
            HIToolbarRef toolbar;
            if (GetWindowToolbar(wid, &toolbar) == noErr) {
                if (toolbar) {
                    // Let HIToolbar do its thang, but things like the OpenGL context
                    // needs to know about it.
                    CallNextEventHandler(er, event);
                    qt_event_request_window_change(widget);
                    widget->data->fstrut_dirty = true;
                }
            }
        } else if(ekind == kEventWindowGetRegion) {
            WindowRef window;
            GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
                              sizeof(window), 0, &window);
            WindowRegionCode wcode;
            GetEventParameter(event, kEventParamWindowRegionCode, typeWindowRegionCode, 0,
                              sizeof(wcode), 0, &wcode);
            if (wcode != kWindowOpaqueRgn){
                // If the region is kWindowOpaqueRgn, don't call next
                // event handler cause this will make the shadow of
                // masked windows become offset. Unfortunately, we're not sure why.
                CallNextEventHandler(er, event);
            }
			RgnHandle rgn;
            GetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, 0,
                              sizeof(rgn), 0, &rgn);

            if(QWidgetPrivate::qt_widget_rgn(qt_mac_find_window(window), wcode, rgn, false))
                SetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, sizeof(rgn), &rgn);
        } else if(ekind == kEventWindowProxyBeginDrag) {
            QIconDragEvent e;
            QApplication::sendSpontaneousEvent(widget, &e);
        } else if(ekind == kEventWindowResizeCompleted) {
            // Create a mouse up event, since such an event is not send by carbon to the
            // application event handler (while a mouse down <b>is</b> on kEventWindowResizeStarted)
            EventRef mouseUpEvent;
            CreateEvent(0, kEventClassMouse, kEventMouseUp, 0, kEventAttributeUserEvent, &mouseUpEvent);
            UInt16 mbutton = kEventMouseButtonPrimary;
            SetEventParameter(mouseUpEvent, kEventParamMouseButton, typeMouseButton, sizeof(mbutton), &mbutton);
            WindowRef window;
            GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0, sizeof(window), 0, &window);
            Rect dragRect;
            GetWindowBounds(window, kWindowGrowRgn, &dragRect);
            Point pos = {dragRect.bottom, dragRect.right};
            SetEventParameter(mouseUpEvent, kEventParamMouseLocation, typeQDPoint, sizeof(pos), &pos);
            SendEventToApplication(mouseUpEvent);
            ReleaseEvent(mouseUpEvent);
        } else if(ekind == kEventWindowBoundsChanging || ekind == kEventWindowBoundsChanged) {
            // Panther doesn't send Changing for sheets, only changed, so only
            // bother handling Changed event if we are on 10.3 and we are a
            // sheet.
            if (ekind == kEventWindowBoundsChanged
                    && (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4
                        || !(widget->windowFlags() & Qt::Sheet))) {
                handled_event = false;
            } else {
                UInt32 flags = 0;
                GetEventParameter(event, kEventParamAttributes, typeUInt32, 0,
                                      sizeof(flags), 0, &flags);
                Rect nr;
                GetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle, 0,
                                      sizeof(nr), 0, &nr);

                QRect newRect(nr.left, nr.top, nr.right - nr.left, nr.bottom - nr.top);

                QTLWExtra * const tlwExtra = widget->d_func()->maybeTopData();
                if (tlwExtra && tlwExtra->isSetGeometry == 1) {
                    widget->d_func()->setGeometry_sys_helper(newRect.left(), newRect.top(), newRect.width(), newRect.height(), tlwExtra->isMove);
                } else {
                    //implicitly removes the maximized bit
                    if((widget->data->window_state & Qt::WindowMaximized) &&
                       IsWindowInStandardState(wid, 0, 0)) {
                        widget->data->window_state &= ~Qt::WindowMaximized;
                        QWindowStateChangeEvent e(Qt::WindowStates(widget->data->window_state
                                                    | Qt::WindowMaximized));
                        QApplication::sendSpontaneousEvent(widget, &e);

                    }

                    handled_event = false;
                    const QRect oldRect = widget->data->crect;
                    if((flags & kWindowBoundsChangeOriginChanged)) {
                        if(nr.left != oldRect.x() || nr.top != oldRect.y()) {
                            widget->data->crect.moveTo(nr.left, nr.top);
                            QMoveEvent qme(widget->data->crect.topLeft(), oldRect.topLeft());
                            QApplication::sendSpontaneousEvent(widget, &qme);
                        }
                    }
                    if((flags & kWindowBoundsChangeSizeChanged)) {
                        if (widget->isWindow()) {
                            QSize newSize = QLayout::closestAcceptableSize(widget, newRect.size());
                            int dh = newSize.height() - newRect.height();
                            int dw = newSize.width() - newRect.width();
                            if (dw != 0 || dh != 0) {
                                handled_event = true;  // We want to change the bounds, so we handle the event

                                // set the rect, so we can also do the resize down below (yes, we need to resize).
                                newRect.setBottom(newRect.bottom() + dh);
                                newRect.setRight(newRect.right() + dw);

                                nr.left = newRect.x();
                                nr.top = newRect.y();
                                nr.right = nr.left + newRect.width();
                                nr.bottom = nr.top + newRect.height();
                                SetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle, sizeof(Rect), &nr);
                            }
                        }

                        if (oldRect.width() != newRect.width() || oldRect.height() != newRect.height()) {
                            widget->data->crect.setSize(newRect.size());
                            HIRect bounds = CGRectMake(0, 0, newRect.width(), newRect.height());

                            // If the WA_StaticContents attribute is set we can optimize the resize
                            // by only repainting the newly exposed area. We do this by disabling
                            // painting when setting the size of the view. The OS will invalidate
                            // the newly exposed area for us.
                            const bool staticContents = widget->testAttribute(Qt::WA_StaticContents);
                            const HIViewRef view = qt_mac_nativeview_for(widget);
                            if (staticContents)
                                HIViewSetDrawingEnabled(view, false);
                            HIViewSetFrame(view, &bounds);
                            if (staticContents)
                                HIViewSetDrawingEnabled(view, true);

                            QResizeEvent qre(newRect.size(), oldRect.size());
                            QApplication::sendSpontaneousEvent(widget, &qre);
                            qt_event_request_window_change(widget);
                        }
                    }
                }
            }
        } else {
            handled_event = false;
        }
        break; }
    case kEventClassMouse: {
#if 0
        return SendEventToApplication(event);
#endif

        bool send_to_app = false;
        {
            WindowPartCode wpc;
            if (GetEventParameter(event, kEventParamWindowPartCode, typeWindowPartCode, 0,
                                  sizeof(wpc), 0, &wpc) == noErr && wpc != inContent)
                send_to_app = true;
        }
        if(!send_to_app) {
            WindowRef window;
            if(GetEventParameter(event, kEventParamWindowRef, typeWindowRef, 0,
                                 sizeof(window), 0, &window) == noErr) {
                HIViewRef hiview;
                if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) {
                    if(QWidget *w = QWidget::find((WId)hiview)) {
#if 0
                        send_to_app = !w->isActiveWindow();
#else
                        Q_UNUSED(w);
                        send_to_app = true;
#endif
                    }
                }
            }
        }
        if(send_to_app)
            return SendEventToApplication(event);
        handled_event = false;
        break; }
    default:
        handled_event = false;
    }
    if(!handled_event) //let the event go through
        return eventNotHandledErr;
    return noErr; //we eat the event
}

// widget events
static HIObjectClassRef widget_class = 0;
static EventTypeSpec widget_events[] = {
    { kEventClassHIObject, kEventHIObjectConstruct },
    { kEventClassHIObject, kEventHIObjectDestruct },

    { kEventClassControl, kEventControlDraw },
    { kEventClassControl, kEventControlInitialize },
    { kEventClassControl, kEventControlGetPartRegion },
    { kEventClassControl, kEventControlGetClickActivation },
    { kEventClassControl, kEventControlSetFocusPart },
    { kEventClassControl, kEventControlDragEnter },
    { kEventClassControl, kEventControlDragWithin },
    { kEventClassControl, kEventControlDragLeave },
    { kEventClassControl, kEventControlDragReceive },
    { kEventClassControl, kEventControlOwningWindowChanged },
    { kEventClassControl, kEventControlBoundsChanged },
    { kEventClassControl, kEventControlGetSizeConstraints },
    { kEventClassControl, kEventControlVisibilityChanged },

    { kEventClassMouse, kEventMouseDown },
    { kEventClassMouse, kEventMouseUp },
    { kEventClassMouse, kEventMouseMoved },
    { kEventClassMouse, kEventMouseDragged }
};
static EventHandlerUPP mac_widget_eventUPP = 0;
static void cleanup_widget_eventUPP()
{
    DisposeEventHandlerUPP(mac_widget_eventUPP);
    mac_widget_eventUPP = 0;
}
static const EventHandlerUPP make_widget_eventUPP()
{
    if(mac_widget_eventUPP)
        return mac_widget_eventUPP;
    qAddPostRoutine(cleanup_widget_eventUPP);
    return mac_widget_eventUPP = NewEventHandlerUPP(QWidgetPrivate::qt_widget_event);
}
OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, void *)
{
    QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);

    bool handled_event = true;
    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
    switch(eclass) {
    case kEventClassHIObject: {
        HIViewRef view = 0;
        GetEventParameter(event, kEventParamHIObjectInstance, typeHIObjectRef,
                          0, sizeof(view), 0, &view);
        if(ekind == kEventHIObjectConstruct) {
            if(view) {
                HIViewChangeFeatures(view, kHIViewAllowsSubviews, 0);
                SetEventParameter(event, kEventParamHIObjectInstance,
                                  typeVoidPtr, sizeof(view), &view);
            }
        } else if(ekind == kEventHIObjectDestruct) {
            //nothing to really do.. or is there?
        } else {
            handled_event = false;
        }
        break; }
    case kEventClassControl: {
        QWidget *widget = 0;
        HIViewRef hiview = 0;
        if(GetEventParameter(event, kEventParamDirectObject, typeControlRef,
                             0, sizeof(hiview), 0, &hiview) == noErr)
            widget = QWidget::find((WId)hiview);
        if (widget && widget->macEvent(er, event))
            return noErr;
        if(ekind == kEventControlDraw) {
            if(widget && qt_isGenuineQWidget(hiview)) {

                // if there is a window change event pending for any gl child wigets,
                // send it immediately. (required for flicker-free resizing)
                extern void qt_mac_send_posted_gl_updates(QWidget *widget);
                qt_mac_send_posted_gl_updates(widget);

                if (QApplicationPrivate::graphicsSystem() && !widget->d_func()->paintOnScreen()) {
                    widget->d_func()->syncBackingStore();
                    widget->d_func()->dirtyOnWidget = QRegion();
                    return noErr;
                }

                //requested rgn
                RgnHandle rgn;
                GetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof(rgn), 0, &rgn);
                QRegion qrgn(qt_mac_convert_mac_region(rgn));

                //update handles
                GrafPtr qd = 0;
                CGContextRef cg = 0;
#ifndef QT_MAC_NO_QUICKDRAW
                {
                    if(GetEventParameter(event, kEventParamGrafPort, typeGrafPtr, 0, sizeof(qd), 0, &qd) != noErr) {
                        GDHandle dev = 0;
                        GetGWorld(&qd, &dev); //just use the global port..
                    }
                }
                bool end_cg_context = false;
                if(GetEventParameter(event, kEventParamCGContextRef, typeCGContextRef, 0, sizeof(cg), 0, &cg) != noErr && qd) {
                    end_cg_context = true;
                    QDBeginCGContext(qd, &cg);
                }
#else
                if(GetEventParameter(event, kEventParamCGContextRef, typeCGContextRef, 0, sizeof(cg), 0, &cg) != noErr) {
                    Q_ASSERT(false);
                }
#endif
                widget->d_func()->hd = cg;
                widget->d_func()->qd_hd = qd;
                CGContextSaveGState(cg);

#ifdef DEBUG_WIDGET_PAINT
                const bool doDebug = true;
                if(doDebug)  {
                    qDebug("asked to draw %p[%p] [%s::%s] %p[%p] [%d] [%dx%d]", widget, hiview, widget->metaObject()->className(),
                           widget->objectName().local8Bit().data(), widget->parentWidget(),
                           (HIViewRef)(widget->parentWidget() ? qt_mac_nativeview_for(widget->parentWidget()) : (HIViewRef)0),
                           HIViewIsCompositingEnabled(hiview), qt_mac_posInWindow(widget).x(), qt_mac_posInWindow(widget).y());
#if 0
                    QVector<QRect> region_rects = qrgn.rects();
                    qDebug("Region! %d", region_rects.count());
                    for(int i = 0; i < region_rects.count(); i++)
                        qDebug("%d %d %d %d", region_rects[i].x(), region_rects[i].y(),
                               region_rects[i].width(), region_rects[i].height());
                    region_rects = widget->d_func()->clp.rects();
                    qDebug("Widget Region! %d", region_rects.count());
                    for(int i = 0; i < region_rects.count(); i++)
                        qDebug("%d %d %d %d", region_rects[i].x(), region_rects[i].y(),
                               region_rects[i].width(), region_rects[i].height());
#endif
                }
#endif
                if (widget->isVisible() && widget->updatesEnabled()) { //process the actual paint event.
                    if(widget->testAttribute(Qt::WA_WState_InPaintEvent))
                        qWarning("QWidget::repaint: Recursive repaint detected");

                    QPoint redirectionOffset(0, 0);
                    QWidget *tl = widget->window();
                    if (tl) {
                        Qt::WindowFlags flags = tl->windowFlags();
                        if (flags & Qt::FramelessWindowHint
                            || (flags & Qt::CustomizeWindowHint && !(flags & Qt::WindowTitleHint))) {
                            if(tl->d_func()->extra && !tl->d_func()->extra->mask.isEmpty())
                                redirectionOffset += tl->d_func()->extra->mask.boundingRect().topLeft();
                        }
                    }

                    //setup the context
                    widget->setAttribute(Qt::WA_WState_InPaintEvent);
                    QPaintEngine *engine = widget->paintEngine();
                    if (engine)
                        engine->setSystemClip(qrgn);

                    //handle the erase
                    if (engine && (!widget->testAttribute(Qt::WA_NoSystemBackground)
                        && (widget->isWindow() || widget->autoFillBackground())
                        || widget->testAttribute(Qt::WA_TintedBackground)
                        || widget->testAttribute(Qt::WA_StyledBackground))) {
#ifdef DEBUG_WIDGET_PAINT
                        if(doDebug)
                            qDebug(" Handling erase for [%s::%s]", widget->metaObject()->className(),
                                   widget->objectName().local8Bit().data());
#endif
                        if (!redirectionOffset.isNull())
                            widget->d_func()->setRedirected(widget, redirectionOffset);

                        bool was_unclipped = widget->testAttribute(Qt::WA_PaintUnclipped);
                        widget->setAttribute(Qt::WA_PaintUnclipped, false);
                        QPainter p(widget);
                        p.setClipping(false);
                        if(was_unclipped)
                            widget->setAttribute(Qt::WA_PaintUnclipped);

                        QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(widget->parent());
                        QPoint scrollAreaOffset;
                        if (scrollArea && scrollArea->viewport() == widget) {
                            QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(static_cast<QWidget *>(scrollArea)->d_ptr);
                            scrollAreaOffset = priv->contentsOffset();
                            p.translate(-scrollAreaOffset);
                        }

                        widget->d_func()->paintBackground(&p, qrgn, scrollAreaOffset, widget->isWindow() ? DrawAsRoot : 0);
                        if (widget->testAttribute(Qt::WA_TintedBackground)) {
                            QColor tint = widget->palette().window().color();
                            tint.setAlphaF(.6);
                            const QVector<QRect> &rects = qrgn.rects();
                            for (int i = 0; i < rects.size(); ++i)
                                p.fillRect(rects.at(i).translated(scrollAreaOffset), tint);
                        }
                        p.end();
                        if (!redirectionOffset.isNull())
                            widget->d_func()->restoreRedirected();
                    }

                    if (widget->isWindow() && !widget->d_func()->isOpaque
                           && !widget->testAttribute(Qt::WA_MacBrushedMetal)) {
                        QRect qrgnRect = qrgn.boundingRect();
                        CGContextClearRect(cg, CGRectMake(qrgnRect.x(), qrgnRect.y(), qrgnRect.width(), qrgnRect.height()));
                    }


                    if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
                        CallNextEventHandler(er, event);

                    //send the paint
                    redirectionOffset += widget->data->wrect.topLeft(); // Map from system to qt coordinates
                    if (!redirectionOffset.isNull())
                        widget->d_func()->setRedirected(widget, redirectionOffset);
                    qrgn.translate(redirectionOffset);
                    QPaintEvent e(qrgn);
                    widget->d_func()->dirtyOnWidget = QRegion();
#ifdef QT3_SUPPORT
                    e.setErased(true);
#endif
                    QApplication::sendSpontaneousEvent(widget, &e);
                    if (!redirectionOffset.isNull())
                        widget->d_func()->restoreRedirected();
#ifdef QT_RASTER_PAINTENGINE
                    if(engine && engine->type() == QPaintEngine::Raster)
                        static_cast<QRasterPaintEngine*>(engine)->flush(widget,
                                                                        qrgn.boundingRect().topLeft());
#endif

                    //cleanup
                    if (engine)
                        engine->setSystemClip(QRegion());

                    widget->setAttribute(Qt::WA_WState_InPaintEvent, false);
                    if(!widget->testAttribute(Qt::WA_PaintOutsidePaintEvent) && widget->paintingActive())
                        qWarning("QWidget: It is dangerous to leave painters active on a widget outside of the PaintEvent");
                }

                widget->d_func()->hd = 0;
                widget->d_func()->qd_hd = 0;
                CGContextRestoreGState(cg);
#ifndef QT_MAC_NO_QUICKDRAW
                if(end_cg_context)
                    QDEndCGContext(qd, &cg);
#endif
            } else if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) {
                CallNextEventHandler(er, event);
            }
        } else if(ekind == kEventControlInitialize) {
            if(HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) {
                UInt32 features = kControlSupportsDragAndDrop | kControlSupportsClickActivation | kControlSupportsFocus;
                SetEventParameter(event, kEventParamControlFeatures, typeUInt32, sizeof(features), &features);
            } else {
                handled_event = false;
            }
        } else if(ekind == kEventControlSetFocusPart) {
            if(widget) {
                ControlPartCode part;
                GetEventParameter(event, kEventParamControlPart, typeControlPartCode, 0,
                                  sizeof(part), 0, &part);
                if(part == kControlFocusNoPart){
                    if (widget->hasFocus())
                        QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
                } else
                    widget->setFocus();
            }
            if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
                CallNextEventHandler(er, event);
        } else if(ekind == kEventControlGetClickActivation) {
            ClickActivationResult clickT = kActivateAndIgnoreClick;
            SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult,
                              sizeof(clickT), &clickT);
        } else if(ekind == kEventControlGetPartRegion) {
            handled_event = false;
            if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget) && CallNextEventHandler(er, event) == noErr) {
                handled_event = true;
                break;
            }
            if(widget && !widget->isWindow()) {
                ControlPartCode part;
                GetEventParameter(event, kEventParamControlPart, typeControlPartCode, 0,
                                  sizeof(part), 0, &part);
                if(part == kControlClickableMetaPart && widget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
                    RgnHandle rgn;
                    GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
                                      sizeof(rgn), 0, &rgn);
                    SetEmptyRgn(rgn);
                    handled_event = true;
                } else if(part == kControlStructureMetaPart || part == kControlClickableMetaPart) {
                    RgnHandle rgn;
                    GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
                                      sizeof(rgn), 0, &rgn);
                    SetRectRgn(rgn, 0, 0, widget->width(), widget->height());
                    if(QWidgetPrivate::qt_widget_rgn(widget, kWindowStructureRgn, rgn, false))
                        handled_event = true;
                } else if(part == kControlOpaqueMetaPart) {
                    if(widget->d_func()->isOpaque) {
                        RgnHandle rgn;
                        GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
                                          sizeof(RgnHandle), 0, &rgn);
                        SetRectRgn(rgn, 0, 0, widget->width(), widget->height());
                        QWidgetPrivate::qt_widget_rgn(widget, kWindowStructureRgn, rgn, false);
                        SetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle,
                                sizeof(RgnHandle), &rgn);
                        handled_event = true;
                    }
                }
            }
        } else if(ekind == kEventControlOwningWindowChanged) {
            if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
                CallNextEventHandler(er, event);
            if(widget && qt_mac_window_for(hiview)) {
                WindowRef foo = 0;
                GetEventParameter(event, kEventParamControlCurrentOwningWindow, typeWindowRef, 0,
                                  sizeof(foo), 0, &foo);
                widget->d_func()->initWindowPtr();
            }
            if (widget)
                qt_event_request_window_change(widget);
        } else if(ekind == kEventControlDragEnter || ekind == kEventControlDragWithin ||
                  ekind == kEventControlDragLeave || ekind == kEventControlDragReceive) {
            // dnd are really handled in qdnd_mac.cpp,
            // just modularize the code a little...
            DragRef drag;
            GetEventParameter(event, kEventParamDragRef, typeDragRef, 0, sizeof(drag), 0, &drag);
            handled_event = false;
            bool drag_allowed = false;

            QWidget *dropWidget = widget;
            if (qobject_cast<QFocusFrame *>(widget)){
                // We might shadow widgets underneath the focus
                // frame, so stay interrested, and let the dnd through
                drag_allowed = true;
                handled_event = true;
                Point where;
                GetDragMouse(drag, &where, 0);
                dropWidget = QApplication::widgetAt(QPoint(where.h, where.v));

                if (dropWidget != QDragManager::self()->currentTarget()) {
                    // We have to 'fake' enter and leave events for the shaddowed widgets:
                    if (ekind == kEventControlDragEnter) {
                        if (QDragManager::self()->currentTarget())
                            QDragManager::self()->currentTarget()->d_func()->qt_mac_dnd_event(kEventControlDragLeave, drag);
                        if (dropWidget) {
                            dropWidget->d_func()->qt_mac_dnd_event(kEventControlDragEnter, drag);
                        }
                        // Set dropWidget to zero, so qt_mac_dnd_event
                        // doesn't get called a second time below:
                        dropWidget = 0;
                    }
                }
            }

            // Send the dnd event to the widget:
            if (dropWidget && dropWidget->d_func()->qt_mac_dnd_event(ekind, drag)) {
                drag_allowed = true;
                handled_event = true;
            }

            if (ekind == kEventControlDragEnter) {
                // If we don't accept the enter event, we will
                // receive no more drag events for this widget
                const Boolean wouldAccept = drag_allowed ? true : false;
                SetEventParameter(event, kEventParamControlWouldAcceptDrop, typeBoolean,
                        sizeof(wouldAccept), &wouldAccept);
            }
        } else if (ekind == kEventControlBoundsChanged) {
            if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_Moved) || widget->testAttribute(Qt::WA_Resized)) {
                handled_event = false;
            } else {
                // Sync our view in case some other (non-Qt) view is controlling us.
                handled_event = true;
                Rect newBounds;
                GetEventParameter(event, kEventParamCurrentBounds,
                                  typeQDRectangle, 0, sizeof(Rect), 0, &newBounds);
                QRect rect(newBounds.left, newBounds.top,
                            newBounds.right - newBounds.left, newBounds.bottom - newBounds.top);

                bool moved = widget->testAttribute(Qt::WA_Moved);
                bool resized = widget->testAttribute(Qt::WA_Resized);
                widget->setGeometry(rect);
                widget->setAttribute(Qt::WA_Moved, moved);
                widget->setAttribute(Qt::WA_Resized, resized);
                qt_event_request_window_change(widget);
            }
        } else if (ekind == kEventControlGetSizeConstraints) {
            if (!widget || !qt_isGenuineQWidget(widget)) {
                handled_event = false;
            } else {
                handled_event = true;
                QWidgetItem item(widget);
                QSize size = item.minimumSize();
                HISize hisize = { size.width(), size.height() };
                SetEventParameter(event, kEventParamMinimumSize, typeHISize, sizeof(HISize), &hisize);
                size = item.maximumSize();
                hisize.width = size.width() + 2; // ### shouldn't have to add 2 (but it works).
                hisize.height = size.height();
                SetEventParameter(event, kEventParamMaximumSize, typeHISize, sizeof(HISize), &hisize);
            }
        } else if (ekind == kEventControlVisibilityChanged) {
            handled_event = false;
            if (widget) {
                qt_event_request_window_change(widget);
                if (!HIViewIsVisible(HIViewRef(widget->winId()))) {
                    extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
                    if (widget == qt_button_down)
                        qt_button_down = 0;
                }
            }
        }
        break; }
    case kEventClassMouse: {
        bool send_to_app = false;
        extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
        if(qt_button_down)
            send_to_app = true;
        if(send_to_app) {
            OSStatus err = SendEventToApplication(event);
            if(err != noErr)
                handled_event = false;
        } else {
            CallNextEventHandler(er, event);
        }
        break; }
    default:
        handled_event = false;
        break;
    }
    if(!handled_event) //let the event go through
        return eventNotHandledErr;
    return noErr; //we eat the event
}
#endif

OSViewRef qt_mac_create_widget(QWidget *widget, QWidgetPrivate *widgetPrivate, OSViewRef parent)
{
#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    QT_MANGLE_NAMESPACE(QCocoaView) *view = [[QT_MANGLE_NAMESPACE(QCocoaView) alloc] initWithQWidget:widget widgetPrivate:widgetPrivate];
    if (view && parent)
        [parent addSubview:view];
    return view;
#else
    Q_UNUSED(widget);
    Q_UNUSED(widgetPrivate);
    if(!widget_class) {
        OSStatus err = HIObjectRegisterSubclass(kObjectQWidget, kHIViewClassID, 0, make_widget_eventUPP(),
                                                GetEventTypeCount(widget_events), widget_events,
                                                0, &widget_class);
        if (err && err != hiObjectClassExistsErr)
            qWarning("QWidget: Internal error (%d)", __LINE__);
    }
    HIViewRef ret = 0;
    if(HIObjectCreate(kObjectQWidget, 0, (HIObjectRef*)&ret) != noErr)
        qWarning("QWidget: Internal error (%d)", __LINE__);
    if(ret && parent)
        HIViewAddSubview(parent, ret);
    return ret;
#endif
}

void qt_mac_unregister_widget()
{
#ifndef QT_MAC_USE_COCOA
    HIObjectUnregisterClass(widget_class);
    widget_class = 0;
#endif
}

void QWidgetPrivate::toggleDrawers(bool visible)
{
    for (int i = 0; i < children.size(); ++i) {
        register QObject *object = children.at(i);
        if (!object->isWidgetType())
            continue;
        QWidget *widget = static_cast<QWidget*>(object);
        if(qt_mac_is_macdrawer(widget)) {
            if(visible) {
                if (!widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
                    widget->show();
            } else {
                widget->hide();
                widget->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
            }
        }
    }
}

/*****************************************************************************
  QWidgetPrivate member functions
 *****************************************************************************/
bool QWidgetPrivate::qt_mac_update_sizer(QWidget *w, int up)
{
    // I'm not sure what "up" is
    if(!w || !w->isWindow())
        return false;

    QTLWExtra *topData = w->d_func()->topData();
    QWExtra *extraData = w->d_func()->extraData();
    // topData->resizer is only 4 bits, so subtracting -1 from zero causes bad stuff
    // to happen, prevent that here (you really want the thing hidden).
    if (up >= 0 || topData->resizer != 0)
        topData->resizer += up;
    OSWindowRef windowRef = qt_mac_window_for(OSViewRef(w->winId()));
    {
#ifndef QT_MAC_USE_COCOA
        WindowClass wclass;
        GetWindowClass(windowRef, &wclass);
        if(!(GetAvailableWindowAttributes(wclass) & kWindowResizableAttribute))
            return true;
#endif
    }
    bool remove_grip = (topData->resizer || (w->windowFlags() & Qt::FramelessWindowHint)
                        || (extraData->maxw && extraData->maxh &&
                            extraData->maxw == extraData->minw && extraData->maxh == extraData->minh));
#ifndef QT_MAC_USE_COCOA
    WindowAttributes attr;
    GetWindowAttributes(windowRef, &attr);
    if(remove_grip) {
        if(attr & kWindowResizableAttribute) {
            ChangeWindowAttributes(qt_mac_window_for(w), kWindowNoAttributes,
                                   kWindowResizableAttribute);
            ReshapeCustomWindow(qt_mac_window_for(w));
        }
    } else if(!(attr & kWindowResizableAttribute)) {
        ChangeWindowAttributes(windowRef, kWindowResizableAttribute,
                               kWindowNoAttributes);
        ReshapeCustomWindow(windowRef);
    }
#else
    [windowRef setShowsResizeIndicator:!remove_grip];
#endif
    return true;
}

void QWidgetPrivate::qt_clean_root_win()
{
#ifdef QT_MAC_USE_COCOA
    [qt_root_win release];
#else
    if(!qt_root_win)
        return;
    CFRelease(qt_root_win);
#endif
    qt_root_win = 0;
}

bool QWidgetPrivate::qt_create_root_win()
{
    if(qt_root_win)
        return false;
    const QSize desktopSize = qt_mac_desktopSize();
    QRect desktopRect(QPoint(0, 0), desktopSize);
#ifdef QT_MAC_USE_COCOA
    qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, NSBorderlessWindowMask, desktopRect);
#else
    WindowAttributes wattr = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
    qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, wattr, desktopRect);
#endif
    if(!qt_root_win)
        return false;
    qAddPostRoutine(qt_clean_root_win);
    return true;
}

bool QWidgetPrivate::qt_recreate_root_win()
{
    if(!qt_root_win) //sanity check
        return false;
    //store old
    OSWindowRef old_root_win = qt_root_win;
    //recreate
    qt_root_win = 0;
    qt_create_root_win();
    //cleanup old window
#ifdef QT_MAC_USE_COCOA
    [old_root_win release];
#else
    CFRelease(old_root_win);
#endif
    return true;
}

bool QWidgetPrivate::qt_widget_rgn(QWidget *widget, short wcode, RgnHandle rgn, bool force = false)
{
    bool ret = false;
#ifndef QT_MAC_USE_COCOA
    switch(wcode) {
    case kWindowStructureRgn: {
        if(widget) {
            if(widget->d_func()->extra && !widget->d_func()->extra->mask.isEmpty()) {
                QRegion rin = qt_mac_convert_mac_region(rgn);
                if(!rin.isEmpty()) {
                    QPoint rin_tl = rin.boundingRect().topLeft(); //in offset
                    rin.translate(-rin_tl.x(), -rin_tl.y()); //bring into same space as below
                    QRegion mask = widget->d_func()->extra->mask;
                    Qt::WindowFlags flags = widget->windowFlags();
                    if(widget->isWindow()
                       && !(flags & Qt::FramelessWindowHint
                            || (flags & Qt::CustomizeWindowHint && !(flags & Qt::WindowTitleHint)))) {
                        QRegion title;
                        {
                            QMacSmartQuickDrawRegion rgn(qt_mac_get_rgn());
                            GetWindowRegion(qt_mac_window_for(widget), kWindowTitleBarRgn, rgn);
                            title = qt_mac_convert_mac_region(rgn);
                        }
                        QRect br = title.boundingRect();
                        mask.translate(0, br.height()); //put the mask 'under' the title bar..
                        title.translate(-br.x(), -br.y());
                        mask += title;
                    }

                    QRegion cr = rin & mask;
                    cr.translate(rin_tl.x(), rin_tl.y()); //translate back to incoming space
                    CopyRgn(QMacSmartQuickDrawRegion(cr.toQDRgn()), rgn);
                }
                ret = true;
            } else if(force) {
                QRegion cr(widget->geometry());
                CopyRgn(QMacSmartQuickDrawRegion(cr.toQDRgn()), rgn);
                ret = true;
            }
        }
        break; }
    default: break;
    }
    //qDebug() << widget << ret << wcode << qt_mac_convert_mac_region(rgn);
#else
    Q_UNUSED(widget);
    Q_UNUSED(wcode);
    Q_UNUSED(rgn);
    Q_UNUSED(force);
#endif
    return ret;
}

/*****************************************************************************
  QWidget member functions
 *****************************************************************************/
void QWidgetPrivate::determineWindowClass()
{
    Q_Q(QWidget);
#ifndef QT_MAC_USE_COCOA
// ### COCOA:Interleave these better!

    const Qt::WindowType type = q->windowType();
    Qt::WindowFlags &flags = data.window_flags;
    const bool popup = (type == Qt::Popup);
    if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
        flags |= Qt::FramelessWindowHint;

    WindowClass wclass = kSheetWindowClass;
    if(qt_mac_is_macdrawer(q))
        wclass = kDrawerWindowClass;
    else if (q->testAttribute(Qt::WA_ShowModal) && flags & Qt::CustomizeWindowHint)
        wclass = kDocumentWindowClass;
    else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
        wclass = kModalWindowClass;
    else if(q->testAttribute(Qt::WA_ShowModal))
        wclass = kMovableModalWindowClass;
    else if(type == Qt::ToolTip)
        wclass = kHelpWindowClass;
    else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
                                 && type == Qt::SplashScreen))
        wclass = kFloatingWindowClass;
    else
        wclass = kDocumentWindowClass;

    WindowGroupRef grp = 0;
    WindowAttributes wattr = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
    if (q->testAttribute(Qt::WA_MacFrameworkScaled))
        wattr |= kWindowFrameworkScaledAttribute;
    if(qt_mac_is_macsheet(q)) {
        //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
        wclass = kSheetWindowClass;
    } else {
        grp = GetWindowGroupOfClass(wclass);
        // Shift things around a bit to get the correct window class based on the presence
        // (or lack) of the border.
	bool customize = flags & Qt::CustomizeWindowHint;
        bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
        if (framelessWindow) {
            if(wclass == kDocumentWindowClass) {
                if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
                    wattr |= kWindowNoTitleBarAttribute;
                else
                    wclass = kPlainWindowClass;
            } else if(wclass == kFloatingWindowClass) {
                if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
                    wattr |= kWindowNoTitleBarAttribute;
                else
                    wclass = kToolbarWindowClass;
            } else if (wclass  == kMovableModalWindowClass) {
                    wclass = kModalWindowClass;
            }
        } else {
            if(wclass != kModalWindowClass)
                wattr |= kWindowResizableAttribute;
        }
        // Only add extra decorations (well, buttons) for widgets that can have them
        // and have an actual border we can put them on.
        if(wclass != kModalWindowClass && wclass != kMovableModalWindowClass
                && wclass != kSheetWindowClass && wclass != kPlainWindowClass
                && !framelessWindow && wclass != kDrawerWindowClass
                && wclass != kHelpWindowClass) {
            if (flags & Qt::WindowMaximizeButtonHint)
                wattr |= kWindowFullZoomAttribute;
            if (flags & Qt::WindowMinimizeButtonHint)
                wattr |= kWindowCollapseBoxAttribute;
            if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
                wattr |= kWindowCloseBoxAttribute;
            if (flags & Qt::MacWindowToolBarButtonHint)
                wattr |= kWindowToolbarButtonAttribute;
        } else {
            // Clear these hints so that we aren't call them on invalid windows
            flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
                       | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
        }
    }
    if((popup || type == Qt::Tool) && !q->isModal())
        wattr |= kWindowHideOnSuspendAttribute;
    wattr |= kWindowLiveResizeAttribute;

#ifdef DEBUG_WINDOW_CREATE
#define ADD_DEBUG_WINDOW_NAME(x) { x, #x }
    struct {
        UInt32 tag;
        const char *name;
    } known_attribs[] = {
        ADD_DEBUG_WINDOW_NAME(kWindowCompositingAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowMetalAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowCollapseBoxAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowHorizontalZoomAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowVerticalZoomAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowResizableAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowNoActivatesAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowNoUpdatesAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowOpaqueForEventsAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowLiveResizeAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowCloseBoxAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
        { 0, 0 }
    }, known_classes[] = {
        ADD_DEBUG_WINDOW_NAME(kHelpWindowClass),
        ADD_DEBUG_WINDOW_NAME(kPlainWindowClass),
        ADD_DEBUG_WINDOW_NAME(kDrawerWindowClass),
        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
        ADD_DEBUG_WINDOW_NAME(kSheetWindowClass),
        ADD_DEBUG_WINDOW_NAME(kFloatingWindowClass),
        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
        ADD_DEBUG_WINDOW_NAME(kDocumentWindowClass),
        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
        ADD_DEBUG_WINDOW_NAME(kMovableModalWindowClass),
        ADD_DEBUG_WINDOW_NAME(kModalWindowClass),
        { 0, 0 }
    };
    qDebug("Qt: internal: ************* Creating new window %p (%s::%s)", q, q->metaObject()->className(),
            q->objectName().toLocal8Bit().constData());
    bool found_class = false;
    for(int i = 0; known_classes[i].name; i++) {
        if(wclass == known_classes[i].tag) {
            found_class = true;
            qDebug("Qt: internal: ** Class: %s", known_classes[i].name);
            break;
        }
    }
    if(!found_class)
        qDebug("Qt: internal: !! Class: Unknown! (%d)", (int)wclass);
    if(wattr) {
        WindowAttributes tmp_wattr = wattr;
        qDebug("Qt: internal: ** Attributes:");
        for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
            if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
                tmp_wattr ^= known_attribs[i].tag;
                qDebug("Qt: internal: * %s %s", known_attribs[i].name,
                        (GetAvailableWindowAttributes(wclass) & known_attribs[i].tag) ? "" : "(*)");
            }
        }
        if(tmp_wattr)
            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
    }
#endif

    /* Just to be extra careful we will change to the kUtilityWindowClass if the
       requested attributes cannot be used */
    if((GetAvailableWindowAttributes(wclass) & wattr) != wattr) {
        WindowClass tmp_class = wclass;
        if(wclass == kToolbarWindowClass || wclass == kUtilityWindowClass)
            wclass = kFloatingWindowClass;
        if(tmp_class != wclass) {
            if(!grp)
                grp = GetWindowGroupOfClass(wclass);
            wclass = tmp_class;
        }
    }
    topData()->wclass = wclass;
    topData()->wattr = wattr;
#else
    const Qt::WindowType type = q->windowType();
    Qt::WindowFlags &flags = data.window_flags;
    const bool popup = (type == Qt::Popup);
    if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
        flags |= Qt::FramelessWindowHint;

    WindowClass wclass = kSheetWindowClass;
    if(qt_mac_is_macdrawer(q))
        wclass = kDrawerWindowClass;
    else if (q->testAttribute(Qt::WA_ShowModal) && flags & Qt::CustomizeWindowHint)
        wclass = kDocumentWindowClass;
    else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
        wclass = kModalWindowClass;
    else if(q->testAttribute(Qt::WA_ShowModal) || type == Qt::Dialog)
        wclass = kMovableModalWindowClass;
    else if(type == Qt::ToolTip)
        wclass = kHelpWindowClass;
    else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
                                 && type == Qt::SplashScreen))
        wclass = kFloatingWindowClass;
    else
        wclass = kDocumentWindowClass;

    WindowAttributes wattr = NSBorderlessWindowMask;
    if(qt_mac_is_macsheet(q)) {
        //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
        wclass = kSheetWindowClass;
        wattr = NSTitledWindowMask | NSResizableWindowMask;
    } else {
#ifndef QT_MAC_USE_COCOA
        grp = GetWindowGroupOfClass(wclass);
#endif
        // Shift things around a bit to get the correct window class based on the presence
        // (or lack) of the border.
	bool customize = flags & Qt::CustomizeWindowHint;
        bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
        if (framelessWindow) {
            if (wclass == kDocumentWindowClass) {
                wclass = kSimpleWindowClass;
            } else if (wclass == kFloatingWindowClass) {
                wclass = kToolbarWindowClass;
            } else if (wclass  == kMovableModalWindowClass) {
                wclass  = kModalWindowClass;
            }
        } else {
            wattr |= NSTitledWindowMask;
            if (wclass != kModalWindowClass)
                wattr |= NSResizableWindowMask;
        }
        // Only add extra decorations (well, buttons) for widgets that can have them
        // and have an actual border we can put them on.
        if (wclass != kModalWindowClass
                && wclass != kSheetWindowClass && wclass != kPlainWindowClass
                && !framelessWindow && wclass != kDrawerWindowClass
                && wclass != kHelpWindowClass) {
            if (flags & Qt::WindowMinimizeButtonHint)
                wattr |= NSMiniaturizableWindowMask;
            if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
                wattr |= NSClosableWindowMask;
        } else {
            // Clear these hints so that we aren't call them on invalid windows
            flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
                       | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
        }
    }
    if (q->testAttribute(Qt::WA_MacBrushedMetal))
        wattr |= NSTexturedBackgroundWindowMask;

#ifdef DEBUG_WINDOW_CREATE
#define ADD_DEBUG_WINDOW_NAME(x) { x, #x }
    struct {
        UInt32 tag;
        const char *name;
    } known_attribs[] = {
        ADD_DEBUG_WINDOW_NAME(kWindowCompositingAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowMetalAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowCollapseBoxAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowHorizontalZoomAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowVerticalZoomAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowResizableAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowNoActivatesAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowNoUpdatesAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowOpaqueForEventsAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowLiveResizeAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowCloseBoxAttribute),
        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
        { 0, 0 }
    }, known_classes[] = {
        ADD_DEBUG_WINDOW_NAME(kHelpWindowClass),
        ADD_DEBUG_WINDOW_NAME(kPlainWindowClass),
        ADD_DEBUG_WINDOW_NAME(kDrawerWindowClass),
        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
        ADD_DEBUG_WINDOW_NAME(kSheetWindowClass),
        ADD_DEBUG_WINDOW_NAME(kFloatingWindowClass),
        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
        ADD_DEBUG_WINDOW_NAME(kDocumentWindowClass),
        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
        ADD_DEBUG_WINDOW_NAME(kMovableModalWindowClass),
        ADD_DEBUG_WINDOW_NAME(kModalWindowClass),
        { 0, 0 }
    };
    qDebug("Qt: internal: ************* Creating new window %p (%s::%s)", q, q->metaObject()->className(),
            q->objectName().toLocal8Bit().constData());
    bool found_class = false;
    for(int i = 0; known_classes[i].name; i++) {
        if(wclass == known_classes[i].tag) {
            found_class = true;
            qDebug("Qt: internal: ** Class: %s", known_classes[i].name);
            break;
        }
    }
    if(!found_class)
        qDebug("Qt: internal: !! Class: Unknown! (%d)", (int)wclass);
    if(wattr) {
        WindowAttributes tmp_wattr = wattr;
        qDebug("Qt: internal: ** Attributes:");
        for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
            if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
                tmp_wattr ^= known_attribs[i].tag;
                qDebug("Qt: internal: * %s %s", known_attribs[i].name,
                        (GetAvailableWindowAttributes(wclass) & known_attribs[i].tag) ? "" : "(*)");
            }
        }
        if(tmp_wattr)
            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
    }
#endif

#ifndef QT_MAC_USE_COCOA
    /* Just to be extra careful we will change to the kUtilityWindowClass if the
       requested attributes cannot be used */
    if((GetAvailableWindowAttributes(wclass) & wattr) != wattr) {
        WindowClass tmp_class = wclass;
        if(wclass == kToolbarWindowClass || wclass == kUtilityWindowClass)
            wclass = kFloatingWindowClass;
        if(tmp_class != wclass) {
            if(!grp)
                grp = GetWindowGroupOfClass(wclass);
            wclass = tmp_class;
        }
    }
#endif
#endif
    topData()->wclass = wclass;
    topData()->wattr = wattr;
}

#ifndef QT_MAC_USE_COCOA  // This is handled in Cocoa via our category.
void QWidgetPrivate::initWindowPtr()
{
    Q_Q(QWidget);
    OSWindowRef windowRef = qt_mac_window_for(qt_mac_nativeview_for(q)); //do not create!
    if(!windowRef)
        return;
    QWidget *window = q->window(), *oldWindow = 0;
    if(GetWindowProperty(windowRef, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(oldWindow), 0, &oldWindow) == noErr) {
        Q_ASSERT(window == oldWindow);
        return;
    }

    if(SetWindowProperty(windowRef, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(window), &window) != noErr)
        qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__); //no real way to recover
    if(!q->windowType() != Qt::Desktop) { //setup an event callback handler on the window
        InstallWindowEventHandler(windowRef, make_win_eventUPP(), GetEventTypeCount(window_events),
                window_events, static_cast<void *>(qApp), &window_event);
    }
}

void QWidgetPrivate::finishCreateWindow_sys_Carbon(OSWindowRef windowRef)
{
    Q_Q(QWidget);
    const Qt::WindowType type = q->windowType();
    Qt::WindowFlags &flags = data.window_flags;
    QWidget *parentWidget = q->parentWidget();

    const bool desktop = (type == Qt::Desktop);
    const bool dialog = (type == Qt::Dialog
                         || type == Qt::Sheet
                         || type == Qt::Drawer
                         || (flags & Qt::MSWindowsFixedSizeDialogHint));
    QTLWExtra *topExtra = topData();
    quint32 wattr = topExtra->wattr;
    if (!desktop)
        SetAutomaticControlDragTrackingEnabledForWindow(windowRef, true);
    HIWindowChangeFeatures(windowRef, kWindowCanCollapse, 0);
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
        if (wattr & kWindowHideOnSuspendAttribute)
            HIWindowChangeAvailability(windowRef, kHIWindowExposeHidden, 0);
        else
            HIWindowChangeAvailability(windowRef, 0, kHIWindowExposeHidden);
    }
#endif
    if ((flags & Qt::WindowStaysOnTopHint))
        ChangeWindowAttributes(windowRef, kWindowNoAttributes, kWindowHideOnSuspendAttribute);
    if (qt_mac_is_macdrawer(q) && parentWidget)
        SetDrawerParent(windowRef, qt_mac_window_for (parentWidget));
    if (topExtra->group) {
        qt_mac_release_window_group(topExtra->group);
        topExtra->group = 0;
    }
    if (type == Qt::ToolTip)
        qt_mac_set_window_group_to_tooltip(windowRef);
    else if (type == Qt::Popup && (flags & Qt::WindowStaysOnTopHint))
        qt_mac_set_window_group_to_popup(windowRef);
    else if (flags & Qt::WindowStaysOnTopHint)
        qt_mac_set_window_group_to_stays_on_top(windowRef, type);
    else if (dialog)
        SetWindowGroup(windowRef, GetWindowGroupOfClass(kMovableModalWindowClass));

#ifdef DEBUG_WINDOW_CREATE
    if (WindowGroupRef grpf = GetWindowGroup(windowRef)) {
        QCFString cfname;
        CopyWindowGroupName(grpf, &cfname);
        SInt32 lvl;
        GetWindowGroupLevel(grpf, &lvl);
        const char *from = "Default";
        if (topExtra && grpf == topData()->group)
            from = "Created";
        else if (grpf == grp)
            from = "Copied";
        qDebug("Qt: internal: With window group '%s' [%p] @ %d: %s",
                static_cast<QString>(cfname).toLatin1().constData(), grpf, (int)lvl, from);
    } else {
        qDebug("Qt: internal: No window group!!!");
    }
    HIWindowAvailability hi_avail = 0;
    if (HIWindowGetAvailability(windowRef, &hi_avail) == noErr) {
        struct {
            UInt32 tag;
            const char *name;
        } known_avail[] = {
            ADD_DEBUG_WINDOW_NAME(kHIWindowExposeHidden),
            { 0, 0 }
        };
        qDebug("Qt: internal: ** HIWindowAvailibility:");
        for (int i = 0; hi_avail && known_avail[i].name; i++) {
            if ((hi_avail & known_avail[i].tag) == known_avail[i].tag) {
                hi_avail ^= known_avail[i].tag;
                qDebug("Qt: internal: * %s", known_avail[i].name);
            }
        }
        if (hi_avail)
            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)hi_avail);
    }
#undef ADD_DEBUG_WINDOW_NAME
#endif
    if (extra && !extra->mask.isEmpty())
        ReshapeCustomWindow(windowRef);
    SetWindowModality(windowRef, kWindowModalityNone, 0);
    if (qt_mac_is_macdrawer(q))
        SetDrawerOffsets(windowRef, 0.0, 25.0);
    data.fstrut_dirty = true; // when we create a toplevel widget, the frame strut should be dirty
    HIViewRef hiview = (HIViewRef)data.winid;
    HIViewRef window_hiview = qt_mac_get_contentview_for(windowRef);
    if(!hiview) {
        hiview = qt_mac_create_widget(q, this, window_hiview);
        setWinId((WId)hiview);
    } else {
        HIViewAddSubview(window_hiview, hiview);
    }
    if (hiview) {
        Rect win_rect;
        GetWindowBounds(qt_mac_window_for (window_hiview), kWindowContentRgn, &win_rect);
        HIRect bounds = CGRectMake(0, 0, win_rect.right-win_rect.left, win_rect.bottom-win_rect.top);
        HIViewSetFrame(hiview, &bounds);
        HIViewSetVisible(hiview, true);
        if (q->testAttribute(Qt::WA_DropSiteRegistered))
            registerDropSite(true);
        transferChildren();
    }
    initWindowPtr();

    if (topExtra->posFromMove) {
        updateFrameStrut();
        const QRect &fStrut = frameStrut();
        Rect r;
        SetRect(&r, data.crect.left(), data.crect.top(), data.crect.right() + 1, data.crect.bottom() + 1);
        SetRect(&r, r.left + fStrut.left(), r.top + fStrut.top(),
                    (r.left + fStrut.left() + data.crect.width()) - fStrut.right(),
                    (r.top + fStrut.top() + data.crect.height()) - fStrut.bottom());
        SetWindowBounds(windowRef, kWindowContentRgn, &r);
        topExtra->posFromMove = false;
    }

    if (q->testAttribute(Qt::WA_WState_WindowOpacitySet)){
        q->setWindowOpacity(topExtra->opacity / 255.0f);
    } else if (qt_mac_is_macsheet(q)){
        SetThemeWindowBackground(qt_mac_window_for(q), kThemeBrushSheetBackgroundTransparent, true);
        CGFloat alpha = 0;
        GetWindowAlpha(qt_mac_window_for(q), &alpha);
        if (alpha == 1){
            // For some reason the 'SetThemeWindowBackground' does not seem
            // to work. So we do this little hack until it hopefully starts to
            // work in newer versions of mac OS.
            q->setWindowOpacity(0.95f);
            q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
        }
    } else{
        // If the window has been recreated after beeing e.g. a sheet,
        // make sure that we don't report a faulty opacity:
        q->setWindowOpacity(1.0f);
        q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
    }

    // Since we only now have a window, sync our state.
    macUpdateHideOnSuspend();
    macUpdateOpaqueSizeGrip();
    macUpdateMetalAttribute();
    macUpdateIgnoreMouseEvents();
    setWindowTitle_helper(extra->topextra->caption);
    setWindowIconText_helper(extra->topextra->iconText);
    setWindowFilePath_helper(extra->topextra->filePath);
    setWindowModified_sys(q->isWindowModified());
    updateFrameStrut();
    qt_mac_update_sizer(q);
    applyMaxAndMinSizeOnWindow();
}
#else  // QT_MAC_USE_COCOA
void QWidgetPrivate::finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ voidWindowRef)
{
    Q_Q(QWidget);
    QMacCocoaAutoReleasePool pool;
    NSWindow *windowRef = static_cast<NSWindow *>(voidWindowRef);
    const Qt::WindowType type = q->windowType();
    Qt::WindowFlags &flags = data.window_flags;
    QWidget *parentWidget = q->parentWidget();

    const bool popup = (type == Qt::Popup);
    const bool dialog = (type == Qt::Dialog
                         || type == Qt::Sheet
                         || type == Qt::Drawer
                         || (flags & Qt::MSWindowsFixedSizeDialogHint));
    QTLWExtra *topExtra = topData();

    if ((popup || type == Qt::Tool || type == Qt::ToolTip) && !q->isModal()) {
        [windowRef setHidesOnDeactivate:YES];
    } else {
        [windowRef setHidesOnDeactivate:NO];
    }
    [windowRef setHasShadow:YES];
    Q_UNUSED(parentWidget);
    Q_UNUSED(dialog);

    data.fstrut_dirty = true; // when we create a toplevel widget, the frame strut should be dirty
    OSViewRef nsview = (OSViewRef)data.winid;
    OSViewRef window_contentview = qt_mac_get_contentview_for(windowRef);
    if (!nsview) {
        nsview = qt_mac_create_widget(q, this, window_contentview);
        setWinId(WId(nsview));
    } else {
        [window_contentview addSubview:nsview];
    }
    if (nsview) {
        NSRect bounds = [window_contentview bounds];
        [nsview setFrame:bounds];
        [nsview setHidden:NO];
        if (q->testAttribute(Qt::WA_DropSiteRegistered))
            registerDropSite(true);
        transferChildren();
    }

    if (topExtra->posFromMove) {
        updateFrameStrut();

        const QRect &fStrut = frameStrut();
        const QRect &crect = data.crect;
        const QRect frameRect(QPoint(crect.left(), crect.top()),
                              QSize(fStrut.left() + fStrut.right() + crect.width(),
                                    fStrut.top() + fStrut.bottom() + crect.height()));
        NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1),
                                           frameRect.width(), frameRect.height());
        [windowRef setFrame:cocoaFrameRect display:NO];
        topExtra->posFromMove = false;
    }

    if (q->testAttribute(Qt::WA_WState_WindowOpacitySet)){
        q->setWindowOpacity(topExtra->opacity / 255.0f);
    } else if (qt_mac_is_macsheet(q)){
        CGFloat alpha = [qt_mac_window_for(q) alphaValue];
        if (alpha >= 1.0) {
            q->setWindowOpacity(0.95f);
            q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
        }
    } else{
        // If the window has been recreated after beeing e.g. a sheet,
        // make sure that we don't report a faulty opacity:
        q->setWindowOpacity(1.0f);
        q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
    }

    macUpdateHideOnSuspend();
    macUpdateOpaqueSizeGrip();
    macUpdateIgnoreMouseEvents();
    setWindowTitle_helper(extra->topextra->caption);
    setWindowIconText_helper(extra->topextra->iconText);
    setWindowModified_sys(q->isWindowModified());
    updateFrameStrut();
    syncCocoaMask();
    macUpdateIsOpaque();
    qt_mac_update_sizer(q);
    applyMaxAndMinSizeOnWindow();
}

#endif // QT_MAC_USE_COCOA

/*
 Recreates widget window. Useful if immutable
 properties for it has changed.
 */
void QWidgetPrivate::recreateMacWindow()
{
    Q_Q(QWidget);
    OSViewRef myView = qt_mac_nativeview_for(q);
    OSWindowRef oldWindow = qt_mac_window_for(myView);
#ifndef QT_MAC_USE_COCOA
    HIViewRemoveFromSuperview(myView);
    determineWindowClass();
    createWindow_sys();
    if (QMainWindowLayout *mwl = qobject_cast<QMainWindowLayout *>(q->layout())) {
        mwl->updateHIToolBarStatus();
    }

    if (IsWindowVisible(oldWindow))
        show_sys();
#else
    QMacCocoaAutoReleasePool pool;
    [myView removeFromSuperview];
    determineWindowClass();
    createWindow_sys();
    if (NSToolbar *toolbar = [oldWindow toolbar]) {
        OSWindowRef newWindow = qt_mac_window_for(myView);
        [newWindow setToolbar:toolbar];
        [toolbar setVisible:[toolbar isVisible]];
    }
    if ([oldWindow isVisible]){
        if ([oldWindow isSheet])
            [NSApp endSheet:oldWindow];
        [oldWindow orderOut:oldWindow];
        show_sys();
    }
#endif // QT_MAC_USE_COCOA

    // Release the window after creating the new window, because releasing it early
    // may cause the app to quit ("close on last window closed attribute")
    qt_mac_destructWindow(oldWindow);
}

void QWidgetPrivate::createWindow_sys()
{
    Q_Q(QWidget);
    Qt::WindowFlags &flags = data.window_flags;
    QWidget *parentWidget = q->parentWidget();

    QTLWExtra *topExtra = topData();
    if (topExtra->embedded)
        return;  // Simply return because this view "is" the top window.
    quint32 wattr = topExtra->wattr;

    if(parentWidget && (parentWidget->window()->windowFlags() & Qt::WindowStaysOnTopHint)) // If our parent has Qt::WStyle_StaysOnTop, so must we
        flags |= Qt::WindowStaysOnTopHint;

    data.fstrut_dirty = true;

    OSWindowRef windowRef = qt_mac_create_window(q, topExtra->wclass, wattr, data.crect);
    if (windowRef == 0)
        qWarning("QWidget: Internal error: %s:%d: If you reach this error please contact Trolltech and include the\n"
                "      WidgetFlags used in creating the widget.", __FILE__, __LINE__);
#ifndef QT_MAC_USE_COCOA
    finishCreateWindow_sys_Carbon(windowRef);
#else
    finishCreateWindow_sys_Cocoa(windowRef);
#endif
}

void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
{
    Q_Q(QWidget);
    OSViewRef destroyid = 0;
#ifndef QT_MAC_USE_COCOA
    window_event = 0;
#endif

    Qt::WindowType type = q->windowType();
    Qt::WindowFlags flags = data.window_flags;
    QWidget *parentWidget = q->parentWidget();

    bool topLevel = (flags & Qt::Window);
    bool popup = (type == Qt::Popup);
    bool dialog = (type == Qt::Dialog
                   || type == Qt::Sheet
                   || type == Qt::Drawer
                   || (flags & Qt::MSWindowsFixedSizeDialogHint));
    bool desktop = (type == Qt::Desktop);

    // Determine this early for top-levels so, we can use it later.
    if (topLevel)
        determineWindowClass();

    if (desktop) {
        QSize desktopSize = qt_mac_desktopSize();
        q->setAttribute(Qt::WA_WState_Visible);
        data.crect.setRect(0, 0, desktopSize.width(), desktopSize.height());
        dialog = popup = false;                  // force these flags off
    } else {
        q->setAttribute(Qt::WA_WState_Visible, false);

        if (topLevel && (type != Qt::Drawer)) {
            if (QDesktopWidget *dsk = QApplication::desktop()) { // calc pos/size from screen
                const bool wasResized = q->testAttribute(Qt::WA_Resized);
                const bool wasMoved = q->testAttribute(Qt::WA_Moved);
                int deskn = dsk->primaryScreen();
                if (parentWidget && parentWidget->windowType() != Qt::Desktop)
                    deskn = dsk->screenNumber(parentWidget);
                QRect screenGeo = dsk->screenGeometry(deskn);
                if (!wasResized) {
#ifndef QT_MAC_USE_COCOA
                    data.crect.setSize(QSize(screenGeo.width()/2, 4*screenGeo.height()/10));
#else
                    NSRect newRect = [NSWindow frameRectForContentRect:NSMakeRect(0, 0,
                                                                  screenGeo.width() / 2.,
                                                                  4 * screenGeo.height() / 10.)
                                        styleMask:topData()->wattr];
                    data.crect.setSize(QSize(newRect.size.width, newRect.size.height));
#endif
                    // Constrain to minimums and maximums we've set
                    if (extra->minw > 0)
                        data.crect.setWidth(qMax(extra->minw, data.crect.width()));
                    if (extra->minh > 0)
                        data.crect.setHeight(qMax(extra->minh, data.crect.height()));
                    if (extra->maxw > 0)
                        data.crect.setWidth(qMin(extra->maxw, data.crect.width()));
                    if (extra->maxh > 0)
                        data.crect.setHeight(qMin(extra->maxh, data.crect.height()));
                }
                if (!wasMoved && !q->testAttribute(Qt::WA_DontShowOnScreen))
                    data.crect.moveTopLeft(QPoint(screenGeo.width()/4,
                                                  3 * screenGeo.height() / 10));
            }
        }
    }


    if(!window)                              // always initialize
        initializeWindow=true;

    hd = 0;
    if(window) {                                // override the old window (with a new NSView)
        OSViewRef nativeView = OSViewRef(window);
        OSViewRef parent = 0;
#ifndef QT_MAC_USE_COCOA
        CFRetain(nativeView);
#else
        [nativeView retain];
#endif
        if (destroyOldWindow)
            destroyid = qt_mac_nativeview_for(q);
        bool transfer = false;
        setWinId((WId)nativeView);
#ifndef QT_MAC_USE_COCOA
#ifndef HIViewInstallEventHandler
        // Macro taken from the CarbonEvents Header on Tiger
#define HIViewInstallEventHandler( target, handler, numTypes, list, userData, outHandlerRef ) \
               InstallEventHandler( HIObjectGetEventTarget( (HIObjectRef) (target) ), (handler), (numTypes), (list), (userData), (outHandlerRef) )
#endif
        HIViewInstallEventHandler(nativeView, make_widget_eventUPP(), GetEventTypeCount(widget_events), widget_events, 0, 0);
#endif
        if(topLevel) {
            for(int i = 0; i < 2; ++i) {
                if(i == 1) {
                    if(!initializeWindow)
                        break;
                    createWindow_sys();
                }
                if(OSWindowRef windowref = qt_mac_window_for(nativeView)) {
#ifndef QT_MAC_USE_COCOA
                    CFRetain(windowref);
#else
                    [windowref retain];
#endif
                    if (initializeWindow) {
                        parent = qt_mac_get_contentview_for(windowref);
                    } else {
#ifndef QT_MAC_USE_COCOA
                        parent = HIViewGetSuperview(nativeView);
#else
                        parent = [nativeView superview];
#endif
                    }
                    break;
                }
            }
            if(!parent)
                transfer = true;
        } else if (parentWidget) {
            // I need to be added to my parent, therefore my parent needs an NSView
            parentWidget->createWinId();
            parent = qt_mac_nativeview_for(parentWidget);
        }
        if(parent != nativeView && parent) {
#ifndef QT_MAC_USE_COCOA
            HIViewAddSubview(parent, nativeView);
#else
            [parent addSubview:nativeView];
#endif
        }
        if(transfer)
            transferChildren();
        data.fstrut_dirty = true; // we'll re calculate this later
        q->setAttribute(Qt::WA_WState_Visible,
#ifndef QT_MAC_USE_COCOA
                        HIViewIsVisible(nativeView)
#else
                        ![nativeView isHidden]
#endif
                        );
        if(initializeWindow) {
#ifndef QT_MAC_USE_COCOA
            HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
            HIViewSetFrame(nativeView, &bounds);
            q->setAttribute(Qt::WA_WState_Visible, HIViewIsVisible(nativeView));
#else
            NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
            [nativeView setFrame:bounds];
            q->setAttribute(Qt::WA_WState_Visible, [nativeView isHidden]);
#endif
        }
#ifndef QT_MAC_USE_COCOA
        initWindowPtr();
#endif
    } else if (desktop) {                        // desktop widget
        if (!qt_root_win)
            QWidgetPrivate::qt_create_root_win();
        Q_ASSERT(qt_root_win);
        WId rootWinID = 0;
#ifndef QT_MAC_USE_COCOA
        CFRetain(qt_root_win);
        if(HIViewRef rootContentView = HIViewGetRoot(qt_root_win)) {
            rootWinID = (WId)rootContentView;
            CFRetain(rootContentView);
        }
#else
        [qt_root_win retain];
        if (OSViewRef rootContentView = [qt_root_win contentView]) {
            rootWinID = (WId)rootContentView;
            [rootContentView retain];
        }
#endif
        setWinId(rootWinID);
    } else if (topLevel) {
        determineWindowClass();
        if(OSViewRef osview = qt_mac_create_widget(q, this, 0)) {
#ifndef QT_MAC_USE_COCOA
            HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(),
                                       data.crect.width(), data.crect.height());
            HIViewSetFrame(osview, &bounds);
#else
            NSRect bounds = NSMakeRect(data.crect.x(), flipYCoordinate(data.crect.y()),
                                       data.crect.width(), data.crect.height());
            [osview setFrame:bounds];
#endif
            setWinId((WId)osview);
        }
    } else {
        data.fstrut_dirty = false; // non-toplevel widgets don't have a frame, so no need to update the strut
        if(OSViewRef osview = qt_mac_create_widget(q, this, qt_mac_nativeview_for(parentWidget))) {
#ifndef QT_MAC_USE_COCOA
            HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
            HIViewSetFrame(osview, &bounds);
            setWinId((WId)osview);
#else
            NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
            [osview setFrame:bounds];
            setWinId((WId)osview);
#endif
            if (q->testAttribute(Qt::WA_DropSiteRegistered))
                registerDropSite(true);
        }
    }

    updateIsOpaque();
    if (q->hasFocus())
        setFocus_sys();
    if (!topLevel && initializeWindow)
        setWSGeometry();

    if (destroyid)
        qt_mac_destructView(destroyid);
}

/*!
    Returns the QuickDraw handle of the widget. Use of this function is not
    portable. This function will return 0 if QuickDraw is not supported, or
    if the handle could not be created.

    \warning This function is only available on Mac OS X.
*/

Qt::HANDLE
QWidget::macQDHandle() const
{
#ifndef QT_MAC_USE_COCOA
    return d_func()->qd_hd;
#else
    return 0;
#endif
}

/*!
  Returns the CoreGraphics handle of the widget. Use of this function is
  not portable. This function will return 0 if no painter context can be
  established, or if the handle could not be created.

  \warning This function is only available on Mac OS X.
*/
Qt::HANDLE
QWidget::macCGHandle() const
{
    return handle();
}

void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
{
    Q_D(QWidget);
    if (!isWindow() && parentWidget())
        parentWidget()->d_func()->invalidateBuffer(geometry());
    d->deactivateWidgetCleanup();
    qt_mac_event_release(this);
    if(testAttribute(Qt::WA_WState_Created)) {
        QMacCocoaAutoReleasePool pool;
        setAttribute(Qt::WA_WState_Created, false);
        QObjectList chldrn = children();
        for(int i = 0; i < chldrn.size(); i++) {  // destroy all widget children
            QObject *obj = chldrn.at(i);
            if(obj->isWidgetType())
                static_cast<QWidget*>(obj)->destroy(destroySubWindows, destroySubWindows);
        }
        if(mac_mouse_grabber == this)
            releaseMouse();
        if(mac_keyboard_grabber == this)
            releaseKeyboard();
        if(acceptDrops())
            setAcceptDrops(false);

        if(testAttribute(Qt::WA_ShowModal))          // just be sure we leave modal
            QApplicationPrivate::leaveModal(this);
        else if((windowType() == Qt::Popup))
            qApp->d_func()->closePopup(this);
        if (destroyWindow) {
            if(OSViewRef hiview = qt_mac_nativeview_for(this)) {
                OSWindowRef window = 0;
                NSDrawer *drawer = nil;
#ifdef QT_MAC_USE_COCOA
                if (qt_mac_is_macdrawer(this)) {
                    drawer = qt_mac_drawer_for(this);
                } else
#endif
                if (isWindow())
                    window = qt_mac_window_for(hiview);

                // Because of how "destruct" works, we have to do just a normal release for the root_win.
                if (window && window == qt_root_win) {
#ifndef QT_MAC_USE_COCOA
                    CFRelease(hiview);
#else
                    [hiview release];
#endif
                } else {
                    qt_mac_destructView(hiview);
                }
                if (drawer)
                    qt_mac_destructDrawer(drawer);
                if (window)
                    qt_mac_destructWindow(window);
            }
        }
        d->setWinId(0);
    }
}

void QWidgetPrivate::transferChildren()
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;  // Can't add any views anyway

    QObjectList chlist = q->children();
    for (int i = 0; i < chlist.size(); ++i) {
        QObject *obj = chlist.at(i);
        if (obj->isWidgetType()) {
            QWidget *w = (QWidget *)obj;
            if (!w->isWindow()) {
                // This seems weird, no need to call it in a loop right?
                if (!topData()->caption.isEmpty())
                    setWindowTitle_helper(extra->topextra->caption);
                if (w->testAttribute(Qt::WA_WState_Created)) {
#ifndef QT_MAC_USE_COCOA
                    HIViewAddSubview(qt_mac_nativeview_for(q), qt_mac_nativeview_for(w));
#else
                    // New NSWindows get an extra reference when drops are
                    // registered (at least in 10.5) which means that we may
                    // access the window later and get a crash (becasue our
                    // widget is dead). Work around this be having the drop
                    // site disabled until it is part of the new hierarchy.
                    bool oldRegistered = w->testAttribute(Qt::WA_DropSiteRegistered);
                    w->setAttribute(Qt::WA_DropSiteRegistered, false);
                    [qt_mac_nativeview_for(q) addSubview:qt_mac_nativeview_for(w)];
                    w->setAttribute(Qt::WA_DropSiteRegistered, oldRegistered);
#endif
                }
            }
        }
    }
}

void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
{
    Q_Q(QWidget);
    QMacCocoaAutoReleasePool pool;
    QTLWExtra *topData = maybeTopData();
    bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
#ifdef QT_MAC_USE_COCOA
    bool wasWindow = q->isWindow();
#endif
    OSViewRef old_id = 0;

    if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
        q->parentWidget()->d_func()->invalidateBuffer(q->geometry());

    // Maintain the glWidgets list on parent change: remove "our" gl widgets
    // from the list on the old parent and grandparents.
    if (glWidgets.isEmpty() == false) {
        QWidget *current = q->parentWidget();
        while (current) {
            for (QList<QWidgetPrivate::GlWidgetInfo>::const_iterator it = glWidgets.constBegin();
                 it != glWidgets.constEnd(); ++it)
                current->d_func()->glWidgets.removeAll(*it);

            if (current->isWindow())
                break;
            current = current->parentWidget();
        }
    }

#ifndef QT_MAC_USE_COCOA
    EventHandlerRef old_window_event = 0;
#else
    bool oldToolbarVisible = false;
    NSDrawer *oldDrawer = nil;
    NSToolbar *oldToolbar = 0;
#endif
    if (wasCreated && !(q->windowType() == Qt::Desktop)) {
        old_id = qt_mac_nativeview_for(q);
#ifndef QT_MAC_USE_COCOA
        old_window_event = window_event;
#else
        OSWindowRef oldWindow = qt_mac_window_for(old_id);
        if (qt_mac_is_macdrawer(q)) {
            oldDrawer = qt_mac_drawer_for(q);
        }
        if (wasWindow) {
            oldToolbar = [oldWindow toolbar];
            oldToolbarVisible = [oldToolbar isVisible];
        }
#endif
    }
    QWidget* oldtlw = q->window();

    if (q->testAttribute(Qt::WA_DropSiteRegistered))
        q->setAttribute(Qt::WA_DropSiteRegistered, false);

    //recreate and setup flags
    QObjectPrivate::setParent_helper(parent);
    QPoint pt = q->pos();
    bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
    if (wasCreated && !qt_isGenuineQWidget(q))
        return;

    if ((data.window_flags & Qt::Sheet) && topData && topData->opacity == 242)
        q->setWindowOpacity(1.0f);

    setWinId(0); //do after the above because they may want the id

    data.window_flags = f;
    q->setAttribute(Qt::WA_WState_Created, false);
    q->setAttribute(Qt::WA_WState_Visible, false);
    q->setAttribute(Qt::WA_WState_Hidden, false);
    adjustFlags(data.window_flags, q);
    // keep compatibility with previous versions, we need to preserve the created state
    // (but we recreate the winId for the widget being reparented, again for compatibility)
    if (wasCreated || (!q->isWindow() && parent->testAttribute(Qt::WA_WState_Created))) {
        createWinId();
        if (q->isWindow()) {
#ifndef QT_MAC_USE_COCOA
            // We do this down below for wasCreated, so avoid doing this twice
            // (only for performance, it gets called a lot anyway).
            if (!wasCreated) {
                if (QMainWindowLayout *mwl = qobject_cast<QMainWindowLayout *>(q->layout())) {
                    mwl->updateHIToolBarStatus();
                }
            }
#else
            // Simply transfer our toolbar over. Everything should stay put, unlike in Carbon.
            if (oldToolbar && !(f & Qt::FramelessWindowHint)) {
                OSWindowRef newWindow = qt_mac_window_for(q);
                [newWindow setToolbar:oldToolbar];
                [oldToolbar setVisible:oldToolbarVisible];
            }
#endif
        }
    }
    if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
        q->setAttribute(Qt::WA_WState_Hidden);
    q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);

    if (wasCreated) {
        transferChildren();
#ifndef QT_MAC_USE_COCOA
        // If we were a unified window, We just transfered our toolbars out of the unified toolbar.
        // So redo the status one more time. It apparently is not an issue with Cocoa.
        if (q->isWindow()) {
            if (QMainWindowLayout *mwl = qobject_cast<QMainWindowLayout *>(q->layout())) {
                mwl->updateHIToolBarStatus();
            }
        }
#endif

        if (topData &&
                (!topData->caption.isEmpty() || !topData->filePath.isEmpty()))
            setWindowTitle_helper(q->windowTitle());
    }

    if (q->testAttribute(Qt::WA_AcceptDrops)
        || (!q->isWindow() && q->parentWidget()
            && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
        q->setAttribute(Qt::WA_DropSiteRegistered, true);

    //cleanup
#ifndef QT_MAC_USE_COCOA
    if (old_window_event)
        RemoveEventHandler(old_window_event);
#endif
    if (old_id) { //don't need old window anymore
        OSWindowRef window = (oldtlw == q) ? qt_mac_window_for(old_id) : 0;
        qt_mac_destructView(old_id);

#ifdef QT_MAC_USE_COCOA
        if (oldDrawer) {
            qt_mac_destructDrawer(oldDrawer);
        } else
#endif
        if (window)
            qt_mac_destructWindow(window);
    }

    // Maintain the glWidgets list on parent change: add "our" gl widgets
    // to the list on the new parent and grandparents.
    if (glWidgets.isEmpty() == false) {
        QWidget *current = q->parentWidget();
        while (current) {
            current->d_func()->glWidgets += glWidgets;
            if (current->isWindow())
                break;
            current = current->parentWidget();
        }
    }

    invalidateBuffer(q->rect());
    qt_event_request_window_change(q);
}

QPoint QWidget::mapToGlobal(const QPoint &pos) const
{
    Q_D(const QWidget);
    if (!testAttribute(Qt::WA_WState_Created)) {
        QPoint p = pos + data->crect.topLeft();
        return isWindow() ?  p : parentWidget()->mapToGlobal(p);
    }
#ifndef QT_MAC_USE_COCOA
    QPoint tmp = d->mapToWS(pos);
    HIPoint hi_pos = CGPointMake(tmp.x(), tmp.y());
    HIViewConvertPoint(&hi_pos, qt_mac_nativeview_for(this), 0);
    Rect win_rect;
    GetWindowBounds(qt_mac_window_for(this), kWindowStructureRgn, &win_rect);
    return QPoint((int)hi_pos.x+win_rect.left, (int)hi_pos.y+win_rect.top);
#else
    QPoint tmp = d->mapToWS(pos);
    NSPoint hi_pos = NSMakePoint(tmp.x(), tmp.y());
    hi_pos = [qt_mac_nativeview_for(this) convertPoint:hi_pos toView:nil];
    NSRect win_rect = [qt_mac_window_for(this) frame];
    hi_pos.x += win_rect.origin.x;
    hi_pos.y += win_rect.origin.y;
    // If we aren't the desktop we need to flip, if you flip the desktop on itself, you get the other problem.
    return ((window()->windowFlags() & Qt::Desktop) == Qt::Desktop) ? QPointF(hi_pos.x, hi_pos.y).toPoint()
                                                                    : flipPoint(hi_pos).toPoint();
#endif
}

QPoint QWidget::mapFromGlobal(const QPoint &pos) const
{
    Q_D(const QWidget);
    if (!testAttribute(Qt::WA_WState_Created)) {
        QPoint p = isWindow() ?  pos : parentWidget()->mapFromGlobal(pos);
        return p - data->crect.topLeft();
    }
#ifndef QT_MAC_USE_COCOA
    Rect win_rect;
    GetWindowBounds(qt_mac_window_for(this), kWindowStructureRgn, &win_rect);
    HIPoint hi_pos = CGPointMake(pos.x()-win_rect.left, pos.y()-win_rect.top);
    HIViewConvertPoint(&hi_pos, 0, qt_mac_nativeview_for(this));
    return d->mapFromWS(QPoint((int)hi_pos.x, (int)hi_pos.y));
#else
    NSRect win_rect = [qt_mac_window_for(this) frame];
    // The Window point is in "Cocoa coordinates," but the view is in "Qt coordinates"
    // so make sure to keep them in sync.
    NSPoint hi_pos = NSMakePoint(pos.x()-win_rect.origin.x,
                                 flipYCoordinate(pos.y())-win_rect.origin.y);
    hi_pos = [qt_mac_nativeview_for(this) convertPoint:hi_pos fromView:0];
    return d->mapFromWS(QPoint(qRound(hi_pos.x), qRound(hi_pos.y)));
#endif
}

void QWidgetPrivate::updateSystemBackground()
{
}

void QWidgetPrivate::setCursor_sys(const QCursor &)
{
#ifndef QT_MAC_USE_COCOA
    qt_mac_update_cursor();
#else
     Q_Q(QWidget);
    if (q->testAttribute(Qt::WA_WState_Created)) {
        [qt_mac_window_for(q) invalidateCursorRectsForView:qt_mac_nativeview_for(q)];
    }
#endif
}

void QWidgetPrivate::unsetCursor_sys()
{
#ifndef QT_MAC_USE_COCOA
    qt_mac_update_cursor();
#else
     Q_Q(QWidget);
    if (q->testAttribute(Qt::WA_WState_Created)) {
        [qt_mac_window_for(q) invalidateCursorRectsForView:qt_mac_nativeview_for(q)];
    }
#endif
}

void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
{
    Q_Q(QWidget);
    if (q->isWindow()) {
#ifndef QT_MAC_USE_COCOA
        SetWindowTitleWithCFString(qt_mac_window_for(q), QCFString(caption));
#else
        QMacCocoaAutoReleasePool pool;
        [qt_mac_window_for(q)
          setTitle:reinterpret_cast<const NSString *>(static_cast<CFStringRef>(QCFString(caption)))];
#endif
    }
}

void QWidgetPrivate::setWindowModified_sys(bool mod)
{
    Q_Q(QWidget);
    if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) {
#ifndef QT_MAC_USE_COCOA
        SetWindowModified(qt_mac_window_for(q), mod);
#else
        [qt_mac_window_for(q) setDocumentEdited:mod];
#endif
    }
}

void QWidgetPrivate::setWindowFilePath_sys(const QString &filePath)
{
    Q_Q(QWidget);
#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    [qt_mac_window_for(q) setRepresentedFilename:reinterpret_cast<const NSString *>(static_cast<CFStringRef>(QCFString(filePath)))];
#else
    bool validRef = false;
    FSRef ref;
    bzero(&ref, sizeof(ref));
    OSStatus status;

    if (!filePath.isEmpty()) {
        status = FSPathMakeRef(reinterpret_cast<const UInt8 *>(filePath.toUtf8().constData()), &ref, 0);
        validRef = (status == noErr);
    }
    // Set the proxy regardless, since this is our way of clearing it as well, but ignore the
    // return value as well.
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
        if (validRef) {
            status = HIWindowSetProxyFSRef(qt_mac_window_for(q), &ref);
        } else {
            status = RemoveWindowProxy(qt_mac_window_for(q));
        }
    } else {
        // Convert to an FSSpec and set it. It's deprecated but it works for where we don't have the other call.
        if (validRef) {
            FSSpec fsspec;
            FSGetCatalogInfo(&ref, kFSCatInfoNone, 0, 0, &fsspec, 0);
            status = SetWindowProxyFSSpec(qt_mac_window_for(q), &fsspec);
        } else {
            status = RemoveWindowProxy(qt_mac_window_for(q));
        }
    }
    if (status != noErr)
        qWarning("QWidget::setWindowFilePath: Error setting proxyicon for path (%s):%ld",
                qPrintable(filePath), status);
#endif
}

void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
{
    Q_Q(QWidget);

    if (!q->testAttribute(Qt::WA_WState_Created))
        return;

    QTLWExtra *topData = this->topData();
    if (topData->iconPixmap && !forceReset) // already set
        return;

    QIcon icon = q->windowIcon();
    QPixmap *pm = 0;
    if (!icon.isNull()) {
        // now create the extra
        if (!topData->iconPixmap) {
            pm = new QPixmap(icon.pixmap(QSize(22, 22)));
            topData->iconPixmap = pm;
        } else {
            pm = topData->iconPixmap;
        }
    }
    if (q->isWindow()) {
#ifndef QT_MAC_USE_COCOA
        IconRef previousIcon = 0;
        if (icon.isNull()) {
            RemoveWindowProxy(qt_mac_window_for(q));
            previousIcon = topData->windowIcon;
            topData->windowIcon = 0;
        } else {
            WindowClass wclass;
            GetWindowClass(qt_mac_window_for(q), &wclass);

            if (wclass == kDocumentWindowClass) {
                IconRef newIcon = qt_mac_create_iconref(*pm);
                previousIcon = topData->windowIcon;
                topData->windowIcon = newIcon;
                SetWindowProxyIcon(qt_mac_window_for(q), newIcon);
            }
        }

        // Release the previous icon if it was set by this function.
        if (previousIcon != 0)
            ReleaseIconRef(previousIcon);
#else
        QMacCocoaAutoReleasePool pool;
        NSButton *iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
        if (icon.isNull()) {
            [iconButton setImage:nil];
        } else {
            NSImage *image = static_cast<NSImage *>(qt_mac_create_nsimage(*pm));
            [iconButton setImage:image];
            [image release];
        }
#endif
    }
}

void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
{
    Q_Q(QWidget);
    if(q->isWindow() && !iconText.isEmpty()) {
#ifndef QT_MAC_USE_COCOA
        SetWindowAlternateTitle(qt_mac_window_for(q), QCFString(iconText));
#else
        QMacCocoaAutoReleasePool pool;
        [qt_mac_window_for(q)
            setMiniwindowTitle:reinterpret_cast<const NSString *>(static_cast<CFStringRef>(QCFString(iconText)))];
#endif
    }
}

void QWidget::grabMouse()
{
    if(isVisible() && !qt_nograb()) {
        if(mac_mouse_grabber)
            mac_mouse_grabber->releaseMouse();
        mac_mouse_grabber=this;
    }
}

void QWidget::grabMouse(const QCursor &)
{
    if(isVisible() && !qt_nograb()) {
        if(mac_mouse_grabber)
            mac_mouse_grabber->releaseMouse();
        mac_mouse_grabber=this;
    }
}

void QWidget::releaseMouse()
{
    if(!qt_nograb() && mac_mouse_grabber == this)
        mac_mouse_grabber = 0;
}

void QWidget::grabKeyboard()
{
    if(!qt_nograb()) {
        if(mac_keyboard_grabber)
            mac_keyboard_grabber->releaseKeyboard();
        mac_keyboard_grabber = this;
    }
}

void QWidget::releaseKeyboard()
{
    if(!qt_nograb() && mac_keyboard_grabber == this)
        mac_keyboard_grabber = 0;
}

QWidget *QWidget::mouseGrabber()
{
    return mac_mouse_grabber;
}

QWidget *QWidget::keyboardGrabber()
{
    return mac_keyboard_grabber;
}

void QWidget::activateWindow()
{
    QWidget *tlw = window();
    if(!tlw->isVisible() || !tlw->isWindow() || (tlw->windowType() == Qt::Desktop))
        return;
    qt_event_remove_activate();

    QWidget *fullScreenWidget = tlw;
    QWidget *parentW = tlw;
    // Find the oldest parent or the parent with fullscreen, whichever comes first.
    while (parentW) {
        fullScreenWidget = parentW->window();
        if (fullScreenWidget->windowState() & Qt::WindowFullScreen)
            break;
        parentW = fullScreenWidget->parentWidget();
    }

    if (fullScreenWidget->windowType() != Qt::ToolTip) {
        qt_mac_set_fullscreen_mode((fullScreenWidget->windowState() & Qt::WindowFullScreen) &&
                                               qApp->desktop()->screenNumber(this) == 0);
    }

    bool windowActive;
    OSWindowRef win = qt_mac_window_for(tlw);
#ifndef QT_MAC_USE_COCOA
    windowActive = IsWindowActive(win);
#else
    QMacCocoaAutoReleasePool pool;
    windowActive = [win isKeyWindow];
#endif
    if ((tlw->windowType() == Qt::Popup)
            || (tlw->windowType() == Qt::Tool)
            || qt_mac_is_macdrawer(tlw)
            || windowActive) {
#ifndef QT_MAC_USE_COCOA
        ActivateWindow(win, true);
#else
        [win makeKeyWindow];
#endif
        qApp->setActiveWindow(tlw);
    } else if(!isMinimized()) {
#ifndef QT_MAC_USE_COCOA
        SelectWindow(win);
#else
        [win makeKeyAndOrderFront:win];
#endif
    }
}

QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
{
    return new QMacWindowSurface(q_func());
}

void QWidgetPrivate::update_sys(const QRect &r)
{
    Q_Q(QWidget);
    if (r == q->rect()) {
        if (updateRedirectedToGraphicsProxyWidget(q, r))
            return;
        dirtyOnWidget += r;
#ifndef QT_MAC_USE_COCOA
            HIViewSetNeedsDisplay(qt_mac_nativeview_for(q), true);
#else
            [qt_mac_nativeview_for(q) setNeedsDisplay:YES];
#endif
        return;
    }

    int x = r.x(), y = r.y(), w = r.width(), h = r.height();
    if (w < 0)
        w = q->data->crect.width() - x;
    if (h < 0)
        h = q->data->crect.height() - y;
    if (w && h) {
        const QRect updateRect = QRect(x, y, w, h);
        if (updateRedirectedToGraphicsProxyWidget(q, updateRect))
            return;
#ifndef QT_MAC_USE_COCOA
#    if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
            dirtyOnWidget += updateRect;
            HIRect r = CGRectMake(x, y, w, h);
            HIViewSetNeedsDisplayInRect(qt_mac_nativeview_for(q), &r, true);
        } else
    #endif
        {
            q->update(QRegion(updateRect));
        }
#else
        [qt_mac_nativeview_for(q) setNeedsDisplayInRect:NSMakeRect(x, y, w, h)];
#endif
    }
}

void QWidgetPrivate::update_sys(const QRegion &rgn)
{
    Q_Q(QWidget);
    if (updateRedirectedToGraphicsProxyWidget(q, rgn))
        return;
    dirtyOnWidget += rgn;
#ifndef QT_MAC_USE_COCOA
    HIViewSetNeedsDisplayInRegion(qt_mac_nativeview_for(q), QMacSmartQuickDrawRegion(rgn.toQDRgn()), true);
#else
    // Cocoa doesn't do regions, it seems more efficient to just update the bounding rect instead of a potential number of message passes for each rect.
    const QRect &boundingRect = rgn.boundingRect();
    [qt_mac_nativeview_for(q) setNeedsDisplayInRect:NSMakeRect(boundingRect.x(),
                                                            boundingRect.y(), boundingRect.width(),
                                                            boundingRect.height())];
#endif
}

bool QWidgetPrivate::isRealWindow() const
{
    return q_func()->isWindow() && !topData()->embedded;
}

void QWidgetPrivate::show_sys()
{
    Q_Q(QWidget);
    if ((q->windowType() == Qt::Desktop)) //desktop is always visible
        return;

    invalidateBuffer(q->rect());
    if (q->testAttribute(Qt::WA_OutsideWSRange))
        return;
    QMacCocoaAutoReleasePool pool;
    q->setAttribute(Qt::WA_Mapped);
    if (q->testAttribute(Qt::WA_DontShowOnScreen))
        return;

    bool realWindow = isRealWindow();
    if (realWindow && !q->testAttribute(Qt::WA_Moved)) {
        q->createWinId();
        if (QWidget *p = q->parentWidget()) {
            p->createWinId();
#ifndef QT_MAC_USE_COCOA
            RepositionWindow(qt_mac_window_for(q), qt_mac_window_for(p), kWindowCenterOnParentWindow);
#else
            CGRect parentFrame = NSRectToCGRect([qt_mac_window_for(p) frame]);
            OSWindowRef windowRef = qt_mac_window_for(q);
            NSRect windowFrame = [windowRef frame];
            NSPoint parentCenter = NSMakePoint(CGRectGetMidX(parentFrame), CGRectGetMidY(parentFrame));
            [windowRef setFrameTopLeftPoint:NSMakePoint(parentCenter.x - (windowFrame.size.width / 2),
                                                        (parentCenter.y + (windowFrame.size.height / 2)))];
#endif
        } else {
#ifndef QT_MAC_USE_COCOA
            RepositionWindow(qt_mac_window_for(q), 0, kWindowCenterOnMainScreen);
#else
            // Ideally we would do a "center" here, but NSWindow's center is more equivalent to
            // kWindowAlertPositionOnMainScreen instead of kWindowCenterOnMainScreen.
            QRect availGeo = QApplication::desktop()->availableGeometry(q);
            // Center the content only.
            data.crect.moveCenter(availGeo.center());
            QRect fStrut = frameStrut();
            QRect frameRect(data.crect.x() - fStrut.left(), data.crect.y() - fStrut.top(),
                            fStrut.left() + fStrut.right() + data.crect.width(),
                            fStrut.top() + fStrut.bottom() + data.crect.height());
            NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1), frameRect.width(), frameRect.height());
            [qt_mac_window_for(q) setFrame:cocoaFrameRect display:NO];
#endif
        }
    }
    data.fstrut_dirty = true;
    if (realWindow) {
         // Delegates can change window state, so record some things earlier.
        bool isCurrentlyMinimized = (q->windowState() & Qt::WindowMinimized);
        setModal_sys();
        OSWindowRef window = qt_mac_window_for(q);
#ifndef QT_MAC_USE_COCOA
        SizeWindow(window, q->width(), q->height(), true);
#endif

#ifdef QT_MAC_USE_COCOA
        // Make sure that we end up sending a repaint event to
        // the widget if the window has been visible one before:
        [qt_mac_get_contentview_for(window) setNeedsDisplay:YES];
#endif
        if(qt_mac_is_macsheet(q)) {
            qt_event_request_showsheet(q);
        } else if(qt_mac_is_macdrawer(q)) {
#ifndef QT_MAC_USE_COCOA
            OpenDrawer(window, kWindowEdgeDefault, false);
#else
            NSDrawer *drawer = qt_mac_drawer_for(q);
            [drawer openOnEdge:[drawer preferredEdge]];
#endif
        } else {
#ifndef QT_MAC_USE_COCOA
            ShowHide(window, true);
#else
            // sync the opacity value back (in case of a fade).
            [window setAlphaValue:q->windowOpacity()];

            [window makeKeyAndOrderFront:window];
            if (data.window_modality == Qt::ApplicationModal)
                QCoreApplication::postEvent(qApp, new QEvent(QEvent::CocoaRequestModal));
#endif
            if (q->windowType() == Qt::Popup) {
			    if (q->focusWidget())
				    q->focusWidget()->d_func()->setFocus_sys();
				else
                    setFocus_sys();
			}
            toggleDrawers(true);
        }
        if (isCurrentlyMinimized) { //show in collapsed state
#ifndef QT_MAC_USE_COCOA
            CollapseWindow(window, true);
#else
            [window miniaturize:window];
#endif
        } else if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
            qt_event_request_activate(q);
#ifdef QT_MAC_USE_COCOA
            if (q->windowModality() == Qt::ApplicationModal) {
                // We call 'activeModalSession' early to force creation of q's modal
                // session. This seems neccessary for child dialogs to pop to front:
                QEventDispatcherMacPrivate::activeModalSession();
            }
#endif
        }
    } else if(topData()->embedded || !q->parentWidget() || q->parentWidget()->isVisible()) {
#ifndef QT_MAC_USE_COCOA
        HIViewSetVisible(qt_mac_nativeview_for(q), true);
#else
        [qt_mac_nativeview_for(q) setHidden:NO];

#endif
    }

    if (!QWidget::mouseGrabber()){
        QWidget *enterWidget = QApplication::widgetAt(QCursor::pos());
        QApplicationPrivate::dispatchEnterLeave(enterWidget, qt_mouseover);
        qt_mouseover = enterWidget;
    }

    qt_event_request_window_change(q);
}


QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt)
{
#ifndef QT_MAC_USE_COCOA
    CGPoint nativePoint = CGPointMake(pt.x(), pt.y());
    HIViewConvertPoint(&nativePoint, qt_mac_nativeview_for(child->parentWidget()),
                       qt_mac_nativeview_for(child));
#else
    NSPoint nativePoint = [qt_mac_nativeview_for(child) convertPoint:NSMakePoint(pt.x(), pt.y()) fromView:qt_mac_nativeview_for(child->parentWidget())];
#endif
    return QPoint(nativePoint.x, nativePoint.y);
}


void QWidgetPrivate::hide_sys()
{
    Q_Q(QWidget);
    if((q->windowType() == Qt::Desktop)) //you can't hide the desktop!
        return;

    QMacCocoaAutoReleasePool pool;
    if(q->isWindow()) {
        OSWindowRef window = qt_mac_window_for(q);
        if(qt_mac_is_macsheet(q)) {
#ifndef QT_MAC_USE_COCOA
            WindowRef parent = 0;
            if(GetSheetWindowParent(window, &parent) != noErr || !parent)
                ShowHide(window, false);
            else
                HideSheetWindow(window);
#else
            [NSApp endSheet:window];
            [window orderOut:window];
#endif
        } else if(qt_mac_is_macdrawer(q)) {
#ifndef QT_MAC_USE_COCOA
            CloseDrawer(window, false);
#else
            [qt_mac_drawer_for(q) close];
#endif
        } else {
#ifndef QT_MAC_USE_COCOA
            ShowHide(window, false);
#else
            [window orderOut:window];
#endif
            toggleDrawers(false);
#ifndef QT_MAC_USE_COCOA
            // Clear modality (because it seems something that we've always done).
            if (data.window_modality != Qt::NonModal) {
                SetWindowModality(window, kWindowModalityNone,
                          q->parentWidget() ? qt_mac_window_for(q->parentWidget()->window()) : 0);
            }
#endif
        }
        if(q->isActiveWindow() && !(q->windowType() == Qt::Popup)) {
            QWidget *w = 0;
            if(q->parentWidget())
                w = q->parentWidget()->window();
            if(!w || (!w->isVisible() && !w->isMinimized())) {
#ifndef QT_MAC_USE_COCOA
                for(WindowPtr wp = GetFrontWindowOfClass(kDocumentWindowClass, true);
                    wp; wp = GetNextWindowOfClass(wp, kDocumentWindowClass, true)) {
                    if((w = qt_mac_find_window(wp)))
                        break;
                }
                if (!w){
                    for(WindowPtr wp = GetFrontWindowOfClass(kSimpleWindowClass, true);
                        wp; wp = GetNextWindowOfClass(wp, kSimpleWindowClass, true)) {
                        if((w = qt_mac_find_window(wp)))
                            break;
                    }
                }
#else
                NSArray *windows = [NSApp windows];
                NSUInteger totalWindows = [windows count];
                for (NSUInteger i = 0; i < totalWindows; ++i) {
                    OSWindowRef wp = [windows objectAtIndex:i];
                    if ((w = qt_mac_find_window(wp)))
                        break;
                }
#endif
            }
            if(w && w->isVisible() && !w->isMinimized())
                qt_event_request_activate(w);
        }
    } else {
         invalidateBuffer(q->rect());
#ifndef QT_MAC_USE_COCOA
        HIViewSetVisible(qt_mac_nativeview_for(q), false);
#else
        [qt_mac_nativeview_for(q) setHidden:YES];
#endif
    }

    if (!QWidget::mouseGrabber()){
        QWidget *enterWidget = QApplication::widgetAt(QCursor::pos());
        QApplicationPrivate::dispatchEnterLeave(enterWidget, qt_mouseover);
        qt_mouseover = enterWidget;
    }

    qt_event_request_window_change(q);
    deactivateWidgetCleanup();
    qt_mac_event_release(q);
}

void QWidget::setWindowState(Qt::WindowStates newstate)
{
    Q_D(QWidget);
    bool needShow = false;
    Qt::WindowStates oldstate = windowState();
    if (oldstate == newstate)
        return;

#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
#endif
    bool needSendStateChange = true;
    if(isWindow()) {
        if((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
            if(newstate & Qt::WindowFullScreen) {
                if(QTLWExtra *tlextra = d->topData()) {
                    if(tlextra->normalGeometry.width() < 0) {
                        if(!testAttribute(Qt::WA_Resized))
                            adjustSize();
                        tlextra->normalGeometry = geometry();
                    }
                    tlextra->savedFlags = windowFlags();
                }
                needShow = isVisible();
                const QRect fullscreen(qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(this)));
                setParent(parentWidget(), Qt::Window | Qt::FramelessWindowHint | (windowFlags() & 0xffff0000)); //save
                setGeometry(fullscreen);
                if(!qApp->desktop()->screenNumber(this))
                    qt_mac_set_fullscreen_mode(true);
            } else {
                needShow = isVisible();
                setParent(parentWidget(), d->topData()->savedFlags);
                setGeometry(d->topData()->normalGeometry);
                if(!qApp->desktop()->screenNumber(this))
                    qt_mac_set_fullscreen_mode(false);
                d->topData()->normalGeometry.setRect(0, 0, -1, -1);
            }
        }

        d->createWinId();

        OSWindowRef window = qt_mac_window_for(this);
        if((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
            if (newstate & Qt::WindowMinimized) {
#ifndef QT_MAC_USE_COCOA
                CollapseWindow(window, true);
#else
                [window miniaturize:window];
#endif
            } else {
#ifndef QT_MAC_USE_COCOA
                CollapseWindow(window, false);
#else
                [window deminiaturize:window];
#endif
            }
            needSendStateChange = oldstate == windowState(); // Collapse didn't change our flags.
        }

        if((newstate & Qt::WindowMaximized) && !((newstate & Qt::WindowFullScreen))) {
            if(QTLWExtra *tlextra = d->topData()) {
                if(tlextra->normalGeometry.width() < 0) {
                    if(!testAttribute(Qt::WA_Resized))
                        adjustSize();
                    tlextra->normalGeometry = geometry();
                }
            }
        } else if(!(newstate & Qt::WindowFullScreen)) {
//            d->topData()->normalGeometry = QRect(0, 0, -1, -1);
        }

#ifdef DEBUG_WINDOW_STATE
#define WSTATE(x) qDebug("%s -- %s --> %s", #x, (oldstate & x) ? "true" : "false", (newstate & x) ? "true" : "false")
        WSTATE(Qt::WindowMinimized);
        WSTATE(Qt::WindowMaximized);
        WSTATE(Qt::WindowFullScreen);
#undef WSTATE
#endif
        if(!(newstate & (Qt::WindowMinimized|Qt::WindowFullScreen)) &&
           ((oldstate & Qt::WindowFullScreen) || (oldstate & Qt::WindowMinimized) ||
            (oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized))) {
            if(newstate & Qt::WindowMaximized) {
                data->fstrut_dirty = true;
#ifndef QT_MAC_USE_COCOA
                HIToolbarRef toolbarRef;
                if (GetWindowToolbar(window, &toolbarRef) == noErr && toolbarRef
                        && !isVisible() && !IsWindowToolbarVisible(window)) {
                    // HIToolbar, needs to be shown so that it's in the structure window
                    // Typically this is part of a main window and will get shown
                    // during the show, but it's will make the maximize all wrong.
                    ShowHideWindowToolbar(window, true, false);
                    d->updateFrameStrut();  // In theory the dirty would work, but it's optimized out if the window is not visible :(
                }
                Rect bounds;
                QDesktopWidget *dsk = QApplication::desktop();
                QRect avail = dsk->availableGeometry(dsk->screenNumber(this));
                SetRect(&bounds, avail.x(), avail.y(), avail.x() + avail.width(), avail.y() + avail.height());
                if(QWExtra *extra = d->extraData()) {
                    if(bounds.right - bounds.left > extra->maxw)
                        bounds.right = bounds.left + extra->maxw;
                    if(bounds.bottom - bounds.top > extra->maxh)
                        bounds.bottom = bounds.top + extra->maxh;
                }
                if(d->topData()) {
                    QRect fs = d->frameStrut();
                    bounds.left += fs.left();
                    if(bounds.right < avail.x()+avail.width())
                        bounds.right = qMin<short>((uint)avail.x()+avail.width(), bounds.right+fs.left());
                    if(bounds.bottom < avail.y()+avail.height())
                        bounds.bottom = qMin<short>((uint)avail.y()+avail.height(), bounds.bottom+fs.top());
                    bounds.top += fs.top();
                    bounds.right -= fs.right();
                    bounds.bottom -= fs.bottom();
                }
                QRect orect(geometry().x(), geometry().y(), width(), height()),
                      nrect(bounds.left, bounds.top, bounds.right - bounds.left,
                            bounds.bottom - bounds.top);
                if(orect != nrect) { // the new rect differ from the old
                    Point idealSize  = { nrect.height(), nrect.width() };
                    ZoomWindowIdeal(window, inZoomOut, &idealSize);
                }
#else
                NSToolbar *toolbarRef = [window toolbar];
                if (toolbarRef && !isVisible() && ![toolbarRef isVisible]) {
                    // HIToolbar, needs to be shown so that it's in the structure window
                    // Typically this is part of a main window and will get shown
                    // during the show, but it's will make the maximize all wrong.
                    // ### Not sure this is right for NSToolbar...
                    [toolbarRef setVisible:true];
//                    ShowHideWindowToolbar(window, true, false);
                    d->updateFrameStrut();  // In theory the dirty would work, but it's optimized out if the window is not visible :(
                }
                // Everything should be handled by Cocoa.
                [window zoom:window];
#endif
                needSendStateChange = oldstate == windowState(); // Zoom didn't change flags.
            } else if(oldstate & Qt::WindowMaximized) {
#ifndef QT_MAC_USE_COCOA
                Point idealSize;
                ZoomWindowIdeal(window, inZoomIn, &idealSize);
#else
                [window zoom:window];
#endif
                if(QTLWExtra *tlextra = d->topData()) {
                    setGeometry(tlextra->normalGeometry);
                    tlextra->normalGeometry.setRect(0, 0, -1, -1);
                }
            }
        }
    }

    data->window_state = newstate;

    if(needShow)
        show();

    if(newstate & Qt::WindowActive)
        activateWindow();

    qt_event_request_window_change(this);
    if (needSendStateChange) {
        QWindowStateChangeEvent e(oldstate);
        QApplication::sendEvent(this, &e);
    }
}

void QWidgetPrivate::setFocus_sys()
{
    Q_Q(QWidget);
    if (q->testAttribute(Qt::WA_WState_Created)) {
#ifdef QT_MAC_USE_COCOA
        QMacCocoaAutoReleasePool pool;
        NSView *view = qt_mac_nativeview_for(q);
        [[view window] makeFirstResponder:view];
#else
        SetKeyboardFocus(qt_mac_window_for(q), qt_mac_nativeview_for(q), 1);
#endif
    }
}

void QWidgetPrivate::raise_sys()
{
    Q_Q(QWidget);
    if((q->windowType() == Qt::Desktop))
        return;

#if QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    if (isRealWindow()) {
        // Calling orderFront shows the window on Cocoa too.
        if (!q->testAttribute(Qt::WA_DontShowOnScreen)) {
            [qt_mac_window_for(q) orderFront:qt_mac_window_for(q)];
        }
        if (qt_mac_raise_process) { //we get to be the active process now
            ProcessSerialNumber psn;
            GetCurrentProcess(&psn);
            SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
        }
    } else {
        // Cocoa doesn't really have an idea of Z-ordering, but you can
        // fake it by changing the order of it. But beware, removing an
        // NSView will also remove it as the first responder. So we re-set
        // the first responder just in case:
        NSView *view = qt_mac_nativeview_for(q);
        NSView *parentView = [view superview];
        NSResponder *firstResponder = [[view window] firstResponder];
        [view removeFromSuperview];
        [parentView addSubview:view];
        [[view window] makeFirstResponder:firstResponder];
    }
#else
    if(q->isWindow()) {
        //raise this window
        BringToFront(qt_mac_window_for(q));
        if(qt_mac_raise_process) { //we get to be the active process now
            ProcessSerialNumber psn;
            GetCurrentProcess(&psn);
            SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
        }
    } else if(q->parentWidget()) {
        HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderAbove, 0);
        qt_event_request_window_change(q);
    }
#endif
}

void QWidgetPrivate::lower_sys()
{
    Q_Q(QWidget);
    if((q->windowType() == Qt::Desktop))
        return;
#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    if (isRealWindow()) {
        OSWindowRef window = qt_mac_window_for(q);
        [window orderBack:window];
    } else {
        // Cocoa doesn't really have an idea of Z-ordering, but you can
        // fake it by changing the order of it. In this case
        // we put the item at the beginning of the list, but that means
        // we must re-insert everything since we cannot modify the list directly.
        NSView *myview = qt_mac_nativeview_for(q);
        NSView *parentView = [myview superview];
        NSArray *tmpViews = [parentView subviews];
        NSMutableArray *subviews = [[NSMutableArray alloc] initWithCapacity:[tmpViews count]];
        [subviews addObjectsFromArray:tmpViews];
        NSResponder *firstResponder = [[myview window] firstResponder];
        // Implicit assumption that myViewIndex is included in subviews, that's why I'm not checking
        // myViewIndex.
        NSUInteger index = 0;
        NSUInteger myViewIndex = 0;
        bool foundMyView = false;
        for (NSView *subview in subviews) {
            [subview removeFromSuperview];
            if (subview == myview) {
                foundMyView = true;
                myViewIndex = index;
            }
            ++index;
        }
        [parentView addSubview:myview];
        if (foundMyView)
            [subviews removeObjectAtIndex:myViewIndex];
        for (NSView *subview in subviews)
            [parentView addSubview:subview];
        [subviews release];
        [[myview window] makeFirstResponder:firstResponder];
    }
#else
    if(q->isWindow()) {
        SendBehind(qt_mac_window_for(q), 0);
    } else if(q->parentWidget()) {
        invalidateBuffer(q->rect());
        HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderBelow, 0);
        qt_event_request_window_change(q);
    }
#endif
}

void QWidgetPrivate::stackUnder_sys(QWidget *w)
{
    // stackUnder
    Q_Q(QWidget);
    if(!w || q->isWindow() || (q->windowType() == Qt::Desktop))
        return;
#ifdef QT_MAC_USE_COCOA
    // Do the same trick as lower_sys() and put this widget before the widget passed in.
    QMacCocoaAutoReleasePool pool;
    NSView *myview = qt_mac_nativeview_for(q);
    NSView *wView = qt_mac_nativeview_for(w);
    NSView *parentView = [myview superview];
    NSArray *tmpViews = [parentView subviews];
    NSMutableArray *subviews = [[NSMutableArray alloc] initWithCapacity:[tmpViews count]];
    [subviews addObjectsFromArray:tmpViews];
    // Implicit assumption that myViewIndex and wViewIndex is included in subviews,
    // that's why I'm not checking myViewIndex.
    NSUInteger index = 0;
    NSUInteger myViewIndex = 0;
    NSUInteger wViewIndex = 0;
    for (NSView *subview in subviews) {
        [subview removeFromSuperview];
        if (subview == myview)
            myViewIndex = index;
        else if (subview == wView)
            wViewIndex = index;
        ++index;
    }

    index = 0;
    for (NSView *subview in subviews) {
        if (index == myViewIndex)
            continue;
        if (index == wViewIndex)
            [parentView addSubview:myview];
        [parentView addSubview:subview];
        ++index;
    }
    [subviews release];
#else
    QWidget *p = q->parentWidget();
    if(!p || p != w->parentWidget())
        return;
    invalidateBuffer(q->rect());
    HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderBelow, qt_mac_nativeview_for(w));
    qt_event_request_window_change(q);
#endif
}

/*
    Modifies the bounds for a widgets backing HIView during moves and resizes. Also updates the
    widget, either by scrolling its contents or repainting, depending on the WA_StaticContents
    and QWidgetPrivate::isOpaque flags.
*/
static void qt_mac_update_widget_posisiton(QWidget *q, QRect oldRect, QRect newRect)
{
#ifndef QT_MAC_USE_COCOA
    HIRect bounds = CGRectMake(newRect.x(), newRect.y(),
                               newRect.width(), newRect.height());

    const HIViewRef view = qt_mac_nativeview_for(q);
    const bool isMove = (oldRect.topLeft() != newRect.topLeft());
    const bool isResize = (oldRect.size() != newRect.size());

//    qDebug() << oldRect << newRect << isMove << isResize << q->testAttribute(Qt::WA_OpaquePaintEvent) << q->testAttribute(Qt::WA_StaticContents);
    QWidgetPrivate *qd = qt_widget_private(q);

    // Perform a normal (complete repaint) update in some cases:
    if (
        // move-by-scroll requires QWidgetPrivate::isOpaque set
        (isMove && q->testAttribute(Qt::WA_OpaquePaintEvent) == false) ||

        // limited update on resize requires WA_StaticContents.
        (isResize && q->testAttribute(Qt::WA_StaticContents) == false) ||

        // one of the rects are invalid
        (oldRect.isValid() == false || newRect.isValid() == false)  ||

        // the position update is a part of a drag-and-drop operation
        QDragManager::self()->object
    ){
        HIViewSetFrame(view, &bounds);
        return;
    }

    const int dx = newRect.x() - oldRect.x();
    const int dy = newRect.y() - oldRect.y();

    if (isMove) {
        // HIViewScrollRect silently fails if we try to scroll anything under the grow box.
        // Check if there's one present within the widget rect, and if there is fall back
        // to repainting the entire widget.
        QWidget const * const parentWidget = q->parentWidget();
        const HIViewRef parentView = qt_mac_nativeview_for(parentWidget);
        HIViewRef nativeSizeGrip = 0;
        if (q->testAttribute(Qt::WA_WState_Created))
            HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(q->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
        if (nativeSizeGrip) {
            QWidget * const window = q->window();

            const int sizeGripSize = 20;
            const QRect oldWidgetRect = QRect(q->mapTo(window, QPoint(0, 0)), QSize(oldRect.width(), oldRect.height()));
            const QRect newWidgetRect = QRect(q->mapTo(window, QPoint(0, 0)), QSize(newRect.width(), newRect.height()));
            const QRect sizeGripRect = QRect(window->rect().bottomRight() - QPoint(sizeGripSize, sizeGripSize),
                                             window->rect().bottomRight());

            if (sizeGripRect.intersects(oldWidgetRect) || sizeGripRect.intersects(newWidgetRect)) {
                HIViewSetFrame(view, &bounds);
                return;
            }
        }

        // Don't scroll anything outside the parent widget rect.
        const QRect scrollRect = (oldRect | newRect) & parentWidget->rect();
        const HIRect scrollBounds =
            CGRectMake(scrollRect.x(), scrollRect.y(), scrollRect.width(), scrollRect.height());

        // We cannot scroll when the widget has a mask as that would
        // scroll the masked out areas too
        if (qd->extra && qd->extra->hasMask) {
            HIViewMoveBy(view, dx, dy);
            return;
        }

        OSStatus err = HIViewScrollRect(parentView, &scrollBounds, dx, dy);
        if (err != noErr) {
            HIViewSetNeedsDisplay(view, true);
            qWarning("QWidget: Internal error (%s:%d)", __FILE__, __LINE__);
        }
    }
    // Set the view bounds with drawing disabled to prevent repaints.
    HIViewSetDrawingEnabled(view, false);
    HIViewSetFrame(view, &bounds);
    HIViewSetDrawingEnabled(view, true);

    // Update any newly exposed areas due to resizing.
    const int startx = oldRect.width();
    const int stopx = newRect.width();
    const int starty = oldRect.height();
    const int stopy = newRect.height();

    const HIRect verticalSlice = CGRectMake(startx, 0, stopx , stopy);
    HIViewSetNeedsDisplayInRect(view, &verticalSlice, true);
    const HIRect horizontalSlice = CGRectMake(0, starty, startx, stopy);
    HIViewSetNeedsDisplayInRect(view, &horizontalSlice, true);
#else
    Q_UNUSED(oldRect);
    NSRect bounds = NSMakeRect(newRect.x(), newRect.y(),
                               newRect.width(), newRect.height());
    [qt_mac_nativeview_for(q) setFrame:bounds];
#endif
}

/*
  Helper function for non-toplevel widgets. Helps to map Qt's 32bit
  coordinate system to OS X's 16bit coordinate system.

  Sets the geometry of the widget to data.crect, but clipped to sizes
  that OS X can handle. Unmaps widgets that are completely outside the
  valid range.

  Maintains data.wrect, which is the geometry of the OS X widget,
  measured in this widget's coordinate system.

  if the parent is not clipped, parentWRect is empty, otherwise
  parentWRect is the geometry of the parent's OS X rect, measured in
  parent's coord sys
*/
void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect)
{
    Q_Q(QWidget);
    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
    Q_UNUSED(oldRect);
    /*
      There are up to four different coordinate systems here:
      Qt coordinate system for this widget.
      X coordinate system for this widget (relative to wrect).
      Qt coordinate system for parent
      X coordinate system for parent (relative to parent's wrect).
    */
    QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
    QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
    QRect wrect;
    //xrect is the X geometry of my X widget. (starts out in  parent's Qt coord sys, and ends up in parent's X coord sys)
    QRect xrect = data.crect;

    QRect parentWRect;
    if (q->isWindow() && topData()->embedded) {
#ifndef QT_MAC_USE_COCOA
        HIViewRef parentView = HIViewGetSuperview(qt_mac_nativeview_for(q));
#else
        NSView *parentView = [qt_mac_nativeview_for(q) superview];
#endif
        if (parentView) {
#ifndef QT_MAC_USE_COCOA
            HIRect tmpRect;
            HIViewGetFrame(parentView, &tmpRect);
#else
            NSRect tmpRect = [parentView frame];
#endif
            parentWRect = QRect(tmpRect.origin.x, tmpRect.origin.y,
                                tmpRect.size.width, tmpRect.size.height);
        } else {
            parentWRect = wrectRange;
        }
    } else {
        parentWRect = q->parentWidget()->data->wrect;
    }

    if (parentWRect.isValid()) {
        // parent is clipped, and we have to clip to the same limit as parent
        if (!parentWRect.contains(xrect)) {
            xrect &= parentWRect;
            wrect = xrect;
            //translate from parent's to my Qt coord sys
            wrect.translate(-data.crect.topLeft());
        }
        //translate from parent's Qt coords to parent's X coords
        xrect.translate(-parentWRect.topLeft());

    } else {
        // parent is not clipped, we may or may not have to clip

        if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
            // This is where the main optimization is: we are already
            // clipped, and if our clip is still valid, we can just
            // move our window, and do not need to move or clip
            // children

            QRect vrect = xrect & q->parentWidget()->rect();
            vrect.translate(-data.crect.topLeft()); //the part of me that's visible through parent, in my Qt coords
            if (data.wrect.contains(vrect)) {
                xrect = data.wrect;
                xrect.translate(data.crect.topLeft());
#ifndef QT_MAC_USE_COCOA
                HIRect bounds = CGRectMake(xrect.x(), xrect.y(),
                                           xrect.width(), xrect.height());
                HIViewSetFrame(qt_mac_nativeview_for(q), &bounds);
#else
                NSRect bounds = NSMakeRect(xrect.x(), xrect.y(),
                                           xrect.width(), xrect.height());
                [qt_mac_nativeview_for(q) setFrame:bounds];
#endif
                if (q->testAttribute(Qt::WA_OutsideWSRange)) {
                    q->setAttribute(Qt::WA_OutsideWSRange, false);
                    if (!dontShow) {
                        q->setAttribute(Qt::WA_Mapped);
#ifndef QT_MAC_USE_COCOA
                        HIViewSetVisible(qt_mac_nativeview_for(q), true);
#else
                        [qt_mac_nativeview_for(q) setHidden:NO];
#endif
                    }
                }
                return;
            }
        }

        if (!validRange.contains(xrect)) {
            // we are too big, and must clip
            xrect &=wrectRange;
            wrect = xrect;
            wrect.translate(-data.crect.topLeft());
            //parent's X coord system is equal to parent's Qt coord
            //sys, so we don't need to map xrect.
        }

    }

    // unmap if we are outside the valid window system coord system
    bool outsideRange = !xrect.isValid();
    bool mapWindow = false;
    if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
        q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
        if (outsideRange) {
#ifndef QT_MAC_USE_COCOA
            HIViewSetVisible(qt_mac_nativeview_for(q), false);
#else
            [qt_mac_nativeview_for(q) setHidden:YES];
#endif
            q->setAttribute(Qt::WA_Mapped, false);
        } else if (!q->isHidden()) {
            mapWindow = true;
        }
    }

    if (outsideRange)
        return;

    bool jump = (data.wrect != wrect);
    data.wrect = wrect;


    // and now recursively for all children...
    // ### can be optimized
    for (int i = 0; i < children.size(); ++i) {
        QObject *object = children.at(i);
        if (object->isWidgetType()) {
            QWidget *w = static_cast<QWidget *>(object);
            if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
                w->d_func()->setWSGeometry();
        }
    }

    qt_mac_update_widget_posisiton(q, oldRect, xrect);

    if  (jump) {
        updateSystemBackground();
        q->update();
    }
    if (mapWindow && !dontShow) {
        q->setAttribute(Qt::WA_Mapped);
#ifndef QT_MAC_USE_COCOA
        HIViewSetVisible(qt_mac_nativeview_for(q), true);
#else
        [qt_mac_nativeview_for(q) setHidden:NO];
#endif
    }
}

void QWidgetPrivate::adjustWithinMaxAndMinSize(int &w, int &h)
{
    if (QWExtra *extra = extraData()) {
        w = qMin(w, extra->maxw);
        h = qMin(h, extra->maxh);
        w = qMax(w, extra->minw);
        h = qMax(h, extra->minh);

        // Deal with size increment
        if (QTLWExtra *top = topData()) {
            if(top->incw) {
                w = w/top->incw;
                w *= top->incw;
            }
            if(top->inch) {
                h = h/top->inch;
                h *= top->inch;
            }
        }
    }

    if (isRealWindow()) {
        w = qMax(0, w);
        h = qMax(0, h);
    }
}

void QWidgetPrivate::applyMaxAndMinSizeOnWindow()
{
    Q_Q(QWidget);
    const float max_f(20000);
#ifndef QT_MAC_USE_COCOA
#define SF(x) ((x > max_f) ? max_f : x)
    HISize max = CGSizeMake(SF(extra->maxw), SF(extra->maxh));
    HISize min = CGSizeMake(SF(extra->minw), SF(extra->minh));
#undef SF
    SetWindowResizeLimits(qt_mac_window_for(q), &min, &max);
#else
#define SF(x) ((x > max_f) ? max_f : x)
    NSSize max = NSMakeSize(SF(extra->maxw), SF(extra->maxh));
    NSSize min = NSMakeSize(SF(extra->minw), SF(extra->minh));
#undef SF
    [qt_mac_window_for(q) setContentMinSize:min];
    [qt_mac_window_for(q) setContentMaxSize:max];
#endif
}

void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
{
    Q_Q(QWidget);
    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));

    if(q->windowType() == Qt::Desktop)
        return;

    QMacCocoaAutoReleasePool pool;
    bool realWindow = isRealWindow();

    if (realWindow && !q->testAttribute(Qt::WA_DontShowOnScreen)){
        adjustWithinMaxAndMinSize(w, h);
#ifndef QT_MAC_USE_COCOA
        if (w != 0 && h != 0) {
            topData()->isSetGeometry = 1;
            topData()->isMove = isMove;
            Rect r; SetRect(&r, x, y, x + w, y + h);
            SetWindowBounds(qt_mac_window_for(q), kWindowContentRgn, &r);
            topData()->isSetGeometry = 0;
        } else {
            setGeometry_sys_helper(x, y, w, h, isMove);
        }
#else
        QSize  olds = q->size();
        const bool isResize = (olds != QSize(w, h));
        NSWindow *window = qt_mac_window_for(q);
        const QRect &fStrut = frameStrut();
        const QRect frameRect(QPoint(x - fStrut.left(), y - fStrut.top()),
                              QSize(fStrut.left() + fStrut.right() + w,
                                    fStrut.top() + fStrut.bottom() + h));
        NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1),
                                           frameRect.width(), frameRect.height());
        // The setFrame call will trigger a 'windowDidResize' notification for the corresponding
        // NSWindow. The pending flag is set, so that the resize event can be send as non-spontaneous.
        if (isResize)
            q->setAttribute(Qt::WA_PendingResizeEvent);
        QPoint currTopLeft = data.crect.topLeft();
        if (currTopLeft.x() == x && currTopLeft.y() == y
                && cocoaFrameRect.size.width != 0
                && cocoaFrameRect.size.height != 0) {
            [window setFrame:cocoaFrameRect display:NO];
        } else {
            // The window is moved and resized (or resized to zero).
            // Since Cocoa usually only sends us a resize callback after
            // setting a window frame, we issue an explicit move as
            // well. To stop Cocoa from optimize away the move (since the move
            // would have the same origin as the setFrame call) we shift the
            // window back and forth inbetween.
            cocoaFrameRect.origin.y += 1;
            [window setFrame:cocoaFrameRect display:NO];
            cocoaFrameRect.origin.y -= 1;
            [window setFrameOrigin:cocoaFrameRect.origin];
        }
#endif
    } else {
        setGeometry_sys_helper(x, y, w, h, isMove);
    }
}

void QWidgetPrivate::setGeometry_sys_helper(int x, int y, int w, int h, bool isMove)
{
    Q_Q(QWidget);
    bool realWindow = isRealWindow();

    QPoint oldp = q->pos();
    QSize  olds = q->size();
    const bool isResize = (olds != QSize(w, h));

    if (!realWindow && !isResize && QPoint(x, y) == oldp)
        return;

    if (isResize)
        data.window_state = data.window_state & ~Qt::WindowMaximized;

    const bool visible = q->isVisible();
    data.crect = QRect(x, y, w, h);

    if (realWindow) {
        adjustWithinMaxAndMinSize(w, h);
        qt_mac_update_sizer(q);

#ifndef QT_MAC_USE_COCOA
        if (q->windowFlags() & Qt::WindowMaximizeButtonHint) {
            OSWindowRef window = qt_mac_window_for(q);
            if (extra->maxw && extra->maxh && extra->maxw == extra->minw
                    && extra->maxh == extra->minh) {
                ChangeWindowAttributes(window, kWindowNoAttributes, kWindowFullZoomAttribute);
            } else {
                ChangeWindowAttributes(window, kWindowFullZoomAttribute, kWindowNoAttributes);
            }
        }
        HIRect bounds = CGRectMake(0, 0, w, h);
        HIViewSetFrame(qt_mac_nativeview_for(q), &bounds);
#else
        [qt_mac_nativeview_for(q) setFrame:NSMakeRect(0, 0, w, h)];
#endif
    } else {
        const QRect oldRect(oldp, olds);
        if (!isResize && QApplicationPrivate::graphicsSystem())
            moveRect(oldRect, x - oldp.x(), y - oldp.y());
        setWSGeometry(false, oldRect);
        if (isResize && QApplicationPrivate::graphicsSystem()) {
            invalidateBuffer(q->rect());
            if (extra && !extra->mask.isEmpty()) {
                QRegion oldRegion(extra->mask.translated(oldp));
                oldRegion &= oldRect;
                q->parentWidget()->d_func()->invalidateBuffer(oldRegion);
            } else {
                q->parentWidget()->d_func()->invalidateBuffer(oldRect);
            }
        }
    }

    if(isMove || isResize) {
        if(!visible) {
            if(isMove && q->pos() != oldp)
                q->setAttribute(Qt::WA_PendingMoveEvent, true);
            if(isResize)
                q->setAttribute(Qt::WA_PendingResizeEvent, true);
        } else {
            if(isResize) { //send the resize event..
                QResizeEvent e(q->size(), olds);
                QApplication::sendEvent(q, &e);
            }
            if(isMove && q->pos() != oldp) { //send the move event..
                QMoveEvent e(q->pos(), oldp);
                QApplication::sendEvent(q, &e);
            }
        }
    }
    qt_event_request_window_change(q);
}

void QWidgetPrivate::setConstraints_sys()
{
    updateMaximizeButton_sys();
    applyMaxAndMinSizeOnWindow();
}

void QWidgetPrivate::updateMaximizeButton_sys()
{
    Q_Q(QWidget);
    if (q->data->window_flags & Qt::CustomizeWindowHint)
        return;

    OSWindowRef window = qt_mac_window_for(q);
    QTLWExtra * tlwExtra = topData();
#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    NSButton *maximizeButton = [window standardWindowButton:NSWindowZoomButton];
#endif
    if (extra->maxw && extra->maxh
        && extra->maxw == extra->minw
        && extra->maxh == extra->minh) {
        // The window has a fixed size, so gray out the maximize button:
        if (!tlwExtra->savedWindowAttributesFromMaximized) {
#ifndef QT_MAC_USE_COCOA
            GetWindowAttributes(window,
                                (WindowAttributes*)&extra->topextra->savedWindowAttributesFromMaximized);

#else
            tlwExtra->savedWindowAttributesFromMaximized = (![maximizeButton isHidden] && [maximizeButton isEnabled]);
#endif
        }
#ifndef QT_MAC_USE_COCOA
        ChangeWindowAttributes(window, kWindowNoAttributes, kWindowFullZoomAttribute);
#else
       [maximizeButton setEnabled:NO];
#endif


    } else {
        if (tlwExtra->savedWindowAttributesFromMaximized) {
#ifndef QT_MAC_USE_COCOA
            ChangeWindowAttributes(window,
                                   extra->topextra->savedWindowAttributesFromMaximized,
                                   kWindowNoAttributes);
#else
            [maximizeButton setEnabled:YES];
#endif
            tlwExtra->savedWindowAttributesFromMaximized = 0;
        }
    }


}

void QWidgetPrivate::scroll_sys(int dx, int dy)
{
    if (QApplicationPrivate::graphicsSystem() && !paintOnScreen()) {
        scrollChildren(dx, dy);
        scrollRect(q_func()->rect(), dx, dy);
    } else {
        scroll_sys(dx, dy, QRect());
    }
}

void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
{
    Q_Q(QWidget);

    if (QApplicationPrivate::graphicsSystem() && !paintOnScreen()) {
        scrollRect(r, dx, dy);
        return;
    }

    const bool valid_rect = r.isValid();
    if (!q->updatesEnabled() &&  (valid_rect || q->children().isEmpty()))
        return;

    qt_event_request_window_change(q);

#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
#endif

    if(!valid_rect) {        // scroll children
        QPoint pd(dx, dy);
        QWidgetList moved;
        QObjectList chldrn = q->children();
        for(int i = 0; i < chldrn.size(); i++) {  //first move all children
            QObject *obj = chldrn.at(i);
            if(obj->isWidgetType()) {
                QWidget *w = (QWidget*)obj;
                if(!w->isWindow()) {
                    w->data->crect = QRect(w->pos() + pd, w->size());
                    if (w->testAttribute(Qt::WA_WState_Created)) {
#ifndef QT_MAC_USE_COCOA
                        HIRect bounds = CGRectMake(w->data->crect.x(), w->data->crect.y(),
                                                   w->data->crect.width(), w->data->crect.height());
                        HIViewRef hiview = qt_mac_nativeview_for(w);
                        const bool opaque = q->testAttribute(Qt::WA_OpaquePaintEvent);

                        if (opaque)
                            HIViewSetDrawingEnabled(hiview,  false);
                        HIViewSetFrame(hiview, &bounds);
                        if (opaque)
                            HIViewSetDrawingEnabled(hiview,  true);
#else
                        [qt_mac_nativeview_for(w)
                            setFrame:NSMakeRect(w->data->crect.x(), w->data->crect.y(),
                                                w->data->crect.width(), w->data->crect.height())];
#endif
                    }
                    moved.append(w);
                }
            }
        }
        //now send move events (do not do this in the above loop, breaks QAquaFocusWidget)
        for(int i = 0; i < moved.size(); i++) {
            QWidget *w = moved.at(i);
            QMoveEvent e(w->pos(), w->pos() - pd);
            QApplication::sendEvent(w, &e);
        }
    }

    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isVisible())
        return;

    OSViewRef view = qt_mac_nativeview_for(q);
#ifndef QT_MAC_USE_COCOA
    HIRect scrollrect = CGRectMake(r.x(), r.y(), r.width(), r.height());
#  if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
   if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
       OSStatus err = _HIViewScrollRectWithOptions(view, valid_rect ? &scrollrect : 0, dx, dy, kHIViewScrollRectAdjustInvalid);
       if (err) {
           // The only parameter that can go wrong, is the rect.
           qWarning("QWidget::scroll: Your rectangle was too big for the widget, clipping rect");
           scrollrect = CGRectMake(qMax(r.x(), 0), qMax(r.y(), 0),
                                   qMin(r.width(), q->width()), qMin(r.height(), q->height()));
           _HIViewScrollRectWithOptions(view, valid_rect ? &scrollrect : 0, dx, dy, kHIViewScrollRectAdjustInvalid);
       }
   } else {
       if (HIViewGetNeedsDisplay(view)) {
           q->update(valid_rect ? r : q->rect());
           return;
       }
       HIRect scrollrect = CGRectMake(r.x(), r.y(), r.width(), r.height());
       OSStatus err = HIViewScrollRect(view, valid_rect ? &scrollrect : 0, dx, dy);
       if (err) {
           // The only parameter that can go wrong, is the rect.
           qWarning("QWidget::scroll: Your rectangle was too big for the widget, clipping rect");
           scrollrect = CGRectMake(qMax(r.x(), 0), qMax(r.y(), 0),
                   qMin(r.width(), q->width()), qMin(r.height(), q->height()));
           HIViewScrollRect(view, valid_rect ? &scrollrect : 0, dx, dy);
       }
   }
#  endif
#else
    NSRect scrollRect = valid_rect ? NSMakeRect(r.x(), r.y(), r.width(), r.height())
                                   : NSMakeRect(0, 0, q->width(), q->height());


    // calc the updateRect
    NSRect deltaXRect = { {0, 0}, {0, 0} };
    NSRect deltaYRect = { {0, 0}, {0, 0} };
    if (dy != 0) {
        deltaYRect.size.width = scrollRect.size.width;
        if (dy > 0) {
            deltaYRect.size.height = dy;
        } else {
            deltaYRect.size.height = -dy;
            deltaYRect.origin.y = scrollRect.size.height + dy;
        }
    }
    if (dx != 0) {
        deltaXRect.size.height = scrollRect.size.height;
        if (dx > 0) {
            deltaXRect.size.width = dx;
        } else {
            deltaXRect.size.width = -dx;
            deltaXRect.origin.x = scrollRect.size.width + dx;
        }
    }

    // ### Scroll the dirty regions as well, the following is not correct.
    QRegion displayRegion = r.isNull() ? dirtyOnWidget : (dirtyOnWidget & r);
    const QVector<QRect> &rects = dirtyOnWidget.rects();
    const QVector<QRect>::const_iterator end = rects.end();
    QVector<QRect>::const_iterator it = rects.begin();
    while (it != end) {
         const QRect rect = *it;
         const NSRect dirtyRect = NSMakeRect(rect.x() + dx, rect.y() + dy,
                                             rect.width(), rect.height());
         [view setNeedsDisplayInRect:dirtyRect];
         ++it;
    }
    [view scrollRect:scrollRect by:NSMakeSize(dx, dy)];
    // Yes, we potentially send a duplicate area, but I think Cocoa can handle it.
    [view setNeedsDisplayInRect:deltaXRect];
    [view setNeedsDisplayInRect:deltaYRect];
#endif // QT_MAC_USE_COCOA
}

int QWidget::metric(PaintDeviceMetric m) const
{
    switch(m) {
    case PdmHeightMM:
        return qRound(metric(PdmHeight) * 25.4 / qreal(metric(PdmDpiY)));
    case PdmWidthMM:
        return qRound(metric(PdmWidth) * 25.4 / qreal(metric(PdmDpiX)));
    case PdmHeight:
    case PdmWidth: {
#ifndef QT_MAC_USE_COCOA
        HIRect rect;
        HIViewGetFrame(qt_mac_nativeview_for(this), &rect);
#else
        NSRect rect = [qt_mac_nativeview_for(this) frame];
#endif
        if(m == PdmWidth)
            return (int)rect.size.width;
        return (int)rect.size.height; }
    case PdmDepth:
        return 32;
    case PdmNumColors:
        return INT_MAX;
    case PdmDpiX:
    case PdmPhysicalDpiX: {
        Q_D(const QWidget);
        if (d->extra && d->extra->customDpiX)
            return d->extra->customDpiX;
        else if (d->parent)
            return static_cast<QWidget *>(d->parent)->metric(m);
        extern float qt_mac_defaultDpi_x(); //qpaintdevice_mac.cpp
        return int(qt_mac_defaultDpi_x()); }
    case PdmDpiY:
    case PdmPhysicalDpiY: {
        Q_D(const QWidget);
        if (d->extra && d->extra->customDpiY)
            return d->extra->customDpiY;
        else if (d->parent)
            return static_cast<QWidget *>(d->parent)->metric(m);
        extern float qt_mac_defaultDpi_y(); //qpaintdevice_mac.cpp
        return int(qt_mac_defaultDpi_y()); }
    default: //leave this so the compiler complains when new ones are added
        qWarning("QWidget::metric: Unhandled parameter %d", m);
        return QPaintDevice::metric(m);
    }
    return 0;
}

void QWidgetPrivate::createSysExtra()
{
#ifdef QT_MAC_USE_COCOA
    extra->imageMask = 0;
#endif
}

void QWidgetPrivate::deleteSysExtra()
{
#ifdef QT_MAC_USE_COCOA
    if (extra->imageMask)
        CFRelease(extra->imageMask);
#endif
}

void QWidgetPrivate::createTLSysExtra()
{
    extra->topextra->wclass = 0;
    extra->topextra->group = 0;
    extra->topextra->windowIcon = 0;
    extra->topextra->resizer = 0;
    extra->topextra->isSetGeometry = 0;
    extra->topextra->savedWindowAttributesFromMaximized = 0;
}

void QWidgetPrivate::deleteTLSysExtra()
{
#ifndef QT_MAC_USE_COCOA
    if(extra->topextra->group) {
        qt_mac_release_window_group(extra->topextra->group);
        extra->topextra->group = 0;
    }
#endif
}

void QWidgetPrivate::updateFrameStrut()
{
    Q_Q(QWidget);

    QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);

    that->data.fstrut_dirty = false;
    QTLWExtra *top = that->topData();

#if QT_MAC_USE_COCOA
    // 1 Get the window frame
    OSWindowRef oswnd = qt_mac_window_for(q);
    NSRect frameW = [oswnd frame];
    // 2 Get the content frame - so now
    NSRect frameC = [oswnd contentRectForFrameRect:frameW];
    top->frameStrut.setCoords(frameC.origin.x - frameW.origin.x,
                              (frameW.origin.y + frameW.size.height) - (frameC.origin.y + frameC.size.height),
                              (frameW.origin.x + frameW.size.width) - (frameC.origin.x + frameC.size.width),
                              frameC.origin.y - frameW.origin.y);
#else
    Rect window_r;
    GetWindowStructureWidths(qt_mac_window_for(q), &window_r);
    top->frameStrut.setCoords(window_r.left, window_r.top, window_r.right, window_r.bottom);
#endif
}

void QWidgetPrivate::registerDropSite(bool on)
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;
#ifndef QT_MAC_USE_COCOA
    SetControlDragTrackingEnabled(qt_mac_nativeview_for(q), on);
#else
    NSView *view = qt_mac_nativeview_for(q);
    if (on && [view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
        [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view) registerDragTypes];
    }
#endif
}

void QWidgetPrivate::setMask_sys(const QRegion &region)
{
    Q_UNUSED(region);
#ifndef QT_MAC_USE_COCOA
    Q_Q(QWidget);
    if (q->isWindow())
        ReshapeCustomWindow(qt_mac_window_for(q));
    else
        HIViewReshapeStructure(qt_mac_nativeview_for(q));
#else
    if (extra->mask.isEmpty()) {
        extra->maskBits = QImage();
        finishCocoaMaskSetup();
    } else {
        syncCocoaMask();
    }

#endif
}

extern "C" {
    typedef struct CGSConnection *CGSConnectionRef;
    typedef struct CGSWindow *CGSWindowRef;
    extern OSStatus CGSSetWindowAlpha(CGSConnectionRef, CGSWindowRef, float);
    extern CGSWindowRef GetNativeWindowFromWindowRef(WindowRef);
    extern CGSConnectionRef _CGSDefaultConnection();
}

void QWidgetPrivate::setWindowOpacity_sys(qreal level)
{
    Q_Q(QWidget);

    if (!q->isWindow())
        return;

    level = qBound(0.0, level, 1.0);
    topData()->opacity = (uchar)(level * 255);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;

#if QT_MAC_USE_COCOA
    OSWindowRef oswindow = qt_mac_window_for(q);
    [oswindow setAlphaValue:level];
#else
    CGSSetWindowAlpha(_CGSDefaultConnection(),
                      GetNativeWindowFromWindowRef(qt_mac_window_for(q)), level);
#endif
}

#ifdef QT_MAC_USE_COCOA
void QWidgetPrivate::syncCocoaMask()
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created) || !extra)
        return;

    if (extra->hasMask && extra->maskBits.size() != q->size()) {
        extra->maskBits = QImage(q->size(), QImage::Format_Mono);
        extra->maskBits.fill(QColor(Qt::color1).rgba());
        extra->maskBits.setNumColors(2);
        extra->maskBits.setColor(0, QColor(Qt::color0).rgba());
        extra->maskBits.setColor(1, QColor(Qt::color1).rgba());
        QPainter painter(&extra->maskBits);
        painter.setBrush(Qt::color1);
        painter.setPen(Qt::NoPen);
        painter.drawRects(extra->mask.rects());
        painter.end();
        finishCocoaMaskSetup();
    }
}

void QWidgetPrivate::finishCocoaMaskSetup()
{
    Q_Q(QWidget);

    if (!q->testAttribute(Qt::WA_WState_Created) || !extra)
        return;

    // Technically this is too late to release, because the data behind the image
    // has already been released. But it's more tidy to do it here.
    // If you are seeing a crash, consider doing a CFRelease before changing extra->maskBits.
    if (extra->imageMask) {
        CFRelease(extra->imageMask);
        extra->imageMask = 0;
    }

    if (!extra->maskBits.isNull()) {
        QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(0,
                                                                       extra->maskBits.bits(),
                                                                       extra->maskBits.numBytes(),
                                                                       0); // shouldn't need to release.
        CGFloat decode[2] = {1, 0};
        extra->imageMask = CGImageMaskCreate(extra->maskBits.width(), extra->maskBits.height(),
                                             1, 1, extra->maskBits.bytesPerLine(), dataProvider,
                                             decode, false);
    }
    if (q->isWindow()) {
        NSWindow *window = qt_mac_window_for(q);
        [window setOpaque:(extra->imageMask == 0)];
        [window invalidateShadow];
    }
    [qt_mac_nativeview_for(q) setNeedsDisplay:YES];
}
#endif

struct QPaintEngineCleanupHandler
{
    inline QPaintEngineCleanupHandler() : engine(0) {}
    inline ~QPaintEngineCleanupHandler() { delete engine; }
    QPaintEngine *engine;
};

Q_GLOBAL_STATIC(QPaintEngineCleanupHandler, engineHandler)

QPaintEngine *QWidget::paintEngine() const
{
    QPaintEngine *&pe = engineHandler()->engine;
#ifdef QT_RASTER_PAINTENGINE
    if (!pe) {
        if(qgetenv("QT_MAC_USE_COREGRAPHICS").isNull())
            pe = new QRasterPaintEngine();
        else
            pe = new QCoreGraphicsPaintEngine();
    }
    if (pe->isActive()) {
        QPaintEngine *engine =
            qgetenv("QT_MAC_USE_COREGRAPHICS").isNull()
            ? (QPaintEngine*)new QRasterPaintEngine() : (QPaintEngine*)new QCoreGraphicsPaintEngine();
        engine->setAutoDestruct(true);
        return engine;
    }
#else
    if (!pe)
        pe = new QCoreGraphicsPaintEngine();
    if (pe->isActive()) {
        QPaintEngine *engine = new QCoreGraphicsPaintEngine();
        engine->setAutoDestruct(true);
        return engine;
    }
#endif
    return pe;
}

void QWidgetPrivate::setModal_sys()
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
        return;
    const QWidget * const windowParent = q->window()->parentWidget();
    const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
    OSWindowRef windowRef = qt_mac_window_for(q);

#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    bool alreadySheet = [windowRef styleMask] & NSDocModalWindowMask;

    if (windowParent && q->windowModality() == Qt::WindowModal){
        // Window should be window-modal, which implies a sheet.
        if (!alreadySheet) {
            // NB: the following call will call setModal_sys recursivly:
            recreateMacWindow();
            windowRef = qt_mac_window_for(q);
        }
        if ([windowRef isKindOfClass:[NSPanel class]]){
            // If the primary window of the sheet parent is a child of a modal dialog,
            // the sheet parent should not be modally shaddowed.
            // This goes for the sheet as well:
            OSWindowRef ref = primaryWindow ? qt_mac_window_for(primaryWindow) : 0;
            bool isDialog = ref ? [ref isKindOfClass:[NSPanel class]] : false;
            bool worksWhenModal = isDialog ? [static_cast<NSPanel *>(ref) worksWhenModal] : false;
            if (worksWhenModal)
                [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
        }
    } else {
        // Window shold not be window-modal, and as such, not a sheet.
        if (alreadySheet){
            // NB: the following call will call setModal_sys recursivly:
            recreateMacWindow();
            windowRef = qt_mac_window_for(q);
        }
        if (q->windowModality() == Qt::ApplicationModal) {
            [windowRef setLevel:NSModalPanelWindowLevel];
        } else if (primaryWindow && primaryWindow->windowModality() == Qt::ApplicationModal) {
            // INVARIANT: Our window is a dialog that has a dialog parent that is
            // application modal, or . This means that q is supposed to be on top of this
            // dialog and not be modally shaddowed:
            [windowRef setLevel:NSModalPanelWindowLevel];
            if ([windowRef isKindOfClass:[NSPanel class]])
                [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
        } else {
            // INVARIANT: q should not be modal.
            NSInteger winLevel = -1;
            if (q->windowType() == Qt::Popup) {
                winLevel = NSPopUpMenuWindowLevel;
                // Popup should be in at least the same level as its parent.
                if (primaryWindow) {
                    OSWindowRef parentRef = qt_mac_window_for(primaryWindow);
                    winLevel = qMax([parentRef level], winLevel);
                }
            } else if (q->windowType() == Qt::Tool) {
                winLevel = NSFloatingWindowLevel;
            } else if (q->windowType() == Qt::Dialog) {
                winLevel = NSModalPanelWindowLevel;
            }

            // StayOnTop window should appear above Tool windows.
            if (data.window_flags & Qt::WindowStaysOnTopHint)
                winLevel = NSPopUpMenuWindowLevel;
            // Tooltips should appear above StayOnTop windows.
            if (q->windowType() == Qt::ToolTip)
                winLevel = NSScreenSaverWindowLevel;
            // All other types are Normal level.
            if (winLevel == -1)
                winLevel = NSNormalWindowLevel;
            [windowRef setLevel:winLevel];
        }
    }

#else
    const bool primaryWindowModal = primaryWindow ? primaryWindow->testAttribute(Qt::WA_ShowModal) : false;
    const bool modal = q->testAttribute(Qt::WA_ShowModal);

    WindowClass old_wclass;
    GetWindowClass(windowRef, &old_wclass);

    if (modal || primaryWindowModal) {
        if (q->windowModality() == Qt::WindowModal
                || (primaryWindow && primaryWindow->windowModality() == Qt::WindowModal)){
            // Window should be window-modal (which implies a sheet).
            if (old_wclass != kSheetWindowClass){
                // We cannot convert a created window to a sheet.
                // So we recreate the window:
                recreateMacWindow();
                return;
            }
        } else {
            // Window should be application-modal (which implies NOT using a sheet).
            if (old_wclass == kSheetWindowClass){
                // We cannot convert a sheet to a window.
                // So we recreate the window:
                recreateMacWindow();
                return;
            } else if (!(q->data->window_flags & Qt::CustomizeWindowHint)) {
                if (old_wclass == kDocumentWindowClass || old_wclass == kFloatingWindowClass || old_wclass == kUtilityWindowClass){
                    // Only change the class to kMovableModalWindowClass if the no explicit jewels
                    // are set (kMovableModalWindowClass can't contain them), and the current window class
                    // can be converted to modal (according to carbon doc). Mind the order of
                    // HIWindowChangeClass and ChangeWindowAttributes.
                    WindowGroupRef group = GetWindowGroup(windowRef);
                    HIWindowChangeClass(windowRef, kMovableModalWindowClass);
                    quint32 tmpWattr = kWindowCloseBoxAttribute | kWindowHorizontalZoomAttribute;
                    ChangeWindowAttributes(windowRef, tmpWattr, kWindowNoAttributes);
                    ChangeWindowAttributes(windowRef, kWindowNoAttributes, tmpWattr);
                    // If the window belongs to a qt-created group, set that group once more:
                    if (data.window_flags & Qt::WindowStaysOnTopHint
                            || q->windowType() == Qt::Popup
                            || q->windowType() == Qt::ToolTip)
                        SetWindowGroup(windowRef, group);
                }
                // Popups are usually handled "special" and are never modal.
                Qt::WindowType winType = q->windowType();
                if (winType != Qt::Popup && winType != Qt::ToolTip)
                    SetWindowModality(windowRef, kWindowModalityAppModal, 0);
            }
        }
    } else if (windowRef) {
        if (old_wclass == kSheetWindowClass){
            // Converting a sheet to a window is complex. It's easier to recreate:
            recreateMacWindow();
            return;
        }

        SetWindowModality(windowRef, kWindowModalityNone, 0);
	if (!(q->data->window_flags & Qt::CustomizeWindowHint)) {
	    if (q->window()->d_func()->topData()->wattr |= kWindowCloseBoxAttribute)
		ChangeWindowAttributes(windowRef, kWindowCloseBoxAttribute, kWindowNoAttributes);
	    if (q->window()->d_func()->topData()->wattr |= kWindowHorizontalZoomAttribute)
		ChangeWindowAttributes(windowRef, kWindowHorizontalZoomAttribute, kWindowNoAttributes);
	    if (q->window()->d_func()->topData()->wattr |= kWindowCollapseBoxAttribute)
                ChangeWindowAttributes(windowRef, kWindowCollapseBoxAttribute, kWindowNoAttributes);
	}

        WindowClass newClass = q->window()->d_func()->topData()->wclass;
        if (old_wclass != newClass && newClass != 0){
            WindowGroupRef group = GetWindowGroup(windowRef);
            HIWindowChangeClass(windowRef, newClass);
            // If the window belongs to a qt-created group, set that group once more:
            if (data.window_flags & Qt::WindowStaysOnTopHint
                || q->windowType() == Qt::Popup
                || q->windowType() == Qt::ToolTip)
                SetWindowGroup(windowRef, group);
        }
    }

    // Make sure that HIWindowChangeClass didn't remove drag support
    // or reset the opaque size grip setting:
    SetAutomaticControlDragTrackingEnabledForWindow(windowRef, true);
    macUpdateOpaqueSizeGrip();
#endif
}

void QWidgetPrivate::macUpdateHideOnSuspend()
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow() || q->windowType() != Qt::Tool)
        return;
#ifndef QT_MAC_USE_COCOA
    if(q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
        ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowHideOnSuspendAttribute);
    else
        ChangeWindowAttributes(qt_mac_window_for(q), kWindowHideOnSuspendAttribute, 0);
#else
    if(q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
        [qt_mac_window_for(q) setHidesOnDeactivate:NO];
    else
        [qt_mac_window_for(q) setHidesOnDeactivate:YES];
#endif
}

void QWidgetPrivate::macUpdateOpaqueSizeGrip()
{
    Q_Q(QWidget);

    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
        return;

#ifndef QT_MAC_USE_COCOA	// Growbox is always transparent on Cocoa. Can emulate with setting a QSizeGrip
    HIViewRef growBox;
    HIViewFindByID(HIViewGetRoot(qt_mac_window_for(q)), kHIViewWindowGrowBoxID, &growBox);
    if (!growBox)
        return;
    HIGrowBoxViewSetTransparent(growBox, !q->testAttribute(Qt::WA_MacOpaqueSizeGrip));
#endif
}

void QWidgetPrivate::macUpdateSizeAttribute()
{
    Q_Q(QWidget);
    QEvent event(QEvent::MacSizeChange);
    QApplication::sendEvent(q, &event);
    for (int i = 0; i < children.size(); ++i) {
        QWidget *w = qobject_cast<QWidget *>(children.at(i));
        if (w && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
              && !q->testAttribute(Qt::WA_MacMiniSize) // no attribute set? inherit from parent
              && !w->testAttribute(Qt::WA_MacSmallSize)
              && !w->testAttribute(Qt::WA_MacNormalSize))
            w->d_func()->macUpdateSizeAttribute();
    }
    resolveFont();
}

void QWidgetPrivate::macUpdateIgnoreMouseEvents()
{
#ifndef QT_MAC_USE_COCOA  // This is handled inside the mouse handler on Cocoa.
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;

    if(q->isWindow())
	{
        if(q->testAttribute(Qt::WA_TransparentForMouseEvents))
            ChangeWindowAttributes(qt_mac_window_for(q), kWindowIgnoreClicksAttribute, 0);
        else
            ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowIgnoreClicksAttribute);
        ReshapeCustomWindow(qt_mac_window_for(q));
    } else {
#ifndef kHIViewFeatureIgnoresClicks
#define kHIViewFeatureIgnoresClicks kHIViewIgnoresClicks
#endif
        if(q->testAttribute(Qt::WA_TransparentForMouseEvents))
            HIViewChangeFeatures(qt_mac_nativeview_for(q), kHIViewFeatureIgnoresClicks, 0);
        else
            HIViewChangeFeatures(qt_mac_nativeview_for(q), 0, kHIViewFeatureIgnoresClicks);
        HIViewReshapeStructure(qt_mac_nativeview_for(q));
    }
#endif
}

void QWidgetPrivate::macUpdateMetalAttribute()
{
    Q_Q(QWidget);
    bool realWindow = isRealWindow();
    if (!q->testAttribute(Qt::WA_WState_Created) || !realWindow)
        return;

    if (realWindow) {
#if QT_MAC_USE_COCOA
        // Cocoa doesn't let us change the style mask once it's been changed
        // So, that means we need to recreate the window.
        OSWindowRef cocoaWindow = qt_mac_window_for(q);
        if ([cocoaWindow styleMask] & NSTexturedBackgroundWindowMask)
            return;
        recreateMacWindow();
#else
        QMainWindowLayout *layout = qobject_cast<QMainWindowLayout *>(q->layout());
        if (q->testAttribute(Qt::WA_MacBrushedMetal)) {
            if (layout)
                layout->updateHIToolBarStatus();
            ChangeWindowAttributes(qt_mac_window_for(q), kWindowMetalAttribute, 0);
            if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
                ChangeWindowAttributes(qt_mac_window_for(q), kWindowMetalNoContentSeparatorAttribute, 0);
        } else {
            if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
                ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowMetalNoContentSeparatorAttribute);
            ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowMetalAttribute);
            if (layout)
                layout->updateHIToolBarStatus();
        }
#endif
    }
}

void QWidgetPrivate::setEnabled_helper_sys(bool enable)
{
#ifdef QT_MAC_USE_COCOA
    Q_Q(QWidget);
    NSView *view = qt_mac_nativeview_for(q);
    if ([view isKindOfClass:[NSControl class]])
        [static_cast<NSControl *>(view) setEnabled:enable];
#else
    Q_UNUSED(enable);
#endif
}

QT_END_NAMESPACE