summaryrefslogtreecommitdiffstats
path: root/src/widgets/platforms/mac/qwidget_mac.mm
blob: dd958761a1e142f166869f1e1507001323ae1b0f (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
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $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.
**
****************************************************************************/

#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 "qfileinfo.h"
#include "qimage.h"
#include "qlayout.h"
#include "qmenubar.h"
#include <private/qbackingstore_p.h>
#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 "qevent_p.h"
#include "qdnd_p.h"
#include <QtGui/qgraphicsproxywidget.h>
#include "qmainwindow.h"

QT_BEGIN_NAMESPACE

// qmainwindow.cpp
extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);

#define XCOORD_MAX 16383
#define WRECT_MAX 8191



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

/*****************************************************************************
  QWidget globals
 *****************************************************************************/

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


/*****************************************************************************
  Externals
 *****************************************************************************/
extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
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_last_mouse_receiver; //qapplication_mac.mm
extern QPointer<QWidget> qt_last_native_mouse_receiver; //qt_cocoa_helpers_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
extern void qt_mac_setMouseGrabCursor(bool set, QCursor *cursor = 0); // qcursor_mac.mm
extern QPointer<QWidget> topLevelAt_cache; // qapplication_mac.mm
/*****************************************************************************
  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);
}

static NSDrawer *qt_mac_drawer_for(const QWidget *widget)
{
    NSView *widgetView = reinterpret_cast<NSView *>(widget->window()->effectiveWinId());
    NSArray *windows = [NSApp windows];
    for (NSWindow *window in windows) {
        NSArray *drawers = [window drawers];
        for (NSDrawer *drawer in drawers) {
            if ([drawer contentView] == widgetView)
                return drawer;
        }
    }
    return 0;
}

static void qt_mac_destructView(OSViewRef view)
{
    NSWindow *window = [view window];
    if ([window contentView] == view)
        [window setContentView:[[NSView alloc] initWithFrame:[view bounds]]];
    [view removeFromSuperview];
    [view release];
}

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

    [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForWindow:window];
    [window release];
}

static void qt_mac_destructDrawer(NSDrawer *drawer)
{
    [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForDrawer:drawer];
    [drawer release];
}

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_insideKeyWindow(const QWidget *w)
{
    return [[reinterpret_cast<NSView *>(w->effectiveWinId()) window] isKeyWindow];
    return false;
}

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;

    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];
    return true;
}

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)
{
    return [window QT_MANGLE_NAMESPACE(qt_qwidget)];
}

inline static void qt_mac_set_fullscreen_mode(bool b)
{
    extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
    if(qt_mac_app_fullscreen == b)
        return;
    qt_mac_app_fullscreen = b;
    if (b) {
        SetSystemUIMode(kUIModeAllHidden, kUIOptionAutoShowMenuBar);
    } else {
        SetSystemUIMode(kUIModeNormal, 0);
    }
}

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

Q_GUI_EXPORT OSViewRef qt_mac_effectiveview_for(const QWidget *w)
{
    // Get the first non-alien (parent) widget for
    // w, and return its NSView (if it has one):
    return reinterpret_cast<OSViewRef>(w->effectiveWinId());
}

Q_GUI_EXPORT OSViewRef qt_mac_get_contentview_for(OSWindowRef w)
{
    return [w contentView];
}

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

Q_GUI_EXPORT OSWindowRef qt_mac_window_for(OSViewRef view)
{
    if (view)
        return [view window];
    return 0;
}

static bool qt_isGenuineQWidget(OSViewRef ref)
{
    return [ref isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]];
}

bool qt_isGenuineQWidget(const QWidget *window)
{
    if (!window)
        return false;

    if (!window->internalWinId())
        return true;  //alien

    return qt_isGenuineQWidget(OSViewRef(window->internalWinId()));
}

Q_GUI_EXPORT OSWindowRef qt_mac_window_for(const QWidget *w)
{
    if (OSViewRef hiview = qt_mac_effectiveview_for(w)) {
        OSWindowRef window = qt_mac_window_for(hiview);
        if (window)
            return window;

        if (qt_isGenuineQWidget(hiview)) {
            // 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.
            QWidget *toplevel = w->window();
            if (toplevel != w) {
                hiview = qt_mac_nativeview_for(toplevel);
                if (OSWindowRef w = qt_mac_window_for(hiview))
                    return w;
            }

            toplevel->d_func()->createWindow_sys();
            // Reget the hiview since "create window" could potentially move the view (I guess).
            hiview = qt_mac_nativeview_for(toplevel);
            return qt_mac_window_for(hiview);
        }
    }
    return 0;
}



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::macSetNeedsDisplay(QRegion region)
{
    Q_Q(QWidget);
    if (NSView *nativeView = qt_mac_nativeview_for(q)) {
        // INVARIANT: q is _not_ alien. So we can optimize a little:
        if (region.isEmpty()) {
            [nativeView setNeedsDisplay:YES];
        } else {
            QVector<QRect> rects = region.rects();
            for (int i = 0; i<rects.count(); ++i) {
                const QRect &rect = rects.at(i);
                NSRect nsrect = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
                [nativeView setNeedsDisplayInRect:nsrect];
            }
        }
    } else if (QWidget *effectiveWidget = q->nativeParentWidget()) {
        // INVARIANT: q is alien, and effectiveWidget is native.
        if (NSView *effectiveView = qt_mac_nativeview_for(effectiveWidget)) {
            if (region.isEmpty()) {
                const QRect &rect = q->rect();
                QPoint p = q->mapTo(effectiveWidget, rect.topLeft());
                NSRect nsrect = NSMakeRect(p.x(), p.y(), rect.width(), rect.height());
                [effectiveView setNeedsDisplayInRect:nsrect];
            } else {
                QVector<QRect> rects = region.rects();
                for (int i = 0; i<rects.count(); ++i) {
                    const QRect &rect = rects.at(i);
                    QPoint p = q->mapTo(effectiveWidget, rect.topLeft());
                    NSRect nsrect = NSMakeRect(p.x(), p.y(), rect.width(), rect.height());
                    [effectiveView setNeedsDisplayInRect:nsrect];
                }
            }
        }
    }
}

void QWidgetPrivate::macUpdateIsOpaque()
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;
    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];
    }
}
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;
}

OSViewRef qt_mac_create_widget(QWidget *widget, QWidgetPrivate *widgetPrivate, OSViewRef parent)
{
    QMacCocoaAutoReleasePool pool;
    QT_MANGLE_NAMESPACE(QCocoaView) *view = [[QT_MANGLE_NAMESPACE(QCocoaView) alloc] initWithQWidget:widget widgetPrivate:widgetPrivate];

#ifdef ALIEN_DEBUG
    qDebug() << "Creating NSView for" << widget;
#endif

    if (view && parent)
        [parent addSubview:view];
    return view;
}

void qt_mac_unregister_widget()
{
}

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)) {
            bool oldState = widget->testAttribute(Qt::WA_WState_ExplicitShowHide);
            if(visible) {
                if (!widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
                    widget->show();
            } else {
                widget->hide();
                if(!oldState)
                    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->effectiveWinId()));
    {
    }
    bool remove_grip = (topData->resizer || (w->windowFlags() & Qt::FramelessWindowHint)
                        || (extraData->maxw && extraData->maxh &&
                            extraData->maxw == extraData->minw && extraData->maxh == extraData->minh));
    [windowRef setShowsResizeIndicator:!remove_grip];
    return true;
}

void QWidgetPrivate::qt_clean_root_win()
{
    QMacCocoaAutoReleasePool pool;
    [qt_root_win release];
    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);
    qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, NSBorderlessWindowMask, desktopRect);
    if(!qt_root_win)
        return false;
    qAddPostRoutine(qt_clean_root_win);
    return true;
}

bool QWidgetPrivate::qt_widget_rgn(QWidget *widget, short wcode, RgnHandle rgn, bool force = false)
{
    bool ret = false;
    Q_UNUSED(widget);
    Q_UNUSED(wcode);
    Q_UNUSED(rgn);
    Q_UNUSED(force);
    return ret;
}

/*****************************************************************************
  QWidget member functions
 *****************************************************************************/
void QWidgetPrivate::determineWindowClass()
{
    Q_Q(QWidget);
#if !defined(QT_NO_MAINWINDOW) && !defined(QT_NO_TOOLBAR)
    // Make sure that QMainWindow has the MacWindowToolBarButtonHint when the
    // unifiedTitleAndToolBarOnMac property is ON. This is to avoid reentry of
    // setParent() triggered by the QToolBar::event(QEvent::ParentChange).
    QMainWindow *mainWindow = qobject_cast<QMainWindow *>(q);
    if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
        data.window_flags |= Qt::MacWindowToolBarButtonHint;
    }
#endif

    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(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 if(q->testAttribute(Qt::WA_ShowModal))
        wclass = kMovableModalWindowClass;
    else
        wclass = kDocumentWindowClass;

    WindowAttributes wattr = NSBorderlessWindowMask;
    if(qt_mac_is_macsheet(q)) {
        //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
        wclass = kSheetWindowClass;
        wattr = NSTitledWindowMask | NSResizableWindowMask;
    } else {
        // 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;
            }
        }
        if(tmp_wattr)
            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
    }
#endif

    topData()->wclass = wclass;
    topData()->wattr = wattr;
}

#undef ADD_DEBUG_WINDOW_NAME

void QWidgetPrivate::setWindowLevel()
{
    Q_Q(QWidget);
    const QWidget * const windowParent = q->window()->parentWidget();
    const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
    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) {
        // Correct modality level (NSModalPanelWindowLevel) will be
        // set by cocoa when creating a modal session later.
        winLevel = NSNormalWindowLevel;
    }

    // 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;
    [qt_mac_window_for(q) setLevel:winLevel];
}

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];
    }
    if (q->testAttribute(Qt::WA_MacNoShadow))
        [windowRef setHasShadow:NO];
    else
        [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;
    if (!nsview) {
        nsview = qt_mac_create_widget(q, this, 0);
        setWinId(WId(nsview));
    }
    [windowRef setContentView:nsview];
    [nsview setHidden:NO];
    transferChildren();

    // Tell Cocoa explicit that we wan't the view to receive key events
    // (regardless of focus policy) because this is how it works on other
    // platforms (and in the carbon port):
    [windowRef makeFirstResponder:nsview];

    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);
    }

    // Its more performant to handle the mouse cursor
    // ourselves, expecially when using alien widgets:
    [windowRef disableCursorRects];

    setWindowLevel();
    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();
}


/*
 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);
    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();
    }

    // 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 Qt Support and include the\n"
                "      WidgetFlags used in creating the widget.", __FILE__, __LINE__);
    finishCreateWindow_sys_Cocoa(windowRef);
}

void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
{
    Q_Q(QWidget);
    QMacCocoaAutoReleasePool pool;

    OSViewRef destroyid = 0;

    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 {
        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) {
                    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));
                    // 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;
        [nativeView retain];
        if (destroyOldWindow)
            destroyid = qt_mac_nativeview_for(q);
        bool transfer = false;
        setWinId((WId)nativeView);
        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)) {
                    [windowref retain];
                    if (initializeWindow) {
                        parent = qt_mac_get_contentview_for(windowref);
                    } else {
                        parent = [nativeView superview];
                    }
                    break;
                }
            }
            if(!parent)
                transfer = true;
        } else if (parentWidget) {
            // I need to be added to my parent, therefore my parent needs an NSView
            // Alien note: a 'window' was supplied as argument, meaning this widget
            // is not alien. So therefore the parent cannot be alien either.
            parentWidget->createWinId();
            parent = qt_mac_nativeview_for(parentWidget);
        }
        if(parent != nativeView && parent) {
            [parent addSubview:nativeView];
        }
        if(transfer)
            transferChildren();
        data.fstrut_dirty = true; // we'll re calculate this later
        q->setAttribute(Qt::WA_WState_Visible,
                        ![nativeView isHidden]
                        );
        if(initializeWindow) {
            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]);
        }
    } else if (desktop) {                        // desktop widget
        if (!qt_root_win)
            QWidgetPrivate::qt_create_root_win();
        Q_ASSERT(qt_root_win);
        WId rootWinID = 0;
        [qt_root_win retain];
        if (OSViewRef rootContentView = [qt_root_win contentView]) {
            rootWinID = (WId)rootContentView;
            [rootContentView retain];
        }
        setWinId(rootWinID);
    } else if (topLevel) {
        determineWindowClass();
        if(OSViewRef osview = qt_mac_create_widget(q, this, 0)) {
            NSRect bounds = NSMakeRect(data.crect.x(), flipYCoordinate(data.crect.y()),
                                       data.crect.width(), data.crect.height());
            [osview setFrame:bounds];
            setWinId((WId)osview);
        }
    } else {
        data.fstrut_dirty = false; // non-toplevel widgets don't have a frame, so no need to update the strut

        if (q->testAttribute(Qt::WA_NativeWindow) == false || q->internalWinId() != 0) {
            // INVARIANT: q is Alien, and we should not create an NSView to back it up.
        } else
        if (OSViewRef osview = qt_mac_create_widget(q, this, qt_mac_nativeview_for(parentWidget))) {
            NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
            [osview setFrame:bounds];
            setWinId((WId)osview);
            if (q->isVisible()) {
                // If q were Alien before, but now became native (e.g. if a call to
                // winId was done from somewhere), we need to show the view immidiatly:
                QMacCocoaAutoReleasePool pool;
                [osview setHidden:NO];
            }
        }
    }

    updateIsOpaque();

    if (q->testAttribute(Qt::WA_DropSiteRegistered))
        registerDropSite(true);
    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
{
    return 0;
}

/*!
  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 qt_mac_updateParentUnderAlienWidget(QWidget *alienWidget)
{
    QWidget *nativeParent = alienWidget->nativeParentWidget();
    if (!nativeParent)
        return;

    QPoint globalPos = alienWidget->mapToGlobal(QPoint(0, 0));
    QRect dirtyRect = QRect(nativeParent->mapFromGlobal(globalPos), alienWidget->size());
    nativeParent->update(dirtyRect);
}

void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
{
    Q_D(QWidget);
    QMacCocoaAutoReleasePool pool;
    d->aboutToDestroy();
    if (!isWindow() && parentWidget())
        parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry()));
    if (!internalWinId())
        qt_mac_updateParentUnderAlienWidget(this);
    d->deactivateWidgetCleanup();
    qt_mac_event_release(this);
    if(testAttribute(Qt::WA_WState_Created)) {
        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(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;
                if (qt_mac_is_macdrawer(this)) {
                    drawer = qt_mac_drawer_for(this);
                } else
                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) {
                    [hiview release];
                } else {
                    qt_mac_destructView(hiview);
                }
                if (drawer)
                    qt_mac_destructDrawer(drawer);
                if (window)
                    qt_mac_destructWindow(window);
            }
        }
        QT_TRY {
            d->setWinId(0);
        } QT_CATCH (const std::bad_alloc &) {
            // swallow - destructors must not throw
	}
    }
}

void QWidgetPrivate::transferChildren()
{
    Q_Q(QWidget);
    if (!q->internalWinId())
        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->internalWinId()) {
                    // 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(w) retain];
                    [qt_mac_nativeview_for(w) removeFromSuperview];
                    [qt_mac_nativeview_for(q) addSubview:qt_mac_nativeview_for(w)];
                    [qt_mac_nativeview_for(w) release];
                    w->setAttribute(Qt::WA_DropSiteRegistered, oldRegistered);
                }
            }
        }
    }
}

void QWidgetPrivate::setSubWindowStacking(bool set)
{
    // After hitting too many unforeseen bugs trying to put Qt on top of the cocoa child
    // window API, we have decided to revert this behaviour as much as we can. We
    // therefore now only allow child windows to exist for children of modal dialogs.
    static bool use_behaviour_qt473 = !qgetenv("QT_MAC_USE_CHILDWINDOWS").isEmpty();

    // This will set/remove a visual relationship between parent and child on screen.
    // The reason for doing this is to ensure that a child always stacks infront of
    // its parent. Unfortunatly is turns out that [NSWindow addChildWindow] has
    // several unwanted side-effects, one of them being the moving of a child when
    // moving the parent, which we choose to accept. A way tougher side-effect is
    // that Cocoa will hide the parent if you hide the child. And in the case of
    // a tool window, since it will normally hide when you deactivate the
    // application, Cocoa will hide the parent upon deactivate as well. The result often
    // being no more visible windows on screen. So, to make a long story short, we only
    // allow parent-child relationships between windows that both are either a plain window
    // or a dialog.

    Q_Q(QWidget);
    if (!q->isWindow())
        return;
    NSWindow *qwin = [qt_mac_nativeview_for(q) window];
    if (!qwin)
        return;
    Qt::WindowType qtype = q->windowType();
    if (set && !(qtype == Qt::Window || qtype == Qt::Dialog))
        return;
    if (set && ![qwin isVisible])
        return;

    if (QWidget *parent = q->parentWidget()) {
        if (NSWindow *pwin = [qt_mac_nativeview_for(parent) window]) {
            if (set) {
                Qt::WindowType ptype = parent->window()->windowType();
                if ([pwin isVisible]
                    && (ptype == Qt::Window || ptype == Qt::Dialog)
                    && ![qwin parentWindow]
                    && (use_behaviour_qt473 || parent->windowModality() == Qt::ApplicationModal)) {
                    NSInteger level = [qwin level];
                    [pwin addChildWindow:qwin ordered:NSWindowAbove];
                    if ([qwin level] < level)
                        [qwin setLevel:level];
                }
            } else {
                [pwin removeChildWindow:qwin];
            }
        }
    }

    // Only set-up child windows for q if q is modal:
    if (set && !use_behaviour_qt473 && q->windowModality() != Qt::ApplicationModal)
        return;

    QObjectList widgets = q->children();
    for (int i=0; i<widgets.size(); ++i) {
        QWidget *child = qobject_cast<QWidget *>(widgets.at(i));
        if (child && child->isWindow()) {
            if (NSWindow *cwin = [qt_mac_nativeview_for(child) window]) {
                if (set) {
                    Qt::WindowType ctype = child->window()->windowType();
                    if ([cwin isVisible] && (ctype == Qt::Window || ctype == Qt::Dialog) && ![cwin parentWindow]) {
                        NSInteger level = [cwin level];
                        [qwin addChildWindow:cwin ordered:NSWindowAbove];
                        if ([cwin level] < level)
                            [cwin setLevel:level];
                    }
                } else {
                    [qwin removeChildWindow:qt_mac_window_for(child)];
                }
            }
        }
    }
}

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);
    bool wasWindow = q->isWindow();
    OSViewRef old_id = 0;

    if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
        q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(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();
        }
    }

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

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

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

    if (!q->testAttribute(Qt::WA_WState_WindowOpacitySet)) {
        q->setWindowOpacity(1.0f);
        q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
    }

    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,
    // unless this is an alien widget. )
    const bool nonWindowWithCreatedParent = !q->isWindow() && parent->testAttribute(Qt::WA_WState_Created);
    const bool nativeWidget = q->internalWinId() != 0;
    if (wasCreated || (nativeWidget && nonWindowWithCreatedParent)) {
        createWinId();
        if (q->isWindow()) {
            // 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 release];
                [oldToolbar setVisible:oldToolbarVisible];
            }
        }
    }
    if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
        q->setAttribute(Qt::WA_WState_Hidden);
    q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);

    if (wasCreated) {
        transferChildren();

        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
    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);

        if (oldDrawer) {
            qt_mac_destructDrawer(oldDrawer);
        } else
        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 (!internalWinId()) {
        QPoint p = pos + data->crect.topLeft();
        return isWindow() ?  p : parentWidget()->mapToGlobal(p);
    }
    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();
}

QPoint QWidget::mapFromGlobal(const QPoint &pos) const
{
    Q_D(const QWidget);
    if (!internalWinId()) {
        QPoint p = isWindow() ?  pos : parentWidget()->mapFromGlobal(pos);
        return p - data->crect.topLeft();
    }
    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)));
}

void QWidgetPrivate::updateSystemBackground()
{
}

void QWidgetPrivate::setCursor_sys(const QCursor &)
{
    qt_mac_update_cursor();
}

void QWidgetPrivate::unsetCursor_sys()
{
    qt_mac_update_cursor();
}

void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
{
    Q_Q(QWidget);
    if (q->isWindow()) {
        QMacCocoaAutoReleasePool pool;
        [qt_mac_window_for(q) setTitle:qt_mac_QStringToNSString(caption)];
    }
}

void QWidgetPrivate::setWindowModified_sys(bool mod)
{
    Q_Q(QWidget);
    if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) {
        [qt_mac_window_for(q) setDocumentEdited:mod];
    }
}

void QWidgetPrivate::setWindowFilePath_sys(const QString &filePath)
{
    Q_Q(QWidget);
    QMacCocoaAutoReleasePool pool;
    QFileInfo fi(filePath);
    [qt_mac_window_for(q) setRepresentedFilename:fi.exists() ? qt_mac_QStringToNSString(filePath) : @""];
}

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()) {
        QMacCocoaAutoReleasePool pool;
        if (icon.isNull())
            return;
        NSButton *iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
        if (iconButton == nil) {
            QCFString string(q->windowTitle());
            const NSString *tmpString = reinterpret_cast<const NSString *>((CFStringRef)string);
            [qt_mac_window_for(q) setRepresentedURL:[NSURL fileURLWithPath:const_cast<NSString *>(tmpString)]];
            iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
        }
        if (icon.isNull()) {
            [iconButton setImage:nil];
        } else {
            QPixmap scaled = pm->scaled(QSize(16,16), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            NSImage *image = static_cast<NSImage *>(qt_mac_create_nsimage(scaled));
            [iconButton setImage:image];
            [image release];
        }
    }
}

void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
{
    Q_Q(QWidget);
    if(q->isWindow() && !iconText.isEmpty()) {
        QMacCocoaAutoReleasePool pool;
        [qt_mac_window_for(q) setMiniwindowTitle:qt_mac_QStringToNSString(iconText)];
    }
}

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

#ifndef QT_NO_CURSOR
void QWidget::grabMouse(const QCursor &cursor)
{
    if(isVisible() && !qt_nograb()) {
        if(mac_mouse_grabber)
            mac_mouse_grabber->releaseMouse();
        mac_mouse_grabber=this;
        qt_mac_setMouseGrabCursor(true, const_cast<QCursor *>(&cursor));
    }
}
#endif

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

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);
    QMacCocoaAutoReleasePool pool;
    windowActive = [win isKeyWindow];
    if ((tlw->windowType() == Qt::Popup)
            || (tlw->windowType() == Qt::Tool)
            || qt_mac_is_macdrawer(tlw)
            || windowActive) {
        [win makeKeyWindow];
    } else if(!isMinimized()) {
        [win makeKeyAndOrderFront:win];
    }
}

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

void QWidgetPrivate::update_sys(const QRect &r)
{
    Q_Q(QWidget);
    if (updateRedirectedToGraphicsProxyWidget(q, r))
        return;
    dirtyOnWidget += r;
    macSetNeedsDisplay(r != q->rect() ? r : QRegion());
}

void QWidgetPrivate::update_sys(const QRegion &rgn)
{
    Q_Q(QWidget);
    if (updateRedirectedToGraphicsProxyWidget(q, rgn))
        return;
    dirtyOnWidget += rgn;
    macSetNeedsDisplay(rgn);
}

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();

    data.fstrut_dirty = true;
    if (realWindow) {
        bool isCurrentlyMinimized = (q->windowState() & Qt::WindowMinimized);
        setModal_sys();
        OSWindowRef window = qt_mac_window_for(q);

        // 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];
        if(qt_mac_is_macsheet(q)) {
            qt_event_request_showsheet(q);
        } else if(qt_mac_is_macdrawer(q)) {
            NSDrawer *drawer = qt_mac_drawer_for(q);
            [drawer openOnEdge:[drawer preferredEdge]];
        } else {
            // sync the opacity value back (in case of a fade).
            [window setAlphaValue:q->windowOpacity()];

            QWidget *top = 0;
            if (QApplicationPrivate::tryModalHelper(q, &top)) {
                [window makeKeyAndOrderFront:window];
                // If this window is app modal, we need to start spinning
                // a modal session for it. Interrupting
                // the event dispatcher will make this happend:
                if (data.window_modality == Qt::ApplicationModal)
                    QEventDispatcherMac::instance()->interrupt();
            } else {
                // The window is modally shaddowed, so we need to make
                // sure that we don't pop in front of the modal window:
                [window orderFront:window];
                if (!top->testAttribute(Qt::WA_DontShowOnScreen)) {
                    if (NSWindow *modalWin = qt_mac_window_for(top))
                        [modalWin orderFront:window];
                }
            }
            setSubWindowStacking(true);
            qt_mac_update_cursor();
            if (q->windowType() == Qt::Popup) {
                qt_button_down = 0;
                if (q->focusWidget())
				    q->focusWidget()->d_func()->setFocus_sys();
				else
                    setFocus_sys();
			}
            toggleDrawers(true);
        }
        if (isCurrentlyMinimized) { //show in collapsed state
            [window miniaturize:window];
        } else if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
        }
    } else if(topData()->embedded || !q->parentWidget() || q->parentWidget()->isVisible()) {
        if (NSView *view = qt_mac_nativeview_for(q)) {
            // INVARIANT: q is native. Just show the view:
            [view setHidden:NO];
        } else {
            // INVARIANT: q is alien. Update q instead:
            q->update();
        }
    }

    if ([NSApp isActive] && !qt_button_down && !QWidget::mouseGrabber()){
        // Update enter/leave immidiatly, don't wait for a move event. But only
        // if no grab exists (even if the grab points to this widget, it seems, ref X11)
        QPoint qlocal, qglobal;
        QWidget *widgetUnderMouse = 0;
        qt_mac_getTargetForMouseEvent(0, QEvent::Enter, qlocal, qglobal, 0, &widgetUnderMouse);
        QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, qt_last_mouse_receiver);
        qt_last_mouse_receiver = widgetUnderMouse;
        qt_last_native_mouse_receiver = widgetUnderMouse ?
            (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
    }

    topLevelAt_cache = 0;
    qt_event_request_window_change(q);
}

QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt)
{
    NSPoint nativePoint = [qt_mac_nativeview_for(child) convertPoint:NSMakePoint(pt.x(), pt.y()) fromView:qt_mac_nativeview_for(child->parentWidget())];
    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()) {
        setSubWindowStacking(false);
        OSWindowRef window = qt_mac_window_for(q);
        if(qt_mac_is_macsheet(q)) {
            [NSApp endSheet:window];
            [window orderOut:window];
        } else if(qt_mac_is_macdrawer(q)) {
            [qt_mac_drawer_for(q) close];
        } else {
            [window orderOut:window];
            // Unfortunately it is not as easy as just hiding the window, we need
            // to find out if we were in full screen mode. If we were and this is
            // the last window in full screen mode then we need to unset the full screen
            // mode. If this is not the last visible window in full screen mode then we
            // don't change the full screen mode.
            if(q->isFullScreen())
            {
                bool keepFullScreen = false;
                QWidgetList windowList = qApp->topLevelWidgets();
                int windowCount = windowList.count();
                for(int i = 0; i < windowCount; i++)
                {
                    QWidget *w = windowList[i];
                    // If it is the same window, we don't need to check :-)
                    if(q == w)
                        continue;
                    // If they are not visible or if they are minimized then
                    // we just ignore them.
                    if(!w->isVisible() || w->isMinimized())
                        continue;
                    // Is it full screen?
                    // Notice that if there is one window in full screen mode then we
                    // cannot switch the full screen mode off, therefore we just abort.
                    if(w->isFullScreen()) {
                        keepFullScreen = true;
                        break;
                    }
                }
                // No windows in full screen mode, so let just unset that flag.
                if(!keepFullScreen)
                    qt_mac_set_fullscreen_mode(false);
            }
            toggleDrawers(false);
            qt_mac_update_cursor();
        }
    } else {
         invalidateBuffer(q->rect());
        if (NSView *view = qt_mac_nativeview_for(q)) {
            // INVARIANT: q is native. Just hide the view:
            [view setHidden:YES];
        } else {
            // INVARIANT: q is alien. Repaint where q is placed instead:
            qt_mac_updateParentUnderAlienWidget(q);
        }
    }

    if ([NSApp isActive] && !qt_button_down && !QWidget::mouseGrabber()){
        // Update enter/leave immidiatly, don't wait for a move event. But only
        // if no grab exists (even if the grab points to this widget, it seems, ref X11)
        QPoint qlocal, qglobal;
        QWidget *widgetUnderMouse = 0;
        qt_mac_getTargetForMouseEvent(0, QEvent::Leave, qlocal, qglobal, 0, &widgetUnderMouse);
        QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, qt_last_native_mouse_receiver);
        qt_last_mouse_receiver = widgetUnderMouse;
        qt_last_native_mouse_receiver = widgetUnderMouse ?
            (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
     }

    topLevelAt_cache = 0;
    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;

    QMacCocoaAutoReleasePool pool;
    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();
                if(!qApp->desktop()->screenNumber(this))
                    qt_mac_set_fullscreen_mode(false);
                setParent(parentWidget(), d->topData()->savedFlags);
                setGeometry(d->topData()->normalGeometry);
                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) {
                [window miniaturize:window];
            } else {
                [window deminiaturize:window];
            }
            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;
                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];
                needSendStateChange = oldstate == windowState(); // Zoom didn't change flags.
            } else if(oldstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen)) {
                [window zoom:window];
                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)) {
        QMacCocoaAutoReleasePool pool;
        NSView *view = qt_mac_nativeview_for(q);
        [[view window] makeFirstResponder:view];
    }
}

NSComparisonResult compareViews2Raise(id view1, id view2, void *context)
{
    id topView = reinterpret_cast<id>(context);
    if (view1 == topView)
        return NSOrderedDescending;
    if (view2 == topView)
        return NSOrderedAscending;
    return NSOrderedSame;
}

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

    QMacCocoaAutoReleasePool pool;
    if (isRealWindow()) {
        // With the introduction of spaces it is not as simple as just raising the window.
        // First we need to check if we are in the right space. If we are, then we just continue
        // as usual. The problem comes when we are not in the active space. There are two main cases:
        // 1. Our parent was moved to a new space. In this case we want the window to be raised
        // in the same space as its parent.
        // 2. We don't have a parent. For this case we will just raise the window and let Cocoa
        // switch to the corresponding space.
        // NOTICE: There are a lot of corner cases here. We are keeping this simple for now, if
        // required we will introduce special handling for some of them.
        if (!q->testAttribute(Qt::WA_DontShowOnScreen) && q->isVisible()) {
            OSWindowRef window = qt_mac_window_for(q);
            // isOnActiveSpace is available only from 10.6 onwards, so we need to check if it is
            // available before calling it.
            if([window respondsToSelector:@selector(isOnActiveSpace)]) {
                if(![window performSelector:@selector(isOnActiveSpace)]) {
                    QWidget *parentWidget = q->parentWidget();
                    if(parentWidget) {
                        OSWindowRef parentWindow = qt_mac_window_for(parentWidget);
                        if(parentWindow && [parentWindow respondsToSelector:@selector(isOnActiveSpace)]) {
                            if ([parentWindow performSelector:@selector(isOnActiveSpace)]) {
                                // The window was created in a different space. Therefore if we want
                                // to show it in the current space we need to recreate it in the new
                                // space.
                                recreateMacWindow();
                                window = qt_mac_window_for(q);
                            }
                        }
                    }
                }
            }
            [window orderFront:window];
        }
        if (qt_mac_raise_process) { //we get to be the active process now
            ProcessSerialNumber psn;
            GetCurrentProcess(&psn);
            SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
        }
    } else {
        NSView *view = qt_mac_nativeview_for(q);
        NSView *parentView = [view superview];
        [parentView sortSubviewsUsingFunction:compareViews2Raise context:reinterpret_cast<void *>(view)];
    }
    topLevelAt_cache = 0;
}

NSComparisonResult compareViews2Lower(id view1, id view2, void *context)
{
    id topView = reinterpret_cast<id>(context);
    if (view1 == topView)
        return NSOrderedAscending;
    if (view2 == topView)
        return NSOrderedDescending;
    return NSOrderedSame;
}

void QWidgetPrivate::lower_sys()
{
    Q_Q(QWidget);
    if((q->windowType() == Qt::Desktop))
        return;
    if (isRealWindow()) {
        OSWindowRef window = qt_mac_window_for(q);
        [window orderBack:window];
    } else {
        NSView *view = qt_mac_nativeview_for(q);
        NSView *parentView = [view superview];
        [parentView sortSubviewsUsingFunction:compareViews2Lower context:reinterpret_cast<void *>(view)];
    }
    topLevelAt_cache = 0;
}

NSComparisonResult compareViews2StackUnder(id view1, id view2, void *context)
{
    const QHash<NSView *, int> &viewOrder = *reinterpret_cast<QHash<NSView *, int> *>(context);
    if (viewOrder[view1] < viewOrder[view2])
        return NSOrderedAscending;
    if (viewOrder[view1] > viewOrder[view2])
        return NSOrderedDescending;
    return NSOrderedSame;
}

void QWidgetPrivate::stackUnder_sys(QWidget *w)
{
    // stackUnder
    Q_Q(QWidget);
    if(!w || q->isWindow() || (q->windowType() == Qt::Desktop))
        return;
    // Do the same trick as lower_sys() and put this widget before the widget passed in.
    NSView *myView = qt_mac_nativeview_for(q);
    NSView *wView = qt_mac_nativeview_for(w);

    QHash<NSView *, int> viewOrder;
    NSView *parentView = [myView superview];
    NSArray *subviews = [parentView subviews];
    NSUInteger index = 1;
    // make a hash of view->zorderindex and make sure z-value is always odd,
    // so that when we modify the order we create a new (even) z-value which
    // will not interfere with others.
    for (NSView *subview in subviews) {
        viewOrder.insert(subview, index * 2);
        ++index;
    }
    viewOrder[myView] = viewOrder[wView] - 1;

    [parentView sortSubviewsUsingFunction:compareViews2StackUnder context:reinterpret_cast<void *>(&viewOrder)];
}


/*
  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));

    if (!q->internalWinId() && QApplicationPrivate::graphicsSystem() != 0) {
        // We have no view to move, and no paint engine that
        // we can update dirty regions on. So just return:
        return;
    }

    QMacCocoaAutoReleasePool pool;

    /*
      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).
    */

    // wrect is the same as crect, except that it is
    // clipped to fit inside parent (and screen):
    QRect wrect;

    // wrectInParentCoordSys will be the same as wrect, except that it is
    // originated in q's parent rather than q itself. It starts out in
    // parent's Qt coord system, and ends up in parent's coordinate system:
    QRect wrectInParentCoordSys = data.crect;

    // If q's parent has been clipped, parentWRect will
    // be filled with the parents clipped crect:
    QRect parentWRect;

    // Embedded have different meaning on each platform, and on
    // Mac, it means that q is a QMacNativeWidget.
    bool isEmbeddedWindow = (q->isWindow() && topData()->embedded);
    NSView *nsview = qt_mac_nativeview_for(q);
    if (!isEmbeddedWindow) {
        parentWRect = q->parentWidget()->data->wrect;
    } else {
        // INVARIANT: q's parent view is not owned by Qt. So we need to
        // do some extra calls to get the clipped rect of the parent view:
        NSView *parentView = [qt_mac_nativeview_for(q) superview];
        if (parentView) {
            NSRect tmpRect = [parentView frame];
            parentWRect = QRect(tmpRect.origin.x, tmpRect.origin.y,
                                tmpRect.size.width, tmpRect.size.height);
        } else {
            const QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
            parentWRect = wrectRange;
        }
    }

    if (parentWRect.isValid()) {
        // INVARIANT: q's parent has been clipped.
        // So we fit our own wrects inside it:
        if (!parentWRect.contains(wrectInParentCoordSys) && !isEmbeddedWindow) {
            wrectInParentCoordSys &= parentWRect;
            wrect = wrectInParentCoordSys;
            // Make sure wrect is originated in q's coordinate system:
            wrect.translate(-data.crect.topLeft());
        }
        // // Make sure wrectInParentCoordSys originated in q's parent coordinate system:
        wrectInParentCoordSys.translate(-parentWRect.topLeft());
    } else {
        // INVARIANT: we dont know yet the clipping rect of q's parent.
        // So we may or may not have to adjust our wrects:

        if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
            // This is where the main optimization is: we have an old wrect from an earlier
            // setGeometry call, and the new crect is smaller than it. If the final wrect is
            // also inside the old wrect, we can just move q and its children to the new
            // location without any clipping:

             // vrect will be the part of q that's will be visible inside
             // q's parent. If it inside the old wrect, then we can just move:
            QRect vrect = wrectInParentCoordSys & q->parentWidget()->rect();
            vrect.translate(-data.crect.topLeft());

            if (data.wrect.contains(vrect)) {
                wrectInParentCoordSys = data.wrect;
                wrectInParentCoordSys.translate(data.crect.topLeft());
                if (nsview) {
                    // INVARIANT: q is native. Set view frame:
                    NSRect bounds = NSMakeRect(wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
                        wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
                        [nsview setFrame:bounds];
                } else {
                    // INVARIANT: q is alien. Repaint wrect instead (includes old and new wrect):
                    QWidget *parent = q->parentWidget();
                    QPoint globalPosWRect = parent->mapToGlobal(data.wrect.topLeft());

                    QWidget *nativeParent = q->nativeParentWidget();
                    QRect dirtyWRect = QRect(nativeParent->mapFromGlobal(globalPosWRect), data.wrect.size());

                    nativeParent->update(dirtyWRect);
                }
                if (q->testAttribute(Qt::WA_OutsideWSRange)) {
                    q->setAttribute(Qt::WA_OutsideWSRange, false);
                    if (!dontShow) {
                        q->setAttribute(Qt::WA_Mapped);
                        // If q is Alien, the following call does nothing:
                        [nsview setHidden:NO];
                    }
                }
                return;
            }
        }

    }

    // unmap if we are outside the valid window system coord system
    bool outsideRange = !wrectInParentCoordSys.isValid();
    bool mapWindow = false;
    if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
        q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
        if (outsideRange) {
            // If q is Alien, the following call does nothing:
            [nsview setHidden:YES];
            q->setAttribute(Qt::WA_Mapped, false);
        } else if (!q->isHidden()) {
            mapWindow = true;
        }
    }

    if (outsideRange)
        return;

    // Store the new clipped rect:
    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();
        }
    }

    if (nsview) {
        // INVARIANT: q is native. Move the actual NSView:
        NSRect bounds = NSMakeRect(
            wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
            wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
        [nsview setFrame:bounds];
        if (jump)
            q->update();
    } else if (QApplicationPrivate::graphicsSystem() == 0){
        // INVARIANT: q is alien and we use native paint engine.
        // Schedule updates where q is moved from and to:
        const QWidget *parent = q->parentWidget();
        const QPoint globalPosOldWRect = parent->mapToGlobal(oldRect.topLeft());
        const QPoint globalPosNewWRect = parent->mapToGlobal(wrectInParentCoordSys.topLeft());

        QWidget *nativeParent = q->nativeParentWidget();
        const QRegion dirtyOldWRect = QRect(nativeParent->mapFromGlobal(globalPosOldWRect), oldRect.size());
        const QRegion dirtyNewWRect = QRect(nativeParent->mapFromGlobal(globalPosNewWRect), wrectInParentCoordSys.size());

        const bool sizeUnchanged = oldRect.size() == wrectInParentCoordSys.size();
        const bool posUnchanged = oldRect.topLeft() == wrectInParentCoordSys.topLeft();

        // Resolve/minimize the region that needs to update:
        if (sizeUnchanged && q->testAttribute(Qt::WA_OpaquePaintEvent)) {
            // INVARIANT: q is opaque, and is only moved (not resized). So in theory we only
            // need to blit pixels, and skip a repaint. But we can only make this work if we
            // had access to the backbuffer, so we need to update all:
            nativeParent->update(dirtyOldWRect | dirtyNewWRect);
        } else if (posUnchanged && q->testAttribute(Qt::WA_StaticContents)) {
            // We only need to redraw exposed areas:
            nativeParent->update(dirtyNewWRect - dirtyOldWRect);
        } else {
            nativeParent->update(dirtyOldWRect | dirtyNewWRect);
        }
    }

    if (mapWindow && !dontShow) {
        q->setAttribute(Qt::WA_Mapped);
        // If q is Alien, the following call does nothing:
        [nsview setHidden:NO];
    }
}

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);
    QMacCocoaAutoReleasePool pool;

    const float max_f(20000);
#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];
}

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);
        if (!isMove && !q->testAttribute(Qt::WA_Moved) && !q->isVisible()) {
            // INVARIANT: The location of the window has not yet been set. The default will
            // instead be to center it on the desktop, or over the parent, if any. Since we now
            // resize the window, we need to adjust the top left position to keep the window
            // centeralized. And we need to to this now (and before show) in case the positioning
            // of other windows (e.g. sub-windows) depend on this position:
            if (QWidget *p = q->parentWidget()) {
                x = p->geometry().center().x() - (w / 2);
                y = p->geometry().center().y() - (h / 2);
            } else {
                QRect availGeo = QApplication::desktop()->availableGeometry(q);
                x = availGeo.center().x() - (w / 2);
                y = availGeo.center().y() - (h / 2);
            }
        }

        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:realWindow];
        } 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:realWindow];
            cocoaFrameRect.origin.y -= 1;
            [window setFrameOrigin:cocoaFrameRect.origin];
        }
    } else {
        setGeometry_sys_helper(x, y, w, h, isMove);
    }

    topLevelAt_cache = 0;
}

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();
    // Apply size restrictions, applicable for Windows & Widgets.
    if (QWExtra *extra = extraData()) {
        w = qBound(extra->minw, w, extra->maxw);
        h = qBound(extra->minh, h, extra->maxh);
    }
    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);

        [qt_mac_nativeview_for(q) setFrame:NSMakeRect(0, 0, w, h)];
    } 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_resizeHelper(oldp, olds);
    }

    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();
    QMacCocoaAutoReleasePool pool;
    NSButton *maximizeButton = [window standardWindowButton:NSWindowZoomButton];
    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) {
            tlwExtra->savedWindowAttributesFromMaximized = (![maximizeButton isHidden] && [maximizeButton isEnabled]);
        }
       [maximizeButton setEnabled:NO];


    } else {
        if (tlwExtra->savedWindowAttributesFromMaximized) {
            [maximizeButton setEnabled:YES];
            tlwExtra->savedWindowAttributesFromMaximized = 0;
        }
    }


}

void QWidgetPrivate::scroll_sys(int dx, int dy)
{
    if (QApplicationPrivate::graphicsSystem() && !paintOnScreen()) {
        // INVARIANT: Alien paint engine
        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 &qscrollRect)
{
    if (QMacScrollOptimization::delayScroll(this, dx, dy, qscrollRect))
        return;

    Q_Q(QWidget);
    if (QApplicationPrivate::graphicsSystem() && !paintOnScreen()) {
        // INVARIANT: Alien paint engine
        scrollRect(qscrollRect, dx, dy);
        return;
    }

    static int accelEnv = -1;
    if (accelEnv == -1) {
        accelEnv = qgetenv("QT_NO_FAST_SCROLL").toInt() == 0;
    }

    // Scroll the whole widget if qscrollRect is not valid:
    QRect validScrollRect = qscrollRect.isValid() ? qscrollRect : q->rect();
    validScrollRect &= clipRect();

    // If q is overlapped by other widgets, we cannot just blit pixels since
    // this will move overlapping widgets as well. In case we just update:
    const bool overlapped = isOverlapped(validScrollRect.translated(data.crect.topLeft()));
    const bool accelerateScroll = accelEnv && isOpaque && !overlapped;
    const bool isAlien = (q->internalWinId() == 0);
    const QPoint scrollDelta(dx, dy);

    // If qscrollRect is valid, we are _not_ supposed to scroll q's children (as documented).
    // But we do scroll children (and the whole of q) if qscrollRect is invalid. This case is
    // documented as undefined, but we exploit it to help factor our code into one function.
    const bool scrollChildren = !qscrollRect.isValid();

    if (!q->updatesEnabled()) {
        // We are told not to update anything on q at this point. So unless
        // we are supposed to scroll children, we bail out early:
        if (!scrollChildren || q->children().isEmpty())
            return;
    }

    if (!accelerateScroll) {
        if (overlapped) {
            QRegion region(validScrollRect);
            subtractOpaqueSiblings(region);
            update_sys(region);
        }else {
            update_sys(qscrollRect);
        }
        return;
    }

    QMacCocoaAutoReleasePool pool;

    // First move all native children. Alien children will indirectly be
    // moved when the parent is scrolled. All directly or indirectly moved
    // children will receive a move event before the function call returns.
    QWidgetList movedChildren;
    if (scrollChildren) {
        QObjectList children = q->children();

        for (int i=0; i<children.size(); i++) {
            QObject *obj = children.at(i);
            if (QWidget *w = qobject_cast<QWidget*>(obj)) {
                if (!w->isWindow()) {
                    w->data->crect = QRect(w->pos() + scrollDelta, w->size());
                    if (NSView *view = qt_mac_nativeview_for(w)) {
                        // INVARIANT: w is not alien
                        [view setFrame:NSMakeRect(
                            w->data->crect.x(), w->data->crect.y(),
                            w->data->crect.width(), w->data->crect.height())];
                    }
                    movedChildren.append(w);
                }
            }
        }
    }

    if (q->testAttribute(Qt::WA_WState_Created) && q->isVisible()) {
        // Scroll q itself according to the qscrollRect, and
        // call update on any exposed areas so that they get redrawn:


        QWidget *nativeWidget = isAlien ? q->nativeParentWidget() : q;
        if (!nativeWidget)
            return;
        OSViewRef view = qt_mac_nativeview_for(nativeWidget);
        if (!view)
            return;

        // Calculate the rectangles that needs to be redrawn
        // after the scroll. This will be source rect minus destination rect:
        QRect deltaXRect;
        if (dx != 0) {
            deltaXRect.setY(validScrollRect.y());
            deltaXRect.setHeight(validScrollRect.height());
            if (dx > 0) {
                deltaXRect.setX(validScrollRect.x());
                deltaXRect.setWidth(dx);
            } else {
                deltaXRect.setX(validScrollRect.x() + validScrollRect.width() + dx);
                deltaXRect.setWidth(-dx);
            }
        }

        QRect deltaYRect;
        if (dy != 0) {
            deltaYRect.setX(validScrollRect.x());
            deltaYRect.setWidth(validScrollRect.width());
            if (dy > 0) {
                deltaYRect.setY(validScrollRect.y());
                deltaYRect.setHeight(dy);
           } else {
                deltaYRect.setY(validScrollRect.y() + validScrollRect.height() + dy);
                deltaYRect.setHeight(-dy);
            }
        }

        if (isAlien) {
            // Adjust the scroll rect to the location as seen from the native parent:
            QPoint scrollTopLeftInsideNative = nativeWidget->mapFromGlobal(q->mapToGlobal(validScrollRect.topLeft()));
            validScrollRect.moveTo(scrollTopLeftInsideNative);
        }

        // Make the pixel copy rect within the validScrollRect bounds:
        NSRect nsscrollRect = NSMakeRect(
            validScrollRect.x() + (dx < 0 ? -dx : 0),
            validScrollRect.y() + (dy < 0 ? -dy : 0),
            validScrollRect.width() + (dx > 0 ? -dx : 0),
            validScrollRect.height() + (dy > 0 ? -dy : 0));

        NSSize deltaSize = NSMakeSize(dx, dy);
        [view scrollRect:nsscrollRect by:deltaSize];

        // Some areas inside the scroll rect might have been marked as dirty from before, which
        // means that they are scheduled to be redrawn. But as we now scroll, those dirty rects
        // should also move along to ensure that q receives repaints on the correct places.
        // Since some of the dirty rects might lay outside, or only intersect with, the scroll
        // rect, the old calls to setNeedsDisplay still makes sense.
        // NB: Using [view translateRectsNeedingDisplayInRect:nsscrollRect by:deltaSize] have
        // so far not been proven fruitful to solve this problem.
        const QVector<QRect> &dirtyRectsToScroll = dirtyOnWidget.rects();
        for (int i=0; i<dirtyRectsToScroll.size(); ++i) {
            QRect qdirtyRect = dirtyRectsToScroll[i];
            qdirtyRect.translate(dx, dy);
            update_sys(qdirtyRect);
        }

        // Update newly exposed areas. This will generate new dirty areas on
        // q, and therefore, we do it after updating the old dirty rects above:
        if (dx != 0)
            update_sys(deltaXRect);
        if (dy != 0)
            update_sys(deltaYRect);

    }

    for (int i=0; i<movedChildren.size(); i++) {
        QWidget *w = movedChildren.at(i);
        QMoveEvent e(w->pos(), w->pos() - scrollDelta);
        QApplication::sendEvent(w, &e);
    }
}

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:
        if (m == PdmWidth)
            return data->crect.width();
        else
            return data->crect.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()
{
    extra->imageMask = 0;
}

void QWidgetPrivate::deleteSysExtra()
{
    if (extra->imageMask)
        CFRelease(extra->imageMask);
}

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

void QWidgetPrivate::deleteTLSysExtra()
{
}

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

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

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

    // 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);
}

void QWidgetPrivate::registerDropSite(bool on)
{
    Q_Q(QWidget);
    if (!q->testAttribute(Qt::WA_WState_Created))
        return;
    NSWindow *win = qt_mac_window_for(q);
    if (on) {
        if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaWindow) class]])
            [static_cast<QT_MANGLE_NAMESPACE(QCocoaWindow) *>(win) registerDragTypes];
        else if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaPanel) class]])
            [static_cast<QT_MANGLE_NAMESPACE(QCocoaPanel) *>(win) registerDragTypes];
    }
}

void QWidgetPrivate::registerTouchWindow(bool enable)
{
    Q_UNUSED(enable);
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
    if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6)
        return;

    Q_Q(QWidget);
    if (enable == touchEventsEnabled)
        return;

    QT_MANGLE_NAMESPACE(QCocoaView) *view = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_effectiveview_for(q));
    if (!view)
        return;

    if (enable) {
        ++view->alienTouchCount;
        if (view->alienTouchCount == 1) {
            touchEventsEnabled = true;
            [view setAcceptsTouchEvents:YES];
        }
    } else {
        --view->alienTouchCount;
        if (view->alienTouchCount == 0) {
            touchEventsEnabled = false;
            [view setAcceptsTouchEvents:NO];
        }
    }
#endif
}

void QWidgetPrivate::setMask_sys(const QRegion &region)
{
    Q_UNUSED(region);
    Q_Q(QWidget);

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

    if (extra->mask.isEmpty()) {
        extra->maskBits = QImage();
        finishCocoaMaskSetup();
    } else {
        syncCocoaMask();
    }

    topLevelAt_cache = 0;
}

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;

    OSWindowRef oswindow = qt_mac_window_for(q);
    [oswindow setAlphaValue:level];
}

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

    if (extra->hasMask) {
        if(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];
    }
    macSetNeedsDisplay(QRegion());
}

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;
    if (!pe)
        pe = new QCoreGraphicsPaintEngine();
    if (pe->isActive()) {
        QPaintEngine *engine = new QCoreGraphicsPaintEngine();
        engine->setAutoDestruct(true);
        return engine;
    }
    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);

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

    if (windowParent && q->windowModality() == Qt::WindowModal){
        // INVARIANT: 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 {
        // INVARIANT: 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::NonModal
            && primaryWindow && primaryWindow->windowModality() == Qt::ApplicationModal) {
            // INVARIANT: Our window has a parent that is application modal.
            // This means that q is supposed to be on top of this window and
            // not be modally shaddowed:
            if ([windowRef isKindOfClass:[NSPanel class]])
                [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
        }
    }

}

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

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

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

}

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()
{
}

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

    if (realWindow) {
        // 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();
    }
}

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

QT_END_NAMESPACE