-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
evaluator.js
5218 lines (4794 loc) · 163 KB
/
evaluator.js
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
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
AbortException,
assert,
FONT_IDENTITY_MATRIX,
FormatError,
IDENTITY_MATRIX,
info,
isArrayEqual,
normalizeUnicode,
OPS,
shadow,
stringToPDFString,
TextRenderingMode,
Util,
warn,
} from "../shared/util.js";
import { CMapFactory, IdentityCMap } from "./cmap.js";
import { Cmd, Dict, EOF, isName, Name, Ref, RefSet } from "./primitives.js";
import { ErrorFont, Font } from "./fonts.js";
import {
getEncoding,
MacRomanEncoding,
StandardEncoding,
SymbolSetEncoding,
WinAnsiEncoding,
ZapfDingbatsEncoding,
} from "./encodings.js";
import {
getFontNameToFileMap,
getSerifFonts,
getStandardFontName,
getStdFontMap,
getSymbolsFonts,
isKnownFontName,
} from "./standard_fonts.js";
import { getTilingPatternIR, Pattern } from "./pattern.js";
import { getXfaFontDict, getXfaFontName } from "./xfa_fonts.js";
import { IdentityToUnicodeMap, ToUnicodeMap } from "./to_unicode_map.js";
import { isNumberArray, lookupMatrix, lookupNormalRect } from "./core_utils.js";
import { isPDFFunction, PDFFunctionFactory } from "./function.js";
import { Lexer, Parser } from "./parser.js";
import {
LocalColorSpaceCache,
LocalGStateCache,
LocalImageCache,
LocalTilingPatternCache,
RegionalImageCache,
} from "./image_utils.js";
import { BaseStream } from "./base_stream.js";
import { bidi } from "./bidi.js";
import { ColorSpace } from "./colorspace.js";
import { DecodeStream } from "./decode_stream.js";
import { FontFlags } from "./fonts_utils.js";
import { getFontSubstitution } from "./font_substitutions.js";
import { getGlyphsUnicode } from "./glyphlist.js";
import { getMetrics } from "./metrics.js";
import { getUnicodeForGlyph } from "./unicode.js";
import { ImageResizer } from "./image_resizer.js";
import { JpegStream } from "./jpeg_stream.js";
import { MurmurHash3_64 } from "../shared/murmurhash3.js";
import { OperatorList } from "./operator_list.js";
import { PDFImage } from "./image.js";
import { Stream } from "./stream.js";
const DefaultPartialEvaluatorOptions = Object.freeze({
maxImageSize: -1,
disableFontFace: false,
ignoreErrors: false,
isEvalSupported: true,
isOffscreenCanvasSupported: false,
isImageDecoderSupported: false,
canvasMaxAreaInBytes: -1,
fontExtraProperties: false,
useSystemFonts: true,
cMapUrl: null,
standardFontDataUrl: null,
});
const PatternType = {
TILING: 1,
SHADING: 2,
};
// Optionally avoid sending individual, or very few, text chunks to reduce
// `postMessage` overhead with ReadableStream (see issue 13962).
//
// PLEASE NOTE: This value should *not* be too large (it's used as a lower limit
// in `enqueueChunk`), since that would cause streaming of textContent to become
// essentially useless in practice by sending all (or most) chunks at once.
// Also, a too large value would (indirectly) affect the main-thread `textLayer`
// building negatively by forcing all textContent to be handled at once, which
// could easily end up hurting *overall* performance (e.g. rendering as well).
const TEXT_CHUNK_BATCH_SIZE = 10;
const deferred = Promise.resolve();
// Convert PDF blend mode names to HTML5 blend mode names.
function normalizeBlendMode(value, parsingArray = false) {
if (Array.isArray(value)) {
// Use the first *supported* BM value in the Array (fixes issue11279.pdf).
for (const val of value) {
const maybeBM = normalizeBlendMode(val, /* parsingArray = */ true);
if (maybeBM) {
return maybeBM;
}
}
warn(`Unsupported blend mode Array: ${value}`);
return "source-over";
}
if (!(value instanceof Name)) {
if (parsingArray) {
return null;
}
return "source-over";
}
switch (value.name) {
case "Normal":
case "Compatible":
return "source-over";
case "Multiply":
return "multiply";
case "Screen":
return "screen";
case "Overlay":
return "overlay";
case "Darken":
return "darken";
case "Lighten":
return "lighten";
case "ColorDodge":
return "color-dodge";
case "ColorBurn":
return "color-burn";
case "HardLight":
return "hard-light";
case "SoftLight":
return "soft-light";
case "Difference":
return "difference";
case "Exclusion":
return "exclusion";
case "Hue":
return "hue";
case "Saturation":
return "saturation";
case "Color":
return "color";
case "Luminosity":
return "luminosity";
}
if (parsingArray) {
return null;
}
warn(`Unsupported blend mode: ${value.name}`);
return "source-over";
}
function addLocallyCachedImageOps(opList, data) {
if (data.objId) {
opList.addDependency(data.objId);
}
opList.addImageOps(data.fn, data.args, data.optionalContent, data.hasMask);
if (data.fn === OPS.paintImageMaskXObject && data.args[0]?.count > 0) {
data.args[0].count++;
}
}
// Trying to minimize Date.now() usage and check every 100 time.
class TimeSlotManager {
static TIME_SLOT_DURATION_MS = 20;
static CHECK_TIME_EVERY = 100;
constructor() {
this.reset();
}
check() {
if (++this.checked < TimeSlotManager.CHECK_TIME_EVERY) {
return false;
}
this.checked = 0;
return this.endTime <= Date.now();
}
reset() {
this.endTime = Date.now() + TimeSlotManager.TIME_SLOT_DURATION_MS;
this.checked = 0;
}
}
class PartialEvaluator {
constructor({
xref,
handler,
pageIndex,
idFactory,
fontCache,
builtInCMapCache,
standardFontDataCache,
globalImageCache,
systemFontCache,
options = null,
}) {
this.xref = xref;
this.handler = handler;
this.pageIndex = pageIndex;
this.idFactory = idFactory;
this.fontCache = fontCache;
this.builtInCMapCache = builtInCMapCache;
this.standardFontDataCache = standardFontDataCache;
this.globalImageCache = globalImageCache;
this.systemFontCache = systemFontCache;
this.options = options || DefaultPartialEvaluatorOptions;
this.type3FontRefs = null;
this._regionalImageCache = new RegionalImageCache();
this._fetchBuiltInCMapBound = this.fetchBuiltInCMap.bind(this);
ImageResizer.setOptions(this.options);
JpegStream.setOptions(this.options);
}
/**
* Since Functions are only cached (locally) by reference, we can share one
* `PDFFunctionFactory` instance within this `PartialEvaluator` instance.
*/
get _pdfFunctionFactory() {
const pdfFunctionFactory = new PDFFunctionFactory({
xref: this.xref,
isEvalSupported: this.options.isEvalSupported,
});
return shadow(this, "_pdfFunctionFactory", pdfFunctionFactory);
}
get parsingType3Font() {
return !!this.type3FontRefs;
}
clone(newOptions = null) {
const newEvaluator = Object.create(this);
newEvaluator.options = Object.assign(
Object.create(null),
this.options,
newOptions
);
return newEvaluator;
}
hasBlendModes(resources, nonBlendModesSet) {
if (!(resources instanceof Dict)) {
return false;
}
if (resources.objId && nonBlendModesSet.has(resources.objId)) {
return false;
}
const processed = new RefSet(nonBlendModesSet);
if (resources.objId) {
processed.put(resources.objId);
}
const nodes = [resources],
xref = this.xref;
while (nodes.length) {
const node = nodes.shift();
// First check the current resources for blend modes.
const graphicStates = node.get("ExtGState");
if (graphicStates instanceof Dict) {
for (let graphicState of graphicStates.getRawValues()) {
if (graphicState instanceof Ref) {
if (processed.has(graphicState)) {
continue; // The ExtGState has already been processed.
}
try {
graphicState = xref.fetch(graphicState);
} catch (ex) {
// Avoid parsing a corrupt ExtGState more than once.
processed.put(graphicState);
info(`hasBlendModes - ignoring ExtGState: "${ex}".`);
continue;
}
}
if (!(graphicState instanceof Dict)) {
continue;
}
if (graphicState.objId) {
processed.put(graphicState.objId);
}
const bm = graphicState.get("BM");
if (bm instanceof Name) {
if (bm.name !== "Normal") {
return true;
}
continue;
}
if (bm !== undefined && Array.isArray(bm)) {
for (const element of bm) {
if (element instanceof Name && element.name !== "Normal") {
return true;
}
}
}
}
}
// Descend into the XObjects to look for more resources and blend modes.
const xObjects = node.get("XObject");
if (!(xObjects instanceof Dict)) {
continue;
}
for (let xObject of xObjects.getRawValues()) {
if (xObject instanceof Ref) {
if (processed.has(xObject)) {
// The XObject has already been processed, and by avoiding a
// redundant `xref.fetch` we can *significantly* reduce the load
// time for badly generated PDF files (fixes issue6961.pdf).
continue;
}
try {
xObject = xref.fetch(xObject);
} catch (ex) {
// Avoid parsing a corrupt XObject more than once.
processed.put(xObject);
info(`hasBlendModes - ignoring XObject: "${ex}".`);
continue;
}
}
if (!(xObject instanceof BaseStream)) {
continue;
}
if (xObject.dict.objId) {
processed.put(xObject.dict.objId);
}
const xResources = xObject.dict.get("Resources");
if (!(xResources instanceof Dict)) {
continue;
}
// Checking objId to detect an infinite loop.
if (xResources.objId && processed.has(xResources.objId)) {
continue;
}
nodes.push(xResources);
if (xResources.objId) {
processed.put(xResources.objId);
}
}
}
// When no blend modes exist, there's no need re-fetch/re-parse any of the
// processed `Ref`s again for subsequent pages. This helps reduce redundant
// `XRef.fetch` calls for some documents (e.g. issue6961.pdf).
for (const ref of processed) {
nonBlendModesSet.put(ref);
}
return false;
}
async #fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to fetch file "${url}" with "${response.statusText}".`
);
}
return new Uint8Array(await response.arrayBuffer());
}
async fetchBuiltInCMap(name) {
const cachedData = this.builtInCMapCache.get(name);
if (cachedData) {
return cachedData;
}
let data;
if (this.options.cMapUrl !== null) {
// Only compressed CMaps are (currently) supported here.
const cMapData = await this.#fetchData(
`${this.options.cMapUrl}${name}.bcmap`
);
data = { cMapData, isCompressed: true };
} else {
// Get the data on the main-thread instead.
data = await this.handler.sendWithPromise("FetchBuiltInCMap", { name });
}
// Cache the CMap data, to avoid fetching it repeatedly.
this.builtInCMapCache.set(name, data);
return data;
}
async fetchStandardFontData(name) {
const cachedData = this.standardFontDataCache.get(name);
if (cachedData) {
return new Stream(cachedData);
}
// The symbol fonts are not consistent across platforms, always load the
// standard font data for them.
if (
this.options.useSystemFonts &&
name !== "Symbol" &&
name !== "ZapfDingbats"
) {
return null;
}
const standardFontNameToFileName = getFontNameToFileMap(),
filename = standardFontNameToFileName[name];
let data;
try {
if (this.options.standardFontDataUrl !== null) {
data = await this.#fetchData(
`${this.options.standardFontDataUrl}${filename}`
);
} else {
// Get the data on the main-thread instead.
data = await this.handler.sendWithPromise("FetchStandardFontData", {
filename,
});
}
} catch (ex) {
warn(ex);
return null;
}
// Cache the "raw" standard font data, to avoid fetching it repeatedly
// (see e.g. issue 11399).
this.standardFontDataCache.set(name, data);
return new Stream(data);
}
async buildFormXObject(
resources,
xobj,
smask,
operatorList,
task,
initialState,
localColorSpaceCache
) {
const dict = xobj.dict;
const matrix = lookupMatrix(dict.getArray("Matrix"), null);
const bbox = lookupNormalRect(dict.getArray("BBox"), null);
let optionalContent, groupOptions;
if (dict.has("OC")) {
optionalContent = await this.parseMarkedContentProps(
dict.get("OC"),
resources
);
}
if (optionalContent !== undefined) {
operatorList.addOp(OPS.beginMarkedContentProps, ["OC", optionalContent]);
}
const group = dict.get("Group");
if (group) {
groupOptions = {
matrix,
bbox,
smask,
isolated: false,
knockout: false,
};
const groupSubtype = group.get("S");
let colorSpace = null;
if (isName(groupSubtype, "Transparency")) {
groupOptions.isolated = group.get("I") || false;
groupOptions.knockout = group.get("K") || false;
if (group.has("CS")) {
const cs = group.getRaw("CS");
const cachedColorSpace = ColorSpace.getCached(
cs,
this.xref,
localColorSpaceCache
);
if (cachedColorSpace) {
colorSpace = cachedColorSpace;
} else {
colorSpace = await this.parseColorSpace({
cs,
resources,
localColorSpaceCache,
});
}
}
}
if (smask?.backdrop) {
colorSpace ||= ColorSpace.singletons.rgb;
smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
}
operatorList.addOp(OPS.beginGroup, [groupOptions]);
}
// If it's a group, a new canvas will be created that is the size of the
// bounding box and translated to the correct position so we don't need to
// apply the bounding box to it.
const args = group ? [matrix, null] : [matrix, bbox];
operatorList.addOp(OPS.paintFormXObjectBegin, args);
await this.getOperatorList({
stream: xobj,
task,
resources: dict.get("Resources") || resources,
operatorList,
initialState,
});
operatorList.addOp(OPS.paintFormXObjectEnd, []);
if (group) {
operatorList.addOp(OPS.endGroup, [groupOptions]);
}
if (optionalContent !== undefined) {
operatorList.addOp(OPS.endMarkedContent, []);
}
}
_sendImgData(objId, imgData, cacheGlobally = false) {
if (
(typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) &&
imgData
) {
assert(Number.isInteger(imgData.dataLen), "Expected dataLen to be set.");
}
const transfers = imgData ? [imgData.bitmap || imgData.data.buffer] : null;
if (this.parsingType3Font || cacheGlobally) {
return this.handler.send(
"commonobj",
[objId, "Image", imgData],
transfers
);
}
return this.handler.send(
"obj",
[objId, this.pageIndex, "Image", imgData],
transfers
);
}
async buildPaintImageXObject({
resources,
image,
isInline = false,
operatorList,
cacheKey,
localImageCache,
localColorSpaceCache,
}) {
const dict = image.dict;
const imageRef = dict.objId;
const w = dict.get("W", "Width");
const h = dict.get("H", "Height");
if (!(w && typeof w === "number") || !(h && typeof h === "number")) {
warn("Image dimensions are missing, or not numbers.");
return;
}
const maxImageSize = this.options.maxImageSize;
if (maxImageSize !== -1 && w * h > maxImageSize) {
const msg = "Image exceeded maximum allowed size and was removed.";
if (this.options.ignoreErrors) {
warn(msg);
return;
}
throw new Error(msg);
}
let optionalContent;
if (dict.has("OC")) {
optionalContent = await this.parseMarkedContentProps(
dict.get("OC"),
resources
);
}
const imageMask = dict.get("IM", "ImageMask") || false;
let imgData, args;
if (imageMask) {
// This depends on a tmpCanvas being filled with the
// current fillStyle, such that processing the pixel
// data can't be done here. Instead of creating a
// complete PDFImage, only read the information needed
// for later.
const interpolate = dict.get("I", "Interpolate");
const bitStrideLength = (w + 7) >> 3;
const imgArray = image.getBytes(bitStrideLength * h);
const decode = dict.getArray("D", "Decode");
if (this.parsingType3Font) {
imgData = PDFImage.createRawMask({
imgArray,
width: w,
height: h,
imageIsFromDecodeStream: image instanceof DecodeStream,
inverseDecode: decode?.[0] > 0,
interpolate,
});
imgData.cached = !!cacheKey;
args = [imgData];
operatorList.addImageOps(
OPS.paintImageMaskXObject,
args,
optionalContent
);
if (cacheKey) {
const cacheData = {
fn: OPS.paintImageMaskXObject,
args,
optionalContent,
};
localImageCache.set(cacheKey, imageRef, cacheData);
if (imageRef) {
this._regionalImageCache.set(
/* name = */ null,
imageRef,
cacheData
);
}
}
return;
}
imgData = await PDFImage.createMask({
imgArray,
width: w,
height: h,
imageIsFromDecodeStream: image instanceof DecodeStream,
inverseDecode: decode?.[0] > 0,
interpolate,
isOffscreenCanvasSupported: this.options.isOffscreenCanvasSupported,
});
if (imgData.isSingleOpaquePixel) {
// Handles special case of mainly LaTeX documents which use image
// masks to draw lines with the current fill style.
operatorList.addImageOps(
OPS.paintSolidColorImageMask,
[],
optionalContent
);
if (cacheKey) {
const cacheData = {
fn: OPS.paintSolidColorImageMask,
args: [],
optionalContent,
};
localImageCache.set(cacheKey, imageRef, cacheData);
if (imageRef) {
this._regionalImageCache.set(
/* name = */ null,
imageRef,
cacheData
);
}
}
return;
}
const objId = `mask_${this.idFactory.createObjId()}`;
operatorList.addDependency(objId);
imgData.dataLen = imgData.bitmap
? imgData.width * imgData.height * 4
: imgData.data.length;
this._sendImgData(objId, imgData);
args = [
{
data: objId,
width: imgData.width,
height: imgData.height,
interpolate: imgData.interpolate,
count: 1,
},
];
operatorList.addImageOps(
OPS.paintImageMaskXObject,
args,
optionalContent
);
if (cacheKey) {
const cacheData = {
objId,
fn: OPS.paintImageMaskXObject,
args,
optionalContent,
};
localImageCache.set(cacheKey, imageRef, cacheData);
if (imageRef) {
this._regionalImageCache.set(/* name = */ null, imageRef, cacheData);
}
}
return;
}
const SMALL_IMAGE_DIMENSIONS = 200;
const hasMask = dict.has("SMask") || dict.has("Mask");
// Inlining small images into the queue as RGB data
if (isInline && w + h < SMALL_IMAGE_DIMENSIONS && !hasMask) {
try {
const imageObj = new PDFImage({
xref: this.xref,
res: resources,
image,
isInline,
pdfFunctionFactory: this._pdfFunctionFactory,
localColorSpaceCache,
});
// We force the use of RGBA_32BPP images here, because we can't handle
// any other kind.
imgData = await imageObj.createImageData(
/* forceRGBA = */ true,
/* isOffscreenCanvasSupported = */ false
);
operatorList.isOffscreenCanvasSupported =
this.options.isOffscreenCanvasSupported;
operatorList.addImageOps(
OPS.paintInlineImageXObject,
[imgData],
optionalContent
);
} catch (reason) {
const msg = `Unable to decode inline image: "${reason}".`;
if (!this.options.ignoreErrors) {
throw new Error(msg);
}
warn(msg);
}
return;
}
// If there is no imageMask, create the PDFImage and a lot
// of image processing can be done here.
let objId = `img_${this.idFactory.createObjId()}`,
cacheGlobally = false;
if (this.parsingType3Font) {
objId = `${this.idFactory.getDocId()}_type3_${objId}`;
} else if (cacheKey && imageRef) {
cacheGlobally = this.globalImageCache.shouldCache(
imageRef,
this.pageIndex
);
if (cacheGlobally) {
assert(!isInline, "Cannot cache an inline image globally.");
objId = `${this.idFactory.getDocId()}_${objId}`;
}
}
// Ensure that the dependency is added before the image is decoded.
operatorList.addDependency(objId);
args = [objId, w, h];
operatorList.addImageOps(
OPS.paintImageXObject,
args,
optionalContent,
hasMask
);
if (cacheGlobally) {
if (this.globalImageCache.hasDecodeFailed(imageRef)) {
this.globalImageCache.setData(imageRef, {
objId,
fn: OPS.paintImageXObject,
args,
optionalContent,
hasMask,
byteSize: 0, // Data is `null`, since decoding failed previously.
});
this._sendImgData(objId, /* imgData = */ null, cacheGlobally);
return;
}
// For large (at least 500x500) or more complex images that we'll cache
// globally, check if the image is still cached locally on the main-thread
// to avoid having to re-parse the image (since that can be slow).
if (w * h > 250000 || hasMask) {
const localLength = await this.handler.sendWithPromise("commonobj", [
objId,
"CopyLocalImage",
{ imageRef },
]);
if (localLength) {
this.globalImageCache.setData(imageRef, {
objId,
fn: OPS.paintImageXObject,
args,
optionalContent,
hasMask,
byteSize: 0, // Temporary entry, to avoid `setData` returning early.
});
this.globalImageCache.addByteSize(imageRef, localLength);
return;
}
}
}
PDFImage.buildImage({
xref: this.xref,
res: resources,
image,
isInline,
pdfFunctionFactory: this._pdfFunctionFactory,
localColorSpaceCache,
})
.then(async imageObj => {
imgData = await imageObj.createImageData(
/* forceRGBA = */ false,
/* isOffscreenCanvasSupported = */ this.options
.isOffscreenCanvasSupported
);
imgData.dataLen = imgData.bitmap
? imgData.width * imgData.height * 4
: imgData.data.length;
imgData.ref = imageRef;
if (cacheGlobally) {
this.globalImageCache.addByteSize(imageRef, imgData.dataLen);
}
return this._sendImgData(objId, imgData, cacheGlobally);
})
.catch(reason => {
warn(`Unable to decode image "${objId}": "${reason}".`);
if (imageRef) {
this.globalImageCache.addDecodeFailed(imageRef);
}
return this._sendImgData(objId, /* imgData = */ null, cacheGlobally);
});
if (cacheKey) {
const cacheData = {
objId,
fn: OPS.paintImageXObject,
args,
optionalContent,
hasMask,
};
localImageCache.set(cacheKey, imageRef, cacheData);
if (imageRef) {
this._regionalImageCache.set(/* name = */ null, imageRef, cacheData);
if (cacheGlobally) {
this.globalImageCache.setData(imageRef, {
objId,
fn: OPS.paintImageXObject,
args,
optionalContent,
hasMask,
byteSize: 0, // Temporary entry, note `addByteSize` above.
});
}
}
}
}
handleSMask(
smask,
resources,
operatorList,
task,
stateManager,
localColorSpaceCache
) {
const smaskContent = smask.get("G");
const smaskOptions = {
subtype: smask.get("S").name,
backdrop: smask.get("BC"),
};
// The SMask might have a alpha/luminosity value transfer function --
// we will build a map of integer values in range 0..255 to be fast.
const transferObj = smask.get("TR");
if (isPDFFunction(transferObj)) {
const transferFn = this._pdfFunctionFactory.create(transferObj);
const transferMap = new Uint8Array(256);
const tmp = new Float32Array(1);
for (let i = 0; i < 256; i++) {
tmp[0] = i / 255;
transferFn(tmp, 0, tmp, 0);
transferMap[i] = (tmp[0] * 255) | 0;
}
smaskOptions.transferMap = transferMap;
}
return this.buildFormXObject(
resources,
smaskContent,
smaskOptions,
operatorList,
task,
stateManager.state.clone(),
localColorSpaceCache
);
}
handleTransferFunction(tr) {
let transferArray;
if (Array.isArray(tr)) {
transferArray = tr;
} else if (isPDFFunction(tr)) {
transferArray = [tr];
} else {
return null; // Not a valid transfer function entry.
}
const transferMaps = [];
let numFns = 0,
numEffectfulFns = 0;
for (const entry of transferArray) {
const transferObj = this.xref.fetchIfRef(entry);
numFns++;
if (isName(transferObj, "Identity")) {
transferMaps.push(null);
continue;
} else if (!isPDFFunction(transferObj)) {
return null; // Not a valid transfer function object.
}
const transferFn = this._pdfFunctionFactory.create(transferObj);
const transferMap = new Uint8Array(256),
tmp = new Float32Array(1);
for (let j = 0; j < 256; j++) {
tmp[0] = j / 255;
transferFn(tmp, 0, tmp, 0);
transferMap[j] = (tmp[0] * 255) | 0;
}
transferMaps.push(transferMap);
numEffectfulFns++;
}
if (!(numFns === 1 || numFns === 4)) {
return null; // Only 1 or 4 functions are supported, by the specification.
}
if (numEffectfulFns === 0) {
return null; // Only /Identity transfer functions found, which are no-ops.
}
return transferMaps;
}
handleTilingType(
fn,
color,
resources,
pattern,
patternDict,
operatorList,
task,
localTilingPatternCache
) {
// Create an IR of the pattern code.
const tilingOpList = new OperatorList();
// Merge the available resources, to prevent issues when the patternDict
// is missing some /Resources entries (fixes issue6541.pdf).
const patternResources = Dict.merge({
xref: this.xref,
dictArray: [patternDict.get("Resources"), resources],