summaryrefslogtreecommitdiffstatshomepage
path: root/src/osd/sdl/debugosx.m
blob: 50482bc7459208b22c7fdf85a0f7940ad398d12a (plain) (blame)
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
//============================================================
//
//  debugosx.m - MacOS X Cocoa debug window handling
//
//  Copyright (c) 1996-2010, Nicola Salmoria and the MAME Team.
//  Visit http://mamedev.org for licensing and usage restrictions.
//
//============================================================


// TODO:
//  * Automatic scrolling for console and log views
//  * Using alpha for disabled foreground colours doesn't really work
//  * New windows created from auxiliary windows should inherit focus rather than pointing at current CPU
//  * Should have map of machine to console for multiple machine support rather than a single console
//  * Improve behaviour of expression history in memory and disassembly windows - the double tap is annoying
//  * Keyboard shortcuts in error log windows
//  * Don't accept keyboard input while the game is running
//  * Interior focus rings - standard/exterior focus rings look really ugly here
//  * Scroll views with content narrower than clipping area are flaky under Tiger - nothing I can do about this


// standard Cocoa headers
#include <AvailabilityMacros.h>
#import <Cocoa/Cocoa.h>

// MAME headers
#include "emu.h"
#include "debug/debugvw.h"
#include "debug/debugcon.h"
#include "debug/debugcpu.h"
#include "debugger.h"
#include "debug/dvdisasm.h"
#include "debug/dvmemory.h"
#include "debug/dvstate.h"

// MAMEOS headers
#include "debugosx.h"
#include "osdsdl.h"



//============================================================
//  LOCAL VARIABLES
//============================================================

static MAMEDebugConsole *main_console = nil;

static BOOL waiting_for_debugger = NO;

static NSString *const MAMEHideDebuggerNotification = @"MAMEHideDebuggerNotification";
static NSString *const MAMEShowDebuggerNotification = @"MAMEShowDebuggerNotification";
static NSString *const MAMEAuxiliaryDebugWindowWillCloseNotification
															= @"MAMEAuxiliaryDebugWindowWillCloseNotification";


//============================================================
//  PROTOTYPES
//============================================================

static void debugwin_view_update(debug_view &view, void *osdprivate);

static void console_create_window(running_machine *machine);


//============================================================
//  sdl_osd_interface::init_debugger
//============================================================

void sdl_osd_interface::init_debugger()
{
}

//============================================================
//  sdl_osd_interface::wait_for_debugger
//============================================================

void sdl_osd_interface::wait_for_debugger(running_device &device, bool firststop)
{
	// create a console window
	if (main_console == nil)
		console_create_window(&machine());

	// make sure the debug windows are visible
	waiting_for_debugger = YES;
	if (firststop) {
		NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithPointer:&device],
																		@"MAMEDebugDevice",
																		nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:MAMEShowDebuggerNotification
															object:main_console
														  userInfo:info];
	}

	// get and process messages
	{
		NSEvent *ev = [NSApp nextEventMatchingMask:NSAnyEventMask
										 untilDate:[NSDate distantFuture]
											inMode:NSDefaultRunLoopMode
										   dequeue:YES];
		if (ev != nil)
			[NSApp sendEvent:ev];
	}

	// mark the debugger as active
	waiting_for_debugger = NO;
}


//============================================================
//  debugwin_update_during_game
//============================================================

void debugwin_update_during_game(running_machine *machine)
{
}


//============================================================
//  debugwin_view_update
//============================================================

static void debugwin_view_update(debug_view &view, void *osdprivate)
{
	[(MAMEDebugView *)osdprivate update];
}


//============================================================
//  console_create_window
//============================================================

void console_create_window(running_machine *machine)
{
	main_console = [[MAMEDebugConsole alloc] initWithMachine:machine];
}


//============================================================
//  MAMEDebugView class
//============================================================

@implementation MAMEDebugCommandHistory

+ (NSInteger)defaultLength {
	return 100;
}


- (id)init {
	if (!(self = [super init]))
		return nil;
	length = [[self class] defaultLength];
	position = -1;
	current = nil;
	history = [[NSMutableArray alloc] initWithCapacity:length];
	return self;
}


- (void)dealloc {
	if (current != nil)
		[current release];
	if (history != nil)
		[history release];
	[super dealloc];
}


- (NSInteger)length {
	return length;
}


- (void)setLength:(NSInteger)l {
	length = l;
	while ([history count] > length)
		[history removeLastObject];
}


- (void)add:(NSString *)entry {
	if (([history count] == 0) || ![[history objectAtIndex:0] isEqualToString:entry]) {
		[history insertObject:entry atIndex:0];
		while ([history count] > length)
			[history removeLastObject];
	}
	position = -1;
}


- (NSString *)previous:(NSString *)cur {
	if ((position + 1) < [history count]) {
		if (position < 0) {
			[current autorelease];
			current = [cur copy];
		}
		return [history objectAtIndex:++position];
	} else {
		return nil;
	}
}


- (NSString *)next:(NSString *)cur {
	if (position > 0) {
		return [history objectAtIndex:--position];
	} else if (position == 0) {
		position--;
		return [[current retain] autorelease];
	} else {
		return nil;
	}
}


- (void)reset {
	position = -1;
	if (current != nil) {
		[current release];
		current = nil;
	}
}


- (void)clear {
	position = -1;
	if (current != nil) {
		[current release];
		current = nil;
	}
	[history removeAllObjects];
}

@end


//============================================================
//  MAMEDebugView class
//============================================================

@implementation MAMEDebugView

- (NSColor *)foregroundForAttribute:(UINT8)attrib {
	const CGFloat alpha = (attrib & DCA_DISABLED) ? 0.5 : 1.0;
	if (attrib & DCA_COMMENT)
		return [NSColor colorWithCalibratedRed:0.0 green:0.375 blue:0.0 alpha:1.0];
	else if (attrib & DCA_INVALID)
		return [NSColor colorWithCalibratedRed:0.0 green:0.0 blue:1.0 alpha:alpha];
	else if (attrib & DCA_CHANGED)
		return [NSColor colorWithCalibratedRed:0.875 green:0.0 blue:0.0 alpha:alpha];
	else
		return [NSColor colorWithCalibratedWhite:0.0 alpha:alpha];
}


- (NSColor *)backgroundForAttribute:(UINT8)attrib {
	if ((attrib & DCA_SELECTED) && (attrib & DCA_CURRENT)) {
		if ([[self window] isKeyWindow] && ([[self window] firstResponder] == self))
			return [NSColor colorWithCalibratedRed:0.875 green:0.625 blue:0.875 alpha:1.0];
		else
			return [NSColor colorWithCalibratedRed:0.875 green:0.5 blue:0.625 alpha:1.0];
	} else if (attrib & DCA_CURRENT) {
		return [NSColor colorWithCalibratedRed:1.0 green:0.625 blue:0.625 alpha:1.0];
	} else if (attrib & DCA_SELECTED) {
		if ([[self window] isKeyWindow] && ([[self window] firstResponder] == self))
			return [NSColor colorWithCalibratedRed:0.75 green:0.875 blue:1.0 alpha:1.0];
		else
			return [NSColor colorWithCalibratedWhite:0.875 alpha:1.0];
	} else if (attrib & DCA_ANCILLARY) {
		return [NSColor colorWithCalibratedWhite:0.75 alpha:1.0];
	} else {
		return [NSColor colorWithCalibratedWhite:1.0 alpha:1.0];
	}
}


- (debug_view_xy)convertLocation:(NSPoint)location {
	debug_view_xy position;
	position.x = lround(floor(location.x / fontWidth));
	position.y = lround(floor(location.y / fontHeight));
	if (position.x < 0)
		position.x = 0;
	else if (position.x >= totalSize->x)
		position.x = totalSize->x - 1;
	if (position.y < 0)
		position.y = 0;
	else if (position.y >= totalSize->y)
		position.y = totalSize->y - 1;
	return position;
}


- (void)convertBounds:(NSRect)b toPosition:(debug_view_xy *)origin size:(debug_view_xy *)size {
	origin->x = lround(floor(b.origin.x / fontWidth));
	origin->y = lround(floor(b.origin.y / fontHeight));
	size->x = lround(ceil((b.origin.x + b.size.width) / fontWidth)) - origin->x;
	size->y = lround(ceil((b.origin.y + b.size.height) / fontHeight)) - origin->y;
}


- (void)recomputeVisible {
	if ([self window] != nil) {
		debug_view_xy	origin, size;

		// this gets all the characters that are at least paritally visible
		[self convertBounds:[self visibleRect] toPosition:&origin size:&size];

		// need to render entire lines or we get screwed up characters when widening views
		origin.x = 0;
		size.x = totalSize->x;

		// tell them what we think
		view->set_visible_size(size);
		view->set_visible_position(origin);
		topLeft->x = origin.x;
		topLeft->y = origin.y;
	}
}


- (void)typeCharacterAndScrollToCursor:(char)ch {
	if (view->cursor_supported()) {
		debug_view_xy oldPos = view->cursor_position();
		view->process_char(ch);
		{
			debug_view_xy newPos = view->cursor_position();
			if ((newPos.x != oldPos.x) || (newPos.y != oldPos.y)) {
				[self scrollRectToVisible:NSMakeRect(newPos.x * fontWidth,
													 newPos.y * fontHeight,
													 fontWidth,
													 fontHeight)];
			}
		}
	} else {
		view->process_char(ch);
	}
}


+ (NSFont *)defaultFont {
	// maybe we should get the configured system fixed-width font...
	return [NSFont fontWithName:@"Monaco" size:10];
}


- (id)initWithFrame:(NSRect)f type:(debug_view_type)t machine:(running_machine *)m {
	if (!(self = [super initWithFrame:f]))
		return nil;
	type = t;
	machine = m;
	view = machine->debug_view().alloc_view((debug_view_type)type, debugwin_view_update, self);
	if (view == nil) {
		[self release];
		return nil;
	}
	totalSize = global_alloc(debug_view_xy());
	topLeft = global_alloc(debug_view_xy());
	totalSize->x = totalSize->y = 0;
	topLeft->x = topLeft->y = 0;
	[self setFont:[[self class] defaultFont]];
	return self;
}


- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	if (font != nil)
		[font release];
	global_free(totalSize);
	global_free(topLeft);
	[super dealloc];
}


- (void)update {
	debug_view_xy	newSize, newOrigin;

	// resize our frame if the total size has changed
	newSize = view->total_size();
	if ((newSize.x != totalSize->x) || (newSize.y != totalSize->y)) {
		[self setFrameSize:NSMakeSize(fontWidth * newSize.x, fontHeight * newSize.y)];
		totalSize->x = newSize.x;
		totalSize->y = newSize.y;
	}

	// scroll the view if we're being told to
	newOrigin = view->visible_position();
	if (newOrigin.y != topLeft->y) {
		[self scrollPoint:NSMakePoint([self visibleRect].origin.x, newOrigin.y * fontHeight)];
		topLeft->y = newOrigin.y;
	}

	// recompute the visible area and mark as dirty
	[self recomputeVisible];
	[self setNeedsDisplay:YES];
}


- (NSSize)maximumFrameSize {
	debug_view_xy max = view->total_size();
	return NSMakeSize(max.x * fontWidth, max.y * fontHeight);
}


- (NSFont *)font {
	return [[font retain] autorelease];
}


- (void)setFont:(NSFont *)f {
	[font autorelease];
	font = [f retain];
	fontWidth = [font maximumAdvancement].width;
	fontHeight = ceil([font ascender] - [font descender]);
	fontAscent = [font ascender];
	[[self enclosingScrollView] setLineScroll:fontHeight];
	totalSize->x = totalSize->y = 0;
	[self update];
}


- (void)windowDidBecomeKey:(NSNotification *)notification {
	NSWindow *win = [notification object];
	if ((win == [self window]) && ([win firstResponder] == self) && view->cursor_supported())
		[self setNeedsDisplay:YES];
}


- (void)windowDidResignKey:(NSNotification *)notification {
	NSWindow *win = [notification object];
	if ((win == [self window]) && ([win firstResponder] == self) && view->cursor_supported())
		[self setNeedsDisplay:YES];
}


- (BOOL)acceptsFirstResponder {
	return view->cursor_supported();
}


- (BOOL)becomeFirstResponder {
	if (view->cursor_supported()) {
		debug_view_xy pos;
		view->set_cursor_visible(true);
		pos = view->cursor_position();
		[self scrollRectToVisible:NSMakeRect(pos.x * fontWidth, pos.y * fontHeight, fontWidth, fontHeight)];
		[self setNeedsDisplay:YES];
		return [super becomeFirstResponder];
	} else {
		return NO;
	}
}


- (BOOL)resignFirstResponder {
	if (view->cursor_supported())
		[self setNeedsDisplay:YES];
	return [super resignFirstResponder];
}


- (void)viewDidMoveToSuperview {
	[[self enclosingScrollView] setLineScroll:fontHeight];
	[super viewDidMoveToSuperview];
}


- (void)viewDidMoveToWindow {
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
	if ([self window] != nil) {
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(windowDidBecomeKey:)
													 name:NSWindowDidBecomeKeyNotification
												   object:[self window]];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(windowDidResignKey:)
													 name:NSWindowDidResignKeyNotification
												   object:[self window]];
		[self recomputeVisible];
	}
}


- (BOOL)isFlipped {
	return YES;
}


- (void)drawRect:(NSRect)dirtyRect {
	const debug_view_char	*base;
	debug_view_xy			origin, size;
	debug_view_xy			position, clip;
	NSMutableString			*text;
	NSMutableDictionary		*attributes;
	UINT32					pass, row, col;

	// work out how much we need to draw
	[self recomputeVisible];
	origin = view->visible_position();
	size = view->visible_size();
	[self convertBounds:dirtyRect toPosition:&position size:&clip];

	// this gets the text for the whole visible area
	base = view->viewdata();
	if (!base)
		return;

	text = [[NSMutableString alloc] initWithCapacity:clip.x];
	attributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:font, NSFontAttributeName, nil];
	for (pass = 0; pass < 2; pass++) {
		const debug_view_char *data = base + ((position.y - origin.y) * size.x);
		for (row = position.y; row < position.y + clip.y; row++, data += size.x) {
			int attr = -1;

			if ((row < origin.y) || (row >= origin.y + size.y))
				continue;

			// render entire lines to get character alignment right
			for (col = origin.x; col < origin.x + size.x; col++) {
				if ((attr != data[col - origin.x].attrib) && ([text length] > 0)) {
					if (pass == 0) {
						[[self backgroundForAttribute:attr] set];
						[NSBezierPath fillRect:NSMakeRect((col - [text length]) * fontWidth,
														  row * fontHeight,
														  [text length] * fontWidth,
														  fontHeight)];
					} else {
						[attributes setObject:[self foregroundForAttribute:attr]
									   forKey:NSForegroundColorAttributeName];
						[text drawAtPoint:NSMakePoint((col - [text length]) * fontWidth, row * fontHeight)
						   withAttributes:attributes];
					}
					[text setString:@""];
				}
				attr = data[col - origin.x].attrib;
				[text appendFormat:@"%c", data[col - origin.x].byte];
			}
			if ([text length] > 0) {
				if (pass == 0) {
					[[self backgroundForAttribute:attr] set];
					[NSBezierPath fillRect:NSMakeRect((col - [text length]) * fontWidth,
													  row * fontHeight,
													  [text length] * fontWidth,
													  fontHeight)];
				} else {
					[attributes setObject:[self foregroundForAttribute:attr]
								   forKey:NSForegroundColorAttributeName];
					[text drawAtPoint:NSMakePoint((col - [text length]) * fontWidth, row * fontHeight)
					   withAttributes:attributes];
				}
				[text setString:@""];
			}
		}
	}
	[attributes release];
	[text release];
}


- (void)mouseDown:(NSEvent *)event {
	NSPoint	location = [self convertPoint:[event locationInWindow] fromView:nil];
	if (view->cursor_supported()) {
		view->set_cursor_position([self convertLocation:location]);
		view->set_cursor_visible(true);
		[self setNeedsDisplay:YES];
	}
}


- (void)mouseDragged:(NSEvent *)event {
	NSPoint	location = [self convertPoint:[event locationInWindow] fromView:nil];
	if (view->cursor_supported()) {
		[self autoscroll:event];
		view->set_cursor_position([self convertLocation:location]);
		[self setNeedsDisplay:YES];
	}
}


- (void)rightMouseDown:(NSEvent *)event {
	NSPoint	location = [self convertPoint:[event locationInWindow] fromView:nil];
	if (view->cursor_supported()) {
		view->set_cursor_position([self convertLocation:location]);
		view->set_cursor_visible(true);
		[self setNeedsDisplay:YES];
	}
	[super rightMouseDown:event];
}


- (void)keyDown:(NSEvent *)event {
	NSUInteger	modifiers = [event modifierFlags];
	NSString	*str = [event charactersIgnoringModifiers];

	if ([str length] == 1) {
		if (modifiers & NSNumericPadKeyMask) {
			switch ([str characterAtIndex:0]) {
				case NSUpArrowFunctionKey:
					if (modifiers & NSCommandKeyMask)
						view->process_char(DCH_CTRLHOME);
					else
						view->process_char(DCH_UP);
					return;
				case NSDownArrowFunctionKey:
					if (modifiers & NSCommandKeyMask)
						view->process_char(DCH_CTRLEND);
					else
						view->process_char(DCH_DOWN);
					return;
				case NSLeftArrowFunctionKey:
					if (modifiers & NSCommandKeyMask)
						[self typeCharacterAndScrollToCursor:DCH_HOME];
					else if (modifiers & NSAlternateKeyMask)
						[self typeCharacterAndScrollToCursor:DCH_CTRLLEFT];
					else
						[self typeCharacterAndScrollToCursor:DCH_LEFT];
					return;
				case NSRightArrowFunctionKey:
					if (modifiers & NSCommandKeyMask)
						[self typeCharacterAndScrollToCursor:DCH_END];
					else if (modifiers & NSAlternateKeyMask)
						[self typeCharacterAndScrollToCursor:DCH_CTRLRIGHT];
					else
						[self typeCharacterAndScrollToCursor:DCH_RIGHT];
					return;
				default:
					[self interpretKeyEvents:[NSArray arrayWithObject:event]];
					return;
			}
		} else if (modifiers & NSFunctionKeyMask) {
			switch ([str characterAtIndex:0]) {
				case NSPageUpFunctionKey:
					if (modifiers & NSAlternateKeyMask) {
						view->process_char(DCH_PUP);
						return;
					}
				case NSPageDownFunctionKey:
					if (modifiers & NSAlternateKeyMask) {
						view->process_char(DCH_PDOWN);
						return;
					}
				default:
					;
			}
			[super keyDown:event];
			return;
		}
	}
	[self interpretKeyEvents:[NSArray arrayWithObject:event]];
}


- (void)insertTab:(id)sender {
	if ([[self window] firstResponder] == self)
		[[self window] selectNextKeyView:self];
}


- (void)insertBacktab:(id)sender {
	if ([[self window] firstResponder] == self)
		[[self window] selectPreviousKeyView:self];
}


- (void)insertNewline:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->single_step();
}


- (void)insertText:(id)string {
	NSUInteger	len;
	NSRange		found;
	if ([string isKindOfClass:[NSAttributedString class]])
		string = [string string];
	for (len = [string length], found = NSMakeRange(0, 0);
		 found.location < len;
		 found.location += found.length) {
		found = [string rangeOfComposedCharacterSequenceAtIndex:found.location];
		if (found.length == 1) {
			unichar ch = [string characterAtIndex:found.location];
			if ((ch >= 32) && (ch < 127))
				[self typeCharacterAndScrollToCursor:ch];
		}
	}
}

@end


//============================================================
//  MAMEMemoryView class
//============================================================

@implementation MAMEMemoryView

- (id)initWithFrame:(NSRect)f machine:(running_machine *)m {
	NSMenu	*contextMenu;

	if (!(self = [super initWithFrame:f type:DVT_MEMORY machine:m]))
		return nil;

	contextMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:@"Memory"];
	[self insertActionItemsInMenu:contextMenu atIndex:0];
	[self setMenu:contextMenu];
	[contextMenu release];

	return self;
}


- (void)dealloc {
	[super dealloc];
}


- (BOOL)validateMenuItem:(NSMenuItem *)item {
	SEL			action = [item action];
	NSInteger	tag = [item tag];
	debug_view_memory *memview = downcast<debug_view_memory *>(view);

	if (action == @selector(showChunkSize:)) {
		[item setState:((tag == memview->bytes_per_chunk()) ? NSOnState : NSOffState)];
	} else if (action == @selector(showPhysicalAddresses:)) {
		[item setState:((tag == memview->physical()) ? NSOnState : NSOffState)];
	} else if (action == @selector(showReverseView:)) {
		[item setState:((tag == memview->reverse()) ? NSOnState : NSOffState)];
	} else if (action == @selector(showReverseViewToggle:)) {
		[item setState:(memview->reverse() ? NSOnState : NSOffState)];
	}
	return YES;
}


- (NSSize)maximumFrameSize {
	debug_view_xy				max;
	running_device				*curcpu = debug_cpu_get_visible_cpu(machine);
	const debug_view_source		*source = view->source_list().match_device(curcpu);

	max.x = max.y = 0;
	for (const debug_view_source *source = view->source_list().head(); source != NULL; source = source->next())
	{
		debug_view_xy	current;
		view->set_source(*source);
		current = view->total_size();
		if (current.x > max.x)
			max.x = current.x;
		if (current.y > max.y)
			max.y = current.y;
	}
	view->set_source(*source);
	return NSMakeSize(max.x * fontWidth, max.y * fontHeight);
}


- (NSString *)selectedSubviewName {
	const debug_view_source *source = view->source();
	if (source != NULL)
		return [NSString stringWithUTF8String:source->name()];
	else
		return @"";
}


- (int)selectedSubviewIndex {
	const debug_view_source *source = view->source();
	if (source != NULL)
		return view->source_list().index(*source);
	else
		return -1;
}


- (void)selectSubviewAtIndex:(int)index {
	const int	selected = view->source_list().index(*view->source());
	if (selected != index) {
		view->set_source(*view->source_list().by_index(index));
		if ([[self window] firstResponder] != self)
			view->set_cursor_visible(false);
	}
}


- (void)selectSubviewForCPU:(running_device *)device {
	const debug_view_source		*selected = view->source();
	const debug_view_source		*source = view->source_list().match_device(device);
	if ( selected != source ) {
		view->set_source(*source);
		if ([[self window] firstResponder] != self)
			view->set_cursor_visible(false);
	}
}


- (NSString *)expression {
	return [NSString stringWithUTF8String:downcast<debug_view_memory *>(view)->expression()];
}


- (void)setExpression:(NSString *)exp {
	downcast<debug_view_memory *>(view)->set_expression([exp UTF8String]);
}


- (IBAction)showChunkSize:(id)sender {
	downcast<debug_view_memory *>(view)->set_bytes_per_chunk([sender tag]);
}


- (IBAction)showPhysicalAddresses:(id)sender {
	downcast<debug_view_memory *>(view)->set_physical([sender tag]);
}


- (IBAction)showReverseView:(id)sender {
	downcast<debug_view_memory *>(view)->set_reverse([sender tag]);
}


- (IBAction)showReverseViewToggle:(id)sender {
	downcast<debug_view_memory *>(view)->set_reverse(!downcast<debug_view_memory *>(view)->reverse());
}


- (void)insertActionItemsInMenu:(NSMenu *)menu atIndex:(NSInteger)index {
	{
		NSInteger tag;
		for (tag = 1; tag <= 8; tag <<= 1) {
			NSString	*title = [NSString stringWithFormat:@"%d-byte Chunks", tag];
			NSMenuItem	*chunkItem = [menu insertItemWithTitle:title
														action:@selector(showChunkSize:)
												 keyEquivalent:[NSString stringWithFormat:@"%d", tag]
													   atIndex:index++];
			[chunkItem setTarget:self];
			[chunkItem setTag:tag];
		}
	}
	[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
	{
		NSMenuItem *logicalItem = [menu insertItemWithTitle:@"Logical Addresses"
													 action:@selector(showPhysicalAddresses:)
											  keyEquivalent:@"v"
													atIndex:index++];
		[logicalItem setTarget:self];
		[logicalItem setTag:FALSE];
	}
	{
		NSMenuItem *physicalItem = [menu insertItemWithTitle:@"Physical Addresses"
													  action:@selector(showPhysicalAddresses:)
											   keyEquivalent:@"y"
													 atIndex:index++];
		[physicalItem setTarget:self];
		[physicalItem setTag:TRUE];
	}
	[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
	{
		NSMenuItem *reverseItem = [menu insertItemWithTitle:@"Reverse View"
													 action:@selector(showReverseViewToggle:)
											  keyEquivalent:@"r"
													atIndex:index++];
		[reverseItem setTarget:self];
	}
	if (index < [menu numberOfItems])
		[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
}


- (void)insertSubviewItemsInMenu:(NSMenu *)menu atIndex:(NSInteger)index {
	for (const debug_view_source *source = view->source_list().head(); source != NULL; source = source->next())
	{
		[[menu insertItemWithTitle:[NSString stringWithUTF8String:source->name()]
							action:NULL
					 keyEquivalent:@""
						   atIndex:index++] setTag:view->source_list().index(*source)];
	}
	if (index < [menu numberOfItems])
		[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
}

@end


//============================================================
//  MAMEDisassemblyView class
//============================================================

@implementation MAMEDisassemblyView

- (device_debug::breakpoint *)findBreakpointAtAddress:(offs_t)address inAddressSpace:(address_space *)space {
	device_debug			*cpuinfo = space->cpu->debug();
	device_debug::breakpoint	*bp;
	for (bp = cpuinfo->breakpoint_first(); (bp != NULL) && (address != bp->address()); bp = bp->next()) {}
	return bp;
}

- (void)createContextMenu {
	NSMenu		*contextMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:@"Disassembly"];
	NSMenuItem	*item;

	item = [contextMenu addItemWithTitle:@"Toggle Breakpoint"
								  action:@selector(debugToggleBreakpoint:)
						   keyEquivalent:[NSString stringWithFormat:@"%C", NSF9FunctionKey]];
	[item setKeyEquivalentModifierMask:0];
	[item setTarget:self];

	item = [contextMenu addItemWithTitle:@"Disable Breakpoint"
								  action:@selector(debugToggleBreakpointEnable:)
						   keyEquivalent:[NSString stringWithFormat:@"%C", NSF9FunctionKey]];
	[item setKeyEquivalentModifierMask:NSShiftKeyMask];
	[item setTarget:self];

	[contextMenu addItem:[NSMenuItem separatorItem]];

	item = [contextMenu addItemWithTitle:@"Run to Cursor"
								  action:@selector(debugRunToCursor:)
						   keyEquivalent:[NSString stringWithFormat:@"%C", NSF4FunctionKey]];
	[item setKeyEquivalentModifierMask:0];
	[item setTarget:self];

	[contextMenu addItem:[NSMenuItem separatorItem]];

	item = [contextMenu addItemWithTitle:@"Raw Opcodes"
								  action:@selector(showRightColumn:)
						   keyEquivalent:@"r"];
	[item setTarget:self];
	[item setTag:DASM_RIGHTCOL_RAW];

	item = [contextMenu addItemWithTitle:@"Encrypted Opcodes"
								  action:@selector(showRightColumn:)
						   keyEquivalent:@"e"];
	[item setTarget:self];
	[item setTag:DASM_RIGHTCOL_ENCRYPTED];

	item = [contextMenu addItemWithTitle:@"Comments"
								  action:@selector(showRightColumn:)
						   keyEquivalent:@"n"];
	[item setTarget:self];
	[item setTag:DASM_RIGHTCOL_COMMENTS];

	[self setMenu:contextMenu];
	[contextMenu release];
}


- (id)initWithFrame:(NSRect)f machine:(running_machine *)m useConsole:(BOOL)uc {
	if (!(self = [super initWithFrame:f type:DVT_DISASSEMBLY machine:m]))
		return nil;
	useConsole = uc;
	[self createContextMenu];
	return self;
}


- (void)dealloc {
	[super dealloc];
}


- (BOOL)validateMenuItem:(NSMenuItem *)item {
	SEL						action = [item action];
	BOOL					inContextMenu = ([item menu] == [self menu]);
	BOOL					haveCursor = NO, isCurrent = NO;
	device_debug::breakpoint	*breakpoint = NULL;

	if (view->cursor_visible()) {
		if (debug_cpu_get_visible_cpu(machine) == view->source()->device()) {
			isCurrent = YES;
			if (!useConsole || isCurrent) {
				offs_t address = downcast<debug_view_disasm *>(view)->selected_address();
				haveCursor = YES;
				breakpoint = [self findBreakpointAtAddress:address inAddressSpace:downcast<const debug_view_disasm_source *>(view->source())->space()];
			}
		}
	}

	if (action == @selector(debugToggleBreakpoint:)) {
		if (haveCursor) {
			if (breakpoint != NULL) {
				if (inContextMenu)
					[item setTitle:@"Clear Breakpoint"];
				else
					[item setTitle:@"Clear Breakpoint at Cursor"];
			} else {
				if (inContextMenu)
					[item setTitle:@"Set Breakpoint"];
				else
					[item setTitle:@"Set Breakpoint at Cursor"];
			}
		} else {
			if (inContextMenu)
				[item setTitle:@"Toggle Breakpoint"];
			else
				[item setTitle:@"Toggle Breakpoint at Cursor"];
		}
		return haveCursor;
	} else if (action == @selector(debugToggleBreakpointEnable:)) {
		if ((breakpoint != NULL) && !breakpoint->enabled()) {
			if (inContextMenu)
				[item setTitle:@"Enable Breakpoint"];
			else
				[item setTitle:@"Enable Breakpoint at Cursor"];
		} else {
			if (inContextMenu)
				[item setTitle:@"Disable Breakpoint"];
			else
				[item setTitle:@"Disable Breakpoint at Cursor"];
		}
		return (breakpoint != NULL);
	} else if (action == @selector(debugRunToCursor:)) {
		return isCurrent;
	} else if (action == @selector(showRightColumn:)) {
		[item setState:((downcast<debug_view_disasm *>(view)->right_column() == [item tag]) ? NSOnState : NSOffState)];
		return YES;
	} else {
		return YES;
	}
}


- (NSSize)maximumFrameSize {
	debug_view_xy				max;
	running_device				*curcpu = debug_cpu_get_visible_cpu(machine);
	const debug_view_source		*source = view->source_list().match_device(curcpu);

	max.x = max.y = 0;
	for (const debug_view_source *source = view->source_list().head(); source != NULL; source = source->next())
	{
		debug_view_xy   current;
		view->set_source(*source);
		current = view->total_size();
		if (current.x > max.x)
			max.x = current.x;
		if (current.y > max.y)
			max.y = current.y;
	}
	view->set_source(*source);
	return NSMakeSize(max.x * fontWidth, max.y * fontHeight);
}


- (NSString *)selectedSubviewName {
	const debug_view_source *source = view->source();
	if (source != NULL)
		return [NSString stringWithUTF8String:source->name()];
	else
		return @"";
}


- (int)selectedSubviewIndex {
	const debug_view_source *source = view->source();
	if (source != NULL)
		return view->source_list().index(*source);
	else
		return -1;
}


- (void)selectSubviewAtIndex:(int)index {
	const int	selected = view->source_list().index(*view->source());
	if (selected != index) {
		view->set_source(*view->source_list().by_index(index));
		if ([[self window] firstResponder] != self)
			view->set_cursor_visible(false);
	}
}


- (void)selectSubviewForCPU:(running_device *)device {
	const debug_view_source     *selected = view->source();
	const debug_view_source     *source = view->source_list().match_device(device);
	if ( selected != source ) {
		view->set_source(*source);
		if ([[self window] firstResponder] != self)
			view->set_cursor_visible(false);
	}
}


- (NSString *)expression {
	return [NSString stringWithUTF8String:downcast<debug_view_disasm *>(view)->expression()];
}


- (void)setExpression:(NSString *)exp {
	downcast<debug_view_disasm *>(view)->set_expression([exp UTF8String]);
}


- (IBAction)debugToggleBreakpoint:(id)sender {
	if (view->cursor_visible()) {
		address_space *space = downcast<const debug_view_disasm_source *>(view->source())->space();
		if (!useConsole || (debug_cpu_get_visible_cpu(machine) == space->cpu)) {
			offs_t				address = downcast<debug_view_disasm *>(view)->selected_address();
			device_debug::breakpoint *bp = [self findBreakpointAtAddress:address inAddressSpace:space];

			// if it doesn't exist, add a new one
			if (useConsole) {
				NSString *command;
				if (bp == NULL)
					command = [NSString stringWithFormat:@"bpset %lX", (unsigned long)address];
				else
					command = [NSString stringWithFormat:@"bpclear %X", (unsigned)bp->index()];
				debug_console_execute_command(machine, [command UTF8String], 1);
			} else {
				if (bp == NULL)
					space->cpu->debug()->breakpoint_set(address, NULL, NULL);
				else
					space->cpu->debug()->breakpoint_clear(bp->index());
			}
		}
	}
}


- (IBAction)debugToggleBreakpointEnable:(id)sender {
	if (view->cursor_visible()) {
		address_space *space = downcast<const debug_view_disasm_source *>(view->source())->space();
		if (!useConsole || (debug_cpu_get_visible_cpu(machine) == space->cpu)) {
			offs_t				address = downcast<debug_view_disasm *>(view)->selected_address();
			device_debug::breakpoint *bp = [self findBreakpointAtAddress:address inAddressSpace:space];

			if (bp != NULL) {
				NSString *command;
				if (useConsole) {
					if (bp->enabled())
						command = [NSString stringWithFormat:@"bpdisable %X", (unsigned)bp->index()];
					else
						command = [NSString stringWithFormat:@"bpenable %X", (unsigned)bp->index()];
					debug_console_execute_command(machine, [command UTF8String], 1);
				} else {
					space->cpu->debug()->breakpoint_enable(bp->index(), !bp->enabled());
				}
			}
		}
	}
}


- (IBAction)debugRunToCursor:(id)sender {
	if (view->cursor_visible()) {
		address_space *space = downcast<const debug_view_disasm_source *>(view->source())->space();
		if (debug_cpu_get_visible_cpu(machine) == space->cpu) {
			offs_t address = downcast<debug_view_disasm *>(view)->selected_address();
			if (useConsole) {
				NSString *command = [NSString stringWithFormat:@"go 0x%lX", (unsigned long)address];
				debug_console_execute_command(machine, [command UTF8String], 1);
			} else {
				debug_cpu_get_visible_cpu(machine)->debug()->go(address);
			}
		}
	}
}


- (IBAction)showRightColumn:(id)sender {
	downcast<debug_view_disasm *>(view)->set_right_column((disasm_right_column) [sender tag]);
}


- (void)insertActionItemsInMenu:(NSMenu *)menu atIndex:(NSInteger)index {
	{
		NSMenuItem *breakItem = [menu insertItemWithTitle:@"Toggle Breakpoint at Cursor"
												   action:@selector(debugToggleBreakpoint:)
											keyEquivalent:[NSString stringWithFormat:@"%C", NSF9FunctionKey]
												  atIndex:index++];
		[breakItem setKeyEquivalentModifierMask:0];
		[breakItem setTarget:self];
	}
	{
		NSMenuItem *disableItem = [menu insertItemWithTitle:@"Disable Breakpoint at Cursor"
													 action:@selector(debugToggleBreakpointEnable:)
											  keyEquivalent:[NSString stringWithFormat:@"%C", NSF9FunctionKey]
													atIndex:index++];
		[disableItem setKeyEquivalentModifierMask:NSShiftKeyMask];
		[disableItem setAlternate:YES];
		[disableItem setTarget:self];
	}
	{
		NSMenu		*runMenu = [[menu itemWithTitle:@"Run"] submenu];
		NSMenuItem	*runItem;
		if (runMenu != nil) {
			runItem = [runMenu addItemWithTitle:@"to Cursor"
										 action:@selector(debugRunToCursor:)
								  keyEquivalent:[NSString stringWithFormat:@"%C", NSF4FunctionKey]];
		} else {
			runItem = [menu insertItemWithTitle:@"Run to Cursor"
										 action:@selector(debugRunToCursor:)
								  keyEquivalent:[NSString stringWithFormat:@"%C", NSF4FunctionKey]
										atIndex:index++];
		}
		[runItem setKeyEquivalentModifierMask:0];
		[runItem setTarget:self];
	}
	[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
	{
		NSMenuItem *rawItem = [menu insertItemWithTitle:@"Show Raw Opcodes"
												 action:@selector(showRightColumn:)
										  keyEquivalent:@"r"
												atIndex:index++];
		[rawItem setTarget:self];
		[rawItem setTag:DASM_RIGHTCOL_RAW];
	}
	{
		NSMenuItem *encItem = [menu insertItemWithTitle:@"Show Encrypted Opcodes"
												 action:@selector(showRightColumn:)
										  keyEquivalent:@"e"
												atIndex:index++];
		[encItem setTarget:self];
		[encItem setTag:DASM_RIGHTCOL_ENCRYPTED];
	}
	{
		NSMenuItem *commentsItem = [menu insertItemWithTitle:@"Show Comments"
													  action:@selector(showRightColumn:)
											   keyEquivalent:@"n"
													 atIndex:index++];
		[commentsItem setTarget:self];
		[commentsItem setTag:DASM_RIGHTCOL_COMMENTS];
	}
	if (index < [menu numberOfItems])
		[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
}


- (void)insertSubviewItemsInMenu:(NSMenu *)menu atIndex:(NSInteger)index {
	for (const debug_view_source *source = view->source_list().head(); source != NULL; source = source->next())
	{
		[[menu insertItemWithTitle:[NSString stringWithUTF8String:source->name()]
							action:NULL
					 keyEquivalent:@""
						   atIndex:index++] setTag:view->source_list().index(*source)];
	}
	if (index < [menu numberOfItems])
		[menu insertItem:[NSMenuItem separatorItem] atIndex:index++];
}

@end


//============================================================
//  MAMERegistersView class
//============================================================

@implementation MAMERegistersView

- (id)initWithFrame:(NSRect)f machine:(running_machine *)m {
	if (!(self = [super initWithFrame:f type:DVT_STATE machine:m]))
		return nil;
	return self;
}


- (void)dealloc {
	[super dealloc];
}


- (NSSize)maximumFrameSize {
	debug_view_xy				max;
	running_device				*curcpu = debug_cpu_get_visible_cpu(machine);
	const debug_view_source		*source = view->source_list().match_device(curcpu);


	max.x = max.y = 0;
	for (const debug_view_source *source = view->source_list().head(); source != NULL; source = source->next())
	{
		debug_view_xy   current;
		view->set_source(*source);
		current = view->total_size();
		if (current.x > max.x)
			max.x = current.x;
		if (current.y > max.y)
			max.y = current.y;
	}
	view->set_source(*source);
	return NSMakeSize(max.x * fontWidth, max.y * fontHeight);
}


- (NSString *)selectedSubviewName {
	return @"";
}


- (int)selectedSubviewIndex {
	return -1;
}


- (void)selectSubviewAtIndex:(int)index {
}


- (void)selectSubviewForCPU:(running_device *)device {
	//dv = get_view(dmain, DVT_STATE);
	view->set_source(*view->source_list().match_device(device));
}

@end


//============================================================
//  MAMEConsoleView class
//============================================================

@implementation MAMEConsoleView

- (id)initWithFrame:(NSRect)f machine:(running_machine *)m {
	if (!(self = [super initWithFrame:f type:DVT_CONSOLE machine:m]))
		return nil;
	return self;
}


- (void)dealloc {
	[super dealloc];
}

@end


//============================================================
//  MAMEErrorLogView class
//============================================================

@implementation MAMEErrorLogView

- (id)initWithFrame:(NSRect)f machine:(running_machine *)m {
	if (!(self = [super initWithFrame:f type:DVT_LOG machine:m]))
		return nil;
	return self;
}


- (void)dealloc {
	[super dealloc];
}

@end


//============================================================
//  MAMEDebugWindowHandler class
//============================================================

@implementation MAMEDebugWindowHandler

+ (void)addCommonActionItems:(NSMenu *)menu {
	{
		NSMenuItem *runParentItem = [menu addItemWithTitle:@"Run"
													action:@selector(debugRun:)
											 keyEquivalent:[NSString stringWithFormat:@"%C", NSF5FunctionKey]];
		NSMenu *runMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:@"Run"];
		[runParentItem setSubmenu:runMenu];
		[runMenu release];
		[runParentItem setKeyEquivalentModifierMask:0];
		[[runMenu addItemWithTitle:@"and Hide Debugger"
							action:@selector(debugRunAndHide:)
					 keyEquivalent:[NSString stringWithFormat:@"%C", NSF12FunctionKey]]
		 setKeyEquivalentModifierMask:0];
		[[runMenu addItemWithTitle:@"to Next CPU"
							action:@selector(debugRunToNextCPU:)
					 keyEquivalent:[NSString stringWithFormat:@"%C", NSF6FunctionKey]]
		 setKeyEquivalentModifierMask:0];
		[[runMenu addItemWithTitle:@"until Next Interrupt on Current CPU"
							action:@selector(debugRunToNextInterrupt:)
					 keyEquivalent:[NSString stringWithFormat:@"%C", NSF7FunctionKey]]
		 setKeyEquivalentModifierMask:0];
		[[runMenu addItemWithTitle:@"until Next VBLANK"
							action:@selector(debugRunToNextVBLANK:)
					 keyEquivalent:[NSString stringWithFormat:@"%C", NSF8FunctionKey]]
		 setKeyEquivalentModifierMask:0];
	}
	{
		NSMenuItem *stepParentItem = [menu addItemWithTitle:@"Step" action:NULL keyEquivalent:@""];
		NSMenu *stepMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:@"Step"];
		[stepParentItem setSubmenu:stepMenu];
		[stepMenu release];
		[[stepMenu addItemWithTitle:@"Into"
							 action:@selector(debugStepInto:)
					  keyEquivalent:[NSString stringWithFormat:@"%C", NSF11FunctionKey]]
		 setKeyEquivalentModifierMask:0];
		[[stepMenu addItemWithTitle:@"Over"
							 action:@selector(debugStepOver:)
					  keyEquivalent:[NSString stringWithFormat:@"%C", NSF10FunctionKey]]
		 setKeyEquivalentModifierMask:0];
		[[stepMenu addItemWithTitle:@"Out"
							 action:@selector(debugStepOut:)
					  keyEquivalent:[NSString stringWithFormat:@"%C", NSF10FunctionKey]]
		 setKeyEquivalentModifierMask:NSShiftKeyMask];
	}
	{
		NSMenuItem *resetParentItem = [menu addItemWithTitle:@"Reset" action:NULL keyEquivalent:@""];
		NSMenu *resetMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:@"Reset"];
		[resetParentItem setSubmenu:resetMenu];
		[resetMenu release];
		[[resetMenu addItemWithTitle:@"Soft"
							  action:@selector(debugSoftReset:)
					   keyEquivalent:[NSString stringWithFormat:@"%C", NSF3FunctionKey]]
		 setKeyEquivalentModifierMask:0];
		[[resetMenu addItemWithTitle:@"Hard"
							  action:@selector(debugHardReset:)
					   keyEquivalent:[NSString stringWithFormat:@"%C", NSF3FunctionKey]]
		 setKeyEquivalentModifierMask:NSShiftKeyMask];
	}
	[menu addItem:[NSMenuItem separatorItem]];
	{
		NSMenuItem *newParentItem = [menu addItemWithTitle:@"New" action:NULL keyEquivalent:@""];
		NSMenu *newMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:@"New"];
		[newParentItem setSubmenu:newMenu];
		[newMenu release];
		[newMenu addItemWithTitle:@"Memory Window"
						   action:@selector(debugNewMemoryWindow:)
					keyEquivalent:@"d"];
		[newMenu addItemWithTitle:@"Disassembly Window"
						   action:@selector(debugNewDisassemblyWindow:)
					keyEquivalent:@"a"];
		[newMenu addItemWithTitle:@"Error Log Window"
						   action:@selector(debugNewErrorLogWindow:)
					keyEquivalent:@"l"];
	}
	[menu addItem:[NSMenuItem separatorItem]];
	[menu addItemWithTitle:@"Close Window" action:@selector(performClose:) keyEquivalent:@"w"];
	[menu addItemWithTitle:@"Exit" action:@selector(debugExit:) keyEquivalent:@""];
}


+ (NSPopUpButton *)newActionButtonWithFrame:(NSRect)frame {
	NSPopUpButton *actionButton = [[NSPopUpButton alloc] initWithFrame:frame pullsDown:YES];
	[actionButton setTitle:@""];
	[actionButton addItemWithTitle:@""];
	[actionButton setBezelStyle:NSShadowlessSquareBezelStyle];
	[actionButton setFocusRingType:NSFocusRingTypeNone];
	[[actionButton cell] setArrowPosition:NSPopUpArrowAtCenter];
	[[self class] addCommonActionItems:[actionButton menu]];
	return actionButton;
}


- (id)initWithMachine:(running_machine *)m title:(NSString *)t {
	if (!(self = [super init]))
		return nil;

	window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 320, 240)
										 styleMask:(NSTitledWindowMask |
													NSClosableWindowMask |
													NSMiniaturizableWindowMask |
													NSResizableWindowMask)
										   backing:NSBackingStoreBuffered
											 defer:YES];
	[window setReleasedWhenClosed:NO];
	[window setDelegate:self];
	[window setTitle:t];
	[window setContentMinSize:NSMakeSize(320, 240)];

	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(showDebugger:)
												 name:MAMEShowDebuggerNotification
											   object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(hideDebugger:)
												 name:MAMEHideDebuggerNotification
											   object:nil];

	machine = m;

	return self;
}


- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];

	if (window != nil)
		[window release];

	[super dealloc];
}


- (void)activate {
	[window makeKeyAndOrderFront:self];
}


- (IBAction)debugRun:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->go();
}


- (IBAction)debugRunAndHide:(id)sender {
	[[NSNotificationCenter defaultCenter] postNotificationName:MAMEHideDebuggerNotification object:self];
	debug_cpu_get_visible_cpu(machine)->debug()->go();
}


- (IBAction)debugRunToNextCPU:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->go_next_device();
}


- (IBAction)debugRunToNextInterrupt:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->go_interrupt();
}


- (IBAction)debugRunToNextVBLANK:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->go_vblank();
}


- (IBAction)debugStepInto:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->single_step();
}


- (IBAction)debugStepOver:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->single_step_over();
}


- (IBAction)debugStepOut:(id)sender {
	debug_cpu_get_visible_cpu(machine)->debug()->single_step_out();
}


- (IBAction)debugSoftReset:(id)sender {
	machine->schedule_soft_reset();
	debug_cpu_get_visible_cpu(machine)->debug()->go();
}


- (IBAction)debugHardReset:(id)sender {
	machine->schedule_hard_reset();
}


- (IBAction)debugExit:(id)sender {
	machine->schedule_exit();
}


- (void)showDebugger:(NSNotification *)notification {
	running_device *device = (running_device *) [[[notification userInfo] objectForKey:@"MAMEDebugDevice"] pointerValue];
	if (device->machine == machine) {
		if (![window isVisible] && ![window isMiniaturized])
			[window orderFront:self];
	}
}


- (void)hideDebugger:(NSNotification *)notification {
	[window orderOut:self];
}

@end



//============================================================
//  MAMEDebugConsole class
//============================================================

@implementation MAMEDebugConsole

- (id)initWithMachine:(running_machine *)m {
	NSSplitView		*regSplit, *dasmSplit;
	NSScrollView	*regScroll, *dasmScroll, *consoleScroll;
	NSView			*consoleContainer;
	NSPopUpButton	*actionButton;
	NSRect			rct;

	// initialise superclass
	if (!(self = [super initWithMachine:m title:@"Debug"]))
		return nil;
	history = [[MAMEDebugCommandHistory alloc] init];
	auxiliaryWindows = [[NSMutableArray alloc] init];

	// create the register view
	regView = [[MAMERegistersView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) machine:machine];
	regScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[regScroll setDrawsBackground:YES];
	[regScroll setHasHorizontalScroller:YES];
	[regScroll setHasVerticalScroller:YES];
	[regScroll setAutohidesScrollers:YES];
	[regScroll setBorderType:NSBezelBorder];
	[regScroll setDocumentView:regView];
	[regView release];

	// create the disassembly view
	dasmView = [[MAMEDisassemblyView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)
												  machine:machine
											   useConsole:YES];
	[dasmView setExpression:@"curpc"];
	dasmScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[dasmScroll setDrawsBackground:YES];
	[dasmScroll setHasHorizontalScroller:YES];
	[dasmScroll setHasVerticalScroller:YES];
	[dasmScroll setAutohidesScrollers:YES];
	[dasmScroll setBorderType:NSBezelBorder];
	[dasmScroll setDocumentView:dasmView];
	[dasmView release];

	// create the console view
	consoleView = [[MAMEConsoleView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) machine:machine];
	consoleScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[consoleScroll setDrawsBackground:YES];
	[consoleScroll setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
	[consoleScroll setHasHorizontalScroller:YES];
	[consoleScroll setHasVerticalScroller:YES];
	[consoleScroll setAutohidesScrollers:YES];
	[consoleScroll setBorderType:NSBezelBorder];
	[consoleScroll setDocumentView:consoleView];
	[consoleView release];

	// create the command field
	commandField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 100, 19)];
	[commandField setAutoresizingMask:(NSViewWidthSizable | NSViewMaxYMargin)];
	[commandField setFont:[[MAMEDebugView class] defaultFont]];
	[commandField setFocusRingType:NSFocusRingTypeNone];
	[commandField setTarget:self];
	[commandField setAction:@selector(doCommand:)];
	[commandField setDelegate:self];
	rct = [commandField frame];
	[commandField setFrame:NSMakeRect(rct.size.height, 0, rct.size.width - rct.size.height, rct.size.height)];

	// create the action pull-down button
	actionButton = [[self class] newActionButtonWithFrame:NSMakeRect(0, 0, rct.size.height, rct.size.height)];
	[actionButton setAutoresizingMask:(NSViewMaxXMargin | NSViewMaxYMargin)];
	[dasmView insertActionItemsInMenu:[actionButton menu] atIndex:1];

	// create the container for the console and command input field
	consoleContainer = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[consoleScroll setFrame:NSMakeRect(0,
									   rct.size.height,
									   100,
									   [consoleContainer bounds].size.height - rct.size.height)];
	[consoleContainer addSubview:consoleScroll];
	[consoleContainer addSubview:commandField];
	[consoleContainer addSubview:actionButton];
	[consoleScroll release];
	[commandField release];
	[actionButton release];

	// create the split between the disassembly and the console
	dasmSplit = [[NSSplitView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[dasmSplit setDelegate:self];
	[dasmSplit setVertical:NO];
	[dasmSplit addSubview:dasmScroll];
	[dasmSplit addSubview:consoleContainer];
	[dasmScroll release];
	[consoleContainer release];

	// create the split between the registers and the console
	regSplit = [[NSSplitView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[regSplit setDelegate:self];
	[regSplit setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
	[regSplit setVertical:YES];
	[regSplit addSubview:regScroll];
	[regSplit addSubview:dasmSplit];
	[regScroll release];
	[dasmSplit release];

	// put the split views in the window and get them into a half-reasonable state
	[window setContentView:regSplit];
	[regSplit release];
	[regSplit adjustSubviews];
	[dasmSplit adjustSubviews];

	// keyboard focus should start on the command field
	[window makeFirstResponder:commandField];

	// calculate the optimal size for everything
	{
		NSRect	available = [[NSScreen mainScreen] visibleFrame];
		NSRect	windowFrame = [window frame];
		NSSize	regCurrent = [regScroll frame].size;
		NSSize	regSize = [NSScrollView frameSizeForContentSize:[regView maximumFrameSize]
										 hasHorizontalScroller:YES
										   hasVerticalScroller:YES
													borderType:[regScroll borderType]];
		NSSize	dasmCurrent = [dasmScroll frame].size;
		NSSize	dasmSize = [NSScrollView frameSizeForContentSize:[dasmView maximumFrameSize]
										  hasHorizontalScroller:YES
											hasVerticalScroller:YES
													 borderType:[dasmScroll borderType]];
		NSSize	consoleCurrent = [consoleContainer frame].size;
		NSSize	consoleSize = [NSScrollView frameSizeForContentSize:[consoleView maximumFrameSize]
											 hasHorizontalScroller:YES
											   hasVerticalScroller:YES
														borderType:[consoleScroll borderType]];
		NSSize	adjustment;
		NSRect	lhsFrame, rhsFrame;

		consoleSize.width += consoleCurrent.width - [consoleScroll frame].size.width;
		consoleSize.height += consoleCurrent.height - [consoleScroll frame].size.height;
		adjustment.width = regSize.width - regCurrent.width;
		adjustment.height = regSize.height - regCurrent.height;
		adjustment.width += MAX(dasmSize.width - dasmCurrent.width, consoleSize.width - consoleCurrent.width);

		windowFrame.size.width += adjustment.width;
		windowFrame.size.height += adjustment.height; // not used - better to go for fixed height
		windowFrame.size.height = MIN(512.0, available.size.height);
		windowFrame.size.width = MIN(windowFrame.size.width, available.size.width);
		windowFrame.origin.x = available.origin.x + available.size.width - windowFrame.size.width;
		windowFrame.origin.y = available.origin.y;
		[window setFrame:windowFrame display:YES];

		lhsFrame = [regScroll frame];
		rhsFrame = [dasmSplit frame];
		adjustment.width = MIN(regSize.width, ([regSplit frame].size.width - [regSplit dividerThickness]) / 2);
		rhsFrame.origin.x -= lhsFrame.size.width - adjustment.width;
		rhsFrame.size.width += lhsFrame.size.width - adjustment.width;
		lhsFrame.size.width = adjustment.width;
		[regScroll setFrame:lhsFrame];
		[dasmSplit setFrame:rhsFrame];
	}

	// select the current processor
	[self setCPU:machine->firstcpu];

	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(auxiliaryWindowWillClose:)
												 name:MAMEAuxiliaryDebugWindowWillCloseNotification
											   object:nil];

	// don't forget the return value
	return self;
}


- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];

	if (history != nil)
		[history release];
	if (auxiliaryWindows != nil)
		[auxiliaryWindows release];

	[super dealloc];
}


- (void)setCPU:(running_device *)device {
	[regView selectSubviewForCPU:device];
	[dasmView selectSubviewForCPU:device];
	[window setTitle:[NSString stringWithFormat:@"Debug: %s - %s '%s'",
												device->machine->gamedrv->name,
												device->name(),
												device->tag()]];
}


- (IBAction)doCommand:(id)sender {
	NSString *command = [sender stringValue];
	if ([command length] == 0) {
		debug_cpu_get_visible_cpu(machine)->debug()->single_step();
	} else {
		debug_console_execute_command(machine, [command UTF8String], 1);
		[history add:command];
	}
	[sender setStringValue:@""];
}


- (IBAction)debugNewMemoryWindow:(id)sender {
	MAMEMemoryViewer *win = [[MAMEMemoryViewer alloc] initWithMachine:machine console:self];
	[auxiliaryWindows addObject:win];
	[win release];
	[win activate];
}


- (IBAction)debugNewDisassemblyWindow:(id)sender {
	MAMEDisassemblyViewer *win = [[MAMEDisassemblyViewer alloc] initWithMachine:machine console:self];
	[auxiliaryWindows addObject:win];
	[win release];
	[win activate];
}


- (IBAction)debugNewErrorLogWindow:(id)sender {
	MAMEDisassemblyViewer *win = [[MAMEErrorLogViewer alloc] initWithMachine:machine console:self];
	[auxiliaryWindows addObject:win];
	[win release];
	[win activate];
}


- (void)showDebugger:(NSNotification *)notification {
	running_device *device = (running_device * )[[[notification userInfo] objectForKey:@"MAMEDebugDevice"] pointerValue];
	if (device->machine == machine) {
		[self setCPU:device];
		[window makeKeyAndOrderFront:self];
	}
}


- (void)auxiliaryWindowWillClose:(NSNotification *)notification {
	[auxiliaryWindows removeObjectIdenticalTo:[notification object]];
}


- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command {
	if (control == commandField) {
		if (command == @selector(cancelOperation:)) {
			[commandField setStringValue:@""];
			[history reset];
			return YES;
		} else if (command == @selector(moveUp:)) {
			NSString *hist = [history previous:[commandField stringValue]];
			if (hist != nil) {
				[commandField setStringValue:hist];
				[commandField selectText:self];
				[(NSText *)[window firstResponder] setSelectedRange:NSMakeRange([hist length], 0)];
			}
			return YES;
		} else if (command == @selector(moveDown:)) {
			NSString *hist = [history next:[commandField stringValue]];
			if (hist != nil) {
				[commandField setStringValue:hist];
				[commandField selectText:self];
				[(NSText *)[window firstResponder] setSelectedRange:NSMakeRange([hist length], 0)];
			}
			return YES;
		}
    }
	return NO;
}


- (void)windowWillClose:(NSNotification *)notification {
	if ([notification object] != window)
		return;
	[[NSNotificationCenter defaultCenter] postNotificationName:MAMEHideDebuggerNotification object:self];
	debug_cpu_get_visible_cpu(machine)->debug()->go();
}


- (CGFloat)splitView:(NSSplitView *)sender constrainMinCoordinate:(CGFloat)min ofSubviewAt:(NSInteger)offs {
	return (min < 100) ? 100 : min;
}


- (CGFloat)splitView:(NSSplitView *)sender constrainMaxCoordinate:(CGFloat)max ofSubviewAt:(NSInteger)offs {
	NSSize	sz = [sender bounds].size;
	CGFloat	allowed = ([sender isVertical] ? sz.width : sz.height) - 100 - [sender dividerThickness];
	return (max > allowed) ? allowed : max;
}


- (BOOL)splitView:(NSSplitView *)sender canCollapseSubview:(NSView *)subview {
	// allow registers or disassembly to be collapsed, but not console
	return [[sender subviews] indexOfObjectIdenticalTo:subview] == 0;
}


- (void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize {
	// This can only deal with a single split, but that's all we use, anyway
	NSRect first, second;
	[sender adjustSubviews];
	first = [[[sender subviews] objectAtIndex:0] frame];
	second = [[[sender subviews] objectAtIndex:1] frame];
	if ([sender isVertical]) {
		if (first.size.width < 100) {
			CGFloat diff = 100 - first.size.width;
			first.size.width = 100;
			second.origin.x += diff;
			second.size.width -= diff;
		} else if (second.size.width < 100) {
			CGFloat diff = 100 - second.size.width;
			second.size.width = 100;
			second.origin.x -= diff;
			first.size.width -= diff;
		}
	} else {
		if (first.size.height < 100) {
			CGFloat diff = 100 - first.size.height;
			first.size.height = 100;
			second.origin.y += diff;
			second.size.height -= diff;
		} else if (second.size.height < 100) {
			CGFloat diff = 100 - second.size.height;
			second.size.height = 100;
			second.origin.y -= diff;
			first.size.height -= diff;
		}
	}
	[[[sender subviews] objectAtIndex:0] setFrame:first];
	[[[sender subviews] objectAtIndex:1] setFrame:second];
}

@end


//============================================================
//  MAMEAuxiliaryDebugWindowHandler class
//============================================================

@implementation MAMEAuxiliaryDebugWindowHandler

+ (void)cascadeWindow:(NSWindow *)window {
	static NSPoint lastPosition = { 0, 0 };
	if (NSEqualPoints(lastPosition, NSZeroPoint)) {
		NSRect available = [[NSScreen mainScreen] visibleFrame];
		lastPosition = NSMakePoint(available.origin.x + 12, available.origin.y + available.size.height - 8);
	}
	lastPosition = [window cascadeTopLeftFromPoint:lastPosition];
}


- (id)initWithMachine:(running_machine *)m title:(NSString *)t console:(MAMEDebugConsole *)c {
	if (!(self = [super initWithMachine:m title:t]))
		return nil;
	console = c;
	return self;
}


- (void)dealloc {
	[super dealloc];
}


- (IBAction)debugNewMemoryWindow:(id)sender {
	[console debugNewMemoryWindow:sender];
}


- (IBAction)debugNewDisassemblyWindow:(id)sender {
	[console debugNewDisassemblyWindow:sender];
}


- (IBAction)debugNewErrorLogWindow:(id)sender {
	[console debugNewErrorLogWindow:sender];
}


- (void)windowWillClose:(NSNotification *)notification {
	[[NSNotificationCenter defaultCenter] postNotificationName:MAMEAuxiliaryDebugWindowWillCloseNotification
														object:self];
}

- (void)cascadeWindowWithDesiredSize:(NSSize)desired forView:(NSView *)view {
	NSRect	available = [[NSScreen mainScreen] visibleFrame];
	NSRect	windowFrame = [window frame];
	NSSize	current = [view frame].size;

	desired.width -= current.width;
	desired.height -= current.height;

	windowFrame.size.width += desired.width;
	windowFrame.size.height += desired.height;
	windowFrame.size.height = MIN(MIN(windowFrame.size.height, 240), available.size.height);
	windowFrame.size.width = MIN(windowFrame.size.width, available.size.width);
	windowFrame.origin.x = available.origin.x + available.size.width - windowFrame.size.width;
	windowFrame.origin.y = available.origin.y;
	[window setFrame:windowFrame display:YES];
	[[self class] cascadeWindow:window];

	windowFrame = [[window contentView] frame];
	desired = [window contentMinSize];
	[window setContentMinSize:NSMakeSize(MIN(windowFrame.size.width, desired.width),
										 MIN(windowFrame.size.height, desired.height))];
}

@end


//============================================================
//  MAMEExpreesionAuxiliaryDebugWindowHandler class
//============================================================

@implementation MAMEExpressionAuxiliaryDebugWindowHandler

- (id)initWithMachine:(running_machine *)m title:(NSString *)t console:(MAMEDebugConsole *)c {
	if (!(self = [super initWithMachine:m title:t console:c]))
		return nil;
	history = [[MAMEDebugCommandHistory alloc] init];
	return self;
}


- (void)dealloc {
	if (history != nil)
		[history release];
	[super dealloc];
}


- (id <MAMEDebugViewExpressionSupport>)documentView {
	return nil;
}


- (IBAction)doExpression:(id)sender {
	NSString *expr = [sender stringValue];
	if ([expr length] > 0) {
		[history add:expr];
		[[self documentView] setExpression:expr];
	} else {
		[sender setStringValue:[[self documentView] expression]];
		[history reset];
	}
	[sender selectText:self];
}


- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command {
	if (control == expressionField) {
		if (command == @selector(cancelOperation:)) {
			[history reset];
			[expressionField setStringValue:[[self documentView] expression]];
			[expressionField selectText:self];
			return YES;
		} else if (command == @selector(moveUp:)) {
			NSString *hist = [history previous:[expressionField stringValue]];
			if (hist != nil) {
				[expressionField setStringValue:hist];
				[expressionField selectText:self];
			}
			return YES;
		} else if (command == @selector(moveDown:)) {
			NSString *hist = [history next:[expressionField stringValue]];
			if (hist != nil) {
				[expressionField setStringValue:hist];
				[expressionField selectText:self];
			}
			return YES;
		}
    }
	return NO;
}

@end


//============================================================
//  MAMEMemoryViewer class
//============================================================

@implementation MAMEMemoryViewer

- (id)initWithMachine:(running_machine *)m console:(MAMEDebugConsole *)c {
	NSScrollView	*memoryScroll;
	NSView			*expressionContainer;
	NSPopUpButton	*actionButton, *subviewButton;
	NSRect			contentBounds, expressionFrame;

	if (!(self = [super initWithMachine:m title:@"Memory" console:c]))
		return nil;
	contentBounds = [[window contentView] bounds];

	// create the expression field
	expressionField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 100, 19)];
	[expressionField setAutoresizingMask:(NSViewWidthSizable | NSViewMaxXMargin | NSViewMinYMargin)];
	[expressionField setFont:[[MAMEDebugView class] defaultFont]];
	[expressionField setFocusRingType:NSFocusRingTypeNone];
	[expressionField setTarget:self];
	[expressionField setAction:@selector(doExpression:)];
	[expressionField setDelegate:self];
	expressionFrame = [expressionField frame];
	expressionFrame.size.width = (contentBounds.size.width - expressionFrame.size.height) / 2;
	[expressionField setFrameSize:expressionFrame.size];

	// create the subview popup
	subviewButton = [[NSPopUpButton alloc] initWithFrame:NSOffsetRect(expressionFrame,
																	  expressionFrame.size.width,
																	  0)];
	[subviewButton setAutoresizingMask:(NSViewWidthSizable | NSViewMinXMargin | NSViewMinYMargin)];
	[subviewButton setBezelStyle:NSShadowlessSquareBezelStyle];
	[subviewButton setFocusRingType:NSFocusRingTypeNone];
	[subviewButton setFont:[[MAMEDebugView class] defaultFont]];
	[subviewButton setTarget:self];
	[subviewButton setAction:@selector(changeSubview:)];
	[[subviewButton cell] setArrowPosition:NSPopUpArrowAtBottom];

	// create a container for the expression field and subview popup
	expressionFrame = NSMakeRect(expressionFrame.size.height,
								 contentBounds.size.height - expressionFrame.size.height,
								 contentBounds.size.width - expressionFrame.size.height,
								 expressionFrame.size.height);
	expressionContainer = [[NSView alloc] initWithFrame:expressionFrame];
	[expressionContainer setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
	[expressionContainer addSubview:expressionField];
	[expressionField release];
	[expressionContainer addSubview:subviewButton];
	[subviewButton release];
	[[window contentView] addSubview:expressionContainer];
	[expressionContainer release];

	// create the memory view
	memoryView = [[MAMEMemoryView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)
											   machine:machine];
	[memoryView insertSubviewItemsInMenu:[subviewButton menu] atIndex:0];
	memoryScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0,
																  0,
																  contentBounds.size.width,
																  expressionFrame.origin.y)];
	[memoryScroll setDrawsBackground:YES];
	[memoryScroll setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
	[memoryScroll setHasHorizontalScroller:YES];
	[memoryScroll setHasVerticalScroller:YES];
	[memoryScroll setAutohidesScrollers:YES];
	[memoryScroll setBorderType:NSNoBorder];
	[memoryScroll setDocumentView:memoryView];
	[memoryView release];
	[[window contentView] addSubview:memoryScroll];
	[memoryScroll release];

	// create the action popup
	actionButton = [[self class] newActionButtonWithFrame:NSMakeRect(0,
																	 expressionFrame.origin.y,
																	 expressionFrame.size.height,
																	 expressionFrame.size.height)];
	[actionButton setAutoresizingMask:(NSViewMaxXMargin | NSViewMinYMargin)];
	[memoryView insertActionItemsInMenu:[actionButton menu] atIndex:1];
	[[window contentView] addSubview:actionButton];
	[actionButton release];

	// set default state
	[memoryView selectSubviewForCPU:debug_cpu_get_visible_cpu(machine)];
	[memoryView setExpression:@"0"];
	[expressionField setStringValue:@"0"];
	[expressionField selectText:self];
	[subviewButton selectItemAtIndex:[subviewButton indexOfItemWithTag:[memoryView selectedSubviewIndex]]];
	[window makeFirstResponder:expressionField];
	[window setTitle:[NSString stringWithFormat:@"Memory: %@", [memoryView selectedSubviewName]]];

	// calculate the optimal size for everything
	{
		NSSize	desired = [NSScrollView frameSizeForContentSize:[memoryView maximumFrameSize]
										  hasHorizontalScroller:YES
											hasVerticalScroller:YES
													 borderType:[memoryScroll borderType]];
		[self cascadeWindowWithDesiredSize:desired forView:memoryScroll];
	}

	// don't forget the result
	return self;
}


- (void)dealloc {
	[super dealloc];
}


- (id <MAMEDebugViewExpressionSupport>)documentView {
	return memoryView;
}


- (IBAction)changeSubview:(id)sender {
	[memoryView selectSubviewAtIndex:[[sender selectedItem] tag]];
	[window setTitle:[NSString stringWithFormat:@"Memory: %@", [memoryView selectedSubviewName]]];
}

@end


//============================================================
//  MAMEDisassemblyViewer class
//============================================================

@implementation MAMEDisassemblyViewer

- (id)initWithMachine:(running_machine *)m console:(MAMEDebugConsole *)c {
	NSScrollView	*dasmScroll;
	NSView			*expressionContainer;
	NSPopUpButton	*actionButton, *subviewButton;
	NSRect			contentBounds, expressionFrame;

	if (!(self = [super initWithMachine:m title:@"Disassembly" console:c]))
		return nil;
	contentBounds = [[window contentView] bounds];

	// create the expression field
	expressionField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 100, 19)];
	[expressionField setAutoresizingMask:(NSViewWidthSizable | NSViewMaxXMargin | NSViewMinYMargin)];
	[expressionField setFont:[[MAMEDebugView class] defaultFont]];
	[expressionField setFocusRingType:NSFocusRingTypeNone];
	[expressionField setTarget:self];
	[expressionField setAction:@selector(doExpression:)];
	[expressionField setDelegate:self];
	expressionFrame = [expressionField frame];
	expressionFrame.size.width = (contentBounds.size.width - expressionFrame.size.height) / 2;
	[expressionField setFrameSize:expressionFrame.size];

	// create the subview popup
	subviewButton = [[NSPopUpButton alloc] initWithFrame:NSOffsetRect(expressionFrame,
																	  expressionFrame.size.width,
																	  0)];
	[subviewButton setAutoresizingMask:(NSViewWidthSizable | NSViewMinXMargin | NSViewMinYMargin)];
	[subviewButton setBezelStyle:NSShadowlessSquareBezelStyle];
	[subviewButton setFocusRingType:NSFocusRingTypeNone];
	[subviewButton setFont:[[MAMEDebugView class] defaultFont]];
	[subviewButton setTarget:self];
	[subviewButton setAction:@selector(changeSubview:)];
	[[subviewButton cell] setArrowPosition:NSPopUpArrowAtBottom];

	// create a container for the expression field and subview popup
	expressionFrame = NSMakeRect(expressionFrame.size.height,
								 contentBounds.size.height - expressionFrame.size.height,
								 contentBounds.size.width - expressionFrame.size.height,
								 expressionFrame.size.height);
	expressionContainer = [[NSView alloc] initWithFrame:expressionFrame];
	[expressionContainer setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
	[expressionContainer addSubview:expressionField];
	[expressionField release];
	[expressionContainer addSubview:subviewButton];
	[subviewButton release];
	[[window contentView] addSubview:expressionContainer];
	[expressionContainer release];

	// create the disassembly view
	dasmView = [[MAMEDisassemblyView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)
												  machine:machine
											   useConsole:NO];
	[dasmView insertSubviewItemsInMenu:[subviewButton menu] atIndex:0];
	dasmScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0,
																0,
																contentBounds.size.width,
																expressionFrame.origin.y)];
	[dasmScroll setDrawsBackground:YES];
	[dasmScroll setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
	[dasmScroll setHasHorizontalScroller:YES];
	[dasmScroll setHasVerticalScroller:YES];
	[dasmScroll setAutohidesScrollers:YES];
	[dasmScroll setBorderType:NSNoBorder];
	[dasmScroll setDocumentView:dasmView];
	[dasmView release];
	[[window contentView] addSubview:dasmScroll];
	[dasmScroll release];

	// create the action popup
	actionButton = [[self class] newActionButtonWithFrame:NSMakeRect(0,
																	 expressionFrame.origin.y,
																	 expressionFrame.size.height,
																	 expressionFrame.size.height)];
	[actionButton setAutoresizingMask:(NSViewMaxXMargin | NSViewMinYMargin)];
	[dasmView insertActionItemsInMenu:[actionButton menu] atIndex:1];
	[[window contentView] addSubview:actionButton];
	[actionButton release];

	// set default state
	[dasmView selectSubviewForCPU:debug_cpu_get_visible_cpu(machine)];
	[dasmView setExpression:@"curpc"];
	[expressionField setStringValue:@"curpc"];
	[expressionField selectText:self];
	[subviewButton selectItemAtIndex:[subviewButton indexOfItemWithTag:[dasmView selectedSubviewIndex]]];
	[window makeFirstResponder:expressionField];
	[window setTitle:[NSString stringWithFormat:@"Disassembly: %@", [dasmView selectedSubviewName]]];

	// calculate the optimal size for everything
	{
		NSSize	desired = [NSScrollView frameSizeForContentSize:[dasmView maximumFrameSize]
										  hasHorizontalScroller:YES
											hasVerticalScroller:YES
													 borderType:[dasmScroll borderType]];
		[self cascadeWindowWithDesiredSize:desired forView:dasmScroll];
	}

	// don't forget the result
	return self;
}


- (void)dealloc {
	[super dealloc];
}


- (id <MAMEDebugViewExpressionSupport>)documentView {
	return dasmView;
}


- (IBAction)changeSubview:(id)sender {
	[dasmView selectSubviewAtIndex:[[sender selectedItem] tag]];
	[window setTitle:[NSString stringWithFormat:@"Disassembly: %@", [dasmView selectedSubviewName]]];
}

@end


//============================================================
//  MAMEErrorLogViewer class
//============================================================

@implementation MAMEErrorLogViewer

- (id)initWithMachine:(running_machine *)m console:(MAMEDebugConsole *)c {
	NSScrollView	*logScroll;
	NSString		*title;

	title = [NSString stringWithFormat:@"Error Log: %@ [%@]",
									   [NSString stringWithUTF8String:m->gamedrv->description],
									   [NSString stringWithUTF8String:m->gamedrv->name]];
	if (!(self = [super initWithMachine:m title:title console:c]))
		return nil;

	// create the error log view
	logView = [[MAMEErrorLogView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100) machine:machine];
	logScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[logScroll setDrawsBackground:YES];
	[logScroll setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
	[logScroll setHasHorizontalScroller:YES];
	[logScroll setHasVerticalScroller:YES];
	[logScroll setAutohidesScrollers:YES];
	[logScroll setBorderType:NSNoBorder];
	[logScroll setDocumentView:logView];
	[logView release];
	[window setContentView:logScroll];
	[logScroll release];

	// calculate the optimal size for everything
	{
		NSSize	desired = [NSScrollView frameSizeForContentSize:[logView maximumFrameSize]
										  hasHorizontalScroller:YES
											hasVerticalScroller:YES
													 borderType:[logScroll borderType]];

		// this thing starts with no content, so its prefered height may be very small
		desired.height = MAX(desired.height, 240);
		[self cascadeWindowWithDesiredSize:desired forView:logScroll];
	}

	// don't forget the result
	return self;
}


- (void)dealloc {
	[super dealloc];
}

@end