summaryrefslogtreecommitdiff
path: root/video/cocoa_v.m
blob: 71065cd25aa8ea866a773ebaaea263314623021c (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
/* $Id$ */

/******************************************************************************
 *                             Cocoa video driver                             *
 * Known things left to do:                                                   *
 *  Nothing at the moment.                                                    *
 ******************************************************************************/

#ifdef WITH_COCOA

#import <Cocoa/Cocoa.h>
#import <sys/time.h> /* gettimeofday */
#import <sys/param.h> /* for MAXPATHLEN */
#import <unistd.h>

/* Portions of CPS.h */
typedef struct CPSProcessSerNum {
	UInt32 lo;
	UInt32 hi;
} CPSProcessSerNum;

extern OSErr CPSGetCurrentProcess(CPSProcessSerNum* psn);
extern OSErr CPSEnableForegroundOperation(CPSProcessSerNum* psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess(CPSProcessSerNum* psn);

/* From Menus.h (according to Xcode Developer Documentation) */
extern void ShowMenuBar(void);
extern void HideMenuBar(void);

/* Disables a warning. This is needed since the method exists but has been dropped from the header, supposedly as of 10.4. */
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
@interface NSApplication(NSAppleMenu)
- (void)setAppleMenu:(NSMenu *)menu;
@end
#endif


/* Defined in ppc/param.h or i386/param.h included from sys/param.h */
#undef ALIGN
/* Defined in stdbool.h */
#ifndef __cplusplus
# ifndef __BEOS__
#  undef bool
#  undef false
#  undef true
# endif
#endif

#include "../stdafx.h"
#include "../openttd.h"
#include "../debug.h"
#include "../functions.h"
#include "../gfx.h"
#include "../macros.h"
#include "../sdl.h"
#include "../window.h"
#include "../network.h"
#include "../variables.h"
#include "../os/macosx/splash.h"

#include "cocoa_v.h"
#include "cocoa_keys.h"

#undef Point
#undef Rect


/* Subclass of NSWindow to fix genie effect and support resize events  */
@interface OTTD_QuartzWindow : NSWindow
- (void)miniaturize:(id)sender;
- (void)display;
- (void)setFrame:(NSRect)frameRect display:(BOOL)flag;
- (void)appDidHide:(NSNotification*)note;
- (void)appWillUnhide:(NSNotification*)note;
- (void)appDidUnhide:(NSNotification*)note;
- (id)initWithContentRect:(NSRect)contentRect styleMask:(unsigned int)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag;
@end

/* Delegate for our NSWindow to send ask for quit on close */
@interface OTTD_QuartzWindowDelegate : NSObject
- (BOOL)windowShouldClose:(id)sender;
@end

@interface OTTDMain : NSObject
@end


/* Structure for rez switch gamma fades
 * We can hide the monitor flicker by setting the gamma tables to 0
 */
#define QZ_GAMMA_TABLE_SIZE 256

typedef struct {
	CGGammaValue red[QZ_GAMMA_TABLE_SIZE];
	CGGammaValue green[QZ_GAMMA_TABLE_SIZE];
	CGGammaValue blue[QZ_GAMMA_TABLE_SIZE];
} OTTD_QuartzGammaTable;

/* Add methods to get at private members of NSScreen.
 * Since there is a bug in Apple's screen switching code that does not update
 * this variable when switching to fullscreen, we'll set it manually (but only
 * for the main screen).
 */
@interface NSScreen (NSScreenAccess)
	- (void) setFrame:(NSRect)frame;
@end

@implementation NSScreen (NSScreenAccess)
- (void) setFrame:(NSRect)frame;
{
	_frame = frame;
}
@end


static void QZ_Draw(void);
static void QZ_UnsetVideoMode(void);
static void QZ_UpdatePalette(uint start, uint count);
static void QZ_WarpCursor(int x, int y);
static void QZ_ShowMouse(void);
static void QZ_HideMouse(void);
static void CocoaVideoFullScreen(bool full_screen);


static NSAutoreleasePool *_ottd_autorelease_pool;
static OTTDMain *_ottd_main;


static struct CocoaVideoData {
	bool isset;
	bool issetting;

	CGDirectDisplayID  display_id;         /* 0 == main display (only support single display) */
	CFDictionaryRef    mode;               /* current mode of the display */
	CFDictionaryRef    save_mode;          /* original mode of the display */
	CFArrayRef         mode_list;          /* list of available fullscreen modes */
	CGDirectPaletteRef palette;            /* palette of an 8-bit display */

	uint32 device_width;
	uint32 device_height;
	uint32 device_bpp;

	void *realpixels;
	uint8 *pixels;
	uint32 width;
	uint32 height;
	uint32 pitch;
	bool fullscreen;

	unsigned int current_mods;
	bool tab_is_down;
	bool emulating_right_button;

	bool cursor_visible;
	bool active;

#ifdef _DEBUG
	uint32 tEvent;
#endif

	OTTD_QuartzWindow *window;
	NSQuickDrawView *qdview;

#define MAX_DIRTY_RECTS 100
	OTTDRect dirty_rects[MAX_DIRTY_RECTS];
	int num_dirty_rects;

	uint16 palette16[256];
	uint32 palette32[256];
} _cocoa_video_data;

static bool _cocoa_video_started = false;
static bool _cocoa_video_dialog = false;




/******************************************************************************
 *                             Game loop and accessories                      *
 ******************************************************************************/

static uint32 GetTick(void)
{
	struct timeval tim;

	gettimeofday(&tim, NULL);
	return tim.tv_usec / 1000 + tim.tv_sec * 1000;
}

static void QZ_CheckPaletteAnim(void)
{
	if (_pal_last_dirty != -1) {
		QZ_UpdatePalette(_pal_first_dirty, _pal_last_dirty - _pal_first_dirty + 1);
		_pal_last_dirty = -1;
	}
}



extern void DoExitSave(void);

static void QZ_AskQuit(void)
{
	if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
		_exit_game = true;
	} else if (_patches.autosave_on_exit) {
		DoExitSave();
		_exit_game = true;
	} else {
		AskExitGame();
	}
}



typedef struct VkMapping {
	unsigned short vk_from;
	byte map_to;
} VkMapping;

#define AS(x, z) {x, z}

static const VkMapping _vk_mapping[] = {
	AS(QZ_BACKQUOTE,  WKC_BACKQUOTE), // key left of '1'
	AS(QZ_BACKQUOTE2, WKC_BACKQUOTE), // some keyboards have it on another scancode

	// Pageup stuff + up/down
	//AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),  <==== Does this include HOME/END?
	AS(QZ_PAGEUP,   WKC_PAGEUP),
	AS(QZ_PAGEDOWN, WKC_PAGEDOWN),

	AS(QZ_UP,    WKC_UP),
	AS(QZ_DOWN,  WKC_DOWN),
	AS(QZ_LEFT,  WKC_LEFT),
	AS(QZ_RIGHT, WKC_RIGHT),

	AS(QZ_HOME, WKC_HOME),
	AS(QZ_END,  WKC_END),

	AS(QZ_INSERT, WKC_INSERT),
	AS(QZ_DELETE, WKC_DELETE),

	// Letters. QZ_[a-z] is not in numerical order so we can't use AM(...)
	AS(QZ_a, 'A'),
	AS(QZ_b, 'B'),
	AS(QZ_c, 'C'),
	AS(QZ_d, 'D'),
	AS(QZ_e, 'E'),
	AS(QZ_f, 'F'),
	AS(QZ_g, 'G'),
	AS(QZ_h, 'H'),
	AS(QZ_i, 'I'),
	AS(QZ_j, 'J'),
	AS(QZ_k, 'K'),
	AS(QZ_l, 'L'),
	AS(QZ_m, 'M'),
	AS(QZ_n, 'N'),
	AS(QZ_o, 'O'),
	AS(QZ_p, 'P'),
	AS(QZ_q, 'Q'),
	AS(QZ_r, 'R'),
	AS(QZ_s, 'S'),
	AS(QZ_t, 'T'),
	AS(QZ_u, 'U'),
	AS(QZ_v, 'V'),
	AS(QZ_w, 'W'),
	AS(QZ_x, 'X'),
	AS(QZ_y, 'Y'),
	AS(QZ_z, 'Z'),
	// Same thing for digits
	AS(QZ_0, '0'),
	AS(QZ_1, '1'),
	AS(QZ_2, '2'),
	AS(QZ_3, '3'),
	AS(QZ_4, '4'),
	AS(QZ_5, '5'),
	AS(QZ_6, '6'),
	AS(QZ_7, '7'),
	AS(QZ_8, '8'),
	AS(QZ_9, '9'),

	AS(QZ_ESCAPE,    WKC_ESC),
	AS(QZ_PAUSE,     WKC_PAUSE),
	AS(QZ_BACKSPACE, WKC_BACKSPACE),

	AS(QZ_SPACE,  WKC_SPACE),
	AS(QZ_RETURN, WKC_RETURN),
	AS(QZ_TAB,    WKC_TAB),

	// Function keys
	AS(QZ_F1,  WKC_F1),
	AS(QZ_F2,  WKC_F2),
	AS(QZ_F3,  WKC_F3),
	AS(QZ_F4,  WKC_F4),
	AS(QZ_F5,  WKC_F5),
	AS(QZ_F6,  WKC_F6),
	AS(QZ_F7,  WKC_F7),
	AS(QZ_F8,  WKC_F8),
	AS(QZ_F9,  WKC_F9),
	AS(QZ_F10, WKC_F10),
	AS(QZ_F11, WKC_F11),
	AS(QZ_F12, WKC_F12),

	// Numeric part.
	AS(QZ_KP0,         WKC_NUM_0),
	AS(QZ_KP1,         WKC_NUM_1),
	AS(QZ_KP2,         WKC_NUM_2),
	AS(QZ_KP3,         WKC_NUM_3),
	AS(QZ_KP4,         WKC_NUM_4),
	AS(QZ_KP5,         WKC_NUM_5),
	AS(QZ_KP6,         WKC_NUM_6),
	AS(QZ_KP7,         WKC_NUM_7),
	AS(QZ_KP8,         WKC_NUM_8),
	AS(QZ_KP9,         WKC_NUM_9),
	AS(QZ_KP_DIVIDE,   WKC_NUM_DIV),
	AS(QZ_KP_MULTIPLY, WKC_NUM_MUL),
	AS(QZ_KP_MINUS,    WKC_NUM_MINUS),
	AS(QZ_KP_PLUS,     WKC_NUM_PLUS),
	AS(QZ_KP_ENTER,    WKC_NUM_ENTER),
	AS(QZ_KP_PERIOD,   WKC_NUM_DECIMAL)
};


static uint32 QZ_MapKey(unsigned short sym)
{
	const VkMapping *map;
	uint32 key = 0;

	for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
		if (sym == map->vk_from) {
			key = map->map_to;
			break;
		}
	}

	if (_cocoa_video_data.current_mods & NSShiftKeyMask)     key |= WKC_SHIFT;
	if (_cocoa_video_data.current_mods & NSControlKeyMask)   key |= WKC_CTRL;
	if (_cocoa_video_data.current_mods & NSAlternateKeyMask) key |= WKC_ALT;
	if (_cocoa_video_data.current_mods & NSCommandKeyMask)   key |= WKC_META;

	return key << 16;
}

static void QZ_KeyEvent(unsigned short keycode, unsigned short unicode, BOOL down)
{
	switch (keycode) {
		case QZ_UP:    SB(_dirkeys, 1, 1, down); break;
		case QZ_DOWN:  SB(_dirkeys, 3, 1, down); break;
		case QZ_LEFT:  SB(_dirkeys, 0, 1, down); break;
		case QZ_RIGHT: SB(_dirkeys, 2, 1, down); break;

		case QZ_TAB: _cocoa_video_data.tab_is_down = down; break;

		case QZ_RETURN:
		case QZ_f:
			if (down && (
						(_cocoa_video_data.current_mods & NSControlKeyMask) ||
						(_cocoa_video_data.current_mods & NSCommandKeyMask)
					)) {
				CocoaVideoFullScreen(!_fullscreen);
			}
			break;
	}

	if (down) {
		_pressed_key = QZ_MapKey(keycode) | unicode;
		DEBUG(driver, 2)("cocoa_v: QZ_KeyEvent: %x (%x), down, mapping: %x", keycode, unicode, _pressed_key);
	} else {
		DEBUG(driver, 2)("cocoa_v: QZ_KeyEvent: %x (%x), up", keycode, unicode);
	}
}

static void QZ_DoUnsidedModifiers(unsigned int newMods)
{
	const int mapping[] = { QZ_CAPSLOCK, QZ_LSHIFT, QZ_LCTRL, QZ_LALT, QZ_LMETA };

	int i;
	int bit;

	if (_cocoa_video_data.current_mods == newMods) return;

	/* Iterate through the bits, testing each against the current modifiers */
	for (i = 0, bit = NSAlphaShiftKeyMask; bit <= NSCommandKeyMask; bit <<= 1, ++i) {
		unsigned int currentMask, newMask;

		currentMask = _cocoa_video_data.current_mods & bit;
		newMask     = newMods & bit;

		if (currentMask && currentMask != newMask) { /* modifier up event */
			/* If this was Caps Lock, we need some additional voodoo to make SDL happy (is this needed in ottd?) */
			if (bit == NSAlphaShiftKeyMask) QZ_KeyEvent(mapping[i], 0, YES);
			QZ_KeyEvent(mapping[i], 0, NO);
		} else if (newMask && currentMask != newMask) { /* modifier down event */
			QZ_KeyEvent(mapping[i], 0, YES);
			/* If this was Caps Lock, we need some additional voodoo to make SDL happy (is this needed in ottd?) */
			if (bit == NSAlphaShiftKeyMask) QZ_KeyEvent(mapping[i], 0, NO);
		}
	}

	_cocoa_video_data.current_mods = newMods;
}

static void QZ_MouseMovedEvent(int x, int y)
{
	if (_cursor.fix_at) {
		int dx = x - _cursor.pos.x;
		int dy = y - _cursor.pos.y;

		if (dx != 0 || dy != 0) {
			_cursor.delta.x += dx;
			_cursor.delta.y += dy;

			QZ_WarpCursor(_cursor.pos.x, _cursor.pos.y);
		}
	} else {
		_cursor.delta.x = x - _cursor.pos.x;
		_cursor.delta.y = y - _cursor.pos.y;
		_cursor.pos.x = x;
		_cursor.pos.y = y;
		_cursor.dirty = true;
	}
}

void QZ_MouseButtonEvent(int button, BOOL down)
{
	switch (button) {
		case 0:
			if (down) {
				_left_button_down = true;
			} else {
				_left_button_down = false;
				_left_button_clicked = false;
			}
			break;

		case 1:
			if (down) {
				_right_button_down = true;
				_right_button_clicked = true;
			} else {
				_right_button_down = false;
			}
			break;
	}
}


static inline NSPoint QZ_GetMouseLocation(NSEvent *event)
{
	NSPoint pt;

	if (_cocoa_video_data.fullscreen) {
		pt = [ NSEvent mouseLocation ];
		pt.y = _cocoa_video_data.height - pt.y;
	} else {
		pt = [event locationInWindow];
		pt = [_cocoa_video_data.qdview convertPoint:pt fromView:nil];
	}

	return pt;
}

static bool QZ_MouseIsInsideView(NSPoint *pt)
{
	if (_cocoa_video_data.fullscreen) {
		return pt->x >= 0 && pt->y >= 0 && pt->x < _cocoa_video_data.width && pt->y < _cocoa_video_data.height;
	} else {
		return [ _cocoa_video_data.qdview mouse:*pt inRect:[ _cocoa_video_data.qdview bounds ] ];
	}
}


static bool QZ_PollEvent(void)
{
	NSEvent *event;
	NSPoint pt;
	NSString *chars;
#ifdef _DEBUG
	uint32 et0, et;
#endif

#ifdef _DEBUG
	et0 = GetTick();
#endif
	event = [ NSApp nextEventMatchingMask:NSAnyEventMask
			untilDate: [ NSDate distantPast ]
			inMode: NSDefaultRunLoopMode dequeue:YES ];
#ifdef _DEBUG
	et = GetTick();
	_cocoa_video_data.tEvent+= et - et0;
#endif

	if (event == nil) return false;
	if (!_cocoa_video_data.active) {
		QZ_ShowMouse();
		[NSApp sendEvent:event];
		return true;
	}

	QZ_DoUnsidedModifiers( [ event modifierFlags ] );

	switch ([event type]) {
		case NSMouseMoved:
		case NSOtherMouseDragged:
		case NSRightMouseDragged:
		case NSLeftMouseDragged:
			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt) &&
					!_cocoa_video_data.emulating_right_button) {
				QZ_ShowMouse();
				[NSApp sendEvent:event];
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);
			break;

		case NSLeftMouseDown:
			if (!([ event modifierFlags ] & NSCommandKeyMask) ||
					!QZ_MouseIsInsideView(&pt)) {
				[NSApp sendEvent:event];
			}

			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt)) {
				QZ_ShowMouse();
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);

			/* Right mouse button emulation */
			if ([ event modifierFlags ] & NSCommandKeyMask) {
				_cocoa_video_data.emulating_right_button = true;
				QZ_MouseButtonEvent(1, YES);
			} else {
				QZ_MouseButtonEvent(0, YES);
			}
			break;

		case NSLeftMouseUp:
			[NSApp sendEvent:event];

			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt)) {
				QZ_ShowMouse();
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);

			/* Right mouse button emulation */
			if (_cocoa_video_data.emulating_right_button) {
				_cocoa_video_data.emulating_right_button = false;
				QZ_MouseButtonEvent(1, NO);
			} else {
				QZ_MouseButtonEvent(0, NO);
			}
			break;

		case NSRightMouseDown:
			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt)) {
				QZ_ShowMouse();
				[NSApp sendEvent:event];
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);
			QZ_MouseButtonEvent(1, YES);
			break;

		case NSRightMouseUp:
			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt)) {
				QZ_ShowMouse();
				[NSApp sendEvent:event];
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);
			QZ_MouseButtonEvent(1, NO);
			break;

#if 0
		/* This is not needed since openttd currently only use two buttons */
		case NSOtherMouseDown:
			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt)) {
				QZ_ShowMouse();
				[NSApp sendEvent:event];
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);
			QZ_MouseButtonEvent([ event buttonNumber ], YES);
			break;

		case NSOtherMouseUp:
			pt = QZ_GetMouseLocation(event);
			if (!QZ_MouseIsInsideView(&pt)) {
				QZ_ShowMouse();
				[NSApp sendEvent:event];
				break;
			}

			QZ_HideMouse();
			QZ_MouseMovedEvent((int)pt.x, (int)pt.y);
			QZ_MouseButtonEvent([ event buttonNumber ], NO);
			break;
#endif

		case NSKeyDown:
			/* Quit, hide and minimize */
			switch ([event keyCode]) {
				case QZ_q:
				case QZ_h:
				case QZ_m:
					if ([ event modifierFlags ] & NSCommandKeyMask) {
						[NSApp sendEvent:event];
					}
					break;
			}

			chars = [ event characters ];
			QZ_KeyEvent([event keyCode], [ chars length ] ? [ chars characterAtIndex:0 ] : 0, YES);
			break;

		case NSKeyUp:
			/* Quit, hide and minimize */
			switch ([event keyCode]) {
				case QZ_q:
				case QZ_h:
				case QZ_m:
					if ([ event modifierFlags ] & NSCommandKeyMask) {
						[NSApp sendEvent:event];
					}
					break;
			}

			chars = [ event characters ];
			QZ_KeyEvent([event keyCode], [ chars length ] ? [ chars characterAtIndex:0 ] : 0, NO);
			break;

		case NSScrollWheel:
			if ([ event deltaX ] > 0.0 || [ event deltaY ] > 0.0) { /* Scroll up */
				_cursor.wheel--;
			} else { /* Scroll down */
				_cursor.wheel++;
			}
			break;

		default:
			[NSApp sendEvent:event];
	}

	return true;
}




static void QZ_GameLoop(void)
{
	uint32 next_tick = GetTick() + 30;
	uint32 cur_ticks;
	uint32 pal_tick = 0;
#ifdef _DEBUG
	uint32 et0, et, st0, st;
#endif
	int i;

	DEBUG(driver, 1)("cocoa_v: QZ_GameLoop");

#ifdef _DEBUG
	et0 = GetTick();
	st = 0;
#endif

	_screen.dst_ptr = _cocoa_video_data.pixels;
	DisplaySplashImage();
	QZ_CheckPaletteAnim();
	QZ_Draw();
	CSleep(1);

	for (i = 0; i < 2; i++) GameLoop();

	_screen.dst_ptr = _cocoa_video_data.pixels;
	UpdateWindows();
	QZ_CheckPaletteAnim();
	QZ_Draw();
	CSleep(1);

	for (;;) {
		InteractiveRandom(); // randomness

		while (QZ_PollEvent()) {}

		if (_exit_game) break;

#if defined(_DEBUG)
		if (_cocoa_video_data.current_mods & NSShiftKeyMask)
#else
		if (_cocoa_video_data.tab_is_down)
#endif
		{
			if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
		} else if (_fast_forward & 2) {
			_fast_forward = 0;
		}

		cur_ticks = GetTick();
		if ((_fast_forward && !_pause) || cur_ticks > next_tick)
			next_tick = cur_ticks;

		if (cur_ticks == next_tick) {
			next_tick += 30;

			_ctrl_pressed = !!(_cocoa_video_data.current_mods & NSControlKeyMask);
			_shift_pressed = !!(_cocoa_video_data.current_mods & NSShiftKeyMask);
#ifdef _DEBUG
			_dbg_screen_rect = !!(_cocoa_video_data.current_mods & NSAlphaShiftKeyMask);
#endif

			GameLoop();

			_screen.dst_ptr = _cocoa_video_data.pixels;
			UpdateWindows();
			if (++pal_tick > 4) {
				QZ_CheckPaletteAnim();
				pal_tick = 1;
			}
			QZ_Draw();
		} else {
#ifdef _DEBUG
			st0 = GetTick();
#endif
			CSleep(1);
#ifdef _DEBUG
			st += GetTick() - st0;
#endif
			_screen.dst_ptr = _cocoa_video_data.pixels;
			DrawTextMessage();
			DrawMouseCursor();
			QZ_Draw();
		}
	}

#ifdef _DEBUG
	et = GetTick();

	DEBUG(driver, 1)("cocoa_v: nextEventMatchingMask took %i ms total", _cocoa_video_data.tEvent);
	DEBUG(driver, 1)("cocoa_v: game loop took %i ms total (%i ms without sleep)", et - et0, et - et0 - st);
	DEBUG(driver, 1)("cocoa_v: (nextEventMatchingMask total)/(game loop total) is %f%%", (double)_cocoa_video_data.tEvent / (double)(et - et0) * 100);
	DEBUG(driver, 1)("cocoa_v: (nextEventMatchingMask total)/(game loop without sleep total) is %f%%", (double)_cocoa_video_data.tEvent / (double)(et - et0 - st) * 100);
#endif
}


/******************************************************************************
 *                             Windowed mode                                  *
 ******************************************************************************/

/* This function makes the *game region* of the window 100% opaque.
 * The genie effect uses the alpha component. Otherwise,
 * it doesn't seem to matter what value it has.
 */
static void QZ_SetPortAlphaOpaque(void)
{
	if (_cocoa_video_data.device_bpp == 32) {
		uint32* pixels = (uint32*)_cocoa_video_data.realpixels;
		uint32 rowPixels = _cocoa_video_data.pitch / 4;
		uint32 i;
		uint32 j;

		for (i = 0; i < _cocoa_video_data.height; i++)
			for (j = 0; j < _cocoa_video_data.width; j++) {
			pixels[i * rowPixels + j] |= 0xFF000000;
		}
	}
}


@implementation OTTD_QuartzWindow

/* we override these methods to fix the miniaturize animation/dock icon bug */
- (void)miniaturize:(id)sender
{
	/* make the alpha channel opaque so anim won't have holes in it */
	QZ_SetPortAlphaOpaque ();

	/* window is hidden now */
	_cocoa_video_data.active = false;

	QZ_ShowMouse();

	[ super miniaturize:sender ];
}

- (void)display
{
	/* This method fires just before the window deminaturizes from the Dock.
	 * We'll save the current visible surface, let the window manager redraw any
	 * UI elements, and restore the surface. This way, no expose event
	 * is required, and the deminiaturize works perfectly.
	 */

	QZ_SetPortAlphaOpaque();

	/* save current visible surface */
	[ self cacheImageInRect:[ _cocoa_video_data.qdview frame ] ];

	/* let the window manager redraw controls, border, etc */
	[ super display ];

	/* restore visible surface */
	[ self restoreCachedImage ];

	/* window is visible again */
	_cocoa_video_data.active = true;
}

- (void)setFrame:(NSRect)frameRect display:(BOOL)flag
{
	NSRect newViewFrame;
	CGrafPtr thePort;

	[ super setFrame:frameRect display:flag ];

	/* Don't do anything if the window is currently beign created */
	if (_cocoa_video_data.issetting) return;

	if (_cocoa_video_data.window == nil) return;

	newViewFrame = [ _cocoa_video_data.qdview frame ];

	/* Update the pixels and pitch */
	thePort = [ _cocoa_video_data.qdview qdPort ];
	LockPortBits(thePort);

	_cocoa_video_data.realpixels = GetPixBaseAddr(GetPortPixMap(thePort));
	_cocoa_video_data.pitch      = GetPixRowBytes(GetPortPixMap(thePort));

	/* _cocoa_video_data.realpixels now points to the window's pixels
	 * We want it to point to the *view's* pixels
	 */
	{
		int vOffset = [ _cocoa_video_data.window frame ].size.height - newViewFrame.size.height - newViewFrame.origin.y;
		int hOffset = newViewFrame.origin.x;

		_cocoa_video_data.realpixels = (uint8*)_cocoa_video_data.realpixels + (vOffset * _cocoa_video_data.pitch) + hOffset * (_cocoa_video_data.device_bpp / 8);
	}

	UnlockPortBits(thePort);

	/* Allocate new buffer */
	free(_cocoa_video_data.pixels);
	_cocoa_video_data.pixels = (uint8*)malloc(newViewFrame.size.width * newViewFrame.size.height);
	assert(_cocoa_video_data.pixels != NULL);


	/* Tell the game that the resolution changed */
	_cocoa_video_data.width = newViewFrame.size.width;
	_cocoa_video_data.height = newViewFrame.size.height;

	_screen.width = _cocoa_video_data.width;
	_screen.height = _cocoa_video_data.height;
	_screen.pitch = _cocoa_video_data.width;

	GameSizeChanged();

	/* Redraw screen */
	_cocoa_video_data.num_dirty_rects = MAX_DIRTY_RECTS;
}

- (void)appDidHide:(NSNotification*)note
{
	_cocoa_video_data.active = false;
}


- (void)appWillUnhide:(NSNotification*)note
{
	QZ_SetPortAlphaOpaque ();

	/* save current visible surface */
	[ self cacheImageInRect:[ _cocoa_video_data.qdview frame ] ];
}

- (void)appDidUnhide:(NSNotification*)note
{
	/* restore cached image, since it may not be current, post expose event too */
	[ self restoreCachedImage ];

	_cocoa_video_data.active = true;
}


- (id)initWithContentRect:(NSRect)contentRect styleMask:(unsigned int)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag
{
	/* Make our window subclass receive these application notifications */
	[ [ NSNotificationCenter defaultCenter ] addObserver:self
	selector:@selector(appDidHide:) name:NSApplicationDidHideNotification object:NSApp ];

	[ [ NSNotificationCenter defaultCenter ] addObserver:self
	selector:@selector(appDidUnhide:) name:NSApplicationDidUnhideNotification object:NSApp ];

	[ [ NSNotificationCenter defaultCenter ] addObserver:self
	selector:@selector(appWillUnhide:) name:NSApplicationWillUnhideNotification object:NSApp ];

	return [ super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag ];
}

@end

@implementation OTTD_QuartzWindowDelegate
- (BOOL)windowShouldClose:(id)sender
{
	QZ_AskQuit();

	return NO;
}

- (void)windowDidBecomeKey:(NSNotification*)aNotification
{
	_cocoa_video_data.active = true;
}

- (void)windowDidResignKey:(NSNotification*)aNotification
{
	_cocoa_video_data.active = false;
}

- (void)windowDidBecomeMain:(NSNotification*)aNotification
{
	_cocoa_video_data.active = true;
}

- (void)windowDidResignMain:(NSNotification*)aNotification
{
	_cocoa_video_data.active = false;
}

@end


static void QZ_UpdateWindowPalette(uint start, uint count)
{
	uint i;

	switch (_cocoa_video_data.device_bpp) {
		case 32:
			for (i = start; i < start + count; i++) {
				uint32 clr32 = 0xff000000;
				clr32 |= (uint32)_cur_palette[i].r << 16;
				clr32 |= (uint32)_cur_palette[i].g << 8;
				clr32 |= (uint32)_cur_palette[i].b;
				_cocoa_video_data.palette32[i] = clr32;
			}
			break;
		case 16:
			for (i = start; i < start + count; i++) {
				uint16 clr16 = 0x0000;
				clr16 |= (uint16)((_cur_palette[i].r >> 3) & 0x1f) << 10;
				clr16 |= (uint16)((_cur_palette[i].g >> 3) & 0x1f) << 5;
				clr16 |= (uint16)((_cur_palette[i].b >> 3) & 0x1f);
				_cocoa_video_data.palette16[i] = clr16;
			}
			break;
	}

	_cocoa_video_data.num_dirty_rects = MAX_DIRTY_RECTS;
}

static inline void QZ_WindowBlitIndexedPixelsToView32(uint left, uint top, uint right, uint bottom)
{
	const uint32* pal = _cocoa_video_data.palette32;
	const uint8* src = _cocoa_video_data.pixels;
	uint32* dst = (uint32*)_cocoa_video_data.realpixels;
	uint width = _cocoa_video_data.width;
	uint pitch = _cocoa_video_data.pitch / 4;
	uint x;
	uint y;

	for (y = top; y < bottom; y++) {
		for (x = left; x < right; x++) {
			dst[y * pitch + x] = pal[src[y * width + x]];
		}
	}
}

static inline void QZ_WindowBlitIndexedPixelsToView16(uint left, uint top, uint right, uint bottom)
{
	const uint16* pal = _cocoa_video_data.palette16;
	const uint8* src = _cocoa_video_data.pixels;
	uint16* dst = (uint16*)_cocoa_video_data.realpixels;
	uint width = _cocoa_video_data.width;
	uint pitch = _cocoa_video_data.pitch / 2;
	uint x;
	uint y;

	for (y = top; y < bottom; y++) {
		for (x = left; x < right; x++) {
			dst[y * pitch + x] = pal[src[y * width + x]];
		}
	}
}

static inline void QZ_WindowBlitIndexedPixelsToView(int left, int top, int right, int bottom)
{
	switch (_cocoa_video_data.device_bpp) {
		case 32: QZ_WindowBlitIndexedPixelsToView32(left, top, right, bottom); break;
		case 16: QZ_WindowBlitIndexedPixelsToView16(left, top, right, bottom); break;
	}
}

static bool _resize_icon[] = {
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1,
	0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
	0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0,
	0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
	0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1,
	0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
	0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0,
	1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0
};

static void QZ_DrawResizeIcon(void)
{
	int xoff = _cocoa_video_data.width - 16;
	int yoff = _cocoa_video_data.height - 16;
	int x;
	int y;

	for (y = 0; y < 16; y++) {
		uint16* trg16 = (uint16*)_cocoa_video_data.realpixels + (yoff + y) * _cocoa_video_data.pitch / 2 + xoff;
		uint32* trg32 = (uint32*)_cocoa_video_data.realpixels + (yoff + y) * _cocoa_video_data.pitch / 4 + xoff;

		for (x = 0; x < 16; x++, trg16++, trg32++) {
			if (!_resize_icon[y * 16 + x]) continue;

			switch (_cocoa_video_data.device_bpp) {
				case 32: *trg32 = 0xff000000; break;
				case 16: *trg16 = 0x0000;     break;
			}
		}
	}
}

static void QZ_DrawWindow(void)
{
	int i;
	RgnHandle dirty, temp;

	/* Check if we need to do anything */
	if (_cocoa_video_data.num_dirty_rects == 0 ||
			[ _cocoa_video_data.window isMiniaturized ]) {
		return;
	}

	if (_cocoa_video_data.num_dirty_rects >= MAX_DIRTY_RECTS) {
		_cocoa_video_data.num_dirty_rects = 1;
		_cocoa_video_data.dirty_rects[0].left = 0;
		_cocoa_video_data.dirty_rects[0].top = 0;
		_cocoa_video_data.dirty_rects[0].right = _cocoa_video_data.width;
		_cocoa_video_data.dirty_rects[0].bottom = _cocoa_video_data.height;
	}

	dirty = NewRgn();
	temp  = NewRgn();

	SetEmptyRgn(dirty);

	/* Build the region of dirty rectangles */
	for (i = 0; i < _cocoa_video_data.num_dirty_rects; i++) {
		QZ_WindowBlitIndexedPixelsToView(
			_cocoa_video_data.dirty_rects[i].left,
			_cocoa_video_data.dirty_rects[i].top,
			_cocoa_video_data.dirty_rects[i].right,
			_cocoa_video_data.dirty_rects[i].bottom
		);

		MacSetRectRgn(
			temp,
			_cocoa_video_data.dirty_rects[i].left,
			_cocoa_video_data.dirty_rects[i].top,
			_cocoa_video_data.dirty_rects[i].right,
			_cocoa_video_data.dirty_rects[i].bottom
		);
		MacUnionRgn(dirty, temp, dirty);
	}

	QZ_DrawResizeIcon();

	/* Flush the dirty region */
	QDFlushPortBuffer([ _cocoa_video_data.qdview qdPort ], dirty);
	DisposeRgn(dirty);
	DisposeRgn(temp);

	_cocoa_video_data.num_dirty_rects = 0;
}


extern const char _openttd_revision[];

static const char* QZ_SetVideoWindowed(uint width, uint height)
{
	char caption[50];
	NSString *nsscaption;
	unsigned int style;
	NSRect contentRect;
	BOOL isCustom = NO;

	if (width > _cocoa_video_data.device_width)
		width = _cocoa_video_data.device_width;
	if (height > _cocoa_video_data.device_height)
		height = _cocoa_video_data.device_height;

	_cocoa_video_data.width = width;
	_cocoa_video_data.height = height;

	contentRect = NSMakeRect(0, 0, width, height);

	/* Check if we should completely destroy the previous mode
	 * - If it is fullscreen
	 */
	if (_cocoa_video_data.isset && _cocoa_video_data.fullscreen)
		QZ_UnsetVideoMode();

	/* Check if we should recreate the window */
	if (_cocoa_video_data.window == nil) {
		/* Set the window style */
		style = NSTitledWindowMask;
		style |= (NSMiniaturizableWindowMask | NSClosableWindowMask);
		style |= NSResizableWindowMask;

		/* Manually create a window, avoids having a nib file resource */
		_cocoa_video_data.window = [ [ OTTD_QuartzWindow alloc ]
										initWithContentRect:contentRect
										styleMask:style
										backing:NSBackingStoreBuffered
										defer:NO ];

		if (_cocoa_video_data.window == nil)
			return "Could not create the Cocoa window";

		snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
		nsscaption = [ [ NSString alloc ] initWithCString:caption ];
		[ _cocoa_video_data.window setTitle:nsscaption ];
		[ _cocoa_video_data.window setMiniwindowTitle:nsscaption ];
		[ nsscaption release ];

		[ _cocoa_video_data.window setAcceptsMouseMovedEvents:YES ];
		[ _cocoa_video_data.window setViewsNeedDisplay:NO ];

		[ _cocoa_video_data.window setDelegate: [ [ [ OTTD_QuartzWindowDelegate alloc ] init ] autorelease ] ];
	} else {
		/* We already have a window, just change its size */
		if (!isCustom) {
			[ _cocoa_video_data.window setContentSize:contentRect.size ];
			[ _cocoa_video_data.qdview setFrameSize:contentRect.size ];
		}
	}

	[ _cocoa_video_data.window center ];

	/* Only recreate the view if it doesn't already exist */
	if (_cocoa_video_data.qdview == nil) {
		_cocoa_video_data.qdview = [ [ NSQuickDrawView alloc ] initWithFrame:contentRect ];
		[ _cocoa_video_data.qdview setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
		[ [ _cocoa_video_data.window contentView ] addSubview:_cocoa_video_data.qdview ];
		[ _cocoa_video_data.qdview release ];
		[ _cocoa_video_data.window makeKeyAndOrderFront:nil ];
	}

	LockPortBits([ _cocoa_video_data.qdview qdPort ]);
	_cocoa_video_data.realpixels = GetPixBaseAddr(GetPortPixMap([ _cocoa_video_data.qdview qdPort ]));
	_cocoa_video_data.pitch = GetPixRowBytes(GetPortPixMap([ _cocoa_video_data.qdview qdPort ]));
	UnlockPortBits([ _cocoa_video_data.qdview qdPort ]);

	/* _cocoa_video_data.realpixels now points to the window's pixels
	 * We want it to point to the *view's* pixels
	*/
	{
		int vOffset = [ _cocoa_video_data.window frame ].size.height - [ _cocoa_video_data.qdview frame ].size.height - [ _cocoa_video_data.qdview frame ].origin.y;
		int hOffset = [ _cocoa_video_data.qdview frame ].origin.x;

		_cocoa_video_data.realpixels = (uint8*)_cocoa_video_data.realpixels + (vOffset * _cocoa_video_data.pitch) + hOffset * (_cocoa_video_data.device_bpp / 8);
	}

	free(_cocoa_video_data.pixels);
	_cocoa_video_data.pixels = (uint8*)malloc(width * height);
	if (_cocoa_video_data.pixels == NULL) return "Failed to allocate 8-bit buffer";

	_cocoa_video_data.fullscreen = false;

	return NULL;
}


/******************************************************************************
 *                             Fullscreen mode                                *
 ******************************************************************************/

/* Gamma functions to try to hide the flash from a rez switch
 * Fade the display from normal to black
 * Save gamma tables for fade back to normal
 */
static uint32 QZ_FadeGammaOut(OTTD_QuartzGammaTable* table)
{
	CGGammaValue redTable[QZ_GAMMA_TABLE_SIZE];
	CGGammaValue greenTable[QZ_GAMMA_TABLE_SIZE];
	CGGammaValue blueTable[QZ_GAMMA_TABLE_SIZE];
	float percent;
	int j;
	unsigned int actual;

	if (CGGetDisplayTransferByTable(
				_cocoa_video_data.display_id, QZ_GAMMA_TABLE_SIZE,
				table->red, table->green, table->blue, &actual
			) != CGDisplayNoErr ||
			actual != QZ_GAMMA_TABLE_SIZE) {
		return 1;
	}

	memcpy(redTable,   table->red,   sizeof(redTable));
	memcpy(greenTable, table->green, sizeof(greenTable));
	memcpy(blueTable,  table->blue,  sizeof(greenTable));

	for (percent = 1.0; percent >= 0.0; percent -= 0.01) {
		for (j = 0; j < QZ_GAMMA_TABLE_SIZE; j++) {
			redTable[j]   = redTable[j]   * percent;
			greenTable[j] = greenTable[j] * percent;
			blueTable[j]  = blueTable[j]  * percent;
		}

		if (CGSetDisplayTransferByTable(
					_cocoa_video_data.display_id, QZ_GAMMA_TABLE_SIZE,
					redTable, greenTable, blueTable
				) != CGDisplayNoErr) {
			CGDisplayRestoreColorSyncSettings();
			return 1;
		}

		CSleep(10);
	}

	return 0;
}

/* Fade the display from black to normal
 * Restore previously saved gamma values
 */
static uint32 QZ_FadeGammaIn(const OTTD_QuartzGammaTable* table)
{
	CGGammaValue redTable[QZ_GAMMA_TABLE_SIZE];
	CGGammaValue greenTable[QZ_GAMMA_TABLE_SIZE];
	CGGammaValue blueTable[QZ_GAMMA_TABLE_SIZE];
	float percent;
	int j;

	memset(redTable, 0, sizeof(redTable));
	memset(greenTable, 0, sizeof(greenTable));
	memset(blueTable, 0, sizeof(greenTable));

	for (percent = 0.0; percent <= 1.0; percent += 0.01) {
		for (j = 0; j < QZ_GAMMA_TABLE_SIZE; j++) {
			redTable[j]   = table->red[j]   * percent;
			greenTable[j] = table->green[j] * percent;
			blueTable[j]  = table->blue[j]  * percent;
		}

		if (CGSetDisplayTransferByTable(
					_cocoa_video_data.display_id, QZ_GAMMA_TABLE_SIZE,
					redTable, greenTable, blueTable
				) != CGDisplayNoErr) {
			CGDisplayRestoreColorSyncSettings();
			return 1;
		}

		CSleep(10);
	}

	return 0;
}

static const char* QZ_SetVideoFullScreen(int width, int height)
{
	const char* errstr = "QZ_SetVideoFullScreen error";
	int exact_match;
	CFNumberRef number;
	int bpp;
	int gamma_error;
	OTTD_QuartzGammaTable gamma_table;
	NSRect screen_rect;
	CGError error;
	NSPoint pt;

	/* Destroy any previous mode */
	if (_cocoa_video_data.isset) QZ_UnsetVideoMode();

	/* See if requested mode exists */
	_cocoa_video_data.mode = CGDisplayBestModeForParameters(_cocoa_video_data.display_id, 8, width, height, &exact_match);

	/* If the mode wasn't an exact match, check if it has the right bpp, and update width and height */
	if (!exact_match) {
		number = CFDictionaryGetValue (_cocoa_video_data.mode, kCGDisplayBitsPerPixel);
		CFNumberGetValue(number, kCFNumberSInt32Type, &bpp);
		if (bpp != 8) {
			errstr = "Failed to find display resolution";
			goto ERR_NO_MATCH;
		}

		number = CFDictionaryGetValue(_cocoa_video_data.mode, kCGDisplayWidth);
		CFNumberGetValue(number, kCFNumberSInt32Type, &width);

		number = CFDictionaryGetValue(_cocoa_video_data.mode, kCGDisplayHeight);
		CFNumberGetValue(number, kCFNumberSInt32Type, &height);
	}

	/* Fade display to zero gamma */
	gamma_error = QZ_FadeGammaOut(&gamma_table);

	/* Put up the blanking window (a window above all other windows) */
	error = CGDisplayCapture(_cocoa_video_data.display_id);

	if (CGDisplayNoErr != error) {
		errstr = "Failed capturing display";
		goto ERR_NO_CAPTURE;
	}

	/* Do the physical switch */
	if (CGDisplaySwitchToMode(_cocoa_video_data.display_id, _cocoa_video_data.mode) != CGDisplayNoErr) {
		errstr = "Failed switching display resolution";
		goto ERR_NO_SWITCH;
	}

	_cocoa_video_data.realpixels = (uint8*)CGDisplayBaseAddress(_cocoa_video_data.display_id);
	_cocoa_video_data.pitch  = CGDisplayBytesPerRow(_cocoa_video_data.display_id);

	_cocoa_video_data.width = CGDisplayPixelsWide(_cocoa_video_data.display_id);
	_cocoa_video_data.height = CGDisplayPixelsHigh(_cocoa_video_data.display_id);
	_cocoa_video_data.fullscreen = true;

	/* Setup double-buffer emulation */
	_cocoa_video_data.pixels = (uint8*)malloc(width * height);
	if (_cocoa_video_data.pixels == NULL) {
		errstr = "Failed to allocate memory for double buffering";
		goto ERR_DOUBLEBUF;
	}

	if (!CGDisplayCanSetPalette(_cocoa_video_data.display_id)) {
		errstr = "Not an indexed display mode.";
		goto ERR_NOT_INDEXED;
	}

	/* If we don't hide menu bar, it will get events and interrupt the program */
	HideMenuBar();

	/* Fade the display to original gamma */
	if (!gamma_error) QZ_FadeGammaIn(&gamma_table);

	/* There is a bug in Cocoa where NSScreen doesn't synchronize
	 * with CGDirectDisplay, so the main screen's frame is wrong.
	 * As a result, coordinate translation produces incorrect results.
	 * We can hack around this bug by setting the screen rect ourselves.
	 * This hack should be removed if/when the bug is fixed.
	 */
	screen_rect = NSMakeRect(0, 0, width, height);
	[ [ NSScreen mainScreen ] setFrame:screen_rect ];

	/* we're fullscreen, so flag all input states... */
	_cocoa_video_data.active = true;


	pt = [ NSEvent mouseLocation ];
	pt.y = CGDisplayPixelsHigh(_cocoa_video_data.display_id) - pt.y;
	if (QZ_MouseIsInsideView(&pt)) QZ_HideMouse();

	return NULL;

/* Since the blanking window covers *all* windows (even force quit) correct recovery is crucial */
ERR_NOT_INDEXED:
	free(_cocoa_video_data.pixels);
	_cocoa_video_data.pixels = NULL;
ERR_DOUBLEBUF:
	CGDisplaySwitchToMode(_cocoa_video_data.display_id, _cocoa_video_data.save_mode);
ERR_NO_SWITCH:
	CGReleaseAllDisplays();
ERR_NO_CAPTURE:
	if (!gamma_error) QZ_FadeGammaIn(&gamma_table);
ERR_NO_MATCH:
	return errstr;
}


static void QZ_UpdateFullscreenPalette(uint first_color, uint num_colors)
{
	CGTableCount  index;
	CGDeviceColor color;

	for (index = first_color; index < first_color+num_colors; index++) {
		/* Clamp colors between 0.0 and 1.0 */
		color.red   = _cur_palette[index].r / 255.0;
		color.blue  = _cur_palette[index].b / 255.0;
		color.green = _cur_palette[index].g / 255.0;

		CGPaletteSetColorAtIndex(_cocoa_video_data.palette, color, index);
	}

	CGDisplaySetPalette(_cocoa_video_data.display_id, _cocoa_video_data.palette);
}

/* Wait for the VBL to occur (estimated since we don't have a hardware interrupt) */
static void QZ_WaitForVerticalBlank(void)
{
	/* The VBL delay is based on Ian Ollmann's RezLib <iano@cco.caltech.edu> */
	double refreshRate;
	double linesPerSecond;
	double target;
	double position;
	double adjustment;
	CFNumberRef refreshRateCFNumber;

	refreshRateCFNumber = CFDictionaryGetValue(_cocoa_video_data.mode, kCGDisplayRefreshRate);
	if (refreshRateCFNumber == NULL) return;

	if (CFNumberGetValue(refreshRateCFNumber, kCFNumberDoubleType, &refreshRate) == 0)
		return;

	if (refreshRate == 0) return;

	linesPerSecond = refreshRate * _cocoa_video_data.height;
	target = _cocoa_video_data.height;

	/* Figure out the first delay so we start off about right */
	position = CGDisplayBeamPosition(_cocoa_video_data.display_id);
	if (position > target) position = 0;

	adjustment = (target - position) / linesPerSecond;

	CSleep((uint32)(adjustment * 1000));
}

static void QZ_DrawScreen(void)
{
	const uint8* src;
	uint8* dst;
	uint height;
	uint width;
	uint pitch;
	uint y;

	src = _cocoa_video_data.pixels;
	dst = (uint8*)_cocoa_video_data.realpixels;
	width  = _cocoa_video_data.width;
	pitch  = _cocoa_video_data.pitch;

#ifdef __POWERPC__
	// PPC appears to handle updating of rectangles right
	{
		uint num_dirty_rects;
		uint length_drawn;
		uint left;
		uint i;

		num_dirty_rects = _cocoa_video_data.num_dirty_rects;

		/* Check if we need to do anything */
		if (num_dirty_rects == 0 ) return;

		if (num_dirty_rects >= MAX_DIRTY_RECTS) {
			num_dirty_rects = 1;
			_cocoa_video_data.dirty_rects[0].left = 0;
			_cocoa_video_data.dirty_rects[0].top = 0;
			_cocoa_video_data.dirty_rects[0].right = _cocoa_video_data.width;
			_cocoa_video_data.dirty_rects[0].bottom = _cocoa_video_data.height;
		}

		QZ_WaitForVerticalBlank();
		/* Build the region of dirty rectangles */
		for (i = 0; i < num_dirty_rects; i++) {

			y = _cocoa_video_data.dirty_rects[i].top;
			left = _cocoa_video_data.dirty_rects[i].left;
			length_drawn = _cocoa_video_data.dirty_rects[i].right - left + 1;
			height = _cocoa_video_data.dirty_rects[i].bottom;
			for (; y <= height; y++) memcpy(dst + y * pitch + left, src + y * width +left, length_drawn);
		}

		_cocoa_video_data.num_dirty_rects = 0;
	}
#else
	// it appears that Intel based macs didn't like to only update parts of the screen at a time, so they still update everything at each frame
	// we need to switch to use Quartz exclusively (no QuickDraw commands at all) to fix this
	// to use Quartz exclusively, we should use 16 or 32 bit graphics since 8 bit coloured graphic support sucks
	height  = _cocoa_video_data.height;
	QZ_WaitForVerticalBlank();
	for (y = 0; y < height; y++) memcpy(dst + y * pitch, src + y * width, width);
#endif
}

static int QZ_ListFullscreenModes(OTTDPoint* mode_list, int max_modes)
{
	CFIndex num_modes;
	CFIndex i;
	int list_size = 0;

	num_modes = CFArrayGetCount(_cocoa_video_data.mode_list);

	/* Build list of modes with the requested bpp */
	for (i = 0; i < num_modes && list_size < max_modes; i++) {
		CFDictionaryRef onemode;
		CFNumberRef     number;
		int bpp;
		int intvalue;
		bool hasMode;
		uint16 width, height;

		onemode = CFArrayGetValueAtIndex(_cocoa_video_data.mode_list, i);
		number = CFDictionaryGetValue(onemode, kCGDisplayBitsPerPixel);
		CFNumberGetValue (number, kCFNumberSInt32Type, &bpp);

		if (bpp != 8) continue;

		number = CFDictionaryGetValue(onemode, kCGDisplayWidth);
		CFNumberGetValue(number, kCFNumberSInt32Type, &intvalue);
		width = (uint16)intvalue;

		number = CFDictionaryGetValue(onemode, kCGDisplayHeight);
		CFNumberGetValue(number, kCFNumberSInt32Type, &intvalue);
		height = (uint16)intvalue;

		/* Check if mode is already in the list */
		{
			int i;
			hasMode = false;
			for (i = 0; i < list_size; i++) {
				if (mode_list[i].x == width &&  mode_list[i].y == height) {
					hasMode = true;
					break;
				}
			}
		}

		if (hasMode) continue;

		/* Add mode to the list */
		mode_list[list_size].x = width;
		mode_list[list_size].y = height;
		list_size++;
	}

	/* Sort list smallest to largest */
	{
		int i, j;
		for (i = 0; i < list_size; i++) {
			for (j = 0; j < list_size-1; j++) {
				if (mode_list[j].x > mode_list[j + 1].x || (
							mode_list[j].x == mode_list[j + 1].x &&
							mode_list[j].y >  mode_list[j + 1].y
						)) {
					uint tmpw = mode_list[j].x;
					uint tmph = mode_list[j].y;

					mode_list[j].x = mode_list[j + 1].x;
					mode_list[j].y = mode_list[j + 1].y;

					mode_list[j + 1].x = tmpw;
					mode_list[j + 1].y = tmph;
				}
			}
		}
	}

	return list_size;
}


/******************************************************************************
 *                             Windowed and fullscreen common code            *
 ******************************************************************************/

static void QZ_UpdatePalette(uint start, uint count)
{
	if (_cocoa_video_data.fullscreen) {
		QZ_UpdateFullscreenPalette(start, count);
	} else {
		QZ_UpdateWindowPalette(start, count);
	}
}

static void QZ_InitPalette(void)
{
	QZ_UpdatePalette(0, 256);
}

static void QZ_Draw(void)
{
	if (_cocoa_video_data.fullscreen) {
		QZ_DrawScreen();
	} else {
		QZ_DrawWindow();
	}
}


static const OTTDPoint _default_resolutions[] = {
	{ 640,  480},
	{ 800,  600},
	{1024,  768},
	{1152,  864},
	{1280,  800},
	{1280,  960},
	{1280, 1024},
	{1400, 1050},
	{1600, 1200},
	{1680, 1050},
	{1920, 1200}
};

static void QZ_UpdateVideoModes(void)
{
	uint i, j, count;
	OTTDPoint modes[32];
	const OTTDPoint *current_modes;

	if (_cocoa_video_data.fullscreen) {
		count = QZ_ListFullscreenModes(modes, 32);
		current_modes = modes;
	} else {
		count = lengthof(_default_resolutions);
		current_modes = _default_resolutions;
	}

	for (i = 0, j = 0; j < lengthof(_resolutions) && i < count; i++) {
		if (_cocoa_video_data.fullscreen || (
					(uint)current_modes[i].x <= _cocoa_video_data.device_width &&
					(uint)current_modes[i].y <= _cocoa_video_data.device_height)
				) {
			_resolutions[j][0] = current_modes[i].x;
			_resolutions[j][1] = current_modes[i].y;
			j++;
		}
	}

	_num_resolutions = j;
}

static void QZ_UnsetVideoMode(void)
{
	if (_cocoa_video_data.fullscreen) {
		/* Release fullscreen resources */
		OTTD_QuartzGammaTable gamma_table;
		int gamma_error;
		NSRect screen_rect;

		gamma_error = QZ_FadeGammaOut(&gamma_table);

		/* Restore original screen resolution/bpp */
		CGDisplaySwitchToMode(_cocoa_video_data.display_id, _cocoa_video_data.save_mode);
		CGReleaseAllDisplays();
		ShowMenuBar();
		/* Reset the main screen's rectangle
		 * See comment in QZ_SetVideoFullscreen for why we do this
		 */
		screen_rect = NSMakeRect(0,0,_cocoa_video_data.device_width,_cocoa_video_data.device_height);
		[ [ NSScreen mainScreen ] setFrame:screen_rect ];

		if (!gamma_error) QZ_FadeGammaIn(&gamma_table);
	} else {
		/* Release window mode resources */
		[ _cocoa_video_data.window close ];
		_cocoa_video_data.window = nil;
		_cocoa_video_data.qdview = nil;
	}

	free(_cocoa_video_data.pixels);
	_cocoa_video_data.pixels = NULL;

	QZ_ShowMouse();

	/* Signal successful teardown */
	_cocoa_video_data.isset = false;
}


static const char* QZ_SetVideoMode(uint width, uint height, bool fullscreen)
{
	const char *ret;

	_cocoa_video_data.issetting = true;
	if (fullscreen) {
		/* Setup full screen video */
		ret = QZ_SetVideoFullScreen(width, height);
	} else {
		/* Setup windowed video */
		ret = QZ_SetVideoWindowed(width, height);
	}
	_cocoa_video_data.issetting = false;
	if (ret != NULL) return ret;

	/* Signal successful completion (used internally) */
	_cocoa_video_data.isset = true;

	/* Tell the game that the resolution has changed */
	_screen.width = _cocoa_video_data.width;
	_screen.height = _cocoa_video_data.height;
	_screen.pitch = _cocoa_video_data.width;

	QZ_UpdateVideoModes();
	GameSizeChanged();

	QZ_InitPalette();

	return NULL;
}

static const char* QZ_SetVideoModeAndRestoreOnFailure(uint width, uint height, bool fullscreen)
{
	bool wasset = _cocoa_video_data.isset;
	uint32 oldwidth = _cocoa_video_data.width;
	uint32 oldheight = _cocoa_video_data.height;
	bool oldfullscreen = _cocoa_video_data.fullscreen;
	const char *ret;

	ret = QZ_SetVideoMode(width, height, fullscreen);
	if (ret != NULL && wasset) QZ_SetVideoMode(oldwidth, oldheight, oldfullscreen);

	return ret;
}

static void QZ_VideoInit(void)
{
	memset(&_cocoa_video_data, 0, sizeof(_cocoa_video_data));

	/* Initialize the video settings; this data persists between mode switches */
	_cocoa_video_data.display_id = kCGDirectMainDisplay;
	_cocoa_video_data.save_mode  = CGDisplayCurrentMode(_cocoa_video_data.display_id);
	_cocoa_video_data.mode_list  = CGDisplayAvailableModes(_cocoa_video_data.display_id);
	_cocoa_video_data.palette    = CGPaletteCreateDefaultColorPalette();

	/* Gather some information that is useful to know about the display */
	/* Maybe this should be moved to QZ_SetVideoMode, in case this is changed after startup */
	CFNumberGetValue(
		CFDictionaryGetValue(_cocoa_video_data.save_mode, kCGDisplayBitsPerPixel),
		kCFNumberSInt32Type, &_cocoa_video_data.device_bpp
	);

	CFNumberGetValue(
		CFDictionaryGetValue(_cocoa_video_data.save_mode, kCGDisplayWidth),
		kCFNumberSInt32Type, &_cocoa_video_data.device_width
	);

	CFNumberGetValue(
		CFDictionaryGetValue(_cocoa_video_data.save_mode, kCGDisplayHeight),
		kCFNumberSInt32Type, &_cocoa_video_data.device_height
	);

	_cocoa_video_data.cursor_visible = true;

	/* register for sleep notifications so wake from sleep generates SDL_VIDEOEXPOSE */
//	QZ_RegisterForSleepNotifications();
}


/* Convert local coordinate to window server (CoreGraphics) coordinate */
static CGPoint QZ_PrivateLocalToCG(NSPoint* p)
{
	CGPoint cgp;

	if (!_cocoa_video_data.fullscreen) {
		*p = [ _cocoa_video_data.qdview convertPoint:*p toView: nil ];
		*p = [ _cocoa_video_data.window convertBaseToScreen:*p ];
		p->y = _cocoa_video_data.device_height - p->y;
	}

	cgp.x = p->x;
	cgp.y = p->y;

	return cgp;
}

static void QZ_WarpCursor(int x, int y)
{
	NSPoint p;
	CGPoint cgp;

	/* Only allow warping when in foreground */
	if (![ NSApp isActive ]) return;

	p = NSMakePoint(x, y);
	cgp = QZ_PrivateLocalToCG(&p);

	/* this is the magic call that fixes cursor "freezing" after warp */
	CGSetLocalEventsSuppressionInterval(0.0);
	/* Do the actual warp */
	CGWarpMouseCursorPosition(cgp);

	/* Generate the mouse moved event */
}

static void QZ_ShowMouse(void)
{
	if (!_cocoa_video_data.cursor_visible) {
		[ NSCursor unhide ];
		_cocoa_video_data.cursor_visible = true;
	}
}

static void QZ_HideMouse(void)
{
	if (_cocoa_video_data.cursor_visible) {
#ifndef _DEBUG
		[ NSCursor hide ];
#endif
		_cocoa_video_data.cursor_visible = false;
	}
}


/******************************************************************************
 *                             OS X application creation                      *
 ******************************************************************************/

/* The main class of the application, the application's delegate */
@implementation OTTDMain
/* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification*) note
{
	/* Hand off to main application code */
	QZ_GameLoop();

	/* We're done, thank you for playing */
	[ NSApp stop:_ottd_main ];
}

/* Display the in game quit confirmation dialog */
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*) sender
{

	QZ_AskQuit();

	return NSTerminateCancel;		// NSTerminateLater ?
}
@end

static void setApplicationMenu(void)
{
	/* warning: this code is very odd */
	NSMenu *appleMenu;
	NSMenuItem *menuItem;
	NSString *title;
	NSString *appName;

	appName = @"OTTD";
	appleMenu = [[NSMenu alloc] initWithTitle:appName];

	/* Add menu items */
	title = [@"About " stringByAppendingString:appName];
	[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];

	[appleMenu addItem:[NSMenuItem separatorItem]];

	title = [@"Hide " stringByAppendingString:appName];
	[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];

	menuItem = (NSMenuItem*)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
	[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];

	[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];

	[appleMenu addItem:[NSMenuItem separatorItem]];

	title = [@"Quit " stringByAppendingString:appName];
	[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];


	/* Put menu into the menubar */
	menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
	[menuItem setSubmenu:appleMenu];
	[[NSApp mainMenu] addItem:menuItem];

	/* Tell the application object that this is now the application menu */
	[NSApp setAppleMenu:appleMenu];

	/* Finally give up our references to the objects */
	[appleMenu release];
	[menuItem release];
}

/* Create a window menu */
static void setupWindowMenu(void)
{
	NSMenu* windowMenu;
	NSMenuItem* windowMenuItem;
	NSMenuItem* menuItem;

	windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];

	/* "Minimize" item */
	menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
	[windowMenu addItem:menuItem];
	[menuItem release];

	/* Put menu into the menubar */
	windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
	[windowMenuItem setSubmenu:windowMenu];
	[[NSApp mainMenu] addItem:windowMenuItem];

	/* Tell the application object that this is now the window menu */
	[NSApp setWindowsMenu:windowMenu];

	/* Finally give up our references to the objects */
	[windowMenu release];
	[windowMenuItem release];
}

static void setupApplication(void)
{
	CPSProcessSerNum PSN;

	/* Ensure the application object is initialised */
	[NSApplication sharedApplication];

	/* Tell the dock about us */
	if (!CPSGetCurrentProcess(&PSN) &&
			!CPSEnableForegroundOperation(&PSN, 0x03, 0x3C, 0x2C, 0x1103) &&
			!CPSSetFrontProcess(&PSN)) {
		[NSApplication sharedApplication];
	}

	/* Set up the menubar */
	[NSApp setMainMenu:[[NSMenu alloc] init]];
	setApplicationMenu();
	setupWindowMenu();

	/* Create OTTDMain and make it the app delegate */
	_ottd_main = [[OTTDMain alloc] init];
	[NSApp setDelegate:_ottd_main];
}


/******************************************************************************
 *                             Video driver interface                         *
 ******************************************************************************/

static void CocoaVideoStop(void)
{
	DEBUG(driver, 1)("cocoa_v: CocoaVideoStop");

	if (!_cocoa_video_started) return;

	if (_cocoa_video_data.isset) QZ_UnsetVideoMode();

	[_ottd_main release];

	_cocoa_video_started = false;
}

static const char *CocoaVideoStart(const char * const *parm)
{
	const char *ret;

	DEBUG(driver, 1)("cocoa_v: CocoaVideoStart");

	if (_cocoa_video_started) return "Already started";
	_cocoa_video_started = true;

	memset(&_cocoa_video_data, 0, sizeof(_cocoa_video_data));

	setupApplication();

	/* Don't create a window or enter fullscreen if we're just going to show a dialog. */
	if (_cocoa_video_dialog) return NULL;

	QZ_VideoInit();

	ret = QZ_SetVideoMode(_cur_resolution[0], _cur_resolution[1], _fullscreen);
	if (ret != NULL) CocoaVideoStop();

	return ret;
}

static void CocoaVideoMakeDirty(int left, int top, int width, int height)
{
	if (_cocoa_video_data.num_dirty_rects < MAX_DIRTY_RECTS) {
		_cocoa_video_data.dirty_rects[_cocoa_video_data.num_dirty_rects].left = left;
		_cocoa_video_data.dirty_rects[_cocoa_video_data.num_dirty_rects].top = top;
		_cocoa_video_data.dirty_rects[_cocoa_video_data.num_dirty_rects].right = left + width;
		_cocoa_video_data.dirty_rects[_cocoa_video_data.num_dirty_rects].bottom = top + height;
	}
	_cocoa_video_data.num_dirty_rects++;
}

static void CocoaVideoMainLoop(void)
{
	DEBUG(driver, 1)("cocoa_v: CocoaVideoMainLoop");

	/* Start the main event loop */
	[NSApp run];
}

static bool CocoaVideoChangeRes(int w, int h)
{
	const char *ret;
	DEBUG(driver, 1)("cocoa_v: CocoaVideoChangeRes");

	ret = QZ_SetVideoModeAndRestoreOnFailure((uint)w, (uint)h, _cocoa_video_data.fullscreen);
	if (ret != NULL) {
		DEBUG(driver, 1)("cocoa_v:  failed with message: %s", ret);
	}

	return ret == NULL;
}

static void CocoaVideoFullScreen(bool full_screen)
{
	const char *ret;

	DEBUG(driver, 1)("cocoa_v: CocoaVideoFullScreen");

	ret = QZ_SetVideoModeAndRestoreOnFailure(_cocoa_video_data.width, _cocoa_video_data.height, full_screen);
	if (ret != NULL) {
		DEBUG(driver, 1)("cocoa_v:  failed with message: %s", ret);
	}

	_fullscreen = _cocoa_video_data.fullscreen;
}

const HalVideoDriver _cocoa_video_driver = {
	CocoaVideoStart,
	CocoaVideoStop,
	CocoaVideoMakeDirty,
	CocoaVideoMainLoop,
	CocoaVideoChangeRes,
	CocoaVideoFullScreen,
};


/* This is needed since sometimes assert is called before the videodriver is initialized */
void CocoaDialog(const char* title, const char* message, const char* buttonLabel)
{
	bool wasstarted;

	_cocoa_video_dialog = true;

	wasstarted = _cocoa_video_started;
	if (!_cocoa_video_started && CocoaVideoStart(NULL) != NULL) {
		fprintf(stderr, "%s: %s\n", title, message);
		return;
	}

	NSRunAlertPanel([NSString stringWithCString: title], [NSString stringWithCString: message], [NSString stringWithCString: buttonLabel], nil, nil);

	if (!wasstarted) CocoaVideoStop();

	_cocoa_video_dialog = false;
}


/* This is needed since OS X applications are started with the working dir set to / when double-clicked */
void cocoaSetWorkingDirectory(void)
{
	char parentdir[MAXPATHLEN];
	int chdir_ret;
	CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
	CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
	if (CFURLGetFileSystemRepresentation(url2, true, (unsigned char*)parentdir, MAXPATHLEN)) {
		chdir_ret = chdir(parentdir); /* chdir to the binary app's parent */
		assert(chdir_ret == 0);
	}
	CFRelease(url);
	CFRelease(url2);
}

/* These are called from main() to prevent a _NSAutoreleaseNoPool error when
 * exiting before the cocoa video driver has been loaded
 */
void cocoaSetupAutoreleasePool(void)
{
	_ottd_autorelease_pool = [[NSAutoreleasePool alloc] init];
}

void cocoaReleaseAutoreleasePool(void)
{
	[_ottd_autorelease_pool release];
}

#endif /* WITH_COCOA */