File: viewercontrol.pas

package info (click to toggle)
doublecmd 0.7.7-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 32,764 kB
  • ctags: 34,016
  • sloc: pascal: 273,752; ansic: 5,938; sh: 733; makefile: 194; python: 116; xml: 107
file content (3281 lines) | stat: -rw-r--r-- 88,975 bytes parent folder | download
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
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
{
   Component ViewerControl (Free Pascal)
   show file in text (wraped or not) or bin or hex mode

   This is part of Seksi Commander

   To searching use uFindMmap,
   to movement call Upxxxx, Downxxxx, or set Position

   Realised under GNU GPL 2
   author Radek Cervinka (radek.cervinka@centrum.cz)

   changes:
   5.7. (RC)
     - selecting text with mouse
     - CopyToclipBoard, SelectAll
   ?.6. - LoadFromStdIn and loading first 64Kb of files with size=0 :) (/proc fs ..)
   17.6. (RC)
     - mapfile (in error set FMappedFile=nil)
     - writetext TABs fixed (tab is replaced by 9 spaces)
     - set correct position for modes hex, bin (SetPosition)
   21.7
     - wrap text on 80 character lines works better now (by Radek Polak)
     - problems with function UpLine for specific lines:
       (lines of 80(=cTextWidth) character ended with ENTER (=#10)
   6.2. (RC)
     - ported to fpc for linux (CustomControl and gtk)
   7.2. (RC)
     - use temp to new implementation of LoadFromStdIn (and mmap temp file)
     - faster drawing of text (I hope)

   contributors:

   Copyright (C) 2006-2013 Alexander Koblov (alexx2000@mail.ru)


   TODO:
   a) File mapping blocks writing into file by other processes.
      Either:
      + Open small text files by reading them all into memory (done).
      - Add optional custom loading/caching portions of file in memory
        and only reading from file when neccessary.

   b) Searching in Unicode encodings and case-insensitive searching.

   c) Selecting text does not work well with composed Unicode characters
      (characters that are composed of multiple Unicode characters).

   d) Drawing/selecting text does not work correctly with RTL (right to left) text.

   e) FTextHeight is unreliable with complex unicode characters. It should be
      calculated based on currently displayed text (get max from each line's height).

}

unit ViewerControl;

{$mode objfpc}{$H+}

interface

uses
  SysUtils, Classes, Controls, StdCtrls, fgl;

const
  MaxMemSize = $400000; // 4 Mb

type
  TViewerMode = (vmBin, vmHex, vmText, vmWrap, vmBook);
  TDataAccess = (dtMmap, dtNothing);
  TCharSide = (csBefore, csLeft, csRight, csAfter);

  TPtrIntList = specialize TFPGList<PtrInt>;

  TGuessEncodingEvent = function(const s: string): string;

type
  // If additional encodings are added they should be also supported by:
  // - GetNextCharAsAscii
  // - GetPrevCharAsAscii
  // - GetNextCharAsUtf8
  // - ConvertToUTF8
  // - UpdateSelection
  TViewerEncoding = (veAutoDetect,
                     veUtf8,
                     veUtf8bom,
                     veAnsi,
                     veCp1250,
                     veCp1251,
                     veCp1252,
                     veCp1253,
                     veCp1254,
                     veCp1255,
                     veCp1256,
                     veCp1257,
                     veCp1258,
                     veCp437,
                     veCp850,
                     veCp852,
                     veCp866,
                     veCp874,
                     veCp932,
                     veCp936,
                     veCp949,
                     veCp950,
                     veIso88591,
                     veIso88592,
                     veKoi8,
                     veUcs2le,
                     veUcs2be,
                     veUtf16le,
                     veUtf16be,
                     veUtf32le,  // = ucs4le
                     veUtf32be); // = ucs4be

  TViewerEncodings = set of TViewerEncoding;

const
  ViewerEncodingsNames: array [TViewerEncoding] of string =
                   ('Auto-detect',
                    'UTF-8',
                    'UTF-8BOM',
                    'Ansi',
                    'CP1250',
                    'CP1251',
                    'CP1252',
                    'CP1253',
                    'CP1254',
                    'CP1255',
                    'CP1256',
                    'CP1257',
                    'CP1258',
                    'CP437',
                    'CP850',
                    'CP852',
                    'CP866',
                    'CP874',
                    'CP932',
                    'CP936',
                    'CP949',
                    'CP950',
                    'ISO-8859-1',
                    'ISO-8859-2',
                    'KOI-8',
                    'UCS-2LE',
                    'UCS-2BE',
                    'UTF-16LE',
                    'UTF-16BE',
                    'UTF-32LE',
                    'UTF-32BE');

const
  ViewerEncodingMultiByte: TViewerEncodings = [
    veUtf8, veUtf8bom, veUcs2le, veUcs2be,
    veUtf16le, veUtf16be, veUtf32le, veUtf32be];

type

  { TViewerControl }

  TViewerControl = class(TCustomControl)
  protected
    FEncoding:           TViewerEncoding;
    FViewerMode:         TViewerMode;
    FFileName:           String;
    FFileHandle:         THandle;
    FFileSize:           Int64;
    FMappingHandle:      THandle;
    FMappedFile:         Pointer;
    FPosition:           PtrInt;
    FHPosition:          Integer;  // Tab for text during horizontal scroll
    FHLowEnd:            Integer;  // End for HPosition (string with max char)
    FVisibleOffset:      PtrInt;   // Offset in symbols for current line (see IsVisible and MakeVisible)
    FLowLimit:           PtrInt;   // Lowest possible value for Position
    FHighLimit:          PtrInt;   // Position cannot reach this value
    FBOMLength:          Integer;
    FLineList:           TPtrIntList;
    FBlockBeg:           PtrInt;
    FBlockEnd:           PtrInt;
    FMouseBlockBeg:      PtrInt;
    FMouseBlockSide:     TCharSide;
    FSelecting:          Boolean;
    FTextWidth: 	 Integer; // max char count or width in window
    FTextHeight:         Integer; // measured values of font, rec calc at font changed
    FScrollBarVert:      TScrollBar;
    FScrollBarHorz:      TScrollBar;
    FOnPositionChanged:  TNotifyEvent;
    FUpdateScrollBarPos: Boolean; // used to block updating of scrollbar
    FScrollBarPosition:  Integer;  // for updating vertical scrollbar based on Position
    FHScrollBarPosition: Integer;  // for updating horizontal scrollbar based on HPosition
    FColCount:           Integer;
    FOnGuessEncoding:    TGuessEncodingEvent;

    function GetPercent: Integer;
    procedure SetPercent(const AValue: Integer);
    procedure SetBlockBegin(const AValue: PtrInt);
    procedure SetBlockEnd(const AValue: PtrInt);
    procedure SetPosition(Value: PtrInt); virtual;
    procedure SetHPosition(Value: Integer);
    procedure SetPosition(Value: PtrInt; Force: Boolean); overload;
    procedure SetHPosition(Value: Integer; Force: Boolean); overload;
    procedure SetEncoding(AEncoding: TViewerEncoding);
    function GetEncodingName: string;
    procedure SetEncodingName(AEncodingName: string);
    procedure SetViewerMode(Value: TViewerMode);
    procedure SetColCount(const AValue: Integer);

    {en
       Returns how many lines (given current FTextHeight) will fit into the window.
    }
    function GetClientHeightInLines: Integer; inline;

    {en
       Calculates how many lines can be displayed from given position.
       @param(FromPosition
              Position from which to check. It should point to a start of a line.)
       @param(LastLineReached
              If it is set to @true when the function returns, then the last
              line of text was reached when scanning.
              This means that there are no more lines to be displayed other than
              the ones scanned from FromPosition. In other words:
                SetPosition(GetStartOfNextLine(FromPosition)) will be one line
                too many and will be scrolled back.)
    }
    function GetLinesTillEnd(FromPosition: PtrInt; out LastLineReached: Boolean): Integer;

    function GetBomLength: Integer;

    procedure UpdateLimits;

    {en
       @param(iStartPos
              Should point to start of a line.
              It is increased by the amount of parsed data (with line endings).)
       @param(aLimit
              Position which cannot be reached while reading from file.)
       @param(DataLength
              It is length in bytes of parsed data without any line endings.
              iStartPos is moved beyond the line endings though.)
    }
    function CalcTextLineLength(var iStartPos: PtrInt; const aLimit: Int64; out DataLength: PtrInt): Integer;

    function GetStartOfLine(aPosition: PtrInt): PtrInt;
    function GetEndOfLine(aPosition: PtrInt): PtrInt;

    function GetStartOfPrevLine(aPosition: PtrInt): PtrInt;
    function GetStartOfNextLine(aPosition: PtrInt): PtrInt;

    {en
       Changes the value of aPosition to X lines back or forward.
       @param(aPosition
              File position to change.)
       @param(iLines
              Nr of lines to scroll.
              If positive the position is increased by iLines lines,
              if negative the position is decreased by -iLines lines.)
    }
    function ScrollPosition(var aPosition: PtrInt; iLines: Integer): Boolean;

    {en
       Calculates (x,y) cursor position to a position within file.
       @param(x
              Client X coordinate of mouse cursor.)
       @param(y
              Client Y coordinate of mouse cursor.)
       @param(CharSide
              To which side of a character at returned position the (x,y) points to.
              Only valid if returned position is not -1.)
       @returns(Position in file to which (x,y) points to, based on what is
                currently displayed.
                Returns -1 if (x,y) doesn't point to any position (outside of
                the text for example).)
    }
    function XYPos2Adr(x, y: Integer; out CharSide: TCharSide): PtrInt;

    procedure OutText(x, y: Integer; StartPos: PtrInt; DataLength: Integer);
    procedure OutHex(x, y: Integer; sText: string; StartPos: PtrInt; DataLength: Integer);
    procedure OutBin(x, y: Integer; sText: string; StartPos: PtrInt; DataLength: Integer);
    procedure WriteText;
    procedure WriteHex; virtual;
    procedure WriteBin;
    function TransformText(const sText: String; const Xoffset: Integer): String;
    function TransformHex(var aPosition: PtrInt; aLimit: PtrInt): AnsiString;
    function TransformBin(var aPosition: PtrInt; aLimit: PtrInt): AnsiString;

    procedure AddLineOffset(iOffset: PtrInt); inline;

    function MapFile(const sFileName: String): Boolean;
    procedure UnMapFile;
    procedure SetFileName(const sFileName: String);

    procedure UpdateScrollbars;

    procedure ViewerResize(Sender: TObject);

    {en
       Returns next unicode character from the file, depending on Encoding.
       It is a faster version, which does as little conversion as possible,
       but only Ascii values are guaranteed to be valid (0-127).
       Other unicode values may/may not be valid, so shouldn't be tested.
       This function is used for reading pure ascii characters such as
       line endings, tabs, white spaces, etc.
    }
    function GetNextCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
    function GetPrevCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;

    {en
       Retrieve next character from the file depending on encoding and
       automatically convert it to UTF-8.
       If CharLenInBytes is greater than 0 but the result is an empty string
       then it's possible there was no appropriate UTF-8 character for the
       next character of the current encoding.
    }
    function GetNextCharAsUtf8(const iPosition: PtrInt; out CharLenInBytes: Integer): String;

    procedure ReReadFile;
    function IsFileOpen: Boolean; inline;

    {en
       Searches for an ASCII character.
       @param(aPosition
              Position from where the search starts.)
       @param(aMaxBytes
              How many bytes are available for reading.)
       @param(AsciiChars
              The function searches for any character that this string contains.)
       @param(bFindNotIn
              If @true searches for first character not included in AsciiChars.
              If @false searches for first character included in AsciiChars.)
    }
    function FindAsciiSetForward(aPosition, aMaxBytes: PtrInt;
                                 const AsciiChars: String;
                                 bFindNotIn: Boolean): PtrInt;

    {en
       Same as FindForward but it searches backwards from pAdr.
       aMaxBytes must be number of available bytes for reading backwards from pAdr.
    }
    function FindAsciiSetBackward(aPosition, aMaxBytes: PtrInt;
                                  const AsciiChars: String;
                                  bFindNotIn: Boolean): PtrInt;

    {en
       Checks if current selection is still valid given current viewer mode and encoding.
       For example checks if selection is not in the middle of a unicode character.
    }
    procedure UpdateSelection;

    procedure ScrollBarVertScroll(Sender: TObject; ScrollCode: TScrollCode;
      var ScrollPos: Integer);
    procedure ScrollBarHorzScroll(Sender: TObject; ScrollCode: TScrollCode;
      var ScrollPos: Integer);

    function GetText(const StartPos, Len: PtrInt; const Xoffset: Integer): string;

  protected
    procedure KeyDown(var Key: word; Shift: TShiftState); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
    function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;

  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    procedure Paint; override;

    {en
       Scrolls the displayed text in the window.

       @param(iLines
              Nr of lines to scroll.
              If positive the text is scrolled downwards,
              if negative the text is scrolled upwards.)
       @returns(@true if the text was scrolled.)
    }
    function Scroll(iLines: Integer): Boolean;
    function HScroll(iSymbols: Integer): Boolean;

    procedure PageUp;
    procedure PageDown;
    procedure GoHome;
    procedure GoEnd;

    procedure HPageUp;
    procedure HPageDown;
    procedure HGoHome;
    procedure HGoEnd;

    function GetDataAdr: Pointer;

    procedure SelectAll;
    procedure SelectText(AStart, AEnd: PtrInt);
    procedure CopyToClipboard;

    function IsVisible(const aPosition: PtrInt): Boolean; overload;
    procedure MakeVisible(const aPosition: PtrInt);

    function ConvertToUTF8(const sText: AnsiString): String;
    function ConvertFromUTF8(const sText: String): AnsiString;
    function FindUtf8Text(iStartPos: PtrInt; const sSearchText: String;
                          bCaseSensitive: Boolean; bSearchBackwards: Boolean): PtrInt;

    procedure ResetEncoding;
    function DetectEncoding: TViewerEncoding;
    procedure GetSupportedEncodings(List: TStrings);

    property Percent: Integer Read GetPercent Write SetPercent;
    property Position: PtrInt Read FPosition Write SetPosition;
    property FileSize: Int64 Read FFileSize;
    property SelectionStart: PtrInt Read FBlockBeg Write SetBlockBegin;
    property SelectionEnd: PtrInt Read FBlockEnd Write SetBlockEnd;
    property EncodingName: string Read GetEncodingName Write SetEncodingName;
    property ColCount: Integer Read FColCount Write SetColCount;
    property OnGuessEncoding: TGuessEncodingEvent Read FOnGuessEncoding Write FOnGuessEncoding;

  published
    property ViewerMode: TViewerMode Read FViewerMode Write SetViewerMode default vmWrap;
    property FileName: String Read FFileName Write SetFileName;
    property Encoding: TViewerEncoding Read FEncoding Write SetEncoding default veAutoDetect;
    property OnPositionChanged: TNotifyEvent Read FOnPositionChanged Write FOnPositionChanged;

    property OnClick;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;

    property OnMouseWheelUp;
    property OnMouseWheelDown;

    property Align;
    property Color;
    property Cursor default crIBeam;
    property Font;
    property ParentColor default False;
    property TabStop default True;
  end;

procedure Register;

implementation

uses
  LCLType, LCLVersion, Graphics, Forms, LCLProc, Clipbrd, LConvEncoding,
  UnicodeUtils, LCLIntf
  {$IF DEFINED(UNIX)}
  , BaseUnix, Unix
  {$ELSEIF DEFINED(WINDOWS)}
  , Windows
  {$ENDIF};

const
  //cTextWidth      = 80;  // wrap on 80 chars
  cBinWidth       = 80;
  cMaxTextWidth   = 65535; // maximum of chars on one line unwrapped text
  cHexWidth       = 16;
  cTabSpaces      = 8;   // tab stop - allow to set in settings
  cHexOffsetWidth = 8;
  cHexStartHex    = cHexOffsetWidth + 2;  // ': '
  cHexEndHex      = cHexStartHex + (cHexWidth * 3);
  cHexStartAscii  = cHexStartHex + (cHexWidth * 3) + 2;  // '  '

  // These strings must be Ascii only.
  sNonCharacter: string = ' !"#$%&''()*+,-./:;<=>?@[\]^`{|}~'#13#10#9;
  sWhiteSpace  : string = ' '#13#10#9#8;

// ----------------------------------------------------------------------------

constructor TViewerControl.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Cursor := crIBeam;
  ParentColor := False;
  DoubleBuffered := True;
  ControlStyle := ControlStyle + [csTripleClicks, csOpaque];
  TabStop := True; // so that it can get keyboard focus

  FEncoding := veAutoDetect;
  FViewerMode := vmText;
  FFileName := '';
  FMappedFile := nil;
  FFileHandle := 0;
  FMappingHandle := 0;
  FPosition := 0;
  FHPosition := 0;
  FHLowEnd := 0;
  FLowLimit := 0;
  FHighLimit := 0;
  FBOMLength := 0;
  FTextHeight := 14; // dummy value
  FColCount := 1;

  FLineList := TPtrIntList.Create;

  FScrollBarVert          := TScrollBar.Create(Self);
  FScrollBarVert.Parent   := Self;
  FScrollBarVert.Kind     := sbVertical;
  FScrollBarVert.Align    := alRight;
  FScrollBarVert.OnScroll := @ScrollBarVertScroll;
  FScrollBarVert.TabStop  := False;
  FScrollBarVert.PageSize := 0;

  FScrollBarHorz          := TScrollBar.Create(Self);
  FScrollBarHorz.Parent   := Self;
  FScrollBarHorz.Kind     := sbHorizontal;
  FScrollBarHorz.Align    := alBottom;
  FScrollBarHorz.OnScroll := @ScrollBarHorzScroll;
  FScrollBarHorz.TabStop  := False;
  FScrollBarHorz.PageSize := 0;

  FUpdateScrollBarPos := True;
  FScrollBarPosition  := 0;
  FHScrollBarPosition := 0;

  FOnPositionChanged := nil;
  FOnGuessEncoding   := nil;

  OnResize := @ViewerResize;
end;

destructor TViewerControl.Destroy;
begin
  UnMapFile;

  if Assigned(FLineList) then
    FreeAndNil(FLineList);

  inherited Destroy;
end;

procedure TViewerControl.Paint;
begin
  if not IsFileOpen then
    Exit;

  Canvas.Font := Self.Font;
  Canvas.Brush.Color := Self.Color;
  {$IF DEFINED(LCLQT) and (LCL_FULLVERSION < 093100)}
  Canvas.Brush.Style := bsSolid;
  Canvas.FillRect(ClientRect);
  {$ENDIF}
  Canvas.Brush.Style := bsClear;
  FTextHeight := Canvas.TextHeight('Wg') + 2;

  if FViewerMode = vmBook then
    FTextWidth := ((ClientWidth - (Canvas.TextWidth('W') * FColCount)) div FColCount)
  else
    FTextWidth := ClientWidth  div Canvas.TextWidth('W') - 2;

  FLineList.Clear;

  case FViewerMode of
    vmBin : WriteBin;
    vmHex : WriteHex;
    vmText: WriteText;
    vmWrap: WriteText;
    vmBook: WriteText;
  end;
end;

procedure TViewerControl.SetViewerMode(Value: TViewerMode);
begin
  if not (csDesigning in ComponentState) then
  begin
    FLineList.Clear; // do not use cache from previous mode

    // Take limits into account for selection.
    FBlockBeg := FBlockBeg + (GetDataAdr - FMappedFile);
    FBlockEnd := FBlockEnd + (GetDataAdr - FMappedFile);

    FViewerMode := Value;

    FHPosition := 0;
    FBOMLength := GetBomLength;
    UpdateLimits;

    // Take limits into account for selection.
    FBlockBeg := FBlockBeg - (GetDataAdr - FMappedFile);
    FBlockEnd := FBlockEnd - (GetDataAdr - FMappedFile);

    UpdateSelection;

    // Force recalculating position.
    SetPosition(FPosition, True);
    SetHPosition(FHPosition, True);

    UpdateScrollbars;
    Invalidate;
  end
  else
    FViewerMode := Value;
end;

procedure TViewerControl.SetColCount(const AValue: Integer);
begin
  if AValue > 0 then FColCount := AValue
    else FColCount := 1;
end;

function TViewerControl.ScrollPosition(var aPosition: PtrInt; iLines: Integer): Boolean;
var
  i:      Integer;
  NewPos: PtrInt;
begin
  Result := False;
  NewPos := aPosition;
  if iLines < 0 then
    for i := 1 to -iLines do
      NewPos := GetStartOfPrevLine(NewPos)
  else
    for i := 1 to iLines do
      NewPos := GetStartOfNextLine(NewPos);

  Result    := aPosition <> NewPos;
  aPosition := NewPos;
end;

function TViewerControl.Scroll(iLines: Integer): Boolean;
var
  aPosition: PtrInt;
begin
  aPosition := FPosition;
  Result := ScrollPosition(aPosition, iLines);
  if aPosition <> FPosition then
    SetPosition(aPosition);
end;

function TViewerControl.HScroll(iSymbols: Integer): Boolean;
var
  newPos: integer;
begin
  newPos := FHPosition;
  if (FHLowEnd - FTextWidth) > 0 then
    begin
      newPos := newPos+ iSymbols;
      if newPos < 0 then newPos := 0;
      if newPos > FHLowEnd-FTextWidth then newPos := FHLowEnd-FTextWidth;
    end;
  if newPos <> FHPosition then
    SetHPosition(newPos);
end;

function TViewerControl.GetText(const StartPos, Len: PtrInt; const Xoffset: Integer): string;
begin
  SetString(Result, GetDataAdr + StartPos, Len);
  Result := TransformText(ConvertToUTF8(Result), Xoffset);
end;

function TViewerControl.CalcTextLineLength(var iStartPos: PtrInt; const aLimit: Int64; out DataLength: PtrInt): Integer;
var
  MaxLineLength: Boolean;
  CharLenInBytes: Integer;
  OldPos, LastSpacePos: PtrInt;
  LastSpaceResult: Integer;
begin
  Result := 0;
  DataLength := 0;
  LastSpacePos := -1;
  MaxLineLength := True;
  OldPos := iStartPos;

  while MaxLineLength and (iStartPos < aLimit) do
  begin
    case GetNextCharAsAscii(iStartPos, CharLenInBytes) of
      9:             // tab
        Inc(Result, cTabSpaces - Result mod cTabSpaces);
      10:            // stroka
        begin
          DataLength := iStartPos - OldPos;
          iStartPos := iStartPos + CharLenInBytes;
          Exit;
        end;
      13:             // karetka
        begin
          DataLength := iStartPos - OldPos;
          iStartPos := iStartPos + CharLenInBytes;
          // Move after possible #10.
          if (iStartPos < aLimit) and (GetNextCharAsAscii(iStartPos, CharLenInBytes) = 10) then
            Inc(iStartPos, CharLenInBytes);
          Exit;
        end;
      32, 33, 40, 41, 44, 45, 46, 47, 92, 58, 59, 63, 91, 93:              //probel
        begin
          Inc(Result, 1);
          LastSpacePos := iStartPos + CharLenInBytes;
          LastSpaceResult := Result;
        end;
      else
        Inc(Result, 1);
    end;

    if CharLenInBytes = 0 then  // End of data or invalid character.
      break;

    iStartPos := iStartPos + CharLenInBytes;
    DataLength := iStartPos - OldPos;
    case FViewerMode of
    vmText:   MaxLineLength := Result < cMaxTextWidth;
    vmWrap:   MaxLineLength := Result < FTextWidth;
    vmBook:   MaxLineLength := Canvas.TextWidth(GetText(OldPos, DataLength, 0)) < FTextWidth;
    else
      Exit;
    end;
  end;

  if (not MaxLineLength) and (LastSpacePos <> -1) then
  begin
    iStartPos := LastSpacePos;
    Result := LastSpaceResult;
    DataLength := iStartPos - OldPos;
  end;
end;

function TViewerControl.TransformText(const sText: String; const Xoffset: Integer): String;
var
  c: AnsiChar;
  i: Integer;
begin
  Result := '';
  for i := 1 to Length(sText) do
  begin
    c := sText[i];
    // Parse only ASCII chars.
    case c of
      #9:
        Result := Result + StringOfChar(' ',
                    cTabSpaces - (UTF8Length(Result) + Xoffset) mod cTabSpaces);
      else
        begin
          if c < ' ' then
            Result := Result + ' '
          else
            Result := Result + c;
        end;
    end;
  end;
end;

function TViewerControl.TransformHex(var aPosition: PtrInt; aLimit: PtrInt): AnsiString;

  function LineFormat(const sHex, sAscii: AnsiString; iOffset: PtrInt): AnsiString;
  begin
    Result := Format('%s: %s', [IntToHex(iOffset, cHexOffsetWidth), sHex]);
    if Length(sHex) < cHexWidth * 3 then
      Result := Result + StringOfChar(' ', cHexWidth * 3 - Length(sHex));
    Result := Result + '  ';
    Result := Result + sAscii;
  end;

var
  c: AnsiChar;
  i: Integer;
  sStr: string = '';
  sHex: string = '';
  aStartOffset: PtrInt;
begin
  if aPosition >= aLimit then
    Exit('');

  aStartOffset := aPosition;
  for i := 0 to cHexWidth - 1 do
  begin
    if aPosition >= aLimit then
      Break;
    c := PAnsiChar(GetDataAdr)[aPosition];
    if c < ' ' then
      sStr := sStr + '.'
    else if c > #127 then
      sStr := sStr + '.'
    else
      sStr := sStr + c;

    sHex := sHex + IntToHex(Ord(c), 2);
    if ((i and 7) = 7) and (i <> cHexWidth - 1) then
      sHex := sHex + '|'
    else
      sHex := sHex + ' ';

    Inc(aPosition);
  end;

  Result := LineFormat(sHex, sStr, aStartOffset)
end;

function TViewerControl.TransformBin(var aPosition: PtrInt; aLimit: PtrInt): AnsiString;
var
  c: AnsiChar;
  i: Integer;
begin
  Result := '';
  for i := 0 to cBinWidth - 1 do
  begin
    if aPosition >= aLimit then
      Break;
    c := PAnsiChar(GetDataAdr)[aPosition];
    if c < ' ' then
      Result := Result + '.'
    else if c > #127 then
      Result := Result + '.'
    else
      Result := Result + c;

    Inc(aPosition);
  end;
end;

function TViewerControl.GetStartOfLine(aPosition: PtrInt): PtrInt;

  function GetStartOfLineText: PtrInt;
  var
    tmpPos, LineStartPos: PtrInt;
    DataLength: PtrInt;
    prevChar: Cardinal;
    CharLenInBytes: Integer;
  begin
    prevChar := GetPrevCharAsAscii(aPosition, CharLenInBytes);
    if CharLenInBytes = 0 then
      Exit(aPosition);

    // Check if this already is not a start of line (if previous char is #10).
    if prevChar = 10 then
      Exit(aPosition);

    tmpPos := aPosition - CharLenInBytes;

    if tmpPos <= FLowLimit then
      Exit(FLowLimit);

    // Check if we're not in the middle of line ending
    // (previous char is #13, current char is #10).
    if (prevChar = 13) and
       (GetNextCharAsAscii(aPosition, CharLenInBytes) = 10) then
    begin
      prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
      if CharLenInBytes = 0 then
        Exit(aPosition);
      Dec(tmpPos, CharLenInBytes);
    end;

    if tmpPos <= FLowLimit then
      Exit(FLowLimit);

    // Search for real start of line.
    while (not (prevChar in [10, 13])) and (tmpPos > FLowLimit) do
    begin
      prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
      if CharLenInBytes = 0 then
        Break;
      Dec(tmpPos, CharLenInBytes);
    end;

    // Previous end of line not found and there are no more data to check.
    if (not (prevChar in [10, 13])) and (tmpPos <= FLowLimit) then
      Exit(FLowLimit);

    // Move forward to first non-line ending character.
    Inc(tmpPos, CharLenInBytes);

    // Search for start of real line or wrapped line.
    while True do
    begin
      LineStartPos := tmpPos;
      CalcTextLineLength(tmpPos, FHighLimit, DataLength);

      if tmpPos = aPosition then
      begin
        if aPosition < FHighLimit then
          Exit(aPosition)       // aPosition is already at start of a line
        else
          Exit(LineStartPos);   // aPosition points to end of file so return start of this line
      end
      else if tmpPos > aPosition then
        Exit(LineStartPos);     // Found start of line
    end;
  end;

  function GetStartOfLineFixed(aFixedWidth: Integer): PtrInt;
  begin
    Result := aPosition - (aPosition mod aFixedWidth);
  end;

var
  i: Integer;
begin
  if aPosition <= FLowLimit then
    Exit(FLowLimit)
  else if aPosition >= FHighLimit then
    aPosition := FHighLimit;   // search from the end of the file

  // Speedup for currently displayed positions.
  if (FLineList.Count > 0) and
     (aPosition >= FLineList.Items[0]) and
     (aPosition <= FLineList.Items[FLineList.Count - 1]) then
  begin
    for i := FLineList.Count - 1 downto 0 do
      if FLineList.Items[i] <= aPosition then
        Exit(FLineList.Items[i]);
  end;

  case FViewerMode of
    vmBin:
      Result := GetStartOfLineFixed(cBinWidth);
    vmHex:
      Result := GetStartOfLineFixed(cHexWidth);
    vmText, vmWrap, vmBook:
      Result := GetStartOfLineText;
    else
      Result := aPosition;
  end;
end;

function TViewerControl.GetEndOfLine(aPosition: PtrInt): PtrInt;

  function GetEndOfLineText: PtrInt;
  var
    tmpPos: PtrInt;
    DataLength: PtrInt;
  begin
    Result := GetStartOfLine(aPosition);
    tmpPos := Result;
    CalcTextLineLength(tmpPos, FHighLimit, DataLength);
    Result := Result + DataLength;
    if Result < aPosition then
      Result := aPosition;
  end;

  function GetEndOfLineFixed(aFixedWidth: Integer): PtrInt;
  begin
    Result := aPosition - (aPosition mod aFixedWidth) + aFixedWidth;
  end;

begin
  case FViewerMode of
    vmBin:
      Result := GetEndOfLineFixed(cBinWidth);
    vmHex:
      Result := GetEndOfLineFixed(cHexWidth);
    vmText, vmWrap, vmBook:
      Result := GetEndOfLineText;
    else
      Result := aPosition;
  end;
end;

function TViewerControl.GetStartOfPrevLine(aPosition: PtrInt): PtrInt;

  function GetPrevLineText: PtrInt;
  var
    tmpPos, LineStartPos: PtrInt;
    DataLength: PtrInt;
    prevChar: Cardinal;
    CharLenInBytes: Integer;
  begin
    prevChar := GetPrevCharAsAscii(aPosition, CharLenInBytes);
    if CharLenInBytes = 0 then
      Exit(aPosition);

    tmpPos := aPosition - CharLenInBytes; // start search from previous character

    if tmpPos <= FLowLimit then
      Exit(FLowLimit);

    // Check if we're not in the middle of line ending
    // (previous char is #13, current char is #10).
    if (prevChar = 13) and
       (GetNextCharAsAscii(aPosition, CharLenInBytes) = 10) then
    begin
      prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
      if CharLenInBytes = 0 then
        Exit(aPosition);
      Dec(tmpPos, CharLenInBytes);
    end
    else
    begin
      // Bypass possible end of previous line.
      if prevChar = 10 then
      begin
        prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
        if CharLenInBytes = 0 then
          Exit(aPosition);
        Dec(tmpPos, CharLenInBytes);
      end;
      if prevChar = 13 then
      begin
        prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
        if CharLenInBytes = 0 then
          Exit(aPosition);
        Dec(tmpPos, CharLenInBytes);
      end;
    end;

    if tmpPos <= FLowLimit then
      Exit(FLowLimit);

    // Search for real start of line.
    while (not (prevChar in [10, 13])) and (tmpPos > FLowLimit) do
    begin
      prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
      if CharLenInBytes = 0 then
        Break;
      Dec(tmpPos, CharLenInBytes);
    end;

    // Move forward to first non-line ending character.
    Inc(tmpPos, CharLenInBytes);

    // Search for start of real line or wrapped line.
    while True do
    begin
      LineStartPos := tmpPos;
      CalcTextLineLength(tmpPos, aPosition, DataLength);

      if tmpPos >= aPosition then
        Exit(LineStartPos);  // Found start of line
    end;
  end;

  function GetPrevLineFixed(aFixedWidth: Integer): PtrInt;
  begin
    Result := aPosition - (aPosition mod aFixedWidth);
    if Result >= aFixedWidth then
      Result := Result - aFixedWidth;
  end;

var
  i: Integer;
begin
  if aPosition <= FLowLimit then
    Exit(FLowLimit)
  else if aPosition >= FHighLimit then
    aPosition := FHighLimit;   // search from the end of the file

  // Speedup for currently displayed positions.
  if (FLineList.Count > 0) and
     (aPosition >= FLineList.Items[0]) and
     (aPosition <= FLineList.Items[FLineList.Count - 1]) then
  begin
    for i := FLineList.Count - 1 downto 0 do
      if FLineList.Items[i] < aPosition then
        Exit(FLineList.Items[i]);
  end;

  case FViewerMode of
    vmBin:
      Result := GetPrevLineFixed(cBinWidth);
    vmHex:
      Result := GetPrevLineFixed(cHexWidth);
    vmText, vmWrap, vmBook:
      Result := GetPrevLineText;
    else
      Result := aPosition;
  end;
end;

function TViewerControl.GetStartOfNextLine(aPosition: PtrInt): PtrInt;

  function GetNextLineText: PtrInt;
  var
    tmpPos: PtrInt;
    DataLength: PtrInt;
    prevChar: Cardinal;
    CharLenInBytes: Integer;
  begin
    tmpPos := aPosition;

    // This might not be a real start of line (it may be start of wrapped line).
    // Search for start of line.
    while (tmpPos > FLowLimit) do
    begin
      prevChar := GetPrevCharAsAscii(tmpPos, CharLenInBytes);
      if CharLenInBytes = 0 then
        Break;
      if (prevChar in [10, 13]) then
        Break
      else
        Dec(tmpPos, CharLenInBytes);
    end;

    // Now we know we are at the start of a line, search the start of next line.
    while True do
    begin
      CalcTextLineLength(tmpPos, FHighLimit, DataLength);

      if tmpPos >= aPosition then
        Exit(tmpPos);  // Found start of line
    end;
  end;

  function GetNextLineFixed(aFixedWidth: Integer): PtrInt;
  begin
    Result := aPosition - (aPosition mod aFixedWidth);
    if Result + aFixedWidth < FHighLimit then
      Result := Result + aFixedWidth;
  end;

var
  i: Integer;
begin
  if aPosition < FLowLimit then
    aPosition := FLowLimit         // search from the start of the file
  else if aPosition >= FHighLimit then
    aPosition := FHighLimit;   // search from the end of the file

  // Speedup for currently displayed positions.
  if (FLineList.Count > 0) and
     (aPosition >= FLineList.Items[0]) and
     (aPosition <= FLineList.Items[FLineList.Count - 1]) then
  begin
    for i := 0 to FLineList.Count - 1 do
      if FLineList.Items[i] > aPosition then
        Exit(FLineList.Items[i]);
  end;

  case FViewerMode of
    vmBin:
      Result := GetNextLineFixed(cBinWidth);
    vmHex:
      Result := GetNextLineFixed(cHexWidth);
    vmText, vmWrap, vmBook:
      Result := GetNextLineText;
    else
      Result := aPosition;
  end;
end;

procedure TViewerControl.PageUp;
var
  H: Integer;
begin
  H := GetClientHeightInLines * FColCount - 1;
  if H <= 0 then
    H := 1;
  Scroll(-H);
end;

procedure TViewerControl.HPageUp;
var
  H: Integer;
begin
  H := FHPosition - FTextWidth;
  if H <= 0 then
    H := FHPosition else H:= FTextWidth;
  HScroll(-H);
end;

procedure TViewerControl.PageDown;
var
  H: Integer;
begin
  H := GetClientHeightInLines * FColCount - 1;
  if H <= 0 then
    H := 1;
  Scroll(H);
end;

procedure TViewerControl.HPageDown;
var
  H: Integer;
begin
  H := FHLowEnd - FHPosition;
  if H > FTextWidth then H := FTextWidth ;
  HScroll(H);
end;

procedure TViewerControl.GoHome;
begin
  Position := FLowLimit;
end;

procedure TViewerControl.GoEnd;
begin
  Position := FHighLimit;
end;

procedure TViewerControl.HGoHome;
begin
  HScroll (-FHPosition);
end;

procedure TViewerControl.HGoEnd;
begin
  HScroll (FHLowEnd-FHPosition);
end;

procedure TViewerControl.SetFileName(const sFileName: String);
begin
  if not (csDesigning in ComponentState) then
  begin
    UnMapFile;

    if sFileName <> '' then
    begin
      if MapFile(sFileName) then
      begin
        FFileName  := sFileName;

        // Detect encoding if needed.
        if FEncoding = veAutoDetect then
          FEncoding := DetectEncoding;

        ReReadFile;
      end;
    end;
  end
  else
    FFileName  := sFileName;
end;

function TViewerControl.MapFile(const sFileName: String): Boolean;

  function ReadFile: Boolean; inline;
  begin
    FMappedFile := GetMem(FFileSize);
    Result := (FileRead(FFileHandle, FMappedFile^, FFileSize) = FFileSize);
    FileClose(FFileHandle);
    FFileHandle := 0;
  end;

{$IFDEF MSWINDOWS}
var
  wFileName: WideString;
begin
  Result := False;
  if Assigned(FMappedFile) then
    UnMapFile; // if needed

  wFileName   := UTF8Decode(sFileName);
  FFileHandle := CreateFileW(PWChar(wFileName), GENERIC_READ,
      FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE, nil,
      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

  if FFileHandle = INVALID_HANDLE_VALUE then
  begin
    FFileHandle := 0;
    Exit;
  end;

  FFileSize := GetFileSize(FFileHandle, nil);

  if (FFileSize < MaxMemSize) then
  begin
    Result := ReadFile;
    Exit;
  end;

  FMappingHandle := CreateFileMapping(FFileHandle, nil, PAGE_READONLY, 0, 0, nil);

  if FMappingHandle <> 0 then
    FMappedFile := MapViewOfFile(FMappingHandle, FILE_MAP_READ, 0, 0, 0)
  else
  begin
    FMappedFile := nil;
    FileClose(FFileHandle);
    FFileHandle := 0;
    Exit;
  end;

  Result := True;
end;
{$ELSE}
var
  StatBuf: Stat;
begin
  Result := False;
  if Assigned(FMappedFile) then
    UnMapFile; // if needed

  FFileHandle := fpOpen(PChar(sFileName), O_RDONLY);
  if FFileHandle = feInvalidHandle then
  begin
    FFileHandle := 0;
    Exit;
  end;

  if fpFStat(FFileHandle, StatBuf) <> 0 then
  begin
    fpClose(FFileHandle);
    FFileHandle := 0;
    Exit;
  end;

  FFileSize := StatBuf.st_size;

  if (FFileSize < MaxMemSize) then
  begin
    Result := ReadFile;
    Exit;
  end;

  FMappedFile := fpmmap(nil, FFileSize, PROT_READ, MAP_PRIVATE{SHARED}, FFileHandle, 0);
  if FMappedFile = MAP_FAILED then
  begin
    FMappedFile:= nil;
    fpClose(FFileHandle);
    FFileHandle := 0;
    Exit;
  end;

  Result:= True;
end;
{$ENDIF}

procedure TViewerControl.UnMapFile;
begin
  if (FFileSize < MaxMemSize) then
  begin
    if Assigned(FMappedFile) then
    begin
      FreeMem(FMappedFile);
      FMappedFile := nil;
    end;
  end;

{$IFDEF MSWINDOWS}

  if Assigned(FMappedFile) then
  begin
    UnmapViewOfFile(FMappedFile);
    FMappedFile := nil;
  end;

  if FMappingHandle <> 0 then
  begin
    CloseHandle(FMappingHandle);
    FMappingHandle := 0;
  end;

  if FFileHandle <> 0 then
  begin
    FileClose(FFileHandle);
    FFileHandle := 0;
  end;

{$ELSE}

  if Assigned(FMappedFile) then
  begin
    if fpmunmap(FMappedFile, FFileSize) = -1 then
      DebugLn('Error unmapping file: ', SysErrorMessage(fpgeterrno));
    FMappedFile := nil;
  end;

  if FFileHandle <> 0 then
  begin
    fpClose(FFileHandle);
    FFileHandle := 0;
  end;

{$ENDIF}

  FFileName  := '';
  FFileSize  := 0;
  Position   := 0;
  FLowLimit  := 0;
  FHighLimit := 0;
  FBOMLength := 0;
  FBlockBeg  := 0;
  FBlockEnd  := 0;
end;

procedure TViewerControl.WriteText;
var
  yIndex, xIndex, w, scrollTab, i: Integer;
  LineStart, iPos: PtrInt;
  DataLength: PtrInt;
begin
  iPos := FPosition;
  if ViewerMode = vmBook then
     w := Width div FColCount
  else
     w := 0;
  if (ViewerMode = vmText) and (FHPosition>0) then
    scrollTab := -FHPosition * Canvas.TextWidth('W')
  else
    scrollTab :=0;
  for xIndex := 0 to FColCount-1 do
    begin
      for yIndex := 0 to GetClientHeightInLines - 1 do
      begin
        if iPos >= FHighLimit then
          Break;
        AddLineOffset(iPos);
        LineStart := iPos;
        i := CalcTextLineLength(iPos, FHighLimit, DataLength);
        if i > FHLowEnd then FHLowEnd:=i;
        if DataLength > 0 then
          OutText(scrollTab+xIndex*w, yIndex * FTextHeight, LineStart, DataLength)
      end;
    end;
end;

procedure TViewerControl.WriteHex;
var
  yIndex: Integer;
  iPos, LineStart: PtrInt;
  s: string;
begin
  iPos := FPosition;
  for yIndex := 0 to GetClientHeightInLines - 1 do
  begin
    if iPos >= FHighLimit then
      Break;
    LineStart := iPos;
    AddLineOffset(iPos);
    s := TransformHex(iPos, FHighLimit);
    if s <> '' then
      OutHex(0, yIndex * FTextHeight, s, LineStart, iPos - LineStart);
  end;
end;

procedure TViewerControl.WriteBin;
var
  yIndex: Integer;
  iPos, LineStart: PtrInt;
  s: string;
begin
  iPos := FPosition;
  for yIndex := 0 to GetClientHeightInLines - 1 do
  begin
    if iPos >= FHighLimit then
      Break;
    LineStart := iPos;
    AddLineOffset(iPos);
    s := TransformBin(iPos, FHighLimit);
    if s <> '' then
      OutBin(0, yIndex * FTextHeight, s, LineStart, iPos - LineStart);
  end;
end;

function TViewerControl.GetDataAdr: Pointer;
begin
  case FViewerMode of
    vmText, vmWrap, vmBook:
      Result := FMappedFile + FBOMLength;
    else
      Result := FMappedFile;
  end;
end;

procedure TViewerControl.SetPosition(Value: PtrInt);
begin
  SetPosition(Value, False);
end;

procedure TViewerControl.SetHPosition(Value: Integer);
begin
  SetHPosition(Value, False);
end;

procedure TViewerControl.SetHPosition(Value: Integer; Force: Boolean);
begin
  if not IsFileOpen then
    Exit;

  FHPosition := Value;
  // Set new scroll position.
  if (FHLowEnd - FTextWidth) > 0 then
  begin
    if FHPosition > 0 then
      FHScrollBarPosition := FHPosition * 100 div (FHLowEnd - FTextWidth)
    else
      FHScrollBarPosition := 0;
  end;
  // Update scrollbar position.
  if FUpdateScrollBarPos then
  begin
    if FScrollBarHorz.Position <> FHScrollBarPosition then
    begin
      // Workaround for bug: http://bugs.freepascal.org/view.php?id=23815
      {$IF DEFINED(LCLQT) and (LCL_FULLVERSION < 1010000)}
      FScrollBarHorz.OnScroll := nil;
      FScrollBarHorz.Position := FHScrollBarPosition;
      Application.ProcessMessages; // Skip message
      FScrollBarHorz.OnScroll := @ScrollBarHorzScroll;
      {$ELSE}
      FScrollBarHorz.Position := FHScrollBarPosition;
      {$ENDIF}
    end;
  end;
  // else the scrollbar position will be updated in ScrollBarVertScroll
  Invalidate;
end;

procedure TViewerControl.SetPosition(Value: PtrInt; Force: Boolean);
var
  LinesTooMany:    Integer;
  LastLineReached: Boolean;
begin
  if not IsFileOpen then
    Exit;

  // Speedup if total nr of lines is less then nr of lines that can be displayed.
  if (FPosition = FLowLimit) and                // only if already at the top
     (FLineList.Count > 0) and (FLineList.Count < GetClientHeightInLines)
  then
    Value := FLowLimit
  else
    // Boundary checks are done in GetStartOfLine.
    Value := GetStartOfLine(Value);

  if (Value <> FPosition) or Force then
  begin
    // Don't allow empty lines at the bottom of the control.
    LinesTooMany := GetClientHeightInLines - GetLinesTillEnd(Value, LastLineReached);
    if LinesTooMany > 0 then
      ScrollPosition(Value, -LinesTooMany); // scroll back upwards

    FPosition := Value;
    if Assigned(FOnPositionChanged) then
      FOnPositionChanged(Self);
    Invalidate;

    // Set new scroll position.
    if LastLineReached then
      FScrollBarPosition := 100
    else
      FScrollBarPosition := Percent;
  end;

  // Update scrollbar position.
  if FUpdateScrollBarPos then
  begin
    if FScrollBarVert.Position <> FScrollBarPosition then
    begin
      // Workaround for bug: http://bugs.freepascal.org/view.php?id=23815
      {$IF DEFINED(LCLQT) and (LCL_FULLVERSION < 1010000)}
      FScrollBarVert.OnScroll := nil;
      FScrollBarVert.Position := FScrollBarPosition;
      Application.ProcessMessages; // Skip message
      FScrollBarVert.OnScroll := @ScrollBarVertScroll;
      {$ELSE}
      FScrollBarVert.Position := FScrollBarPosition;
      {$ENDIF}
    end;
  end;
  // else the scrollbar position will be updated in ScrollBarVertScroll
end;

procedure TViewerControl.SetEncoding(AEncoding: TViewerEncoding);
begin
  if not (csDesigning in ComponentState) then
  begin
    if AEncoding = veAutoDetect then
      FEncoding := DetectEncoding
    else
      FEncoding := AEncoding;

    ReReadFile;
  end
  else
    FEncoding := AEncoding;
end;

function TViewerControl.GetEncodingName: string;
begin
  Result := ViewerEncodingsNames[FEncoding];
end;

procedure TViewerControl.SetEncodingName(AEncodingName: string);
var
  i: TViewerEncoding;
begin
  for i := Low(TViewerEncoding) to High(TViewerEncoding) do
    if NormalizeEncoding(ViewerEncodingsNames[i]) = NormalizeEncoding(AEncodingName) then
    begin
      SetEncoding(i);
      break;
    end;
end;

function TViewerControl.GetClientHeightInLines: Integer;
begin
  if FViewerMode <> vmText then
    Result:= 0
  else // Take horizontal scrollbar into account
    Result:= GetSystemMetrics(SM_CYHSCROLL);

  if FTextHeight > 0 then
    Result := (ClientRect.Bottom - ClientRect.Top - Result) div FTextHeight
             // or Self.Height div FTextHeight?
  else
    Result := 0;
end;

function TViewerControl.GetLinesTillEnd(FromPosition: PtrInt;
  out LastLineReached: Boolean): Integer;
var
  yIndex: Integer;
  iPos:   PtrInt;
  DataLength: PtrInt;
begin
  Result := 0;
  iPos   := FromPosition;
  for yIndex := 0 to GetClientHeightInLines - 1 do
  begin
    if iPos >= FHighLimit then
      Break;
    Inc(Result, 1);
    case ViewerMode of
      vmBin:
        iPos := iPos + cBinWidth;
      vmHex:
        iPos := iPos + cHexWidth;
      vmText, vmWrap, vmBook:
        CalcTextLineLength(iPos, FHighLimit, DataLength);
    end;
  end;
  LastLineReached := (iPos >= FHighLimit);
end;

function TViewerControl.GetPercent: Integer;
begin
  if FHighLimit - FLowLimit > 0 then
    Result := (Int64(FPosition - FLowLimit) * 100) div Int64(FHighLimit - FLowLimit)
  else
    Result := 0;
end;

procedure TViewerControl.SetPercent(const AValue: Integer);
begin
  if FHighLimit - FLowLimit > 0 then
    Position := Int64(AValue) * (Int64(FHighLimit  - FLowLimit) div 100) + FLowLimit
  else
    Position := 0;
end;

procedure TViewerControl.SetBlockBegin(const AValue: PtrInt);
begin
  if (AValue >= FLowLimit) and (AValue < FHighLimit) then
  begin
    if FBlockEnd < AValue then
      FBlockEnd := AValue;
    FBlockBeg   := AValue;
    Invalidate;
  end;
end;

procedure TViewerControl.SetBlockEnd(const AValue: PtrInt);
begin
  if (AValue >= FLowLimit) and (AValue < FHighLimit) then
  begin
    if FBlockBeg > AValue then
      FBlockBeg := AValue;
    FBlockEnd   := AValue;
    Invalidate;
  end;
end;

procedure TViewerControl.OutText(x, y: Integer;
  StartPos: PtrInt; DataLength: Integer);
var
  pBegLine, pEndLine: PtrInt;
  iBegDrawIndex, iEndDrawIndex: PtrInt;
  xOffset: Integer;
  sText: string;
begin
  pBegLine := StartPos;
  pEndLine := pBegLine + DataLength;

  if ((FBlockEnd - FBlockBeg) = 0) or ((FBlockBeg < pBegLine) and (FBlockEnd < pBegLine)) or // before
     ((FBlockBeg > pEndLine) and (FBlockEnd > pEndLine)) then //after
  begin
    // out of selection, draw normal
    Canvas.Font.Color := Font.Color;
    Canvas.TextOut(x, y, GetText(StartPos, DataLength, 0));
    Exit;
  end;

  // Get selection start/end.
  if (FBlockBeg <= pBegLine) then
    iBegDrawIndex := pBegLine
  else
    iBegDrawIndex := FBlockBeg;
  if (FBlockEnd < pEndLine) then
    iEndDrawIndex := FBlockEnd
  else
    iEndDrawIndex := pEndLine;

  xOffset := 0;

  // Text before selection.
  if iBegDrawIndex - pBegLine > 0 then
  begin
    sText := GetText(StartPos, iBegDrawIndex - pBegLine, xOffset);
    Canvas.Font.Color := Font.Color;
    Canvas.TextOut(x, y, sText);
    x := x + Canvas.TextWidth(sText);
    xOffset := xOffset + UTF8Length(sText);
  end;

  // Selected text.
  sText := GetText(StartPos + iBegDrawIndex - pBegLine,
                   iEndDrawIndex - iBegDrawIndex, xOffset);

  Canvas.Brush.Color := clHighlight;
  Canvas.Font.Color  := clHighlightText;

  // Cannot simply draw text with brush with TextOut
  // because it differs between widgetsets.
  Canvas.Brush.Style := bsSolid;
  Canvas.FillRect(Bounds(x, y, Canvas.TextWidth(sText), FTextHeight));
  Canvas.Brush.Style := bsClear;

  // Or use TextRect instead of TextOut with Opaque = True.
  //ts := Canvas.TextStyle;
  //ts.Opaque := True;
  //ts.Clipping := True;
  //Canvas.TextRect(Bounds(X, Y, Canvas.TextWidth(sText), FTextHeight), X, Y, sText, ts);

  Canvas.TextOut(x, y, sText);
  x := x + Canvas.TextWidth(sText);
  xOffset := xOffset + UTF8Length(sText);

  // restore previous canvas settings
  Canvas.Brush.Color := Color;
  Canvas.Font.Color  := Font.Color;

  // Text after selection.
  if pEndLine - iEndDrawIndex > 0 then
  begin
    sText := GetText(StartPos + iEndDrawIndex - pBegLine,
                     pEndLine - iEndDrawIndex, xOffset);
    Canvas.TextOut(x, y, sText);
  end;
end;

procedure TViewerControl.OutHex(x, y: Integer; sText: string;
  StartPos: PtrInt; DataLength: Integer);
var
  pBegLine, pEndLine: PtrInt;
  iBegDrawIndex, iEndDrawIndex: PtrInt;
  sNextText: String = '';
  sTmpText: String;
begin
  pBegLine := StartPos;
  pEndLine := pBegLine + DataLength;

  if ((FBlockEnd - FBlockBeg) = 0) or ((FBlockBeg < pBegLine) and (FBlockEnd <= pBegLine)) or // before
     ((FBlockBeg > pEndLine) and (FBlockEnd > pEndLine)) then //after
  begin
    // out of selection, draw normal
    Canvas.Font.Color := Font.Color;
    Canvas.TextOut(x, y, sText);
    Exit;
  end;

  // Get selection start/end.
  if (FBlockBeg <= pBegLine) then
    iBegDrawIndex := pBegLine
  else
    iBegDrawIndex := FBlockBeg;
  if (FBlockEnd < pEndLine) then
    iEndDrawIndex := FBlockEnd
  else
    iEndDrawIndex := pEndLine;

  // Text before selection (offset and hex part).
  sTmpText := Copy(sText, 1, cHexStartHex + (iBegDrawIndex - pBegLine) * 3);
  Canvas.Font.Color := Font.Color;
  Canvas.TextOut(x, y, sTmpText);
  x := x + Canvas.TextWidth(sTmpText);

  // Selected text (hex part).
  sTmpText := Copy(sText, 1 + cHexStartHex + (iBegDrawIndex - pBegLine) * 3,
                                             (iEndDrawIndex - iBegDrawIndex) * 3);

  // Move last character from selection to not selected text.
  sNextText := Copy(sTmpText, Length(sTmpText), 1);
  Delete(sTmpText, Length(sTmpText), 1);

  Canvas.Brush.Color := clHighlight;
  Canvas.Font.Color  := clHighlightText;

  Canvas.Brush.Style := bsSolid;
  Canvas.FillRect(Bounds(x, y, Canvas.TextWidth(sTmpText), FTextHeight));
  Canvas.Brush.Style := bsClear;
  Canvas.TextOut(x, y, sTmpText);
  x := x + Canvas.TextWidth(sTmpText);

  // restore previous canvas settings
  Canvas.Brush.Color := Color;
  Canvas.Font.Color  := Font.Color;

  // Text after selection (hex part).
  if pEndLine - iEndDrawIndex > 0 then
  begin
    sTmpText := sNextText +
      Copy(sText, 1 + cHexStartHex + (iEndDrawIndex - pBegLine) * 3,
                                     (pEndLine - iEndDrawIndex) * 3);
    sNextText := '';
    Canvas.TextOut(x, y, sTmpText);
    x := x + Canvas.TextWidth(sTmpText);
  end;

  // Space after hex if data doesn't span full line.
  if DataLength < cHexWidth then
    sNextText := sNextText + Copy(sText, 1 + cHexStartHex + DataLength * 3,
                                         (cHexWidth - DataLength) * 3);

  // Space between hex and ascii.
  sTmpText := sNextText + '  ';
  Canvas.TextOut(x, y, sTmpText);
  x := x + Canvas.TextWidth(sTmpText);

  // Text before selection (ascii part).
  if iBegDrawIndex - pBegLine > 0 then
  begin
    sTmpText := Copy(sText, 1 + cHexStartAscii, iBegDrawIndex - pBegLine);
    Canvas.TextOut(x, y, sTmpText);
    x := x + Canvas.TextWidth(sTmpText);
  end;

  // Selected text (ascii part).
  sTmpText := Copy(sText, 1 + cHexStartAscii + iBegDrawIndex - pBegLine,
                                               iEndDrawIndex - iBegDrawIndex);
  Canvas.Brush.Color := clHighlight;
  Canvas.Font.Color  := clHighlightText;
  Canvas.Brush.Style := bsSolid;
  Canvas.FillRect(Bounds(x, y, Canvas.TextWidth(sTmpText), FTextHeight));
  Canvas.Brush.Style := bsClear;
  Canvas.TextOut(x, y, sTmpText);
  x := x + Canvas.TextWidth(sTmpText);

  // restore background color
  Canvas.Brush.Color := Color;
  Canvas.Font.Color  := Font.Color;

  // Text after selection.
  if pEndLine - iEndDrawIndex > 0 then
  begin
    sTmpText := Copy(sText, 1 + cHexStartAscii + iEndDrawIndex - pBegLine,
                                                 pEndLine - iEndDrawIndex);
    Canvas.TextOut(x, y, sTmpText);
  end;
end;

procedure TViewerControl.OutBin(x, y: Integer; sText: string; StartPos: PtrInt;
  DataLength: Integer);
var
  pBegLine, pEndLine: PtrInt;
  iBegDrawIndex, iEndDrawIndex: PtrInt;
  sTmpText: String;
begin
  pBegLine := StartPos;
  pEndLine := pBegLine + DataLength;

  if ((FBlockEnd - FBlockBeg) = 0) or ((FBlockBeg < pBegLine) and (FBlockEnd < pBegLine)) or // before
     ((FBlockBeg > pEndLine) and (FBlockEnd > pEndLine)) then //after
  begin
    // out of selection, draw normal
    Canvas.Font.Color := Font.Color;
    Canvas.TextOut(x, y, sText);
    Exit;
  end;

  // Get selection start/end.
  if (FBlockBeg <= pBegLine) then
    iBegDrawIndex := pBegLine
  else
    iBegDrawIndex := FBlockBeg;
  if (FBlockEnd < pEndLine) then
    iEndDrawIndex := FBlockEnd
  else
    iEndDrawIndex := pEndLine;

  // Text before selection.
  if iBegDrawIndex - pBegLine > 0 then
  begin
    sTmpText := Copy(sText, 1, iBegDrawIndex - pBegLine);
    Canvas.Font.Color := Font.Color;
    Canvas.TextOut(x, y, sTmpText);
    x := x + Canvas.TextWidth(sTmpText);
  end;

  // Selected text.
  sTmpText := Copy(sText, 1 + iBegDrawIndex - pBegLine, iEndDrawIndex - iBegDrawIndex);

  Canvas.Brush.Color := clHighlight;
  Canvas.Font.Color  := clHighlightText;
  Canvas.Brush.Style := bsSolid;
  Canvas.FillRect(Bounds(x, y, Canvas.TextWidth(sTmpText), FTextHeight));
  Canvas.Brush.Style := bsClear;
  Canvas.TextOut(x, y, sTmpText);
  x := x + Canvas.TextWidth(sTmpText);

  // restore previous canvas settings
  Canvas.Brush.Color := Color;
  Canvas.Font.Color  := Font.Color;

  // Text after selection.
  if pEndLine - iEndDrawIndex > 0 then
  begin
    sTmpText := Copy(sText, 1 + iEndDrawIndex - pBegLine, pEndLine - iEndDrawIndex);
    Canvas.TextOut(x, y, sTmpText);
  end;
end;

procedure TViewerControl.AddLineOffset(iOffset: PtrInt);
begin
  FLineList.Add(iOffset);
end;

procedure TViewerControl.KeyDown(var Key: word; Shift: TShiftState);
begin
  if Shift = [] then
  begin
    case Key of
      VK_DOWN:
        begin
          Key := 0;
          Scroll(1);
        end;
      VK_UP:
        begin
          Key := 0;
          Scroll(-1);
        end;
      VK_HOME:
        begin
          Key := 0;
          GoHome;
        end;
      VK_END:
        begin
          Key := 0;
          GoEnd;
        end;
      VK_PRIOR:
        begin
          Key := 0;
          PageUp;
        end;
      VK_NEXT:
        begin
          Key := 0;
          PageDown;
        end;
      else
        inherited KeyDown(Key, Shift);
    end;
  end
  else if Shift = [ssCtrl] then
  begin
    case Key of
      VK_HOME:
        begin
          Key := 0;
          GoHome;
        end;
      VK_END:
        begin
          Key := 0;
          GoEnd;
        end;
      else
        inherited KeyDown(Key, Shift);
    end;
  end
  else
    inherited KeyDown(Key, Shift);
end;

function TViewerControl.FindAsciiSetForward(aPosition, aMaxBytes: PtrInt;
                                            const AsciiChars: String;
                                            bFindNotIn: Boolean): PtrInt;
var
  i: Integer;
  found: Boolean;
  u: Cardinal;
  CharLenInBytes: Integer;
begin
  Result := -1;
  while aMaxBytes > 0 do
  begin
    u := GetNextCharAsAscii(aPosition, CharLenInBytes);
    if CharLenInBytes = 0 then
      Exit;

    if not bFindNotIn then
    begin
      for i := 1 to Length(AsciiChars) do
        if u = ord(AsciiChars[i]) then
          Exit(aPosition);
    end
    else
    begin
      found := False;
      for i := 1 to Length(AsciiChars) do
        if u = ord(AsciiChars[i]) then
        begin
          found := True;
          break;
        end;

      if not found then
        Exit(aPosition);
    end;

    Inc(aPosition, CharLenInBytes);
    Dec(aMaxBytes, CharLenInBytes);
  end;
end;

function TViewerControl.FindAsciiSetBackward(aPosition, aMaxBytes: PtrInt;
                                             const AsciiChars: String;
                                             bFindNotIn: Boolean): PtrInt;
var
  i: Integer;
  found: Boolean;
  u: Cardinal;
  CharLenInBytes: Integer;
begin
  Result := -1;
  while aMaxBytes > 0 do
  begin
    u := GetPrevCharAsAscii(aPosition, CharLenInBytes);
    if CharLenInBytes = 0 then
      Exit;

    if not bFindNotIn then
    begin
      for i := 1 to Length(AsciiChars) do
        if u = ord(AsciiChars[i]) then
          Exit(aPosition);
    end
    else
    begin
      found := False;
      for i := 1 to Length(AsciiChars) do
        if u = ord(AsciiChars[i]) then
        begin
          found := True;
          break;
        end;

      if not found then
        Exit(aPosition);
    end;

    Dec(aPosition, CharLenInBytes);
    Dec(aMaxBytes, CharLenInBytes);
  end;
end;

procedure TViewerControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer);
var
  LineBegin, LineEnd: PtrInt;
  ClickPos: PtrInt;
  CharSide: TCharSide;
begin
  inherited;

  SetFocus;

  if not IsFileOpen then
    Exit;

  case Button of
    mbLeft:
      begin
        if Shift * [ssDouble, ssTriple] = [] then
        begin
          // Single click.
          ClickPos := XYPos2Adr(x, y, CharSide);
          if ClickPos <> -1 then
          begin
            FBlockBeg       := ClickPos;
            FBlockEnd       := ClickPos;
            FMouseBlockBeg  := ClickPos;
            FMouseBlockSide := CharSide;
            FSelecting      := True;
            Invalidate;
          end
          else
            FSelecting := False;
        end
        else // if double click or triple click
        begin
          FSelecting := False;
          LineBegin  := GetStartOfLine(FMouseBlockBeg);
          LineEnd    := GetEndOfLine(FMouseBlockBeg);

          if ssDouble in Shift then
          begin
            // Select word with double-click.
            FBlockBeg := FindAsciiSetBackward(FMouseBlockBeg,
                           FMouseBlockBeg - LineBegin, sNonCharacter, False);

            FBlockEnd := FindAsciiSetForward(FMouseBlockBeg,
                           LineEnd - FMouseBlockBeg, sNonCharacter, False);
          end
          else if ssTriple in Shift then
          begin
            // Select line with triple-click.
            FBlockBeg := FindAsciiSetForward(LineBegin,
                           LineEnd - LineBegin, sWhiteSpace, True);

            FBlockEnd := FindAsciiSetBackward(LineEnd,
                           LineEnd - LineBegin, sWhiteSpace, True);
          end;

          if FBlockBeg = -1 then
            FBlockBeg := LineBegin;
          if FBlockEnd = -1 then
            FBlockEnd := LineEnd;

          if FBlockBeg > FBlockEnd then
            FBlockEnd := FBlockBeg;

          CopyToClipboard;
          Invalidate;
        end;
      end; // mbLeft
  end; // case
end;

procedure TViewerControl.MouseMove(Shift: TShiftState; X, Y: Integer);

  procedure MoveOneChar(var aPosition: PtrInt);
  var
    CharLenInBytes: Integer;
  begin
    GetNextCharAsAscii(aPosition, CharLenInBytes);
    aPosition := aPosition + CharLenInBytes;
  end;

  procedure MoveOneCharByMouseSide(var aPosition: PtrInt);
  begin
    if FMouseBlockSide in [csRight, csAfter] then
      MoveOneChar(aPosition);
  end;

var
  ClickPos: PtrInt;
  CharSide: TCharSide;
begin
  inherited;

  if FSelecting then
  begin
    if y < FTextHeight then
      Scroll(-3)
    else if y > ClientHeight - FTextHeight then
      Scroll(3);

    ClickPos := XYPos2Adr(x, y, CharSide);
    if ClickPos <> -1 then
    begin
      if ClickPos < FMouseBlockBeg then
      begin
        // Got a new beginning.
        FBlockBeg := ClickPos;
        FBlockEnd := FMouseBlockBeg;

        // Move end beyond last character.
        MoveOneCharByMouseSide(FBlockEnd);

        // When selecting from right to left, the current selected side must be
        // either csLeft or csBefore, otherwise current position is not included.
        if not (CharSide in [csLeft, csBefore]) then
        begin
          // Current position should not be included in selection.
          // Move beginning after first character.
          MoveOneChar(FBlockBeg);
        end;
      end
      else if ClickPos > FMouseBlockBeg then
      begin
        // Got a new end.
        FBlockBeg := FMouseBlockBeg;
        FBlockEnd := ClickPos;

        // Move beginning after first character.
        MoveOneCharByMouseSide(FBlockBeg);

        // When selecting from left to right, the current selected side must be
        // either csRight or csAfter, otherwise current position is not included.
        if CharSide in [csRight, csAfter] then
        begin
          // Current position should be included in selection.
          // Move end beyond last character.
          MoveOneChar(FBlockEnd);
        end;
      end
      else if FMouseBlockSide <> CharSide then
      begin
        // Same position but changed side of the character.
        FBlockBeg := FMouseBlockBeg;
        FBlockEnd := FMouseBlockBeg;

        if ((FMouseBlockSide in [csBefore, csLeft]) and
            (CharSide in [csRight, csAfter])) or
           ((FMouseBlockSide in [csRight, csAfter]) and
            (CharSide in [csBefore, csLeft])) then
        begin
          // Move end beyond last character.
          MoveOneChar(FBlockEnd);
        end;
      end
      else
      begin
        FBlockBeg := FMouseBlockBeg;
        FBlockEnd := FMouseBlockBeg;
      end;

      Invalidate;
    end;
  end;
end;

procedure TViewerControl.MouseUp(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer);
begin
  inherited;

  if FSelecting and (Button = mbLeft) and (Shift * [ssDouble, ssTriple] = []) then
  begin
    CopyToClipboard;
    FSelecting := False;
  end;
end;

function TViewerControl.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
  Result := inherited;
  if not Result then
    Result := Scroll(Mouse.WheelScrollLines);
end;

function TViewerControl.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
  Result := inherited;
  if not Result then
    Result := Scroll(-Mouse.WheelScrollLines);
end;

function TViewerControl.XYPos2Adr(x, y: Integer; out CharSide: TCharSide): PtrInt;
var
  yIndex:  Integer;
  StartLine, EndLine: PtrInt;

  function XYPos2AdrBin: PtrInt;
  var
    i:  Integer;
    px: Integer = 0;
    charWidth: Integer;
    sText: String;
    tmpPosition: PtrInt;
  begin
    tmpPosition := StartLine;
    sText := TransformBin(tmpPosition, EndLine);
    for i := 1 to Length(sText) do
    begin
      charWidth := Canvas.TextWidth(string(sText[i]));
      if px + charWidth > x then
      begin
        if px + charWidth div 2 > x then
          CharSide := csLeft
        else
          CharSide := csRight;

        Exit(StartLine + i - 1);  // -1 because we count from 1
      end;
      px  := px + charWidth;
    end;
    CharSide := csBefore;
    Result := EndLine;
  end;

  function XYPos2AdrHex: PtrInt;
  var
    i:  Integer;
    px: Integer = 0;
    charWidth: Integer;
    sText, sPartialText: String;
    tmpPosition: PtrInt;
  begin
    tmpPosition  := StartLine;
    sText := TransformHex(tmpPosition, EndLine);

    // Clicked on offset.
    sPartialText := Copy(sText, 1, cHexStartHex);
    charWidth := Canvas.TextWidth(sPartialText);
    px := px + charWidth;
    if px > x then
    begin
      CharSide := csBefore;
      Exit(StartLine);
    end;

    // Clicked on hex part.
    for i := 0 to cHexWidth - 1 do
    begin
      sPartialText := Copy(sText, 1 + cHexStartHex + i * 3, 2);
      charWidth := Canvas.TextWidth(sPartialText);
      if px + charWidth > x then
      begin
        // Check if we're not after end of data.
        if StartLine + i >= EndLine then
        begin
          CharSide := csBefore;
          Exit(EndLine);
        end;

        if px + charWidth div 2 > x then
          CharSide := csLeft
        else
          CharSide := csRight;

        Exit(StartLine + i);
      end;

      // Space after hex number.
      charWidth := charWidth +
                   Canvas.TextWidth(string(sText[1 + cHexStartHex + i * 3 + 2]));

      if px + charWidth > x then
      begin
        CharSide := csAfter;
        Exit(StartLine + i);
      end;

      px := px + charWidth;
    end;

    // Clicked between hex and ascii.
    sPartialText := Copy(sText, 1 + cHexEndHex, cHexStartAscii - cHexEndHex);
    charWidth := Canvas.TextWidth(sPartialText);
    if px + charWidth > x then
    begin
      Exit(-1); // No position.
    end;
    px := px + charWidth;

    // Clicked on ascii part.
    for i := 0 to cHexWidth - 1 do
    begin
      charWidth := Canvas.TextWidth(string(sText[1 + cHexStartAscii + i]));
      if px + charWidth > x then
      begin
        // Check if we're not after end of data.
        if StartLine + i >= EndLine then
        begin
          CharSide := csBefore;
          Exit(EndLine);
        end;

        if px + charWidth div 2 > x then
          CharSide := csLeft
        else
          CharSide := csRight;

        Exit(StartLine + i);
      end;
      px := px + charWidth;
    end;

    CharSide := csBefore;
    Result := EndLine;
  end;

  function XYPos2AdrText: PtrInt;
  var
    i: Integer;
    px: Integer = 0;
    charWidth: Integer;
    len: Integer = 0;
    CharLenInBytes: Integer;
    s: String;
  begin
    i := StartLine;

    while i < EndLine do
    begin
      s := GetNextCharAsUtf8(i, CharLenInBytes);
      if CharLenInBytes = 0 then
        Break;

      // Check if the conversion to UTF-8 was successful.
      if Length(s) > 0 then
      begin
        if s = #9 then
        begin
          s := StringOfChar(' ', cTabSpaces - len mod cTabSpaces);
          len := len + (cTabSpaces - len mod cTabSpaces);
        end
        else
          Inc(len); // Assume there is one character after conversion
                    // (otherwise use Inc(len, UTF8Length(s))).

      if len <= FHPosition then
        begin
          i := i + CharLenInBytes;
          Continue;
        end;

        charWidth := Canvas.TextWidth(s);
        if px + charWidth > x then
        begin
          if px + charWidth div 2 > x then
            CharSide := csLeft
          else
            CharSide := csRight;

          Exit(i);
        end;

        px := px + charWidth;
      end;

      i := i + CharLenInBytes;
    end;

    CharSide := csBefore;
    Result := EndLine;
  end;

begin
  if FLineList.Count = 0 then
    Exit(-1);

  yIndex := y div FTextHeight;
  if yIndex >= FLineList.Count then
    yIndex := FLineList.Count - 1;
  if yIndex < 0 then
    yIndex := 0;

  // Get position of first character of the line.
  StartLine := FLineList.Items[yIndex];
  // Get position of last character of the line.
  EndLine   := GetEndOfLine(StartLine);

  if x = 0 then
  begin
    CharSide := csBefore;
    Exit(StartLine);
  end;

  case ViewerMode of
    vmBin:
      Result := XYPos2AdrBin;
    vmHex:
      Result := XYPos2AdrHex;
    vmText, vmWrap, vmBook:
      Result := XYPos2AdrText;
    else
      raise Exception.Create('Invalid viewer mode');
  end;
end;

procedure TViewerControl.SelectAll;
begin
  SelectText(FLowLimit, FHighLimit);
end;

procedure TViewerControl.SelectText(AStart, AEnd: PtrInt);
begin
  if AStart < FLowLimit then
    AStart := FLowLimit;
  if AEnd > FHighLimit then
    AEnd := FHighLimit;

  if AStart <= AEnd then
  begin
    FBlockBeg := AStart;
    FBlockEnd := AEnd;
    Invalidate;
  end;
end;

procedure TViewerControl.CopyToClipboard;
var
  sText, utf8Text: string;
begin
  if (FBlockEnd - FBlockBeg) <= 0 then
    Exit;
  if (FBlockEnd - FBlockBeg) > 1024 * 1024 then // Max 1 MB to clipboard
    Exit;
  SetString(sText, GetDataAdr + FBlockBeg, FBlockEnd - FBlockBeg);
  utf8Text := ConvertToUTF8(sText);
  {$IFDEF LCLGTK2}
  // Workaround for Lazarus bug #0021453. LCL adds trailing zero to clipboard in Clipboard.AsText.
  Clipboard.Clear;
  Clipboard.AddFormat(PredefinedClipboardFormat(pcfText), utf8Text[1], Length(utf8Text));
  {$ELSE}
  Clipboard.AsText := utf8Text;
  {$ENDIF}
end;

function TViewerControl.GetNextCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
var
  u1, u2: Word;
  InvalidCharLen: Integer;
begin
  Result := 0;
  case FEncoding of
    veUtf8, veUtf8bom:
      begin
        if iPosition < FHighLimit then
        begin
          CharLenInBytes := SafeUTF8NextCharLen(GetDataAdr + iPosition,
                                                FHighLimit - iPosition,
                                                InvalidCharLen);

          // It's enough to only return Ascii.
          if CharLenInBytes = 1 then
            Result := PByte(GetDataAdr)[iPosition];

          // Full conversion:
          // Result := UTF8CharacterToUnicode(PAnsiChar(GetDataAdr + iPosition), CharLenInBytes);
        end
        else
          CharLenInBytes := 0;
      end;

    veAnsi,
    veCp1250..veCp950,
    veIso88591,
    veIso88592,
    veKoi8:
      if iPosition < FHighLimit then
      begin
        Result := PByte(GetDataAdr)[iPosition];
        CharLenInBytes := 1;
      end
      else
        CharLenInBytes := 0;

    veUcs2be:
      if iPosition + SizeOf(Word) - 1 < FHighLimit then
      begin
        Result := BEtoN(PWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUcs2le:
      if iPosition + SizeOf(Word) - 1 < FHighLimit then
      begin
        Result := LEtoN(PWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUtf16be:
      if iPosition + SizeOf(Word) - 1 < FHighLimit then
      begin
        u1 := BEtoN(PWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := UTF16CharacterLength(@u1);
        if CharLenInBytes = 1 then
        begin
          Result := u1;
        end
        else if iPosition + SizeOf(Word) * CharLenInBytes - 1 < FHighLimit then
        begin
          u2 := BEtoN(PWord(GetDataAdr + iPosition)[1]);
          Result := utf16PairToUnicode(u1, u2);
        end;

        CharLenInBytes := CharLenInBytes * SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUtf16le:
      if iPosition + SizeOf(Word) - 1 < FHighLimit then
      begin
        u1 := LEtoN(PWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := UTF16CharacterLength(@u1);
        if CharLenInBytes = 1 then
        begin
          Result := u1;
        end
        else if iPosition + SizeOf(Word) * CharLenInBytes - 1 < FHighLimit then
        begin
          u2 := LEtoN(PWord(GetDataAdr + iPosition)[1]);
          Result := utf16PairToUnicode(u1, u2);
        end
        else
          CharLenInBytes := 0;

        CharLenInBytes := CharLenInBytes * SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUtf32be:
      if iPosition + SizeOf(LongWord) - 1 < FHighLimit then
      begin
        Result := BEtoN(PLongWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := SizeOf(LongWord);
      end
      else
        CharLenInBytes := 0;

    veUtf32le:
      if iPosition + SizeOf(LongWord) - 1 < FHighLimit then
      begin
        Result := LEtoN(PLongWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := SizeOf(LongWord);
      end
      else
        CharLenInBytes := 0;

    else
      raise Exception.Create('Unsupported viewer encoding');
  end;
end;

function TViewerControl.GetPrevCharAsAscii(const iPosition: PtrInt; out CharLenInBytes: Integer): Cardinal;
var
  u1, u2: Word;
  InvalidCharLen: Integer;
begin
  Result := 0;
  case FEncoding of
    veUtf8, veUtf8bom:
      begin
        if iPosition > FLowLimit then
        begin
          CharLenInBytes := SafeUTF8PrevCharLen(GetDataAdr + iPosition,
                                                iPosition - FLowLimit,
                                                InvalidCharLen);

          // It's enough to only return Ascii.
          if CharLenInBytes = 1 then
            Result := PByte(GetDataAdr)[iPosition - 1];

          // Full conversion:
          // Result := UTF8CharacterToUnicode(PAnsiChar(GetDataAdr + iPosition - CharLenInBytes), CharLenInBytes);
        end
        else
          CharLenInBytes := 0;
      end;

    veAnsi,
    veCp1250..veCp950,
    veIso88591,
    veIso88592,
    veKoi8:
      if iPosition > FLowLimit then
      begin
        Result := PByte(GetDataAdr + iPosition)[-1];
        CharLenInBytes := 1;
      end
      else
        CharLenInBytes := 0;

    veUcs2be:
      if iPosition >= FLowLimit + SizeOf(Word) then
      begin
        Result := BEtoN(PWord(GetDataAdr + iPosition)[-1]);
        CharLenInBytes := SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUcs2le:
      if iPosition >= FLowLimit + SizeOf(Word) then
      begin
        Result := LEtoN(PWord(GetDataAdr + iPosition)[-1]);
        CharLenInBytes := SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUtf16be:
      if iPosition >= FLowLimit + SizeOf(Word) then
      begin
        u1 := BEtoN(PWord(GetDataAdr + iPosition)[-1]);
        CharLenInBytes := UTF16CharacterLength(@u1);
        if CharLenInBytes = 1 then
        begin
          Result := u1;
        end
        else if iPosition >= FLowLimit + SizeOf(Word) * CharLenInBytes then
        begin
          u2 := BEtoN(PWord(GetDataAdr + iPosition)[-2]);
          // u2 is the first, u1 is the second value of the pair
          Result := utf16PairToUnicode(u2, u1);
        end;

        CharLenInBytes := CharLenInBytes * SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUtf16le:
      if iPosition >= FLowLimit + SizeOf(Word) then
      begin
        u1 := LEtoN(PWord(GetDataAdr + iPosition)[-1]);
        CharLenInBytes := UTF16CharacterLength(@u1);
        if CharLenInBytes = 1 then
        begin
          Result := u1;
        end
        else if iPosition >= FLowLimit + SizeOf(Word) * CharLenInBytes then
        begin
          u2 := LEtoN(PWord(GetDataAdr + iPosition)[-2]);
          // u2 is the first, u1 is the second value of the pair
          Result := utf16PairToUnicode(u2, u1);
        end;

        CharLenInBytes := CharLenInBytes * SizeOf(Word);
      end
      else
        CharLenInBytes := 0;

    veUtf32be:
      if iPosition >= FLowLimit + SizeOf(LongWord) then
      begin
        Result := BEtoN(PLongWord(GetDataAdr + iPosition)[-1]);
        CharLenInBytes := SizeOf(LongWord);
      end
      else
        CharLenInBytes := 0;

    veUtf32le:
      if iPosition >= FLowLimit + SizeOf(LongWord) then
      begin
        Result := LEtoN(PLongWord(GetDataAdr + iPosition)[-1]);
        CharLenInBytes := SizeOf(LongWord);
      end
      else
        CharLenInBytes := 0;

    else
      raise Exception.Create('Unsupported viewer encoding');
  end;
end;

function TViewerControl.GetNextCharAsUtf8(const iPosition: PtrInt; out CharLenInBytes: Integer): String;
var
  u1: Word;
  s: string;
  InvalidCharLen: Integer;
begin
  Result := '';
  case FEncoding of
    veUtf8, veUtf8bom:
      CharLenInBytes := SafeUTF8NextCharLen(GetDataAdr + iPosition,
                                            FHighLimit - iPosition,
                                            InvalidCharLen);
    veAnsi,
    veCp1250..veCp950,
    veIso88591,
    veIso88592,
    veKoi8:
      CharLenInBytes := 1;
    veUcs2be, veUcs2le:
      CharLenInBytes := 2;
    veUtf16be:
      if iPosition + SizeOf(Word) - 1 < FHighLimit then
      begin
        u1 := BEtoN(PWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := UTF16CharacterLength(@u1) * SizeOf(Word);
      end
      else
        CharLenInBytes := 0;
    veUtf16le:
      if iPosition + SizeOf(Word) - 1 < FHighLimit then
      begin
        u1 := LEtoN(PWord(GetDataAdr + iPosition)[0]);
        CharLenInBytes := UTF16CharacterLength(@u1) * SizeOf(Word);
      end
      else
        CharLenInBytes := 0;
    veUtf32be, veUtf32le:
      CharLenInBytes := 4;
    else
      raise Exception.Create('Unsupported viewer encoding');
  end;

  if (CharLenInBytes > 0) and (iPosition + CharLenInBytes - 1 < FHighLimit) then
  begin
    SetString(s, GetDataAdr + iPosition, CharLenInBytes);
    Result := ConvertToUTF8(s);
  end
  else
    Result := '';
end;

function TViewerControl.ConvertToUTF8(const sText: AnsiString): String;
begin
  if FEncoding = veAutoDetect then
    FEncoding := DetectEncoding;  // Force detect encoding.

  case FEncoding of
    veAutoDetect: ;
    veUtf8, veUtf8bom:
      Result := Utf8ReplaceBroken(sText);
    veUtf16be:
      Result := Utf16BEToUtf8(sText);
    veUtf16le:
      Result := Utf16LEToUtf8(sText);
    veUtf32be:
      Result := Utf32BEToUtf8(sText);
    veUtf32le:
      Result := Utf32LEToUtf8(sText);
    else
      Result := LConvEncoding.ConvertEncoding(sText,
                    ViewerEncodingsNames[FEncoding], EncodingUTF8);
  end;
end;

function TViewerControl.ConvertFromUTF8(const sText: String): AnsiString;
begin
  if FEncoding = veAutoDetect then
    FEncoding := DetectEncoding;  // Force detect encoding.

  case FEncoding of
    veAutoDetect: ;
    veUtf8, veUtf8bom:
      Result := sText;
    veUtf16be:
      Result := Utf8ToUtf16BE(sText);
    veUtf16le:
      Result := Utf8ToUtf16LE(sText);
    veUtf32be:
      Result := '';//Utf8ToUtf32BE(sText);
    veUtf32le:
      Result := '';//Utf8ToUtf32LE(sText);
    else
      Result := LConvEncoding.ConvertEncoding(sText,
                    EncodingUTF8, ViewerEncodingsNames[FEncoding]);
  end;
end;

function TViewerControl.IsVisible(const aPosition: PtrInt): Boolean;
var
  StartPos: PtrInt;
  CharLenInBytes: Integer;
begin
  if IsFileOpen and (FLineList.Count > 0) then
    begin
      FVisibleOffset:= 0;
      StartPos:= GetStartOfLine(aPosition);
      // Calculate horizontal offset in symbols
      while (StartPos < aPosition) do
      begin
        GetNextCharAsAscii(StartPos, CharLenInBytes);
        Inc(StartPos, CharLenInBytes);
        Inc(FVisibleOffset);
      end;

      Result := (aPosition >= FLineList.Items[0]) and
                (aPosition <= FLineList.Items[FLineList.Count - 1]) and
                (FVisibleOffset >= FHPosition) and
                (FVisibleOffset <= FHPosition + FTextWidth);
    end
  else
    Result := False;
end;

procedure TViewerControl.MakeVisible(const aPosition: PtrInt);
var
  Offset: Integer;
  LastLine: Boolean;
begin
  if not IsVisible(aPosition) then
  begin
    SetPosition(aPosition);
    Offset:= GetLinesTillEnd(aPosition, LastLine);
    if (Offset > 4) and (LastLine = False) then Scroll(-4);

    Update;

    if (FVisibleOffset < FHPosition) or
       (FVisibleOffset > FHPosition + FTextWidth) then
    begin
      SetHPosition(FVisibleOffset);
      HScroll(-1);
    end;
  end;
end;

procedure TViewerControl.ScrollBarVertScroll(Sender: TObject;
  ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
  FUpdateScrollBarPos := False;
  case ScrollCode of
    scLineUp:     Scroll(-1);
    scLineDown:   Scroll(1);
    scPageUp:     PageUp;
    scPageDown:   PageDown;
    scTop:        GoHome;
    scBottom:     GoEnd;
    scTrack,
    scPosition:
      begin
        // This check helps avoiding loops if changing ScrollPos below
        // triggers another scPosition message.
        if (ScrollCode = scTrack) or (ScrollPos <> FScrollBarPosition) then
        begin
          if ScrollPos = 0 then
            GoHome
          else if ScrollPos = 100 then
            GoEnd
          else
            Percent := ScrollPos;
        end;
      end;
    scEndScroll:
      begin
      end;
  end;

  ScrollPos := FScrollBarPosition;
  FUpdateScrollBarPos := True;
end;

procedure TViewerControl.ScrollBarHorzScroll(Sender: TObject;
  ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
  FUpdateScrollBarPos := False;
  case ScrollCode of
    scLineUp:     HScroll(-1);
    scLineDown:   HScroll(1);
    scPageUp:     HPageUp;
    scPageDown:   HPageDown;
    scTop:        HGoHome;
    scBottom:     HGoEnd;
    scTrack,
    scPosition:
      begin
        // This check helps avoiding loops if changing ScrollPos below
        // triggers another scPosition message.
        if (ScrollCode = scTrack) or (ScrollPos <> FHScrollBarPosition) then
        begin
          if ScrollPos = 0 then
            HGoHome
          else if ScrollPos = 100 then
            HGoEnd
            else
         HScroll((FHLowEnd - FTextWidth) * ScrollPos div 100 - FHPosition);
        end;
      end;
    scEndScroll:
      begin
      end;
  end;
  ScrollPos := FHScrollBarPosition;
  FUpdateScrollBarPos := True;
end;

procedure TViewerControl.UpdateScrollbars;
begin
  FScrollBarVert.LargeChange := GetClientHeightInLines - 1;
  case ViewerMode of
    vmBin, vmHex:
    begin
      //FScrollBarVert.PageSize :=
      //  ((FHighLimit div cHexWidth - GetClientHeightInLines) div 100);
    end
    else
      FScrollBarVert.PageSize := 1;
  end;
  FScrollBarHorz.Visible:= (FViewerMode = vmText);
end;

procedure TViewerControl.ViewerResize(Sender: TObject);
begin
  UpdateScrollbars;
  // Force recalculating position.
  SetPosition(FPosition);
  SetHPosition(FHPosition);
end;

procedure TViewerControl.ReReadFile;
begin
  FBlockBeg := 0;
  FBlockEnd := 0;

  FBOMLength := GetBomLength;
  UpdateLimits;

  UpdateScrollbars;
  Invalidate;
end;

function TViewerControl.IsFileOpen: Boolean;
begin
  Result := Assigned(FMappedFile);
end;

function TViewerControl.DetectEncoding: TViewerEncoding;
var
  DetectStringLength: Integer = 2048; // take first 2kB of the file to detect encoding
  DetectString: String;
  DetectedEncodingName: String;
  Enc: TViewerEncoding;
begin
  if IsFileOpen then
  begin
    // Default to Ansi in case encoding cannot be detected or is unsupported.
    Result := veAnsi;

    if FFileSize < DetectStringLength then
      DetectStringLength := FFileSize;

    SetString(DetectString, PAnsiChar(FMappedFile), DetectStringLength);

    if Assigned(FOnGuessEncoding) then
      DetectedEncodingName := FOnGuessEncoding(DetectString)
    else
      DetectedEncodingName := LConvEncoding.GuessEncoding(DetectString);

    if DetectedEncodingName <> '' then
    begin
      DetectedEncodingName := NormalizeEncoding(DetectedEncodingName);

      // Map UCS-2 to UTF-16.
      if DetectedEncodingName = 'ucs2le' then
        DetectedEncodingName := 'utf16le'
      else if DetectedEncodingName = 'ucs2be' then
        DetectedEncodingName := 'utf16be';

      for Enc := Low(TViewerEncoding) to High(TViewerEncoding) do
      begin
        if NormalizeEncoding(ViewerEncodingsNames[Enc]) = DetectedEncodingName then
        begin
          Result := Enc;
          break;
        end;
      end;
    end;
  end
  else
    Result := veAutoDetect;
end;

procedure TViewerControl.GetSupportedEncodings(List: TStrings);
var
  Enc: TViewerEncoding;
begin
  for Enc := Low(TViewerEncoding) to High(TViewerEncoding) do
    List.Add(ViewerEncodingsNames[Enc]);
end;

function TViewerControl.GetBomLength: Integer;
begin
  Result := 0;

  case FEncoding of
    veUtf8, veUtf8bom:
      if (FFileSize >= 3) and
         (PByte(FMappedFile)[0] = $EF) and
         (PByte(FMappedFile)[1] = $BB) and
         (PByte(FMappedFile)[2] = $BF) then
      begin
        Result := 3;
      end;

    veUcs2be, veUtf16be:
      if (FFileSize >= 2) and
         (PByte(FMappedFile)[0] = $FE) and
         (PByte(FMappedFile)[1] = $FF) then
      begin
        Result := 2;
      end;

    veUcs2le, veUtf16le:
      if (FFileSize >= 2) and
         (PByte(FMappedFile)[0] = $FF) and
         (PByte(FMappedFile)[1] = $FE) then
      begin
        Result := 2;
      end;

    veUtf32be:
      if (FFileSize >= 4) and
         (PByte(FMappedFile)[0] = $00) and
         (PByte(FMappedFile)[1] = $00) and
         (PByte(FMappedFile)[2] = $FE) and
         (PByte(FMappedFile)[3] = $FF) then
      begin
        Result := 4;
      end;

    veUtf32le:
      if (FFileSize >= 4) and
         (PByte(FMappedFile)[0] = $00) and
         (PByte(FMappedFile)[1] = $00) and
         (PByte(FMappedFile)[2] = $FF) and
         (PByte(FMappedFile)[3] = $FE) then
      begin
        Result := 4;
      end;
  end;
end;

procedure TViewerControl.UpdateLimits;
begin
  if FEncoding = veAutoDetect then
    FEncoding := DetectEncoding;

  FBOMLength := GetBomLength;

  case FViewerMode of
    vmText, vmWrap, vmBook:
      begin
        FLowLimit  := 0;
        FHighLimit := FFileSize - FBOMLength;
      end;
    else
      begin
        FLowLimit  := 0;
        FHighLimit := FFileSize;
      end;
  end;
end;

procedure TViewerControl.UpdateSelection;

  procedure Check(var aPosition: PtrInt; Backwards: Boolean);
  var
    CharStart: Pointer;
  begin
    case FEncoding of
      veUtf8, veUtf8bom:
        begin
          if not Backwards then
          begin
            CharStart := SafeUTF8NextCharStart(GetDataAdr + aPosition,
                                               FHighLimit - aPosition);
            if Assigned(CharStart) then
              aPosition := CharStart - GetDataAdr
            else
              aPosition := 0;
          end
          else
          begin
            CharStart := SafeUTF8PrevCharEnd(GetDataAdr + aPosition,
                                             aPosition - FLowLimit);
            if Assigned(CharStart) then
              aPosition := CharStart - GetDataAdr
            else
              aPosition := 0;
          end;
        end;

      veAnsi,
      veCp1250..veCp950,
      veIso88591,
      veIso88592,
      veKoi8:
        ; // any position allowed

      veUcs2be, veUcs2le:
        aPosition := ((aPosition - FLowLimit) and not 1) + FLowLimit;
      veUtf16be, veUtf16le:
        // todo: check if not in the middle of utf-16 character
        aPosition := ((aPosition - FLowLimit) and not 1) + FLowLimit;
      veUtf32be, veUtf32le:
        aPosition := ((aPosition - FLowLimit) and not 3) + FLowLimit;

      else
        raise Exception.Create('Unsupported viewer encoding');
    end;
  end;

begin
  if (FBlockBeg < FLowLimit) or (FBlockBeg >= FHighLimit) or
     (FBlockEnd < FLowLimit) or (FBlockEnd >= FHighLimit) then
  begin
    FBlockBeg := FLowLimit;
    FBlockEnd := FLowLimit;
  end
  else
  begin
    case FViewerMode of
      vmText, vmWrap, vmBook:
        begin
          Check(FBlockBeg, False);
          Check(FBlockEnd, True);

          if (FBlockBeg < FLowLimit) or (FBlockBeg >= FHighLimit) or
             (FBlockEnd < FLowLimit) or (FBlockEnd >= FHighLimit) or
             (FBlockEnd < FBlockBeg) then
          begin
            FBlockBeg := FLowLimit;
            FBlockEnd := FLowLimit;
          end;
        end;
      // In non-text modes any selection is valid.
    end;
  end;
end;

function TViewerControl.FindUtf8Text(iStartPos: PtrInt; const sSearchText: String;
                                     bCaseSensitive: Boolean; bSearchBackwards: Boolean): PtrInt;
var
  SearchTextLength: Integer;
  sSearchChars: array of String;
  pCurrentAddr, pEndAddr: PtrInt;
  i, charLen: Integer;

  function sPos2(pAdr: PtrInt):Boolean;
  var
    curChr:String;
    i, charLen: Integer;
  begin
    Result := False;
    for i := 0 to SearchTextLength-1 do
    begin
      curChr:=GetNextCharAsUtf8(pAdr,charLen);
      case bCaseSensitive of
       False: if UTF8UpperCase(curChr) <> UTF8UpperCase(sSearchChars[i]) then Exit;
       True : if curChr <> sSearchChars[i] then Exit;
      end;
      if charLen>0 then
        pAdr:=pAdr+charLen
      else
        Inc(pAdr);
    end;
    Result:=True;
  end;

begin
  Result := PtrInt(-1);
  SearchTextLength := UTF8Length(sSearchText);
  if (SearchTextLength <= 0) then
    Exit;

  setLength(sSearchChars,SearchTextLength);
  for i:=1 to SearchTextLength do
    sSearchChars[i-1]:=UTF8Copy(sSearchText,i,1);


  pCurrentAddr := iStartPos;
  pEndAddr := FHighLimit - Length(ConvertFromUTF8(sSearchText));

  if bSearchBackwards and (pCurrentAddr > pEndAddr) then
    // Move to the first possible position for searching backwards.
    pCurrentAddr := pEndAddr;

  if (pEndAddr < 0) or (pCurrentAddr < 0) or (pCurrentAddr > pEndAddr) then
    Exit;

  while True do
  begin
    if (pCurrentAddr > pEndAddr) or (pCurrentAddr < 0) then
      Exit;

    if sPos2(pCurrentAddr) then
    begin
      Result := pCurrentAddr;
      Exit;
    end;

    case bSearchBackwards of
      False:
      begin
        GetNextCharAsUtf8(pCurrentAddr,charLen);
        if charLen>0 then
          pCurrentAddr:=pCurrentAddr+charLen
        else
          Inc(pCurrentAddr);
       end;
      True : Dec(pCurrentAddr);
    end;
  end;
end;

procedure TViewerControl.ResetEncoding;
begin
  FEncoding:= veAutoDetect;
end;

procedure Register;
begin
  RegisterComponents('SeksiCmd', [TViewerControl]);
end;

end.