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
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.ComponentModel;
using System.IO;
using System.Windows.Xps.Packaging;
using System.Printing;
using System.Windows.Markup;
enum PDFType_t
{
PDFX,
PDFA
}
enum AppBar_t
{
TEXT_SEARCH,
STANDARD
}
enum NotifyType_t
{
MESS_STATUS,
MESS_ERROR
};
enum RenderingStatus_t
{
REN_AVAILABLE,
REN_THUMBS,
REN_UPDATE_THUMB_CANVAS,
REN_PAGE /* Used to ignore value when source based setting */
};
public enum status_t
{
S_ISOK,
E_FAILURE,
E_OUTOFMEM,
E_NEEDPASSWORD
};
enum view_t
{
VIEW_WEB,
VIEW_CONTENT,
VIEW_PAGE,
VIEW_PASSWORD,
VIEW_TEXTSEARCH
};
public enum Page_Content_t
{
FULL_RESOLUTION = 0,
THUMBNAIL,
DUMMY,
OLD_RESOLUTION,
NOTSET
};
/* Put all the PDF types first to make the switch statment shorter
Save_Type_t.PDF is the test */
public enum Save_Type_t
{
PDF13,
PDFA1_RGB,
PDFA1_CMYK,
PDFA2_RGB,
PDFA2_CMYK,
PDFX3_GRAY,
PDFX3_CMYK,
PDF,
PCLXL,
XPS,
SVG,
PCLBitmap,
PNG,
PWG,
PNM,
TEXT
}
public enum Extract_Type_t
{
PDF,
EPS,
PS,
SVG
}
public struct spatial_info_t
{
public Point size;
public double scale_factor;
};
/* C# has no defines.... */
static class Constants
{
public const int LOOK_AHEAD = 1; /* A +/- count on the pages to pre-render */
public const int THUMB_PREADD = 10;
public const double MIN_SCALE = 0.5;
public const double SCALE_THUMB = 0.05;
public const int BLANK_WIDTH = 17;
public const int BLANK_HEIGHT = 22;
public const double ZOOM_STEP = 0.25;
public const int ZOOM_MAX = 4;
public const double ZOOM_MIN = 0.25;
public const int KEY_PLUS = 0xbb;
public const int KEY_MINUS = 0xbd;
public const int ZOOM_IN = 0;
public const int ZOOM_OUT = 1;
public const double SCREEN_SCALE = 1;
public const int HEADER_SIZE = 54;
public const int SEARCH_FORWARD = 1;
public const int SEARCH_BACKWARD = -1;
public const int TEXT_NOT_FOUND = -1;
public const int DEFAULT_GS_RES = 300;
}
public static class DocumentTypes
{
public const string PDF = "Portable Document Format";
public const string PS = "PostScript";
public const string XPS = "XPS";
public const string EPS = "Encapsulated PostScript";
public const string CBZ = "Comic Book Archive";
public const string UNKNOWN = "Unknown";
}
namespace gsview
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public struct thumb_t
{
public int page_num;
public Byte[] bitmap;
public Point size;
}
public struct searchResults_t
{
public String needle;
public bool done;
public int page_found;
public List<Rect> rectangles;
public int num_rects;
}
public partial class MainWindow : Window
{
mudocument mu_doc;
public Pages m_docPages;
List<DocPage> m_thumbnails;
List<List<RectList>> m_page_link_list = null;
int m_contents_size;
int m_content_item;
List<RectList> m_text_list = null;
private int m_rectlist_page;
private List<ContentEntry> m_content_list;
private bool m_file_open;
private int m_currpage;
private int m_searchpage;
private int m_num_pages;
private bool m_init_done;
private bool m_links_on;
private int m_search_rect_count;
String m_textcolor = "#402572AC";
String m_linkcolor = "#40AC7225";
RenderingStatus_t m_ren_status;
private bool m_insearch;
private bool m_search_active;
private bool m_handlingzoom;
private bool m_have_thumbs;
private bool m_have_contents;
double m_doczoom;
ghostsharp m_ghostscript;
String m_currfile;
private gsprint m_ghostprint = null;
bool m_isXPS;
gsOutput m_gsoutput;
Convert m_convertwin;
Password m_password = null;
bool m_zoomhandled;
BackgroundWorker m_thumbworker = null;
BackgroundWorker m_textsearch = null;
BackgroundWorker m_linksearch = null;
String m_document_type;
Info m_infowindow;
OutputIntent m_outputintents;
Selection m_selection;
private Point startPoint;
private Rectangle rect;
String m_prevsearch = null;
int m_numpagesvisible;
bool m_clipboardset;
public MainWindow()
{
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);
m_file_open = false;
status_t result = CleanUp();
/* Allocations and set up */
try
{
m_docPages = new Pages();
m_thumbnails = new List<DocPage>();
m_ghostscript = new ghostsharp();
m_ghostscript.gsUpdateMain += new ghostsharp.gsCallBackMain(gsProgress);
m_gsoutput = new gsOutput();
m_gsoutput.Activate();
m_outputintents = new OutputIntent();
m_outputintents.Activate();
m_ghostscript.gsIOUpdateMain += new ghostsharp.gsIOCallBackMain(gsIO);
m_convertwin = null;
m_selection = null;
xaml_ZoomSlider.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler(ZoomReleased), true);
mxaml_BackPage.Opacity = 0.5;
mxaml_Contents.Opacity = 0.5;
mxaml_currPage.Opacity = 0.5;
mxaml_ForwardPage.Opacity = 0.5;
mxaml_Links.Opacity = 0.5;
mxaml_Print.Opacity = 0.5;
mxaml_SavePDF.Opacity = 0.5;
mxaml_Search.Opacity = 0.5;
mxaml_Thumbs.Opacity = 0.5;
mxaml_TotalPages.Opacity = 0.5;
mxaml_zoomIn.Opacity = 0.5;
mxaml_zoomOut.Opacity = 0.5;
mxaml_Zoomsize.Opacity = 0.5;
mxaml_Zoomsize.IsEnabled = false;
xaml_ZoomSlider.Opacity = 0.5;
xaml_ZoomSlider.IsEnabled = false;
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed at initialization\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
}
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (m_selection != null && m_selection.IsActive)
m_selection.Close();
m_gsoutput.RealWindowClosing();
m_outputintents.RealWindowClosing();
}
void EnabletoPDF()
{
xaml_savepdf13.IsEnabled = true;
xaml_savepdfa.IsEnabled = true;
xaml_savepdfx3_cmyk.IsEnabled = true;
xaml_savepdfx3_gray.IsEnabled = true;
xaml_savepclxl.IsEnabled = true;
}
void DisabletoPDF()
{
xaml_savepdf13.IsEnabled = false;
xaml_savepdfa.IsEnabled = false;
xaml_savepdfx3_cmyk.IsEnabled = false;
xaml_savepdfx3_gray.IsEnabled = false;
xaml_savepclxl.IsEnabled = false;
}
private status_t CleanUp()
{
m_init_done = false;
/* Collapse this stuff since it is going to be released */
xaml_ThumbGrid.Visibility = System.Windows.Visibility.Collapsed;
xaml_ContentGrid.Visibility = System.Windows.Visibility.Collapsed;
/* Clear out everything */
if (m_docPages != null && m_docPages.Count > 0)
m_docPages.Clear();
if (m_thumbnails != null && m_thumbnails.Count > 0)
m_thumbnails.Clear();
if (m_page_link_list != null && m_page_link_list.Count > 0)
{
m_page_link_list.Clear();
m_page_link_list = null;
}
if (m_text_list != null && m_text_list.Count > 0)
{
m_text_list.Clear();
m_text_list = null;
}
if (mu_doc != null)
mu_doc.CleanUp();
try
{
mu_doc = new mudocument();
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed during clean up\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
status_t result = mu_doc.Initialize();
if (result != status_t.S_ISOK)
{
Console.WriteLine("Library allocation failed during clean up\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Library allocation failed!");
return result;
}
m_have_thumbs = false;
m_file_open = false;
m_insearch = false;
m_search_active = false;
m_num_pages = -1;
m_search_rect_count = 0;
m_links_on = false;
m_rectlist_page = -1;
m_doczoom = 1.0;
m_isXPS = false;
m_zoomhandled = false;
xaml_CancelThumb.IsEnabled = true;
m_currpage = 0;
m_document_type = DocumentTypes.UNKNOWN;
EnabletoPDF();
m_numpagesvisible = 3;
m_clipboardset = false;
return result;
}
private void ShowMessage(NotifyType_t type, String Message)
{
if (type == NotifyType_t.MESS_ERROR)
{
System.Windows.Forms.MessageBox.Show(Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
System.Windows.Forms.MessageBox.Show(Message, "Notice",
MessageBoxButtons.OK);
}
}
private void CloseDoc()
{
CleanUp();
}
/* Set the page with the new raster information */
private void UpdatePage(int page_num, Byte[] bitmap, Point ras_size,
Page_Content_t content, double zoom_in)
{
DocPage doc_page = this.m_docPages[page_num];
doc_page.Width = (int)ras_size.X;
doc_page.Height = (int)ras_size.Y;
doc_page.Content = content;
doc_page.Zoom = zoom_in;
int stride = doc_page.Width * 4;
doc_page.BitMap = BitmapSource.Create(doc_page.Width, doc_page.Height, 72, 72, PixelFormats.Pbgra32, BitmapPalettes.Halftone256, bitmap, stride);
doc_page.PageNum = page_num;
if (content == Page_Content_t.THUMBNAIL)
{
doc_page.Width = (int)(ras_size.X / Constants.SCALE_THUMB);
doc_page.Height = (int)(ras_size.Y / Constants.SCALE_THUMB);
}
}
private void OpenFile(object sender, RoutedEventArgs e)
{
if (m_password != null && m_password.IsActive)
m_password.Close();
if (m_infowindow != null && m_infowindow.IsActive)
m_infowindow.Close();
/* Check if gs is currently busy. If it is then don't allow a new
* file to be opened. They can cancel gs with the cancel button if
* they want */
if (m_ghostscript.GetStatus() != gsStatus.GS_READY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy. Cancel to open new file.");
return;
}
if (m_ghostprint != null && m_ghostprint.IsBusy())
{
ShowMessage(NotifyType_t.MESS_STATUS, "Let printing complete");
return;
}
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Document Files(*.ps;*.eps;*.pdf;*.xps;*.cbz)|*.ps;*.eps;*.pdf;*.xps;*.cbz|All files (*.*)|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (m_file_open)
{
CloseDoc();
}
/* If we have a ps or eps file then launch the distiller first
* and then we will get a temp pdf file which will be opened by
* mupdf */
string extension = System.IO.Path.GetExtension(dlg.FileName);
/* We are doing this based on the extension but like should do
* it based upon the content */
switch(extension.ToUpper())
{
case ".PS":
m_document_type = DocumentTypes.PS;
break;
case ".EPS":
m_document_type = DocumentTypes.EPS;
break;
case ".XPS":
m_document_type = DocumentTypes.XPS;
break;
case ".PDF":
m_document_type = DocumentTypes.PDF;
break;
case ".CBZ":
m_document_type = DocumentTypes.CBZ;
break;
default:
m_document_type = DocumentTypes.UNKNOWN;
break;
}
if (extension.ToUpper() == ".PS" || extension.ToUpper() == ".EPS")
{
xaml_DistillProgress.Value = 0;
if (m_ghostscript.DistillPS(dlg.FileName, Constants.DEFAULT_GS_RES) == gsStatus.GS_BUSY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS currently busy");
return;
}
xaml_DistillName.Text = "Distilling";
xaml_CancelDistill.Visibility = System.Windows.Visibility.Visible;
xaml_DistillName.FontWeight = FontWeights.Bold;
xaml_DistillGrid.Visibility = System.Windows.Visibility.Visible;
return;
}
/* Set if this is already xps for printing */
if (extension.ToUpper() == ".XPS")
{
DisabletoPDF();
m_isXPS = true;
}
OpenFile2(dlg.FileName);
}
}
private void OpenFile2(String File)
{
m_currfile = File;
status_t code = mu_doc.OpenFile(m_currfile);
if (code == status_t.S_ISOK)
{
/* Check if we need a password */
if (mu_doc.RequiresPassword())
GetPassword();
else
StartViewer();
}
else
{
m_currfile = null;
ShowMessage(NotifyType_t.MESS_ERROR, "Failed to open file!");
}
}
private void StartViewer()
{
InitialRender();
RenderThumbs();
m_file_open = true;
mxaml_BackPage.Opacity = 1;
mxaml_Contents.Opacity = 1;
mxaml_currPage.Opacity = 1;
mxaml_ForwardPage.Opacity = 1;
mxaml_Links.Opacity = 1;
mxaml_Print.Opacity = 1;
mxaml_SavePDF.Opacity = 1;
mxaml_Search.Opacity = 1;
mxaml_Thumbs.Opacity = 1;
mxaml_TotalPages.Opacity = 1;
mxaml_zoomIn.Opacity = 1;
mxaml_zoomOut.Opacity = 1;
mxaml_Zoomsize.Opacity = 1;
mxaml_Zoomsize.IsEnabled = true;
mxaml_TotalPages.Text = "/ " + m_num_pages.ToString();
mxaml_currPage.Text = "1";
xaml_ZoomSlider.Opacity = 1.0;
xaml_ZoomSlider.IsEnabled = true;
}
private status_t ComputePageSize(int page_num, double scale_factor,
out Point render_size)
{
Point renpageSize = new Point();
status_t code = (status_t)mu_doc.GetPageSize(page_num, out render_size);
if (code != status_t.S_ISOK)
return code;
renpageSize.X = (render_size.X * scale_factor);
renpageSize.Y = (render_size.Y * scale_factor);
render_size = renpageSize;
return status_t.S_ISOK;
}
private DocPage InitDocPage()
{
DocPage doc_page = new DocPage();
doc_page.BitMap = null;
doc_page.Height = Constants.BLANK_HEIGHT;
doc_page.Width = Constants.BLANK_WIDTH;
doc_page.NativeHeight = Constants.BLANK_HEIGHT;
doc_page.NativeWidth = Constants.BLANK_WIDTH;
doc_page.Content = Page_Content_t.DUMMY;
doc_page.TextBox = null;
doc_page.LinkBox = null;
return doc_page;
}
async private void InitialRender()
{
m_num_pages = mu_doc.GetPageCount();
m_currpage = 0;
for (int k = 0; k < m_num_pages; k++)
{
m_docPages.Add(InitDocPage());
m_docPages[k].PageNum = k;
m_thumbnails.Add(InitDocPage());
}
/* Do the first few full res pages */
for (int k = 0; k < Constants.LOOK_AHEAD + 2; k++)
{
if (m_num_pages > k)
{
Point ras_size;
double scale_factor = 1.0;
if (ComputePageSize(k, scale_factor, out ras_size) == status_t.S_ISOK)
{
try
{
Byte[] bitmap = new byte[(int)ras_size.X * (int)ras_size.Y * 4];
Task<int> ren_task =
new Task<int>(() => mu_doc.RenderPage(k, bitmap, (int)ras_size.X, (int)ras_size.Y, scale_factor, false, true));
ren_task.Start();
await ren_task.ContinueWith((antecedent) =>
{
status_t code = (status_t)ren_task.Result;
if (code == status_t.S_ISOK)
UpdatePage(k, bitmap, ras_size, Page_Content_t.FULL_RESOLUTION, 1.0);
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed page " + k + "\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
}
}
}
m_init_done = true;
xaml_PageList.ItemsSource = m_docPages;
}
private void OnBackPageClick(object sender, RoutedEventArgs e)
{
if (m_currpage == 0 || !m_init_done) return;
RenderRange(m_currpage - 1, true);
}
private void OnForwardPageClick(object sender, RoutedEventArgs e)
{
if (m_currpage == m_num_pages - 1 || !m_init_done) return;
RenderRange(m_currpage + 1, true);
}
private void PageEnterClicked(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Return)
{
e.Handled = true;
var desired_page = mxaml_currPage.Text;
try
{
int page = System.Convert.ToInt32(desired_page);
if (page > 0 && page < (m_num_pages + 1))
RenderRange(page - 1, true);
}
catch (FormatException e1)
{
Console.WriteLine("String is not a sequence of digits.");
}
catch (OverflowException e2)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
}
}
private void CancelLoadClick(object sender, RoutedEventArgs e)
{
/* Cancel during thumbnail loading. Deactivate the button
* and cancel the thumbnail rendering */
if (m_thumbworker != null)
m_thumbworker.CancelAsync();
xaml_CancelThumb.IsEnabled = false;
}
private void ToggleThumbs(object sender, RoutedEventArgs e)
{
if (m_have_thumbs)
{
if (xaml_ThumbGrid.Visibility == System.Windows.Visibility.Collapsed)
{
xaml_ThumbGrid.Visibility = System.Windows.Visibility.Visible;
}
else
{
xaml_ThumbGrid.Visibility = System.Windows.Visibility.Collapsed;
}
}
}
private void ToggleContents(object sender, RoutedEventArgs e)
{
if (xaml_ContentGrid.Visibility == System.Windows.Visibility.Visible)
{
xaml_ContentGrid.Visibility = System.Windows.Visibility.Collapsed;
return;
}
if (m_num_pages < 0)
return;
if (xaml_ContentList.Items.IsEmpty)
{
int size_content = mu_doc.ComputeContents();
if (size_content == 0)
return;
xaml_ContentList.ItemsSource = mu_doc.contents;
}
xaml_ContentGrid.Visibility = System.Windows.Visibility.Visible;
}
private void ThumbSelected(object sender, MouseButtonEventArgs e)
{
var item = ((FrameworkElement)e.OriginalSource).DataContext as DocPage;
if (item != null)
{
if (item.PageNum < 0)
return;
RenderRange(item.PageNum, true);
}
}
private void ContentSelected(object sender, MouseButtonEventArgs e)
{
var item = ((FrameworkElement)e.OriginalSource).DataContext as ContentItem;
if (item != null && item.Page < m_num_pages)
{
int page = m_docPages[item.Page].PageNum;
if (page >= 0 && page < m_num_pages)
RenderRange(page, true);
}
}
/* We need to avoid rendering due to size changes */
private void ListViewScrollChanged(object sender, ScrollChangedEventArgs e)
{
var lv = (System.Windows.Controls.ListView)sender;
foreach (var lvi in lv.Items)
{
var container = lv.ItemContainerGenerator.ContainerFromItem(lvi) as ListBoxItem;
if (container != null && Visible(container, lv))
{
var found = container.Content;
if (found != null)
{
var Item = (DocPage)found;
RenderRange(Item.PageNum, false);
}
return;
}
}
}
/* Render +/- the look ahead from where we are if blank page is present */
async private void RenderRange(int new_page, bool scrollto)
{
int range = (int) Math.Ceiling(((double) m_numpagesvisible - 1.0) / 2.0);
for (int k = new_page - range; k <= new_page + range + 1; k++)
{
if (k >= 0 && k < m_num_pages)
{
/* Check if page is already rendered */
var doc = m_docPages[k];
if (doc.Content != Page_Content_t.FULL_RESOLUTION ||
doc.Zoom != m_doczoom)
{
Point ras_size;
double scale_factor = m_doczoom;
if (ComputePageSize(k, scale_factor, out ras_size) == status_t.S_ISOK)
{
try
{
Byte[] bitmap = new byte[(int)ras_size.X * (int)ras_size.Y * 4];
Task<int> ren_task =
new Task<int>(() => mu_doc.RenderPage(k, bitmap, (int)ras_size.X, (int)ras_size.Y, scale_factor, false, true));
ren_task.Start();
await ren_task.ContinueWith((antecedent) =>
{
status_t code = (status_t)ren_task.Result;
if (code == status_t.S_ISOK)
{
if (m_docPages[k].TextBox != null)
ScaleTextBox(k);
if (m_links_on && m_page_link_list != null)
{
m_docPages[k].LinkBox = m_page_link_list[k];
if (m_docPages[k].LinkBox != null)
ScaleLinkBox(k);
}
else
{
m_docPages[k].LinkBox = null;
}
UpdatePage(k, bitmap, ras_size, Page_Content_t.FULL_RESOLUTION, m_doczoom);
m_docPages[k].PageRefresh();
if (k == new_page && scrollto)
xaml_PageList.ScrollIntoView(m_docPages[k]);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed page " + k + "\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
}
}
else
{
/* We did not have to render the page but we may need to
* scroll to it */
if (k == new_page && scrollto)
xaml_PageList.ScrollIntoView(m_docPages[k]);
}
}
}
/* Release old range and set new page */
ReleasePages(m_currpage, new_page, range);
m_currpage = new_page;
mxaml_currPage.Text = (m_currpage + 1).ToString();
}
private bool Visible(FrameworkElement elem, FrameworkElement cont)
{
if (!elem.IsVisible)
return false;
Rect rect = new Rect(0.0, 0.0, cont.ActualWidth, cont.ActualHeight);
Rect bounds = elem.TransformToAncestor(cont).TransformBounds(new Rect(0.0, 0.0, elem.ActualWidth, elem.ActualHeight));
Rect bounds2 = new Rect(new Point(bounds.TopLeft.X, bounds.TopLeft.Y), new Point(bounds.BottomRight.X, bounds.BottomRight.Y - 5));
return rect.Contains(bounds2.TopLeft) || rect.Contains(bounds2.BottomRight);
}
private void ReleasePages(int old_page, int new_page, int range)
{
if (old_page == new_page) return;
/* To keep from having memory issue reset the page back to
the thumb if we are done rendering the thumbnails */
for (int k = old_page - range; k <= old_page + range; k++)
{
if (k < new_page - range || k > new_page + range)
{
if (k >= 0 && k < m_num_pages)
{
SetThumb(k);
}
}
}
}
/* Return this page from a full res image to the thumb image */
private void SetThumb(int page_num)
{
/* See what is there now */
var doc_page = m_docPages[page_num];
if (doc_page.Content == Page_Content_t.THUMBNAIL &&
doc_page.Zoom == m_doczoom) return;
if (m_thumbnails.Count > page_num)
{
doc_page.Content = Page_Content_t.THUMBNAIL;
doc_page.Zoom = m_doczoom;
doc_page.BitMap = m_thumbnails[page_num].BitMap;
doc_page.Width = (int)(m_doczoom * doc_page.BitMap.PixelWidth / Constants.SCALE_THUMB);
doc_page.Height = (int)(m_doczoom * doc_page.BitMap.PixelHeight / Constants.SCALE_THUMB);
doc_page.PageNum = page_num;
doc_page.LinkBox = null;
doc_page.TextBox = null;
/* No need to refresh unless it just occurs during other stuff
* we just want to make sure we can release the bitmaps */
//doc_page.PageRefresh();
}
}
private void gsIO(object gsObject, String mess, int len)
{
m_gsoutput.Update(mess, len);
}
private void gsProgress(object gsObject, gsEventArgs asyncInformation)
{
if (asyncInformation.Completed)
{
xaml_DistillProgress.Value = 100;
xaml_DistillGrid.Visibility = System.Windows.Visibility.Collapsed;
if (asyncInformation.Params.result == GS_Result_t.gsFAILED)
{
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:
ShowMessage(NotifyType_t.MESS_STATUS, "Ghostscript failed to create XPS");
break;
case GS_Task_t.PS_DISTILL:
ShowMessage(NotifyType_t.MESS_STATUS, "Ghostscript failed to distill PS");
break;
case GS_Task_t.SAVE_RESULT:
ShowMessage(NotifyType_t.MESS_STATUS, "Ghostscript failed to convert document");
break;
}
return;
}
GSResult(asyncInformation.Params);
}
else
{
this.xaml_DistillProgress.Value = asyncInformation.Progress;
}
}
/* GS Result*/
public void GSResult(gsParams_t gs_result)
{
if (gs_result.result == GS_Result_t.gsCANCELLED)
{
xaml_DistillGrid.Visibility = System.Windows.Visibility.Collapsed;
return;
}
if (gs_result.result == GS_Result_t.gsFAILED)
{
xaml_DistillGrid.Visibility = System.Windows.Visibility.Collapsed;
ShowMessage(NotifyType_t.MESS_STATUS, "GS Failed Conversion");
return;
}
switch (gs_result.task)
{
case GS_Task_t.CREATE_XPS:
xaml_DistillGrid.Visibility = System.Windows.Visibility.Collapsed;
PrintXPS(gs_result.outputfile);
break;
case GS_Task_t.PS_DISTILL:
xaml_DistillGrid.Visibility = System.Windows.Visibility.Collapsed;
OpenFile2(gs_result.outputfile);
break;
case GS_Task_t.SAVE_RESULT:
ShowMessage(NotifyType_t.MESS_STATUS, "GS Completed Conversion");
break;
}
}
/* Printing is achieved using xpswrite device in ghostscript and
* pushing that file through the XPS print queue */
private void Print(object sender, RoutedEventArgs e)
{
if (!m_file_open)
return;
/* If file is already xps then gs need not do this */
if (!m_isXPS)
{
xaml_DistillProgress.Value = 0;
if (m_ghostscript.CreateXPS(m_currfile, Constants.DEFAULT_GS_RES, m_num_pages) == gsStatus.GS_BUSY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS currently busy");
return;
}
else
{
/* Right now this is not possible to cancel due to the way
* that gs is run for xpswrite from pdf */
xaml_CancelDistill.Visibility = System.Windows.Visibility.Collapsed;
xaml_DistillName.Text = "Convert to XPS";
xaml_DistillName.FontWeight = FontWeights.Bold;
xaml_DistillGrid.Visibility = System.Windows.Visibility.Visible;
}
}
else
PrintXPS(m_currfile);
}
private void PrintXPS(String file)
{
gsprint ghostprint = new gsprint();
System.Windows.Controls.PrintDialog pDialog = ghostprint.GetPrintDialog();
if (pDialog == null)
return;
/* We have to create the XPS document on a different thread */
XpsDocument xpsDocument = new XpsDocument(file, FileAccess.Read);
FixedDocumentSequence fixedDocSeq = xpsDocument.GetFixedDocumentSequence();
PrintQueue printQueue = pDialog.PrintQueue;
m_ghostprint = ghostprint;
xaml_PrintGrid.Visibility = System.Windows.Visibility.Visible;
xaml_PrintProgress.Value = 0;
ghostprint.Print(printQueue, fixedDocSeq);
}
private void PrintProgress(object printHelper, gsPrintEventArgs Information)
{
if (Information.Status != PrintStatus_t.PRINT_BUSY)
{
xaml_PrintProgress.Value = 100;
xaml_PrintGrid.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
xaml_PrintProgress.Value =
100.0 * (double) Information.Page / (double)m_num_pages;
}
}
private void CancelDistillClick(object sender, RoutedEventArgs e)
{
xaml_CancelDistill.IsEnabled = false;
if (m_ghostscript != null)
m_ghostscript.Cancel();
}
private void CancelPrintClick(object sender, RoutedEventArgs e)
{
m_ghostprint.CancelAsync();
}
private void ShowGSMessage(object sender, RoutedEventArgs e)
{
m_gsoutput.Show();
}
private void ConvertClick(object sender, RoutedEventArgs e)
{
if (m_ghostscript.GetStatus() != gsStatus.GS_READY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
return;
}
if (m_convertwin == null || !m_convertwin.IsActive)
{
m_convertwin = new Convert(m_num_pages);
m_convertwin.ConvertUpdateMain += new Convert.ConvertCallBackMain(ConvertReturn);
m_convertwin.Activate();
m_convertwin.Show();
}
}
private void ConvertReturn(object sender)
{
if (m_ghostscript.GetStatus() != gsStatus.GS_READY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
return;
}
Device device = (Device)m_convertwin.xaml_DeviceList.SelectedItem;
System.Collections.IList pages = m_convertwin.xaml_PageList.SelectedItems;
System.Collections.IList pages_selected = null;
String options = m_convertwin.xaml_options.Text;
int resolution = 72;
bool multi_page_needed = false;
int first_page = -1;
int last_page = -1;
if (pages.Count == 0)
{
ShowMessage(NotifyType_t.MESS_STATUS, "No Pages Selected");
return;
}
if (device == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "No Device Selected");
return;
}
/* Get a filename */
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "All files (*.*)|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (!device.SupportsMultiPage && m_num_pages > 1)
multi_page_needed = true;
if (pages.Count != m_num_pages)
{
/* We may need to go through page by page. Determine if
* selection of pages is continuous. This is done by
* looking at the first one in the list and the last one
* in the list and checking the length */
SelectPage lastpage = (SelectPage) pages[pages.Count -1];
SelectPage firstpage = (SelectPage) pages[0];
int temp = lastpage.Page - firstpage.Page + 1;
if (temp == pages.Count)
{
/* Pages are contiguous. Add first and last page
* as command line option */
options = options + " -dFirstPage=" + firstpage.Page + " -dLastPage=" + lastpage.Page;
first_page = firstpage.Page;
last_page = lastpage.Page;
}
else
{
/* Pages are not continguous. We will do this page
* by page.*/
pages_selected = pages;
multi_page_needed = true; /* need to put in separate outputs */
}
}
xaml_DistillProgress.Value = 0;
if (m_ghostscript.Convert(m_currfile, options,
device.DeviceName, dlg.FileName, pages.Count, resolution,
multi_page_needed, pages_selected, first_page, last_page,
null, null) == gsStatus.GS_BUSY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
return;
}
xaml_DistillName.Text = "GS Converting Document";
xaml_CancelDistill.Visibility = System.Windows.Visibility.Collapsed;
xaml_DistillName.FontWeight = FontWeights.Bold;
xaml_DistillGrid.Visibility = System.Windows.Visibility.Visible;
m_convertwin.Close();
}
return;
}
private void GetPassword()
{
if (m_password == null)
{
m_password = new Password();
m_password.PassUpdateMain += new Password.PassCallBackMain(PasswordReturn);
m_password.Activate();
m_password.Show();
}
}
private void PasswordReturn(object sender)
{
if (mu_doc.ApplyPassword(m_password.xaml_Password.Password))
{
m_password.Close();
m_password = null;
StartViewer();
}
else
ShowMessage(NotifyType_t.MESS_STATUS, "Password Incorrect");
}
private void ShowInfo(object sender, RoutedEventArgs e)
{
String Message;
if (m_file_open)
{
Message =
" File: " + m_currfile + "\n" +
"Document Type: " + m_document_type + "\n" +
" Pages: " + m_num_pages + "\n" +
" Current Page: " + (m_currpage + 1) + "\n";
if (m_infowindow == null || !(m_infowindow.IsActive))
m_infowindow = new Info();
m_infowindow.xaml_TextInfo.Text = Message;
m_infowindow.FontFamily = new FontFamily("Courier New");
m_infowindow.Show();
}
}
#region Zoom Control
private void ZoomOut(object sender, RoutedEventArgs e)
{
if (!m_init_done)
return;
m_doczoom = m_doczoom - Constants.ZOOM_STEP;
if (m_doczoom < Constants.ZOOM_MIN)
m_doczoom = Constants.ZOOM_MIN;
xaml_ZoomSlider.Value = m_doczoom * 100.0;
m_numpagesvisible = (int)(Math.Ceiling((1.0 / m_doczoom) + 2));
RenderRange(m_currpage, false);
}
private void ZoomIn(object sender, RoutedEventArgs e)
{
if (!m_init_done)
return;
m_doczoom = m_doczoom + Constants.ZOOM_STEP;
if (m_doczoom > Constants.ZOOM_MAX)
m_doczoom = Constants.ZOOM_MAX;
xaml_ZoomSlider.Value = m_doczoom * 100.0;
m_numpagesvisible = (int)(Math.Ceiling((1.0 / m_doczoom) + 2));
RenderRange(m_currpage, false);
}
private void ShowFooter(object sender, RoutedEventArgs e)
{
xaml_FooterControl.Visibility = System.Windows.Visibility.Visible;
}
private void HideFooter(object sender, RoutedEventArgs e)
{
xaml_FooterControl.Visibility = System.Windows.Visibility.Collapsed;
}
private void ZoomReleased(object sender, MouseButtonEventArgs e)
{
if (m_init_done)
{
double zoom = xaml_ZoomSlider.Value / 100.0;
if (zoom > Constants.ZOOM_MAX)
zoom = Constants.ZOOM_MAX;
if (zoom < Constants.ZOOM_MIN)
zoom = Constants.ZOOM_MIN;
m_numpagesvisible = (int)(Math.Ceiling((1.0 / zoom) + 2));
m_doczoom = zoom;
RenderRange(m_currpage, false);
}
}
/* If the zoom is not equalto 1 then set the zoom to 1 and scoll to this page */
private void PageDoubleClick(object sender, MouseButtonEventArgs e)
{
if (m_doczoom != 1.0)
{
m_doczoom = 1.0;
mxaml_Zoomsize.Text = "100";
var item = ((FrameworkElement)e.OriginalSource).DataContext as DocPage;
if (item != null)
RenderRange(item.PageNum, true);
}
}
private void ZoomEnterClicked(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Return)
{
e.Handled = true;
var desired_zoom = mxaml_Zoomsize.Text;
try
{
double zoom = (double) System.Convert.ToInt32(desired_zoom) / 100.0;
if (zoom > Constants.ZOOM_MAX)
zoom = Constants.ZOOM_MAX;
if (zoom < Constants.ZOOM_MIN)
zoom = Constants.ZOOM_MIN;
m_numpagesvisible = (int)(Math.Ceiling((1.0 / zoom) + 2));
m_doczoom = zoom;
RenderRange(m_currpage, false);
}
catch (FormatException e1)
{
Console.WriteLine("String is not a sequence of digits.");
}
catch (OverflowException e2)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
}
}
#endregion Zoom Control
#region Thumb Rendering
void SetThumbInit(int page_num, Byte[] bitmap, Point ras_size, double zoom_in)
{
/* Two jobs. Store the thumb and possibly update the full page */
DocPage doc_page = m_thumbnails[page_num];
doc_page.Width = (int)ras_size.X;
doc_page.Height = (int)ras_size.Y;
doc_page.Content = Page_Content_t.THUMBNAIL;
doc_page.Zoom = zoom_in;
int stride = doc_page.Width * 4;
doc_page.BitMap = BitmapSource.Create(doc_page.Width, doc_page.Height, 72, 72, PixelFormats.Pbgra32, BitmapPalettes.Halftone256, bitmap, stride);
doc_page.PageNum = page_num;
/* And the main page */
var doc = m_docPages[page_num];
if (doc.Content == Page_Content_t.THUMBNAIL || doc.Content == Page_Content_t.FULL_RESOLUTION)
return;
else
{
doc_page = this.m_docPages[page_num];
doc_page.Content = Page_Content_t.THUMBNAIL;
doc_page.Zoom = zoom_in;
doc_page.BitMap = m_thumbnails[page_num].BitMap;
doc_page.Width = (int)(ras_size.X / Constants.SCALE_THUMB);
doc_page.Height = (int)(ras_size.Y / Constants.SCALE_THUMB);
doc_page.PageNum = page_num;
}
}
private void ThumbsWork(object sender, DoWorkEventArgs e)
{
Point ras_size;
status_t code;
double scale_factor = Constants.SCALE_THUMB;
BackgroundWorker worker = sender as BackgroundWorker;
Byte[] bitmap;
for (int k = 0; k < m_num_pages; k++)
{
if (ComputePageSize(k, scale_factor, out ras_size) == status_t.S_ISOK)
{
try
{
bitmap = new byte[(int)ras_size.X * (int)ras_size.Y * 4];
/* Synchronous call on our background thread */
code = (status_t)mu_doc.RenderPage(k, bitmap, (int)ras_size.X, (int)ras_size.Y, scale_factor, false, false);
}
catch (OutOfMemoryException em)
{
Console.WriteLine("Memory allocation failed thumb page " + k + em.Message + "\n");
break;
}
/* Use thumb if we rendered ok */
if (code == status_t.S_ISOK)
{
double percent = 100 * (double)(k + 1) / (double)m_num_pages;
thumb_t curr_thumb = new thumb_t();
curr_thumb.page_num = k;
curr_thumb.bitmap = bitmap;
curr_thumb.size = ras_size;
worker.ReportProgress((int)percent, curr_thumb);
}
}
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
}
}
private void ThumbsCompleted(object sender, RunWorkerCompletedEventArgs e)
{
xaml_ProgressGrid.Visibility = System.Windows.Visibility.Collapsed;
xaml_ThumbProgress.Value = 0;
xaml_ThumbList.ItemsSource = m_thumbnails;
m_have_thumbs = true;
m_thumbworker = null;
xaml_CancelThumb.IsEnabled = true;
}
private void ThumbsProgressChanged(object sender, ProgressChangedEventArgs e)
{
thumb_t thumb = (thumb_t)(e.UserState);
xaml_ThumbProgress.Value = e.ProgressPercentage;
SetThumbInit(thumb.page_num, thumb.bitmap, thumb.size, 1.0);
m_docPages[thumb.page_num].PageRefresh();
m_thumbnails[thumb.page_num].PageRefresh();
}
private void RenderThumbs()
{
/* Create background task for rendering the thumbnails. Allow
this to be cancelled if we open a new doc while we are in loop
rendering. Put the UI updates in the progress changed which will
run on the main thread */
try
{
m_thumbworker = new BackgroundWorker();
m_thumbworker.WorkerReportsProgress = true;
m_thumbworker.WorkerSupportsCancellation = true;
m_thumbworker.DoWork += new DoWorkEventHandler(ThumbsWork);
m_thumbworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ThumbsCompleted);
m_thumbworker.ProgressChanged += new ProgressChangedEventHandler(ThumbsProgressChanged);
xaml_ProgressGrid.Visibility = System.Windows.Visibility.Visible;
m_thumbworker.RunWorkerAsync();
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed during thumb rendering\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
}
#endregion Thumb Rendering
#region Copy Paste
/* Copy the current page as a bmp to the clipboard this is done at the
* current resolution */
private void CopyPage(object sender, RoutedEventArgs e)
{
if (!m_init_done)
return;
var curr_page = m_docPages[m_currpage];
System.Windows.Clipboard.SetImage(curr_page.BitMap);
m_clipboardset = true;
}
/* Paste the page to various types supported by the windows encoder class */
private void PastePage(object sender, RoutedEventArgs e)
{
var menu = (System.Windows.Controls.MenuItem)sender;
String tag = (String) menu.Tag;
if (!m_clipboardset || !System.Windows.Clipboard.ContainsImage() ||
!m_init_done)
return;
var bitmap = System.Windows.Clipboard.GetImage();
BitmapEncoder encoder;
SaveFileDialog dlg = new SaveFileDialog();
dlg.FilterIndex = 1;
switch (tag)
{
case "PNG":
dlg.Filter = "PNG Files(*.png)|*.png";
encoder = new PngBitmapEncoder();
break;
case "JPG":
dlg.Filter = "JPEG Files(*.jpg)|*.jpg";
encoder = new JpegBitmapEncoder();
break;
case "WDP":
dlg.Filter = "HDP Files(*.wdp)|*.wdp";
encoder = new WmpBitmapEncoder();
break;
case "TIF":
dlg.Filter = "TIFF Files(*.tif)|*.tif";
encoder = new TiffBitmapEncoder();
break;
case "BMP":
dlg.Filter = "BMP Files(*.bmp)|*.bmp";
encoder = new BmpBitmapEncoder();
break;
case "GIF":
dlg.Filter = "GIF Files(*.gif)|*.gif";
encoder = new GifBitmapEncoder();
break;
default:
return;
}
encoder.Frames.Add(BitmapFrame.Create(bitmap));
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var stream = dlg.OpenFile())
encoder.Save(stream);
}
}
#endregion Copy Paste
#region SaveAs
String CreatePDFXA(Save_Type_t type)
{
Byte[] Resource;
String Profile;
switch (type)
{
case Save_Type_t.PDFA1_CMYK:
case Save_Type_t.PDFA2_CMYK:
Resource = Properties.Resources.PDFA_def;
Profile = m_outputintents.cmyk_icc;
break;
case Save_Type_t.PDFA1_RGB:
case Save_Type_t.PDFA2_RGB:
Resource = Properties.Resources.PDFA_def;
Profile = m_outputintents.rgb_icc;
break;
case Save_Type_t.PDFX3_CMYK:
Resource = Properties.Resources.PDFX_def;
Profile = m_outputintents.cmyk_icc;
break;
case Save_Type_t.PDFX3_GRAY:
Resource = Properties.Resources.PDFX_def;
Profile = m_outputintents.gray_icc;
break;
default:
return null;
}
String Profile_new = Profile.Replace("\\", "/");
String result = System.Text.Encoding.UTF8.GetString(Resource);
String pdfx_cust = result.Replace("ICCPROFILE", Profile_new);
var out_file = System.IO.Path.GetTempFileName();
System.IO.File.WriteAllText(out_file, pdfx_cust);
return out_file;
}
private void SaveFile(Save_Type_t type)
{
if (!m_file_open)
return;
SaveFileDialog dlg = new SaveFileDialog();
dlg.FilterIndex = 1;
/* PDF output types */
if (type <= Save_Type_t.PDF)
{
dlg.Filter = "PDF Files(*.pdf)|*.pdf";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
String options = null;
bool use_gs = true;
String init_file = CreatePDFXA(type);
;
switch (type)
{
case Save_Type_t.PDF:
/* All done. No need to use gs */
System.IO.File.Copy(m_currfile, dlg.FileName, true);
use_gs = false;
break;
case Save_Type_t.PDF13:
options = "-dCompatibilityLevel=1.3";
break;
case Save_Type_t.PDFA1_CMYK:
options = "-dPDFA=1 -dNOOUTERSAVE -dPDFACompatibilityPolicy=1 -sProcessColorModel=DeviceCMYK -dColorConversionStrategy=/CMYK -sOutputICCProfile=" + m_outputintents.cmyk_icc;
break;
case Save_Type_t.PDFA1_RGB:
options = "-dPDFA=1 -dNOOUTERSAVE -dPDFACompatibilityPolicy=1 -sProcessColorModel=DeviceRGB -dColorConversionStrategy=/RGB -sOutputICCProfile=" + m_outputintents.rgb_icc;
break;
case Save_Type_t.PDFA2_CMYK:
options = "-dPDFA=2 -dNOOUTERSAVE -dPDFACompatibilityPolicy=1 -sProcessColorModel=DeviceCMYK -dColorConversionStrategy=/CMYK -sOutputICCProfile=" + m_outputintents.cmyk_icc;
break;
case Save_Type_t.PDFA2_RGB:
options = "-dPDFA=2 -dNOOUTERSAVE -dPDFACompatibilityPolicy=1 -sProcessColorModel=DeviceRGB -dColorConversionStrategy=/RGB -sOutputICCProfile=" + m_outputintents.rgb_icc;
break;
case Save_Type_t.PDFX3_CMYK:
options = "-dPDFX -dNOOUTERSAVE -dPDFACompatibilityPolicy=1 -sProcessColorModel=DeviceCMYK -dColorConversionStrategy=/CMYK -sOutputICCProfile=" + m_outputintents.cmyk_icc;
break;
case Save_Type_t.PDFX3_GRAY:
options = "-dPDFX -dNOOUTERSAVE -dPDFACompatibilityPolicy=1 -sProcessColorModel=DeviceGray -dColorConversionStrategy=/Gray -sOutputICCProfile=" + m_outputintents.cmyk_icc;
break;
}
if (use_gs)
{
xaml_DistillProgress.Value = 0;
if (m_ghostscript.Convert(m_currfile, options,
Enum.GetName(typeof(gsDevice_t), gsDevice_t.pdfwrite),
dlg.FileName, m_num_pages, 300, false, null, -1, -1,
init_file, null) == gsStatus.GS_BUSY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
return;
}
xaml_DistillName.Text = "Creating PDF";
xaml_CancelDistill.Visibility = System.Windows.Visibility.Collapsed;
xaml_DistillName.FontWeight = FontWeights.Bold;
xaml_DistillGrid.Visibility = System.Windows.Visibility.Visible;
}
}
}
else
{
/* Non PDF output */
gsDevice_t Device = gsDevice_t.xpswrite;
bool use_mupdf = true;
switch (type)
{
case Save_Type_t.PCLBitmap:
break;
case Save_Type_t.PNG:
break;
case Save_Type_t.PWG:
break;
case Save_Type_t.SVG:
break;
case Save_Type_t.PCLXL:
use_mupdf = false;
dlg.Filter = "PCL-XL (*.bin)|*.bin";
Device = gsDevice_t.pxlcolor;
break;
case Save_Type_t.TEXT:
use_mupdf = false;
dlg.Filter = "Text Files(*.txt)|*.txt";
Device = gsDevice_t.txtwrite;
break;
case Save_Type_t.XPS:
use_mupdf = false;
dlg.Filter = "XPS Files(*.xps)|*.xps";
break;
}
if (!use_mupdf)
{
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (m_ghostscript.Convert(m_currfile, "",
Enum.GetName(typeof(gsDevice_t), Device),
dlg.FileName, 1, 300, false, null, -1, -1,
null, null) == gsStatus.GS_BUSY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
return;
}
}
}
}
}
private void SavePNG(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PNG);
}
private void SavePWG(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PWG);
}
private void SavePNM(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PNM);
}
private void SaveSVG(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.SVG);
}
private void SavePCL(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PCLBitmap);
}
private void SavePDF(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PDF);
}
private void SaveText(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.TEXT);
}
private void SavePDF13(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PDF13);
}
private void SavePDFX3_Gray(object sender, RoutedEventArgs e)
{
if (m_outputintents.gray_icc == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "Set Gray Output Intent ICC Profile");
return;
}
SaveFile(Save_Type_t.PDFX3_GRAY);
}
private void SavePDFX3_CMYK(object sender, RoutedEventArgs e)
{
if (m_outputintents.cmyk_icc == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "Set CMYK Output Intent ICC Profile");
return;
}
SaveFile(Save_Type_t.PDFX3_CMYK);
}
private void SavePDFA1_RGB(object sender, RoutedEventArgs e)
{
if (m_outputintents.rgb_icc == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "Set RGB Output Intent ICC Profile");
return;
}
SaveFile(Save_Type_t.PDFA1_RGB);
}
private void SavePDFA1_CMYK(object sender, RoutedEventArgs e)
{
if (m_outputintents.cmyk_icc == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "Set CMYK Output Intent ICC Profile");
return;
}
SaveFile(Save_Type_t.PDFA1_CMYK);
}
private void SavePDFA2_RGB(object sender, RoutedEventArgs e)
{
if (m_outputintents.rgb_icc == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "Set RGB Output Intent ICC Profile");
return;
}
SaveFile(Save_Type_t.PDFA2_RGB);
}
private void SavePDFA2_CMYK(object sender, RoutedEventArgs e)
{
if (m_outputintents.cmyk_icc == null)
{
ShowMessage(NotifyType_t.MESS_STATUS, "Set CMYK Output Intent ICC Profile");
return;
}
SaveFile(Save_Type_t.PDFA2_CMYK);
}
private void SavePCLXL(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.PCLXL);
}
private void SaveXPS(object sender, RoutedEventArgs e)
{
SaveFile(Save_Type_t.XPS);
}
#endregion SaveAs
#region Extract
private void Extract(Extract_Type_t type)
{
if (m_selection != null || !m_init_done)
return;
m_selection = new Selection(m_currpage + 1, m_doczoom, type);
m_selection.UpdateMain += new Selection.CallBackMain(SelectionMade);
m_selection.Show();
m_selection.xaml_Image.Source = m_docPages[m_currpage].BitMap;
m_selection.xaml_Image.Height = m_docPages[m_currpage].Height;
m_selection.xaml_Image.Width = m_docPages[m_currpage].Width;
}
async private void SelectionZoom(int page_num, double zoom)
{
Point ras_size;
if (ComputePageSize(page_num, zoom, out ras_size) == status_t.S_ISOK)
{
try
{
Byte[] bitmap = new byte[(int)ras_size.X * (int)ras_size.Y * 4];
Task<int> ren_task =
new Task<int>(() => mu_doc.RenderPage(page_num, bitmap, (int)ras_size.X, (int)ras_size.Y, zoom, false, true));
ren_task.Start();
await ren_task.ContinueWith((antecedent) =>
{
status_t code = (status_t)ren_task.Result;
if (code == status_t.S_ISOK)
{
if (m_selection != null)
{
int stride = (int) ras_size.X * 4;
m_selection.xaml_Image.Source = BitmapSource.Create((int) ras_size.X, (int) ras_size.Y, 72, 72, PixelFormats.Pbgra32, BitmapPalettes.Halftone256, bitmap, stride);
m_selection.xaml_Image.Height = (int)ras_size.Y;
m_selection.xaml_Image.Width = (int)ras_size.X;
m_selection.UpdateRect();
m_selection.m_curr_state = SelectStatus_t.OK;
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed page " + page_num + "\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
}
}
private void SelectionMade(object gsObject, SelectEventArgs results)
{
switch (results.State)
{
case SelectStatus_t.CANCEL:
case SelectStatus_t.CLOSE:
m_selection = null;
return;
case SelectStatus_t.SELECT:
/* Get the information we need */
double zoom = results.ZoomFactor;
Point start = results.TopLeft;
Point size = results.Size;
int page = results.PageNum;
gsDevice_t Device = gsDevice_t.pdfwrite;
start.X = start.X / zoom;
start.Y = start.Y / zoom;
size.X = size.X / zoom;
size.Y = size.Y / zoom;
/* Do the actual extraction */
String options;
SaveFileDialog dlg = new SaveFileDialog();
dlg.FilterIndex = 1;
/* Get us set up to do a fixed size */
options = "-dFirstPage=" + page + " -dLastPage=" + page +
" -dDEVICEWIDTHPOINTS=" + size.X + " -dDEVICEHEIGHTPOINTS=" +
size.Y + " -dFIXEDMEDIA";
/* Set up the translation */
String init_string = "<</Install {-" + start.X + " -" +
start.Y + " translate (testing) == flush}>> setpagedevice";
switch (results.Type)
{
case Extract_Type_t.PDF:
dlg.Filter = "PDF Files(*.pdf)|*.pdf";
break;
case Extract_Type_t.EPS:
dlg.Filter = "EPS Files(*.eps)|*.eps";
Device = gsDevice_t.eps2write;
break;
case Extract_Type_t.PS:
dlg.Filter = "PostScript Files(*.ps)|*.ps";
Device = gsDevice_t.ps2write;
break;
case Extract_Type_t.SVG:
dlg.Filter = "SVG Files(*.svg)|*.svg";
break;
}
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (m_ghostscript.Convert(m_currfile, options,
Enum.GetName(typeof(gsDevice_t), Device),
dlg.FileName, 1, 300, false, null, page, page,
null, init_string) == gsStatus.GS_BUSY)
{
ShowMessage(NotifyType_t.MESS_STATUS, "GS busy");
return;
}
}
m_selection.Close();
break;
case SelectStatus_t.ZOOMIN:
/* Render new page at this resolution and hand it off */
SelectionZoom(results.PageNum - 1, results.ZoomFactor);
break;
case SelectStatus_t.ZOOMOUT:
/* Render new page at this resolution and hand it off */
SelectionZoom(results.PageNum - 1, results.ZoomFactor);
break;
}
}
private void ExtractPDF(object sender, RoutedEventArgs e)
{
Extract(Extract_Type_t.PDF);
}
private void ExtractEPS(object sender, RoutedEventArgs e)
{
Extract(Extract_Type_t.EPS);
}
private void ExtractPS(object sender, RoutedEventArgs e)
{
Extract(Extract_Type_t.PS);
}
private void ExtractSVG(object sender, RoutedEventArgs e)
{
Extract(Extract_Type_t.SVG);
}
private void OutputIntents(object sender, RoutedEventArgs e)
{
m_outputintents.Show();
}
#endregion Extract
#region Search
/* Search related code */
private void Search(object sender, RoutedEventArgs e)
{
if (!m_init_done || (m_textsearch != null && m_textsearch.IsBusy))
return;
m_textsearch = null; /* Start out fresh */
if (xaml_SearchControl.Visibility == System.Windows.Visibility.Collapsed)
xaml_SearchControl.Visibility = System.Windows.Visibility.Visible;
else
{
xaml_SearchControl.Visibility = System.Windows.Visibility.Collapsed;
xaml_SearchGrid.Visibility = System.Windows.Visibility.Collapsed;
ClearTextSearch();
}
}
private void OnSearchBackClick(object sender, RoutedEventArgs e)
{
String textToFind = xaml_SearchText.Text;
TextSearchSetUp(-1, textToFind);
}
private void OnSearchForwardClick(object sender, RoutedEventArgs e)
{
String textToFind = xaml_SearchText.Text;
TextSearchSetUp(1, textToFind);
}
/* The thread that is actually doing the search work */
void SearchWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<object> genericlist = e.Argument as List<object>;
int direction = (int) genericlist[0];
String needle = (String) genericlist[1];
/* To make sure we get the next page or current page during search */
int in_search = (int)genericlist[2];
m_searchpage = m_currpage + direction * in_search;
searchResults_t results = new searchResults_t();
/* Break if we find something, get to the end (or start of doc)
* or if we have a cancel occur */
while (true)
{
int box_count = mu_doc.TextSearchPage(m_searchpage, needle);
int percent;
if (direction == 1)
percent = (int)(100.0 * ((double)m_searchpage + 1) / (double)m_num_pages);
else
percent = 100 - (int)(100.0 * ((double)m_searchpage) / (double)m_num_pages);
if (box_count > 0)
{
/* This page has something lets go ahead and extract and
* signal to the UI thread and end this thread */
results.done = false;
results.num_rects = box_count;
results.page_found = m_searchpage;
results.rectangles = new List<Rect>();
for (int kk = 0; kk < box_count; kk++ )
{
Point top_left;
Size size;
mu_doc.GetTextSearchItem(kk, out top_left, out size);
var rect = new Rect(top_left, size);
results.rectangles.Add(rect);
}
/* Reset global smart pointer once we have everything */
mu_doc.ReleaseTextSearch();
worker.ReportProgress(percent, results);
break;
}
else
{
/* This page has nothing. Lets go ahead and just update
* the progress bar */
worker.ReportProgress(percent, null);
if (percent >= 100)
{
results.done = true;
results.needle = needle;
break;
}
m_searchpage = m_searchpage + direction;
}
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
}
e.Result = results;
}
private void SearchProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState == null)
{
/* Nothing found */
xaml_SearchProgress.Value = e.ProgressPercentage;
}
else
{
m_text_list = new List<RectList>();
/* found something go to page and show results */
searchResults_t results = (searchResults_t)e.UserState;
xaml_SearchProgress.Value = e.ProgressPercentage;
m_currpage = results.page_found;
/* Add in the rectangles */
for (int kk = 0; kk < results.num_rects; kk++)
{
var rect_item = new RectList();
rect_item.Scale = m_doczoom;
rect_item.Color = m_textcolor;
rect_item.Height = results.rectangles[kk].Height * m_doczoom;
rect_item.Width = results.rectangles[kk].Width * m_doczoom;
rect_item.X = results.rectangles[kk].X * m_doczoom;
rect_item.Y = results.rectangles[kk].Y * m_doczoom;
rect_item.Index = kk.ToString();
m_text_list.Add(rect_item);
}
m_docPages[results.page_found].TextBox = m_text_list;
m_docPages[results.page_found].PageRefresh();
xaml_PageList.ScrollIntoView(m_docPages[results.page_found]);
}
}
private void SearchCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
xaml_SearchGrid.Visibility = System.Windows.Visibility.Collapsed;
m_textsearch = null;
}
else
{
searchResults_t results = (searchResults_t) e.Result;
if (results.done == true)
{
xaml_SearchGrid.Visibility = System.Windows.Visibility.Collapsed;
m_textsearch = null;
ShowMessage(NotifyType_t.MESS_STATUS, "End of document search for \"" + results.needle + "\"");
}
}
}
private void CancelSearchClick(object sender, RoutedEventArgs e)
{
if (m_textsearch != null && m_textsearch.IsBusy)
m_textsearch.CancelAsync();
xaml_SearchGrid.Visibility = System.Windows.Visibility.Collapsed;
m_textsearch = null;
ClearTextSearch();
}
private void ClearTextSearch()
{
for (int kk = 0; kk < m_num_pages; kk++)
{
var temp = m_docPages[kk].TextBox;
if (temp != null)
{
m_docPages[kk].TextBox = null;
m_docPages[kk].PageRefresh();
}
}
}
private void ScaleTextBox(int pagenum)
{
var temp = m_docPages[pagenum].TextBox;
for (int kk = 0; kk < temp.Count; kk++)
{
var rect_item = temp[kk];
double factor = m_doczoom / temp[kk].Scale;
temp[kk].Height = temp[kk].Height * factor;
temp[kk].Width = temp[kk].Width * factor;
temp[kk].X = temp[kk].X * factor;
temp[kk].Y = temp[kk].Y * factor;
temp[kk].Scale = m_doczoom;
temp[kk].PageRefresh();
}
m_docPages[pagenum].TextBox = temp;
}
private void TextSearchSetUp(int direction, String needle)
{
/* Create background task for performing text search. */
try
{
int in_text_search = 0;
if (m_textsearch != null && m_textsearch.IsBusy)
return;
if (m_textsearch != null)
{
in_text_search = 1;
m_textsearch = null;
}
if (m_prevsearch != null && needle != m_prevsearch)
{
in_text_search = 0;
ClearTextSearch();
}
if (m_textsearch == null)
{
m_prevsearch = needle;
m_textsearch = new BackgroundWorker();
m_textsearch.WorkerReportsProgress = true;
m_textsearch.WorkerSupportsCancellation = true;
var arguments = new List<object>();
arguments.Add(direction);
arguments.Add(needle);
arguments.Add(in_text_search);
m_textsearch.DoWork += new DoWorkEventHandler(SearchWork);
m_textsearch.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SearchCompleted);
m_textsearch.ProgressChanged += new ProgressChangedEventHandler(SearchProgressChanged);
xaml_SearchGrid.Visibility = System.Windows.Visibility.Visible;
m_textsearch.RunWorkerAsync(arguments);
}
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Memory allocation failed during text search\n");
ShowMessage(NotifyType_t.MESS_ERROR, "Out of memory: " + e.Message);
}
}
#endregion Search
#region Link
private void LinksToggle(object sender, RoutedEventArgs e)
{
if (!m_init_done)
return;
m_links_on = !m_links_on;
if (m_page_link_list == null)
{
if (m_linksearch != null && m_linksearch.IsBusy)
return;
m_page_link_list = new List<List<RectList>>();
m_linksearch = new BackgroundWorker();
m_linksearch.WorkerReportsProgress = false;
m_linksearch.WorkerSupportsCancellation = true;
m_linksearch.DoWork += new DoWorkEventHandler(LinkWork);
m_linksearch.RunWorkerCompleted += new RunWorkerCompletedEventHandler(LinkCompleted);
m_linksearch.RunWorkerAsync();
}
else
{
if (m_links_on)
LinksOn();
else
LinksOff();
}
}
private void LinkWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int k = 0; k < m_num_pages; k++)
{
int box_count = mu_doc.GetLinksPage(k);
List<RectList> links = new List<RectList>();
if (box_count > 0)
{
var rectlist = new RectList();
for (int j = 0; j < box_count; j++)
{
Point top_left;
Size size;
String uri;
int type;
int topage;
mu_doc.GetLinkItem(j, out top_left, out size, out uri,
out topage, out type);
rectlist.Height = size.Height * m_doczoom;
rectlist.Width = size.Width * m_doczoom;
rectlist.X = top_left.X * m_doczoom;
rectlist.Y = top_left.Y * m_doczoom;
rectlist.Color = m_linkcolor;
rectlist.Index = k.ToString() + "." + j.ToString();
rectlist.PageNum = topage;
rectlist.Scale = m_doczoom;
if (uri != null)
rectlist.Urilink = new Uri(uri);
rectlist.Type = (Link_t) type;
links.Add(rectlist);
}
}
mu_doc.ReleaseLink();
m_page_link_list.Add(links);
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
}
}
private void LinkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
LinksOn();
}
private void ScaleLinkBox(int pagenum)
{
var temp = m_docPages[pagenum].LinkBox;
for (int kk = 0; kk < temp.Count; kk++)
{
var rect_item = temp[kk];
double factor = m_doczoom / temp[kk].Scale;
temp[kk].Height = temp[kk].Height * factor;
temp[kk].Width = temp[kk].Width * factor;
temp[kk].X = temp[kk].X * factor;
temp[kk].Y = temp[kk].Y * factor;
temp[kk].Scale = m_doczoom;
temp[kk].PageRefresh();
}
m_docPages[pagenum].LinkBox = temp;
}
/* Only visible pages */
private void LinksOff()
{
int range = (int)Math.Ceiling(((double)m_numpagesvisible - 1.0) / 2.0);
for (int kk = m_currpage - range; kk <= m_currpage + range; kk++)
{
var temp = m_docPages[kk].LinkBox;
if (temp != null)
{
m_docPages[kk].LinkBox = null;
m_docPages[kk].PageRefresh();
}
}
}
/* Only visible pages */
private void LinksOn()
{
int range = (int)Math.Ceiling(((double)m_numpagesvisible - 1.0) / 2.0);
for (int kk = m_currpage - range; kk <= m_currpage + range; kk++)
{
var temp = m_docPages[kk].LinkBox;
if (temp == null)
{
m_docPages[kk].LinkBox = m_page_link_list[kk];
m_docPages[kk].PageRefresh();
}
}
}
private void LinkClick(object sender, MouseButtonEventArgs e)
{
var item = (Rectangle)sender;
if (item == null)
return;
String tag = (String)item.Tag;
int page = 0;
int index = 0;
if (tag == null || tag.Length < 3 || !(tag.Contains('.')))
return;
String[] parts = tag.Split('.');
try
{
page = System.Convert.ToInt32(parts[0]);
index = System.Convert.ToInt32(parts[1]);
}
catch (FormatException e1)
{
Console.WriteLine("String is not a sequence of digits.");
}
catch (OverflowException e2)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
if (index >= 0 && index < m_num_pages && page >= 0 && page < m_num_pages)
{
var link_list = m_page_link_list[page];
var link = link_list[index];
if (link.Type == Link_t.LINK_GOTO)
{
if (m_currpage != link.PageNum && link.PageNum >= 0 &&
link.PageNum < m_num_pages)
RenderRange(link.PageNum, true);
}
else if (link.Type == Link_t.LINK_URI)
System.Diagnostics.Process.Start(link.Urilink.AbsoluteUri);
}
}
#endregion Link
}
}
|