File: eventeditor.cpp

package info (click to toggle)
freespace2 24.0.2%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: trixie
  • size: 43,188 kB
  • sloc: cpp: 583,107; ansic: 21,729; python: 1,174; sh: 464; makefile: 248; xml: 181
file content (1994 lines) | stat: -rw-r--r-- 51,463 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) Volition, Inc. 1999.  All rights reserved.
 *
 * All source code herein is the property of Volition, Inc. You may not sell 
 * or otherwise commercially exploit the source or things you created based on the 
 * source.
 *
*/



#include "stdafx.h"
#include "FRED.h"
#include "FREDDoc.h"
#include "EventEditor.h"
#include "FREDView.h"
#include "Management.h"
#include "Sexp_tree.h"
#include "textviewdlg.h"
#include "mission/missionmessage.h"
#include "cfile/cfile.h"
#include "sound/audiostr.h"
#include "localization/localize.h"
#include "mod_table/mod_table.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


BEGIN_MESSAGE_MAP(event_sexp_tree, sexp_tree)
	//{{AFX_MSG_MAP(event_sexp_tree)
	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText)
	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText)
	ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnCustomDraw)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


event_editor *Event_editor_dlg = NULL; // global reference needed by event tree class

// this is just useful for comparing modified EAs to unmodified ones
static event_annotation default_ea;

/////////////////////////////////////////////////////////////////////////////
// event_editor dialog

event_editor::event_editor(CWnd* pParent /*=NULL*/)
	: CDialog(event_editor::IDD, pParent)
{
	//{{AFX_DATA_INIT(event_editor)
	m_repeat_count = 0;
	m_trigger_count = 0;
	m_interval = 0;
	m_event_score = 0;
	m_chain_delay = 0;
	m_chained = FALSE;
	m_use_msecs = FALSE;
	m_obj_text = _T("");
	m_obj_key_text = _T("");
	m_avi_filename = _T("");
	m_message_name = _T("");
	m_message_note = _T("");
	m_message_text = _T("");
	m_persona = -1;
	m_wave_filename = _T("");
	m_cur_msg = -1;
	m_cur_msg_old = -1;
	m_team = -1;
	m_message_team = -1;
	m_last_message_node = -1;
	//}}AFX_DATA_INIT
	m_event_tree.m_mode = MODE_EVENTS;
	m_event_tree.link_modified(&modified);
	modified = 0;
	select_sexp_node = -1;
	m_wave_id = -1;
	m_log_true = 0;
	m_log_false = 0;
	m_log_always_false = 0;
	m_log_1st_repeat = 0;
	m_log_last_repeat = 0;
	m_log_1st_trigger = 0;
	m_log_last_trigger = 0;
	m_log_state_change = 0;
}

void event_editor::DoDataExchange(CDataExchange* pDX)
{
	if (m_cur_msg >= 0)
		m_cur_msg_old = m_cur_msg;

	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(event_editor)
	DDX_Control(pDX, IDC_EVENT_TREE, m_event_tree);
	DDX_Text(pDX, IDC_REPEAT_COUNT, m_repeat_count);
	DDX_Text(pDX, IDC_TRIGGER_COUNT, m_trigger_count);
	DDX_Text(pDX, IDC_INTERVAL_TIME, m_interval);
	DDX_Text(pDX, IDC_EVENT_SCORE, m_event_score);
	DDX_Text(pDX, IDC_CHAIN_DELAY, m_chain_delay);
	DDX_Check(pDX, IDC_CHAINED, m_chained);
	DDX_Check(pDX, IDC_USE_MSECS, m_use_msecs);
	DDX_Text(pDX, IDC_OBJ_TEXT, m_obj_text);
	DDX_Text(pDX, IDC_OBJ_KEY_TEXT, m_obj_key_text);
	DDX_CBString(pDX, IDC_AVI_FILENAME, m_avi_filename);
	DDX_Text(pDX, IDC_MESSAGE_NAME, m_message_name);
	DDX_Text(pDX, IDC_MESSAGE_TEXT, m_message_text);
	DDX_CBIndex(pDX, IDC_PERSONA_NAME, m_persona);
	DDX_CBString(pDX, IDC_WAVE_FILENAME, m_wave_filename);
	DDX_LBIndex(pDX, IDC_MESSAGE_LIST, m_cur_msg);
	DDX_Check(pDX, IDC_MISSION_LOG_TRUE, m_log_true);
	DDX_Check(pDX, IDC_MISSION_LOG_FALSE, m_log_false);
	DDX_Check(pDX, IDC_MISSION_LOG_ALWAYS_FALSE, m_log_always_false);
	DDX_Check(pDX, IDC_MISSION_LOG_1ST_REPEAT, m_log_1st_repeat);
	DDX_Check(pDX, IDC_MISSION_LOG_LAST_REPEAT, m_log_last_repeat);
	DDX_Check(pDX, IDC_MISSION_LOG_1ST_TRIGGER, m_log_1st_trigger);
	DDX_Check(pDX, IDC_MISSION_LOG_LAST_TRIGGER, m_log_last_trigger);
	DDX_Check(pDX, IDC_MISSION_LOG_STATE_CHANGE, m_log_state_change);

	// m_team == -1 maps to 2
	if(m_team == -1){
		m_team = MAX_TVT_TEAMS;
	}

	DDX_CBIndex(pDX, IDC_EVENT_TEAM, m_team);

	// m_message_team == -1 maps to 2
	if(m_message_team == -1){
		m_message_team = MAX_TVT_TEAMS;
	}
	DDX_CBIndex(pDX, IDC_MESSAGE_TEAM, m_message_team);
	//}}AFX_DATA_MAP

	DDV_MaxChars(pDX, m_obj_text, NAME_LENGTH - 1);
	DDV_MaxChars(pDX, m_obj_key_text, NAME_LENGTH - 1);
	DDV_MaxChars(pDX, m_message_name, NAME_LENGTH - 1);
	DDV_MaxChars(pDX, m_message_text, MESSAGE_LENGTH - 1);
	DDV_MaxChars(pDX, m_avi_filename, MAX_FILENAME_LEN - 1);
	DDV_MaxChars(pDX, m_wave_filename, MAX_FILENAME_LEN - 1);
}

BEGIN_MESSAGE_MAP(event_editor, CDialog)
	//{{AFX_MSG_MAP(event_editor)
	ON_NOTIFY(NM_RCLICK, IDC_EVENT_TREE, OnRclickEventTree)
	ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_EVENT_TREE, OnBeginlabeleditEventTree)
	ON_NOTIFY(TVN_ENDLABELEDIT, IDC_EVENT_TREE, OnEndlabeleditEventTree)
	ON_BN_CLICKED(IDC_BUTTON_NEW_EVENT, OnButtonNewEvent)
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	ON_BN_CLICKED(ID_OK, OnButtonOk)
	ON_WM_CLOSE()
	ON_NOTIFY(TVN_SELCHANGED, IDC_EVENT_TREE, OnSelchangedEventTree)
	ON_EN_UPDATE(IDC_REPEAT_COUNT, OnUpdateRepeatCount)
	ON_EN_UPDATE(IDC_TRIGGER_COUNT, OnUpdateTriggerCount)
	ON_BN_CLICKED(IDC_CHAINED, OnChained)
	ON_BN_CLICKED(IDC_INSERT, OnInsert)
	ON_LBN_SELCHANGE(IDC_MESSAGE_LIST, OnSelchangeMessageList)
	ON_BN_CLICKED(IDC_NEW_MSG, OnNewMsg)
	ON_BN_CLICKED(IDC_DELETE_MSG, OnDeleteMsg)
	ON_BN_CLICKED(IDC_NEW_NOTE, OnMsgNote)
	ON_BN_CLICKED(IDC_BROWSE_AVI, OnBrowseAvi)
	ON_BN_CLICKED(IDC_BROWSE_WAVE, OnBrowseWave)
	ON_CBN_SELCHANGE(IDC_WAVE_FILENAME, OnSelchangeWaveFilename)
	ON_BN_CLICKED(IDC_PLAY, OnPlay)
	ON_BN_CLICKED(IDC_UPDATE, OnUpdateStuff)
	ON_BN_CLICKED(ID_CANCEL, OnButtonCancel)
	ON_CBN_SELCHANGE(IDC_EVENT_TEAM, OnSelchangeTeam)
	ON_CBN_SELCHANGE(IDC_MESSAGE_TEAM, OnSelchangeMessageTeam)
	ON_LBN_DBLCLK(IDC_MESSAGE_LIST, OnDblclkMessageList)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// event_editor message handlers

void maybe_add_head(CComboBox *box, const char* name)
{
	if (box->FindStringExact(-1, name) == CB_ERR) {
		box->AddString(name);
	}
}

BOOL event_editor::OnInitDialog() 
{
	int i;
	BOOL r = TRUE;
	CListBox *list;
	CComboBox *box;
	MMessage msg; 

	CDialog::OnInitDialog();  // let the base class do the default work
	m_play_bm.LoadBitmap(IDB_PLAY);
	((CButton *) GetDlgItem(IDC_PLAY)) -> SetBitmap(m_play_bm);

	theApp.init_window(&Events_wnd_data, this, 0);
	m_event_tree.setup((CEdit *) GetDlgItem(IDC_HELP_BOX));
	load_tree();
	create_tree();

	update_cur_event();
	i = m_event_tree.select_sexp_node;
	if (i != -1) {
		GetDlgItem(IDC_EVENT_TREE) -> SetFocus();
		m_event_tree.hilite_item(i);
		r = FALSE;
	}

	// determine all the handles for event annotations
	for (auto &ea : Event_annotations)
	{
		auto h = traverse_path(ea);
		if (h)
		{
			ea.handle = h;
			if (!ea.comment.empty())
				event_annotation_swap_image(&m_event_tree, h, ea);
		}
		else
		{
			// event was probably deleted; clear the annotation so it will be deleted later
			ea = default_ea;
		}
	}

	// ---------- end of event initialization ----------

	int num_messages = Num_messages - Num_builtin_messages;
	m_messages.clear();
	m_messages.reserve(num_messages);
	for (i=0; i<num_messages; i++) {
		msg = Messages[i + Num_builtin_messages];
		m_messages.push_back(msg); 
		if (m_messages[i].avi_info.name){
			m_messages[i].avi_info.name = strdup(m_messages[i].avi_info.name);
		}
		if (m_messages[i].wave_info.name){
			m_messages[i].wave_info.name = strdup(m_messages[i].wave_info.name);
		}
	}

	((CEdit *) GetDlgItem(IDC_MESSAGE_NAME))->LimitText(NAME_LENGTH - 1);
	((CEdit *) GetDlgItem(IDC_MESSAGE_TEXT))->LimitText(MESSAGE_LENGTH - 1);
	((CComboBox *) GetDlgItem(IDC_AVI_FILENAME))->LimitText(MAX_FILENAME_LEN - 1);
	((CComboBox *) GetDlgItem(IDC_WAVE_FILENAME))->LimitText(MAX_FILENAME_LEN - 1);

	list = (CListBox *) GetDlgItem(IDC_MESSAGE_LIST);
	list->ResetContent();
	for (const auto &message: m_messages) {
		list->AddString(message.name);
	}

	box = (CComboBox *) GetDlgItem(IDC_AVI_FILENAME);
	box->ResetContent();
	box->AddString("<None>");
	for (i=0; i<Num_messages; i++) {
		if (Messages[i].avi_info.name) {
			maybe_add_head(box, Messages[i].avi_info.name);
		}
	}

	if (!Disable_hc_message_ani) {
		maybe_add_head(box, "Head-TP2");
		maybe_add_head(box, "Head-VC2");
		maybe_add_head(box, "Head-TP4");
		maybe_add_head(box, "Head-TP5");
		maybe_add_head(box, "Head-TP6");
		maybe_add_head(box, "Head-TP7");
		maybe_add_head(box, "Head-TP8");
		maybe_add_head(box, "Head-VP2");
		maybe_add_head(box, "Head-VP2");
		maybe_add_head(box, "Head-CM2");
		maybe_add_head(box, "Head-CM3");
		maybe_add_head(box, "Head-CM4");
		maybe_add_head(box, "Head-CM5");
		maybe_add_head(box, "Head-BSH");
		
	}

	for (auto &thisHead : Custom_head_anis) {
		maybe_add_head(box, thisHead.c_str());
	}

/*
	box->AddString("Head-VC");  // force it in, since Sandeep wants it and it's not used in built-in messages
	box->AddString("Head-VC2");

	// add terran pilot heads
	box->AddString("Head-TP4");
	box->AddString("Head-TP5");
	box->AddString("Head-TP6");
	box->AddString("Head-TP7");
	box->AddString("Head-TP8");

	// add vasudan pilot heads
	box->AddString("Head-VP2");

	// BSH and CM2
	box->AddString("Head-CM2");
	box->AddString("Head-BSH");
	*/

	box = (CComboBox *) GetDlgItem(IDC_WAVE_FILENAME);
	box->ResetContent();
	box->AddString("<None>");
	for (i=0; i<Num_messages; i++){
		if (Messages[i].wave_info.name){
			if (box->FindStringExact(i, Messages[i].wave_info.name) == CB_ERR){
				box->AddString(Messages[i].wave_info.name);
			}
		}
	}

	// add the persona names into the combo box
	box = (CComboBox *) GetDlgItem(IDC_PERSONA_NAME);
	box->ResetContent();
	box->AddString("<None>");
	for (const auto &persona: Personas) {
		box->AddString(persona.name);
	}

	// set the first message to be the first non-builtin message (if it exists)
	if ( Num_messages > Num_builtin_messages ){
		m_cur_msg = 0;
	} else {
		m_cur_msg = -1;
	}

	update_cur_message();
	return r;
}

void event_editor::load_tree()
{
	int i;

	m_event_tree.select_sexp_node = select_sexp_node;
	select_sexp_node = -1;

	m_event_tree.clear_tree();
	m_events.clear();
	m_sig.clear();
	for (i=0; i<(int)Mission_events.size(); i++) {
		m_events.push_back(Mission_events[i]);
		m_sig.push_back(i);

		if (m_events[i].name.empty())
			m_events[i].name = "<Unnamed>";

		m_events[i].formula = m_event_tree.load_sub_tree(Mission_events[i].formula, false, "do-nothing");

		// we must check for the case of the repeat count being 0.  This would happen if the repeat
		// count is not specified in a mission
		if ( m_events[i].repeat_count == 0 ){
			m_events[i].repeat_count = 1;
		}
	}

	m_event_tree.post_load();
	cur_event = -1;
}

void event_editor::create_tree()
{
	int i;
	HTREEITEM h;

	m_event_tree.DeleteAllItems();
	for (i=0; i<(int)m_events.size(); i++) {

		// set the proper bitmap
		int image;
		if (m_events[i].chain_delay >= 0) {
			image = BITMAP_CHAIN;
			if (!m_events[i].objective_text.empty()) {
				image = BITMAP_CHAIN_DIRECTIVE;
			}
		} else {
			image = BITMAP_ROOT;
			if (!m_events[i].objective_text.empty()) {
				image = BITMAP_ROOT_DIRECTIVE;
			}
		}

		h = m_event_tree.insert(m_events[i].name.c_str(), image, image);

		m_event_tree.SetItemData(h, m_events[i].formula);
		m_event_tree.add_sub_tree(m_events[i].formula, h);
	}

	cur_event = -1;
}

void event_editor::OnRclickEventTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	save();
	m_event_tree.right_clicked(MODE_EVENTS);
	*pResult = 0;
}

void event_editor::OnBeginlabeleditEventTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
	CEdit *edit;
	bool is_operator;

	if (m_event_tree.edit_label(pTVDispInfo->item.hItem, &is_operator) == 1)	{
		// when editing operators, do not use the built-in CEdit control, but overlay the special CComboBox
		if (is_operator) {
			*pResult = 1;
			modified = 1;
			m_event_tree.start_operator_edit(pTVDispInfo->item.hItem);
		}
		else {
			*pResult = 0;
			modified = 1;
			edit = m_event_tree.GetEditControl();
			Assert(edit);
			edit->SetLimitText(NAME_LENGTH - 1);
		}

	} else
		*pResult = 1;
}

void event_editor::OnEndlabeleditEventTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;

	*pResult = m_event_tree.end_label_edit(pTVDispInfo->item);
}

// This is needed as a HACK around default MFC standard
// It is not required, but overrides default MFC and links no errors without.
// (Specifically, this overrides the MFC behavior so that pressing Enter doesn't close the dialog)
void event_editor::OnOK()
{
	HWND h;
	CWnd *w;

	save();
	w = GetFocus();
	if (w) {
		h = w->m_hWnd;
		GetDlgItem(IDC_EVENT_TREE)->SetFocus();
		::SetFocus(h);
	}
	((CListBox *)GetDlgItem(IDC_MESSAGE_LIST))->SetCurSel(m_cur_msg);
}

int event_editor::query_modified()
{
	int i;
	char *ptr, buf[MESSAGE_LENGTH];

	UpdateData(TRUE);
	if (modified)
		return 1;

	if (Mission_events.size() != m_events.size())
		return 1;

	for (i=0; i<(int)m_events.size(); i++) {
		if (!lcase_equal(m_events[i].name, Mission_events[i].name))
			return 1;
		if (m_events[i].repeat_count != Mission_events[i].repeat_count)
			return 1;
		if (m_events[i].trigger_count != Mission_events[i].trigger_count)
			return 1;
		if (m_events[i].interval != Mission_events[i].interval)
			return 1;
		if (m_events[i].score != Mission_events[i].score)
			return 1;
		if (m_events[i].chain_delay != Mission_events[i].chain_delay)
			return 1;
		if (!lcase_equal(m_events[i].objective_text, Mission_events[i].objective_text))
			return 1;
		if (!lcase_equal(m_events[i].objective_key_text, Mission_events[i].objective_key_text))
			return 1;
		if (m_events[i].flags != Mission_events[i].flags)
			return 1;
		if (m_events[i].mission_log_flags != Mission_events[i].mission_log_flags)
			return 1;
	}

	if (m_cur_msg < 0)
		return 0;

	if ((int)m_messages.size() != Num_messages - Num_builtin_messages)
		return 1;

	ptr = (char *) (LPCTSTR) m_message_name;
	for (i=0; i<Num_builtin_messages; i++)
		if (!stricmp(ptr, Messages[i].name))
			return 1;

	for (i=0; i<(int)m_messages.size(); i++) {

		if ((i != m_cur_msg) && (!stricmp(ptr, m_messages[m_cur_msg].name)))
			return 1;
	}

	if (stricmp(ptr, m_messages[m_cur_msg].name))
		return 1;  // name is different and allowed to update

	string_copy(buf, m_message_text, MESSAGE_LENGTH - 1);
	if (stricmp(buf, m_messages[m_cur_msg].message))
		return 1;

	string_copy(buf, m_message_note, MESSAGE_LENGTH - 1);
	if (stricmp(buf, m_messages[m_cur_msg].note.c_str()))
		return 1;

	ptr = (char *) (LPCTSTR) m_avi_filename;
	if (advanced_stricmp(ptr, m_messages[m_cur_msg].avi_info.name))
		return 1;

	ptr = (char *) (LPCTSTR) m_wave_filename;
	if (advanced_stricmp(ptr, m_messages[m_cur_msg].wave_info.name))
		return 1;

	// check to see if persona changed.  use -1 since we stuck a "None" for persona
	// at the beginning of the list.
	if ( (m_persona - 1 ) != m_messages[m_cur_msg].persona_index )
		return 1;

	return 0;
}

void event_editor::OnButtonOk()
{
	SCP_vector<std::pair<SCP_string, SCP_string>> names;
	int i;

	audiostream_close_file(m_wave_id, 0);
	m_wave_id = -1;

	save();
	if (query_modified())
		set_modified();

	for (auto &event: Mission_events) {
		free_sexp2(event.formula);
		event.result = 0;  // use this as a processed flag
	}
	
	// rename all sexp references to old events
	for (i=0; i<(int)m_events.size(); i++) {
		if (m_sig[i] >= 0) {
			names.emplace_back(Mission_events[m_sig[i]].name, m_events[i].name);
			Mission_events[m_sig[i]].result = 1;
		}
	}

	// invalidate all sexp references to deleted events.
	for (const auto &event: Mission_events) {
		if (!event.result) {
			SCP_string buf = "<" + event.name + ">";

			// force it to not be too long
			if (SCP_truncate(buf, NAME_LENGTH))
				buf.back() = '>';

			names.emplace_back(event.name, buf);
		}
	}

	// copy all dialog events to the mission
	Mission_events.clear();
	for (const auto &dialog_event: m_events) {
		Mission_events.push_back(dialog_event);
		Mission_events.back().formula = m_event_tree.save_tree(dialog_event.formula);
	}

	// now update all sexp references
	for (const auto &name_pair: names)
		update_sexp_references(name_pair.first.c_str(), name_pair.second.c_str(), OPF_EVENT_NAME);

	for (i=Num_builtin_messages; i<Num_messages; i++) {
		if (Messages[i].avi_info.name)
			free(Messages[i].avi_info.name);

		if (Messages[i].wave_info.name)
			free(Messages[i].wave_info.name);
	}

	Num_messages = (int)m_messages.size() + Num_builtin_messages;
	Messages.resize(Num_messages);
	for (i=0; i<(int)m_messages.size(); i++)
		Messages[i + Num_builtin_messages] = m_messages[i];

	event_annotation_prune();

	// determine all the paths for the annotations that we want to keep
	for (auto &ea : Event_annotations)
	{
		ea.path.clear();
		if (ea.handle)
			populate_path(ea, (HTREEITEM)ea.handle);
		ea.handle = nullptr;
	}

	theApp.record_window_data(&Events_wnd_data, this);
	delete Event_editor_dlg;
	Event_editor_dlg = NULL;

	FREDDoc_ptr->autosave("event editor");
}

// load controls with structure data
void event_editor::update_cur_message()
{
	int enable = TRUE;

	audiostream_close_file(m_wave_id, 0);
	m_wave_id = -1;

	if (m_cur_msg < 0) {
		enable = FALSE;
		m_message_name = _T("");
		m_message_note = _T("");
		m_message_text = _T("");
		m_avi_filename = _T("");
		m_wave_filename = _T("");
		m_persona = 0;
		m_message_team = -1;
	} else {
		m_message_name = m_messages[m_cur_msg].name;
		m_message_note = (CString)m_messages[m_cur_msg].note.c_str();
		m_message_text = m_messages[m_cur_msg].message;
		if (m_messages[m_cur_msg].avi_info.name){
			m_avi_filename = _T(m_messages[m_cur_msg].avi_info.name);
		} else {
			m_avi_filename = _T("<None>");
		}

		if (m_messages[m_cur_msg].wave_info.name){
			m_wave_filename = _T(m_messages[m_cur_msg].wave_info.name);
		} else {
			m_wave_filename = _T("<None>");
		}

		// add persona id
		if ( m_messages[m_cur_msg].persona_index != -1 ){
			m_persona = m_messages[m_cur_msg].persona_index + 1;  // add one for the "none" at the beginning of the list
		} else {
			m_persona = 0;
		}

		if(m_messages[m_cur_msg].multi_team >= MAX_TVT_TEAMS){
			m_message_team = -1;
			m_messages[m_cur_msg].multi_team = -1;
		} else {
			m_message_team = m_messages[m_cur_msg].multi_team;
		}
/*
		m_event_num = find_event();
		if (m_event_num < 0) {
			node = -1;
			m_sender = m_priority = 0;

		} else
			node = CADR(Mission_events[m_event_num].formula);
*/	}

	GetDlgItem(IDC_MESSAGE_NAME)->EnableWindow(enable);
	GetDlgItem(IDC_MESSAGE_TEXT)->EnableWindow(enable);
	GetDlgItem(IDC_AVI_FILENAME)->EnableWindow(enable);
	GetDlgItem(IDC_BROWSE_AVI)->EnableWindow(enable);
	GetDlgItem(IDC_BROWSE_WAVE)->EnableWindow(enable);
	GetDlgItem(IDC_WAVE_FILENAME)->EnableWindow(enable);
	GetDlgItem(IDC_DELETE_MSG)->EnableWindow(enable);
	GetDlgItem(IDC_PERSONA_NAME)->EnableWindow(enable);
	GetDlgItem(IDC_MESSAGE_TEAM)->EnableWindow(enable);
	UpdateData(FALSE);
}

int event_editor::handler(int code, int node, const char *str)
{
	int i;

	switch (code) {
		case ROOT_DELETED:
			for (i=0; i<(int)m_events.size(); i++)
				if (m_events[i].formula == node)
					break;

			Assert(i < (int)m_events.size());
			m_events.erase(m_events.begin() + i);
			m_sig.erase(m_sig.begin() + i);

			if (i >= (int)m_events.size())	// if we have deleted the last event,
				i--;						// i will be set to -1 which is what we want

			cur_event = i;
			update_cur_event();

			return node;

		case ROOT_RENAMED:
			for (i=0; i<(int)m_events.size(); i++)
				if (m_events[i].formula == node)
					break;

			Assert(i < (int)m_events.size());
			m_events[i].name = str;
			return node;

		default:
			Int3();
	}

	return -1;
}

void event_editor::OnButtonNewEvent() 
{
	// before we do anything, we must check and save off any data from the current event (e.g
	// the repeat count and interval count)
	save();

	m_events.emplace_back();
	m_sig.push_back(-1);
	reset_event((int)m_events.size() - 1, TVI_LAST);
}

void event_editor::OnInsert() 
{
	if(cur_event < 0 || m_events.empty())
	{
		//There are no events yet, so just create one
		OnButtonNewEvent();
	}
	else
	{
		// before we do anything, we must check and save off any data from the current event (e.g
		// the repeat count and interval count)
		save();

		m_events.insert(m_events.begin() + cur_event, mission_event());
		m_sig.insert(m_sig.begin() + cur_event, -1);

		if (cur_event){
			reset_event(cur_event, get_event_handle(cur_event - 1));
		} else {
			reset_event(cur_event, TVI_FIRST);
		}
	}
}

HTREEITEM event_editor::get_event_handle(int num)
{
	HTREEITEM h;

	h = m_event_tree.GetRootItem();
	while (h) {
		if ((int) m_event_tree.GetItemData(h) == m_events[num].formula){
			return h;
		}

		h = m_event_tree.GetNextSiblingItem(h);
	}

	return 0;
}

int event_editor::get_event_num(HTREEITEM handle)
{
	int formula = (int)m_event_tree.GetItemData(handle);

	for (int i = 0; i < (int)m_events.size(); ++i)
		if (formula == m_events[i].formula)
			return i;

	return -1;
}

void event_editor::reset_event(int num, HTREEITEM after)
{
	int index;
	HTREEITEM h;

	// this is always called for a freshly constructed event, so all we have to do is set the name
	m_events[num].name = "Event name";
	h = m_event_tree.insert(m_events[num].name.c_str(), BITMAP_ROOT, BITMAP_ROOT, TVI_ROOT, after);

	m_event_tree.item_index = -1;
	m_event_tree.add_operator("when", h);
	index = m_events[num].formula = m_event_tree.item_index;
	m_event_tree.SetItemData(h, index);
	m_event_tree.add_operator("true");
	m_event_tree.item_index = index;
	m_event_tree.add_operator("do-nothing");

	update_cur_event();

	m_event_tree.SelectItem(h);
}

void event_editor::OnDelete() 
{
	HTREEITEM h;

	// call update_cur_event to clean up local class variables so that we can correctly
	// set up the newly selected item.
	cur_event = -1;
	update_cur_event();

	h = m_event_tree.GetSelectedItem();
	if (h) {
		while (m_event_tree.GetParentItem(h))
			h = m_event_tree.GetParentItem(h);

		m_event_tree.setup_selected(h);
		m_event_tree.OnCommand(ID_DELETE, 0);
	}
}

// this is called when you hit the escape key..
void event_editor::OnCancel()
{
	// override MFC default behavior and do nothing
	// the Esc key is used for certain actions inside the events editor
	// so pressing Esc shouldn't close the window
}

// this is called when you click the ID_CANCEL button
void event_editor::OnButtonCancel()
{
	audiostream_close_file(m_wave_id, 0);
	m_wave_id = -1;

	if (query_modified()) {
		int z = MessageBox("Do you want to keep your changes?", "Close", MB_ICONQUESTION | MB_YESNOCANCEL);
		if (z == IDCANCEL){
			return;
		}

		if (z == IDYES) {
			OnButtonOk();
			return;
		}
	}

	event_annotation_prune();

	theApp.record_window_data(&Events_wnd_data, this);
	delete Event_editor_dlg;
	Event_editor_dlg = NULL;
}

void event_editor::OnClose() 
{
	OnButtonCancel();
}

void event_editor::insert_handler(int old, int node)
{
	int i;

	for (i=0; i<(int)m_events.size(); i++){
		if (m_events[i].formula == old){
			break;
		}
	}

	Assert(i < (int)m_events.size());
	m_events[i].formula = node;
	return;
}

void event_editor::save()
{
	int m;

	if (m_cur_msg >= 0) {
		m = m_cur_msg;
	} else {
		// the current message could be -1 because the message list
		// lost focus, so remember the last focused message
		// (but make sure it's valid)
		if (m_cur_msg_old >= 0 && m_cur_msg_old < (int)m_messages.size()) {
			m = m_cur_msg_old;
		} else {
			m = -1;
		}
	}

	save_event(cur_event);
	save_message(m);
}

void event_editor::save_event(int e)
{
	if (e < 0) {
		return;
	}

	UpdateData(TRUE);

	// there is currently no usage of a number < -1, so cap it at that
	if (m_repeat_count < -1)
		m_repeat_count = -1;
	if (m_trigger_count < -1)
		m_trigger_count = -1;

	m_events[e].repeat_count = m_repeat_count;
	m_events[e].trigger_count = m_trigger_count;
	m_events[e].interval = m_interval;
	m_events[e].score = m_event_score;

	// handle chain
	if (m_chained) {
		m_events[e].chain_delay = m_chain_delay;
	} else {
		m_events[e].chain_delay = -1;
	}

	// handle objective text
	m_events[e].objective_text = (LPCTSTR)m_obj_text;
	m_events[e].objective_key_text = (LPCTSTR)m_obj_key_text;

	// update bitmap
	int bitmap;
	if (m_chained) {
		if (m_obj_text.IsEmpty()) {
			bitmap = BITMAP_CHAIN;
		} else {
			bitmap = BITMAP_CHAIN_DIRECTIVE;
		}
	} else {
		// not chained
		if (m_obj_text.IsEmpty()) {
			bitmap = BITMAP_ROOT;
		} else {
			bitmap = BITMAP_ROOT_DIRECTIVE;
		}
	}

	// handle event flags
	m_events[e].flags = 0;
	if (m_use_msecs)
		m_events[e].flags |= MEF_USE_MSECS;

	// handle event log flags
	m_events[e].mission_log_flags = 0;
	if (m_log_true) 
		m_events[e].mission_log_flags |= MLF_SEXP_TRUE;
	if (m_log_false) 
		m_events[e].mission_log_flags |= MLF_SEXP_FALSE;
	if (m_log_always_false) 
		m_events[e].mission_log_flags |= MLF_SEXP_KNOWN_FALSE;
	if (m_log_1st_repeat) 
		m_events[e].mission_log_flags |= MLF_FIRST_REPEAT_ONLY;
	if (m_log_last_repeat) 
		m_events[e].mission_log_flags |= MLF_LAST_REPEAT_ONLY;
	if (m_log_1st_trigger) 
		m_events[e].mission_log_flags |= MLF_FIRST_TRIGGER_ONLY;
	if (m_log_last_trigger) 
		m_events[e].mission_log_flags |= MLF_LAST_TRIGGER_ONLY;
	if (m_log_state_change) 
		m_events[e].mission_log_flags |= MLF_STATE_CHANGE;


	// Search for item to update
	HTREEITEM h = m_event_tree.GetRootItem();
	while (h) {
		if ((int) m_event_tree.GetItemData(h) == m_events[e].formula) {
			m_event_tree.SetItemImage(h, bitmap, bitmap);
			return;
		}

		h = m_event_tree.GetNextSiblingItem(h);
	}

}

// this function deals with the left click on an event in the tree view.  We get into this
// function so that we may update the other data on the screen (i.e repeat count and interval
// count)
void event_editor::OnSelchangedEventTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	int i, z;
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	HTREEITEM h, h2;

	// before we do anything, we must check and save off any data from the current event (i.e.
	// the repeat count and interval count)
	save();
	h = pNMTreeView->itemNew.hItem;
	if (!h){
		return;
	}

	m_event_tree.update_help(h);
	while ((h2 = m_event_tree.GetParentItem(h))>0){
		h = h2;
	}

	z = (int)m_event_tree.GetItemData(h);
	for (i=0; i<(int)m_events.size(); i++){
		if (m_events[i].formula == z){
			break;
		}
	}

	Assert(i < (int)m_events.size());
	cur_event = i;
	update_cur_event();
	
	*pResult = 0;
}

void event_editor::update_cur_event()
{
	if (cur_event < 0) {
		m_repeat_count = 1;
		m_trigger_count = 1;
		m_interval = 1;
		m_chained = FALSE;
		m_chain_delay = 0;
		m_event_score = 0;
		m_team = -1;
		m_obj_text.Empty();
		m_obj_key_text.Empty();
		m_use_msecs = FALSE;

		m_log_true = FALSE;
		m_log_false = FALSE;
		m_log_always_false = FALSE;
		m_log_1st_repeat = FALSE;
		m_log_last_repeat = FALSE;
		m_log_1st_trigger = FALSE;
		m_log_last_trigger = FALSE;
		m_log_state_change = FALSE;

		GetDlgItem(IDC_REPEAT_COUNT)->EnableWindow(FALSE);
		GetDlgItem(IDC_TRIGGER_COUNT)->EnableWindow(FALSE);
		GetDlgItem(IDC_INTERVAL_TIME)->EnableWindow(FALSE);
		GetDlgItem(IDC_CHAINED)->EnableWindow(FALSE);
		GetDlgItem(IDC_CHAIN_DELAY)->EnableWindow(FALSE);
		GetDlgItem(IDC_EVENT_SCORE)->EnableWindow(FALSE);
		GetDlgItem(IDC_EVENT_TEAM)->EnableWindow(FALSE);
		GetDlgItem(IDC_OBJ_TEXT)->EnableWindow(FALSE);
		GetDlgItem(IDC_OBJ_KEY_TEXT)->EnableWindow(FALSE);
		GetDlgItem(IDC_USE_MSECS)->EnableWindow(FALSE);

		GetDlgItem(IDC_MISSION_LOG_TRUE)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_FALSE)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_ALWAYS_FALSE)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_1ST_REPEAT)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_LAST_REPEAT)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_1ST_TRIGGER)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_LAST_TRIGGER)->EnableWindow(FALSE);
		GetDlgItem(IDC_MISSION_LOG_STATE_CHANGE)->EnableWindow(FALSE);

		UpdateData(FALSE);
		return;
	}

	m_team = m_events[cur_event].team;

	m_repeat_count = m_events[cur_event].repeat_count;
	m_trigger_count = m_events[cur_event].trigger_count;
	m_interval = m_events[cur_event].interval;
	m_event_score = m_events[cur_event].score;
	if (m_events[cur_event].chain_delay >= 0) {
		m_chained = TRUE;
		m_chain_delay = m_events[cur_event].chain_delay;
		GetDlgItem(IDC_CHAIN_DELAY) -> EnableWindow(TRUE);

	} else {
		m_chained = FALSE;
		m_chain_delay = 0;
		GetDlgItem(IDC_CHAIN_DELAY) -> EnableWindow(FALSE);
	}

	m_obj_text = m_events[cur_event].objective_text.c_str();
	m_obj_key_text = m_events[cur_event].objective_key_text.c_str();

	GetDlgItem(IDC_REPEAT_COUNT)->EnableWindow(TRUE);
	GetDlgItem(IDC_TRIGGER_COUNT)->EnableWindow(TRUE);

	GetDlgItem(IDC_USE_MSECS)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_TRUE)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_FALSE)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_ALWAYS_FALSE)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_1ST_REPEAT)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_LAST_REPEAT)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_1ST_TRIGGER)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_LAST_TRIGGER)->EnableWindow(TRUE);
	GetDlgItem(IDC_MISSION_LOG_STATE_CHANGE)->EnableWindow(TRUE);

	if ((m_repeat_count < 0) || (m_repeat_count > 1) || (m_trigger_count < 0) || (m_trigger_count > 1)) {
		GetDlgItem(IDC_INTERVAL_TIME) -> EnableWindow(TRUE);
	} else {
		m_interval = 1;
		GetDlgItem(IDC_INTERVAL_TIME) -> EnableWindow(FALSE);
	}

	GetDlgItem(IDC_EVENT_SCORE) -> EnableWindow(TRUE);
	GetDlgItem(IDC_CHAINED) -> EnableWindow(TRUE);
	GetDlgItem(IDC_OBJ_TEXT) -> EnableWindow(TRUE);
	GetDlgItem(IDC_OBJ_KEY_TEXT) -> EnableWindow(TRUE);
	GetDlgItem(IDC_EVENT_TEAM)->EnableWindow(FALSE);
	if ( The_mission.game_type & MISSION_TYPE_MULTI_TEAMS ){
		GetDlgItem(IDC_EVENT_TEAM)->EnableWindow(TRUE);
	}

	// handle event flags
	m_use_msecs = (m_events[cur_event].flags & MEF_USE_MSECS) ? TRUE : FALSE;

	// handle event log flags
	m_log_true = (m_events[cur_event].mission_log_flags & MLF_SEXP_TRUE) ? TRUE : FALSE;
	m_log_false = (m_events[cur_event].mission_log_flags & MLF_SEXP_FALSE) ? TRUE : FALSE;
	m_log_always_false = (m_events[cur_event].mission_log_flags & MLF_SEXP_KNOWN_FALSE) ? TRUE : FALSE;
	m_log_1st_repeat = (m_events[cur_event].mission_log_flags & MLF_FIRST_REPEAT_ONLY) ? TRUE : FALSE;
	m_log_last_repeat = (m_events[cur_event].mission_log_flags & MLF_LAST_REPEAT_ONLY) ? TRUE : FALSE;
	m_log_1st_trigger = (m_events[cur_event].mission_log_flags & MLF_FIRST_TRIGGER_ONLY) ? TRUE : FALSE;
	m_log_last_trigger = (m_events[cur_event].mission_log_flags & MLF_LAST_TRIGGER_ONLY) ? TRUE : FALSE;
	m_log_state_change = (m_events[cur_event].mission_log_flags & MLF_STATE_CHANGE) ? TRUE : FALSE;

	UpdateData(FALSE);
}

void event_editor::OnUpdateRepeatCount()
{
	char buf[128];
	int count = 128; 
	GetDlgItem(IDC_REPEAT_COUNT)->GetWindowText(buf, count);
	m_repeat_count = atoi(buf);

	if ((m_repeat_count < 0) || (m_repeat_count > 1) || (m_trigger_count < 0) || (m_trigger_count > 1)) {
		GetDlgItem(IDC_INTERVAL_TIME)->EnableWindow(TRUE);
	} else {
		GetDlgItem(IDC_INTERVAL_TIME)->EnableWindow(FALSE);
	}
}

void event_editor::OnUpdateTriggerCount()
{
	char buf[128];
	int count = 128;

	GetDlgItem(IDC_TRIGGER_COUNT)->GetWindowText(buf, count);
	m_trigger_count = atoi(buf);

	if ((m_repeat_count < 0) || (m_repeat_count > 1) || (m_trigger_count < 0) || (m_trigger_count > 1)) {
		GetDlgItem(IDC_INTERVAL_TIME)->EnableWindow(TRUE);
	} else {
		GetDlgItem(IDC_INTERVAL_TIME)->EnableWindow(FALSE);
	}
}
void event_editor::move_handler(int node1, int node2, bool insert_before)
{
	int index1, index2, s;
	mission_event e;

	save();

	for (index1=0; index1<(int)m_events.size(); index1++){
		if (m_events[index1].formula == node1){
			break;
		}
	}
	Assert(index1 < (int)m_events.size());

	for (index2=0; index2<(int)m_events.size(); index2++){
		if (m_events[index2].formula == node2){
			break;
		}
	}
	Assert(index2 < (int)m_events.size());

	e = m_events[index1];
	s = m_sig[index1];

	int offset = insert_before ? -1 : 0;

	while (index1 < index2 + offset) {
		m_events[index1] = m_events[index1 + 1];
		m_sig[index1] = m_sig[index1 + 1];
		index1++;
	}
	while (index1 > index2 + offset + 1) {
		m_events[index1] = m_events[index1 - 1];
		m_sig[index1] = m_sig[index1 - 1];
		index1--;
	}

	m_events[index1] = e;
	m_sig[index1] = s;

	cur_event = index2;
	update_cur_event();
}

void event_editor::OnChained() 
{
	int image;
	HTREEITEM h;

	UpdateData(TRUE);
	if (m_chained) {
		GetDlgItem(IDC_CHAIN_DELAY) -> EnableWindow(TRUE);
		if (m_obj_text.IsEmpty()) {
			image = BITMAP_CHAIN;
		} else {
			image = BITMAP_CHAIN_DIRECTIVE;
		}
	} else {
		GetDlgItem(IDC_CHAIN_DELAY) -> EnableWindow(FALSE);
		if (m_obj_text.IsEmpty()) {
			image = BITMAP_ROOT;
		} else {
			image = BITMAP_ROOT_DIRECTIVE;
		}
	}

	h = m_event_tree.GetRootItem();
	while (h) {
		if ((int) m_event_tree.GetItemData(h) == m_events[cur_event].formula) {
			m_event_tree.SetItemImage(h, image, image);
			return;
		}

		h = m_event_tree.GetNextSiblingItem(h);
	}
}

void event_editor::OnSelchangeMessageList() 
{	
	static int flag = 0;

	if (flag)
		return;
/*
	if (save_message(m_cur_msg)) {
		flag = 1;
		((CListBox *) GetDlgItem(IDC_MESSAGE_LIST)) -> SetCurSel(old);
		m_cur_msg = old;
		flag = 0;
		return;
	}*/

	save();
	update_cur_message();
}

int event_editor::save_message(int num)
{
	char *ptr;
	int i, conflict = 0;
	CListBox *list;

	UpdateData(TRUE);
	if (num >= 0) {
		ptr = (char *) (LPCTSTR) m_message_name;
		for (i=0; i<Num_builtin_messages; i++){
			if (!stricmp(m_message_name, Messages[i].name)) {
				conflict = 1;
				break;
			}
		}

		for (i=0; i<(int)m_messages.size(); i++){
			if ((i != num) && (!stricmp(m_message_name, m_messages[i].name))) {
				conflict = 1;
				break;
			}
		}

		if (!conflict) {  // update name if no conflicts, otherwise keep old name
			string_copy(m_messages[num].name, m_message_name, NAME_LENGTH - 1);

			list = (CListBox *) GetDlgItem(IDC_MESSAGE_LIST);
			list->DeleteString(num);
			list->InsertString(num, m_message_name);
		}

		string_copy(m_messages[num].message, m_message_text, MESSAGE_LENGTH - 1);
		m_messages[num].note = m_message_note;
		lcl_fred_replace_stuff(m_messages[num].message, MESSAGE_LENGTH - 1);
		if (m_messages[num].avi_info.name){
			free(m_messages[num].avi_info.name);
		}

		ptr = (char *) (LPCTSTR) m_avi_filename;
		if ( !ptr || !VALID_FNAME(ptr) ) {
			m_messages[num].avi_info.name = NULL;
		} else {
			m_messages[num].avi_info.name = strdup(ptr);
		}

		if (m_messages[num].wave_info.name){
			free(m_messages[num].wave_info.name);
		}

		ptr = (char *) (LPCTSTR) m_wave_filename;
		if ( !ptr || !VALID_FNAME(ptr) ) {
			m_messages[num].wave_info.name = NULL;
		} else {
			m_messages[num].wave_info.name = strdup(ptr);
		}

		// update the persona to the message.  We subtract 1 for the "None" at the beginning of the combo
		// box list.
		m_messages[num].persona_index = m_persona - 1;

		if(m_message_team >= MAX_TVT_TEAMS){
			m_messages[num].multi_team = -1;
			m_message_team = -1;
		} else {
			m_messages[num].multi_team = m_message_team;
		}

		// possible TODO: auto-update event tree references to this message if we renamed it.
	}

	return 0;
}

void event_editor::OnNewMsg() 
{
	MMessage msg; 

	save();
	strcpy_s(msg.name, "<new message>");
	((CListBox *) GetDlgItem(IDC_MESSAGE_LIST))->AddString("<new message>");

	strcpy_s(msg.message, "<put description here>");
	msg.avi_info.name = NULL;
	msg.wave_info.name = NULL;
	msg.persona_index = -1;
	msg.multi_team = -1;
	m_messages.push_back(msg);
	m_cur_msg = (int)m_messages.size() - 1;

	modified = 1;
	update_cur_message();
}

void event_editor::OnDeleteMsg() 
{
	char buf[256];

	// handle this case somewhat gracefully
	Assertion((m_cur_msg >= -1) && (m_cur_msg < (int)m_messages.size()), "Unexpected m_cur_msg value (%d); expected either -1, or between 0-%d. Get a coder!\n", m_cur_msg, (int)m_messages.size() - 1);
	if((m_cur_msg < 0) || (m_cur_msg >= (int)m_messages.size())){
		return;
	}

	if (m_messages[m_cur_msg].avi_info.name){
		free(m_messages[m_cur_msg].avi_info.name);
	}
	if (m_messages[m_cur_msg].wave_info.name){
		free(m_messages[m_cur_msg].wave_info.name);
	}

	((CListBox *) GetDlgItem(IDC_MESSAGE_LIST))->DeleteString(m_cur_msg);
	sprintf(buf, "<%s>", m_messages[m_cur_msg].name);
	update_sexp_references(m_messages[m_cur_msg].name, buf, OPF_MESSAGE);
	update_sexp_references(m_messages[m_cur_msg].name, buf, OPF_MESSAGE_OR_STRING);

	m_messages.erase(m_messages.begin() + m_cur_msg); 

	if (m_cur_msg >= (int)m_messages.size()){
		m_cur_msg = (int)m_messages.size() - 1;
	}

	GetDlgItem(IDC_NEW_MSG)->EnableWindow(TRUE);
	modified = 1;
	update_cur_message();
}

void event_editor::OnMsgNote()
{
	// handle this case somewhat gracefully
	Assertion((m_cur_msg >= -1) && (m_cur_msg < (int)m_messages.size()), "Unexpected m_cur_msg value (%d); expected either -1, or between 0-%d. Get a coder!\n", m_cur_msg, (int)m_messages.size() - 1);
	if((m_cur_msg < 0) || (m_cur_msg >= (int)m_messages.size())){
		return;
	}

	CString old_text = m_message_note;
	CString new_text;

	TextViewDlg dlg;
	dlg.SetText(old_text);
	dlg.SetCaption("Enter a note");
	dlg.SetEditable(true);
	dlg.DoModal();
	dlg.GetText(new_text);

	// comment is unchanged
	if (new_text == old_text)
		return;

	m_message_note = new_text;
}

void event_editor::OnBrowseAvi() 
{
	int z;
	CString name;	

	UpdateData(TRUE);
	if (!stricmp(m_avi_filename, "<None>"))
		m_avi_filename = _T("");

	z = cfile_push_chdir(CF_TYPE_INTERFACE);
	CFileDialog dlg(TRUE, "png", m_avi_filename, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR,
		"APNG Files (*.png)|*.png|Ani Files (*.ani)|*.ani|Eff Files (*.eff)|*.eff|All Anims (*.ani, *.eff, *.png)|*.ani;*.eff;*.png|");

	if (dlg.DoModal() == IDOK) {
		m_avi_filename = dlg.GetFileName();
		UpdateData(FALSE);
		modified = 1;
	}

	if (!z)
		cfile_pop_dir();
}

void event_editor::OnBrowseWave() 
{
	int z;
	CString name;

	audiostream_close_file(m_wave_id, 0);
	m_wave_id = -1;

	UpdateData(TRUE);
	if (!stricmp(m_wave_filename, "<None>"))
		m_wave_filename = _T("");

	if (The_mission.game_type & MISSION_TYPE_TRAINING)
		z = cfile_push_chdir(CF_TYPE_VOICE_TRAINING);
	else
		z = cfile_push_chdir(CF_TYPE_VOICE_SPECIAL);

	CFileDialog dlg(TRUE, "wav", m_wave_filename, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR,
		"Voice Files (*.ogg, *.wav)|*.ogg;*.wav|Ogg Vorbis Files (*.ogg)|*.ogg|Wave Files (*.wav)|*.wav||");

	if (dlg.DoModal() == IDOK) {
		m_wave_filename = dlg.GetFileName();
		update_persona();
	}

	if (!z){
		cfile_pop_dir();
	}
}

char *event_editor::current_message_name(int i)
{
	if ( (i < 0) || (i >= (int)m_messages.size()) ){
		return NULL;
	}

	return m_messages[i].name;
}

char *event_editor::get_message_list_item(int i)
{
	return m_messages[i].name;
}

void event_editor::update_persona()
{
	int i, mask;

	if ((m_wave_filename[0] >= '1') && (m_wave_filename[0] <= '9') && (m_wave_filename[1] == '_') ) {
		i = m_wave_filename[0] - '1';
		if ((i < (int)Personas.size()) && (Personas[i].flags & PERSONA_FLAG_WINGMAN)) {
			m_persona = i + 1;
			if ((m_persona==1) || (m_persona==2)) 
				m_avi_filename = "HEAD-TP1";
			else if ((m_persona==3) || (m_persona==4))
				m_avi_filename = "HEAD-TP2";
			else if ((m_persona==5))
				m_avi_filename = "HEAD-TP3";
			else if ((m_persona==6))
				m_avi_filename = "HEAD-VP1";
		}
	} else {
		mask = 0;
		if (!strnicmp(m_wave_filename, "S_", 2)) {
			mask = PERSONA_FLAG_SUPPORT;
			m_avi_filename = "HEAD-CM1";
		}
		else if (!strnicmp(m_wave_filename, "L_", 2)) {
			mask = PERSONA_FLAG_LARGE;
			m_avi_filename = "HEAD-CM1";
		}
		else if (!strnicmp(m_wave_filename, "TC_", 3)) {
			mask = PERSONA_FLAG_COMMAND;
			m_avi_filename = "HEAD-CM1";
		}

		for (i = 0; i < (int)Personas.size(); i++)
			if (Personas[i].flags & mask)
				m_persona = i + 1;
	}
	//GetDlgItem(IDC_ANI_FILENAME)->SetWindowText(m_avi_filename);
	UpdateData(FALSE);
	modified = 1;
}

void event_editor::OnSelchangeWaveFilename() 
{
	int z;
	CComboBox *box;

	audiostream_close_file(m_wave_id, 0);
	m_wave_id = -1;

	box = (CComboBox *) GetDlgItem(IDC_WAVE_FILENAME);
	z = box -> GetCurSel();
	UpdateData(TRUE);
	UpdateData(TRUE);

	box -> GetLBText(z, m_wave_filename);
	UpdateData(FALSE);
	update_persona();
}

BOOL event_editor::DestroyWindow() 
{
	audiostream_close_file(m_wave_id, 0);
	m_wave_id = -1;

	m_play_bm.DeleteObject();
	return CDialog::DestroyWindow();
}

void event_editor::OnPlay() 
{
	GetDlgItem(IDC_WAVE_FILENAME)->GetWindowText(m_wave_filename);

	if (m_wave_id >= 0) {
		audiostream_close_file(m_wave_id, 0);
		m_wave_id = -1;
		return;
	}

	// we use ASF_EVENTMUSIC here so that it will keep the extension in place
	m_wave_id = audiostream_open((char *)(LPCSTR) m_wave_filename, ASF_EVENTMUSIC);

	if (m_wave_id >= 0) {
		audiostream_play(m_wave_id, 1.0f, 0);
	}
}

void event_editor::OnUpdateStuff() 
{
	int z = MessageBox("This will set the head ANIs according to the FS1 personas.  Do you want to proceed?\n\n(Consider using the 'Sync Personas' buttons in the Voice Acting Manager instead.)", "Update Stuff", MB_ICONQUESTION | MB_YESNO);
	if (z != IDYES) {
		return;
	}

//	GetDlgItem(IDC_WAVE_FILENAME)->GetWindowText(m_wave_filename);
	UpdateData(TRUE);
	update_persona();
}

// code when the "team" selection in the combo box changes
void event_editor::OnSelchangeTeam() 
{
	if ( cur_event < 0 ){
		return;
	}

	UpdateData(TRUE);

	// If the team isn't valid mark it as such. 
	if((m_team >= MAX_TVT_TEAMS) || (m_team < -1) ){
		m_team = -1;
	}

	m_events[cur_event].team = m_team;
}

// code when the "team" selection in the combo box changes
void event_editor::OnSelchangeMessageTeam() 
{
	if ( m_cur_msg < 0 ){
		return;
	}

	UpdateData(TRUE);

	// If the team isn't valid mark it as such. 
	if((m_message_team>= MAX_TVT_TEAMS) || (m_message_team < -1) ) {
		m_message_team = -1;
	}

	m_messages[m_cur_msg].multi_team = m_message_team;
}

// Cycles among sexp nodes with message text
void event_editor::OnDblclkMessageList() 
{
	CListBox *list = (CListBox*) GetDlgItem(IDC_MESSAGE_LIST);
	int num_messages;
	int message_nodes[MAX_SEARCH_MESSAGE_DEPTH];

	// get current message index and message name
	int cur_index = list->GetCurSel();

	// check if message name is in event tree
	char buffer[256];
	list->GetText(cur_index, buffer);


	num_messages = m_event_tree.find_text(buffer, message_nodes);

	if (num_messages == 0) {
		char message[256];
		sprintf(message, "No events using message '%s'", buffer);
		MessageBox(message);
	} else {
		// find last message_node
		if (m_last_message_node == -1) {
			m_last_message_node = message_nodes[0];
		} else {

			if (num_messages == 1) {
				// only 1 message
				m_last_message_node = message_nodes[0];
			} else {
				// find which message and go to next message
				int found_pos = -1;
				for (int i=0; i<num_messages; i++) {
					if (message_nodes[i] == m_last_message_node) {
						found_pos = i;
						break;
					}
				}

				if (found_pos == -1) {
					// no previous message
					m_last_message_node = message_nodes[0];
				} else if (found_pos == num_messages-1) {
					// cycle back to start
					m_last_message_node = message_nodes[0];
				} else {
					// go to next
					m_last_message_node = message_nodes[found_pos+1];
				}
			}
		}

		// highlight next
		m_event_tree.hilite_item(m_last_message_node);
	}
}

void event_annotation_prune()
{
	Event_annotations.erase(
		std::remove_if(Event_annotations.begin(), Event_annotations.end(), [](const event_annotation &ea)
		{
			return ea.comment == default_ea.comment
				&& ea.r == default_ea.r
				&& ea.g == default_ea.g
				&& ea.b == default_ea.b;
		}),
		Event_annotations.end()
	);
}

int event_annotation_lookup(HTREEITEM handle)
{
	for (size_t i = 0; i < Event_annotations.size(); ++i)
	{
		if (Event_annotations[i].handle == handle)
			return (int)i;
	}

	return -1;
}

void event_annotation_swap_image(event_sexp_tree *tree, HTREEITEM handle, int annotation_index)
{
	event_annotation_swap_image(tree, handle, Event_annotations[annotation_index]);
}

void event_annotation_swap_image(event_sexp_tree *tree, HTREEITEM handle, event_annotation &ea)
{
	// see if this node is a top-level event - if so, don't mess with the image
	if (!tree->GetParentItem(handle))
		return;

	int nImage, nSelectedImage;
	tree->GetItemImage(handle, nImage, nSelectedImage);

	// if tree node already has the comment image, replace it with the old one
	if (nImage == BITMAP_COMMENT)
	{
		nImage = ea.item_image;
	}
	// if tree has its normal image, store it and use the comment image
	else
	{
		ea.item_image = nImage;
		nImage = BITMAP_COMMENT;
	}

	// all tree nodes use the same image for both selected and unselected
	tree->SetItemImage(handle, nImage, nImage);
}

// tooltip stuff is based on example at
// https://www.codeproject.com/articles/1761/ctreectrl-clistctrl-clistbox-with-tooltip-based-on

void event_sexp_tree::PreSubclassWindow()
{
	CTreeCtrl::PreSubclassWindow();
	EnableToolTips(TRUE);
}

INT_PTR event_sexp_tree::OnToolHitTest(CPoint point, TOOLINFO *pTI) const
{
	RECT rect;

	UINT nFlags;
	HTREEITEM hitem = HitTest(point, &nFlags);
	if (nFlags & TVHT_ONITEMLABEL)
	{
		GetItemRect(hitem, &rect, TRUE);
		pTI->hwnd = m_hWnd;
		pTI->uId = (UINT)hitem;
		pTI->lpszText = LPSTR_TEXTCALLBACK;
		pTI->rect = rect;
		return pTI->uId;
	}

	return -1;
}

//here we supply the text for the item 
BOOL event_sexp_tree::OnToolTipText(UINT id, NMHDR *pNMHDR, LRESULT *pResult)
{
	// need to handle both ANSI and UNICODE versions of the message
	TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
	TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;

	UINT_PTR nID = pNMHDR->idFrom;

	// Do not process the message from built in tooltip 
	if (nID == (UINT_PTR)m_hWnd &&
		((pNMHDR->code == TTN_NEEDTEXTA && pTTTA->uFlags & TTF_IDISHWND) ||
		(pNMHDR->code == TTN_NEEDTEXTW && pTTTW->uFlags & TTF_IDISHWND)))
		return FALSE;

	// Get the mouse position
	auto pMessage = GetCurrentMessage(); // get mouse pos 
	ASSERT(pMessage);
	auto pt = pMessage->pt;
	ScreenToClient(&pt);

	UINT nFlags;
	HTREEITEM h = HitTest(pt, &nFlags); //Get item pointed by mouse

	if (h)
	{
		int ea_idx = event_annotation_lookup(h);
		if (ea_idx >= 0)
		{
			auto ea = &Event_annotations[ea_idx];

			if (ea->comment != default_ea.comment && !ea->comment.empty())
			{
				m_tooltiptextA = ea->comment.c_str();
				m_tooltiptextW = ea->comment.c_str();

				if (pNMHDR->code == TTN_NEEDTEXTA)
				{
					pTTTA->lpszText = (LPSTR)(LPCSTR)m_tooltiptextA;
					::SendMessage(pTTTA->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 400);
				}
				else
				{
					pTTTW->lpszText = (LPWSTR)(LPCWSTR)m_tooltiptextW;
					::SendMessage(pTTTW->hdr.hwndFrom, TTM_SETMAXTIPWIDTH, 0, 400);
				}
			}
		}
	}

	*pResult = 0;

	return TRUE;    // message was handled
}

// color stuff is based on example at
// https://stackoverflow.com/questions/2119717/changing-the-color-of-a-selected-ctreectrl-item

void event_sexp_tree::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
	static CRect rect;
	static bool drawBorder = false;

	NMTVCUSTOMDRAW *pcd = (NMTVCUSTOMDRAW *)pNMHDR;
	switch (pcd->nmcd.dwDrawStage)
	{
		case CDDS_PREPAINT:
			*pResult = CDRF_NOTIFYITEMDRAW;
			break;

		case CDDS_ITEMPREPAINT:
		{
			drawBorder = false;
			*pResult = CDRF_DODEFAULT;

			HTREEITEM hItem = (HTREEITEM)pcd->nmcd.dwItemSpec;
			if (hItem)
			{
				int ea_idx = event_annotation_lookup(hItem);
				if (ea_idx >= 0)
				{
					auto ea = &Event_annotations[ea_idx];

					if (ea->r != default_ea.r || ea->g != default_ea.g || ea->b != default_ea.b)
					{
						// contrast color calculation taken from here:
						// https://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color
						if ((ea->r*0.299 + ea->g*0.587 + ea->b*0.114) > 149)
							pcd->clrText = RGB(0, 0, 0);
						else
							pcd->clrText = RGB(255, 255, 255);

						pcd->clrTextBk = RGB(ea->r, ea->g, ea->b);

						// if this is selected, save some information for drawing a border later
						if (pcd->nmcd.uItemState & CDIS_SELECTED)
						{
							drawBorder = true;
							GetItemRect((HTREEITEM)pcd->nmcd.dwItemSpec, &rect, TRUE);
							// we want to get the CDDS_ITEMPOSTPAINT notification
							*pResult = CDRF_NOTIFYPOSTPAINT;
						}
					}
				}
			}
			break;
		}

		case CDDS_ITEMPOSTPAINT:
		{
			// see Solution 2 here: https://www.codeproject.com/Questions/685172/CTreeCtrl-with-Item-Border
			if (drawBorder)
			{
				SelectObject(pcd->nmcd.hdc, CreatePen(PS_INSIDEFRAME, 2, RGB(0, 0, 0)));
				SelectObject(pcd->nmcd.hdc, GetStockObject(HOLLOW_BRUSH));
				Rectangle(pcd->nmcd.hdc, rect.left, rect.top, rect.right, rect.bottom);
			}
			break;
		}
	}
}

void event_sexp_tree::edit_comment(HTREEITEM h)
{
	CString old_text = _T("");
	CString new_text;

	int i = event_annotation_lookup(h);
	if (i >= 0)
		old_text = (CString)Event_annotations[i].comment.c_str();

	TextViewDlg dlg;
	dlg.SetText(old_text);
	dlg.SetCaption("Enter a comment");
	dlg.SetEditable(true);
	dlg.DoModal();
	dlg.GetText(new_text);

	// comment is unchanged
	if (new_text == old_text)
		return;

	// maybe add the annotation
	if (i < 0)
	{
		i = (int)Event_annotations.size();
		Event_annotations.emplace_back();
		Event_annotations[i].handle = h;
	}

	Event_annotations[i].comment = new_text;

	// see if we are either adding a new comment or removing an existing comment
	// if so, change the icon
	if (old_text.IsEmpty() || new_text.IsEmpty())
		event_annotation_swap_image(this, h, i);
}

void event_sexp_tree::edit_bg_color(HTREEITEM h)
{
	COLORREF old_color = RGB(255, 255, 255);
	COLORREF new_color;

	int i = event_annotation_lookup(h);
	if (i >= 0)
		old_color = RGB(Event_annotations[i].r, Event_annotations[i].g, Event_annotations[i].b);

	CColorDialog dlg(old_color);
	if (dlg.DoModal() != IDOK)
		return;
	new_color = dlg.GetColor();

	// color is unchanged
	if (new_color == old_color)
		return;

	// maybe add the annotation
	if (i < 0)
	{
		i = (int)Event_annotations.size();
		Event_annotations.emplace_back();
		Event_annotations[i].handle = h;
	}

	Event_annotations[i].r = GetRValue(new_color);
	Event_annotations[i].g = GetGValue(new_color);
	Event_annotations[i].b = GetBValue(new_color);

	// This is needed otherwise the color won't change until the user clicks something
	RedrawWindow();
}

void event_editor::populate_path(event_annotation &ea, HTREEITEM h)
{
	HTREEITEM parent = m_event_tree.GetParentItem(h);

	// this is a node in the event tree
	if (parent)
	{
		int child_num = 0;
		HTREEITEM child = h;
		while ((child = m_event_tree.GetPrevSiblingItem(child)) != nullptr)
			++child_num;

		// push the number and iterate up
		ea.path.push_front(child_num);
		populate_path(ea, parent);
	}
	// if this has no parent, it's an event, so find out which event it is
	else
	{
		int event_num = get_event_num(h);
		if (event_num >= 0)
		{
			ea.path.push_front(event_num);
		}
		else
		{
			Warning(LOCATION, "Could not find event for this handle!\n");
			ea.path.clear();
		}
	}
}

HTREEITEM event_editor::traverse_path(const event_annotation &ea)
{
	if (ea.path.empty())
		return nullptr;

	int event_num = ea.path.front();
	HTREEITEM h = get_event_handle(event_num);
	if (!h)
		return nullptr;

	if (ea.path.size() > 1)
	{
		auto it = ea.path.begin();
		for (++it; it != ea.path.end(); ++it)
		{
			int child_num = *it;

			h = m_event_tree.GetChildItem(h);
			while (child_num > 0 && h)
			{
				h = m_event_tree.GetNextSiblingItem(h);
				--child_num;
			}

			if (!h)
				return nullptr;
		}
	}

	return h;
}