~ubuntu-branches/ubuntu/raring/vice/raring

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
/*
 * ui.c - Windows user interface.
 *
 * Written by
 *  Ettore Perazzoli <ettore@comm2000.it>
 *  Tibor Biczo <crown@mail.matav.hu>
 *  Andreas Boose <viceteam@t-online.de>
 *
 * This file is part of VICE, the Versatile Commodore Emulator.
 * See README for copyright notice.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307  USA.
 *
 */

#include "vice.h"

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>
#ifdef HAVE_COMMCTRL_H
#include <commctrl.h>
#endif

#include "attach.h"
#include "autostart.h"
#include "archdep.h"
#include "charset.h"
#include "clipboard.h"
#include "debug.h"
#include "drive.h"
#include "drivecpu.h"
#include "event.h"
#include "fullscrn.h"
#include "imagecontents.h"
#include "interrupt.h"
#include "intl.h"
#include "kbd.h"
#include "kbdbuf.h"
#include "lib.h"
#include "log.h"
#include "machine.h"
#include "maincpu.h"
#include "mem.h"
#include "monitor.h"
#include "mousedrv.h"
#include "network.h"
#include "res.h"
#include "resources.h"
#include "system.h"
#include "translate.h"
#include "types.h"
#include "ui.h"
#include "uiattach.h"
#include "uiperipheral.h"
#include "uicmdline.h"
#include "uidatasette.h"
#include "uievent.h"
#include "uifliplist.h"
#include "uihelp.h"
#include "uijoystick.h"
#include "uikeyboard.h"
#include "uilib.h"
#include "uimediafile.h"
#include "uinetwork.h"
#include "uiquicksnapshot.h"
#include "uiram.h"
#include "uirs232.h"
#include "uisnapshot.h"
#include "uisound.h"
#include "uispeed.h"
#include "util.h"
#include "version.h"
#include "videoarch.h"
#include "vsync.h"
#include "winmain.h"
#include "statusbar.h"


extern char *intl_speed_at_text;

#define countof(array) (sizeof(array) / sizeof((array)[0]))

#ifndef VK_OEM_PLUS
#define VK_OEM_PLUS 0xbb
#endif

static TCHAR *hwnd_titles[2];

/* Exposure handler.  */
HWND window_handles[2];
int number_of_windows = 0;
int window_canvas_xsize[2];
int window_canvas_ysize[2];

static HACCEL ui_accelerator;

/* Forward prototypes.  */
static long CALLBACK dummywindowproc(HWND window, UINT msg,
                                     WPARAM wparam, LPARAM lparam);
static long CALLBACK window_proc(HWND window, UINT msg,
                                 WPARAM wparam, LPARAM lparam);

/* List of resources that can be grayed out from the menus.  */
static const ui_menu_toggle_t grayed_list[] = {
#ifdef HAVE_TFE
/*    { "ETHERNET_DISABLED", IDM_TFE_SETTINGS }, */
#endif /* #ifdef HAVE_TFE */
    { NULL, 0 }
};

/* List of resources that can be switched on and off from the menus.  */
static const ui_menu_toggle_t toggle_list[] = {
    { "Sound", IDM_TOGGLE_SOUND },
    { "DriveTrueEmulation", IDM_TOGGLE_DRIVE_TRUE_EMULATION },
    { "WarpMode", IDM_TOGGLE_WARP_MODE },
    { "VirtualDevices", IDM_TOGGLE_VIRTUAL_DEVICES },
    { "SaveResourcesOnExit", IDM_TOGGLE_SAVE_SETTINGS_ON_EXIT },
    { "ConfirmOnExit", IDM_TOGGLE_CONFIRM_ON_EXIT },
    { "FullScreenEnabled", IDM_TOGGLE_FULLSCREEN },
    { "AlwaysOnTop", IDM_TOGGLE_ALWAYSONTOP },
    { "KeySetEnable", IDM_JOYKEYS_TOGGLE },
#ifdef DEBUG
    { "MainCPU_TRACE", IDM_TOGGLE_MAINCPU_TRACE },
    { "Drive0CPU_TRACE", IDM_TOGGLE_DRIVE0CPU_TRACE },
    { "Drive1CPU_TRACE", IDM_TOGGLE_DRIVE1CPU_TRACE },
#endif
    { NULL, 0 }
};

/*  List of resources which can have multiple mutual exclusive menu entries. */

static const ui_res_possible_values_t RefreshRateValues[] = {
    { 0, IDM_REFRESH_RATE_AUTO },
    { 1, IDM_REFRESH_RATE_1 },
    { 2, IDM_REFRESH_RATE_2 },
    { 3, IDM_REFRESH_RATE_3 },
    { 4, IDM_REFRESH_RATE_4 },
    { 5, IDM_REFRESH_RATE_5 },
    { 6, IDM_REFRESH_RATE_6 },
    { 7, IDM_REFRESH_RATE_7 },
    { 8, IDM_REFRESH_RATE_8 },
    { 9, IDM_REFRESH_RATE_9 },
    { 10, IDM_REFRESH_RATE_10 },
    { -1, 0 }
};

static ui_res_possible_values_t SpeedValues[] = {
    { 0, IDM_MAXIMUM_SPEED_NO_LIMIT },
    { 10, IDM_MAXIMUM_SPEED_10 },
    { 20, IDM_MAXIMUM_SPEED_20 },
    { 50, IDM_MAXIMUM_SPEED_50 },
    { 100, IDM_MAXIMUM_SPEED_100 },
    { 200, IDM_MAXIMUM_SPEED_200 },
    { -1, 0 }
};

static ui_res_possible_values_t RecordingOptions[] = {
    { EVENT_START_MODE_FILE_SAVE, IDM_EVENT_START_MODE_SAVE },
    { EVENT_START_MODE_FILE_LOAD, IDM_EVENT_START_MODE_LOAD },
    { EVENT_START_MODE_RESET, IDM_EVENT_START_MODE_RESET },
    { EVENT_START_MODE_PLAYBACK, IDM_EVENT_START_MODE_PLAYBACK },
    { -1, 0 }
};

static const ui_res_possible_values_t SyncFactor[] = {
    { MACHINE_SYNC_PAL, IDM_SYNC_FACTOR_PAL },
    { MACHINE_SYNC_NTSC, IDM_SYNC_FACTOR_NTSC },
    { MACHINE_SYNC_NTSCOLD, IDM_SYNC_FACTOR_NTSCOLD },
    { -1, 0 }
};

#ifdef DEBUG
static const ui_res_possible_values_t TraceMode[] = {
    { DEBUG_NORMAL, IDM_DEBUG_MODE_NORMAL },
    { DEBUG_SMALL, IDM_DEBUG_MODE_SMALL },
    { DEBUG_HISTORY, IDM_DEBUG_MODE_HISTORY },
    { DEBUG_AUTOPLAY, IDM_DEBUG_MODE_AUTOPLAY },
    { -1, 0 }
};
#endif

static const ui_res_value_list_t value_list[] = {
    { "RefreshRate", RefreshRateValues, 0 },
    { "Speed", SpeedValues, IDM_MAXIMUM_SPEED_CUSTOM },
    { "MachineVideoStandard", SyncFactor, 0 },
    { "EventStartMode", RecordingOptions, 0 },
#ifdef DEBUG
    { "TraceMode", TraceMode, 0},
#endif
    { NULL, NULL, 0 }
};

static const struct {
    char *lang_code;
    UINT item_id;
} ui_lang_menu_entries [] = {
    { "en", IDM_LANG_EN },
    { "de", IDM_LANG_DE },
    { "fr", IDM_LANG_FR },
    { "hu", IDM_LANG_HU },
    { "it", IDM_LANG_IT },
    { "nl", IDM_LANG_NL },
    { "pl", IDM_LANG_PL },
    { "sv", IDM_LANG_SV },
    { NULL, 0}
};

ui_menu_translation_table_t monitor_trans_popup_table[] = {
    { 1, IDS_MP_FILE },
    { 1, IDS_MP_DEBUG },
    { 1, IDS_MP_VIEW },
    { 1, IDS_MP_WINDOW },
    { 0, 0 }
};

ui_popup_translation_table_t monitor_trans_item_table[] = {
    { IDM_MON_OPEN, IDS_MI_MON_OPEN },
    { IDM_MON_SAVE, IDS_MI_MON_SAVE },
    { IDM_MON_PRINT, IDS_MI_MON_PRINT },
    { IDM_EXIT, IDS_MI_MON_EXIT },
    { IDM_MON_STOP_DEBUG, IDS_MI_MON_STOP_DEBUG },
    { IDM_MON_STOP_EXEC, IDS_MI_MON_STOP_EXEC },
    { IDM_MON_STEP_INTO, IDS_MI_MON_STEP_INTO },
    { IDM_MON_STEP_OVER, IDS_MI_MON_STEP_OVER },
    { IDM_MON_SKIP_RETURN, IDS_MI_MON_SKIP_RETURN },
    { IDM_MON_GOTO_CURSOR, IDS_MI_MON_GOTO_CURSOR },
    { IDM_MON_EVAL, IDS_MI_MON_EVAL },
    { IDM_MON_CURRENT, IDS_MI_MON_CURRENT },
    { IDM_MON_WND_EVAL, IDS_MI_MON_WND_EVAL },
    { IDM_MON_WND_REG, IDS_MI_MON_WND_REG },
    { IDM_MON_WND_MEM, IDS_MI_MON_WND_MEM },
    { IDM_MON_WND_DIS, IDS_MI_MON_WND_DIS },
    { IDM_MON_WND_CONSOLE, IDS_MI_MON_WND_CONSOLE },
    { IDM_MON_COMPUTER, IDS_MI_MON_COMPUTER },
    { IDM_MON_DRIVE8, IDS_MI_MON_DRIVE8 },
    { IDM_MON_DRIVE9, IDS_MI_MON_DRIVE9 },
    { IDM_MON_CASCADE, IDS_MI_MON_CASCADE },
    { IDM_MON_TILE_VERT, IDS_MI_MON_TILE_VERT },
    { IDM_MON_TILE_HORIZ, IDS_MI_MON_TILE_HORIZ },
    { IDM_MON_ARRANGE_ICONS, IDS_MI_MON_ARRANGE_ICONS },
    { 0, 0 }
};

/* ------------------------------------------------------------------------ */
static HWND main_hwnd;

static int emu_menu;

static int pause_pending;

static ui_menu_translation_table_t *menu_translation_table;
static ui_popup_translation_table_t *popup_translation_table;

void ui_register_translation_tables(ui_menu_translation_table_t *menu_table, ui_popup_translation_table_t *popup_table)
{
    menu_translation_table = menu_table;
    popup_translation_table = popup_table;
    ui_update_menu();
}

/* Initialize the UI before setting all the resource values.  */
int ui_init(int *argc, char **argv)
{
    WNDCLASS window_class;

    switch (machine_class) {
      case VICE_MACHINE_C64:
        emu_menu = IDR_MENUC64;
        break;
      case VICE_MACHINE_C64DTV:
        emu_menu = IDR_MENUC64DTV;
        break;
      case VICE_MACHINE_C128:
        emu_menu = IDR_MENUC128;
        break;
      case VICE_MACHINE_VIC20:
        emu_menu = IDR_MENUVIC;
        break;
      case VICE_MACHINE_PET:
        emu_menu = IDR_MENUPET;
        break;
      case VICE_MACHINE_PLUS4:
        emu_menu = IDR_MENUPLUS4;
        break;
      case VICE_MACHINE_CBM2:
        emu_menu = IDR_MENUCBM2;
        break;
      default:
        log_debug("UI: No menu entries for this machine defined!");
        log_debug("UI: Using C64 type UI menues.");
        emu_menu = IDR_MENUC64;
    }

    /* Register the window class.  */
    window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    window_class.lpfnWndProc = window_proc;
    window_class.cbClsExtra = 0;
    window_class.cbWndExtra = 0;
    window_class.hInstance = winmain_instance;
    window_class.hIcon = LoadIcon(winmain_instance,
                                  MAKEINTRESOURCE(IDI_ICON1));
    window_class.hCursor = LoadCursor(NULL, IDC_ARROW);
    window_class.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(0, 0, 0) + 1);
    window_class.lpszMenuName = MAKEINTRESOURCE(emu_menu);
    window_class.lpszClassName = APPLICATION_CLASS;
    RegisterClass(&window_class);


    window_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    window_class.lpfnWndProc = dummywindowproc;
    window_class.cbClsExtra = 0;
    window_class.cbWndExtra = 0;
    window_class.hInstance = winmain_instance;
    window_class.hIcon = LoadIcon(winmain_instance,
                                  MAKEINTRESOURCE(IDI_ICON1));
    window_class.hCursor = LoadCursor(NULL, IDC_ARROW);
    window_class.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(0, 0, 0) + 1);
    window_class.lpszMenuName = NULL;
    window_class.lpszClassName = APPLICATION_CLASS_MAIN;
    RegisterClass(&window_class);

    /* Create the main window.  Notice that we are not going to
       `ShowWindow()' it yet; this will be done as soon as the video module
       requires us to do so.  This is needed both because the video module
       needs an application window to be created to initialize itself, and
       because this might allow us to support more than one emulation window
       in the future.  */
    main_hwnd = CreateWindow(APPLICATION_CLASS_MAIN,
                             TEXT("No title"), /* (for now) */
                             WS_OVERLAPPED | WS_CLIPCHILDREN | WS_BORDER
                             | WS_DLGFRAME| WS_SYSMENU | WS_MINIMIZEBOX
                             | WS_MAXIMIZEBOX,
                             CW_USEDEFAULT,
                             CW_USEDEFAULT,
                             CW_USEDEFAULT,
                             CW_USEDEFAULT,
                             NULL,
                             NULL,
                             winmain_instance,
                             NULL);
    InitCommonControls();

    number_of_windows = 0;

    statusbar_create_brushes();

    return 0;
}

void ui_shutdown(void)
{
   statusbar_delete_brushes();
   uikeyboard_shutdown();
}

/* Initialize the UI after setting all the resource values.  */
int ui_init_finish(void)
{
    ui_accelerator = uikeyboard_create_accelerator_table();
    ui_fullscreen_init();
    atexit(ui_exit);
    return 0;
}

int ui_init_finalize(void)
{
    return 0;
}

/* Exit.  */
void ui_exit(void)
{
    int i;

    for (i = 0; i < number_of_windows; i++)
        lib_free(hwnd_titles[i]);

    if (ui_accelerator) {
        DestroyAcceleratorTable(ui_accelerator);
    }

    ui_fullscreen_shutdown();
    uilib_shutdown();
}

static void ui_translate_menu_popups(HMENU menu, ui_popup_translation_table_t *trans_table)
{
    int pos1 = -1;
    int pos2 = -1;
    int pos3 = -1;

    HMENU menu1 = NULL;
    HMENU menu2 = NULL;
    HMENU menu3 = NULL;

    int i = 0;

    if (trans_table == NULL)
        return;

    while (trans_table[i].level != 0)
    {
        switch (trans_table[i].level)
        {
            case 1:
                menu1 = NULL;
                while (menu1 == NULL)
                {
                    pos1++;
                    menu1 = GetSubMenu(menu, pos1);
                }
                if (trans_table[i].ids != 0)
                    ModifyMenu(menu, (UINT)pos1, MF_BYPOSITION | MF_STRING | MF_POPUP, (UINT)menu1, translate_text(trans_table[i].ids));
                pos2 = -1;
                pos3 = -1;
                break;
            case 2:
                menu2 = NULL;
                while (menu2 == NULL)
                {
                    pos2++;
                    menu2 = GetSubMenu(menu1, pos2);
                }
                ModifyMenu(menu1, (UINT)pos2, MF_BYPOSITION | MF_STRING | MF_POPUP, (UINT)menu2, translate_text(trans_table[i].ids));
                pos3 = -1;
                break;
            case 3:
                menu3 = NULL;
                while (menu3 == NULL)
                {
                    pos3++;
                    menu3 = GetSubMenu(menu2, pos3);
                }
                ModifyMenu(menu2, (UINT)pos3, MF_BYPOSITION | MF_STRING | MF_POPUP, (UINT)menu3, translate_text(trans_table[i].ids));
                break;
        }
        i++;
    }
}

static void ui_translate_menu_items(HMENU menu, ui_menu_translation_table_t *trans_table)
{
    int i = 0;

    if (trans_table == NULL)
        return;

    while (trans_table[i].idm != 0)
    {
        ModifyMenu(menu, trans_table[i].idm, MF_BYCOMMAND | MF_STRING, trans_table[i].idm, translate_text(trans_table[i].ids));
        i++;
    }
}

void ui_translate_monitor_menu(HMENU menu)
{
  ui_translate_menu_popups(menu, (ui_popup_translation_table_t *)monitor_trans_popup_table);
  ui_translate_menu_items(menu, (ui_menu_translation_table_t *)monitor_trans_item_table);
}

/*  Create a Window for the emulation.  */
HWND ui_open_canvas_window(const char *title, unsigned int width,
                           unsigned int height)
{
    HWND hwnd;
    int xpos, ypos;
    HMENU menu;

    resources_get_int_sprintf("Window%dXpos", &xpos, number_of_windows);
    resources_get_int_sprintf("Window%dYpos", &ypos, number_of_windows);

    hwnd_titles[number_of_windows] = system_mbstowcs_alloc(title);
    hwnd = CreateWindow(APPLICATION_CLASS,
                            hwnd_titles[number_of_windows],
                            WS_OVERLAPPED | WS_CLIPCHILDREN | WS_BORDER
                            | WS_DLGFRAME | WS_SYSMENU | WS_MINIMIZEBOX
                            | WS_MAXIMIZEBOX,
                            xpos,
                            ypos,
                            CW_USEDEFAULT,
                            CW_USEDEFAULT,
                            NULL,
                            NULL,
                            winmain_instance,
                            NULL);

    if (hwnd == NULL)
        log_debug("Window creation failed");

    window_handles[number_of_windows] = hwnd;
    window_canvas_xsize[number_of_windows] = width;
    window_canvas_ysize[number_of_windows] = height;
    number_of_windows++;

    statusbar_create(hwnd);

    ui_resize_canvas_window(hwnd, width, height);

    menu=LoadMenu(winmain_instance, MAKEINTRESOURCE(emu_menu));
    ui_translate_menu_items(menu, menu_translation_table);
    ui_translate_menu_popups(menu, popup_translation_table);
    SetMenu(hwnd,menu);
    uikeyboard_menu_shortcuts(menu);
    ShowWindow(hwnd, winmain_cmd_show);
    return hwnd;

}

void ui_update_menu()
{
HMENU menu;
int   i;

    menu = LoadMenu(winmain_instance, MAKEINTRESOURCE(emu_menu));
    if (menu_translation_table != NULL)
    {
        ui_translate_menu_items(menu, menu_translation_table);
        ui_translate_menu_popups(menu, popup_translation_table);
        uikeyboard_menu_shortcuts(menu);
    }
    for (i = 0; i < number_of_windows; i++) {
        SetMenu(window_handles[i], menu);
    }
}

/* Resize `w' so that the client rectangle is of the requested size.  */
void ui_resize_canvas_window(HWND w, unsigned int width, unsigned int height)
{
    RECT wrect;
    int window_index;
    WINDOWPLACEMENT place;

/*  TODO:
    We should store the windowplacement when the window is
    maximized and we switch to fullscreen, and resume it when
    we are switching back to windowed mode... If the canvas
    size should be changed while in fullscreen (mode changes whatever)
    then this cached data should be updated....
*/
//    if (IsFullscreenEnabled()) return;

    for (window_index = 0; window_index < number_of_windows; window_index++) {
        if (window_handles[window_index] == w)
            break;
    }
    place.length = sizeof(WINDOWPLACEMENT);
    GetWindowPlacement(w, &place);

    window_canvas_xsize[window_index] = width;
    window_canvas_ysize[window_index] = height;

    GetClientRect(w, &wrect);
    ClientToScreen(w, (LPPOINT)&wrect);
    ClientToScreen(w, ((LPPOINT)&wrect) + 1);
    wrect.right = wrect.left + width;
    wrect.bottom = wrect.top + height + statusbar_get_status_height();
    //status_height;
    AdjustWindowRect(&wrect, WS_OVERLAPPED|WS_BORDER|WS_DLGFRAME, TRUE);
    if (place.showCmd == SW_SHOWNORMAL) {
        MoveWindow(w,
                   wrect.left,
                   wrect.top,
                   wrect.right - wrect.left,
                   wrect.bottom - wrect.top,
                   TRUE);
    } else {
        place.rcNormalPosition.right = place.rcNormalPosition.left
                                       + wrect.right - wrect.left;
        place.rcNormalPosition.bottom = place.rcNormalPosition.top
                                        + wrect.bottom - wrect.top;
        SetWindowPlacement(w, &place);
        InvalidateRect(w, NULL, FALSE);
    }
}

void ui_set_alwaysontop(int alwaysontop)
{
    int i;

    for (i = 0; i < number_of_windows; i++)
        SetWindowPos(window_handles[i], alwaysontop ? HWND_TOPMOST : HWND_NOTOPMOST,
                        0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}

/* Update all the menus according to the current settings.  */
void ui_update_menus(void)
{
}

static const ui_menu_toggle_t *machine_specific_toggles = NULL;
static const ui_res_value_list_t *machine_specific_values = NULL;

void ui_register_menu_toggles(const ui_menu_toggle_t *toggles)
{
    machine_specific_toggles = toggles;
}

void ui_register_res_values(const ui_res_value_list_t *valuelist)
{
    machine_specific_values = valuelist;
}

static void update_menus(HWND hwnd)
{
    HMENU menu = GetMenu(hwnd);
    unsigned int i, j;
    int value;
    int result;
    const char *lang;

    for (i = 0; grayed_list[i].name != NULL; i++) {
        resources_get_int(grayed_list[i].name, &value);
        EnableMenuItem(menu, grayed_list[i].item_id,
                      value ? MF_GRAYED : MF_ENABLED);
    }
    
    for (i = 0; toggle_list[i].name != NULL; i++) {
        resources_get_int(toggle_list[i].name, &value);
        CheckMenuItem(menu, toggle_list[i].item_id,
                      value ? MF_CHECKED : MF_UNCHECKED);
    }
    
    if (machine_specific_toggles) {
        for (i = 0; machine_specific_toggles[i].name != NULL; i++) {
            resources_get_int(machine_specific_toggles[i].name, &value);
            CheckMenuItem(menu, machine_specific_toggles[i].item_id,
                          value ? MF_CHECKED : MF_UNCHECKED);
        }
    }

    for (i = 0; value_list[i].name != NULL; i++) {
        result = resources_get_int(value_list[i].name, &value);
        if (result == 0) {
            unsigned int checked = 0;

            CheckMenuItem(menu, value_list[i].default_item_id, MF_UNCHECKED);
            for (j = 0; value_list[i].vals[j].item_id != 0; j++) {
                if (value == value_list[i].vals[j].value && !checked) {
                    CheckMenuItem(menu, value_list[i].vals[j].item_id,
                                  MF_CHECKED);
                    checked = 1;
                } else {
                    CheckMenuItem(menu, value_list[i].vals[j].item_id,
                                  MF_UNCHECKED);
                }
            }
            if (checked == 0 && value_list[i].default_item_id > 0)
                CheckMenuItem(menu, value_list[i].default_item_id, MF_CHECKED);
        }
    }

    if (machine_specific_values) {
        for (i = 0; machine_specific_values[i].name != NULL; i++) {
            result = resources_get_int(machine_specific_values[i].name, &value);
            if (result == 0) {
                for (j = 0; machine_specific_values[i].vals[j].item_id != 0;
                    j++) {
                    if (value == machine_specific_values[i].vals[j].value) {
                        CheckMenuItem(menu,
                                      machine_specific_values[i].vals[j].item_id,
                                      MF_CHECKED);
                    } else {
                        CheckMenuItem(menu,
                                      machine_specific_values[i].vals[j].item_id,
                                      MF_UNCHECKED);
                    }
                }
            }
        }
    }
    CheckMenuItem(menu, IDM_PAUSE,
                  ui_emulation_is_paused() ? MF_CHECKED : MF_UNCHECKED);

    resources_get_string("Language", &lang);
    for (i = 0; (ui_lang_menu_entries[i].lang_code != NULL)
        && (i < countof(ui_lang_menu_entries)); i++) {
        if (strcmp(lang, ui_lang_menu_entries[i].lang_code) == 0) {
            CheckMenuItem(menu, ui_lang_menu_entries[i].item_id, MF_CHECKED);
        } else {
            CheckMenuItem(menu, ui_lang_menu_entries[i].item_id, MF_UNCHECKED);
        }
    }

}

static void ui_set_language(unsigned int lang_id)
{
    unsigned int i;

    for (i = 0; (ui_lang_menu_entries[i].lang_code != NULL)
        && (i < countof(ui_lang_menu_entries)); i++) {
        if (ui_lang_menu_entries[i].item_id == lang_id) {
            resources_set_string("Language", ui_lang_menu_entries[i].lang_code);
            break;
        }
    }
}

/* ------------------------------------------------------------------------- */

static ui_machine_specific_t ui_machine_specific = NULL;

void ui_register_machine_specific(ui_machine_specific_t func)
{
    ui_machine_specific = func;
}

/* ------------------------------------------------------------------------- */

/* Report an error to the user (`printf()' style).  */
void ui_error(const char *format, ...)
{
    char *tmp;
    TCHAR *st;
    va_list args;

    va_start(args, format);
    tmp = lib_mvsprintf(format, args);
    va_end(args);

    log_debug(tmp);
    st = system_mbstowcs_alloc(tmp);
    ui_messagebox(st, translate_text(IDS_VICE_ERROR), MB_OK | MB_ICONSTOP);
    system_mbstowcs_free(st);
    vsync_suspend_speed_eval();
    lib_free(tmp);
}

/* Report an error to the user (one string).  */
void ui_error_string(const char *text)
{
    TCHAR *st;

    log_debug(text);
    st = system_mbstowcs_alloc(text);
    ui_messagebox(st, translate_text(IDS_VICE_ERROR), MB_OK | MB_ICONSTOP);
    system_mbstowcs_free(st);
}

/* Report a message to the user (`printf()' style).  */
void ui_message(const char *format, ...)
{
    char *tmp;
    TCHAR *st;
    va_list args;

    va_start(args, format);
    tmp = lib_mvsprintf(format, args);
    va_end(args);

    st = system_mbstowcs_alloc(tmp);
    ui_messagebox(st, translate_text(IDS_VICE_INFORMATION), MB_OK | MB_ICONASTERISK);
    system_mbstowcs_free(st);
    vsync_suspend_speed_eval();
    lib_free(tmp);
}

/* Let the user browse for a filename */
char *ui_get_file(const char *format,...)
{
    char *tmp;
    char *st;
    va_list args;

    va_start(args, format);
    tmp = lib_mvsprintf(format, args);
    va_end(args);

    st = uilib_select_file(NULL, tmp, UILIB_FILTER_ALL,
                                UILIB_SELECTOR_TYPE_FILE_LOAD,
                                UILIB_SELECTOR_STYLE_DISK);
    lib_free(tmp);

    return st;
}

/* Handle the "CPU JAM" case.  */
ui_jam_action_t ui_jam_dialog(const char *format,...)
{
    char *txt, *txt2;
    TCHAR *st;
    int ret;

    va_list ap;
    va_start(ap, format);
    txt = lib_mvsprintf(format, ap);
    txt2 = lib_msprintf(translate_text(IDS_START_MONITOR), txt);
    st = system_mbstowcs_alloc(txt2);
    ret = ui_messagebox(st, translate_text(IDS_VICE_CPU_JAM), MB_YESNOCANCEL);
    system_mbstowcs_free(st);
    lib_free(txt2);
    lib_free(txt);
    switch (ret) {
        case IDYES:
            return UI_JAM_MONITOR;
        case IDNO:
            return UI_JAM_HARD_RESET;
        case IDCANCEL:
            return UI_JAM_NONE;
    }
    return UI_JAM_NONE;
//    UI_JAM_RESET, UI_JAM_HARD_RESET, UI_JAM_MONITOR
}

/* Handle the "Do you want to extend the disk image to 40-track format"?
   dialog.  */
int ui_extend_image_dialog(void)
{
    int ret;

    ret = ui_messagebox(translate_text(IDS_EXTEND_TO_40_TRACKS),
                        translate_text(IDS_VICE_QUESTION), MB_YESNO | MB_ICONQUESTION);
    return ret == IDYES;
}

/* ------------------------------------------------------------------------- */
static int is_paused = 0;

static void pause_trap(WORD addr, void *data)
{
    ui_display_paused(1);
    vsync_suspend_speed_eval();
    while (is_paused)
    {
        Sleep(10);
        ui_dispatch_next_event();
    }
}

void ui_pause_emulation(void)
{
    if (network_connected())
        return;

    is_paused = is_paused ? 0 : 1;
    if (is_paused) {
        interrupt_maincpu_trigger_trap(pause_trap, 0);
    } else {
        ui_display_paused(pause_pending);
    }
}

int ui_emulation_is_paused(void)
{
    return is_paused;
}

/* ------------------------------------------------------------------------- */
/* Display the current emulation speed.  */
static int statustext_display_time = 0;

void ui_display_speed(float percent, float framerate, int warp_flag)
{
    char *buf, *title;
    TCHAR *st_buf;
    int index;

    for (index = 0; index < number_of_windows; index++) {
        title = system_wcstombs_alloc(hwnd_titles[index]);

        buf = lib_msprintf(intl_speed_at_text,
                           title, (int)(percent + .5),
                           (int)(framerate + .5),
                           warp_flag ? " (warp)" : "");
        system_wcstombs_free(title);
        st_buf = system_mbstowcs_alloc(buf);
        SetWindowText(window_handles[index], st_buf);
        system_mbstowcs_free(st_buf);

        lib_free(buf);
    }
    
    if (statustext_display_time > 0) {
        statustext_display_time--;
        if (statustext_display_time == 0)
            statusbar_setstatustext("");
    }
}


void ui_display_statustext(const char *text, int fade_out)
{
    statusbar_setstatustext(text);
    if (fade_out > 0)
        statustext_display_time = 5;
    else
        statustext_display_time = 0;
}


/* ------------------------------------------------------------------------- */
/* Dispay the drive status.  */
void ui_enable_drive_status(ui_drive_enable_t enable, int *drive_led_color)
{
    statusbar_enable_drive_status(enable,drive_led_color);
}

/* Toggle displaying of the drive track.  */
/* drive_base is either 8 or 0 depending on unit or drive display.
   Dual drives display drive 0: and 1: instead of unit 8: and 9: */
void ui_display_drive_track(unsigned int drive_number, unsigned int drive_base,
                            unsigned int half_track_number)
{
    double track_number = (double)half_track_number / 2.0;

    statusbar_display_drive_track(drive_number, drive_base, track_number);
}

/* Toggle displaying of the drive LED.  */
void ui_display_drive_led(int drivenum, unsigned int led_pwm1,
                          unsigned int led_pwm2)
{
    statusbar_display_drive_led(drivenum, led_pwm1);
}

/* display current image */
void ui_display_drive_current_image(unsigned int drivenum, const char *image)
{
    char *directory_name, *image_name, *text;
    char device_str[4];

    if (image == NULL || image[0] == 0) {
        text = lib_msprintf(translate_text(IDS_DETACHED_DEVICE_S), 
                           itoa(drivenum + 8, device_str, 10));
    } else {
        util_fname_split(image, &directory_name, &image_name);
        text = lib_msprintf(translate_text(IDS_ATTACHED_S_TO_DEVICE_S), image_name,
            itoa(drivenum+8, device_str, 10));
        lib_free(image_name);
        lib_free(directory_name);
    }

    ui_display_statustext(text, 1);
    lib_free(text);
}


/* ------------------------------------------------------------------------- */
/* Dispay the tape status.  */
void ui_set_tape_status(int tape_status)
{
    statusbar_set_tape_status(tape_status);
}

void ui_display_tape_motor_status(int motor)
{   
    statusbar_display_tape_motor_status(motor);
}

void ui_display_tape_control_status(int control)
{
    statusbar_display_tape_control_status(control);
}

void ui_display_tape_counter(int counter)
{
    statusbar_display_tape_counter(counter);
}

/* display the attched tape image */
void ui_display_tape_current_image(const char *image)
{
    char *directory_name, *image_name, *text;

    if (image == NULL || image[0] == 0) {
        text = lib_stralloc(translate_text(IDS_DETACHED_TAPE));
    } else {
        util_fname_split(image, &directory_name, &image_name);
        text = lib_msprintf(translate_text(IDS_ATTACHED_TAPE_S), image_name);
        lib_free(image_name);
        lib_free(directory_name);
    }

    ui_display_statustext(text, 1);
    lib_free(text);
}

/* ------------------------------------------------------------------------- */
/* Dispay the recording/playback status.  */
void ui_display_recording(int recording_status)
{
    if (recording_status)
        statusbar_event_status(EVENT_RECORDING);
    else
        statusbar_event_status(EVENT_OFF);
}

void ui_display_playback(int playback_status, char *version)
{
    char st[256];

    if (playback_status) {
        statusbar_event_status(EVENT_PLAYBACK);
        if (version == NULL || version[0] == 0)
            sprintf(st, translate_text(IDS_HISTORY_RECORDED_UNKNOWN));
        else 
            sprintf(st, translate_text(IDS_HISTORY_RECORDED_VICE_S), version);
        ui_display_statustext(st, 1);
    } else {
        statusbar_event_status(EVENT_OFF);
    }
}

void ui_display_event_time(unsigned int current, unsigned int total)
{
    statusbar_event_time(current, total);
}

/* ------------------------------------------------------------------------- */
/* Dispay the joystick status.  */
static BYTE ui_joyport[3] = { 0, 0, 0 };

void ui_display_joyport(BYTE *joyport)
{
    if (ui_joyport[1] != joyport[1] || ui_joyport[2] != joyport[2]) {
        ui_joyport[1] = joyport[1];
        ui_joyport[2] = joyport[2];
        statusbar_display_joyport(ui_joyport);
    }
}


/* ------------------------------------------------------------------------- */
/* Toggle displaying of paused state.  */
void ui_display_paused(int flag)
{
    int index;
    char *buf, *title;
    TCHAR *st_buf;

    for (index = 0; index < number_of_windows; index++) {
        title = system_wcstombs_alloc(hwnd_titles[index]);
        if (flag) {
            buf = lib_msprintf("%s (%s: %s%i)", title, translate_text(IDS_PAUSED), translate_text(IDS_FRAME_NUMBER), vsync_frame_counter);
        } else {
            buf = lib_msprintf("%s (%s)", title, translate_text(IDS_RESUMED));
        }
        system_wcstombs_free(title);
        st_buf = system_mbstowcs_alloc(buf);
        SetWindowText(window_handles[index], st_buf);
        system_mbstowcs_free(st_buf);
        lib_free(buf);
    }
}

ui_button_t ui_ask_confirmation(const char *title, const char *text)
{
    return UI_BUTTON_NONE;
}

/* ------------------------------------------------------------------------ */

/* Return the main window handler.  */
HWND ui_get_main_hwnd(void)
{
    if (window_handles[0] == NULL)
        return main_hwnd;

    return window_handles[0];
}

/* Dispatch the next pending event, if any.  Otherwise, just return.  */
void ui_dispatch_next_event(void)
{
    MSG msg;

    if (!GetMessage(&msg, NULL, 0, 0))
        exit(msg.wParam);
    if (ui_accelerator) {
        if (!TranslateAccelerator(msg.hwnd, ui_accelerator, &msg)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    } else {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

/* Dispatch all the current pending events; return as soon as no more events
   are pending.  */
void ui_dispatch_events(void)
{
    MSG msg;

    /* this function is called once a frame, so this
       handles single frame advance */
    if (pause_pending) {
        ui_pause_emulation();
        pause_pending = 0;
    }

    while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
        ui_dispatch_next_event();
}

/* ------------------------------------------------------------------------ */

static void reset_dialog_proc(WPARAM wparam)
{
    vsync_suspend_speed_eval();
/*
    if (ui_messagebox("Do you really want to reset the emulated machine?",
                      ((wparam & 0xffff) == IDM_RESET_HARD ? "Hard reset"
                      : "Soft reset"),
                      MB_YESNO | MB_ICONQUESTION) == IDYES)
*/
    {
        if ((wparam & 0xffff) == IDM_RESET_HARD) {
            machine_trigger_reset(MACHINE_RESET_MODE_HARD);
        } else {
            machine_trigger_reset(MACHINE_RESET_MODE_SOFT);
        }
    }
}

/* ------------------------------------------------------------------------ */

static void ui_copy_clipboard(HWND window)
{
    BOOL clipboard_is_open = FALSE;
    char * text = NULL;
    HGLOBAL globaltext = NULL;

    do {
        char * p;

        if ( ! OpenClipboard(window) ) {
            break;
        }
        clipboard_is_open = TRUE;

        if ( ! EmptyClipboard() ) {
            break;
        }

        text = clipboard_read_screen_output("\r\n");
        if (text == NULL) {
            break;
        }

        globaltext = GlobalAlloc(GMEM_DDESHARE, strlen(text) + 1);
        if (globaltext == NULL) {
            break;
        }

        p = GlobalLock(globaltext);
        strcpy(p, text);

        SetClipboardData(CF_TEXT, globaltext);

    } while (0);

    if (globaltext) {
        GlobalUnlock(globaltext);
    }

    if (text) {
        lib_free(text);
    }

    if (clipboard_is_open) {
        CloseClipboard();
    }
}

static void ui_paste_clipboard_text(HWND window)
{
    HANDLE hdata;
    BOOL clipboard_is_open = FALSE;
    char * text = NULL;
    char * text_in_petscii = NULL;
    
    do {
        DWORD size;

        if ( ! OpenClipboard(window) ) {
            break;
        }

        clipboard_is_open = TRUE;

        hdata = GetClipboardData(CF_TEXT);

        if ( ! hdata ) {
            break;
        }

        text = GlobalLock(hdata);

        if (text == NULL) {
            break;
        }

        size = GlobalSize(hdata);

        if (size < 1) {
            break;
        }

        /*
         * Allocate memmory for the string to convert in petscii.
         * Note: As we are not sure if the original text is null-terminated,
         *       do *not* use lib_stralloc()!
         */
        text_in_petscii = lib_malloc(size + 1);

        if (text_in_petscii == NULL) {
            break;
        }

        memcpy(text_in_petscii, text, size);
        text_in_petscii[size] = 0;

        charset_petconvstring(text_in_petscii, 0);

        kbdbuf_feed(text_in_petscii);

    } while (0);

    if (text_in_petscii) {
        lib_free(text_in_petscii);
    }

    if (text) {
        GlobalUnlock(text);
    }

    if (clipboard_is_open) {
        CloseClipboard();
    }
}


/* ------------------------------------------------------------------------ */

/* FIXME: tmp hack.  */
int syscolorchanged, displaychanged, querynewpalette, palettechanged;

static void handle_default_command(WPARAM wparam, LPARAM lparam, HWND hwnd)
{
    int i, j, command_found = 0;

    for (i = 0; toggle_list[i].name != NULL && !command_found; i++) {
        if (toggle_list[i].item_id == wparam) {
            resources_toggle(toggle_list[i].name, NULL);
            command_found = 1;
        }
    }

    if (machine_specific_toggles) {
        for (i = 0; machine_specific_toggles[i].name != NULL
            && !command_found; i++) {
            if (machine_specific_toggles[i].item_id == wparam) {
                resources_toggle(machine_specific_toggles[i].name, NULL);
                command_found = 1;
            }
        }
    }

    for (i = 0; value_list[i].name != NULL && !command_found; i++) {
        for (j = 0; value_list[i].vals[j].item_id != 0
            && !command_found; j++) {
            if (value_list[i].vals[j].item_id == wparam) {
                resources_set_int(value_list[i].name,
                                  value_list[i].vals[j].value);
                command_found = 1;
            }
        }
    }

    if (machine_specific_values) {
        for (i = 0; machine_specific_values[i].name != NULL
            && !command_found; i++) {
            for (j = 0; machine_specific_values[i].vals[j].item_id != 0
                && !command_found; j++) {
                if (machine_specific_values[i].vals[j].item_id == wparam) {
                    resources_set_int(machine_specific_values[i].name,
                                      machine_specific_values[i].vals[j].value);
                    command_found = 1;
                }
            }
        }
    }
}

static void handle_wm_initmenupopup(HMENU menu)
{
    /* enable PASTE iff the clipboard contains "our" format: */

    EnableMenuItem(menu, IDM_EDIT_PASTE, 
        MF_BYCOMMAND 
        | ( IsClipboardFormatAvailable(CF_TEXT) ? MF_ENABLED : MF_GRAYED));
}

static void handle_wm_command(WPARAM wparam, LPARAM lparam, HWND hwnd)
{
    TCHAR *st_name;

    wparam &= 0xffff;
    /* Handle machine specific commands first.  */
    if (ui_machine_specific)
        ui_machine_specific(wparam, hwnd);

    switch (wparam) {
      case IDM_DEVICEMANAGER:
      case IDM_FORMFEED_PRINTERIEC4:
      case IDM_FORMFEED_PRINTERIEC5:
        uiperipheral_command(hwnd, wparam);
        break;
      case IDM_EXIT:
        PostMessage(hwnd, WM_CLOSE, wparam, lparam);
        break;
      case IDM_EDIT_COPY:
        ui_copy_clipboard(hwnd);
        break;
      case IDM_EDIT_PASTE:
        ui_paste_clipboard_text(hwnd);
        break;
      case IDM_ABOUT:
      case IDM_HELP:
      case IDM_CONTRIBUTORS:
      case IDM_LICENSE:
      case IDM_WARRANTY:
      case IDM_CMDLINE:
        uihelp_dialog(hwnd, wparam);
        break;
      case IDM_ATTACH_8:
      case IDM_ATTACH_9:
      case IDM_ATTACH_10:
      case IDM_ATTACH_11:
      case IDM_DETACH_8:
      case IDM_DETACH_9:
      case IDM_DETACH_10:
      case IDM_DETACH_11:
      case IDM_DETACH_ALL:
      case IDM_ATTACH_TAPE:
      case IDM_DETACH_TAPE:
      case IDM_AUTOSTART:
        uiattach_command(hwnd, wparam);
        break;
      case IDM_FLIP_ADD:
      case IDM_FLIP_REMOVE:
      case IDM_FLIP_NEXT:
      case IDM_FLIP_PREVIOUS:
      case IDM_FLIP_LOAD:
      case IDM_FLIP_SAVE:
        uifliplist_command(hwnd, wparam);
        break;
      case IDM_DATASETTE_SETTINGS:
      case IDM_DATASETTE_CONTROL_STOP:
      case IDM_DATASETTE_CONTROL_START:
      case IDM_DATASETTE_CONTROL_FORWARD:
      case IDM_DATASETTE_CONTROL_REWIND:
      case IDM_DATASETTE_CONTROL_RECORD:
      case IDM_DATASETTE_CONTROL_RESET:
      case IDM_DATASETTE_RESET_COUNTER:
        uidatasette_command(hwnd, wparam);
        break;
      case IDM_SNAPSHOT_LOAD:
        ui_snapshot_load(hwnd);
        break;
      case IDM_SNAPSHOT_SAVE:
        ui_snapshot_save(hwnd);
        break;
      case IDM_SAVEQUICK:
        ui_quicksnapshot_save(hwnd);
        break;
      case IDM_LOADQUICK:
        ui_quicksnapshot_load(hwnd);
        break;
      case IDM_MEDIAFILE:
        SuspendFullscreenModeKeep(hwnd);
        ui_mediafile_save_dialog(hwnd);
        ResumeFullscreenModeKeep(hwnd);
        break;
      case IDM_SINGLE_FRAME_ADVANCE:
        pause_pending = 1;
        if (!is_paused) {
            break;
        }
        // fall through
      case IDM_PAUSE:
        ui_pause_emulation();
        break;
      case IDM_MONITOR:
        if (!ui_emulation_is_paused())
            monitor_startup_trap();
/*
        else
            monitor_startup();
*/
        break;
      case IDM_RESET_HARD:
      case IDM_RESET_SOFT:
        reset_dialog_proc(wparam);
        break;
      case IDM_RESET_DRIVE8:
        vsync_suspend_speed_eval();
        drivecpu_trigger_reset(0);
        break;
      case IDM_RESET_DRIVE9:
        vsync_suspend_speed_eval();
        drivecpu_trigger_reset(1);
        break;
      case IDM_RESET_DRIVE10:
        vsync_suspend_speed_eval();
        drivecpu_trigger_reset(2);
        break;
      case IDM_RESET_DRIVE11:
        vsync_suspend_speed_eval();
        drivecpu_trigger_reset(3);
        break;
      case IDM_MAXIMUM_SPEED_CUSTOM:
        ui_speed_settings_dialog(hwnd);
        break;
      case IDM_JOY_SETTINGS:
        ui_joystick_settings_dialog(hwnd);
        break;
      case IDM_SWAP_JOYSTICK:
        ui_joystick_swap_joystick();
        break;
      case IDM_SOUND_SETTINGS:
        ui_sound_settings_dialog(hwnd);
        break;
      case IDM_RAM_SETTINGS:
        ui_ram_settings_dialog(hwnd);
        break;
      case IDM_TOGGLE_FULLSCREEN:
        vsync_suspend_speed_eval();
        SwitchFullscreenMode(hwnd);
        break;
      case IDM_SETTINGS_SAVE_FILE:
          if ((st_name = uilib_select_file(hwnd, translate_text(IDS_SAVE_CONFIG_FILE),
              UILIB_FILTER_ALL, UILIB_SELECTOR_TYPE_FILE_SAVE,
              UILIB_SELECTOR_STYLE_DEFAULT)) != NULL)
          {
              char *name;

              name = system_wcstombs_alloc(st_name);

              if (resources_save(st_name) < 0)
              {
                  ui_error(translate_text(IDS_CANNOT_SAVE_SETTINGS));
              }
              else
              {
                  ui_message(translate_text(IDS_SETTINGS_SAVED_SUCCESS));
              }
              uifliplist_save_settings();
              system_wcstombs_free(name);
              lib_free(st_name);
          }
          break;
      case IDM_SETTINGS_LOAD_FILE:
          if ((st_name = uilib_select_file(hwnd, translate_text(IDS_LOAD_CONFIG_FILE),
              UILIB_FILTER_ALL, UILIB_SELECTOR_TYPE_FILE_LOAD,
              UILIB_SELECTOR_STYLE_DEFAULT)) != NULL)
          {
              char *name;

              name = system_wcstombs_alloc(st_name);

              if (resources_load(st_name) < 0)
              {
                  ui_error(translate_text(IDS_CANNOT_LOAD_SETTINGS));
              }
              else
              {
                  ui_message(translate_text(IDS_SETTINGS_LOADED_SUCCESS));
              }
              uifliplist_save_settings();
              system_wcstombs_free(name);
              lib_free(st_name);
          }
          break;
      case IDM_SETTINGS_SAVE:
        if (resources_save(NULL) < 0)
            ui_error(translate_text(IDS_CANNOT_SAVE_SETTINGS));
        else
            ui_message(translate_text(IDS_SETTINGS_SAVED_SUCCESS));
        uifliplist_save_settings();
        break;
      case IDM_SETTINGS_LOAD:
        if (resources_load(NULL) < 0) {
            ui_error(translate_text(IDS_CANNOT_LOAD_SETTINGS));
        } else {
            ui_message(translate_text(IDS_SETTINGS_LOADED_SUCCESS));
        }
        break;
      case IDM_SETTINGS_DEFAULT:
        resources_set_defaults();
        ui_message(translate_text(IDS_DEFAULT_SETTINGS_RESTORED));
        break;
      case IDM_EVENT_DIRECTORY:
      case IDM_EVENT_TOGGLE_RECORD:
      case IDM_EVENT_TOGGLE_PLAYBACK:
      case IDM_EVENT_SETMILESTONE:
      case IDM_EVENT_RESETMILESTONE:
        uievent_command(hwnd, wparam);
        break;
      case IDM_NETWORK_SETTINGS:
        ui_network_dialog(hwnd);
        break;
      case IDM_RS232_SETTINGS:
        ui_rs232_settings_dialog(hwnd);
        break;
      case IDM_LANG_EN:
      case IDM_LANG_DE:
      case IDM_LANG_FR:
      case IDM_LANG_HU:
      case IDM_LANG_IT:
      case IDM_LANG_NL:
      case IDM_LANG_PL:
      case IDM_LANG_SV:
        ui_set_language(wparam);
        break;
      case IDM_SOUND_RECORD_START:
        ui_sound_record_settings_dialog(hwnd);
        break;
      case IDM_SOUND_RECORD_STOP:
        resources_set_string("SoundRecordDeviceName", "");
        ui_display_statustext(translate_text(IDS_SOUND_RECORDING_STOPPED), 1);
        break;
      default:
        handle_default_command(wparam, lparam, hwnd);
    }
}


int ui_active = FALSE;
HWND ui_active_window;

/* Window procedure.  All messages are handled here.  */
static long CALLBACK dummywindowproc(HWND window, UINT msg,
                                     WPARAM wparam, LPARAM lparam)
{
    switch (msg) {
      case WM_ENABLE:
//      log_debug("DUMMY WM_ENABLE %s", wparam == TRUE ? "TRUE" : "FALSE");
        break;
      case WM_ACTIVATEAPP:
//      log_debug("DUMMY WM_ACTIVATEAPP %s",
//                wparam == TRUE ? "ACTIVATE" : "DEACTIVATE");
        break;
      case WM_ACTIVATE:
//      log_debug("DUMMY WM_ACTIVATE %s", wparam == WA_ACTIVE ? "ACTIVATE"
//                : wparam == WA_INACTIVE ?"DEACTIVATE" : "MOUSECLICK");
        break;
      case WM_KILLFOCUS:
//      log_debug("DUMMY WM_KILLFOCUS");
        break;
      case WM_SETFOCUS:
//      log_debug("DUMMY WM_SETFOCUS");
        break;
      case WM_SETREDRAW:
//      log_debug("DUMMY WM_SETREDRAW %s",wparam==TRUE? "TRUE":"FALSE");
        break;
    }
    return DefWindowProc(window, msg, wparam, lparam);
}

extern int fullscreen_transition;

static void ui_wm_move(HWND window, int window_index)
{
    if (window_index<number_of_windows) {
        WINDOWPLACEMENT place;
        RECT rect;

        place.length = sizeof(WINDOWPLACEMENT);
        GetWindowPlacement(window, &place);
        GetWindowRect(window, &rect);
        if (place.showCmd == SW_SHOWNORMAL) {
            resources_set_int_sprintf("Window%dXpos",
                                      rect.left, window_index);
            resources_set_int_sprintf("Window%dYpos",
                                      rect.top, window_index);
        }
    }
}

static void ui_wm_close(HWND window)
{
    int quit = 1;
    int confirm_on_exit, save_on_exit;

    resources_get_int("ConfirmOnExit", &confirm_on_exit);
    resources_get_int("SaveResourcesOnExit", &save_on_exit);

    SuspendFullscreenModeKeep(window);
    vsync_suspend_speed_eval();
    if (confirm_on_exit) {
//      log_debug("Asking exit confirmation");
        if (MessageBox(window,
            translate_text(IDS_REALLY_EXIT),
            TEXT("VICE"), MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2
            | MB_TASKMODAL) == IDYES) {
            quit = 1;
        } else {
            quit = 0;
        }
    }

    if (quit) {
        SuspendFullscreenMode(window);
        if (save_on_exit) {
            if (resources_save(NULL)<0) {
                ui_error(translate_text(IDS_CANNOT_SAVE_SETTINGS));
            }
        }
        DestroyWindow(window);
    } else {
        ResumeFullscreenModeKeep(window);
    }
}

static void ui_wm_dropfiles(HWND window, WPARAM wparam)
{
    char szFile[256];
    HDROP hDrop;

    hDrop = (HDROP)wparam;
    DragQueryFile(hDrop, 0, (char *)&szFile, 256);
    if (GetAsyncKeyState(VK_SHIFT) & 0x8000) {
        if (file_system_attach_disk(8, szFile) < 0)
            ui_error(translate_text(IDS_CANNOT_ATTACH_FILE));
    } else {
        if (autostart_autodetect(szFile, NULL, 0,
            AUTOSTART_MODE_RUN) < 0)
            ui_error(translate_text(IDS_CANNOT_AUTOSTART_FILE));
    }
    DragFinish(hDrop);
}

static void ui_redraw_all_windows(void)
{
    int i;

    for (i = 0; i < number_of_windows; i++) {
        InvalidateRect(window_handles[i], NULL, FALSE);
    }
}

/* Window procedure.  All messages are handled here.  */
static long CALLBACK window_proc(HWND window, UINT msg,
                                 WPARAM wparam, LPARAM lparam)
{
    int window_index;

    for (window_index = 0; window_index < number_of_windows; window_index++) {
        if (window_handles[window_index] == window)
            break;
    }

    switch (msg) {
      case WM_CREATE:
        DragAcceptFiles(window, TRUE);
        return 0;
      case WM_WINDOWPOSCHANGED:
        /* SRT: if focus is changed in full-screen mode, this message is sent 
          Make sure that all windows are repainted.*/
        ui_redraw_all_windows();
        break;
      case WM_SETREDRAW:
//      log_debug("WM_SETREDRAW %s", wparam == TRUE? "TRUE" : "FALSE");
        break;
      case WM_KILLFOCUS:
//      log_debug("WM_KILLFOCUS");
        break;
      case WM_SETFOCUS:
//      log_debug("WM_SETFOCUS");
        break;
      case WM_ENABLE:
//      log_debug("WM_ENABLE %s %d %08x",
//                wparam == TRUE ? "TRUE" : "FALSE", window_index, window);
        break;
      case WM_ACTIVATEAPP:
        if (wparam == TRUE) {
//          log_debug("WM_ACTIVATEAPP activate %d %08x", window_index,window);
        } else {
//          log_debug("WM_ACTIVATEAPP deactivate %d %08x", window_index,window);
        }
//      return 0;
        break;
      case WM_ACTIVATE:
        if (wparam == WA_INACTIVE) {
//          log_debug("WM_ACTIVATE inactive %d %08x", window_index, window);
            ui_active = FALSE;
//          if (!fullscreen_transition)
//              SuspendFullscreenMode(window);
        } else {
//          log_debug("WM_ACTIVATE active %d %08x", window_index, window);
            ui_active = TRUE;
            ui_active_window = window;
//          if (!fullscreen_transition)
//              ResumeFullscreenMode(window);
        }
        mouse_update_mouse_acquire();
        break;
      case WM_SIZE:
        if (window_index<number_of_windows) {
            statusbar_handle_WMSIZE(msg, wparam, lparam, window_index);
        }
        return 0;
      case WM_DRAWITEM:
        statusbar_handle_WMDRAWITEM(wparam,lparam);
        /* SRT: Make sure that all windows are repainted.
          This message seems to be a good candidate for the remote desktop. */
        ui_redraw_all_windows();
        return 0;
      case WM_INITMENUPOPUP:
        handle_wm_initmenupopup((HMENU)wparam);
        break;
      case WM_COMMAND:
        handle_wm_command(wparam, lparam, window);
        return 0;
      case WM_ENTERMENULOOP:
        update_menus(window);
      case WM_ENTERSIZEMOVE:
        vsync_suspend_speed_eval();
        ui_active = FALSE;
        mouse_update_mouse_acquire();
        break;
      case WM_EXITMENULOOP:
      case WM_EXITSIZEMOVE:
        if (GetActiveWindow() == window || !IsIconic(window)) {
            ui_active = TRUE;
        } else {
            ui_active = FALSE;
        }
        mouse_update_mouse_acquire();
        break;
      case WM_MOVE:
        ui_wm_move(window, window_index);
        break;
      case WM_SYSKEYDOWN:
        if (wparam == VK_F10) {
            kbd_handle_keydown(wparam, lparam);
            return 0;
        }
        break;
      case WM_KEYDOWN:
        kbd_handle_keydown(wparam, lparam);
        return 0;
      case WM_SYSKEYUP:
        kbd_handle_keyup(wparam, lparam);
        if (wparam == VK_F10)
              return 0;
        break;
      case WM_KEYUP:
        kbd_handle_keyup(wparam, lparam);
        return 0;
      case WM_SYSCOLORCHANGE:
        syscolorchanged = 1;
        break;
      case WM_DISPLAYCHANGE:
//      log_debug("Display changed %d %d %d",
//                LOWORD(lparam), HIWORD(lparam), wparam);
        displaychanged = 1;
        break;
      case WM_QUERYNEWPALETTE:
        querynewpalette = 1;
        break;
      case WM_PALETTECHANGED:
        if ((HWND)wparam != window)
            palettechanged = 1;
        break;
      case WM_CLOSE:
        ui_wm_close(window);
        return 0;
      case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
      case WM_ERASEBKGND:
        return 1;
      case WM_DROPFILES:
        ui_wm_dropfiles(window, wparam);
        return 0;
      case WM_PAINT:
        {
            RECT update_rect;

            if (GetUpdateRect(window, &update_rect, FALSE)) {
                PAINTSTRUCT ps;
                HDC hdc;

                hdc = BeginPaint(window, &ps);

                video_canvas_update(window, hdc,
                                    ps.rcPaint.left, ps.rcPaint.top,
                                    ps.rcPaint.right - ps.rcPaint.left,
                                    ps.rcPaint.bottom - ps.rcPaint.top);

                EndPaint(window, &ps);
                return 0;
            } else
                break;
        }
      case WM_SYSCOMMAND:
      case WM_NCLBUTTONDOWN:
        vsync_suspend_speed_eval();
        break;
      case WM_RBUTTONDOWN:
        ui_paste_clipboard_text(window);
        break;
      case WM_NOTIFY:
        statusbar_notify(window, window_index, wparam, lparam);
        break;
    }

    return DefWindowProc(window, msg, wparam, lparam);
}

/*
 The following shows a messagebox on the screen.
 It first searches the current active window of VICE, and then 
 suspends fullscreen mode, shows the messagebox, and then resumes
 fullscreen mode.
 If it can't find the current active window of VICE (e.g., no one
 is currently active), it does not suspend and resume fullscreen
 mode. This should be correct because when fullscreen, that window
 has to be active.
*/
int ui_messagebox(LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
    int ret;
    HWND hWnd = NULL;
    
    if (number_of_windows == 1) {
        /* we only have one window, so use that one */
        hWnd = window_handles[0];
    } else {
        int window_index;

        HWND hWndActive = GetActiveWindow();

        for (window_index = 0; window_index < number_of_windows;
            window_index++) {
            if (window_handles[window_index] == hWndActive) {
                hWnd = hWndActive;
                break;
            }
        }
    }

    if (hWnd != NULL) {
        SuspendFullscreenModeKeep(hWnd);
    }

    ret = MessageBox(hWnd, lpText, lpCaption, uType);

    if (hWnd != NULL) {
        ResumeFullscreenModeKeep(hWnd);
    }

    return ret;
}

void ui_display_volume(int vol)
{
    statusbar_display_volume(vol);
}