summaryrefslogtreecommitdiffstats
path: root/src/gui/kernel/qapplication_mac.mm
blob: 5e967b3aac8a9a7d0c78b5fb83999ba04ecaeb41 (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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $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 <Cocoa/Cocoa.h>

#include "qapplication.h"
#include "qbitarray.h"
#include "qclipboard.h"
#include "qcursor.h"
#include "qdatastream.h"
#include "qdatetime.h"
#include "qdesktopwidget.h"
#include "qdockwidget.h"
#include "qevent.h"
#include "qhash.h"
#include "qlayout.h"
#include "qmenubar.h"
#include "qmessagebox.h"
#include "qmime.h"
#include "qpixmapcache.h"
#include "qpointer.h"
#include "qsessionmanager.h"
#include "qsettings.h"
#include "qsocketnotifier.h"
#include "qstyle.h"
#include "qstylefactory.h"
#include "qtextcodec.h"
#include "qtoolbar.h"
#include "qvariant.h"
#include "qwidget.h"
#include "qcolormap.h"
#include "qdir.h"
#include "qdebug.h"
#include "qtimer.h"
#include "private/qmacinputcontext_p.h"
#include "private/qpaintengine_mac_p.h"
#include "private/qcursor_p.h"
#include "private/qapplication_p.h"
#include "private/qcolor_p.h"
#include "private/qwidget_p.h"
#include "private/qkeymapper_p.h"
#include "private/qeventdispatcher_mac_p.h"
#include "private/qeventdispatcher_unix_p.h"
#include <private/qcocoamenuloader_mac_p.h>
#include <private/qcocoaapplication_mac_p.h>
#include <private/qcocoaapplicationdelegate_mac_p.h>
#include <private/qt_cocoa_helpers_mac_p.h>
#include <private/qcocoawindow_mac_p.h>
#include <private/qpixmap_mac_p.h>
#include <private/qdesktopwidget_mac_p.h>
#include <private/qeventdispatcher_mac_p.h>
#include <qvarlengtharray.h>

#ifndef QT_NO_ACCESSIBILITY
#  include "qaccessible.h"
#endif

#ifndef QT_NO_THREAD
#  include "qmutex.h"
#endif

#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include <sys/select.h>

/*****************************************************************************
  QApplication debug facilities
 *****************************************************************************/
//#define DEBUG_EVENTS //like EventDebug but more specific to Qt
//#define DEBUG_DROPPED_EVENTS
//#define DEBUG_MOUSE_MAPS
//#define DEBUG_MODAL_EVENTS
//#define DEBUG_PLATFORM_SETTINGS

#define QMAC_SPEAK_TO_ME
#ifdef QMAC_SPEAK_TO_ME
#include "qregexp.h"
#endif

#ifndef kThemeBrushAlternatePrimaryHighlightColor
#define kThemeBrushAlternatePrimaryHighlightColor -5
#endif


QT_BEGIN_NAMESPACE

//for qt_mac.h
QPaintDevice *qt_mac_safe_pdev = 0;
QList<QMacWindowChangeEvent*> *QMacWindowChangeEvent::change_events = 0;
extern QHash<QByteArray, QFont> *qt_app_fonts_hash(); // qapplication.cpp

/*****************************************************************************
  Internal variables and functions
 *****************************************************************************/
static struct {
    bool use_qt_time_limit;
    QPointer<QWidget> last_widget;
    int last_x, last_y;
    int last_modifiers, last_button;
    EventTime last_time;
} qt_mac_dblclick = { false, 0, -1, -1, 0, 0, -2 };

static bool app_do_modal = false;       // modal mode
extern QWidgetList *qt_modal_stack;     // stack of modal widgets
extern bool qt_tab_all_widgets;         // from qapplication.cpp
bool qt_mac_app_fullscreen = false;
bool qt_scrollbar_jump_to_pos = false;
static bool qt_mac_collapse_on_dblclick = true;
extern int qt_antialiasing_threshold; // from qapplication.cpp
QPointer<QWidget> qt_button_down;                // widget got last button-down
#ifndef QT_MAC_USE_COCOA
static bool qt_button_down_in_content; // whether the button_down was in the content area.
static bool qt_mac_previous_press_in_popup_mode = false;
static bool qt_mac_no_click_through_mode = false;
static int tablet_button_state = 0;
#endif
QPointer<QWidget> qt_mouseover;
#if defined(QT_DEBUG)
static bool        appNoGrab        = false;        // mouse/keyboard grabbing
#endif
#ifndef QT_MAC_USE_COCOA
static EventHandlerRef app_proc_handler = 0;
static EventHandlerUPP app_proc_handlerUPP = 0;
#endif
static AEEventHandlerUPP app_proc_ae_handlerUPP = NULL;
static EventHandlerRef tablet_proximity_handler = 0;
static EventHandlerUPP tablet_proximity_UPP = 0;
bool QApplicationPrivate::native_modal_dialog_active;

/*****************************************************************************
  External functions
 *****************************************************************************/
extern void qt_mac_beep(); //qsound_mac.mm
extern Qt::KeyboardModifiers qt_mac_get_modifiers(int keys); //qkeymapper_mac.cpp
extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
extern OSWindowRef qt_mac_window_for(const QWidget*); //qwidget_mac.cpp
extern QWidget *qt_mac_find_window(OSWindowRef); //qwidget_mac.cpp
extern void qt_mac_set_cursor(const QCursor *, const QPoint &); //qcursor_mac.cpp
extern bool qt_mac_is_macsheet(const QWidget *); //qwidget_mac.cpp
extern QString qt_mac_from_pascal_string(const Str255); //qglobal.cpp
extern void qt_mac_command_set_enabled(MenuRef, UInt32, bool); //qmenu_mac.cpp
extern bool qt_sendSpontaneousEvent(QObject *obj, QEvent *event); // qapplication.cpp

// Forward Decls
void onApplicationWindowChangedActivation( QWidget*widget, bool activated );
void onApplicationChangedActivation( bool activated );

Q_GUI_EXPORT bool qt_mac_execute_apple_script(const char *script, long script_len, AEDesc *ret) {
    OSStatus err;
    AEDesc scriptTextDesc;
    ComponentInstance theComponent = 0;
    OSAID scriptID = kOSANullScript, resultID = kOSANullScript;

    // set up locals to a known state
    AECreateDesc(typeNull, 0, 0, &scriptTextDesc);
    scriptID = kOSANullScript;
    resultID = kOSANullScript;

    // open the scripting component
    theComponent = OpenDefaultComponent(kOSAComponentType, typeAppleScript);
    if (!theComponent) {
        err = paramErr;
        goto bail;
    }

    // put the script text into an aedesc
    err = AECreateDesc(typeUTF8Text, script, script_len, &scriptTextDesc);
    if (err != noErr)
        goto bail;

    // compile the script
    err = OSACompile(theComponent, &scriptTextDesc, kOSAModeNull, &scriptID);
    if (err != noErr)
        goto bail;

    // run the script
    err = OSAExecute(theComponent, scriptID, kOSANullScript, kOSAModeNull, &resultID);

    // collect the results - if any
    if (ret) {
        AECreateDesc(typeNull, 0, 0, ret);
        if (err == errOSAScriptError)
            OSAScriptError(theComponent, kOSAErrorMessage, typeChar, ret);
        else if (err == noErr && resultID != kOSANullScript)
            OSADisplay(theComponent, resultID, typeChar, kOSAModeNull, ret);
    }
bail:
    AEDisposeDesc(&scriptTextDesc);
    if (scriptID != kOSANullScript)
        OSADispose(theComponent, scriptID);
    if (resultID != kOSANullScript)
        OSADispose(theComponent, resultID);
    if (theComponent)
        CloseComponent(theComponent);
    return err == noErr;
}

Q_GUI_EXPORT bool qt_mac_execute_apple_script(const char *script, AEDesc *ret)
{
    return qt_mac_execute_apple_script(script, qstrlen(script), ret);
}

Q_GUI_EXPORT bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret)
{
    const QByteArray l = script.toUtf8(); return qt_mac_execute_apple_script(l.constData(), l.size(), ret);
}

/* Resolution change magic */
void qt_mac_display_change_callbk(CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void *)
{
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
    const bool resized = flags & kCGDisplayDesktopShapeChangedFlag;
#else
    Q_UNUSED(flags);
    const bool resized = true;
#endif
    if (resized && qApp) {
        if (QDesktopWidget *dw = qApp->desktop()) {
            QResizeEvent *re = new QResizeEvent(dw->size(), dw->size());
            QApplication::postEvent(dw, re);
            QCoreGraphicsPaintEngine::cleanUpMacColorSpaces();
        }
    }
}

#ifdef DEBUG_PLATFORM_SETTINGS
static void qt_mac_debug_palette(const QPalette &pal, const QPalette &pal2, const QString &where)
{
    const char *const groups[] = {"Active", "Disabled", "Inactive" };
    const char *const roles[] = { "WindowText", "Button", "Light", "Midlight", "Dark", "Mid",
                            "Text", "BrightText", "ButtonText", "Base", "Window", "Shadow",
                            "Highlight", "HighlightedText", "Link", "LinkVisited" };
    if (!where.isNull())
        qDebug("qt-internal: %s", where.toLatin1().constData());
    for(int grp = 0; grp < QPalette::NColorGroups; grp++) {
        for(int role = 0; role < QPalette::NColorRoles; role++) {
            QBrush b = pal.brush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role);
            QPixmap pm = b.texture();
            qDebug("  %s::%s %d::%d::%d [%p]%s", groups[grp], roles[role], b.color().red(),
                   b.color().green(), b.color().blue(), pm.isNull() ? 0 : &pm,
                   pal2.brush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role) != b ? " (*)" : "");
        }
    }

}
#else
#define qt_mac_debug_palette(x, y, z)
#endif

//raise a notification
#ifndef QT_MAC_USE_COCOA
static NMRec qt_mac_notification = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
#endif
void qt_mac_send_notification()
{
#ifndef QT_MAC_USE_COCOA
    //send it
    qt_mac_notification.nmMark = 1; //non-zero magic number
    qt_mac_notification.qType = nmType;
    NMInstall(&qt_mac_notification);
#else
    QMacCocoaAutoReleasePool pool;
    [[NSApplication sharedApplication] requestUserAttention:NSInformationalRequest];
#endif
}

void qt_mac_cancel_notification()
{
#ifndef QT_MAC_USE_COCOA
    NMRemove(&qt_mac_notification);
#else
    QMacCocoaAutoReleasePool pool;
    [[NSApplication sharedApplication] cancelUserAttentionRequest:NSInformationalRequest];
#endif
}

#ifndef QT_MAC_USE_COCOA
//find widget (and part) at a given point
static short qt_mac_window_at(int x, int y, QWidget **w=0)
{
    Point p;
    p.h = x;
    p.v = y;
    OSWindowRef wp;
    WindowPartCode wpc;
    OSStatus err = FindWindowOfClass(&p, kAllWindowClasses, &wp, &wpc);
    if(err != noErr) {
        if(w)
            (*w) = 0;
        return wpc;
    }
    if(w) {
        if(wp) {
            *w = qt_mac_find_window(wp);
#if 0
            if(!*w)
                qWarning("QApplication: qt_mac_window_at: Couldn't find %d",(int)wp);
#endif
        } else {
            *w = 0;
        }
    }
    return wpc;
}

#endif

void qt_mac_set_app_icon(const QPixmap &pixmap)
{
#ifndef QT_MAC_USE_COCOA
    if(pixmap.isNull()) {
        RestoreApplicationDockTileImage();
    } else {
        CGImageRef img = (CGImageRef)pixmap.macCGHandle();
        SetApplicationDockTileImage(img);
        CGImageRelease(img);
    }
#else
    QMacCocoaAutoReleasePool pool;
    NSImage *image = NULL;
    if (pixmap.isNull()) {
        // Get Application icon from bundle
        image = [[NSImage imageNamed:@"NSApplicationIcon"] retain]; // released below
    } else {
        image = static_cast<NSImage *>(qt_mac_create_nsimage(pixmap));
    }

    [NSApp setApplicationIconImage:image];
    [image release];
#endif
}

Q_GUI_EXPORT void qt_mac_set_press_and_hold_context(bool b)
{
    Q_UNUSED(b);
    qWarning("qt_mac_set_press_and_hold_context: This functionality is no longer available");
}

bool qt_nograb()                                // application no-grab option
{
#if defined(QT_DEBUG)
    return appNoGrab;
#else
    return false;
#endif
}

void qt_mac_update_os_settings()
{
    if (!qApp)
        return;
    if (!QApplication::startingUp()) {
        static bool needToPolish = true;
        if (needToPolish) {
            QApplication::style()->polish(qApp);
            needToPolish = false;
        }
    }
    //focus mode
    /* First worked as of 10.2.3 */
    QSettings appleSettings(QLatin1String("apple.com"));
    QVariant appleValue = appleSettings.value(QLatin1String("AppleKeyboardUIMode"), 0);
    qt_tab_all_widgets = (appleValue.toInt() & 0x2);
    //paging mode
    /* First worked as of 10.2.3 */
    appleValue = appleSettings.value(QLatin1String("AppleScrollerPagingBehavior"), false);
    qt_scrollbar_jump_to_pos = appleValue.toBool();
    //collapse
    /* First worked as of 10.3.3 */
    appleValue = appleSettings.value(QLatin1String("AppleMiniaturizeOnDoubleClick"), true);
    qt_mac_collapse_on_dblclick = appleValue.toBool();

    // Anti-aliasing threshold
    appleValue = appleSettings.value(QLatin1String("AppleAntiAliasingThreshold"));
    if (appleValue.isValid())
        qt_antialiasing_threshold = appleValue.toInt();

#ifdef DEBUG_PLATFORM_SETTINGS
    qDebug("qt_mac_update_os_settings *********************************************************************");
#endif
    { // setup the global palette
        QColor qc;
        (void) QApplication::style();  // trigger creation of application style and system palettes
        QPalette pal = *QApplicationPrivate::sys_pal;

        pal.setBrush( QPalette::Active, QPalette::Highlight, qcolorForTheme(kThemeBrushPrimaryHighlightColor) );
        pal.setBrush( QPalette::Inactive, QPalette::Highlight, qcolorForTheme(kThemeBrushSecondaryHighlightColor) );

        pal.setBrush( QPalette::Disabled, QPalette::Highlight, qcolorForTheme(kThemeBrushSecondaryHighlightColor) );
        pal.setBrush( QPalette::Active, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonActiveDarkShadow) );

        pal.setBrush( QPalette::Inactive, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonInactiveDarkShadow) );
        pal.setBrush( QPalette::Disabled, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonInactiveDarkShadow) );

        qc = qcolorForThemeTextColor(kThemeTextColorDialogActive);
        pal.setColor(QPalette::Active, QPalette::Text, qc);
        pal.setColor(QPalette::Active, QPalette::WindowText, qc);
        pal.setColor(QPalette::Active, QPalette::HighlightedText, qc);

        qc = qcolorForThemeTextColor(kThemeTextColorDialogInactive);
        pal.setColor(QPalette::Inactive, QPalette::Text, qc);
        pal.setColor(QPalette::Inactive, QPalette::WindowText, qc);
        pal.setColor(QPalette::Inactive, QPalette::HighlightedText, qc);
        pal.setColor(QPalette::Disabled, QPalette::Text, qc);
        pal.setColor(QPalette::Disabled, QPalette::WindowText, qc);
        pal.setColor(QPalette::Disabled, QPalette::HighlightedText, qc);
        pal.setBrush(QPalette::ToolTipBase, QColor(255, 255, 199));

        if (!QApplicationPrivate::sys_pal || *QApplicationPrivate::sys_pal != pal) {
            QApplicationPrivate::setSystemPalette(pal);
            QApplication::setPalette(pal);
        }
#ifdef DEBUG_PLATFORM_SETTINGS
        qt_mac_debug_palette(pal, QApplication::palette(), "Global Palette");
#endif
    }

    QFont fnt = qfontForThemeFont(kThemeApplicationFont);
#ifdef DEBUG_PLATFORM_SETTINGS
    qDebug("qt-internal: Font for Application [%s::%d::%d::%d]",
           fnt.family().toLatin1().constData(), fnt.pointSize(), fnt.bold(), fnt.italic());
#endif
    if (!QApplicationPrivate::sys_font || *QApplicationPrivate::sys_font != fnt)
        QApplicationPrivate::setSystemFont(fnt);

    { //setup the fonts
        struct FontMap {
            FontMap(const char *qc, short fk) : qt_class(qc), font_key(fk) { }
            const char *const qt_class;
            short font_key;
        } mac_widget_fonts[] = {
            FontMap("QPushButton", kThemePushButtonFont),
            FontMap("QListView", kThemeViewsFont),
            FontMap("QListBox", kThemeViewsFont),
            FontMap("QTitleBar", kThemeWindowTitleFont),
            FontMap("QMenuBar", kThemeMenuTitleFont),
            FontMap("QMenu", kThemeMenuItemFont),
            FontMap("QComboMenuItem", kThemeSystemFont),
            FontMap("QHeaderView", kThemeSmallSystemFont),
            FontMap("Q3Header", kThemeSmallSystemFont),
            FontMap("QTipLabel", kThemeSmallSystemFont),
            FontMap("QLabel", kThemeSystemFont),
            FontMap("QToolButton", kThemeSmallSystemFont),
            FontMap("QMenuItem", kThemeMenuItemCmdKeyFont),  // It doesn't exist, but its unique.
            FontMap("QComboLineEdit", kThemeViewsFont),  // It doesn't exist, but its unique.
            FontMap("QSmallFont", kThemeSmallSystemFont),  // It doesn't exist, but its unique.
            FontMap("QMiniFont", kThemeMiniSystemFont),  // It doesn't exist, but its unique.
            FontMap(0, 0) };
        for(int i = 0; mac_widget_fonts[i].qt_class; i++) {
            QFont fnt = qfontForThemeFont(mac_widget_fonts[i].font_key);
            bool set_font = true;
            QHash<QByteArray, QFont> *hash = qt_app_fonts_hash();
            if (!hash->isEmpty()) {
                QHash<QByteArray, QFont>::const_iterator it
                                        = hash->constFind(mac_widget_fonts[i].qt_class);
                if (it != hash->constEnd())
                    set_font = (fnt != *it);
            }
            if (set_font) {
                QApplication::setFont(fnt, mac_widget_fonts[i].qt_class);
#ifdef DEBUG_PLATFORM_SETTINGS
                qDebug("qt-internal: Font for %s [%s::%d::%d::%d]", mac_widget_fonts[i].qt_class,
                       fnt.family().toLatin1().constData(), fnt.pointSize(), fnt.bold(), fnt.italic());
#endif
            }
        }
    }
    QApplicationPrivate::initializeWidgetPaletteHash();
#ifdef DEBUG_PLATFORM_SETTINGS
    qDebug("qt_mac_update_os_settings END !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
#endif
}

void QApplicationPrivate::initializeWidgetPaletteHash()
{
    { //setup the palette
        struct PaletteMap {
            inline PaletteMap(const char *qc, ThemeBrush a, ThemeBrush i) :
                qt_class(qc), active(a), inactive(i) { }
            const char *const qt_class;
            ThemeBrush active, inactive;
        } mac_widget_colors[] = {
            PaletteMap("QToolButton", kThemeTextColorBevelButtonActive, kThemeTextColorBevelButtonInactive),
            PaletteMap("QAbstractButton", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
            PaletteMap("QHeaderView", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
            PaletteMap("Q3Header", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
            PaletteMap("QComboBox", kThemeTextColorPopupButtonActive, kThemeTextColorPopupButtonInactive),
            PaletteMap("QAbstractItemView", kThemeTextColorListView, kThemeTextColorDialogInactive),
            PaletteMap("QMessageBoxLabel", kThemeTextColorAlertActive, kThemeTextColorAlertInactive),
            PaletteMap("QTabBar", kThemeTextColorTabFrontActive, kThemeTextColorTabFrontInactive),
            PaletteMap("QLabel", kThemeTextColorPlacardActive, kThemeTextColorPlacardInactive),
            PaletteMap("QGroupBox", kThemeTextColorPlacardActive, kThemeTextColorPlacardInactive),
            PaletteMap("QMenu", kThemeTextColorPopupLabelActive, kThemeTextColorPopupLabelInactive),
            PaletteMap("QTextEdit", 0, 0),
            PaletteMap("QTextControl", 0, 0),
            PaletteMap("QLineEdit", 0, 0),
            PaletteMap(0, 0, 0) };
        QColor qc;
        for(int i = 0; mac_widget_colors[i].qt_class; i++) {
            QPalette pal;
            if (mac_widget_colors[i].active != 0) {
                qc = qcolorForThemeTextColor(mac_widget_colors[i].active);
                pal.setColor(QPalette::Active, QPalette::Text, qc);
                pal.setColor(QPalette::Active, QPalette::WindowText, qc);
                pal.setColor(QPalette::Active, QPalette::HighlightedText, qc);
                qc = qcolorForThemeTextColor(mac_widget_colors[i].inactive);
                pal.setColor(QPalette::Inactive, QPalette::Text, qc);
                pal.setColor(QPalette::Disabled, QPalette::Text, qc);
                pal.setColor(QPalette::Inactive, QPalette::WindowText, qc);
                pal.setColor(QPalette::Disabled, QPalette::WindowText, qc);
                pal.setColor(QPalette::Inactive, QPalette::HighlightedText, qc);
                pal.setColor(QPalette::Disabled, QPalette::HighlightedText, qc);
            }
            if (!strcmp(mac_widget_colors[i].qt_class, "QMenu")) {
                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemActive);
                pal.setBrush(QPalette::ButtonText, qc);
                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemSelected);
                pal.setBrush(QPalette::HighlightedText, qc);
                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemDisabled);
                pal.setBrush(QPalette::Disabled, QPalette::Text, qc);
            } else if (!strcmp(mac_widget_colors[i].qt_class, "QAbstractButton")
                      || !strcmp(mac_widget_colors[i].qt_class, "QHeaderView")
                      || !strcmp(mac_widget_colors[i].qt_class, "Q3Header")) { //special
                pal.setColor(QPalette::Disabled, QPalette::ButtonText,
                             pal.color(QPalette::Disabled, QPalette::Text));
                pal.setColor(QPalette::Inactive, QPalette::ButtonText,
                             pal.color(QPalette::Inactive, QPalette::Text));
                pal.setColor(QPalette::Active, QPalette::ButtonText,
                             pal.color(QPalette::Active, QPalette::Text));
            } else if (!strcmp(mac_widget_colors[i].qt_class, "QAbstractItemView")) {
                pal.setBrush(QPalette::Active, QPalette::Highlight,
                             qcolorForTheme(kThemeBrushAlternatePrimaryHighlightColor));
                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemSelected);
                pal.setBrush(QPalette::Active, QPalette::HighlightedText, qc);
#if 1
                pal.setBrush(QPalette::Inactive, QPalette::Text,
                              pal.brush(QPalette::Active, QPalette::Text));
                pal.setBrush(QPalette::Inactive, QPalette::HighlightedText,
                              pal.brush(QPalette::Active, QPalette::Text));
#endif
            } else if (!strcmp(mac_widget_colors[i].qt_class, "QTextEdit")
                       || !strcmp(mac_widget_colors[i].qt_class, "QTextControl")) {
                pal.setBrush(QPalette::Inactive, QPalette::Text,
                              pal.brush(QPalette::Active, QPalette::Text));
                pal.setBrush(QPalette::Inactive, QPalette::HighlightedText,
                              pal.brush(QPalette::Active, QPalette::Text));
            } else if (!strcmp(mac_widget_colors[i].qt_class, "QLineEdit")) {
                pal.setBrush(QPalette::Disabled, QPalette::Base,
                             pal.brush(QPalette::Active, QPalette::Base));
            }

            bool set_palette = true;
            extern QHash<QByteArray, QPalette> *qt_app_palettes_hash(); //qapplication.cpp
            QHash<QByteArray, QPalette> *phash = qt_app_palettes_hash();
            if (!phash->isEmpty()) {
                QHash<QByteArray, QPalette>::const_iterator it
                                    = phash->constFind(mac_widget_colors[i].qt_class);
                if (it != phash->constEnd())
                    set_palette = (pal != *it);
            }
            if (set_palette) {
                QApplication::setPalette(pal, mac_widget_colors[i].qt_class);
#ifdef DEBUG_PLATFORM_SETTINGS
                qt_mac_debug_palette(pal, QApplication::palette(), QLatin1String("Palette for ") + QString::fromLatin1(mac_widget_colors[i].qt_class));
#endif
            }
        }
    }
}

static void qt_mac_event_release(EventRef &event)
{
    ReleaseEvent(event);
    event = 0;
}
#ifndef QT_MAC_USE_COCOA
static void qt_mac_event_release(QWidget *w, EventRef &event)
{
    if (event) {
        QWidget *widget = 0;
        if (GetEventParameter(event, kEventParamQWidget, typeQWidget, 0, sizeof(widget), 0, &widget) == noErr
           && w == widget) {
            if (IsEventInQueue(GetMainEventQueue(), event))
                RemoveEventFromQueue(GetMainEventQueue(), event);
            qt_mac_event_release(event);
        }
    }
}

static bool qt_mac_event_remove(EventRef &event)
{
    if (event) {
        if (IsEventInQueue(GetMainEventQueue(), event))
            RemoveEventFromQueue(GetMainEventQueue(), event);
        qt_mac_event_release(event);
        return true;
    }
    return false;
}
#endif

/* sheets */
#ifndef QT_MAC_USE_COCOA
static EventRef request_showsheet_pending = 0;
#endif
void qt_event_request_showsheet(QWidget *w)
{
    Q_ASSERT(qt_mac_is_macsheet(w));
#ifdef QT_MAC_USE_COCOA
    [NSApp beginSheet:qt_mac_window_for(w) modalForWindow:qt_mac_window_for(w->parentWidget())
        modalDelegate:nil didEndSelector:nil contextInfo:0];
#else
    qt_mac_event_remove(request_showsheet_pending);
    CreateEvent(0, kEventClassQt, kEventQtRequestShowSheet, GetCurrentEventTime(),
                kEventAttributeUserEvent, &request_showsheet_pending);
    SetEventParameter(request_showsheet_pending, kEventParamQWidget, typeQWidget, sizeof(w), &w);
    PostEventToQueue(GetMainEventQueue(), request_showsheet_pending, kEventPriorityStandard);
#endif
}

static void qt_post_window_change_event(QWidget *widget)
{
    qt_widget_private(widget)->needWindowChange = true;
    QEvent *glWindowChangeEvent = new QEvent(QEvent::MacGLWindowChange);
    QApplication::postEvent(widget, glWindowChangeEvent);
}

/*
    Posts updates to all child and grandchild OpenGL widgets for the given widget.
*/
static void qt_mac_update_child_gl_widgets(QWidget *widget)
{
    if (widget->isWindow())
        return;

    // Update all OpenGL child widgets for the given widget.
    QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget)->glWidgets;
    QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
    QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();

    for (;it != end; ++it) {
        qt_post_window_change_event(it->widget);
    }
}

/*
    Sends updates to all child and grandchild gl widgets that have updates pending.
*/
void qt_mac_send_posted_gl_updates(QWidget *widget)
{
    QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget)->glWidgets;
    QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
    QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();

    for (;it != end; ++it) {
        QWidget *glWidget = it->widget;
        if (qt_widget_private(glWidget)->needWindowChange) {
            QEvent glChangeEvent(QEvent::MacGLWindowChange);
            QApplication::sendEvent(glWidget, &glChangeEvent);
        }
    }
}

/*
    Posts updates to all OpenGL widgets within the window that the given widget intersects.
*/
static void qt_mac_update_intersected_gl_widgets(QWidget *widget)
{
#ifndef QT_MAC_USE_COCOA
    QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget->window())->glWidgets;
    if (glWidgets.isEmpty())
        return;

    // Exit if the window has not been created yet (mapToGlobal/size will force create it)
    if (widget->testAttribute(Qt::WA_WState_Created) == false || HIViewGetWindow(qt_mac_nativeview_for(widget)) == 0)
        return;

    const QRect globalWidgetRect = QRect(widget->mapToGlobal(QPoint(0, 0)), widget->size());

    QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
    QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();

    for (;it != end; ++it){
        QWidget *glWidget = it->widget;
        const QRect globalGlWidgetRect = QRect(glWidget->mapToGlobal(QPoint(0, 0)), glWidget->size());
        if (globalWidgetRect.intersects(globalGlWidgetRect)) {
            qt_post_window_change_event(glWidget);
            it->lastUpdateWidget = widget;
        } else if (it->lastUpdateWidget == widget) {
            // Update the gl wigets that the widget intersected the last time around, 
            // and that we are not intersecting now. This prevents paint errors when the 
            // intersecting widget leaves a gl widget.
            qt_post_window_change_event(glWidget);
            it->lastUpdateWidget = 0;            
        }
    }
#else
    Q_UNUSED(widget);
#endif
}

/*
    Posts a kEventQtRequestWindowChange event to the main Carbon event queue.
*/
static EventRef request_window_change_pending = 0;
Q_GUI_EXPORT void qt_event_request_window_change()
{
    if(request_window_change_pending)
        return;

    CreateEvent(0, kEventClassQt, kEventQtRequestWindowChange, GetCurrentEventTime(),
                kEventAttributeUserEvent, &request_window_change_pending);
    PostEventToQueue(GetMainEventQueue(), request_window_change_pending, kEventPriorityHigh);
}

/* window changing. This is a hack around Apple's missing functionality, pending the toolbox
   team fix. --Sam */
Q_GUI_EXPORT void qt_event_request_window_change(QWidget *widget)
{
    if (!widget)
        return;

    // Post a kEventQtRequestWindowChange event. This event is semi-public,
    // don't remove this line!
    qt_event_request_window_change();
    
    // Post update request on gl widgets unconditionally. 
    if (qt_widget_private(widget)->isGLWidget == true) {
        qt_post_window_change_event(widget);
        return;
    }

    qt_mac_update_child_gl_widgets(widget);
    qt_mac_update_intersected_gl_widgets(widget);
}

/* activation */
static struct {
    QPointer<QWidget> widget;
    EventRef event;
    EventLoopTimerRef timer;
    EventLoopTimerUPP timerUPP;
} request_activate_pending = { 0, 0, 0, 0 };
bool qt_event_remove_activate()
{
    if (request_activate_pending.timer) {
        RemoveEventLoopTimer(request_activate_pending.timer);
        request_activate_pending.timer = 0;
    }
    if (request_activate_pending.event)
        qt_mac_event_release(request_activate_pending.event);
    return true;
}

void qt_event_activate_timer_callbk(EventLoopTimerRef r, void *)
{
    EventLoopTimerRef otc = request_activate_pending.timer;
    qt_event_remove_activate();
    if (r == otc && !request_activate_pending.widget.isNull()) {
        const QWidget *tlw = request_activate_pending.widget->window();
        Qt::WindowType wt = tlw->windowType();
        if (tlw->isVisible()
               && ((wt != Qt::Desktop && wt != Qt::Popup && wt != Qt::Tool) || tlw->isModal())) {
            CreateEvent(0, kEventClassQt, kEventQtRequestActivate, GetCurrentEventTime(),
                        kEventAttributeUserEvent, &request_activate_pending.event);
            PostEventToQueue(GetMainEventQueue(), request_activate_pending.event, kEventPriorityHigh);
        }
    }
}

void qt_event_request_activate(QWidget *w)
{
    if (w == request_activate_pending.widget)
        return;

    /* We put these into a timer because due to order of events being sent we need to be sure this
       comes from inside of the event loop */
    qt_event_remove_activate();
    if (!request_activate_pending.timerUPP)
        request_activate_pending.timerUPP = NewEventLoopTimerUPP(qt_event_activate_timer_callbk);
    request_activate_pending.widget = w;
    InstallEventLoopTimer(GetMainEventLoop(), 0, 0, request_activate_pending.timerUPP, 0, &request_activate_pending.timer);
}


/* menubars */
#ifndef QT_MAC_USE_COCOA
static EventRef request_menubarupdate_pending = 0;
#endif
void qt_event_request_menubarupdate()
{
#ifndef QT_MAC_USE_COCOA
    if (request_menubarupdate_pending) {
        if (IsEventInQueue(GetMainEventQueue(), request_menubarupdate_pending))
            return;
#ifdef DEBUG_DROPPED_EVENTS
        qDebug("%s:%d Whoa, we dropped an event on the floor!", __FILE__, __LINE__);
#endif
    }

    CreateEvent(0, kEventClassQt, kEventQtRequestMenubarUpdate, GetCurrentEventTime(),
                kEventAttributeUserEvent, &request_menubarupdate_pending);
    PostEventToQueue(GetMainEventQueue(), request_menubarupdate_pending, kEventPriorityHigh);
#else
    // Just call this. The request has the benefit that we don't call this multiple times, but
    // we can optimize this.
    QMenuBar::macUpdateMenuBar();
#endif
}

#ifndef QT_MAC_USE_COCOA
//context menu
static EventRef request_context_pending = 0;
static void qt_event_request_context(QWidget *w=0, EventRef *where=0)
{
    if (!where)
        where = &request_context_pending;
    if (*where)
        return;
    CreateEvent(0, kEventClassQt, kEventQtRequestContext, GetCurrentEventTime(),
                kEventAttributeUserEvent, where);
    if (w)
        SetEventParameter(*where, kEventParamQWidget, typeQWidget, sizeof(w), &w);
    PostEventToQueue(GetMainEventQueue(), *where, kEventPriorityStandard);
}
#endif

void QApplicationPrivate::createEventDispatcher()
{
    Q_Q(QApplication);
    if (q->type() != QApplication::Tty)
        eventDispatcher = new QEventDispatcherMac(q);
    else
        eventDispatcher = new QEventDispatcherUNIX(q);
}

/* clipboard */
void qt_event_send_clipboard_changed()
{
#ifndef QT_MAC_USE_COCOA
    AppleEvent ae;
    if (AECreateAppleEvent(kEventClassQt, typeAEClipboardChanged, 0, kAutoGenerateReturnID, kAnyTransactionID, &ae) != noErr)
        qDebug("Can't happen!!");
    AppleEvent reply;
    AESend(&ae, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, 0, 0);
#endif
}

/* app menu */
static QMenu *qt_mac_dock_menu = 0;
Q_GUI_EXPORT void qt_mac_set_dock_menu(QMenu *menu)
{
    qt_mac_dock_menu = menu;
#ifdef QT_MAC_USE_COCOA
    [NSApp setDockMenu:menu->macMenu()];
#else
    SetApplicationDockTileMenu(menu->macMenu());
#endif
}

/* events that hold pointers to widgets, must be cleaned up like this */
void qt_mac_event_release(QWidget *w)
{
    if (w) {
#ifndef QT_MAC_USE_COCOA
        qt_mac_event_release(w, request_showsheet_pending);
        qt_mac_event_release(w, request_context_pending);
#endif
        if (w == qt_mac_dock_menu) {
            qt_mac_dock_menu = 0;
#ifndef QT_MAC_USE_COCOA
            SetApplicationDockTileMenu(0);
#else
            [NSApp setDockMenu:0];
#endif
        }
    }
}

struct QMacAppleEventTypeSpec {
    AEEventClass mac_class;
    AEEventID mac_id;
} app_apple_events[] = {
    { kCoreEventClass, kAEQuitApplication },
    { kCoreEventClass, kAEOpenDocuments }
};
#ifndef QT_MAC_USE_COCOA
/* watched events */
static EventTypeSpec app_events[] = {
    { kEventClassQt, kEventQtRequestWindowChange },
    { kEventClassQt, kEventQtRequestShowSheet },
    { kEventClassQt, kEventQtRequestContext },
    { kEventClassQt, kEventQtRequestActivate },
    { kEventClassQt, kEventQtRequestMenubarUpdate },

    { kEventClassWindow, kEventWindowActivated },
    { kEventClassWindow, kEventWindowDeactivated },

    { kEventClassMouse, kEventMouseWheelMoved },
    { kEventClassMouse, kEventMouseDown },
    { kEventClassMouse, kEventMouseUp },
    { kEventClassMouse, kEventMouseDragged },
    { kEventClassMouse, kEventMouseMoved },

    { kEventClassTablet, kEventTabletProximity },

    { kEventClassApplication, kEventAppActivated },
    { kEventClassApplication, kEventAppDeactivated },
    { kEventClassApplication, kEventAppAvailableWindowBoundsChanged },

    //    { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent },
    { kEventClassKeyboard, kEventRawKeyModifiersChanged },
    { kEventClassKeyboard, kEventRawKeyRepeat },
    { kEventClassKeyboard, kEventRawKeyUp },
    { kEventClassKeyboard, kEventRawKeyDown },

    { kEventClassCommand, kEventCommandProcess },

    { kEventClassAppleEvent, kEventAppleEvent },

    { kAppearanceEventClass, kAEAppearanceChanged }
};

void qt_init_app_proc_handler()
{
    InstallEventHandler(GetApplicationEventTarget(), app_proc_handlerUPP,
                        GetEventTypeCount(app_events), app_events, (void *)qApp,
                        &app_proc_handler);
}
#endif // QT_MAC_USE_COCOA

static void qt_init_tablet_proximity_handler()
{
    EventTypeSpec	tabletProximityEvent = { kEventClassTablet, kEventTabletProximity };
    InstallEventHandler(GetEventMonitorTarget(), tablet_proximity_UPP,
                        1, &tabletProximityEvent, qApp, &tablet_proximity_handler);
}

static void qt_release_tablet_proximity_handler()
{
    RemoveEventHandler(tablet_proximity_handler);
}

QString QApplicationPrivate::appName() const
{
    static QString applName;
    if (applName.isEmpty()) {
        applName = QCoreApplicationPrivate::macMenuBarName();
        ProcessSerialNumber psn;
        if (applName.isEmpty() && qt_is_gui_used && GetCurrentProcess(&psn) == noErr) {
            QCFString cfstr;
            CopyProcessName(&psn, &cfstr);
            applName = cfstr;
        }
    }
    return applName;
}

void qt_release_app_proc_handler()
{
#ifndef QT_MAC_USE_COCOA
    if (app_proc_handler) {
        RemoveEventHandler(app_proc_handler);
        app_proc_handler = 0;
    }
#endif
}

/* platform specific implementations */
void qt_init(QApplicationPrivate *priv, int)
{
    if (qt_is_gui_used) {
        CGDisplayRegisterReconfigurationCallback(qt_mac_display_change_callbk, 0);
        ProcessSerialNumber psn;
        if (GetCurrentProcess(&psn) == noErr) {
            // Jambi needs to transform itself since most people aren't "used"
            // to putting things in bundles, but other people may actually not
            // want to tranform the process (running as a helper or somethng)
            // so don't do that for them. This means checking both LSUIElement
            // and LSBackgroundOnly. If you set them both... well, you
            // shouldn't do that.

            bool forceTransform = true;
            CFTypeRef value = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
                                                                   CFSTR("LSUIElement"));
            if (value) {
                CFTypeID valueType = CFGetTypeID(value);
                // Officially it's supposed to be a string, a boolean makes sense, so we'll check.
                // A number less so, but OK.
                if (valueType == CFStringGetTypeID())
                    forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
                else if (valueType == CFBooleanGetTypeID())
                    forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
                else if (valueType == CFNumberGetTypeID()) {
                    int valueAsInt;
                    CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
                    forceTransform = !valueAsInt;
                }
            }

            if (forceTransform) {
                value = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
                                                             CFSTR("LSBackgroundOnly"));
                if (value) {
                    CFTypeID valueType = CFGetTypeID(value);
                    if (valueType == CFBooleanGetTypeID())
                        forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
                    else if (valueType == CFStringGetTypeID())
                        forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
                    else if (valueType == CFNumberGetTypeID()) {
                        int valueAsInt;
                        CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
                        forceTransform = !valueAsInt;
                    }
                }
            }


            if (forceTransform) {
                TransformProcessType(&psn, kProcessTransformToForegroundApplication);
            }
        }
    }

    char **argv = priv->argv;

    // Get command line params
    if (int argc = priv->argc) {
        int i, j = 1;
        QString passed_psn;
        for(i=1; i < argc; i++) {
            if (argv[i] && *argv[i] != '-') {
                argv[j++] = argv[i];
                continue;
            }
            QByteArray arg(argv[i]);
#if defined(QT_DEBUG)
            if (arg == "-nograb")
                appNoGrab = !appNoGrab;
            else
#endif // QT_DEBUG
                if (arg.left(5) == "-psn_") {
                    passed_psn = QString::fromLatin1(arg.mid(6));
                } else {
                    argv[j++] = argv[i];
                }
        }
        if (j < priv->argc) {
            priv->argv[j] = 0;
            priv->argc = j;
        }

        //special hack to change working directory (for an app bundle) when running from finder
        if (!passed_psn.isNull() && QDir::currentPath() == QLatin1String("/")) {
            QCFType<CFURLRef> bundleURL(CFBundleCopyBundleURL(CFBundleGetMainBundle()));
            QString qbundlePath = QCFString(CFURLCopyFileSystemPath(bundleURL,
                                            kCFURLPOSIXPathStyle));
            if (qbundlePath.endsWith(QLatin1String(".app")))
                QDir::setCurrent(qbundlePath.section(QLatin1Char('/'), 0, -2));
        }
   }

    QMacPasteboardMime::initialize();

    qApp->setObjectName(priv->appName());
    if (qt_is_gui_used) {
        QColormap::initialize();
        QFont::initialize();
        QCursorData::initialize();
        QCoreGraphicsPaintEngine::initialize();
#ifndef QT_NO_ACCESSIBILITY
        QAccessible::initialize();
#endif
        QMacInputContext::initialize();
        QApplicationPrivate::inputContext = new QMacInputContext;

        if (QApplication::desktopSettingsAware())
            qt_mac_update_os_settings();
#ifndef QT_MAC_USE_COCOA
        if (!app_proc_handler) {
            app_proc_handlerUPP = NewEventHandlerUPP(QApplicationPrivate::globalEventProcessor);
            qt_init_app_proc_handler();
        }

#endif
        if (!app_proc_ae_handlerUPP) {
            app_proc_ae_handlerUPP = AEEventHandlerUPP(QApplicationPrivate::globalAppleEventProcessor);
            for(uint i = 0; i < sizeof(app_apple_events) / sizeof(QMacAppleEventTypeSpec); ++i)
                AEInstallEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id,
                        app_proc_ae_handlerUPP, SRefCon(qApp), true);
        }

        if (QApplicationPrivate::app_style) {
            QEvent ev(QEvent::Style);
            qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
        }
    }
    if (QApplication::desktopSettingsAware())
        QApplicationPrivate::qt_mac_apply_settings();
    // Cocoa application delegate
#ifdef QT_MAC_USE_COCOA
    NSApplication *cocoaApp = [NSApplication sharedApplication];
    QMacCocoaAutoReleasePool pool;
    NSObject *oldDelegate = [cocoaApp delegate];
    QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
    Q_ASSERT(newDelegate);
    [newDelegate setQtPrivate:priv];
    // Only do things that make sense to do once, otherwise we crash.
    if (oldDelegate != newDelegate && !QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
        [newDelegate setReflectionDelegate:oldDelegate];
        [cocoaApp setDelegate:newDelegate];

        QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader = [[QT_MANGLE_NAMESPACE(QCocoaMenuLoader) alloc] init];
        if ([NSBundle loadNibNamed:@"qt_menu" owner:qtMenuLoader] == false) {
            qFatal("Qt internal error: qt_menu.nib could not be loaded. The .nib file"
                   " should be placed in QtGui.framework/Versions/Current/Resources/ "
                   " or in the resources directory of your application bundle.");
        }

        [cocoaApp setMenu:[qtMenuLoader menu]];
        [newDelegate setMenuLoader:qtMenuLoader];
        [qtMenuLoader release];
    }
#endif
    if (QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
        extern void qt_mac_set_native_menubar(bool);
        qt_mac_set_native_menubar(false);
    }
    // Register for Carbon tablet proximity events on the event monitor target.
    // This means that we should receive proximity events even when we aren't the active application.
    if (!tablet_proximity_handler) {
        tablet_proximity_UPP = NewEventHandlerUPP(QApplicationPrivate::tabletProximityCallback);
        qt_init_tablet_proximity_handler();
    }
   priv->native_modal_dialog_active = false;

}

void qt_release_apple_event_handler()
{
    if(app_proc_ae_handlerUPP) {
        for(uint i = 0; i < sizeof(app_apple_events) / sizeof(QMacAppleEventTypeSpec); ++i)
            AERemoveEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id,
                    app_proc_ae_handlerUPP, true);
        DisposeAEEventHandlerUPP(app_proc_ae_handlerUPP);
        app_proc_ae_handlerUPP = 0;
    }
}

/*****************************************************************************
  qt_cleanup() - cleans up when the application is finished
 *****************************************************************************/

void qt_cleanup()
{
    CGDisplayRemoveReconfigurationCallback(qt_mac_display_change_callbk, 0);
#ifndef QT_MAC_USE_COCOA
    qt_release_app_proc_handler();
    if (app_proc_handlerUPP) {
        DisposeEventHandlerUPP(app_proc_handlerUPP);
        app_proc_handlerUPP = 0;
    }
#endif
    qt_release_apple_event_handler();
    qt_release_tablet_proximity_handler();
    if (tablet_proximity_UPP)
        DisposeEventHandlerUPP(tablet_proximity_UPP);

    QPixmapCache::clear();
    if (qt_is_gui_used) {
#ifndef QT_NO_ACCESSIBILITY
        QAccessible::cleanup();
#endif
        QMacInputContext::cleanup();
        QCursorData::cleanup();
        QFont::cleanup();
        QColormap::cleanup();
        if (qt_mac_safe_pdev) {
            delete qt_mac_safe_pdev;
            qt_mac_safe_pdev = 0;
        }
        extern void qt_mac_unregister_widget(); // qapplication_mac.cpp
        qt_mac_unregister_widget();
    }
}

/*****************************************************************************
  Platform specific global and internal functions
 *****************************************************************************/
void qt_updated_rootinfo()
{
}

bool qt_wstate_iconified(WId)
{
    return false;
}

/*****************************************************************************
  Platform specific QApplication members
 *****************************************************************************/
extern QWidget * mac_mouse_grabber;
extern QWidget * mac_keyboard_grabber;

#ifdef QT3_SUPPORT
void QApplication::setMainWidget(QWidget *mainWidget)
{
    QApplicationPrivate::main_widget = mainWidget;
    if (QApplicationPrivate::main_widget && windowIcon().isNull()
        && QApplicationPrivate::main_widget->testAttribute(Qt::WA_SetWindowIcon))
        setWindowIcon(QApplicationPrivate::main_widget->windowIcon());
}
#endif
#ifndef QT_NO_CURSOR

/*****************************************************************************
  QApplication cursor stack
 *****************************************************************************/
void QApplication::setOverrideCursor(const QCursor &cursor)
{
    qApp->d_func()->cursor_list.prepend(cursor);

#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    [static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(cursor)) push];
#else
    if (qApp && qApp->activeWindow())
        qt_mac_set_cursor(&qApp->d_func()->cursor_list.first(), QCursor::pos());
#endif
}

void QApplication::restoreOverrideCursor()
{
    if (qApp->d_func()->cursor_list.isEmpty())
        return;
    qApp->d_func()->cursor_list.removeFirst();

#ifdef QT_MAC_USE_COCOA
    QMacCocoaAutoReleasePool pool;
    [NSCursor pop];
#else
    if (qApp && qApp->activeWindow()) {
        const QCursor def(Qt::ArrowCursor);
        qt_mac_set_cursor(qApp->d_func()->cursor_list.isEmpty() ? &def : &qApp->d_func()->cursor_list.first(), QCursor::pos());
    }
#endif
}
#endif // QT_NO_CURSOR

QWidget *QApplication::topLevelAt(const QPoint &p)
{
#ifndef QT_MAC_USE_COCOA
    QWidget *widget;
    qt_mac_window_at(p.x(), p.y(), &widget);
    return widget;
#else
    NSInteger windowCount;
    NSCountWindows(&windowCount);
    if (windowCount <= 0)
        return 0;  // There's no window to find!
    QMacCocoaAutoReleasePool pool;
    NSPoint cocoaPoint = flipPoint(p);
    QVarLengthArray<NSInteger> windowList(windowCount);
    NSWindowList(windowCount, windowList.data());
    for (int i = 0; i < windowCount; ++i) {
        NSWindow *window = [NSApp windowWithWindowNumber:windowList[i]];
        if (window && NSPointInRect(cocoaPoint, [window frame])) {
            QWidget *candidateWindow = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
            // Check to see if there's a hole in the window where the mask is.
            // If there is, we should just continue to see if there is a window below.
            if (candidateWindow && !candidateWindow->mask().isEmpty()) {
                QPoint localPoint = candidateWindow->mapFromGlobal(p);
                if (!candidateWindow->mask().contains(localPoint)) {
                    continue;
                }
            }
            return candidateWindow;
        }
    }
    return 0; // Couldn't find a window at this point
#endif
}

static QWidget *qt_mac_recursive_widgetAt(QWidget *widget, int x, int y)
{
    if (!widget)
        return 0;
    const QObjectList kids = widget->children();
    for(int i = kids.size()-1; i >= 0; --i) {
        if ( QWidget *kid = qobject_cast<QWidget*>(kids.at(i)) ) {
            if (kid->isVisible() && !kid->isTopLevel() &&
                    !kid->testAttribute(Qt::WA_TransparentForMouseEvents)) {
                const int wx=kid->x(), wy=kid->y(),
                      wx2=wx+kid->width(), wy2=wy+kid->height();
                if (x >= wx && y >= wy && x < wx2 && y < wy2) {
                    const QRegion mask = kid->mask();
                    if (!mask.isEmpty() && !mask.contains(QPoint(x-wx, y-wy)))
                        continue;
                    return qt_mac_recursive_widgetAt(kid, x-wx, y-wy);
                }
            }
        }
    }
    return widget;
}

/*****************************************************************************
  Main event loop
 *****************************************************************************/

bool QApplicationPrivate::modalState()
{
    return app_do_modal;
}

#ifdef QT_MAC_USE_COCOA
#endif

void QApplicationPrivate::enterModal_sys(QWidget *widget)
{
#ifdef DEBUG_MODAL_EVENTS
    Q_ASSERT(widget);
    qDebug("Entering modal state with %s::%s::%p (%d)", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(),
            widget, qt_modal_stack ? (int)qt_modal_stack->count() : -1);
#endif
    if (!qt_modal_stack)
        qt_modal_stack = new QWidgetList;

    dispatchEnterLeave(0, qt_mouseover);
    qt_mouseover = 0;

    qt_modal_stack->insert(0, widget);
    if (!app_do_modal)
        qt_event_request_menubarupdate();
    app_do_modal = true;
    qt_button_down = 0;

#ifdef QT_MAC_USE_COCOA
    if (!qt_mac_is_macsheet(widget)) {
        // Add a new, empty (null), NSModalSession to the stack.
        // The next time we spin the event dispatcher, it will
        // check the stack, and recurse into a modal session for it:
        QCocoaModalSessionInfo info = {widget, 0};
        QEventDispatcherMacPrivate::cocoaModalSessionStack.push(info);
    }
#endif
}

void QApplicationPrivate::leaveModal_sys(QWidget *widget)
{
    if (qt_modal_stack && qt_modal_stack->removeAll(widget)) {
#ifdef DEBUG_MODAL_EVENTS
        qDebug("Leaving modal state with %s::%s::%p (%d)", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(),
               widget, qt_modal_stack->count());
#endif
        if (qt_modal_stack->isEmpty()) {
            delete qt_modal_stack;
            qt_modal_stack = 0;
            QPoint p(QCursor::pos());
            app_do_modal = false;
            QWidget* w = 0;
            if (QWidget *grabber = QWidget::mouseGrabber())
                w = grabber;
            else
                w = QApplication::widgetAt(p.x(), p.y());
            dispatchEnterLeave(w, qt_mouseover); // send synthetic enter event
            qt_mouseover = w;
        }
#ifdef QT_MAC_USE_COCOA
        if (!qt_mac_is_macsheet(widget))
            QEventDispatcherMacPrivate::rebuildModalSessionStack(true);
#endif
    }
#ifdef DEBUG_MODAL_EVENTS
    else qDebug("Failure to remove %s::%s::%p -- %p", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(), widget, qt_modal_stack);
#endif
    app_do_modal = (qt_modal_stack != 0);
    if (!app_do_modal)
        qt_event_request_menubarupdate();
}

#if defined(QT_MAC_USE_COCOA)
void QApplicationPrivate::_q_runAppModalWindow()
{
    if (QEventDispatcherMacPrivate::blockCocoaRequestModal) {
        // Just postpone the event until the event dispatcher tells
        // us (by releasing the block) that it is OK to recurse into
        // a new event loop for our non-execing modal window:
        qApp->postEvent(qApp, new QEvent(QEvent::CocoaRequestModal));
    } else {
        // Recurse into a new event loop for the current app modal window:
        threadData->eventDispatcher->processEvents(QEventLoop::DialogExec);
    }
}
#endif

QWidget *QApplicationPrivate::tryModalHelper_sys(QWidget *top)
{
#ifndef QT_MAC_USE_COCOA
    if(top && qt_mac_is_macsheet(top) && !IsWindowVisible(qt_mac_window_for(top))) {
        if(OSWindowRef wp = GetFrontWindowOfClass(kSheetWindowClass, true)) {
            if(QWidget *sheet = qt_mac_find_window(wp))
                top = sheet;
        }
    }
#endif
    return top;
}

#ifndef QT_MAC_USE_COCOA
static bool qt_try_modal(QWidget *widget, EventRef event)
{
    QWidget * top = 0;

    if (QApplicationPrivate::tryModalHelper(widget, &top))
        return true;

    // INVARIANT: widget is modally shaddowed within its
    // window, and should therefore not handle the event.
    // However, if the window is not active, the event
    // might suggest that we should bring it to front:

    bool block_event = false;

    if (event) {
        switch (GetEventClass(event)) {
        case kEventClassMouse:
        case kEventClassKeyboard:
            block_event = true;
            break;
        }
    }

    QWidget *activeWidget = QApplication::activeWindow();
    if ((!activeWidget || QApplicationPrivate::isBlockedByModal(activeWidget)) &&
       top->isWindow() && block_event && !QApplicationPrivate::native_modal_dialog_active)
        top->raise();

#ifdef DEBUG_MODAL_EVENTS
    qDebug("%s:%d -- final decision! (%s)", __FILE__, __LINE__, block_event ? "false" : "true");
#endif
    return !block_event;
}
#endif

OSStatus QApplicationPrivate::tabletProximityCallback(EventHandlerCallRef, EventRef carbonEvent,
                                                      void *)
{
    OSType eventClass = GetEventClass(carbonEvent);
    UInt32 eventKind = GetEventKind(carbonEvent);
    if (eventClass != kEventClassTablet || eventKind != kEventTabletProximity)
        return eventNotHandledErr;

    // Get the current point of the device and its unique ID.
    ::TabletProximityRec proxRec;
    GetEventParameter(carbonEvent, kEventParamTabletProximityRec, typeTabletProximityRec, 0,
                      sizeof(proxRec), 0, &proxRec);
    qt_dispatchTabletProximityEvent(proxRec);
    return noErr;
}

OSStatus
QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event, void *data)
{
#ifndef QT_MAC_USE_COCOA
    QApplication *app = (QApplication *)data;
    QScopedLoopLevelCounter loopLevelCounter(app->d_func()->threadData);
    long result;
    if (app->filterEvent(&event, &result))
        return result;
    if(app->macEventFilter(er, event)) //someone else ate it
        return noErr;
    QPointer<QWidget> widget;

    /*We assume all events are handled and in
      the code below we set it to false when we know we didn't handle it, this
      will let rogue events through (shouldn't really happen, but better safe
      than sorry) */
    bool handled_event=true;
    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
    switch(eclass)
    {
    case kEventClassQt:
        if(ekind == kEventQtRequestShowSheet) {
            request_showsheet_pending = 0;
            QWidget *widget = 0;
            GetEventParameter(event, kEventParamQWidget, typeQWidget, 0,
                              sizeof(widget), 0, &widget);
            if(widget) {
                if (widget->macEvent(er, event))
                    return noErr;
                WindowPtr window = qt_mac_window_for(widget);
                bool just_show = !qt_mac_is_macsheet(widget);
                if(!just_show) {
                    OSStatus err = ShowSheetWindow(window, qt_mac_window_for(widget->parentWidget()));
                    if(err != noErr)
                        qWarning("Qt: QWidget: Unable to show as sheet %s::%s [%ld]", widget->metaObject()->className(),
                                 widget->objectName().toLocal8Bit().constData(), long(err));
                    just_show = true;
                }
                if(just_show) //at least the window will be visible, but the sheet flag doesn't work sadly (probalby too many sheets)
                    ShowHide(window, true);
            }
        } else if(ekind == kEventQtRequestWindowChange) {
            qt_mac_event_release(request_window_change_pending);
        } else if(ekind == kEventQtRequestMenubarUpdate) {
            qt_mac_event_release(request_menubarupdate_pending);
            QMenuBar::macUpdateMenuBar();
        } else if(ekind == kEventQtRequestActivate) {
            qt_mac_event_release(request_activate_pending.event);
            if(request_activate_pending.widget) {
                QWidget *tlw = request_activate_pending.widget->window();
                if (tlw->macEvent(er, event))
                    return noErr;
                request_activate_pending.widget = 0;
                tlw->activateWindow();
                SelectWindow(qt_mac_window_for(tlw));
            }
        } else if(ekind == kEventQtRequestContext) {
            bool send = false;
            if ((send = (event == request_context_pending)))
                qt_mac_event_release(request_context_pending);
            if(send) {
                //figure out which widget to send it to
                QPoint where = QCursor::pos();
                QWidget *widget = 0;
                GetEventParameter(event, kEventParamQWidget, typeQWidget, 0,
                                  sizeof(widget), 0, &widget);
                if(!widget) {
                    if(qt_button_down)
                        widget = qt_button_down;
                    else
                        widget = QApplication::widgetAt(where.x(), where.y());
                }
                if(widget && !isBlockedByModal(widget)) {
                    if (widget->macEvent(er, event))
                        return noErr;
                    QPoint plocal(widget->mapFromGlobal(where));
                    const Qt::KeyboardModifiers keyboardModifiers = qt_mac_get_modifiers(GetCurrentEventKeyModifiers());
                    QContextMenuEvent qme(QContextMenuEvent::Mouse, plocal, where, keyboardModifiers);
                    QApplication::sendEvent(widget, &qme);
                    if(qme.isAccepted()) { //once this happens the events before are pitched
                        qt_button_down = 0;
                        qt_mac_dblclick.last_widget = 0;
                    }
                } else {
                    handled_event = false;
                }
            }
        } else {
            handled_event = false;
        }
        break;
    case kEventClassTablet:
        switch (ekind) {
        case kEventTabletProximity:
            // Get the current point of the device and its unique ID.
            ::TabletProximityRec proxRec;
            GetEventParameter(event, kEventParamTabletProximityRec, typeTabletProximityRec, 0,
                              sizeof(proxRec), 0, &proxRec);
            qt_dispatchTabletProximityEvent(proxRec);
        }
        break;
    case kEventClassMouse:
    {
        static const int kEventParamQAppSeenMouseEvent = 'QASM';
        // Check if we've seen the event, if we have we shouldn't process
        // it again as it may lead to spurious "double events"
        bool seenEvent;
        if (GetEventParameter(event, kEventParamQAppSeenMouseEvent,
                              typeBoolean, 0, sizeof(bool), 0, &seenEvent) == noErr) {
            if (seenEvent)
                return eventNotHandledErr;
        }
        seenEvent = true;
        SetEventParameter(event, kEventParamQAppSeenMouseEvent, typeBoolean,
                          sizeof(bool), &seenEvent);

        Point where;
        bool inNonClientArea = false;
        GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, 0,
                          sizeof(where), 0, &where);
        if(ekind == kEventMouseMoved && qt_mac_app_fullscreen &&
            QApplication::desktop()->screenNumber(QPoint(where.h, where.v)) ==
            QApplication::desktop()->primaryScreen()) {
            if(where.v <= 0)
                ShowMenuBar();
            else if(qt_mac_window_at(where.h, where.v, 0) != inMenuBar)
                HideMenuBar();
        }

#if defined(DEBUG_MOUSE_MAPS)
        const char *edesc = 0;
        switch(ekind) {
        case kEventMouseDown: edesc = "MouseButtonPress"; break;
        case kEventMouseUp: edesc = "MouseButtonRelease"; break;
        case kEventMouseDragged: case kEventMouseMoved: edesc = "MouseMove"; break;
        case kEventMouseWheelMoved: edesc = "MouseWheelMove"; break;
        }
        if(ekind == kEventMouseDown || ekind == kEventMouseUp)
            qDebug("Handling mouse: %s", edesc);
#endif
        QEvent::Type etype = QEvent::None;
        Qt::KeyboardModifiers modifiers;
        {
            UInt32 mac_modifiers = 0;
            GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
                              sizeof(mac_modifiers), 0, &mac_modifiers);
            modifiers = qt_mac_get_modifiers(mac_modifiers);
        }
        Qt::MouseButtons buttons;
        {
            UInt32 mac_buttons = 0;
            GetEventParameter(event, kEventParamMouseChord, typeUInt32, 0,
                              sizeof(mac_buttons), 0, &mac_buttons);
            buttons = qt_mac_get_buttons(mac_buttons);
        }
        int wheel_delta=0;
        if(ekind == kEventMouseWheelMoved) {
            int mdelt = 0;
            GetEventParameter(event, kEventParamMouseWheelDelta, typeSInt32, 0,
                              sizeof(mdelt), 0, &mdelt);
            wheel_delta = mdelt * 120;
        }

        Qt::MouseButton button = Qt::NoButton;
        if(ekind == kEventMouseDown || ekind == kEventMouseUp) {
            EventMouseButton mac_button = 0;
            GetEventParameter(event, kEventParamMouseButton, typeMouseButton, 0,
                              sizeof(mac_button), 0, &mac_button);
            button = qt_mac_get_button(mac_button);
        }

        switch(ekind) {
        case kEventMouseDown:
            etype = QEvent::MouseButtonPress;
            break;
        case kEventMouseUp:
            etype = QEvent::MouseButtonRelease;
            break;
        case kEventMouseDragged:
        case kEventMouseMoved:
            etype = QEvent::MouseMove;
            break;
        }

        const bool inPopupMode = app->d_func()->inPopupMode();

        // A click outside a popup closes the popup. Make sure
        // that no events are generated for the release part of that click.
        // (The press goes to the popup and closes it.)
        if (etype == QEvent::MouseButtonPress) {
            qt_mac_previous_press_in_popup_mode = inPopupMode;
        } else if (qt_mac_previous_press_in_popup_mode && !inPopupMode && etype == QEvent::MouseButtonRelease) {
            qt_mac_previous_press_in_popup_mode = false;
            handled_event = true;
#if defined(DEBUG_MOUSE_MAPS)
            qDebug("Bail out early due to qt_mac_previous_press_in_popup_mode");
#endif
            break; // break from case kEventClassMouse
        }

        //figure out which widget to send it to
        if(inPopupMode) {
            QWidget *popup = qApp->activePopupWidget();
            if (qt_button_down && qt_button_down->window() == popup) {
                widget = qt_button_down;
            } else {
                QPoint pos = popup->mapFromGlobal(QPoint(where.h, where.v));
                widget = popup->childAt(pos);
            }
            if(!widget)
                widget = popup;
        } else {
            if(mac_mouse_grabber) {
                widget = mac_mouse_grabber;
            } else if (qt_button_down) {
                widget = qt_button_down;
            } else {
                {
                    WindowPtr window = 0;
                    if(GetEventParameter(event, kEventParamWindowRef, typeWindowRef, 0,
                                         sizeof(window), 0, &window) != noErr)
                        FindWindowOfClass(&where, kAllWindowClasses, &window, 0);
                    if(window) {
                        HIViewRef hiview;
                        if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) {
                            widget = QWidget::find((WId)hiview);;
                            if (widget) {
                                // Make sure we didn't pass over a widget with a "fake hole" in it.
                                QWidget *otherWidget = QApplication::widgetAt(where.h, where.v);
                                if (otherWidget && otherWidget->testAttribute(Qt::WA_MouseNoMask))
                                    widget = otherWidget;
                            }
                        }
                    }
                }
                if(!widget) //fallback
                    widget = QApplication::widgetAt(where.h, where.v);
                if(ekind == kEventMouseUp && widget) {
                    short part = qt_mac_window_at(where.h, where.v);
                    if(part == inDrag) {
                        UInt32 count = 0;
                        GetEventParameter(event, kEventParamClickCount, typeUInt32, NULL,
                                          sizeof(count), NULL, &count);
                        if(count == 2 && qt_mac_collapse_on_dblclick) {
                            if (widget->macEvent(er, event))
                                return noErr;
                            widget->setWindowState(widget->windowState() | Qt::WindowMinimized);
                            //we send a hide to be like X11/Windows
                            QEvent e(QEvent::Hide);
                            QApplication::sendSpontaneousEvent(widget, &e);
                            break;
                        }
                    }
                }
            }
        }
        if (widget && widget->macEvent(er, event))
            return noErr;
        WindowPartCode wpc = qt_mac_window_at(where.h, where.v, 0);
        if (wpc == inProxyIcon && modifiers == Qt::ControlModifier && buttons != Qt::NoButton) {
            QIconDragEvent e;
            QApplication::sendSpontaneousEvent(widget, &e);
            if (e.isAccepted()) {
                return noErr; // IconDrag ate it.
            }
        }
        if (inPopupMode == false
                && (qt_button_down == 0 || qt_button_down_in_content == false)
                && (wpc != inContent && wpc != inStructure)) {
            inNonClientArea = true;
            switch (etype) {
            case QEvent::MouseButtonPress: {
                UInt32 count = 0;
                GetEventParameter(event, kEventParamClickCount, typeUInt32, 0,
                                      sizeof(count), 0, &count);
                if(count % 2 || count == 0) {
                    etype = QEvent::NonClientAreaMouseButtonPress;
                } else {
                    etype = QEvent::NonClientAreaMouseButtonDblClick;
                }} break;
            case QEvent::MouseButtonRelease:
                etype = QEvent::NonClientAreaMouseButtonRelease;
                break;
            case QEvent::MouseMove:
                if (widget == 0 || widget->hasMouseTracking())
                    etype = QEvent::NonClientAreaMouseMove;
                break;
            default:
                break;
            }
        }

        if(qt_mac_find_window((FrontWindow()))) { //set the cursor up
            QCursor cursor(Qt::ArrowCursor);
            QWidget *cursor_widget = widget;
            if(cursor_widget && cursor_widget == qt_button_down && ekind == kEventMouseUp)
                cursor_widget = QApplication::widgetAt(where.h, where.v);
            if(cursor_widget) { //only over the app, do we set a cursor..
                if(!qApp->d_func()->cursor_list.isEmpty()) {
                    cursor = qApp->d_func()->cursor_list.first();
                } else {
                    for(; cursor_widget; cursor_widget = cursor_widget->parentWidget()) {
                        QWExtra *extra = cursor_widget->d_func()->extraData();
                        if(extra && extra->curs && cursor_widget->isEnabled()) {
                            cursor = *extra->curs;
                            break;
                        }
                    }
                }
            }
            qt_mac_set_cursor(&cursor, QPoint(where.h, where.v));
        }

        //This mouse button state stuff looks like this on purpose
        //although it looks hacky it is VERY intentional..
        if(widget && app_do_modal && !qt_try_modal(widget, event)) {
            if(ekind == kEventMouseDown && qt_mac_is_macsheet(QApplication::activeModalWidget()))
                QApplication::activeModalWidget()->parentWidget()->activateWindow(); //sheets have a parent
            handled_event = false;
#if defined(DEBUG_MOUSE_MAPS)
            qDebug("Bail out early due to qt_try_modal");
#endif
            break;
        }

        UInt32 tabletEventType = 0;
        GetEventParameter(event, kEventParamTabletEventType, typeUInt32, 0,
                          sizeof(tabletEventType), 0, &tabletEventType);
        if (tabletEventType == kEventTabletPoint) {
            TabletPointRec tabletPointRec;
            GetEventParameter(event, kEventParamTabletPointRec, typeTabletPointRec, 0,
                              sizeof(tabletPointRec), 0, &tabletPointRec);
            QEvent::Type t = QEvent::TabletMove; //default
            int new_tablet_button_state = tabletPointRec.buttons ? 1 : 0;
            if (new_tablet_button_state != tablet_button_state)
                if (new_tablet_button_state)
                    t = QEvent::TabletPress;
                else
                    t = QEvent::TabletRelease;
            tablet_button_state = new_tablet_button_state;

            QMacTabletHash *tabletHash = qt_mac_tablet_hash();
            if (!tabletHash->contains(tabletPointRec.deviceID)) {
                qWarning("QCocoaView handleTabletEvent: This tablet device is unknown"
                        " (received no proximity event for it). Discarding event.");
                return false;
            }
            QTabletDeviceData &deviceData = tabletHash->operator[](tabletPointRec.deviceID);
            if (t == QEvent::TabletPress) {
                deviceData.widgetToGetPress = widget;
            } else if (t == QEvent::TabletRelease && deviceData.widgetToGetPress) {
                widget = deviceData.widgetToGetPress;
                deviceData.widgetToGetPress = 0;
            }

            if (widget) {
                int tiltX = ((int)tabletPointRec.tiltX)/(32767/64); // 32K -> 60
                int tiltY = ((int)tabletPointRec.tiltY)/(-32767/64); // 32K -> 60
                HIPoint hiPoint;
                GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, 0, sizeof(HIPoint), 0, &hiPoint);
                QPointF hiRes(hiPoint.x, hiPoint.y);
                QPoint global(where.h, where.v);



                QPoint local(widget->mapFromGlobal(global));
                int z = 0;
                qreal rotation = 0.0;
                qreal tp = 0.0;
                // Again from the Wacom.h header

                if (deviceData.capabilityMask & 0x0200)     // Z-axis
                    z = tabletPointRec.absZ;

                if (deviceData.capabilityMask & 0x0800)  // Tangential pressure
                    tp = tabletPointRec.tangentialPressure / 32767.0;

                if (deviceData.capabilityMask & 0x2000) // Rotation
                    rotation = qreal(tabletPointRec.rotation) / 64.0;

                QTabletEvent e(t, local, global, hiRes, deviceData.tabletDeviceType,
                               deviceData.tabletPointerType,
                               qreal(tabletPointRec.pressure / qreal(0xffff)), tiltX, tiltY,
                               tp, rotation, z, modifiers, deviceData.tabletUniqueID);
                QApplication::sendSpontaneousEvent(widget, &e);
                if (e.isAccepted()) {
#if defined(DEBUG_MOUSE_MAPS)
                    qDebug("Bail out early due to table acceptance");
#endif
                    break;
                }
            }
        }

        if(ekind == kEventMouseDown) {
            qt_mac_no_click_through_mode = false;
            const short windowPart = qt_mac_window_at(where.h, where.v, 0);
            // Menubar almost always wins.
            if (!inPopupMode && windowPart == inMenuBar) {
                MenuSelect(where); //allow menu tracking
                return noErr;
            }

            if (widget && !(GetCurrentKeyModifiers() & cmdKey)) {
                extern bool qt_isGenuineQWidget(const QWidget *); // qwidget_mac.cpp
                QWidget *window = widget->window();
                bool genuineQtWidget = qt_isGenuineQWidget(widget);  // the widget, not the window.
                window->raise();

                bool needActivate = (window->windowType() != Qt::Desktop)
                                     && (window->windowType() != Qt::Popup)
                                     && !qt_mac_is_macsheet(window);
                if (needActivate && (!window->isModal() && qobject_cast<QDockWidget *>(window)))
                    needActivate = false;

                if (genuineQtWidget && needActivate)
                    needActivate = !window->isActiveWindow()
                                    || !IsWindowActive(qt_mac_window_for(window));

                if (needActivate) {
                    window->activateWindow();
                    if (!qt_mac_can_clickThrough(widget)) {
                        qt_mac_no_click_through_mode = true;
                        handled_event = false;
#if defined(DEBUG_MOUSE_MAPS)
                        qDebug("Bail out early due to qt_mac_canClickThrough %s::%s", widget->metaObject()->className(),
                                widget->objectName().toLocal8Bit().constData());
#endif
                        break;
                    }
                }
            }

            if(qt_mac_dblclick.last_widget &&
               qt_mac_dblclick.last_x != -1 && qt_mac_dblclick.last_y != -1 &&
               QRect(qt_mac_dblclick.last_x-2, qt_mac_dblclick.last_y-2, 4, 4).contains(QPoint(where.h, where.v))) {
                if(qt_mac_dblclick.use_qt_time_limit) {
                    EventTime now = GetEventTime(event);
                    if(qt_mac_dblclick.last_time != -2 && qt_mac_dblclick.last_widget == widget &&
                       now - qt_mac_dblclick.last_time <= ((double)QApplicationPrivate::mouse_double_click_time)/1000 &&
                       qt_mac_dblclick.last_button == button)
                        etype = QEvent::MouseButtonDblClick;
                } else {
                    UInt32 count = 0;
                    GetEventParameter(event, kEventParamClickCount, typeUInt32, 0,
                                      sizeof(count), 0, &count);
                    if(!(count % 2) && qt_mac_dblclick.last_modifiers == modifiers &&
                       qt_mac_dblclick.last_widget == widget && qt_mac_dblclick.last_button == button)
                        etype = QEvent::MouseButtonDblClick;
                }
                if(etype == QEvent::MouseButtonDblClick)
                    qt_mac_dblclick.last_widget = 0;
            }
            if(etype != QEvent::MouseButtonDblClick) {
                qt_mac_dblclick.last_x = where.h;
                qt_mac_dblclick.last_y = where.v;
            } else {
                qt_mac_dblclick.last_x = qt_mac_dblclick.last_y = -1;
            }
        } else if(qt_mac_no_click_through_mode) {
            if(ekind == kEventMouseUp)
                qt_mac_no_click_through_mode = false;
            handled_event = false;
#if defined(DEBUG_MOUSE_MAPS)
            qDebug("Bail out early due to qt_mac_no_click_through_mode");
#endif
            break;
        }

        QPointer<QWidget> leaveAfterRelease = 0;
        switch(ekind) {
        case kEventMouseUp:
            if (!buttons) {
                if (!inPopupMode && !QWidget::mouseGrabber())
                    leaveAfterRelease = qt_button_down;
                qt_button_down = 0;
            }
            break;
        case kEventMouseDown: {
            if (!qt_button_down)
                qt_button_down = widget;
            WindowPartCode wpc = qt_mac_window_at(where.h, where.v, 0);
            qt_button_down_in_content = (wpc == inContent || wpc == inStructure);
            break;  }
        }

        // Check if we should send enter/leave events:
        switch(ekind) {
        case kEventMouseDragged:
        case kEventMouseMoved:
        case kEventMouseUp:
        case kEventMouseDown: {
            // If we are in popup mode, widget will point to the current popup no matter
            // where the mouse cursor is. In that case find out if the mouse cursor is
            // really over the popup in order to send correct enter / leave envents.
            QWidget * const enterLeaveWidget = (inPopupMode || ekind == kEventMouseUp) ?
                    QApplication::widgetAt(where.h, where.v) :  static_cast<QWidget*>(widget);

            if ((QWidget *) qt_mouseover != enterLeaveWidget || inNonClientArea) {
#ifdef DEBUG_MOUSE_MAPS
                qDebug("Entering: %p - %s (%s), Leaving %s (%s)", (QWidget*)enterLeaveWidget,
                       enterLeaveWidget ? enterLeaveWidget->metaObject()->className() : "none",
                       enterLeaveWidget ? enterLeaveWidget->objectName().toLocal8Bit().constData() : "",
                       qt_mouseover ? qt_mouseover->metaObject()->className() : "none",
                       qt_mouseover ? qt_mouseover->objectName().toLocal8Bit().constData() : "");
#endif

                QWidget * const mouseGrabber = QWidget::mouseGrabber();

                if (inPopupMode) {
                    QWidget *enter = enterLeaveWidget;
                    QWidget *leave = qt_mouseover;
                    if (mouseGrabber) {
                        QWidget * const popupWidget = qApp->activePopupWidget();
                        if (leave == popupWidget)
                            enter = mouseGrabber;
                        if (enter == popupWidget)
                            leave = mouseGrabber;
                        if ((enter == mouseGrabber && leave == popupWidget)
                            || (leave == mouseGrabber  && enter == popupWidget)) {
                            QApplicationPrivate::dispatchEnterLeave(enter, leave);
                            qt_mouseover = enter;
                        }
                    } else {
                        QApplicationPrivate::dispatchEnterLeave(enter, leave);
                        qt_mouseover = enter;
                    }
                } else if ((!qt_button_down || !qt_mouseover) && !mouseGrabber && !leaveAfterRelease) {
                    QApplicationPrivate::dispatchEnterLeave(enterLeaveWidget, qt_mouseover);
                    qt_mouseover = enterLeaveWidget;
                }
            }
            break; }
        }

        if(widget) {
            QPoint p(where.h, where.v);
            QPoint plocal(widget->mapFromGlobal(p));
            if(etype == QEvent::MouseButtonPress) {
                qt_mac_dblclick.last_widget = widget;
                qt_mac_dblclick.last_modifiers = modifiers;
                qt_mac_dblclick.last_button = button;
                qt_mac_dblclick.last_time = GetEventTime(event);
            }
            if(wheel_delta) {
                EventMouseWheelAxis axis;
                GetEventParameter(event, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0,
                                  sizeof(axis), 0, &axis);
                QWheelEvent qwe(plocal, p, wheel_delta, buttons, modifiers,
                                axis == kEventMouseWheelAxisX ? Qt::Horizontal : Qt::Vertical);
                QApplication::sendSpontaneousEvent(widget, &qwe);
                if(!qwe.isAccepted() && QApplicationPrivate::focus_widget && QApplicationPrivate::focus_widget != widget) {
                    QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(p), p,
                                     wheel_delta, buttons, modifiers,
                                     axis == kEventMouseWheelAxisX ? Qt::Horizontal : Qt::Vertical);
                    QApplication::sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
                    if(!qwe2.isAccepted())
                        handled_event = false;
                }
            } else {
#ifdef QMAC_SPEAK_TO_ME
                const int speak_keys = Qt::AltModifier | Qt::ShiftModifier;
		if(etype == QMouseEvent::MouseButtonDblClick && ((modifiers & speak_keys) == speak_keys)) {
                    QVariant v = widget->property("displayText");
                    if(!v.isValid()) v = widget->property("text");
                    if(!v.isValid()) v = widget->property("windowTitle");
                    if(v.isValid()) {
                        QString s = v.toString();
                        s.replace(QRegExp(QString::fromLatin1("(\\&|\\<[^\\>]*\\>)")), QLatin1String(""));
                        SpeechChannel ch;
                        NewSpeechChannel(0, &ch);
                        SpeakText(ch, s.toLatin1().constData(), s.length());
                        DisposeSpeechChannel(ch);
                    }
                }
#endif
                Qt::MouseButton buttonToSend = button;
                static bool lastButtonTranslated = false;
                if(ekind == kEventMouseDown &&
                   button == Qt::LeftButton && (modifiers & Qt::MetaModifier)) {
                    buttonToSend = Qt::RightButton;
                    lastButtonTranslated = true;
                } else if(ekind == kEventMouseUp && lastButtonTranslated) {
                    buttonToSend = Qt::RightButton;
                    lastButtonTranslated = false;
                }
                QMouseEvent qme(etype, plocal, p, buttonToSend, buttons, modifiers);
                QApplication::sendSpontaneousEvent(widget, &qme);
                if(!qme.isAccepted() || inNonClientArea)
                    handled_event = false;
            }

            if (leaveAfterRelease) {
                QWidget *enter = QApplication::widgetAt(where.h, where.v);
                QApplicationPrivate::dispatchEnterLeave(enter, leaveAfterRelease);
                qt_mouseover = enter;
                leaveAfterRelease = 0;
            }

            if(ekind == kEventMouseDown &&
               ((button == Qt::RightButton) ||
                (button == Qt::LeftButton && (modifiers & Qt::MetaModifier))))
                qt_event_request_context();

#ifdef DEBUG_MOUSE_MAPS
            const char *event_desc = edesc;
            if(etype == QEvent::MouseButtonDblClick)
                event_desc = "Double Click";
            else if(etype == QEvent::NonClientAreaMouseButtonPress)
                event_desc = "NonClientMousePress";
            else if(etype == QEvent::NonClientAreaMouseButtonRelease)
                event_desc = "NonClientMouseRelease";
            else if(etype == QEvent::NonClientAreaMouseMove)
                event_desc = "NonClientMouseMove";
            else if(etype == QEvent::NonClientAreaMouseButtonDblClick)
                event_desc = "NonClientMouseDblClick";
            qDebug("%d %d (%d %d) - Would send (%s) event to %p %s %s (%d 0x%08x 0x%08x %d)", p.x(), p.y(),
                   plocal.x(), plocal.y(), event_desc, (QWidget*)widget,
                   widget ? widget->objectName().toLocal8Bit().constData() : "*Unknown*",
                   widget ? widget->metaObject()->className() : "*Unknown*",
                   button, (int)buttons, (int)modifiers, wheel_delta);
#endif
        } else {
            handled_event = false;
        }
        break;
    }
    case kEventClassTextInput:
    case kEventClassKeyboard: {
        EventRef key_event = event;
        if(eclass == kEventClassTextInput) {
            Q_ASSERT(ekind == kEventTextInputUnicodeForKeyEvent);
            OSStatus err = GetEventParameter(event, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0,
                                             sizeof(key_event), 0, &key_event);
            Q_ASSERT(err == noErr);
            Q_UNUSED(err);
        }
        const UInt32 key_ekind = GetEventKind(key_event);
        Q_ASSERT(GetEventClass(key_event) == kEventClassKeyboard);

        if(key_ekind == kEventRawKeyDown)
            qt_keymapper_private()->updateKeyMap(er, key_event, data);
        if(mac_keyboard_grabber)
            widget = mac_keyboard_grabber;
        else if (app->activePopupWidget())
            widget = (app->activePopupWidget()->focusWidget() ?
                      app->activePopupWidget()->focusWidget() : app->activePopupWidget());
        else if(QApplication::focusWidget())
            widget = QApplication::focusWidget();
        else
            widget = app->activeWindow();

        if (widget) {
            if (widget->macEvent(er, event))
                return noErr;
        } else {
            // Darn, I need to update tho modifier state, even though
            // Qt itself isn't getting them, otherwise the keyboard state get inconsistent.
            if (key_ekind == kEventRawKeyModifiersChanged) {
                UInt32 modifiers = 0;
                GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
                                  sizeof(modifiers), 0, &modifiers);
                extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object); // qkeymapper_mac.cpp
                // Just send it to the qApp for the time being.
                qt_mac_send_modifiers_changed(modifiers, qApp);
            }
            handled_event = false;
            break;
        }

        if(app_do_modal && !qt_try_modal(widget, key_event))
            break;
        if (eclass == kEventClassTextInput) {
            handled_event = false;
        } else {
            handled_event = qt_keymapper_private()->translateKeyEvent(widget, er, key_event, data,
                                                                      widget == mac_keyboard_grabber);
        }
        break; }
    case kEventClassWindow: {
        WindowRef wid = 0;
        GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
                          sizeof(WindowRef), 0, &wid);
        widget = qt_mac_find_window(wid);
        if (widget && widget->macEvent(er, event))
            return noErr;
        if(ekind == kEventWindowActivated) {
            if(QApplicationPrivate::app_style) {
                QEvent ev(QEvent::Style);
                QApplication::sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
            }

            if(widget && app_do_modal && !qt_try_modal(widget, event))
                break;

            if(widget && widget->window()->isVisible()) {
                QWidget *tlw = widget->window();
		if(tlw->isWindow() && !(tlw->windowType() == Qt::Popup)
                   && !qt_mac_is_macdrawer(tlw)
                   && (!tlw->parentWidget() || tlw->isModal()
                       || !(tlw->windowType() == Qt::Tool))) {
                    bool just_send_event = false;
                    {
                        WindowActivationScope scope;
                        if(GetWindowActivationScope((WindowRef)wid, &scope) == noErr &&
                           scope == kWindowActivationScopeIndependent) {
                            if(GetFrontWindowOfClass(kAllWindowClasses, true) != wid)
                                just_send_event = true;
                        }
                    }
                    if(just_send_event) {
                        QEvent e(QEvent::WindowActivate);
                        QApplication::sendSpontaneousEvent(widget, &e);
                    } else {
                        app->setActiveWindow(tlw);
                    }
                }
                QMenuBar::macUpdateMenuBar();
            }
        } else if(ekind == kEventWindowDeactivated) {
            if(widget && QApplicationPrivate::active_window == widget)
                app->setActiveWindow(0);
        } else {
            handled_event = false;
        }
        break; }
    case kEventClassApplication:
        if(ekind == kEventAppActivated) {
            if(QApplication::desktopSettingsAware())
                qt_mac_update_os_settings();
            if(qt_clipboard) { //manufacture an event so the clipboard can see if it has changed
                QEvent ev(QEvent::Clipboard);
                QApplication::sendSpontaneousEvent(qt_clipboard, &ev);
            }
            if(app) {
                QEvent ev(QEvent::ApplicationActivate);
                QApplication::sendSpontaneousEvent(app, &ev);
            }
            if(!app->activeWindow()) {
                WindowPtr wp = ActiveNonFloatingWindow();
                if(QWidget *tmp_w = qt_mac_find_window(wp))
                    app->setActiveWindow(tmp_w);
            }
            QMenuBar::macUpdateMenuBar();
        } else if(ekind == kEventAppDeactivated) {
            //qt_mac_no_click_through_mode = false;
            while(app->d_func()->inPopupMode())
                app->activePopupWidget()->close();
            if(app) {
                QEvent ev(QEvent::ApplicationDeactivate);
                QApplication::sendSpontaneousEvent(app, &ev);
            }
            app->setActiveWindow(0);
        } else if(ekind == kEventAppAvailableWindowBoundsChanged) {
            QDesktopWidgetImplementation::instance()->onResize();
        } else {
            handled_event = false;
        }
        break;
    case kAppearanceEventClass:
        if(ekind == kAEAppearanceChanged) {
            if(QApplication::desktopSettingsAware())
                qt_mac_update_os_settings();
            if(QApplicationPrivate::app_style) {
                QEvent ev(QEvent::Style);
                QApplication::sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
            }
        } else {
            handled_event = false;
        }
        break;
    case kEventClassAppleEvent:
        if(ekind == kEventAppleEvent) {
            EventRecord erec;
            if(!ConvertEventRefToEventRecord(event, &erec))
                qDebug("Qt: internal: WH0A, unexpected condition reached. %s:%d", __FILE__, __LINE__);
            else if(AEProcessAppleEvent(&erec) != noErr)
                handled_event = false;
        } else {
            handled_event = false;
        }
        break;
    case kEventClassCommand:
        if(ekind == kEventCommandProcess) {
            HICommand cmd;
            GetEventParameter(event, kEventParamDirectObject, typeHICommand,
                              0, sizeof(cmd), 0, &cmd);
            handled_event = false;
            if(!cmd.menu.menuRef && GetApplicationDockTileMenu()) {
                EventRef copy = CopyEvent(event);
                HICommand copy_cmd;
                GetEventParameter(event, kEventParamDirectObject, typeHICommand,
                                  0, sizeof(copy_cmd), 0, &copy_cmd);
                copy_cmd.menu.menuRef = GetApplicationDockTileMenu();
                SetEventParameter(copy, kEventParamDirectObject, typeHICommand, sizeof(copy_cmd), &copy_cmd);
                if(SendEventToMenu(copy, copy_cmd.menu.menuRef) == noErr)
                    handled_event = true;
            }
            if(!handled_event) {
                if(cmd.commandID == kHICommandQuit) {
                    handled_event = true;
                    HiliteMenu(0);
                    bool handle_quit = true;
                    if(QApplicationPrivate::modalState()) {
                        int visible = 0;
                        const QWidgetList tlws = QApplication::topLevelWidgets();
                        for(int i = 0; i < tlws.size(); ++i) {
                            if(tlws.at(i)->isVisible())
                                ++visible;
                        }
                        handle_quit = (visible <= 1);
                    }
                    if(handle_quit) {
                        QCloseEvent ev;
                        QApplication::sendSpontaneousEvent(app, &ev);
                        if(ev.isAccepted())
                            app->quit();
                    } else {
                        QApplication::beep();
                    }
                } else if(cmd.commandID == kHICommandSelectWindow) {
                    if((GetCurrentKeyModifiers() & cmdKey))
                        handled_event = true;
                } else if(cmd.commandID == kHICommandAbout) {
                    QMessageBox::aboutQt(0);
                    HiliteMenu(0);
                    handled_event = true;
                }
            }
        }
        break;
    }

#ifdef DEBUG_EVENTS
    qDebug("%shandled event %c%c%c%c %d", handled_event ? "(*) " : "",
           char(eclass >> 24), char((eclass >> 16) & 255), char((eclass >> 8) & 255),
           char(eclass & 255), (int)ekind);
#endif
    if(!handled_event) //let the event go through
        return eventNotHandledErr;
    return noErr; //we eat the event
#else
    Q_UNUSED(er);
    Q_UNUSED(event);
    Q_UNUSED(data);
    return eventNotHandledErr;
#endif
}

// In Carbon this is your one stop for apple events.
// In Cocoa, it ISN'T. This is the catch-all Apple Event handler that exists
// for the time between instantiating the NSApplication, but before the
// NSApplication has installed it's OWN Apple Event handler. When Cocoa has
// that set up, we remove this.  So, if you are debugging problems, you likely
// want to check out QCocoaApplicationDelegate instead.
OSStatus QApplicationPrivate::globalAppleEventProcessor(const AppleEvent *ae, AppleEvent *, long handlerRefcon)
{
    QApplication *app = (QApplication *)handlerRefcon;
    bool handled_event=false;
    OSType aeID=typeWildCard, aeClass=typeWildCard;
    AEGetAttributePtr(ae, keyEventClassAttr, typeType, 0, &aeClass, sizeof(aeClass), 0);
    AEGetAttributePtr(ae, keyEventIDAttr, typeType, 0, &aeID, sizeof(aeID), 0);
    if(aeClass == kCoreEventClass) {
        switch(aeID) {
        case kAEQuitApplication: {
            extern bool qt_mac_quit_menu_item_enabled; // qmenu_mac.cpp
            if(!QApplicationPrivate::modalState() && qt_mac_quit_menu_item_enabled) {
                QCloseEvent ev;
                QApplication::sendSpontaneousEvent(app, &ev);
                if(ev.isAccepted()) {
                    handled_event = true;
                    app->quit();
                }
            } else {
                QApplication::beep();  // Sorry, you can't quit right now.
            }
            break; }
        case kAEOpenDocuments: {
            AEDescList docs;
            if(AEGetParamDesc(ae, keyDirectObject, typeAEList, &docs) == noErr) {
                long cnt = 0;
                AECountItems(&docs, &cnt);
                UInt8 *str_buffer = NULL;
                for(int i = 0; i < cnt; i++) {
                    FSRef ref;
                    if(AEGetNthPtr(&docs, i+1, typeFSRef, 0, 0, &ref, sizeof(ref), 0) != noErr)
                        continue;
                    if(!str_buffer)
                        str_buffer = (UInt8 *)malloc(1024);
                    FSRefMakePath(&ref, str_buffer, 1024);
                    QFileOpenEvent ev(QString::fromUtf8((const char *)str_buffer));
                    QApplication::sendSpontaneousEvent(app, &ev);
                }
                if(str_buffer)
                    free(str_buffer);
            }
            break; }
        default:
            break;
        }
    }
#ifdef DEBUG_EVENTS
    qDebug("Qt: internal: %shandled Apple event! %c%c%c%c %c%c%c%c", handled_event ? "(*)" : "",
           char(aeID >> 24), char((aeID >> 16) & 255), char((aeID >> 8) & 255),char(aeID & 255),
           char(aeClass >> 24), char((aeClass >> 16) & 255), char((aeClass >> 8) & 255),char(aeClass & 255));
#else
    if(!handled_event) //let the event go through
        return eventNotHandledErr;
    return noErr; //we eat the event
#endif
}

/*!
    \fn bool QApplication::macEventFilter(EventHandlerCallRef caller, EventRef event)

    \warning This virtual function is only implemented under Mac OS X when against Carbon.

    If you create an application that inherits QApplication and reimplement
    this function, you get direct access to all Carbon Events that Qt registers
    for from Mac OS X with this function being called with the \a caller and
    the \a event.

    Return true if you want to stop the event from being processed.
    Return false for normal event dispatching. The default
    implementation returns false.

    Cocoa uses a different event system which means this function is NOT CALLED
    when building Qt against Cocoa. If you want similar functionality subclass
    NSApplication and reimplement the sendEvent: message to handle all the
    NSEvents. You also will need to to instantiate your custom NSApplication
    before creating a QApplication. See \l
    {http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/Reference/Reference.html}{Apple's
    NSApplication Reference} for more information.

*/
bool QApplication::macEventFilter(EventHandlerCallRef, EventRef)
{
    return false;
}

/*!
    \internal
*/
void QApplicationPrivate::openPopup(QWidget *popup)
{
    if (!QApplicationPrivate::popupWidgets)                        // create list
        QApplicationPrivate::popupWidgets = new QWidgetList;
    QApplicationPrivate::popupWidgets->append(popup);                // add to end of list

    // popups are not focus-handled by the window system (the first
    // popup grabbed the keyboard), so we have to do that manually: A
    // new popup gets the focus
    if (popup->focusWidget()) {
        popup->focusWidget()->setFocus(Qt::PopupFocusReason);
    } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup
        popup->setFocus(Qt::PopupFocusReason);
    }
}

/*!
    \internal
*/
void QApplicationPrivate::closePopup(QWidget *popup)
{
    Q_Q(QApplication);
    if (!QApplicationPrivate::popupWidgets)
        return;

    QApplicationPrivate::popupWidgets->removeAll(popup);
    if (popup == qt_button_down)
        qt_button_down = 0;
    if (QApplicationPrivate::popupWidgets->isEmpty()) {  // this was the last popup
        delete QApplicationPrivate::popupWidgets;
        QApplicationPrivate::popupWidgets = 0;
        
        // Special case for Tool windows: since they are activated and deactived together
        // with a normal window they never become the QApplicationPrivate::active_window.
        QWidget *appFocusWidget = QApplication::focusWidget();
        if (appFocusWidget && appFocusWidget->window()->windowType() == Qt::Tool) {
            appFocusWidget->setFocus(Qt::PopupFocusReason);
        } else if (QApplicationPrivate::active_window) {
            if (QWidget *fw = QApplicationPrivate::active_window->focusWidget()) {
                if (fw != QApplication::focusWidget()) {
                    fw->setFocus(Qt::PopupFocusReason);
                } else {
                    QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
                    q->sendEvent(fw, &e);
                }
            }
        }
    } else {
        // popups are not focus-handled by the window system (the
        // first popup grabbed the keyboard), so we have to do that
        // manually: A popup was closed, so the previous popup gets
        // the focus.
        QWidget* aw = QApplicationPrivate::popupWidgets->last();
        if (QWidget *fw = aw->focusWidget())
            fw->setFocus(Qt::PopupFocusReason);
    }
}

void QApplication::beep()
{
    qt_mac_beep();
}

void QApplication::alert(QWidget *widget, int duration)
{
    if (!QApplicationPrivate::checkInstance("alert"))
        return;

    QWidgetList windowsToMark;
    if (!widget)
        windowsToMark += topLevelWidgets();
    else
        windowsToMark.append(widget->window());

    bool needNotification = false;
    for (int i = 0; i < windowsToMark.size(); ++i) {
        QWidget *window = windowsToMark.at(i);
        if (!window->isActiveWindow() && window->isVisible()) {
            needNotification = true; // yeah, we may set it multiple times, but that's OK.
            if (duration != 0) {
               QTimer *timer = new QTimer(qApp);
               timer->setSingleShot(true);
               connect(timer, SIGNAL(timeout()), qApp, SLOT(_q_alertTimeOut()));
               if (QTimer *oldTimer = qApp->d_func()->alertTimerHash.value(widget)) {
                   qApp->d_func()->alertTimerHash.remove(widget);
                   delete oldTimer;
               }
               qApp->d_func()->alertTimerHash.insert(widget, timer);
               timer->start(duration);
            }
        }
    }
    if (needNotification)
        qt_mac_send_notification();
}

void QApplicationPrivate::_q_alertTimeOut()
{
    if (QTimer *timer = qobject_cast<QTimer *>(q_func()->sender())) {
        QHash<QWidget *, QTimer *>::iterator it = alertTimerHash.begin();
        while (it != alertTimerHash.end()) {
            if (it.value() == timer) {
                alertTimerHash.erase(it);
                timer->deleteLater();
                break;
            }
            ++it;
        }
        if (alertTimerHash.isEmpty()) {
            qt_mac_cancel_notification();
        }
    }
}

void  QApplication::setCursorFlashTime(int msecs)
{
    QApplicationPrivate::cursor_flash_time = msecs;
}

int QApplication::cursorFlashTime()
{
    return QApplicationPrivate::cursor_flash_time;
}

void QApplication::setDoubleClickInterval(int ms)
{
    qt_mac_dblclick.use_qt_time_limit = true;
    QApplicationPrivate::mouse_double_click_time = ms;
}

int QApplication::doubleClickInterval()
{
    if (!qt_mac_dblclick.use_qt_time_limit) { //get it from the system
        QSettings appleSettings(QLatin1String("apple.com"));
        /* First worked as of 10.3.3 */
        double dci = appleSettings.value(QLatin1String("com/apple/mouse/doubleClickThreshold"), 0.5).toDouble();
        return int(dci * 1000);
    }
    return QApplicationPrivate::mouse_double_click_time;
}

void QApplication::setKeyboardInputInterval(int ms)
{
    QApplicationPrivate::keyboard_input_time = ms;
}

int QApplication::keyboardInputInterval()
{
    // FIXME: get from the system
    return QApplicationPrivate::keyboard_input_time;
}

void QApplication::setWheelScrollLines(int n)
{
    QApplicationPrivate::wheel_scroll_lines = n;
}

int QApplication::wheelScrollLines()
{
    return QApplicationPrivate::wheel_scroll_lines;
}

void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
{
    switch (effect) {
    case Qt::UI_FadeMenu:
        QApplicationPrivate::fade_menu = enable;
        break;
    case Qt::UI_AnimateMenu:
        QApplicationPrivate::animate_menu = enable;
        break;
    case Qt::UI_FadeTooltip:
        QApplicationPrivate::fade_tooltip = enable;
        break;
    case Qt::UI_AnimateTooltip:
        QApplicationPrivate::animate_tooltip = enable;
        break;
    case Qt::UI_AnimateCombo:
        QApplicationPrivate::animate_combo = enable;
        break;
    case Qt::UI_AnimateToolBox:
        QApplicationPrivate::animate_toolbox = enable;
        break;
    case Qt::UI_General:
        QApplicationPrivate::fade_tooltip = true;
        break;
    default:
        QApplicationPrivate::animate_ui = enable;
        break;
    }

    if (enable)
        QApplicationPrivate::animate_ui = true;
}

bool QApplication::isEffectEnabled(Qt::UIEffect effect)
{
    if (QColormap::instance().depth() < 16 || !QApplicationPrivate::animate_ui)
        return false;

    switch(effect) {
    case Qt::UI_AnimateMenu:
        return QApplicationPrivate::animate_menu;
    case Qt::UI_FadeMenu:
        return QApplicationPrivate::fade_menu;
    case Qt::UI_AnimateCombo:
        return QApplicationPrivate::animate_combo;
    case Qt::UI_AnimateTooltip:
        return QApplicationPrivate::animate_tooltip;
    case Qt::UI_FadeTooltip:
        return QApplicationPrivate::fade_tooltip;
    case Qt::UI_AnimateToolBox:
        return QApplicationPrivate::animate_toolbox;
    default:
        break;
    }
    return QApplicationPrivate::animate_ui;
}

/*!
    \internal
*/
bool QApplicationPrivate::qt_mac_apply_settings()
{
    QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
    settings.beginGroup(QLatin1String("Qt"));

    /*
      Qt settings.  This is how they are written into the datastream.
      Palette/ *             - QPalette
      font                   - QFont
      libraryPath            - QStringList
      style                  - QString
      doubleClickInterval    - int
      cursorFlashTime        - int
      wheelScrollLines       - int
      colorSpec              - QString
      defaultCodec           - QString
      globalStrut/width      - int
      globalStrut/height     - int
      GUIEffects             - QStringList
      Font Substitutions/ *  - QStringList
      Font Substitutions/... - QStringList
    */

    // read library (ie. plugin) path list
    QString libpathkey =
        QString::fromLatin1("%1.%2/libraryPath")
                    .arg(QT_VERSION >> 16)
                    .arg((QT_VERSION & 0xff00) >> 8);
    QStringList pathlist = settings.value(libpathkey).toString().split(QLatin1Char(':'));
    if (!pathlist.isEmpty()) {
        QStringList::ConstIterator it = pathlist.begin();
        while(it != pathlist.end())
            QApplication::addLibraryPath(*it++);
    }

    QString defaultcodec = settings.value(QLatin1String("defaultCodec"), QVariant(QLatin1String("none"))).toString();
    if (defaultcodec != QLatin1String("none")) {
        QTextCodec *codec = QTextCodec::codecForName(defaultcodec.toLatin1().constData());
        if (codec)
            QTextCodec::setCodecForTr(codec);
    }

    if (qt_is_gui_used) {
        QString str;
        QStringList strlist;
        int num;

        // read new palette
        int i;
        QPalette pal(QApplication::palette());
        strlist = settings.value(QLatin1String("Palette/active")).toStringList();
        if (strlist.count() == QPalette::NColorRoles) {
            for (i = 0; i < QPalette::NColorRoles; i++)
                pal.setColor(QPalette::Active, (QPalette::ColorRole) i,
                            QColor(strlist[i]));
        }
        strlist = settings.value(QLatin1String("Palette/inactive")).toStringList();
        if (strlist.count() == QPalette::NColorRoles) {
            for (i = 0; i < QPalette::NColorRoles; i++)
                pal.setColor(QPalette::Inactive, (QPalette::ColorRole) i,
                            QColor(strlist[i]));
        }
        strlist = settings.value(QLatin1String("Palette/disabled")).toStringList();
        if (strlist.count() == QPalette::NColorRoles) {
            for (i = 0; i < QPalette::NColorRoles; i++)
                pal.setColor(QPalette::Disabled, (QPalette::ColorRole) i,
                            QColor(strlist[i]));
        }

        if (pal != QApplication::palette())
            QApplication::setPalette(pal);

        // read new font
        QFont font(QApplication::font());
        str = settings.value(QLatin1String("font")).toString();
        if (!str.isEmpty()) {
            font.fromString(str);
            if (font != QApplication::font())
                QApplication::setFont(font);
        }

        // read new QStyle
        QString stylename = settings.value(QLatin1String("style")).toString();
        if (! stylename.isNull() && ! stylename.isEmpty()) {
            QStyle *style = QStyleFactory::create(stylename);
            if (style)
                QApplication::setStyle(style);
            else
                stylename = QLatin1String("default");
        } else {
            stylename = QLatin1String("default");
        }

        num = settings.value(QLatin1String("doubleClickInterval"),
                            QApplication::doubleClickInterval()).toInt();
        QApplication::setDoubleClickInterval(num);

        num = settings.value(QLatin1String("cursorFlashTime"),
                            QApplication::cursorFlashTime()).toInt();
        QApplication::setCursorFlashTime(num);

        num = settings.value(QLatin1String("wheelScrollLines"),
                            QApplication::wheelScrollLines()).toInt();
        QApplication::setWheelScrollLines(num);

        QString colorspec = settings.value(QLatin1String("colorSpec"),
                                            QVariant(QLatin1String("default"))).toString();
        if (colorspec == QLatin1String("normal"))
            QApplication::setColorSpec(QApplication::NormalColor);
        else if (colorspec == QLatin1String("custom"))
            QApplication::setColorSpec(QApplication::CustomColor);
        else if (colorspec == QLatin1String("many"))
            QApplication::setColorSpec(QApplication::ManyColor);
        else if (colorspec != QLatin1String("default"))
            colorspec = QLatin1String("default");

        int w = settings.value(QLatin1String("globalStrut/width")).toInt();
        int h = settings.value(QLatin1String("globalStrut/height")).toInt();
        QSize strut(w, h);
        if (strut.isValid())
            QApplication::setGlobalStrut(strut);

        QStringList effects = settings.value(QLatin1String("GUIEffects")).toStringList();
        if (!effects.isEmpty()) {
            if (effects.contains(QLatin1String("none")))
                QApplication::setEffectEnabled(Qt::UI_General, false);
            if (effects.contains(QLatin1String("general")))
                QApplication::setEffectEnabled(Qt::UI_General, true);
            if (effects.contains(QLatin1String("animatemenu")))
                QApplication::setEffectEnabled(Qt::UI_AnimateMenu, true);
            if (effects.contains(QLatin1String("fademenu")))
                QApplication::setEffectEnabled(Qt::UI_FadeMenu, true);
            if (effects.contains(QLatin1String("animatecombo")))
                QApplication::setEffectEnabled(Qt::UI_AnimateCombo, true);
            if (effects.contains(QLatin1String("animatetooltip")))
                QApplication::setEffectEnabled(Qt::UI_AnimateTooltip, true);
            if (effects.contains(QLatin1String("fadetooltip")))
                QApplication::setEffectEnabled(Qt::UI_FadeTooltip, true);
            if (effects.contains(QLatin1String("animatetoolbox")))
                QApplication::setEffectEnabled(Qt::UI_AnimateToolBox, true);
        } else {
            QApplication::setEffectEnabled(Qt::UI_General, true);
        }

        settings.beginGroup(QLatin1String("Font Substitutions"));
        QStringList fontsubs = settings.childKeys();
        if (!fontsubs.isEmpty()) {
            QStringList::Iterator it = fontsubs.begin();
            for (; it != fontsubs.end(); ++it) {
                QString fam = QString::fromLatin1((*it).toLatin1().constData());
                QStringList subs = settings.value(fam).toStringList();
                QFont::insertSubstitutions(fam, subs);
            }
        }
        settings.endGroup();
    }

    settings.endGroup();
    return true;
}

// DRSWAT

bool QApplicationPrivate::canQuit()
{
#ifndef QT_MAC_USE_COCOA
    return true;
#else
    Q_Q(QApplication);
#ifdef QT_MAC_USE_COCOA
    [[NSApp mainMenu] cancelTracking];
#else
    HiliteMenu(0);
#endif

    bool handle_quit = true;
    if (QApplicationPrivate::modalState() && [[[[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate]
                                                   menuLoader] quitMenuItem] isEnabled]) {
        int visible = 0;
        const QWidgetList tlws = QApplication::topLevelWidgets();
        for(int i = 0; i < tlws.size(); ++i) {
            if (tlws.at(i)->isVisible())
                ++visible;
        }
        handle_quit = (visible <= 1);
    }
    if (handle_quit) {
        QCloseEvent ev;
        QApplication::sendSpontaneousEvent(q, &ev);
        if (ev.isAccepted()) {
            return true;
        }
    }
    return false;
#endif
}

void onApplicationWindowChangedActivation(QWidget *widget, bool activated)
{
#if QT_MAC_USE_COCOA
    if (!widget)
        return;

    if (activated) {
        if (QApplicationPrivate::app_style) {
            QEvent ev(QEvent::Style);
            qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
        }
        qApp->setActiveWindow(widget);
    } else { // deactivated
        if (QApplicationPrivate::active_window == widget)
            qApp->setActiveWindow(0);
    }

    QMenuBar::macUpdateMenuBar();

#else
    Q_UNUSED(widget);
    Q_UNUSED(activated);
#endif
}


void onApplicationChangedActivation( bool activated )
{
#if QT_MAC_USE_COCOA
    QApplication    *app    = qApp;

//NSLog(@"App Changed Activation\n");

    if ( activated ) {
        if (QApplication::desktopSettingsAware())
            qt_mac_update_os_settings();

        if (qt_clipboard) { //manufacture an event so the clipboard can see if it has changed
            QEvent ev(QEvent::Clipboard);
            qt_sendSpontaneousEvent(qt_clipboard, &ev);
        }

        if (app) {
            QEvent ev(QEvent::ApplicationActivate);
            qt_sendSpontaneousEvent(app, &ev);
        }

        if (!app->activeWindow()) {
#if QT_MAC_USE_COCOA
            OSWindowRef wp    = [NSApp keyWindow];
#else
            OSWindowRef wp = ActiveNonFloatingWindow();
#endif
            if (QWidget *tmp_w = qt_mac_find_window(wp))
                app->setActiveWindow(tmp_w);
        }
        QMenuBar::macUpdateMenuBar();
    } else { // de-activated
        QApplicationPrivate *priv = [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] qAppPrivate];
        while (priv->inPopupMode())
            app->activePopupWidget()->close();
        if (app) {
            QEvent ev(QEvent::ApplicationDeactivate);
            qt_sendSpontaneousEvent(app, &ev);
        }
        app->setActiveWindow(0);
    }
#else
    Q_UNUSED(activated);
#endif
}

QT_END_NAMESPACE