summaryrefslogtreecommitdiff
path: root/docview/src/HelpTopic.pas
blob: 8b12b569913256113930bdc981e562d525c95626 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
Unit HelpTopic;

{$mode objfpc}{$H+}

Interface

// This is it - the monster which decodes IPF data.
// It's created with a reference to the contents data defining it.
// It gets relevant pointers out of that. When GetText is called
// it decodes the data and spits out formatted text to suit
// RichTextView.

uses
  Classes,
  HelpWindowDimensions,
  IPFFileFormatUnit;

const
  DefaultGroupIndex = 0;

  RTF_NewLine = #10;

var
  { TODO -oGraeme -cPointers : I don't like this - double check alternatives later }
  // placeholder for font table entry, indiciating user fixed font should be substituted
  SubstituteFixedFont: pointer = Pointer(1);

type
  THelpLink = class(TObject)
  public
    HelpFile: TObject;     // file this link is within
    // Even though it doesn't do anything,
    // we have to have a constructor to allow
    // virtual constructors to work
    constructor Create; virtual;
  end;


  THelpTopicSlot = class(TObject)
  public
    pData: pUInt8;                            // Pointer to actual Slot structure in INF file.
    Size: longint;                            // Number of bytes in the text for this Slot (slotheader.ntext)
    pLocalDictionary: UInt16ArrayPointer;     // Pointer to Slot's local dictionary
    LocalDictSize: uint8;                     // Number of entries in the local dictionary
    destructor Destroy; override;
  end;


  THelpLinkClass = class of THelpLink;


  TFootnoteHelpLink = class(THelpLink)
  public
    TopicIndex: longint;
    Title: string; // from text within link
  end;


  TWindowedHelpLink = class(THelpLink)
  public
    GroupIndex: longint;   // DefaultGroupIndex if not specified.
                           // Note: Overrides contents group index of topic
    Automatic: boolean;    // link should be automatically followed on topic display
    Split: boolean;        // link should open the window within the parent
    ViewPort: boolean;     // link should always open a new window
    Dependent: boolean;    // window opened by link should be closed
                           // when current topic is closed
    Rect: THelpWindowRect; // Display window with this rectangle.
                           // Note: overrides contents rect
    constructor Create; override;
    destructor Destroy; override;
  end;


  TInternalHelpLink = class(TWindowedHelpLink)
  public
    TopicIndex: longint;
  end;


  THelpLinkByResourceID = class(TWindowedHelpLink)
  public
    ResourceID: longint;
  end;


  SlotArray = array[0..0] of THelpTopicSlot;
  pSlotArray = ^SlotArray;


  TFontState = (fsNormal, fsFixed, fsCustom);
  TIPFTextAlignment = (itaLeft, itaRight, itaCenter, itaCenterOnePara);


  TParseState = record
    Alignment: TIPFTextAlignment;
    ForegroundColorTag: string;
    BackgroundColorTag: string;
    Spacing: boolean;
    FontState: TFontState;
    InCharGraphics: boolean;
    LinkIndex: longint;
    StartOfTextBlock: longint;
    TextBlock: string;
    FootnoteLink: TFootnoteHelpLink;
    StyleCode: longint;
  end;


  TTopic = class(TObject)
  protected
    _FileHandle: TFileStream;
    _pTOCEntry: pTTOCEntryStart;
    _pSlotOffsets: UInt32ArrayPointer;
    _Slots: TList;
    _pSlotNumbers: puint16;
    _NumSlots: longint;
    _Title: string;
    _GlobalDictionary: TStringList;
    _ShowInContents: boolean;
    _ContentsLevel: integer;
    _ContentsGroupIndex: longint;
    _FontTable: TList;
    _ReferencedFiles: TStrings;
    procedure SetTitle( const NewValue: string );
    function GetTitle: string;

    // Returns the tag texts for the given bitmap ref
    function GetImageText( CurrentAlignment: TIPFTextAlignment;
                           BitmapOffset: longint;
                           BitmapFlags: longint;
                           ImageOffsets: TList ): string;

    Procedure ProcessLinkedImage( Var State: TParseState;
                                  Var pData: pByte;
                                  Var OutputString: string;
                                  ImageOffsets: TList );
    procedure TranslateIPFEscapeCode( Var State: TParseState;
                                      Var pData: pUInt8;
                                      var AText: String;
                                      Var WordsOnLine: longint;
                                      ImageOffsets: TList );

    function CreateLink( Var LinkIndex: longint;
                         Var Link: THelpLink;
                         LinkClass: THelpLinkClass ): boolean;

    procedure EnsureSlotsLoaded;

    // returns true if the escape code at pData results in whitespace.
    function IPFEscapeCodeSpace( Var State: TParseState; Var pData: pUInt8 ): boolean;

    function GetNextIPFTextItem( Var SlotIndex: longint;
                             Var pData: pUInt8;
                             Var State: TParseState ): longint;

    function CheckForSequence( WordSequences: TList;
                               SlotIndex: longint;
                               pData: pUint8;
                               State: TParseState;
                               GlobalDictIndex: longint
                             ): longint;

  public
    HelpFile: TObject;
    Index: longint;
    SearchRelevance: longint;
    Links: TList; // only valid after GetText
    constructor Create( var FileHandle: TFileStream;
                        pSlotOffsets: UInt32ArrayPointer;
                        Dictionary: TStringList;
                        var pTOCEntry: pTTOCEntryStart;
                        FontTable: TList;
                        ReferencedFiles: TStrings );
    destructor Destroy; override;
    property Title: string read GetTitle write SetTitle;
    procedure SetTitleFromMem( const p: pointer; const Len: byte );
    // Main function for retrieving text for topic.
    // HighlightSequences: list of sequences to highlight
    // if nil then ignored.
    // ShowCodes: indicates debugging: hex output of escape
    //   codes will be included
    // ShowWordSeparators: | will be included after each dictionary
    //   word inserted
    // Text: The output is written to here. IS NOT CLEARED FIRST.
    // ImageOffsets: For each image that occurs in the text,
    //   the help file offset will be written to this list.
    // HighlightMatches: if not nil, and HighlightSequences is not nil,
    // will return offsets to each highlight match
    procedure GetText( HighlightSequences: TList;
                       ShowCodes: boolean;
                       ShowWordSeparators: boolean;
                       var Text: String;
                       ImageOffsets: TList;
                       HighlightMatches: TList );
    // if StopAtFirstOccurrence true, returns 0 or 1
    // if false, returns count of occurrences of word
    function SearchForWord( DictIndex: integer;
                            StopAtFirstOccurrence: boolean ): longint;
    // searches for sequences out of those listed in WordSequence
    // Each element of WordSequence contains a pointer to an array
    // of flags for each dictionary word, indicating whether that word
    // is to be a possible match.
    function SearchForWordSequences( WordSequence: TList; StopAtFirstOccurrence: boolean ): longint;
    procedure GetContentsWindowRect( ContentsRect: THelpWindowRect );
    // search for binary data including codes
    function SearchForData( Data: pbyte; DataLen: integer ): boolean;
    procedure SaveIPFEscapeCode( Var State: TParseState;
                                 Var pData: pUInt8;
                                 Var F: TextFile;
                                 ImageOffsets: TList );
    procedure SaveToIPF( Var f: TextFile; ImageOffsets: TList );
    property ShowInContents: boolean read _ShowInContents;
    property ContentsLevel: integer read _ContentsLevel;
    property ContentsGroupIndex: longint read _ContentsGroupIndex;
    function CountWord( DictIndex: integer ): longint;
    function ContainsWord( DictIndex: integer ): boolean;
  end;


// Compares two topics for purposes of sorting by
// search match relevance
function TopicRelevanceCompare( Item1, Item2: pointer ): longint;

// Compares two topics for purposes of sorting by title
function TopicTitleCompare( Item1, Item2: pointer ): longint;


implementation


uses
  SysUtils
  ,dvConstants
  ,nvUtilities
  ,ACLStringUtility
  ,SettingsUnit
  ,fpg_stringutils
  ,HelpFile
  ;

const
  IPFColors: array[ 0..15 ] of string =
  (
    //rrggbb
    '', // default
    '#0000ff', // blue
    '#ff0000', // red
    '#ff00ff', // pink (purple)
    '#00ff00', // green
    '#00ffff', // cyan
    '#ffff00', // yellow
    '#808000', // neutral = brown
    '#404040', // dark gray
    '#000080', // dark blue
    '#800000', // dark red
    '#800080', // dark pink (purple)
    '#008000', // dark green
    '#008080', // dark cyan
    '#000000', // black
    '#c0c0c0'  // pale gray
  );

  // for ecHighlight1
  IPFHighlight1Tags : array [ 0..6 ] of string =
  (
    '</i></b></u></color>',  // normal
    '<i>',           // hp1 italitc
    '<b>',           // hp2 bold
    '<b><i>',        // hp3 bold italic
    '<u>',           // hp5 underline
    '<u><i>',        // hp6 underline italic
    '<u><b>'         // hp7 underline bold
  );

  // for ecHighlight2
  IPFHighlight2Tags : array [ 0..3 ] of string =
  (
    '</i></b></u></color>',  // normal
    '<color blue>',  // hp4 blue
    '<color red>',   // hp8 red
    '<color purple>' // hp9 purple
  );

  BlankString: string = '';

var
  DefaultTitle: string;


function GetBeginLink( LinkIndex: longint ): string;
begin
  Result := '<link ' + IntToStr( LinkIndex ) + '>'
end;

function GetEndLinkTags( const State: TParseState ): string;
begin
  Result := '</link>' + State.ForegroundColorTag;
end;

// Even though it doesn't do anything,
// we have to have a constructor to allow
// virtual constructors to work
constructor THelpLink.Create;
begin
  // do nothing
end;

constructor TWindowedHelpLink.Create;
begin
  GroupIndex := DefaultGroupIndex;
  Automatic := false;
  ViewPort := false;
  Dependent := false;
  Rect := THelpWindowRect.Create;
end;

destructor TWindowedHelpLink.Destroy;
begin
  Rect.Destroy;
end;

destructor THelpTopicSlot.Destroy;
begin
  { TODO -ograeme -ccleanup memory : Double check this }
  FreeMem(pData);//  DeallocateMemory( pData );
  FreeMem(pLocalDictionary); // DeallocateMemory( pLocalDictionary );
end;

constructor TTopic.Create( var FileHandle: TFileStream;
                           pSlotOffsets: UInt32ArrayPointer;
                           Dictionary: TStringList;
                           var pTOCEntry: pTTOCEntryStart;
                           FontTable: TList;
                           ReferencedFiles: TStrings );
var
  pExtendedInfo: pExtendedTOCEntry;
  titleLen: integer;
  XY: THelpXYPair;
  p: pbyte;
  Flags: byte;
begin
  _FileHandle := FileHandle;
  _pSlotOffsets := pSlotOffsets;

  _Title := '';
  _GlobalDictionary := Dictionary;
  _ContentsGroupIndex := 0;

  _pTOCEntry := pTOCEntry;
  _NumSlots := pTOCEntry^.numslots;

  Flags := _pTOCEntry^.flags;
  p := pByte( _pTOCEntry ) + sizeof( TTOCEntryStart );

  if ( Flags and TOCEntryExtended ) = TOCEntryExtended then
  begin
    pExtendedInfo := pExtendedTOCEntry( p );
    inc( p, sizeof( TExtendedTOCEntry ) );

    if ( pExtendedInfo^.w1 and 1 ) > 0 then
      // skip position
      inc( p, sizeof( XY ) );

    if ( pExtendedInfo^.w1 and 2 ) > 0 then
      // skip size
      inc( p, sizeof( XY ) );

    if ( pExtendedInfo^.w1 and 8 ) > 0 then
      // skip window controls
      inc( p, sizeof(word) );    // increment by 2

    if ( pExtendedInfo^.w1 and $40 ) > 0 then
      // skip something else, unknown... style? 2 bytes
      inc( p, sizeof(word) );    // increment by 2

    if ( pExtendedInfo^.w2 and 4 ) > 0 then
    begin
      _ContentsGroupIndex := pUInt16(p)^;
      // read group
      inc( p, sizeof( uint16 ) );
    end;
  end;

  // skip slot numbers for now.
  _pSlotNumbers := pUInt16(p);
  inc( p, _NumSlots * sizeof( uint16 ) );

  // Calculate the remainder of the tocentry length - that is the bytes used for TOC topic (title) text
  titleLen := _pTOCEntry^.length - ( longword( p ) - longword( _pTOCEntry ) );

  // Read title
  if TitleLen > 0 then
    SetTitleFromMem( p, TitleLen )
  else
    Title := DefaultTitle;

  _ContentsLevel := ( Flags and TOCEntryLevelMask );
  _ShowInContents := Flags and TOCEntryHidden = 0;
  if _ContentsLevel = 0 then
    _ShowInContents := false; // hmmm....

  _FontTable := FontTable;
  _ReferencedFiles := ReferencedFiles;
end;

destructor TTopic.Destroy;
begin
  LogEvent(LogObjConstDest, 'TTopic.Destroy');
  DestroyListAndObjects( Links );
  DestroyListAndObjects( _Slots );
  inherited Destroy;
end;

procedure TTopic.SetTitle( const NewValue: string );
begin
  _Title := NewValue;
end;

procedure TTopic.SetTitleFromMem( const p: pointer; const Len: byte );
begin
  //FreePString( _Title );
  //GetMem( _Title, Len + 1 );
  //_Title^[ 0 ] := char( Len );
  //MemCopy( p, _Title + 1, Len );
  SetString(_Title, p, Len);
end;

function TTopic.GetTitle: string;
begin
  Result := _Title;
end;

// Replace < and > characters with doubles << and >>
// for compatibility with richtextview.
// This works in place, assuming that instances of > or < are
// actually rare. In practice, IPF normally would insert these
// two characters as distinct words, but I don't want to assume that.
procedure SubstituteAngleBrackets( Var s: string );
var
  i: integer;
begin
  i := 1;
  while i <= Length( S ) do
  begin
    case S[ i ] of
      '<':
      begin
        Insert( '<', s, i );
        inc( i );
      end;

      '>':
      begin
        Insert( '>', s, i );
        inc( i );
      end;
    end;
    inc( i );
  end;
end;

function TTopic.GetImageText( CurrentAlignment: TIPFTextAlignment;
                              BitmapOffset: longint;
                              BitmapFlags: longint;
                              ImageOffsets: TList ): string;
var
  BitmapIndex: longint;
  OriginalAlignTag: string;
  ImageTag: string;
  AlignTag: string;
begin
  BitmapIndex := ImageOffsets.IndexOf( pointer( BitmapOffset ) );
  if BitmapIndex = -1 then
    BitmapIndex := ImageOffsets.Add( pointer( BitmapOffset ) );

  ImageTag := '<image '
              + IntToStr( BitmapIndex )
              + '>';

  if ( BitmapFlags and $08 ) > 0 then
  begin
    // stretch to fit - not implemented
  end;

  // aligned
  case CurrentAlignment of
    itaLeft:
      OriginalAlignTag := '<align left>';
    itaRight:
      OriginalAlignTag := '<align right>';
    itaCenter,
    itaCenterOnePara:
      OriginalAlignTag := '<align center>';
  end;

  case BitmapFlags and 7 of
    0, // curious - should not occur? does in dbexpert.hlp
    1: // left
      AlignTag := '<align left>';
    2: // right
      AlignTag := '<align right>';
    4,5: // centre (4 is official, 5 seems to occur too)
      AlignTag := '<align center>';
  end;

  Result := AlignTag
            + ImageTag
            + OriginalAlignTag;

  if ( BitmapFlags and $10 ) = 0 then
  begin
    // NOT runin, new lines before and after
    Result := RTF_NewLine + Result + RTF_NewLine;
  end;

end;

Procedure SaveImageText( BitmapOffset: longint;
                         BitmapFlags: longint;
                         Var F: TextFile;
                         ImageOffsets: TList );
var
  ImageIndex: longint;
begin
  ImageIndex := ImageOffsets.IndexOf( pointer( BitmapOffset ) );
  if ImageIndex = -1 then
    ImageIndex := ImageOffsets.Add( pointer( BitmapOffset ) );

  Write( F, ':artwork name=' );
  Write( F, StrInSingleQuotes('img' + IntToStr(ImageIndex) + '.bmp') );

  case BitmapFlags and 7 of
    2: // right
      Write( F, ' align=right' );
    4,5: // centre (4 is official, 5 seems to occur too)
      Write( F, ' align=center' );
  end;

  if ( BitmapFlags and $10 ) > 0 then
  begin
    // runin
    Write( F, ' runin' );
  end;

  // fit ...
  Write( F, '.' );
end;

Procedure TTopic.ProcessLinkedImage( Var State: TParseState;
                                     Var pData: pByte;
                                     Var OutputString: string;
                                     ImageOffsets: TList );
var
  EscapeLen: uint8;
  EscapeCode: uint8;
  SubEscapeCode: uint8;
  BitmapOffset: longword;
  BitmapFlags: uint8;
  Link: THelpLink;//TInternalHelpLink;
  LinkTopicIndex: integer;
begin
  LinkTopicIndex := -1;
  while true do
  begin
    EscapeLen := pData^;
    SubEscapeCode := ( pData + 2 )^;
    case SubEscapeCode of
      HPART_DEFINE:
      begin
        BitmapFlags := ( pData + 3 )^;
        BitmapOffset := pUInt32( pData + 4 )^;
      end;

      HPART_HDREF: // define whole bitmap topic link?
      begin
        LinkTopicIndex := pUInt16( pData + 3 )^;
      end;
    end;
    inc( pData, EscapeLen );

    // Now pData points at next code or item
    if pData^ <> IPF_ESC then
      // not an escape code, done
      break;
    EscapeCode := (pData + 2) ^;
    if EscapeCode <> ecLinkedImage then
      // not a hyperlink code, done
      break;
    // another linked image code is coming up.
    SubEscapeCode := ( pData + 3 )^;
    if SubEscapeCode = HPART_DEFINE then
      // started another linked image.
      break;
    inc( pData ); // move pointer to escape code len.
  end;

  OutputString := GetImageText( State.Alignment,
                                BitmapOffset,
                                BitmapFlags,
                                ImageOffsets );

  // Don't make it a link if we didn't find a
  // overall link code, i.e. degrade gracefully.
  if LinkTopicIndex > -1 then
  begin    
    if CreateLink( State.LinkIndex, Link, TInternalHelpLink ) then
    begin
      TInternalHelpLink(Link).TopicIndex := LinkTopicIndex;
    end;

    OutputString := GetBeginLink( State.LinkIndex )
                    + OutputString
                    + GetEndLinkTags( State );

    inc( State.LinkIndex );
  end;

end;

Procedure SaveLinkedImage( Var pData: pByte;
                           Var F: TextFile;
                           ImageOffsets: TList );
var
  EscapeLen: uint8;
  EscapeCode: uint8;
  SubEscapeCode: uint8;
  BitmapOffset: longword;
  BitmapFlags: uint8;
  LinkTopicIndex: integer;
begin
  LinkTopicIndex := -1;
  while true do
  begin
    EscapeLen := pData^;
    SubEscapeCode := ( pData + 2 )^;
    case SubEscapeCode of
      HPART_DEFINE:
      begin
        BitmapFlags := ( pData + 3 )^;
        BitmapOffset := pUInt32( pData + 4 )^;
      end;

      HPART_HDREF: // define whole bitmap topic link?
      begin
        LinkTopicIndex := pUInt16( pData + 3 )^;
      end;
    end;
    inc( pData, EscapeLen );

    // Now pData points at next code or item
    if pData^ <> IPF_ESC then
      // not an escape code, done
      break;
    EscapeCode := (pData + 2) ^;
    if EscapeCode <> ecLinkedImage then
      // not a hyperlink code, done
      break;
    // another linked image code is coming up.
    SubEscapeCode := ( pData + 3 )^;
    if SubEscapeCode = HPART_DEFINE then
      // started another linked image.
      break;
    inc( pData ); // move pointer to escape code len.
  end;

  SaveImageText( BitmapOffset,
                 BitmapFlags,
                 F,
                 ImageOffsets );

  // Don't make it a link if we didn't find a
  // overall link code, i.e. degrade gracefully.
  if LinkTopicIndex > -1 then
  begin
    WriteLn( F, '' );
    WriteLn( F, ':artlink.' );
    Write( F, ':link reftype=hd' );
    Write( F, ' refid=' + IntToStr( LinkTopicIndex ) );
    WriteLn( F, '.' );
    WriteLn( F, ':eartlink.' );
  end;

end;

Procedure GetExtraLinkData( Link: TWindowedHelpLink;
                            pData: pUInt8 );
var
  LinkFlags1: uint8;
  LinkFlags2: uint8;
  LinkDataIndex: longint;
  pLinkXY: pHelpXYPair;
  pLinkData: pUInt8;
begin
  LinkFlags1 := ( pData + 0 ) ^;
  LinkFlags2 := ( pData + 1 ) ^;

  pLinkData := pData + 2;

  if ( LinkFlags1 and 1 ) > 0 then
  begin
    // position specified
    pLinkXY := pHelpXYPair( pLinkData );
    ReadHelpPosition( pLinkXY^, Link.Rect );
    inc( pLinkData, sizeof( THelpXYPair ) );
  end;

  if ( LinkFlags1 and 2 ) > 0 then
  begin
    // size specified
    pLinkXY := pHelpXYPair( pLinkData );
    ReadHelpSize( pLinkXY^, Link.Rect );
    inc( pLinkData, sizeof( THelpXYPair ) );
  end;

  if ( LinkFlags1 and 8 ) > 0 then
  begin
    // window controls specified - skip
    inc( pLinkData, 2 );
  end;

  if ( LinkFlags2 and 4 ) > 0 then
  begin
    // group specified
    Link.GroupIndex := pUInt16( pLinkData )^;
    inc( LinkDataIndex, sizeof( uint16 ) );
  end;

  if ( LinkFlags1 and 64 ) > 0 then
  begin
    Link.Automatic := true;
  end;

  if ( LinkFlags1 and 4 ) > 0 then
    Link.ViewPort := true;

  if ( LinkFlags2 and 2 ) > 0 then
    Link.Dependent := true;

  if ( LinkFlags1 and 128 ) > 0 then
    Link.Split := true;

  // cant be bothered with the others.
end;

// If the given link has already been decoded
// ie. the topic has been displayed before,
// then return the already decoded link & return false
// Otherwise, create a new link object & return true
function TTopic.CreateLink( Var LinkIndex: longint;
                            Var Link: THelpLink;
                            LinkClass: THelpLinkClass ): boolean;
begin
  if LinkIndex >= Links.Count then
  begin
    Link := LinkClass.Create;
    Link.HelpFile := HelpFile;
    Links.Add( Link );
    Result := true;
  end
  else
  begin
    Link := THelpLink(Links[ LinkIndex ]);
    Result := false;
  end;
end;

const
  // size of the original View's default font
  AverageViewCharWidth = 8;

procedure GetMarginTag( const Margin: longint;
                        FontState: TFontState;
                        Var MarginString: string;
                        BreakIfPast: boolean );
begin
  MarginString := '<leftmargin ';
  if FontState <> fsCustom then
    // for standard fonts, scale margins to match font
    MarginString := MarginString + IntToStr( Margin )
  else
    // for custom fonts, since the IPF margins were always in
    // terms of the standard font size, set the margin to a width based on that.
    MarginString := MarginString + IntToStr( Margin * AverageViewCharWidth ) + ' pixels';

  if BreakIfPast then
    MarginString := MarginString + ' breakifpast';

  MarginString := MarginString + '>';
end;

// TODO
function FullDoubleQuote( const s: string ): string;
begin
  Result := StrDoubleQuote
            + StrEscapeAllCharsBy(s, [], CharDoubleQuote)
            + StrDoubleQuote;
end;

// End URL, if it has been started. Go back and insert the start tag,
// and add the end tag.
procedure CheckForAutoURL( var Text: string; var State: TParseState );
var
  T: string;
begin
  if State.StartOfTextBlock = -1 then
    // haven't got any text yet
    exit;

  TrimPunctuation( State.TextBlock );

  if not CheckAndEncodeURL( State.TextBlock ) then
  begin
    // not a URL we know
    State.TextBlock := '';
    exit;
  end;

  // It's a URL. Insert link at start of URL
  T := '<color blue><link ' + PARAM_LINK_URL + ' "';
  T := T + State.TextBlock;
  T := T + '">';
  Insert(T, Text, State.StartOfTextBlock);
  Text := Text + GetEndLinkTags(State);

  State.TextBlock := '';
  State.StartOfTextBlock := -1;
end;

procedure TTopic.TranslateIPFEscapeCode( Var State: TParseState;
                                         Var pData: pUInt8;
                                         var AText: String;
                                         Var WordsOnLine: longint;
                                         ImageOffsets: TList );
var
  EscapeLen: uint8;
  EscapeCode: uint8;

  Link: THelpLink;              //TInternalHelpLink;
  FootnoteLink: THelpLink;      //TFootnoteHelpLink;
  LinkByResourceID: THelpLink;  //THelpLinkByResourceID;

  Margin: integer;

  BitmapOffset: longword;
  BitmapFlags: uint8;

  ColorCode: uint8;
  StyleCode: uint8;

  FontIndex: uint8;
  pFontSpec: pTHelpFontSpec;

  FaceName: string;
  PointSize: longint;
  QuotedFaceName: string;

  ExternalLinkFileIndex: uint8;
  ExternalLinkTopicID: string;

  ProgramLink: string;
  ProgramPath: string;
  ProgramFilename: string;
  lURL: string;
  ProgramInfo : TSerializableStringList;
  tmpProgramLinkParts : TStrings;

  OutputString: string;
begin
  EscapeLen := pData^;
  EscapeCode := (pData + 1)^;
  OutputString := '';

  case EscapeCode of

    ecSetLeftMargin:
    begin
      CheckForAutoURL( AText, State );
      Margin := integer( ( pData + 2 )^ );
      GetMarginTag( Margin, State.FontState, OutputString, false );
    end;

    ecSetLeftMarginNewLine:
    begin
      CheckForAutoURL( AText, State );
      Margin := integer( ( pData + 2 )^ );
      GetMarginTag( Margin, State.FontState, OutputString, false );
      OutputString := OutputString  + RTF_NewLine;
    end;

    ecSetLeftMarginFit:
    begin
      CheckForAutoURL( AText, State );
      Margin := integer( ( pData + 2 )^ );
      GetMarginTag( Margin, State.FontState, OutputString, true );
      // note that this will cause following tex to be "tabbed" across to the
      // new margin position, if not yet there.
      // if we are already past this margin then a new line should be started.

    end;

    ecSetLeftMarginHere:
    begin
      OutputString := '<leftmargin here>';
    end;

    ecHighlight1:
    begin
      StyleCode := ( pData + 2 )^;
      if StyleCode <= High( IPFHighlight1Tags ) then
        OutputString := IPFHighlight1Tags[ StyleCode ];
      if StyleCode = 0 then
        State.ForegroundColorTag := '</color>';
    end;

    ecHighlight2:
    begin
      StyleCode := ( pData + 2 )^;
      if StyleCode <= High( IPFHighlight2Tags ) then
        OutputString := IPFHighlight2Tags[ StyleCode ];

      if StyleCode = 0 then
        State.ForegroundColorTag := '</color>'
      else
        State.ForegroundColorTag := OutputString; // only colours
    end;

    ecLinkStart:
    begin
      CheckForAutoURL( AText, State );
      if CreateLink( State.LinkIndex, Link, TInternalHelpLink ) then
      begin
        TInternalHelpLink(Link).TopicIndex := pUInt16( pData + 2 )^;

        if EscapeLen >= 6 then
        begin
          GetExtraLinkData( TInternalHelpLink(Link), pData + 4 );
        end;
      end;

      // If it's not an automatic link
      // then put code in to show it.
      if not TInternalHelpLink(Link).Automatic then
      begin
        OutputString := '<color blue>'
                        + GetBeginLink( State.LinkIndex );
      end;

      inc( State.LinkIndex );
    end;

    ecFootnoteLinkStart:
    begin
      CheckForAutoURL( AText, State );
      if CreateLink( State.LinkIndex, FootnoteLink, TFootnoteHelpLink ) then
      begin
        TFootnoteHelpLink(FootnoteLink).TopicIndex := pUInt16( pData + 2 )^;
        State.FootnoteLink := TFootnoteHelpLink(FootnoteLink);
      end;

      OutputString := '<color blue>' + GetBeginLink( State.LinkIndex );

      inc( State.LinkIndex );
    end;

    ecStartLinkByResourceID:
    begin
      CheckForAutoURL( AText, State );
      if CreateLink( State.LinkIndex, LinkByResourceID, THelpLinkByResourceID ) then
      begin
        THelpLinkByResourceID(LinkByResourceID).ResourceID := pUInt16( pData + 2 )^;

        if EscapeLen >= 6 then
        begin
          GetExtraLinkData( THelpLinkByResourceID(LinkByResourceID), pData + 4 );
        end;
      end;

      OutputString := '<color blue>' + GetBeginLink( State.LinkIndex );

      inc( State.LinkIndex );
    end;

    ecExternalLink:
    begin
      CheckForAutoURL( AText, State );
      // :link reftype=hd refid=... database=<filename>
      ExternalLinkFileIndex := ( pData + 2 )^;
      ExternalLinkTopicID := StrNPas( pchar(pData + 4), (pData + 3)^ );
      OutputString := '<color blue><link ' + PARAM_LINK_EXTERNAL + ' '
                      + IntToStr( ExternalLinkFileIndex )
                      + ' '
                      + ExternalLinkTopicID
                      + '>'

    end;

    ecProgramLink:
    begin
      CheckForAutoURL( AText, State );
      ProgramLink := StrNPas( pchar(pData + 3), EscapeLen-3 );

      tmpProgramLinkParts := TStringList.Create;
      StrExtractStrings(tmpProgramLinkParts, ProgramLink, [' '], #0);
      ProgramPath := tmpProgramLinkParts[0];
      lURL := tmpProgramLinkParts[1];
      tmpProgramLinkParts.Destroy;

      ProgramFilename := ExtractFilename( ProgramPath );

      if    StrStartsWithIgnoringCase(ProgramFilename, PRGM_EXPLORER)
         or StrStartsWithIgnoringCase(ProgramFilename, PRGM_NETSCAPE)
         or StrStartsWithIgnoringCase(ProgramFilename, PRGM_MOZILLA)
         or StrStartsWithIgnoringCase(ProgramFilename, PRGM_FIREFOX)
         then
      begin
        OutputString := '<color blue><link ' + PARAM_LINK_URL + ' '
                        + FullDoubleQuote( lURL )
                        + '>';
      end
      else
      begin
        ProgramInfo := TSerializableStringList.create;
        ProgramInfo.add(ProgramPath);
        ProgramInfo.add(ProgramLink);
        OutputString := '<color blue><link ' + PARAM_LINK_PROGRAM + ' '
                        + ProgramInfo.getSerializedString
                        + '>';
        ProgramInfo.destroy;
      end;
    end;

    ecLinkEnd:
    begin
      OutputString := GetEndLinkTags( State );
      if State.FootnoteLink <> nil then
        State.FootnoteLink := nil;
    end;

    ecStartCharGraphics:
    begin
      State.FontState := fsFixed;
      State.InCharGraphics := true;
      OutputString := RTF_NewLine + RTF_NewLine + '<tt><nowrap>';
      State.Spacing := false;
      WordsOnLine := 0;
    end;

    ecEndCharGraphics:
    begin
      State.FontState := fsNormal;
      State.InCharGraphics := false;
      OutputString := '</nowrap></tt>';// + RTF_NewLine;
      State.Spacing := true;
    end;

    ecImage:
    begin
      CheckForAutoURL( AText, State );
      BitmapFlags := ( pData + 2 )^;
      BitmapOffset := pUInt32( pData + 3 )^;

      OutputString := GetImageText( State.Alignment,
                                    BitmapOffset,
                                    BitmapFlags,
                                    ImageOffsets );

      if State.Spacing
         AND (OutputString[Length(OutputString)] <> RTF_NewLine) // no space after a line break
      then
        OutputString := OutputString + ' ';
    end;

    ecLinkedImage:
    begin
      CheckForAutoURL( AText, State );
      ProcessLinkedImage( State,
                          pData,
                          OutputString,
                          ImageOffsets );
      if State.Spacing then
        OutputString := OutputString + ' ';

      // Note! Early exit, since the procedure
      // will update pData.
      AText := AText + OutputString;
      exit;
    end;

    ecStartLines:
    begin
      CheckForAutoURL( AText, State );
      // aligned text
      case ( pData + 2 )^ of
        0, // just in case - to match image alignment oddities
        1:
        begin
          OutputString := RTF_NewLine + '<align left>';
          State.Alignment := itaLeft;
        end;

        2:
        begin
          OutputString := RTF_NewLine + '<align right>';
          State.Alignment := itaRight;
        end;

        4:
        begin
          OutputString := RTF_NewLine + '<align center>';
          State.Alignment := itaCenter;
        end;
      end;
      OutputString := OutputString + '<nowrap>';
      WordsOnLine := 0;
    end;

    ecEndLines:
    begin
      CheckForAutoURL( AText, State );
      // supposed to turn word wrap on, default font
      OutputString := {'<align left>}'</nowrap>'; // I guess...
      State.Alignment := itaLeft;
    end;

    ecForegroundColor:
    begin
      ColorCode := ( pData + 2 )^;
      if ColorCode = 0 then
        State.ForegroundColorTag := '</color>'
      else if ColorCode <= High( IPFColors ) then
        State.ForegroundColorTag := '<color ' + IPFColors[ ColorCode ] + '>';
      OutputString := State.ForegroundColorTag;
    end;

    ecBackgroundColor:
    begin
      ColorCode := ( pData + 2 )^;
      if ColorCode = 0 then
        State.BackgroundColorTag := '</backcolor>'
      else if ColorCode <= High( IPFColors ) then
        State.BackgroundColorTag := '<backcolor ' + IPFColors[ ColorCode ] + '>';
      OutputString := State.BackgroundColorTag;
    end;

    ecFontChange:
    begin
      FontIndex := ( pData + 2 )^;
      if FontIndex = 0 then
      begin
        // back to default font
        OutputString := '</font>';
        State.FontState := fsNormal;
      end
      else if FontIndex < _FontTable.Count then
      begin
        // valid font index
        pFontSpec := _FontTable[ FontIndex ];

//        if pFontSpec = SubstituteFixedFont then
        if pFontSpec^.Codepage = High(word) then // Substitute Fixed Font detected
        begin
          OutputString := '<tt>';
          State.FontState := fsFixed;
        end
        else
        begin
//          pFontSpec := _FontTable[ FontIndex ];
          FaceName := StrNPas( pFontSpec^.FaceName, sizeof(pFontSpec^.FaceName) );
          // arbitrarily and capriciously use specified height * 2/3
          // as the point size - seems to correspond to what original
          // view wanted...  note this doesn't necessarily scale
          // correctly, since default font could be different. whatever.
          PointSize := (pFontSpec^.Height * 2) div 3;

          if PointSize < 8 then
            PointSize := 8;
          // quote font name, escape double quotes with duplicates
          // e.g. Bob's "Big" Font would become
          //      "Bob's ""Big"" Font"
          QuotedFaceName := FullDoubleQuote( FaceName );
          OutputString := '<font '
                          + QuotedFaceName
                          + ' '
                          + IntToStr( PointSize )
                          + '>';
                          {
                           // for when (if ever) RTV allows setting font
                           // by precise dimensions
                          + '['
                          + IntToStr( pFontSpec ^. Width )
                          + 'x'
                          + IntToStr( pFontSpec ^. Height )
                          + ']';
                          }
          State.FontState := fsCustom;
        end;
      end;
    end
  end; // case escape code of...

  AText := AText + OutputString;
  inc( pData, EscapeLen );
end;

// returns true if the escape code results in whitespace
// also updates the bits of State that relate to spacing
// ie. .Spacing, and .InCharGraphics (which affects whether
// spacing is reset at paragraph ends etc)
function TTopic.IPFEscapeCodeSpace( Var State: TParseState;
                                    Var pData: pUInt8 ): boolean;
var
  EscapeLen: uint8;
  EscapeCode: uint8;

begin
  EscapeLen := pData^;
  EscapeCode := (pData + 1) ^;

  result := false; // for most
  case EscapeCode of
    ecSetLeftMargin,
    ecSetLeftMarginNewLine,
    ecSetLeftMarginFit:
      result := true;

    ecStartCharGraphics:
    begin
      result := true;
      State.InCharGraphics := true;
      State.Spacing := false;
    end;

    ecEndCharGraphics:
    begin
      result := true;
      State.InCharGraphics := false;
      State.Spacing := true;
    end;

    ecImage:
      result := State.Spacing;

    ecLinkedImage:
      result := State.Spacing;

    ecStartLines:
    begin
      result := true;
      State.Spacing := false;
    end;

    ecEndLines:
    begin
      result := true;
      // supposed to turn word wrap on, default font
      State.Spacing := true;
    end;
  end; // case escape code of...

  inc( pData, EscapeLen );
end;

procedure TTopic.EnsureSlotsLoaded;
var
  i: longint;
  pSlotNumber: puint16;
  SlotNumber: uint16;
  SlotHeader: TSlotHeader;
  Slot: THelpTopicSlot;
  bytes: integer;
  expected: integer;
begin
  if _Slots = nil then
  begin
    try
      _Slots := TList.Create;

      // Read slot data
      pSlotNumber := _pSlotNumbers;

      for i := 1 to _NumSlots do
      begin
        SlotNumber := pSlotNumber^;

        // Seek to start of slot
        try
          _FileHandle.Seek(_pSlotOffsets^[SlotNumber], soBeginning);
        except
          // not a valid offset
          raise EHelpFileException.Create( ErrorCorruptHelpFile );
        end;

        // Read header
        bytes := _FileHandle.Read(SlotHeader, SizeOf(TSlotHeader));
        if bytes <> SizeOf(TSlotHeader) then
          // couldn't read slot header
          raise EHelpFileException.Create( 'Failed to load Topic Slots.' );

        // Create slot object
        Slot := THelpTopicSlot.Create;

        Slot.LocalDictSize := SlotHeader.nLocalDict;
        Slot.Size := SlotHeader.ntext;

        // Allocate and read slot dictionary
        _FileHandle.Seek(SlotHeader.localDictPos, soBeginning);
        expected := uint32(Slot.LocalDictSize) * sizeof(uint16); // size we need
        if Slot.pLocalDictionary = nil then
          // allocate memory
          Slot.pLocalDictionary := GetMem(expected);
        bytes := _FileHandle.Read(Slot.pLocalDictionary^, expected);
        if bytes <> expected then
          raise EHelpFileException.Create('Failed to read complete slot dictionary');

        // Allocate and read slot data (text)
        _FileHandle.Seek(_pSlotOffsets^[SlotNumber] + sizeof(TSlotHeader), soBeginning);
        expected := Slot.Size; // size we need
        if Slot.pData = nil then
          // allocate memory
          Slot.pData := GetMem(expected);
        bytes := _FileHandle.Read(Slot.pData^, expected);
        if bytes <> expected then
          raise EHelpFileException.Create('Failed to read complete slot data (text)');

        _Slots.Add( Slot );
        inc( pByte(pSlotNumber), sizeof( UInt16 ) );
      end;
    except
      on E: EHelpFileException do
      begin
        DestroyListAndObjects( _Slots );
        raise;
      end;
    end;
  end;
end;

// returns a global dict index.
// or, -1 for a whitespace item.
// or, -2 for end of text.
function TTopic.GetNextIPFTextItem( Var SlotIndex: longint;
                                    Var pData: pUInt8;
                                    Var State: TParseState ): longint;
var
  Slot: THelpTopicSlot;
  pSlotEnd: pUInt8;

  LocalDictIndex: uint8;
begin
  while SlotIndex < _NumSlots do
  begin
    Slot := THelpTopicSlot(_Slots[ SlotIndex ]);
    pSlotEnd := Slot.pData + Slot.Size;

    while pData < pSlotEnd do
    begin
      LocalDictIndex := pData^;
      inc( pData );

      if LocalDictIndex < Slot.LocalDictSize then
      begin
        // Normal word lookup
        result := Slot.pLocalDictionary^[ LocalDictIndex ];
        exit;
      end;

      // special code
      case LocalDictIndex of
        IPF_END_PARA:
        begin
          result := -1;
          if not State.InCharGraphics then
            State.Spacing := true;
          exit;
        end;

        IPF_CENTER:
        begin
          result := -1;
          exit;
        end;

        IPF_INVERT_SPACING:
        begin
          State.Spacing := not State.Spacing;
        end;

        IPF_LINEBREAK:
        begin
          result := -1;
          if not State.InCharGraphics then
            State.Spacing := true;
          exit;
        end;

        IPF_SPACE:
        begin
          result := -1;
          exit;
        end;

        IPF_ESC:
        begin
          // escape sequence
          if IPFEscapeCodeSpace( State, pData ) then
            result := -1;
        end;
      end;
    end; // while in slot...
    inc( SlotIndex );
  end;
  Result := -2;
end;

// Checks to see if the given word (at pData)
// starts one of the given sequences, by looking forward
// If found, returns the length of the sequence.
function TTopic.CheckForSequence( WordSequences: TList;
                                  SlotIndex: longint;
                                  pData: pUint8;
                                  State: TParseState;
                                  GlobalDictIndex: longint
                                ): longint;
var
  WordSequence: TList;
  SequenceStepIndex: longint;
  pSequenceStepWords: Uint32ArrayPointer;

  SequenceIndex: longint;

  SlotIndexTemp: longint;
  pDataTemp: pUint8;
  StateTemp: TParseState;
//  s : string;
  DictIndex: longint;
begin
  result := 0; // if we don't find a match.

  for SequenceIndex := 0 to WordSequences.Count - 1 do
  begin
    WordSequence := TList(WordSequences[ SequenceIndex ]);
    pSequenceStepWords := WordSequence[ 0 ];

    if pSequenceStepWords^[ GlobalDictIndex ] > 0 then
    begin
      // matched first step in this sequence. Look ahead...

      SequenceStepIndex := 0;

      pDataTemp := pData;
      SlotIndexTemp := SlotIndex;
      StateTemp := State;
      while true do
      begin
        inc( SequenceStepIndex );
        if SequenceStepIndex = WordSequence.Count then
        begin
          // have a match for the sequence, insert start highlight
          Result := WordSequence.Count;
          break;
        end;

        // get words for next step in sequence
        pSequenceStepWords := WordSequence[ SequenceStepIndex ];

        DictIndex := GetNextIPFTextItem( SlotIndexTemp,
                                         pDataTemp,
                                         StateTemp );
        if DictIndex = -2 then
        begin
          // end of text - abort
          break;
        end;

        if DictIndex = -1 then
        begin
          // whitespace - abort
           // for multi-word phrase searching - count this and subsequent whitespace...
          break;
        end;

//        s := _GlobalDictionary[ DictIndex ]; // for debug only
        if not StrIsEmptyOrSpaces(_GlobalDictionary[ DictIndex ]) then
        begin
          if pSequenceStepWords^[ DictIndex ] = 0 then
          begin
            // word doesn't match - abort
            break;
          end;
        end;

      end; // while

    end;
    // else - doesn't match first step, do nothing
  end; // for sequenceindex ...
end;

// Main translation function. Turns the IPF data into
// a text string. Translates formatting codes into tags
// as for Rich Text Viewer.
procedure TTopic.GetText( HighlightSequences: TList;
                            // each element is a TList
                            //   containing a sequence of possible words
                            //     each element of each sequence
                            //     is an array of flags for the dictionary
                            //       indicating if the word is a allowed match at that step
                            // a match is any sequence that matches one or more words at each step.
                          ShowCodes: boolean;
                          ShowWordSeparators: boolean;
                          var Text: String;
                          ImageOffsets: TList;
                          HighlightMatches: TList );
var
  SlotIndex: integer;
  Slot: THelpTopicSlot;
  pData: pUInt8;
  pSlotEnd: pUInt8;

  GlobalDictIndex: uint32;

  WordsOnLine: longint;

  StringToAdd: string;
  LocalDictIndex: uint8;

  State: TParseState;

  EscapeLen: uint8;
  i: longint;

  SequenceStepIndex: longint;
begin
  if Links = nil then
    Links := TList.Create;

  if HighlightMatches <> nil then
    HighlightMatches.Clear;

  // Text.Clear;
  ImageOffsets.Clear;

  try
    EnsureSlotsLoaded;
  except
    on E: EHelpFileException do
    begin
      Text := Text + E.Message;
      exit;
    end;
  end;

  WordsOnLine := 0;

  State.LinkIndex := 0;
  State.FontState := fsNormal; // ? Not sure... this could be reset at start of slot
  State.InCharGraphics := false;
  State.Spacing := true;
  State.ForegroundColorTag := '</color>';
  State.BackgroundColorTag := '</backcolor>';
  State.StartOfTextBlock := -1;
  State.TextBlock := '';
  State.FootnoteLink := nil;
  Text := Text + '<leftmargin 1>';

  SequenceStepIndex := 0;

  for SlotIndex := 0 to _NumSlots - 1 do
  begin
    if not State.InCharGraphics then
      State.Spacing := true; // this is just a guess as to the exact view behaviour.
                             // inf.txt indicates that spacing is reset to true at
                             // slot (cell) start, but that doesn't seem to be the
                             // case when in character graphics... hey ho.

    Slot := THelpTopicSlot(_Slots[ SlotIndex ]);
    pData := Slot.pData;
    pSlotEnd := pData + Slot.Size;
    State.Alignment := itaLeft;

    while pData < pSlotEnd do
    begin
      LocalDictIndex := pData^;
      inc( pData );

      if LocalDictIndex < Slot.LocalDictSize then
      begin
        // Normal word lookup
        GlobalDictIndex := Slot.pLocalDictionary^[ LocalDictIndex ];

        if ShowWordSeparators then
          Text := Text + '{' + IntToStr( GlobalDictIndex )+ '}';

        // normal lookup
        if GlobalDictIndex < _GlobalDictionary.Count then
          StringToAdd := _GlobalDictionary[ GlobalDictIndex ]
        else
          StringToAdd := '';

        if StrIsEmptyOrSpaces( StringToAdd ) then
        begin
          // spaces only...
          CheckForAutoURL( Text, State );
        end
        else
        begin
          // really is a word, not a space.

          // store string into "word"
          if Length(State.TextBlock) = 0 then
            // store start of block
            State.StartOfTextBlock := Length(Text);

          State.TextBlock := State.TextBlock + StringToAdd;

          SubstituteAngleBrackets( StringToAdd );

          if HighlightSequences <> nil then
          begin
            if SequenceStepIndex > 0 then
            begin
              // currently highlighting a sequence.
              dec( SequenceStepIndex );
              if SequenceStepIndex = 0 then
              begin
                // now finished, insert end highlight
                StringToAdd := StringToAdd
                               + State.BackgroundColorTag;

              end;
            end
            else
            begin
              // not yet in a sequence, searching.
              SequenceStepIndex :=
                CheckForSequence( HighlightSequences,
                                  SlotIndex,
                                  pData,
                                  State,
                                  GlobalDictIndex );

              if SequenceStepIndex > 0 then
              begin
                // this word starts a sequence!
                if HighlightMatches <> nil then
                  HighlightMatches.Add( pointer( Length(Text) ) );
                StringToAdd := '<backcolor #'
                         + IntToHex( Settings.Colors[ SearchHighlightTextColorIndex ], 6 )
                         + '>'
                         + StringToAdd;
                dec( SequenceStepIndex );
                if SequenceStepIndex = 0 then
                  // and ends it.
                  StringToAdd := StringToAdd
                           + State.BackgroundColorTag;
              end;

            end;
          end; // if processing sequence
          inc( WordsOnLine );
        end;

        Text := Text + StringToAdd;

        if State.FootnoteLink <> nil then
        begin
          State.FootnoteLink.Title := State.FootnoteLink.Title + StringToAdd;
          if State.Spacing then
          begin
            State.FootnoteLink.Title := State.FootnoteLink.Title + ' ';
          end;
        end;

        if State.Spacing then
        begin
          CheckForAutoURL( Text, State );
          Text := Text + ' ';
        end;
      end
      else
      begin
        // special code

        if ShowCodes then
        begin
          Text := Text + '[' + IntToHex( LocalDictIndex, 2 );
          if LocalDictIndex = IPF_ESC then
          begin
            EscapeLen := pData^;
            for i := 1 to EscapeLen - 1 do
              Text := Text + ' ' + IntToHex( ( pData + i )^, 2 );
          end;
          Text := Text + ']';
        end;

        case LocalDictIndex of
          IPF_END_PARA:
          begin
            if SlotIndex = 0 then
              if pData - 1 = Slot.pData then
                // ignore first FA, not needed with RichTextView
                continue;

            CheckForAutoURL( Text, State );
            if State.Alignment = itaCenterOnePara then
            begin
              State.Alignment := itaLeft;
              Text := Text + '<align left>';
            end;
            Text := Text + RTF_NewLine;

            if WordsOnLine > 0 then
              Text := Text + RTF_NewLine;

            if not State.InCharGraphics then
              State.Spacing := true;

            WordsOnLine := 0;
          end;

          IPF_CENTER:
          begin
            CheckForAutoURL( Text, State );
            Text := Text + RTF_NewLine + '<align center>';
            State.Alignment := itaCenterOnePara;
          end;

          IPF_INVERT_SPACING:
          begin
            if not State.InCharGraphics then
              State.Spacing := not State.Spacing;
          end;

          IPF_LINEBREAK:
          begin
            CheckForAutoURL( Text, State );

            if State.Alignment = itaCenterOnePara then
            begin
              State.Alignment := itaLeft;
              Text := Text + '<align left>';
            end;
            Text := Text + RTF_NewLine;
            if not State.InCharGraphics then
              State.Spacing := true;
            WordsOnLine := 0;
          end;

          IPF_SPACE:
          begin
            CheckForAutoURL( Text, State );
            if State.Spacing then
              Text := Text + '  ';
          end;

          IPF_ESC:
          begin
            // escape sequence
            TranslateIPFEscapeCode( State,
                                    pData,
                                    Text,
                                    WordsOnLine,
                                    ImageOffsets );

          end;

        end; // case code of...
      end;
    end; // for slotindex = ...
  end;
  State.TextBlock := '';
end;

function TTopic.SearchForWord( DictIndex: integer;
                               StopAtFirstOccurrence: boolean )
  : longint;
var
  SlotIndex: integer;
  Slot: THelpTopicSlot;
  pData: pUInt8;
  pSlotEnd: pUInt8;

  EscapeLen: longint;

  GlobalDictIndex: uint32;

  LocalDictIndex: uint8;
begin
  EnsureSlotsLoaded;

  Result := 0;
  for SlotIndex := 0 to _NumSlots - 1 do
  begin
    Slot := THelpTopicSlot(_Slots[ SlotIndex ]);

    pData := Slot.pData;

    pSlotEnd := pData + Slot.Size;

    while pData < pSlotEnd do
    begin
      LocalDictIndex := pData^;

      if LocalDictIndex < Slot.LocalDictSize then
      begin
        // Normal word lookup
        GlobalDictIndex := Slot.pLocalDictionary^[ LocalDictIndex ];

        if GlobalDictIndex = DictIndex then
        begin
          inc( result );
          if StopAtFirstOccurrence then
            exit;
        end;
      end
      else
      begin
        // special code
        if LocalDictIndex = $ff then
        begin
          // escape string, skip it
          EscapeLen := ( pData + 1 ) ^;
          inc( pData, EscapeLen );
        end;
      end;

      inc( pData );
    end; // for slotindex = ...
  end;
end;

// Search for a sequence of bytes, including in escape codes
// this is for debugging to allow finding specific sequences
function TTopic.SearchForData( Data: pbyte;
                               DataLen: integer ): boolean;
var
  SlotIndex: integer;
  Slot: THelpTopicSlot;
  pData: pUInt8;
  pSlotEnd: pUInt8;

  pHold: pUint8;
  pSearch: pUint8;
begin
  EnsureSlotsLoaded;

  for SlotIndex := 0 to _NumSlots - 1 do
  begin
    Slot := THelpTopicSlot(_Slots[ SlotIndex ]);

    pSearch := Data;
    pHold := Slot.pData;
    pData := Slot.pData;
    pSlotEnd := Slot.pData + Slot.Size;

    while pHold < pSlotEnd do
    begin
      if pData^ = pSearch^ then
      begin
        // byte matches
        inc( pData );
        inc( pSearch );
        if ( pSearch >= Data + DataLen ) then
        begin
          // matches
          result := true;
          exit;
        end
      end
      else
      begin
        // no match
        pSearch := Data;
        inc( pHold );
        pData := pHold;
      end;
    end; // for slotindex = ...
  end;

  result := false; // not found
end;

function TTopic.SearchForWordSequences( WordSequence: TList;
    StopAtFirstOccurrence: boolean ): longint;
var
  SlotIndex: integer;
  Slot: THelpTopicSlot;
  pData: pUInt8;
  pSlotEnd: pUInt8;

  EscapeLen: longint;

  GlobalDictIndex: uint32;
  IsWord: boolean;
  WordRelevance: uint32;

  CurrentMatchRelevance: uint32; // total relevances for words matched so far
                                 // in the current sequence

//  CurrentMatch: string;  // useful for debugging only
  LocalDictIndex: uint8;

  SequenceIndex: longint;
  SequenceStartSlotIndex: longint;
  pSequenceStartData: pUInt8;

  pStepWordRelevances: UInt32ArrayPointer; // word relevances for the current step in the sequence

  // get the current slot start and end pointers
  procedure GetSlot;
  begin
    Slot := THelpTopicSlot(_Slots[ SlotIndex ]);
    pData := Slot.pData;
    pSlotEnd := pData + Slot.Size;
  end;

  // get pointer to the current set of word relevances
  procedure GetStepFlags;
  begin
    pStepWordRelevances := WordSequence[ SequenceIndex ];
  end;

  // store the current point as start of a sequence
  procedure StoreStartOfSequence;
  begin
    SequenceIndex := 0;
    SequenceStartSlotIndex := SlotIndex;
    pSequenceStartData := pData;
    CurrentMatchRelevance := 0;
//    CurrentMatch := '';
    GetStepFlags;
  end;

begin
  Result := 0;

  EnsureSlotsLoaded;

  if _NumSlots = 0 then
    // thar's nowt in yon topic, cannae be a match laid
    exit;

  SlotIndex := 0;

  GetSlot;

  StoreStartOfSequence;

  while true do
  begin
    LocalDictIndex := pData^;
    IsWord := false;
    if LocalDictIndex < Slot.LocalDictSize then
    begin
      IsWord := true;
      // Normal word lookup, so get the global dict idnex before we
      // (potentially) move to next slot
      GlobalDictIndex := Slot.pLocalDictionary^[ LocalDictIndex ];
    end;

    inc( pData );
    if pData >= pSlotEnd then
    begin
      // reached end of slot, next please
      inc( SlotIndex );
      if SlotIndex < _NumSlots then
        GetSlot;
      // else - there is nothing more to search
      // but we need to check this last item
    end;

    if IsWord then
    begin
      // Normal word lookup
      WordRelevance := 0;

      if GlobalDictIndex < _GlobalDictionary.Count then
        if not StrIsEmptyOrSpaces( _GlobalDictionary[ GlobalDictIndex ] ) then;
          WordRelevance := pStepWordRelevances^[ GlobalDictIndex ];

      if WordRelevance > 0 then
      begin
        // Found a matching word
        inc( CurrentMatchRelevance, WordRelevance );
// debug:
//        CurrentMatch := CurrentMatch +
//          pstring( _GlobalDictionary[ GlobalDictIndex ] )^;

        if SequenceIndex = 0 then
        begin
          // remember next start point
          SequenceStartSlotIndex := SlotIndex;
          pSequenceStartData := pData;
        end;

        inc( SequenceIndex );

        if SequenceIndex < WordSequence.Count then
        begin
          // get next set of flags.
          GetStepFlags;
        end
        else
        begin
          // found a complete sequence. Cool!

          inc( result, CurrentMatchRelevance );

          if StopAtFirstOccurrence then
            exit;

          // start looking from the beginning of the sequence again.
          StoreStartOfSequence;
        end;
      end
      else
      begin
        // not a match at this point, restart search
        if SequenceIndex > 0 then
        begin
          // we had matched one or more steps already,
          // back to start of sequence AND back to
          // point we started matching from (+1)
          SequenceIndex := 0;
          CurrentMatchRelevance := 0;
//          CurrentMatch := '';
          SlotIndex := SequenceStartSlotIndex;
          GetSlot;
          pData := pSequenceStartData;
          GetStepFlags;
        end
        else
        begin
          // haven't matched anything yet.
          // update start of sequence
          SequenceStartSlotIndex := SlotIndex;
          pSequenceStartData := pData;
        end;
      end;
    end
    else
    begin
      // special code
      if LocalDictIndex = $ff then
      begin
        // escape string, skip it
        EscapeLen := pData ^;
        inc( pData, EscapeLen );
      end;
    end;

    if SlotIndex >= _NumSlots then
    begin
      // finished searching topic
      break;
    end;

    // next item
  end;
end;


function TTopic.CountWord( DictIndex: integer ): longint;
begin
  Result := SearchForWord( DictIndex, false );
end;

function TTopic.ContainsWord( DictIndex: integer ): boolean;
begin
  Result := SearchForWord( DictIndex, true ) > 0;
end;

// Gets the window dimensions specified by this topic's
// contents header
procedure TTopic.GetContentsWindowRect( ContentsRect: THelpWindowRect );
var
  extendedinfo: TExtendedTOCEntry;
  XY: THelpXYPair;
  p: pbyte;

  Flags: byte;
begin
  Flags := _pTOCEntry ^.flags;
  p := pByte( _pTOCEntry + sizeof( TTOCEntryStart ) );

  ContentsRect.Left := 0;
  ContentsRect.Bottom := 0;
  ContentsRect.Width := 100;
  ContentsRect.Height := 100;

  if ( Flags and TOCEntryExtended ) > 0 then
  begin
    // have more details available...
    ExtendedInfo.w1 := p^;
    ExtendedInfo.w2 := ( p+1) ^;
    inc( p, sizeof( ExtendedInfo ) );

    if (  ExtendedInfo.w1 and 1 ) > 0 then
    begin
      // read origin
      XY := pHelpXYPair( p )^;
      inc( p, sizeof( XY ) );
      ReadHelpPosition( XY, ContentsRect );
    end;
    if ( ExtendedInfo.w1 and 2 ) > 0 then
    begin
      // read size
      XY := pHelpXYPair( p )^;
      inc( p, sizeof( XY ) );
      ReadHelpSize( XY, ContentsRect );
    end;
  end;
end;

const
  IPFColorNames: array[ 0..15 ] of string =
  (
    'default',
    'blue',
    'red',
    'pink',
    'green',
    'cyan',
    'yellow',
    'neutral',
//    'brown',  ??
    'darkgray',
    'darkblue',
    'darkred',
    'darkpink',
    'darkgreen',
    'darkcyan',
    'black',
    'palegray'
  );

Procedure SaveExtraLinkData( Link: TWindowedHelpLink;
                            pData: pUInt8 );
var
  LinkFlags1: uint8;
  LinkFlags2: uint8;
  LinkDataIndex: longint;
  pLinkXY: pHelpXYPair;
  pLinkData: pUInt8;
begin
  LinkFlags1 := ( pData + 0 ) ^;
  LinkFlags2 := ( pData + 1 ) ^;

  pLinkData := pData + 2;

  if ( LinkFlags1 and 1 ) > 0 then
  begin
    // position specified
    pLinkXY := pHelpXYPair( pLinkData );
    inc( pLinkData, sizeof( THelpXYPair ) );
  end;

  if ( LinkFlags1 and 2 ) > 0 then
  begin
    // size specified
    pLinkXY := pHelpXYPair( pLinkData );
    inc( pLinkData, sizeof( THelpXYPair ) );
  end;

  if ( LinkFlags1 and 8 ) > 0 then
  begin
    // window controls specified - skip
    inc( pLinkData, 2 );
  end;

  if ( LinkFlags2 and 4 ) > 0 then
  begin
    // group specified
    Link.GroupIndex := pUInt16( pLinkData )^;
    inc( LinkDataIndex, sizeof( uint16 ) );
  end;

  if ( LinkFlags1 and 64 ) > 0 then
  begin
    Link.Automatic := true;
  end;

  if ( LinkFlags1 and 4 ) > 0 then
    Link.ViewPort := true;

  if ( LinkFlags2 and 2 ) > 0 then
    Link.Dependent := true;

  if ( LinkFlags1 and 128 ) > 0 then
    Link.Split := true;

  // cant be bothered with the others.
end;

procedure TTopic.SaveIPFEscapeCode( Var State: TParseState;
                                    Var pData: pUInt8;
                                    Var F: TextFile;
                                    ImageOffsets: TList );
var
  EscapeLen: uint8;
  EscapeCode: uint8;

  Margin: integer;

  BitmapOffset: longword;
  BitmapFlags: uint8;

  ColorCode: uint8;
  StyleCode: uint8;

  FontIndex: uint8;
  pFontSpec: pTHelpFontSpec;

  FaceName: string;

  ExternalLinkFileIndex: uint8;
  ExternalLinkTopicID: string;

  ProgramLink: string;
  ProgramPath: string;
  tmpProgramLinkParts : TStrings;

  OutputString: string;
begin
  EscapeLen := pData^;
  EscapeCode := (pData + 1) ^;
  OutputString := '';

  case EscapeCode of

    ecSetLeftMargin:
    begin
      Margin := integer( ( pData + 2 )^ );
      GetMarginTag( Margin, State.FontState, OutputString, false );
    end;

    ecSetLeftMarginNewLine:
    begin
      Margin := integer( ( pData + 2 )^ );
      GetMarginTag( Margin, State.FontState, OutputString, false );
      OutputString := OutputString
                      + RTF_NewLine;
    end;

    ecSetLeftMarginFit:
    begin
      Margin := integer( ( pData + 2 )^ );
      GetMarginTag( Margin, State.FontState, OutputString, true );
      // note that this will cause following tex to be "tabbed" across to the
      // new margin position, if not yet there.
      // if we are already past this margin then a new line should be started.

    end;

    ecSetLeftMarginHere:
    begin
      OutputString := '<leftmargin here>';
    end;

    ecHighlight1: // hp1,2,3, 5,6,7
    begin
      StyleCode := ( pData + 2 ) ^;
      if StyleCode > 3 then
        StyleCode := StyleCode + 1; // 4, 8 and 9 are expressed in highlight2 code

      if StyleCode > 0 then
        Write( F, ':hp' + IntToStr( StyleCode ) + '.' )
      else
        Write( F, ':ehp' + IntToStr( State.StyleCode ) + '.' );
      State.StyleCode := StyleCode;
    end;

    ecHighlight2: // hp4, 8, 9
    begin
      StyleCode := ( pData + 2 ) ^;
      case StyleCode of
        1: StyleCode := 4;
        2: StyleCode := 8;
        3: StyleCode := 9;
      end;

      if StyleCode > 0 then
        Write( F, ':hp' + IntToStr( StyleCode ) + '.' )
      else
        Write( F, ':ehp' + IntToStr( State.StyleCode ) + '.' );
      State.StyleCode := StyleCode;
    end;

    ecLinkStart:
    begin
      Write( F, ':link reftype=hd' ); // link to heading

      Write( F, ' refid=' + IntToStr( pUInt16( pData + 2 )^ ) );

      {
        if EscapeLen >= 6 then
        begin
          GetExtraLinkData( Link, pData + 4 );
        end;}

//      if Link.Automatic then
//        Write( F, ' auto' );

      Write( F, '.' );

      inc( State.LinkIndex );
    end;

    ecFootnoteLinkStart:
    begin
      Write( F, ':link reftype=fn refid=fn'
             + IntToStr( pUInt16( pData + 2 )^ )
             + '.' );
      inc( State.LinkIndex );
    end;

    ecStartLinkByResourceID:
    begin
      Write( F, ':link reftype=hd res='
             + IntToStr( pUInt16( pData + 2 )^ )
             + '.' );

      inc( State.LinkIndex );
    end;

    ecExternalLink:
    begin
      ExternalLinkFileIndex := ( pData + 2 )^;
      ExternalLinkTopicID := StrNPas( pchar( pData + 4 ), ( pData + 3 )^ );
      Write( F, ':link reftype=hd '
             + ' refid=' + StrInSingleQuotes( ExternalLinkTopicID )
             + ' database=' + StrInSingleQuotes( _ReferencedFiles[ ExternalLinkFileIndex ] )
             + '.' );

    end;

    ecProgramLink:
    begin
      ProgramLink := StrNPas( pchar( pData + 3 ), EscapeLen - 3 );
      tmpProgramLinkParts := TStringList.Create;
      StrExtractStrings(tmpProgramLinkParts, ProgramLink, [' '], #0);
      ProgramPath := tmpProgramLinkParts[0];
      tmpProgramLinkParts.Destroy;

      Write( F, ':link reftype=launch'
             + ' object=' + StrInSingleQuotes( ProgramPath )
             + ' data=' + StrInSingleQuotes( ProgramLink )
             + '.' );
    end;

    ecLinkEnd:
    begin
      Write( F, ':elink.' );
      if State.FootnoteLink <> nil then
        State.FootnoteLink := nil;
    end;

    ecStartCharGraphics:
    begin
      State.FontState := fsFixed;
      State.InCharGraphics := true;
      WriteLn( F, '' );
      WriteLn( F, ':cgraphic.' );
      State.Spacing := false;
    end;

    ecEndCharGraphics:
    begin
      State.FontState := fsNormal;
      State.InCharGraphics := false;
      WriteLn( F, '' );
      WriteLn( F, ':ecgraphic.' );
      State.Spacing := true;
    end;

    ecImage:
    begin
      BitmapFlags := ( pData + 2 )^;
      BitmapOffset := pUInt32( pData + 3 )^;

      SaveImageText( BitmapOffset, BitmapFlags, F, ImageOffsets );

      if State.Spacing then
        Write( F, ' ' );
    end;

    ecLinkedImage:
    begin
      SaveLinkedImage( pData, F, ImageOffsets );
      // Note! Early exit, since the procedure
      // will update pData.
      exit;
    end;

    ecStartLines:
    begin
      WriteLn( F, '' );
      // aligned text
      case ( pData + 2 )^ of
        0, // just in case - to match image alignment oddities
        1:
        begin
          WriteLn( F, ':lines.' );
          State.Alignment := itaLeft;
        end;

        2:
        begin
          WriteLn( F, ':lines align=right.' );
          State.Alignment := itaRight;
        end;

        4:
        begin
          WriteLn( F, ':lines align=center.' );
          State.Alignment := itaCenter;
        end;
      end;
    end;

    ecEndLines:
    begin
      // supposed to turn word wrap on, default font
      WriteLn( F, '' );
      WriteLn( F, ':elines.' );
      State.Alignment := itaLeft;
    end;

    ecForegroundColor:
    begin
      ColorCode := ( pData + 2 )^;

      if ColorCode < High( IPFColorNames ) then
        Write( F, ':color fc=' + IPFColorNames[ ColorCode ] + '.' );
    end;

    ecBackgroundColor:
    begin
      ColorCode := ( pData + 2 )^;
      if ColorCode < High( IPFColorNames ) then
        Write( F, ':color bc=' + IPFColorNames[ ColorCode ] + '.' );
    end;

    ecFontChange:
    begin
      FontIndex := ( pData + 2 )^;
      if FontIndex = 0 then
      begin
        // back to default font
        Write( F, ':font facename=default.' );
        State.FontState := fsNormal;
      end
      else if FontIndex < _FontTable.Count then
      begin
        // valid font index
        pFontSpec := _FontTable[ FontIndex ];

        if pFontSpec = SubstituteFixedFont then
        begin
         // oops.
          OutputString := '<tt>';
          State.FontState := fsFixed;
        end
        else
        begin
          pFontSpec := _FontTable[ FontIndex ];
          FaceName := StrNPas( pFontSpec^.FaceName,
                               sizeof( pFontSpec^.FaceName ) );
          Write( F,
                 ':font facename=' + StrInSingleQuotes( FaceName )
                 + ' size=' + IntToStr( pFontSpec^.Height )
                   + 'x' + IntToStr( pFontSpec^.Width )
                 + '.' );
          State.FontState := fsCustom;
        end;
      end;
    end
  end; // case escape code of...

  // Write( F, OutputString );

  inc( pData, EscapeLen );
end;

procedure TTopic.SaveToIPF( Var f: TextFile;
                            ImageOffsets: TList );
var
  SlotIndex: integer;
  Slot: THelpTopicSlot;
  pData: pUInt8;
  pSlotEnd: pUInt8;
  GlobalDictIndex: uint32;
  StringToAdd: string;
  LocalDictIndex: uint8;
  State: TParseState;
  SequenceStepIndex: longint;
  LineLen: longint;
  c: char;
begin
  EnsureSlotsLoaded;

  State.LinkIndex := 0;
  State.FontState := fsNormal; // ? Not sure... this could be reset at start of slot
  State.InCharGraphics := false;
  State.Spacing := true;
  State.ForegroundColorTag := '</color>';
  State.BackgroundColorTag := '</backcolor>';

  State.StartOfTextBlock := -1;
  State.TextBlock := '';

  State.FootnoteLink := nil;

  State.StyleCode := 0;

  SequenceStepIndex := 0;

  LineLen := 0;

  for SlotIndex := 0 to _NumSlots - 1 do
  begin
    if not State.InCharGraphics then
      State.Spacing := true; // this is just a guess as to the exact view behaviour.
                             // inf.txt indicates that spacing is reset to true at
                             // slot (cell) start, but that doesn't seem to be the
                             // case when in character graphics... hey ho.

    Slot := THelpTopicSlot(_Slots[ SlotIndex ]);

    pData := Slot.pData;

    pSlotEnd := pData + Slot.Size;

    State.Alignment := itaLeft;

    while pData < pSlotEnd do
    begin
      LocalDictIndex := pData^;
      inc( pData );

      if LocalDictIndex < Slot.LocalDictSize then
      begin
        // Normal word lookup
        GlobalDictIndex := Slot.pLocalDictionary^[ LocalDictIndex ];

        // normal lookup
        if GlobalDictIndex < _GlobalDictionary.Count then
        begin
          StringToAdd := _GlobalDictionary[ GlobalDictIndex ];
          StringToAdd := ConvertTextToUTF8(THelpFile(HelpFile).Encoding, StringToAdd);
        end
        else
          StringToAdd := '';

        if (Length( StringToAdd ) = 1) and Settings.IPFTopicSaveAsEscaped then
        begin
          // could be symbol
          c := StringToAdd[ 1 ];
          case C of
            '&': StringToAdd := '&amp.';
            '''': StringToAdd := '&apos.';
            '*': StringToAdd := '&asterisk.';
            '@': StringToAdd := '&atsign.';
            '\': StringToAdd := '&bsl.';
            '^': StringToAdd := '&caret.';
            '"': StringToAdd := '&osq.';
            ':': StringToAdd := '&colon.';
            '.': StringToAdd := '&per.';
            '(': StringToAdd := '&lpar.';
            ')': StringToAdd := '&rpar.';
            '/': StringToAdd := '&slash.';
            ',': StringToAdd := '&comma.';
            '-': StringToAdd := '&hyphen.';
            '_': StringToAdd := '&us.';
            '~': StringToAdd := '&tilde.';
            '+': StringToAdd := '&plus.';
            '>': StringToAdd := '&gt.';
            ';': StringToAdd := '&semi.';
       Chr($da): StringToAdd := '+';
       Chr($c4): StringToAdd := '-';
       Chr($b3): StringToAdd := '|';
       Chr($c3): StringToAdd := '|';
       Chr($bf): StringToAdd := '+';
          end;
        end;

        inc( LineLen, Length( StringToAdd ) );
        if ( LineLen > 80 ) and ( not State.InCharGraphics ) then
        begin
          WriteLn( F );
          LineLen := 0;
        end;

        Write( F, StringToAdd );
{
        if State.FootnoteLink <> nil then
        begin
          State.FootnoteLink.Title := State.FootnoteLink.Title + StringToAdd;
          if State.Spacing then
          begin
            State.FootnoteLink.Title := State.FootnoteLink.Title + ' ';
          end;
        end;
 }
        if State.Spacing then
        begin
          Write( F, ' ' );
          inc( LineLen );
        end;
      end
      else
      begin
        // special code

        case LocalDictIndex of
          IPF_END_PARA:
          begin
            WriteLn( F, '' );
            Write( F, ':p.' );
            LineLen := 3;

            if not State.InCharGraphics then
              State.Spacing := true;
          end;

          IPF_CENTER:
          begin
            WriteLn( F, '' );
            Write( F, '.ce ' ); // remainder of this line is centered.
            LineLen := 4;
            State.Alignment := itaCenterOnePara;
          end;

          IPF_INVERT_SPACING:
          begin
            State.Spacing := not State.Spacing;
          end;

          IPF_LINEBREAK:
          begin
            WriteLn( F, '' );
            if not State.InCharGraphics then
              WriteLn( F, '.br ' ); // break must be the only thing on the line

            LineLen := 0;
            if not State.InCharGraphics then
              State.Spacing := true;
          end;

          IPF_SPACE:
          begin
            if State.Spacing then
              Write( F, '  ' )
            else
              Write( F, ' ' );
          end;

          IPF_ESC:
          begin
            // escape sequence
            SaveIPFEscapeCode( State,
                               pData,
                               F,
                               ImageOffsets );
          end;

        end; // case code of...
      end;
    end; // for slotindex = ...
  end;
  State.TextBlock := '';

end;

// Compares two topics for purposes of sorting by
// search match relevance
function TopicRelevanceCompare( Item1, Item2: pointer ): longint;
var
  Topic1, Topic2: TTopic;
begin
  Topic1 := TTopic(Item1);
  Topic2 := TTopic(Item2);

  if Topic1.SearchRelevance > Topic2.SearchRelevance then
    Result := -1
  else if Topic1.SearchRelevance < Topic2.SearchRelevance then
    Result := 1
  else
    Result := 0;
end;

// Compares two topics for purposes of sorting by title
function TopicTitleCompare( Item1, Item2: pointer ): longint;
begin
  Result := CompareText( TTopic( Item1 )._Title,
                         TTopic( Item2 )._Title );
end;


end.