/
CFFFontSubset.java
1692 lines (1591 loc) · 58.4 KB
/
CFFFontSubset.java
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
/*
*
* This file is part of the iText (R) project.
Copyright (c) 1998-2017 iText Group NV
* Authors: Bruno Lowagie, Paulo Soares, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://itextpdf.com/terms-of-use/
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* In accordance with Section 7(b) of the GNU Affero General Public License,
* a covered work must retain the producer line in every PDF that is created
* or manipulated using iText.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the iText software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers as an ASP,
* serving PDFs on the fly in a web application, shipping iText with a closed
* source product.
*
* For more information, please contact iText Software Corp. at this
* address: sales@itextpdf.com
*/
package com.itextpdf.text.pdf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
/**
* This Class subsets a CFF Type Font. The subset is preformed for CID fonts and NON CID fonts.
* The Charstring is subsetted for both types. For CID fonts only the FDArray which are used are embedded.
* The Lsubroutines of the FDArrays used are subsetted as well. The Subroutine subset supports both Type1 and Type2
* formatting although only tested on Type2 Format.
* For Non CID the Lsubroutines are subsetted. On both types the Gsubroutines is subsetted.
* A font which was not of CID type is transformed into CID as a part of the subset process.
* The CID synthetic creation was written by Sivan Toledo (sivan@math.tau.ac.il)
* @author Oren Manor (manorore@post.tau.ac.il) and Ygal Blum (blumygal@post.tau.ac.il)
*/
public class CFFFontSubset extends CFFFont {
/**
* The Strings in this array represent Type1/Type2 operator names
*/
static final String SubrsFunctions[] = {
"RESERVED_0","hstem","RESERVED_2","vstem","vmoveto","rlineto","hlineto","vlineto",
"rrcurveto","RESERVED_9","callsubr","return","escape","RESERVED_13",
"endchar","RESERVED_15","RESERVED_16","RESERVED_17","hstemhm","hintmask",
"cntrmask","rmoveto","hmoveto","vstemhm","rcurveline","rlinecurve","vvcurveto",
"hhcurveto","shortint","callgsubr","vhcurveto","hvcurveto"
};
/**
* The Strings in this array represent Type1/Type2 escape operator names
*/
static final String SubrsEscapeFuncs[] = {
"RESERVED_0","RESERVED_1","RESERVED_2","and","or","not","RESERVED_6",
"RESERVED_7","RESERVED_8","abs","add","sub","div","RESERVED_13","neg",
"eq","RESERVED_16","RESERVED_17","drop","RESERVED_19","put","get","ifelse",
"random","mul","RESERVED_25","sqrt","dup","exch","index","roll","RESERVED_31",
"RESERVED_32","RESERVED_33","hflex","flex","hflex1","flex1","RESERVED_REST"
};
/**
* Operator codes for unused CharStrings and unused local and global Subrs
*/
static final byte ENDCHAR_OP = 14;
static final byte RETURN_OP = 11;
/**
* A HashMap containing the glyphs used in the text after being converted
* to glyph number by the CMap
*/
HashMap<Integer, int[]> GlyphsUsed;
/**
* The GlyphsUsed keys as an ArrayList
*/
ArrayList<Integer> glyphsInList;
/**
* A HashSet for keeping the FDArrays being used by the font
*/
HashSet<Integer> FDArrayUsed = new HashSet<Integer>();
/**
* A HashMaps array for keeping the subroutines used in each FontDict
*/
HashMap<Integer, int[]>[] hSubrsUsed;
/**
* The SubroutinesUsed HashMaps as ArrayLists
*/
ArrayList<Integer>[] lSubrsUsed;
/**
* A HashMap for keeping the Global subroutines used in the font
*/
HashMap<Integer, int[]> hGSubrsUsed = new HashMap<Integer, int[]>();
/**
* The Global SubroutinesUsed HashMaps as ArrayLists
*/
ArrayList<Integer> lGSubrsUsed = new ArrayList<Integer>();
/**
* A HashMap for keeping the subroutines used in a non-cid font
*/
HashMap<Integer, int[]> hSubrsUsedNonCID = new HashMap<Integer, int[]>();
/**
* The SubroutinesUsed HashMap as ArrayList
*/
ArrayList<Integer> lSubrsUsedNonCID = new ArrayList<Integer>();
/**
* An array of the new Indexes for the local Subr. One index for each FontDict
*/
byte[][] NewLSubrsIndex;
/**
* The new subroutines index for a non-cid font
*/
byte[] NewSubrsIndexNonCID;
/**
* The new global subroutines index of the font
*/
byte[] NewGSubrsIndex;
/**
* The new CharString of the font
*/
byte[] NewCharStringsIndex;
/**
* The bias for the global subroutines
*/
int GBias = 0;
/**
* The linked list for generating the new font stream
*/
LinkedList<Item> OutputList;
/**
* Number of arguments to the stem operators in a subroutine calculated recursively
*/
int NumOfHints=0;
/**
* C'tor for CFFFontSubset
* @param rf - The font file
* @param GlyphsUsed - a HashMap that contains the glyph used in the subset
*/
public CFFFontSubset(RandomAccessFileOrArray rf,HashMap<Integer, int[]> GlyphsUsed){
// Use CFFFont c'tor in order to parse the font file.
super(rf);
this.GlyphsUsed = GlyphsUsed;
//Put the glyphs into a list
glyphsInList = new ArrayList<Integer>(GlyphsUsed.keySet());
for (int i=0;i<fonts.length;++i)
{
// Read the number of glyphs in the font
seek(fonts[i].charstringsOffset);
fonts[i].nglyphs = getCard16();
// Jump to the count field of the String Index
seek(stringIndexOffset);
fonts[i].nstrings = getCard16()+standardStrings.length;
// For each font save the offset array of the charstring
fonts[i].charstringsOffsets = getIndex(fonts[i].charstringsOffset);
// Process the FDSelect if exist
if (fonts[i].fdselectOffset>=0)
{
// Process the FDSelect
readFDSelect(i);
// Build the FDArrayUsed hashmap
BuildFDArrayUsed(i);
}
if (fonts[i].isCID)
// Build the FD Array used Hash Map
ReadFDArray(i);
// compute the charset length
fonts[i].CharsetLength = CountCharset(fonts[i].charsetOffset,fonts[i].nglyphs);
}
}
/**
* Calculates the length of the charset according to its format
* @param Offset The Charset Offset
* @param NumofGlyphs Number of glyphs in the font
* @return the length of the Charset
*/
int CountCharset(int Offset,int NumofGlyphs){
int format;
int Length=0;
seek(Offset);
// Read the format
format = getCard8();
// Calc according to format
switch (format){
case 0:
Length = 1+2*NumofGlyphs;
break;
case 1:
Length = 1+3*CountRange(NumofGlyphs,1);
break;
case 2:
Length = 1+4*CountRange(NumofGlyphs,2);
break;
default:
break;
}
return Length;
}
/**
* Function calculates the number of ranges in the Charset
* @param NumofGlyphs The number of glyphs in the font
* @param Type The format of the Charset
* @return The number of ranges in the Charset data structure
*/
int CountRange(int NumofGlyphs,int Type){
int num=0;
char Sid;
int i=1,nLeft;
while (i<NumofGlyphs){
num++;
Sid = getCard16();
if (Type==1)
nLeft = getCard8();
else
nLeft = getCard16();
i += nLeft+1;
}
return num;
}
/**
* Read the FDSelect of the font and compute the array and its length
* @param Font The index of the font being processed
*/
protected void readFDSelect(int Font)
{
// Restore the number of glyphs
int NumOfGlyphs = fonts[Font].nglyphs;
int[] FDSelect = new int[NumOfGlyphs];
// Go to the beginning of the FDSelect
seek(fonts[Font].fdselectOffset);
// Read the FDSelect's format
fonts[Font].FDSelectFormat = getCard8();
switch(fonts[Font].FDSelectFormat){
// Format==0 means each glyph has an entry that indicated
// its FD.
case 0:
for (int i=0;i<NumOfGlyphs;i++)
{
FDSelect[i] = getCard8();
}
// The FDSelect's Length is one for each glyph + the format
// for later use
fonts[Font].FDSelectLength = fonts[Font].nglyphs+1;
break;
case 3:
// Format==3 means the ranges version
// The number of ranges
int nRanges = getCard16();
int l=0;
// Read the first in the first range
int first = getCard16();
for (int i=0;i<nRanges;i++)
{
// Read the FD index
int fd = getCard8();
// Read the first of the next range
int last = getCard16();
// Calc the steps and write to the array
int steps = last-first;
for (int k=0;k<steps;k++)
{
FDSelect[l] = fd;
l++;
}
// The last from this iteration is the first of the next
first = last;
}
// Store the length for later use
fonts[Font].FDSelectLength = 1+2+nRanges*3+2;
break;
default:
break;
}
// Save the FDSelect of the font
fonts[Font].FDSelect = FDSelect;
}
/**
* Function reads the FDSelect and builds the FDArrayUsed HashMap According to the glyphs used
* @param Font the Number of font being processed
*/
protected void BuildFDArrayUsed(int Font)
{
int[] FDSelect = fonts[Font].FDSelect;
// For each glyph used
for (int i=0;i<glyphsInList.size();i++)
{
// Pop the glyphs index
int glyph = glyphsInList.get(i).intValue();
// Pop the glyph's FD
int FD = FDSelect[glyph];
// Put the FD index into the FDArrayUsed HashMap
FDArrayUsed.add(Integer.valueOf(FD));
}
}
/**
* Read the FDArray count, offsize and Offset array
* @param Font
*/
protected void ReadFDArray(int Font)
{
seek(fonts[Font].fdarrayOffset);
fonts[Font].FDArrayCount = getCard16();
fonts[Font].FDArrayOffsize = getCard8();
// Since we will change values inside the FDArray objects
// We increase its offsize to prevent errors
if (fonts[Font].FDArrayOffsize < 4)
fonts[Font].FDArrayOffsize++;
fonts[Font].FDArrayOffsets = getIndex(fonts[Font].fdarrayOffset);
}
/**
* The Process function extracts one font out of the CFF file and returns a
* subset version of the original.
* @param fontName - The name of the font to be taken out of the CFF
* @return The new font stream
* @throws IOException
*/
public byte[] Process(String fontName)throws IOException{
try
{
// Verify that the file is open
buf.reOpen();
// Find the Font that we will be dealing with
int j;
for (j=0; j<fonts.length; j++)
if (fontName.equals(fonts[j].name)) break;
if (j==fonts.length) return null;
// Calc the bias for the global subrs
if (gsubrIndexOffset >= 0)
GBias = CalcBias(gsubrIndexOffset,j);
// Prepare the new CharStrings Index
BuildNewCharString(j);
// Prepare the new Global and Local Subrs Indices
BuildNewLGSubrs(j);
// Build the new file
byte[] Ret = BuildNewFile(j);
return Ret;
}
finally {
try {
buf.close();
}
catch (Exception e) {
// empty on purpose
}
}
}
/**
* Function calcs bias according to the CharString type and the count
* of the subrs
* @param Offset The offset to the relevant subrs index
* @param Font the font
* @return The calculated Bias
*/
protected int CalcBias(int Offset,int Font)
{
seek(Offset);
int nSubrs = getCard16();
// If type==1 -> bias=0
if (fonts[Font].CharstringType == 1)
return 0;
// else calc according to the count
else if (nSubrs < 1240)
return 107;
else if (nSubrs < 33900)
return 1131;
else
return 32768;
}
/**
*Function uses BuildNewIndex to create the new index of the subset charstrings
* @param FontIndex the font
* @throws IOException
*/
protected void BuildNewCharString(int FontIndex) throws IOException
{
NewCharStringsIndex = BuildNewIndex(fonts[FontIndex].charstringsOffsets,GlyphsUsed,ENDCHAR_OP);
}
/**
* Function builds the new local & global subsrs indices. IF CID then All of
* the FD Array lsubrs will be subsetted.
* @param Font the font
* @throws IOException
*/
@SuppressWarnings("unchecked")
protected void BuildNewLGSubrs(int Font)throws IOException
{
// If the font is CID then the lsubrs are divided into FontDicts.
// for each FD array the lsubrs will be subsetted.
if(fonts[Font].isCID)
{
// Init the hashmap-array and the arraylist-array to hold the subrs used
// in each private dict.
hSubrsUsed = new HashMap[fonts[Font].fdprivateOffsets.length];
lSubrsUsed = new ArrayList[fonts[Font].fdprivateOffsets.length];
// A [][] which will store the byte array for each new FD Array lsubs index
NewLSubrsIndex = new byte[fonts[Font].fdprivateOffsets.length][];
// An array to hold the offset for each Lsubr index
fonts[Font].PrivateSubrsOffset = new int[fonts[Font].fdprivateOffsets.length];
// A [][] which will store the offset array for each lsubr index
fonts[Font].PrivateSubrsOffsetsArray = new int[fonts[Font].fdprivateOffsets.length][];
// Put the FDarrayUsed into a list
ArrayList<Integer> FDInList = new ArrayList<Integer>(FDArrayUsed);
// For each FD array which is used subset the lsubr
for (int j=0;j<FDInList.size();j++)
{
// The FDArray index, Hash Map, Array List to work on
int FD = FDInList.get(j).intValue();
hSubrsUsed[FD] = new HashMap<Integer, int[]>();
lSubrsUsed[FD] = new ArrayList<Integer>();
//Reads the private dicts looking for the subr operator and
// store both the offset for the index and its offset array
BuildFDSubrsOffsets(Font,FD);
// Verify that FDPrivate has a LSubrs index
if(fonts[Font].PrivateSubrsOffset[FD]>=0)
{
//Scans the Charstring data storing the used Local and Global subroutines
// by the glyphs. Scans the Subrs recursively.
BuildSubrUsed(Font,FD,fonts[Font].PrivateSubrsOffset[FD],fonts[Font].PrivateSubrsOffsetsArray[FD],hSubrsUsed[FD],lSubrsUsed[FD]);
// Builds the New Local Subrs index
NewLSubrsIndex[FD] = BuildNewIndex(fonts[Font].PrivateSubrsOffsetsArray[FD],hSubrsUsed[FD],RETURN_OP);
}
}
}
// If the font is not CID && the Private Subr exists then subset:
else if (fonts[Font].privateSubrs>=0)
{
// Build the subrs offsets;
fonts[Font].SubrsOffsets = getIndex(fonts[Font].privateSubrs);
//Scans the Charstring data storing the used Local and Global subroutines
// by the glyphs. Scans the Subrs recursively.
BuildSubrUsed(Font,-1,fonts[Font].privateSubrs,fonts[Font].SubrsOffsets,hSubrsUsedNonCID,lSubrsUsedNonCID);
}
// For all fonts subset the Global Subroutines
// Scan the Global Subr Hashmap recursively on the Gsubrs
BuildGSubrsUsed(Font);
if (fonts[Font].privateSubrs>=0)
// Builds the New Local Subrs index
NewSubrsIndexNonCID = BuildNewIndex(fonts[Font].SubrsOffsets,hSubrsUsedNonCID,RETURN_OP);
//Builds the New Global Subrs index
NewGSubrsIndex = BuildNewIndexAndCopyAllGSubrs(gsubrOffsets, RETURN_OP);
}
/**
* The function finds for the FD array processed the local subr offset and its
* offset array.
* @param Font the font
* @param FD The FDARRAY processed
*/
protected void BuildFDSubrsOffsets(int Font,int FD)
{
// Initiate to -1 to indicate lsubr operator present
fonts[Font].PrivateSubrsOffset[FD] = -1;
// Goto beginning of objects
seek(fonts[Font].fdprivateOffsets[FD]);
// While in the same object:
while (getPosition() < fonts[Font].fdprivateOffsets[FD]+fonts[Font].fdprivateLengths[FD])
{
getDictItem();
// If the dictItem is the "Subrs" then find and store offset,
if (key=="Subrs")
fonts[Font].PrivateSubrsOffset[FD] = ((Integer)args[0]).intValue()+fonts[Font].fdprivateOffsets[FD];
}
//Read the lsubr index if the lsubr was found
if (fonts[Font].PrivateSubrsOffset[FD] >= 0)
fonts[Font].PrivateSubrsOffsetsArray[FD] = getIndex(fonts[Font].PrivateSubrsOffset[FD]);
}
/**
* Function uses ReadAsubr on the glyph used to build the LSubr & Gsubr HashMap.
* The HashMap (of the lsubr only) is then scanned recursively for Lsubr & Gsubrs
* calls.
* @param Font the font
* @param FD FD array processed. 0 indicates function was called by non CID font
* @param SubrOffset the offset to the subr index to calc the bias
* @param SubrsOffsets the offset array of the subr index
* @param hSubr HashMap of the subrs used
* @param lSubr ArrayList of the subrs used
*/
protected void BuildSubrUsed(int Font,int FD,int SubrOffset,int[] SubrsOffsets,HashMap<Integer, int[]> hSubr,ArrayList<Integer> lSubr)
{
// Calc the Bias for the subr index
int LBias = CalcBias(SubrOffset,Font);
// For each glyph used find its GID, start & end pos
for (int i=0;i<glyphsInList.size();i++)
{
int glyph = glyphsInList.get(i).intValue();
int Start = fonts[Font].charstringsOffsets[glyph];
int End = fonts[Font].charstringsOffsets[glyph+1];
// IF CID:
if (FD >= 0)
{
EmptyStack();
NumOfHints=0;
// Using FDSELECT find the FD Array the glyph belongs to.
int GlyphFD = fonts[Font].FDSelect[glyph];
// If the Glyph is part of the FD being processed
if (GlyphFD == FD)
// Find the Subrs called by the glyph and insert to hash:
ReadASubr(Start,End,GBias,LBias,hSubr,lSubr,SubrsOffsets);
}
else
// If the font is not CID
//Find the Subrs called by the glyph and insert to hash:
ReadASubr(Start,End,GBias,LBias,hSubr,lSubr,SubrsOffsets);
}
// For all Lsubrs used, check recursively for Lsubr & Gsubr used
for (int i=0;i<lSubr.size();i++)
{
// Pop the subr value from the hash
int Subr = lSubr.get(i).intValue();
// Ensure the Lsubr call is valid
if (Subr < SubrsOffsets.length-1 && Subr>=0)
{
// Read and process the subr
int Start = SubrsOffsets[Subr];
int End = SubrsOffsets[Subr+1];
ReadASubr(Start,End,GBias,LBias,hSubr,lSubr,SubrsOffsets);
}
}
}
/**
* Function scans the Glsubr used ArrayList to find recursive calls
* to Gsubrs and adds to Hashmap & ArrayList
* @param Font the font
*/
protected void BuildGSubrsUsed(int Font)
{
int LBias = 0;
int SizeOfNonCIDSubrsUsed = 0;
if (fonts[Font].privateSubrs>=0)
{
LBias = CalcBias(fonts[Font].privateSubrs,Font);
SizeOfNonCIDSubrsUsed = lSubrsUsedNonCID.size();
}
// For each global subr used
for (int i=0;i<lGSubrsUsed.size();i++)
{
//Pop the value + check valid
int Subr = lGSubrsUsed.get(i).intValue();
if (Subr < gsubrOffsets.length-1 && Subr>=0)
{
// Read the subr and process
int Start = gsubrOffsets[Subr];
int End = gsubrOffsets[Subr+1];
if (fonts[Font].isCID)
ReadASubr(Start,End,GBias,0,hGSubrsUsed,lGSubrsUsed,null);
else
{
ReadASubr(Start,End,GBias,LBias,hSubrsUsedNonCID,lSubrsUsedNonCID,fonts[Font].SubrsOffsets);
if (SizeOfNonCIDSubrsUsed < lSubrsUsedNonCID.size())
{
for (int j=SizeOfNonCIDSubrsUsed;j<lSubrsUsedNonCID.size();j++)
{
//Pop the value + check valid
int LSubr = lSubrsUsedNonCID.get(j).intValue();
if (LSubr < fonts[Font].SubrsOffsets.length-1 && LSubr>=0)
{
// Read the subr and process
int LStart = fonts[Font].SubrsOffsets[LSubr];
int LEnd = fonts[Font].SubrsOffsets[LSubr+1];
ReadASubr(LStart,LEnd,GBias,LBias,hSubrsUsedNonCID,lSubrsUsedNonCID,fonts[Font].SubrsOffsets);
}
}
SizeOfNonCIDSubrsUsed = lSubrsUsedNonCID.size();
}
}
}
}
}
/**
* The function reads a subrs (glyph info) between begin and end.
* Adds calls to a Lsubr to the hSubr and lSubrs.
* Adds calls to a Gsubr to the hGSubr and lGSubrs.
* @param begin the start point of the subr
* @param end the end point of the subr
* @param GBias the bias of the Global Subrs
* @param LBias the bias of the Local Subrs
* @param hSubr the HashMap for the lSubrs
* @param lSubr the ArrayList for the lSubrs
*/
protected void ReadASubr(int begin,int end,int GBias,int LBias,HashMap<Integer, int[]> hSubr,ArrayList<Integer> lSubr,int[] LSubrsOffsets)
{
// Clear the stack for the subrs
EmptyStack();
NumOfHints = 0;
// Goto beginning of the subr
seek(begin);
while (getPosition() < end)
{
// Read the next command
ReadCommand();
int pos = getPosition();
Object TopElement=null;
if (arg_count > 0)
TopElement = args[arg_count-1];
int NumOfArgs = arg_count;
// Check the modification needed on the Argument Stack according to key;
HandelStack();
// a call to a Lsubr
if (key=="callsubr")
{
// Verify that arguments are passed
if (NumOfArgs > 0)
{
// Calc the index of the Subrs
int Subr = ((Integer)TopElement).intValue() + LBias;
// If the subr isn't in the HashMap -> Put in
if (!hSubr.containsKey(Integer.valueOf (Subr)))
{
hSubr.put(Integer.valueOf(Subr),null);
lSubr.add(Integer.valueOf(Subr));
}
CalcHints(LSubrsOffsets[Subr],LSubrsOffsets[Subr+1],LBias,GBias,LSubrsOffsets);
seek(pos);
}
}
// a call to a Gsubr
else if (key=="callgsubr")
{
// Verify that arguments are passed
if (NumOfArgs > 0)
{
// Calc the index of the Subrs
int Subr = ((Integer)TopElement).intValue() + GBias;
// If the subr isn't in the HashMap -> Put in
if (!hGSubrsUsed.containsKey(Integer.valueOf (Subr)))
{
hGSubrsUsed.put(Integer.valueOf(Subr),null);
lGSubrsUsed.add(Integer.valueOf(Subr));
}
CalcHints(gsubrOffsets[Subr],gsubrOffsets[Subr+1],LBias,GBias,LSubrsOffsets);
seek(pos);
}
}
// A call to "stem"
else if (key == "hstem" || key == "vstem" || key == "hstemhm" || key == "vstemhm") {
// Increment the NumOfHints by the number couples of of arguments
NumOfHints += NumOfArgs / 2;
}
// A call to "mask"
else if (key == "hintmask" || key == "cntrmask")
{
// if stack is not empty the reason is vstem implicit definition
// See Adobe Technical Note #5177, page 25, hintmask usage example.
NumOfHints += NumOfArgs/2;
// Compute the size of the mask
int SizeOfMask = NumOfHints/8;
if (NumOfHints%8 != 0 || SizeOfMask == 0)
SizeOfMask++;
// Continue the pointer in SizeOfMask steps
for (int i=0;i<SizeOfMask;i++)
getCard8();
}
}
}
/**
* Function Checks how the current operator effects the run time stack after being run
* An operator may increase or decrease the stack size
*/
protected void HandelStack()
{
// Find out what the operator does to the stack
int StackHandel = StackOpp();
if (StackHandel < 2)
{
// The operators that enlarge the stack by one
if (StackHandel==1)
PushStack();
// The operators that pop the stack
else
{
// Abs value for the for loop
StackHandel *= -1;
for (int i=0;i<StackHandel;i++)
PopStack();
}
}
// All other flush the stack
else
EmptyStack();
}
/**
* Function checks the key and return the change to the stack after the operator
* @return The change in the stack. 2-> flush the stack
*/
protected int StackOpp()
{
if (key == "ifelse")
return -3;
if (key == "roll" || key == "put")
return -2;
if (key == "callsubr" || key == "callgsubr" || key == "add" || key == "sub" ||
key == "div" || key == "mul" || key == "drop" || key == "and" ||
key == "or" || key == "eq")
return -1;
if (key == "abs" || key == "neg" || key == "sqrt" || key == "exch" ||
key == "index" || key == "get" || key == "not" || key == "return")
return 0;
if (key == "random" || key == "dup")
return 1;
return 2;
}
/**
* Empty the Type2 Stack
*
*/
protected void EmptyStack()
{
// Null the arguments
for (int i=0; i<arg_count; i++) args[i]=null;
arg_count = 0;
}
/**
* Pop one element from the stack
*
*/
protected void PopStack()
{
if (arg_count>0)
{
args[arg_count-1]=null;
arg_count--;
}
}
/**
* Add an item to the stack
*
*/
protected void PushStack()
{
arg_count++;
}
/**
* The function reads the next command after the file pointer is set
*/
protected void ReadCommand()
{
key = null;
boolean gotKey = false;
// Until a key is found
while (!gotKey) {
// Read the first Char
char b0 = getCard8();
// decode according to the type1/type2 format
if (b0 == 28) // the two next bytes represent a short int;
{
int first = getCard8();
int second = getCard8();
args[arg_count] = Integer.valueOf(first<<8 | second);
arg_count++;
continue;
}
if (b0 >= 32 && b0 <= 246) // The byte read is the byte;
{
args[arg_count] = Integer.valueOf(b0 - 139);
arg_count++;
continue;
}
if (b0 >= 247 && b0 <= 250) // The byte read and the next byte constitute a short int
{
int w = getCard8();
args[arg_count] = Integer.valueOf((b0-247)*256 + w + 108);
arg_count++;
continue;
}
if (b0 >= 251 && b0 <= 254)// Same as above except negative
{
int w = getCard8();
args[arg_count] = Integer.valueOf(-(b0-251)*256 - w - 108);
arg_count++;
continue;
}
if (b0 == 255)// The next for bytes represent a double.
{
int first = getCard8();
int second = getCard8();
int third = getCard8();
int fourth = getCard8();
args[arg_count] = Integer.valueOf(first<<24 | second<<16 | third<<8 | fourth);
arg_count++;
continue;
}
if (b0<=31 && b0 != 28) // An operator was found.. Set Key.
{
gotKey=true;
// 12 is an escape command therefore the next byte is a part
// of this command
if (b0 == 12)
{
int b1 = getCard8();
if (b1>SubrsEscapeFuncs.length-1)
b1 = SubrsEscapeFuncs.length-1;
key = SubrsEscapeFuncs[b1];
}
else
key = SubrsFunctions[b0];
continue;
}
}
}
/**
* The function reads the subroutine and returns the number of the hint in it.
* If a call to another subroutine is found the function calls recursively.
* @param begin the start point of the subr
* @param end the end point of the subr
* @param LBias the bias of the Local Subrs
* @param GBias the bias of the Global Subrs
* @param LSubrsOffsets The Offsets array of the subroutines
* @return The number of hints in the subroutine read.
*/
protected int CalcHints(int begin,int end,int LBias,int GBias,int[] LSubrsOffsets)
{
// Goto beginning of the subr
seek(begin);
while (getPosition() < end)
{
// Read the next command
ReadCommand();
int pos = getPosition();
Object TopElement = null;
if (arg_count>0)
TopElement = args[arg_count-1];
int NumOfArgs = arg_count;
//Check the modification needed on the Argument Stack according to key;
HandelStack();
// a call to a Lsubr
if (key=="callsubr")
{
if (NumOfArgs>0)
{
int Subr = ((Integer)TopElement).intValue() + LBias;
CalcHints(LSubrsOffsets[Subr],LSubrsOffsets[Subr+1],LBias,GBias,LSubrsOffsets);
seek(pos);
}
}
// a call to a Gsubr
else if (key=="callgsubr")
{
if (NumOfArgs>0)
{
int Subr = ((Integer)TopElement).intValue() + GBias;
CalcHints(gsubrOffsets[Subr],gsubrOffsets[Subr+1],LBias,GBias,LSubrsOffsets);
seek(pos);
}
}
// A call to "stem"
else if (key == "hstem" || key == "vstem" || key == "hstemhm" || key == "vstemhm")
// Increment the NumOfHints by the number couples of of arguments
NumOfHints += NumOfArgs/2;
// A call to "mask"
else if (key == "hintmask" || key == "cntrmask")
{
// Compute the size of the mask
int SizeOfMask = NumOfHints/8;
if (NumOfHints%8 != 0 || SizeOfMask == 0)
SizeOfMask++;
// Continue the pointer in SizeOfMask steps
for (int i=0;i<SizeOfMask;i++)
getCard8();
}
}
return NumOfHints;
}
/**
* Function builds the new offset array, object array and assembles the index.
* used for creating the glyph and subrs subsetted index
* @param Offsets the offset array of the original index
* @param Used the hashmap of the used objects
* @param OperatorForUnusedEntries the operator inserted into the data stream for unused entries
* @return the new index subset version
* @throws IOException
*/
protected byte[] BuildNewIndex(int[] Offsets,HashMap<Integer, int[]> Used,byte OperatorForUnusedEntries) throws IOException
{
int unusedCount = 0;
int Offset=0;
int[] NewOffsets = new int[Offsets.length];
// Build the Offsets Array for the Subset
for (int i=0;i<Offsets.length;++i)
{
NewOffsets[i] = Offset;
// If the object in the offset is also present in the used
// HashMap then increment the offset var by its size
if (Used.containsKey(Integer.valueOf(i))) {
Offset += Offsets[i+1] - Offsets[i];
} else {
// Else the same offset is kept in i+1.
unusedCount++;
}
}
// Offset var determines the size of the object array
byte[] NewObjects = new byte[Offset+unusedCount];
// Build the new Object array
int unusedOffset = 0;
for (int i=0;i<Offsets.length-1;++i)
{
int start = NewOffsets[i];
int end = NewOffsets[i+1];
NewOffsets[i] = start+unusedOffset;
// If start != End then the Object is used
// So, we will copy the object data from the font file
if (start != end)
{
// All offsets are Global Offsets relative to the beginning of the font file.
// Jump the file pointer to the start address to read from.
buf.seek(Offsets[i]);
// Read from the buffer and write into the array at start.
buf.readFully(NewObjects, start+unusedOffset, end-start);
} else {
NewObjects[start+unusedOffset] = OperatorForUnusedEntries;
unusedOffset++;
}
}
NewOffsets[Offsets.length-1] += unusedOffset;
// Use AssembleIndex to build the index from the offset & object arrays
return AssembleIndex(NewOffsets,NewObjects);
}
/**
* Function builds the new offset array, object array and assembles the index.
* used for creating the glyph and subrs subsetted index
*
* @param Offsets the offset array of the original index
* @param OperatorForUnusedEntries the operator inserted into the data stream for unused entries
* @return the new index subset version
* @throws java.io.IOException
*/
protected byte[] BuildNewIndexAndCopyAllGSubrs(int[] Offsets, byte OperatorForUnusedEntries) throws java.io.IOException {
int unusedCount = 0;
int Offset = 0;
int[] NewOffsets = new int[Offsets.length];
// Build the Offsets Array for the Subset
for (int i = 0; i < Offsets.length - 1; ++i) {
NewOffsets[i] = Offset;
Offset += Offsets[i + 1] - Offsets[i];
}