1 // Copyright 2016 The PDFium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6
7 #include "core/fpdfapi/page/cpdf_streamcontentparser.h"
8
9 #include <algorithm>
10 #include <memory>
11 #include <utility>
12 #include <vector>
13
14 #include "core/fpdfapi/font/cpdf_font.h"
15 #include "core/fpdfapi/font/cpdf_type3font.h"
16 #include "core/fpdfapi/page/cpdf_allstates.h"
17 #include "core/fpdfapi/page/cpdf_docpagedata.h"
18 #include "core/fpdfapi/page/cpdf_form.h"
19 #include "core/fpdfapi/page/cpdf_formobject.h"
20 #include "core/fpdfapi/page/cpdf_image.h"
21 #include "core/fpdfapi/page/cpdf_imageobject.h"
22 #include "core/fpdfapi/page/cpdf_meshstream.h"
23 #include "core/fpdfapi/page/cpdf_pageobject.h"
24 #include "core/fpdfapi/page/cpdf_pathobject.h"
25 #include "core/fpdfapi/page/cpdf_shadingobject.h"
26 #include "core/fpdfapi/page/cpdf_shadingpattern.h"
27 #include "core/fpdfapi/page/cpdf_streamparser.h"
28 #include "core/fpdfapi/page/cpdf_textobject.h"
29 #include "core/fpdfapi/parser/cpdf_array.h"
30 #include "core/fpdfapi/parser/cpdf_dictionary.h"
31 #include "core/fpdfapi/parser/cpdf_document.h"
32 #include "core/fpdfapi/parser/cpdf_name.h"
33 #include "core/fpdfapi/parser/cpdf_number.h"
34 #include "core/fpdfapi/parser/cpdf_reference.h"
35 #include "core/fpdfapi/parser/cpdf_stream.h"
36 #include "core/fpdfapi/parser/fpdf_parser_utility.h"
37 #include "core/fxcrt/autonuller.h"
38 #include "core/fxcrt/bytestring.h"
39 #include "core/fxcrt/fx_safe_types.h"
40 #include "core/fxcrt/scoped_set_insertion.h"
41 #include "core/fxcrt/stl_util.h"
42 #include "core/fxge/cfx_graphstate.h"
43 #include "core/fxge/cfx_graphstatedata.h"
44 #include "third_party/base/check.h"
45 #include "third_party/base/containers/contains.h"
46 #include "third_party/base/containers/span.h"
47 #include "third_party/base/no_destructor.h"
48 #include "third_party/base/notreached.h"
49
50 namespace {
51
52 constexpr int kMaxFormLevel = 40;
53
54 // Upper limit for the number of form XObjects within a form XObject.
55 constexpr int kFormCountLimit = 4096;
56
57 constexpr int kSingleCoordinatePair = 1;
58 constexpr int kTensorCoordinatePairs = 16;
59 constexpr int kCoonsCoordinatePairs = 12;
60 constexpr int kSingleColorPerPatch = 1;
61 constexpr int kQuadColorsPerPatch = 4;
62
63 const char kPathOperatorSubpath = 'm';
64 const char kPathOperatorLine = 'l';
65 const char kPathOperatorCubicBezier1 = 'c';
66 const char kPathOperatorCubicBezier2 = 'v';
67 const char kPathOperatorCubicBezier3 = 'y';
68 const char kPathOperatorClosePath = 'h';
69 const char kPathOperatorRectangle[] = "re";
70
GetShadingBBox(CPDF_ShadingPattern * pShading,const CFX_Matrix & matrix)71 CFX_FloatRect GetShadingBBox(CPDF_ShadingPattern* pShading,
72 const CFX_Matrix& matrix) {
73 ShadingType type = pShading->GetShadingType();
74 RetainPtr<const CPDF_Stream> pStream = ToStream(pShading->GetShadingObject());
75 RetainPtr<CPDF_ColorSpace> pCS = pShading->GetCS();
76 if (!pStream || !pCS)
77 return CFX_FloatRect();
78
79 CPDF_MeshStream stream(type, pShading->GetFuncs(), std::move(pStream),
80 std::move(pCS));
81 if (!stream.Load())
82 return CFX_FloatRect();
83
84 CFX_FloatRect rect;
85 bool update_rect = false;
86 bool bGouraud = type == kFreeFormGouraudTriangleMeshShading ||
87 type == kLatticeFormGouraudTriangleMeshShading;
88
89 int point_count;
90 if (type == kTensorProductPatchMeshShading)
91 point_count = kTensorCoordinatePairs;
92 else if (type == kCoonsPatchMeshShading)
93 point_count = kCoonsCoordinatePairs;
94 else
95 point_count = kSingleCoordinatePair;
96
97 int color_count;
98 if (type == kCoonsPatchMeshShading || type == kTensorProductPatchMeshShading)
99 color_count = kQuadColorsPerPatch;
100 else
101 color_count = kSingleColorPerPatch;
102
103 while (!stream.IsEOF()) {
104 uint32_t flag = 0;
105 if (type != kLatticeFormGouraudTriangleMeshShading) {
106 if (!stream.CanReadFlag())
107 break;
108 flag = stream.ReadFlag();
109 }
110
111 if (!bGouraud && flag) {
112 point_count -= 4;
113 color_count -= 2;
114 }
115
116 for (int i = 0; i < point_count; ++i) {
117 if (!stream.CanReadCoords())
118 break;
119
120 CFX_PointF origin = stream.ReadCoords();
121 if (update_rect) {
122 rect.UpdateRect(origin);
123 } else {
124 rect = CFX_FloatRect(origin);
125 update_rect = true;
126 }
127 }
128 FX_SAFE_UINT32 nBits = stream.Components();
129 nBits *= stream.ComponentBits();
130 nBits *= color_count;
131 if (!nBits.IsValid())
132 break;
133
134 stream.SkipBits(nBits.ValueOrDie());
135 if (bGouraud)
136 stream.ByteAlign();
137 }
138 return matrix.TransformRect(rect);
139 }
140
141 struct AbbrPair {
142 const char* abbr;
143 const char* full_name;
144 };
145
146 const AbbrPair kInlineKeyAbbr[] = {
147 {"BPC", "BitsPerComponent"}, {"CS", "ColorSpace"}, {"D", "Decode"},
148 {"DP", "DecodeParms"}, {"F", "Filter"}, {"H", "Height"},
149 {"IM", "ImageMask"}, {"I", "Interpolate"}, {"W", "Width"},
150 };
151
152 const AbbrPair kInlineValueAbbr[] = {
153 {"G", "DeviceGray"}, {"RGB", "DeviceRGB"},
154 {"CMYK", "DeviceCMYK"}, {"I", "Indexed"},
155 {"AHx", "ASCIIHexDecode"}, {"A85", "ASCII85Decode"},
156 {"LZW", "LZWDecode"}, {"Fl", "FlateDecode"},
157 {"RL", "RunLengthDecode"}, {"CCF", "CCITTFaxDecode"},
158 {"DCT", "DCTDecode"},
159 };
160
161 struct AbbrReplacementOp {
162 bool is_replace_key;
163 ByteString key;
164 ByteStringView replacement;
165 };
166
FindFullName(pdfium::span<const AbbrPair> table,ByteStringView abbr)167 ByteStringView FindFullName(pdfium::span<const AbbrPair> table,
168 ByteStringView abbr) {
169 for (const auto& pair : table) {
170 if (pair.abbr == abbr)
171 return ByteStringView(pair.full_name);
172 }
173 return ByteStringView();
174 }
175
176 void ReplaceAbbr(RetainPtr<CPDF_Object> pObj);
177
ReplaceAbbrInDictionary(CPDF_Dictionary * pDict)178 void ReplaceAbbrInDictionary(CPDF_Dictionary* pDict) {
179 std::vector<AbbrReplacementOp> replacements;
180 {
181 CPDF_DictionaryLocker locker(pDict);
182 for (const auto& it : locker) {
183 ByteString key = it.first;
184 ByteStringView fullname =
185 FindFullName(kInlineKeyAbbr, key.AsStringView());
186 if (!fullname.IsEmpty()) {
187 AbbrReplacementOp op;
188 op.is_replace_key = true;
189 op.key = std::move(key);
190 op.replacement = fullname;
191 replacements.push_back(op);
192 key = fullname;
193 }
194 RetainPtr<CPDF_Object> value = it.second;
195 if (value->IsName()) {
196 ByteString name = value->GetString();
197 fullname = FindFullName(kInlineValueAbbr, name.AsStringView());
198 if (!fullname.IsEmpty()) {
199 AbbrReplacementOp op;
200 op.is_replace_key = false;
201 op.key = key;
202 op.replacement = fullname;
203 replacements.push_back(op);
204 }
205 } else {
206 ReplaceAbbr(std::move(value));
207 }
208 }
209 }
210 for (const auto& op : replacements) {
211 if (op.is_replace_key)
212 pDict->ReplaceKey(op.key, ByteString(op.replacement));
213 else
214 pDict->SetNewFor<CPDF_Name>(op.key, ByteString(op.replacement));
215 }
216 }
217
ReplaceAbbrInArray(CPDF_Array * pArray)218 void ReplaceAbbrInArray(CPDF_Array* pArray) {
219 for (size_t i = 0; i < pArray->size(); ++i) {
220 RetainPtr<CPDF_Object> pElement = pArray->GetMutableObjectAt(i);
221 if (pElement->IsName()) {
222 ByteString name = pElement->GetString();
223 ByteStringView fullname =
224 FindFullName(kInlineValueAbbr, name.AsStringView());
225 if (!fullname.IsEmpty())
226 pArray->SetNewAt<CPDF_Name>(i, ByteString(fullname));
227 } else {
228 ReplaceAbbr(std::move(pElement));
229 }
230 }
231 }
232
ReplaceAbbr(RetainPtr<CPDF_Object> pObj)233 void ReplaceAbbr(RetainPtr<CPDF_Object> pObj) {
234 CPDF_Dictionary* pDict = pObj->AsMutableDictionary();
235 if (pDict) {
236 ReplaceAbbrInDictionary(pDict);
237 return;
238 }
239
240 CPDF_Array* pArray = pObj->AsMutableArray();
241 if (pArray)
242 ReplaceAbbrInArray(pArray);
243 }
244
245 } // namespace
246
CPDF_StreamContentParser(CPDF_Document * pDocument,RetainPtr<CPDF_Dictionary> pPageResources,RetainPtr<CPDF_Dictionary> pParentResources,const CFX_Matrix * pmtContentToUser,CPDF_PageObjectHolder * pObjHolder,RetainPtr<CPDF_Dictionary> pResources,const CFX_FloatRect & rcBBox,const CPDF_AllStates * pStates,CPDF_Form::RecursionState * recursion_state)247 CPDF_StreamContentParser::CPDF_StreamContentParser(
248 CPDF_Document* pDocument,
249 RetainPtr<CPDF_Dictionary> pPageResources,
250 RetainPtr<CPDF_Dictionary> pParentResources,
251 const CFX_Matrix* pmtContentToUser,
252 CPDF_PageObjectHolder* pObjHolder,
253 RetainPtr<CPDF_Dictionary> pResources,
254 const CFX_FloatRect& rcBBox,
255 const CPDF_AllStates* pStates,
256 CPDF_Form::RecursionState* recursion_state)
257 : m_pDocument(pDocument),
258 m_pPageResources(pPageResources),
259 m_pParentResources(pParentResources),
260 m_pResources(CPDF_Form::ChooseResourcesDict(pResources.Get(),
261 pParentResources.Get(),
262 pPageResources.Get())),
263 m_pObjectHolder(pObjHolder),
264 m_RecursionState(recursion_state),
265 m_BBox(rcBBox),
266 m_pCurStates(std::make_unique<CPDF_AllStates>()) {
267 if (pmtContentToUser)
268 m_mtContentToUser = *pmtContentToUser;
269 if (pStates) {
270 m_pCurStates->Copy(*pStates);
271 } else {
272 m_pCurStates->m_GeneralState.Emplace();
273 m_pCurStates->m_GraphState.Emplace();
274 m_pCurStates->m_TextState.Emplace();
275 m_pCurStates->m_ColorState.Emplace();
276 }
277
278 // Add the sentinel.
279 m_ContentMarksStack.push(std::make_unique<CPDF_ContentMarks>());
280 }
281
~CPDF_StreamContentParser()282 CPDF_StreamContentParser::~CPDF_StreamContentParser() {
283 ClearAllParams();
284 }
285
GetNextParamPos()286 int CPDF_StreamContentParser::GetNextParamPos() {
287 if (m_ParamCount == kParamBufSize) {
288 m_ParamStartPos++;
289 if (m_ParamStartPos == kParamBufSize) {
290 m_ParamStartPos = 0;
291 }
292 if (m_ParamBuf[m_ParamStartPos].m_Type == ContentParam::Type::kObject)
293 m_ParamBuf[m_ParamStartPos].m_pObject.Reset();
294
295 return m_ParamStartPos;
296 }
297 int index = m_ParamStartPos + m_ParamCount;
298 if (index >= kParamBufSize) {
299 index -= kParamBufSize;
300 }
301 m_ParamCount++;
302 return index;
303 }
304
AddNameParam(ByteStringView bsName)305 void CPDF_StreamContentParser::AddNameParam(ByteStringView bsName) {
306 ContentParam& param = m_ParamBuf[GetNextParamPos()];
307 param.m_Type = ContentParam::Type::kName;
308 param.m_Name = PDF_NameDecode(bsName);
309 }
310
AddNumberParam(ByteStringView str)311 void CPDF_StreamContentParser::AddNumberParam(ByteStringView str) {
312 ContentParam& param = m_ParamBuf[GetNextParamPos()];
313 param.m_Type = ContentParam::Type::kNumber;
314 param.m_Number = FX_Number(str);
315 }
316
AddObjectParam(RetainPtr<CPDF_Object> pObj)317 void CPDF_StreamContentParser::AddObjectParam(RetainPtr<CPDF_Object> pObj) {
318 ContentParam& param = m_ParamBuf[GetNextParamPos()];
319 param.m_Type = ContentParam::Type::kObject;
320 param.m_pObject = std::move(pObj);
321 }
322
ClearAllParams()323 void CPDF_StreamContentParser::ClearAllParams() {
324 uint32_t index = m_ParamStartPos;
325 for (uint32_t i = 0; i < m_ParamCount; i++) {
326 if (m_ParamBuf[index].m_Type == ContentParam::Type::kObject)
327 m_ParamBuf[index].m_pObject.Reset();
328 index++;
329 if (index == kParamBufSize)
330 index = 0;
331 }
332 m_ParamStartPos = 0;
333 m_ParamCount = 0;
334 }
335
GetObject(uint32_t index)336 RetainPtr<CPDF_Object> CPDF_StreamContentParser::GetObject(uint32_t index) {
337 if (index >= m_ParamCount) {
338 return nullptr;
339 }
340 int real_index = m_ParamStartPos + m_ParamCount - index - 1;
341 if (real_index >= kParamBufSize) {
342 real_index -= kParamBufSize;
343 }
344 ContentParam& param = m_ParamBuf[real_index];
345 if (param.m_Type == ContentParam::Type::kNumber) {
346 param.m_Type = ContentParam::Type::kObject;
347 param.m_pObject =
348 param.m_Number.IsInteger()
349 ? pdfium::MakeRetain<CPDF_Number>(param.m_Number.GetSigned())
350 : pdfium::MakeRetain<CPDF_Number>(param.m_Number.GetFloat());
351 return param.m_pObject;
352 }
353 if (param.m_Type == ContentParam::Type::kName) {
354 param.m_Type = ContentParam::Type::kObject;
355 param.m_pObject = m_pDocument->New<CPDF_Name>(param.m_Name);
356 return param.m_pObject;
357 }
358 if (param.m_Type == ContentParam::Type::kObject)
359 return param.m_pObject;
360
361 NOTREACHED_NORETURN();
362 }
363
GetString(uint32_t index) const364 ByteString CPDF_StreamContentParser::GetString(uint32_t index) const {
365 if (index >= m_ParamCount)
366 return ByteString();
367
368 int real_index = m_ParamStartPos + m_ParamCount - index - 1;
369 if (real_index >= kParamBufSize)
370 real_index -= kParamBufSize;
371
372 const ContentParam& param = m_ParamBuf[real_index];
373 if (param.m_Type == ContentParam::Type::kName)
374 return param.m_Name;
375
376 if (param.m_Type == ContentParam::Type::kObject && param.m_pObject)
377 return param.m_pObject->GetString();
378
379 return ByteString();
380 }
381
GetNumber(uint32_t index) const382 float CPDF_StreamContentParser::GetNumber(uint32_t index) const {
383 if (index >= m_ParamCount)
384 return 0;
385
386 int real_index = m_ParamStartPos + m_ParamCount - index - 1;
387 if (real_index >= kParamBufSize)
388 real_index -= kParamBufSize;
389
390 const ContentParam& param = m_ParamBuf[real_index];
391 if (param.m_Type == ContentParam::Type::kNumber)
392 return param.m_Number.GetFloat();
393
394 if (param.m_Type == ContentParam::Type::kObject && param.m_pObject)
395 return param.m_pObject->GetNumber();
396
397 return 0;
398 }
399
GetNumbers(size_t count) const400 std::vector<float> CPDF_StreamContentParser::GetNumbers(size_t count) const {
401 std::vector<float> values(count);
402 for (size_t i = 0; i < count; ++i)
403 values[i] = GetNumber(count - i - 1);
404 return values;
405 }
406
GetPoint(uint32_t index) const407 CFX_PointF CPDF_StreamContentParser::GetPoint(uint32_t index) const {
408 return CFX_PointF(GetNumber(index + 1), GetNumber(index));
409 }
410
GetMatrix() const411 CFX_Matrix CPDF_StreamContentParser::GetMatrix() const {
412 return CFX_Matrix(GetNumber(5), GetNumber(4), GetNumber(3), GetNumber(2),
413 GetNumber(1), GetNumber(0));
414 }
415
SetGraphicStates(CPDF_PageObject * pObj,bool bColor,bool bText,bool bGraph)416 void CPDF_StreamContentParser::SetGraphicStates(CPDF_PageObject* pObj,
417 bool bColor,
418 bool bText,
419 bool bGraph) {
420 pObj->m_GeneralState = m_pCurStates->m_GeneralState;
421 pObj->m_ClipPath = m_pCurStates->m_ClipPath;
422 pObj->SetContentMarks(*m_ContentMarksStack.top());
423 if (bColor) {
424 pObj->m_ColorState = m_pCurStates->m_ColorState;
425 }
426 if (bGraph) {
427 pObj->m_GraphState = m_pCurStates->m_GraphState;
428 }
429 if (bText) {
430 pObj->m_TextState = m_pCurStates->m_TextState;
431 }
432 }
433
434 // static
435 CPDF_StreamContentParser::OpCodes
InitializeOpCodes()436 CPDF_StreamContentParser::InitializeOpCodes() {
437 return OpCodes({
438 {FXBSTR_ID('"', 0, 0, 0),
439 &CPDF_StreamContentParser::Handle_NextLineShowText_Space},
440 {FXBSTR_ID('\'', 0, 0, 0),
441 &CPDF_StreamContentParser::Handle_NextLineShowText},
442 {FXBSTR_ID('B', 0, 0, 0),
443 &CPDF_StreamContentParser::Handle_FillStrokePath},
444 {FXBSTR_ID('B', '*', 0, 0),
445 &CPDF_StreamContentParser::Handle_EOFillStrokePath},
446 {FXBSTR_ID('B', 'D', 'C', 0),
447 &CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary},
448 {FXBSTR_ID('B', 'I', 0, 0), &CPDF_StreamContentParser::Handle_BeginImage},
449 {FXBSTR_ID('B', 'M', 'C', 0),
450 &CPDF_StreamContentParser::Handle_BeginMarkedContent},
451 {FXBSTR_ID('B', 'T', 0, 0), &CPDF_StreamContentParser::Handle_BeginText},
452 {FXBSTR_ID('C', 'S', 0, 0),
453 &CPDF_StreamContentParser::Handle_SetColorSpace_Stroke},
454 {FXBSTR_ID('D', 'P', 0, 0),
455 &CPDF_StreamContentParser::Handle_MarkPlace_Dictionary},
456 {FXBSTR_ID('D', 'o', 0, 0),
457 &CPDF_StreamContentParser::Handle_ExecuteXObject},
458 {FXBSTR_ID('E', 'I', 0, 0), &CPDF_StreamContentParser::Handle_EndImage},
459 {FXBSTR_ID('E', 'M', 'C', 0),
460 &CPDF_StreamContentParser::Handle_EndMarkedContent},
461 {FXBSTR_ID('E', 'T', 0, 0), &CPDF_StreamContentParser::Handle_EndText},
462 {FXBSTR_ID('F', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPathOld},
463 {FXBSTR_ID('G', 0, 0, 0),
464 &CPDF_StreamContentParser::Handle_SetGray_Stroke},
465 {FXBSTR_ID('I', 'D', 0, 0),
466 &CPDF_StreamContentParser::Handle_BeginImageData},
467 {FXBSTR_ID('J', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineCap},
468 {FXBSTR_ID('K', 0, 0, 0),
469 &CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke},
470 {FXBSTR_ID('M', 0, 0, 0),
471 &CPDF_StreamContentParser::Handle_SetMiterLimit},
472 {FXBSTR_ID('M', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace},
473 {FXBSTR_ID('Q', 0, 0, 0),
474 &CPDF_StreamContentParser::Handle_RestoreGraphState},
475 {FXBSTR_ID('R', 'G', 0, 0),
476 &CPDF_StreamContentParser::Handle_SetRGBColor_Stroke},
477 {FXBSTR_ID('S', 0, 0, 0), &CPDF_StreamContentParser::Handle_StrokePath},
478 {FXBSTR_ID('S', 'C', 0, 0),
479 &CPDF_StreamContentParser::Handle_SetColor_Stroke},
480 {FXBSTR_ID('S', 'C', 'N', 0),
481 &CPDF_StreamContentParser::Handle_SetColorPS_Stroke},
482 {FXBSTR_ID('T', '*', 0, 0),
483 &CPDF_StreamContentParser::Handle_MoveToNextLine},
484 {FXBSTR_ID('T', 'D', 0, 0),
485 &CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading},
486 {FXBSTR_ID('T', 'J', 0, 0),
487 &CPDF_StreamContentParser::Handle_ShowText_Positioning},
488 {FXBSTR_ID('T', 'L', 0, 0),
489 &CPDF_StreamContentParser::Handle_SetTextLeading},
490 {FXBSTR_ID('T', 'c', 0, 0),
491 &CPDF_StreamContentParser::Handle_SetCharSpace},
492 {FXBSTR_ID('T', 'd', 0, 0),
493 &CPDF_StreamContentParser::Handle_MoveTextPoint},
494 {FXBSTR_ID('T', 'f', 0, 0), &CPDF_StreamContentParser::Handle_SetFont},
495 {FXBSTR_ID('T', 'j', 0, 0), &CPDF_StreamContentParser::Handle_ShowText},
496 {FXBSTR_ID('T', 'm', 0, 0),
497 &CPDF_StreamContentParser::Handle_SetTextMatrix},
498 {FXBSTR_ID('T', 'r', 0, 0),
499 &CPDF_StreamContentParser::Handle_SetTextRenderMode},
500 {FXBSTR_ID('T', 's', 0, 0),
501 &CPDF_StreamContentParser::Handle_SetTextRise},
502 {FXBSTR_ID('T', 'w', 0, 0),
503 &CPDF_StreamContentParser::Handle_SetWordSpace},
504 {FXBSTR_ID('T', 'z', 0, 0),
505 &CPDF_StreamContentParser::Handle_SetHorzScale},
506 {FXBSTR_ID('W', 0, 0, 0), &CPDF_StreamContentParser::Handle_Clip},
507 {FXBSTR_ID('W', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOClip},
508 {FXBSTR_ID('b', 0, 0, 0),
509 &CPDF_StreamContentParser::Handle_CloseFillStrokePath},
510 {FXBSTR_ID('b', '*', 0, 0),
511 &CPDF_StreamContentParser::Handle_CloseEOFillStrokePath},
512 {FXBSTR_ID('c', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_123},
513 {FXBSTR_ID('c', 'm', 0, 0),
514 &CPDF_StreamContentParser::Handle_ConcatMatrix},
515 {FXBSTR_ID('c', 's', 0, 0),
516 &CPDF_StreamContentParser::Handle_SetColorSpace_Fill},
517 {FXBSTR_ID('d', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetDash},
518 {FXBSTR_ID('d', '0', 0, 0),
519 &CPDF_StreamContentParser::Handle_SetCharWidth},
520 {FXBSTR_ID('d', '1', 0, 0),
521 &CPDF_StreamContentParser::Handle_SetCachedDevice},
522 {FXBSTR_ID('f', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPath},
523 {FXBSTR_ID('f', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillPath},
524 {FXBSTR_ID('g', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Fill},
525 {FXBSTR_ID('g', 's', 0, 0),
526 &CPDF_StreamContentParser::Handle_SetExtendGraphState},
527 {FXBSTR_ID('h', 0, 0, 0), &CPDF_StreamContentParser::Handle_ClosePath},
528 {FXBSTR_ID('i', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetFlat},
529 {FXBSTR_ID('j', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineJoin},
530 {FXBSTR_ID('k', 0, 0, 0),
531 &CPDF_StreamContentParser::Handle_SetCMYKColor_Fill},
532 {FXBSTR_ID('l', 0, 0, 0), &CPDF_StreamContentParser::Handle_LineTo},
533 {FXBSTR_ID('m', 0, 0, 0), &CPDF_StreamContentParser::Handle_MoveTo},
534 {FXBSTR_ID('n', 0, 0, 0), &CPDF_StreamContentParser::Handle_EndPath},
535 {FXBSTR_ID('q', 0, 0, 0),
536 &CPDF_StreamContentParser::Handle_SaveGraphState},
537 {FXBSTR_ID('r', 'e', 0, 0), &CPDF_StreamContentParser::Handle_Rectangle},
538 {FXBSTR_ID('r', 'g', 0, 0),
539 &CPDF_StreamContentParser::Handle_SetRGBColor_Fill},
540 {FXBSTR_ID('r', 'i', 0, 0),
541 &CPDF_StreamContentParser::Handle_SetRenderIntent},
542 {FXBSTR_ID('s', 0, 0, 0),
543 &CPDF_StreamContentParser::Handle_CloseStrokePath},
544 {FXBSTR_ID('s', 'c', 0, 0),
545 &CPDF_StreamContentParser::Handle_SetColor_Fill},
546 {FXBSTR_ID('s', 'c', 'n', 0),
547 &CPDF_StreamContentParser::Handle_SetColorPS_Fill},
548 {FXBSTR_ID('s', 'h', 0, 0), &CPDF_StreamContentParser::Handle_ShadeFill},
549 {FXBSTR_ID('v', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_23},
550 {FXBSTR_ID('w', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineWidth},
551 {FXBSTR_ID('y', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_13},
552 });
553 }
554
OnOperator(ByteStringView op)555 void CPDF_StreamContentParser::OnOperator(ByteStringView op) {
556 static const pdfium::base::NoDestructor<OpCodes> s_OpCodes(
557 InitializeOpCodes());
558
559 auto it = s_OpCodes->find(op.GetID());
560 if (it != s_OpCodes->end())
561 (this->*it->second)();
562 }
563
Handle_CloseFillStrokePath()564 void CPDF_StreamContentParser::Handle_CloseFillStrokePath() {
565 Handle_ClosePath();
566 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kStroke);
567 }
568
Handle_FillStrokePath()569 void CPDF_StreamContentParser::Handle_FillStrokePath() {
570 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kStroke);
571 }
572
Handle_CloseEOFillStrokePath()573 void CPDF_StreamContentParser::Handle_CloseEOFillStrokePath() {
574 AddPathPointAndClose(m_PathStart, CFX_Path::Point::Type::kLine);
575 AddPathObject(CFX_FillRenderOptions::FillType::kEvenOdd, RenderType::kStroke);
576 }
577
Handle_EOFillStrokePath()578 void CPDF_StreamContentParser::Handle_EOFillStrokePath() {
579 AddPathObject(CFX_FillRenderOptions::FillType::kEvenOdd, RenderType::kStroke);
580 }
581
Handle_BeginMarkedContent_Dictionary()582 void CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary() {
583 RetainPtr<CPDF_Object> pProperty = GetObject(0);
584 if (!pProperty)
585 return;
586
587 ByteString tag = GetString(1);
588 std::unique_ptr<CPDF_ContentMarks> new_marks =
589 m_ContentMarksStack.top()->Clone();
590
591 if (pProperty->IsName()) {
592 ByteString property_name = pProperty->GetString();
593 RetainPtr<CPDF_Dictionary> pHolder = FindResourceHolder("Properties");
594 if (!pHolder || !pHolder->GetDictFor(property_name))
595 return;
596 new_marks->AddMarkWithPropertiesHolder(tag, std::move(pHolder),
597 property_name);
598 } else if (pProperty->IsDictionary()) {
599 new_marks->AddMarkWithDirectDict(tag, ToDictionary(pProperty));
600 } else {
601 return;
602 }
603 m_ContentMarksStack.push(std::move(new_marks));
604 }
605
Handle_BeginImage()606 void CPDF_StreamContentParser::Handle_BeginImage() {
607 FX_FILESIZE savePos = m_pSyntax->GetPos();
608 auto pDict = m_pDocument->New<CPDF_Dictionary>();
609 while (true) {
610 CPDF_StreamParser::ElementType type = m_pSyntax->ParseNextElement();
611 if (type == CPDF_StreamParser::ElementType::kKeyword) {
612 if (m_pSyntax->GetWord() != "ID") {
613 m_pSyntax->SetPos(savePos);
614 return;
615 }
616 }
617 if (type != CPDF_StreamParser::ElementType::kName) {
618 break;
619 }
620 auto word = m_pSyntax->GetWord();
621 ByteString key(word.Last(word.GetLength() - 1));
622 auto pObj = m_pSyntax->ReadNextObject(false, false, 0);
623 if (pObj && !pObj->IsInline()) {
624 pDict->SetNewFor<CPDF_Reference>(key, m_pDocument, pObj->GetObjNum());
625 } else {
626 pDict->SetFor(key, std::move(pObj));
627 }
628 }
629 ReplaceAbbr(pDict);
630 RetainPtr<const CPDF_Object> pCSObj;
631 if (pDict->KeyExist("ColorSpace")) {
632 pCSObj = pDict->GetDirectObjectFor("ColorSpace");
633 if (pCSObj->IsName()) {
634 ByteString name = pCSObj->GetString();
635 if (name != "DeviceRGB" && name != "DeviceGray" && name != "DeviceCMYK") {
636 pCSObj = FindResourceObj("ColorSpace", name);
637 if (pCSObj && pCSObj->IsInline())
638 pDict->SetFor("ColorSpace", pCSObj->Clone());
639 }
640 }
641 }
642 pDict->SetNewFor<CPDF_Name>("Subtype", "Image");
643 RetainPtr<CPDF_Stream> pStream =
644 m_pSyntax->ReadInlineStream(m_pDocument, std::move(pDict), pCSObj.Get());
645 while (true) {
646 CPDF_StreamParser::ElementType type = m_pSyntax->ParseNextElement();
647 if (type == CPDF_StreamParser::ElementType::kEndOfData)
648 break;
649
650 if (type != CPDF_StreamParser::ElementType::kKeyword)
651 continue;
652
653 if (m_pSyntax->GetWord() == "EI")
654 break;
655 }
656 CPDF_ImageObject* pObj =
657 AddImageFromStream(std::move(pStream), /*resource_name=*/"");
658 // Record the bounding box of this image, so rendering code can draw it
659 // properly.
660 if (pObj && pObj->GetImage()->IsMask())
661 m_pObjectHolder->AddImageMaskBoundingBox(pObj->GetRect());
662 }
663
Handle_BeginMarkedContent()664 void CPDF_StreamContentParser::Handle_BeginMarkedContent() {
665 std::unique_ptr<CPDF_ContentMarks> new_marks =
666 m_ContentMarksStack.top()->Clone();
667 new_marks->AddMark(GetString(0));
668 m_ContentMarksStack.push(std::move(new_marks));
669 }
670
Handle_BeginText()671 void CPDF_StreamContentParser::Handle_BeginText() {
672 m_pCurStates->m_TextMatrix = CFX_Matrix();
673 OnChangeTextMatrix();
674 m_pCurStates->m_TextPos = CFX_PointF();
675 m_pCurStates->m_TextLinePos = CFX_PointF();
676 }
677
Handle_CurveTo_123()678 void CPDF_StreamContentParser::Handle_CurveTo_123() {
679 AddPathPoint(GetPoint(4), CFX_Path::Point::Type::kBezier);
680 AddPathPoint(GetPoint(2), CFX_Path::Point::Type::kBezier);
681 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
682 }
683
Handle_ConcatMatrix()684 void CPDF_StreamContentParser::Handle_ConcatMatrix() {
685 m_pCurStates->m_CTM = GetMatrix() * m_pCurStates->m_CTM;
686 OnChangeTextMatrix();
687 }
688
Handle_SetColorSpace_Fill()689 void CPDF_StreamContentParser::Handle_SetColorSpace_Fill() {
690 RetainPtr<CPDF_ColorSpace> pCS = FindColorSpace(GetString(0));
691 if (!pCS)
692 return;
693
694 m_pCurStates->m_ColorState.GetMutableFillColor()->SetColorSpace(
695 std::move(pCS));
696 }
697
Handle_SetColorSpace_Stroke()698 void CPDF_StreamContentParser::Handle_SetColorSpace_Stroke() {
699 RetainPtr<CPDF_ColorSpace> pCS = FindColorSpace(GetString(0));
700 if (!pCS)
701 return;
702
703 m_pCurStates->m_ColorState.GetMutableStrokeColor()->SetColorSpace(
704 std::move(pCS));
705 }
706
Handle_SetDash()707 void CPDF_StreamContentParser::Handle_SetDash() {
708 RetainPtr<CPDF_Array> pArray = ToArray(GetObject(1));
709 if (!pArray)
710 return;
711
712 m_pCurStates->SetLineDash(pArray.Get(), GetNumber(0), 1.0f);
713 }
714
Handle_SetCharWidth()715 void CPDF_StreamContentParser::Handle_SetCharWidth() {
716 m_Type3Data[0] = GetNumber(1);
717 m_Type3Data[1] = GetNumber(0);
718 m_bColored = true;
719 }
720
Handle_SetCachedDevice()721 void CPDF_StreamContentParser::Handle_SetCachedDevice() {
722 for (int i = 0; i < 6; i++) {
723 m_Type3Data[i] = GetNumber(5 - i);
724 }
725 m_bColored = false;
726 }
727
Handle_ExecuteXObject()728 void CPDF_StreamContentParser::Handle_ExecuteXObject() {
729 ByteString name = GetString(0);
730 if (name == m_LastImageName && m_pLastImage && m_pLastImage->GetStream() &&
731 m_pLastImage->GetStream()->GetObjNum()) {
732 CPDF_ImageObject* pObj = AddLastImage();
733 // Record the bounding box of this image, so rendering code can draw it
734 // properly.
735 if (pObj && pObj->GetImage()->IsMask())
736 m_pObjectHolder->AddImageMaskBoundingBox(pObj->GetRect());
737 return;
738 }
739
740 RetainPtr<CPDF_Stream> pXObject(ToStream(FindResourceObj("XObject", name)));
741 if (!pXObject)
742 return;
743
744 ByteString type;
745 if (pXObject->GetDict())
746 type = pXObject->GetDict()->GetByteStringFor("Subtype");
747
748 if (type == "Form") {
749 if (m_RecursionState->form_count > kFormCountLimit) {
750 return;
751 }
752
753 const bool is_first = m_RecursionState->form_count == 0;
754 ++m_RecursionState->form_count;
755 AddForm(std::move(pXObject), name);
756 if (is_first) {
757 m_RecursionState->form_count = 0;
758 }
759 return;
760 }
761
762 if (type == "Image") {
763 CPDF_ImageObject* pObj =
764 pXObject->IsInline()
765 ? AddImageFromStream(ToStream(pXObject->Clone()), name)
766 : AddImageFromStreamObjNum(pXObject->GetObjNum(), name);
767
768 m_LastImageName = std::move(name);
769 if (pObj) {
770 m_pLastImage = pObj->GetImage();
771 if (m_pLastImage->IsMask())
772 m_pObjectHolder->AddImageMaskBoundingBox(pObj->GetRect());
773 }
774 }
775 }
776
AddForm(RetainPtr<CPDF_Stream> pStream,const ByteString & name)777 void CPDF_StreamContentParser::AddForm(RetainPtr<CPDF_Stream> pStream,
778 const ByteString& name) {
779 CPDF_AllStates status;
780 status.m_GeneralState = m_pCurStates->m_GeneralState;
781 status.m_GraphState = m_pCurStates->m_GraphState;
782 status.m_ColorState = m_pCurStates->m_ColorState;
783 status.m_TextState = m_pCurStates->m_TextState;
784 auto form = std::make_unique<CPDF_Form>(
785 m_pDocument, m_pPageResources, std::move(pStream), m_pResources.Get());
786 form->ParseContent(&status, nullptr, m_RecursionState);
787
788 CFX_Matrix matrix = m_pCurStates->m_CTM * m_mtContentToUser;
789 auto pFormObj = std::make_unique<CPDF_FormObject>(GetCurrentStreamIndex(),
790 std::move(form), matrix);
791 pFormObj->SetResourceName(name);
792 if (!m_pObjectHolder->BackgroundAlphaNeeded() &&
793 pFormObj->form()->BackgroundAlphaNeeded()) {
794 m_pObjectHolder->SetBackgroundAlphaNeeded(true);
795 }
796 pFormObj->CalcBoundingBox();
797 SetGraphicStates(pFormObj.get(), true, true, true);
798 m_pObjectHolder->AppendPageObject(std::move(pFormObj));
799 }
800
AddImageFromStream(RetainPtr<CPDF_Stream> pStream,const ByteString & name)801 CPDF_ImageObject* CPDF_StreamContentParser::AddImageFromStream(
802 RetainPtr<CPDF_Stream> pStream,
803 const ByteString& name) {
804 if (!pStream)
805 return nullptr;
806
807 auto pImageObj = std::make_unique<CPDF_ImageObject>(GetCurrentStreamIndex());
808 pImageObj->SetResourceName(name);
809 pImageObj->SetImage(
810 pdfium::MakeRetain<CPDF_Image>(m_pDocument, std::move(pStream)));
811
812 return AddImageObject(std::move(pImageObj));
813 }
814
AddImageFromStreamObjNum(uint32_t stream_obj_num,const ByteString & name)815 CPDF_ImageObject* CPDF_StreamContentParser::AddImageFromStreamObjNum(
816 uint32_t stream_obj_num,
817 const ByteString& name) {
818 auto pImageObj = std::make_unique<CPDF_ImageObject>(GetCurrentStreamIndex());
819 pImageObj->SetResourceName(name);
820 pImageObj->SetImage(
821 CPDF_DocPageData::FromDocument(m_pDocument)->GetImage(stream_obj_num));
822
823 return AddImageObject(std::move(pImageObj));
824 }
825
AddLastImage()826 CPDF_ImageObject* CPDF_StreamContentParser::AddLastImage() {
827 DCHECK(m_pLastImage);
828
829 auto pImageObj = std::make_unique<CPDF_ImageObject>(GetCurrentStreamIndex());
830 pImageObj->SetResourceName(m_LastImageName);
831 pImageObj->SetImage(CPDF_DocPageData::FromDocument(m_pDocument)
832 ->GetImage(m_pLastImage->GetStream()->GetObjNum()));
833
834 return AddImageObject(std::move(pImageObj));
835 }
836
AddImageObject(std::unique_ptr<CPDF_ImageObject> pImageObj)837 CPDF_ImageObject* CPDF_StreamContentParser::AddImageObject(
838 std::unique_ptr<CPDF_ImageObject> pImageObj) {
839 SetGraphicStates(pImageObj.get(), pImageObj->GetImage()->IsMask(), false,
840 false);
841
842 CFX_Matrix ImageMatrix = m_pCurStates->m_CTM * m_mtContentToUser;
843 pImageObj->SetImageMatrix(ImageMatrix);
844
845 CPDF_ImageObject* pRet = pImageObj.get();
846 m_pObjectHolder->AppendPageObject(std::move(pImageObj));
847 return pRet;
848 }
849
GetColors() const850 std::vector<float> CPDF_StreamContentParser::GetColors() const {
851 DCHECK(m_ParamCount > 0);
852 return GetNumbers(m_ParamCount);
853 }
854
GetNamedColors() const855 std::vector<float> CPDF_StreamContentParser::GetNamedColors() const {
856 DCHECK(m_ParamCount > 0);
857 const uint32_t nvalues = m_ParamCount - 1;
858 std::vector<float> values(nvalues);
859 for (size_t i = 0; i < nvalues; ++i)
860 values[i] = GetNumber(m_ParamCount - i - 1);
861 return values;
862 }
863
Handle_MarkPlace_Dictionary()864 void CPDF_StreamContentParser::Handle_MarkPlace_Dictionary() {}
865
Handle_EndImage()866 void CPDF_StreamContentParser::Handle_EndImage() {}
867
Handle_EndMarkedContent()868 void CPDF_StreamContentParser::Handle_EndMarkedContent() {
869 // First element is a sentinel, so do not pop it, ever. This may come up if
870 // the EMCs are mismatched with the BMC/BDCs.
871 if (m_ContentMarksStack.size() > 1)
872 m_ContentMarksStack.pop();
873 }
874
Handle_EndText()875 void CPDF_StreamContentParser::Handle_EndText() {
876 if (m_ClipTextList.empty())
877 return;
878
879 if (TextRenderingModeIsClipMode(m_pCurStates->m_TextState.GetTextMode()))
880 m_pCurStates->m_ClipPath.AppendTexts(&m_ClipTextList);
881
882 m_ClipTextList.clear();
883 }
884
Handle_FillPath()885 void CPDF_StreamContentParser::Handle_FillPath() {
886 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kFill);
887 }
888
Handle_FillPathOld()889 void CPDF_StreamContentParser::Handle_FillPathOld() {
890 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kFill);
891 }
892
Handle_EOFillPath()893 void CPDF_StreamContentParser::Handle_EOFillPath() {
894 AddPathObject(CFX_FillRenderOptions::FillType::kEvenOdd, RenderType::kFill);
895 }
896
Handle_SetGray_Fill()897 void CPDF_StreamContentParser::Handle_SetGray_Fill() {
898 m_pCurStates->m_ColorState.SetFillColor(
899 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceGray),
900 GetNumbers(1));
901 }
902
Handle_SetGray_Stroke()903 void CPDF_StreamContentParser::Handle_SetGray_Stroke() {
904 m_pCurStates->m_ColorState.SetStrokeColor(
905 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceGray),
906 GetNumbers(1));
907 }
908
Handle_SetExtendGraphState()909 void CPDF_StreamContentParser::Handle_SetExtendGraphState() {
910 ByteString name = GetString(0);
911 RetainPtr<CPDF_Dictionary> pGS =
912 ToDictionary(FindResourceObj("ExtGState", name));
913 if (!pGS)
914 return;
915
916 CHECK(!name.IsEmpty());
917 m_pCurStates->m_GeneralState.AppendGraphicsResourceName(std::move(name));
918 m_pCurStates->ProcessExtGS(pGS.Get(), this);
919 }
920
Handle_ClosePath()921 void CPDF_StreamContentParser::Handle_ClosePath() {
922 if (m_PathPoints.empty())
923 return;
924
925 if (m_PathStart.x != m_PathCurrent.x || m_PathStart.y != m_PathCurrent.y) {
926 AddPathPointAndClose(m_PathStart, CFX_Path::Point::Type::kLine);
927 } else {
928 m_PathPoints.back().m_CloseFigure = true;
929 }
930 }
931
Handle_SetFlat()932 void CPDF_StreamContentParser::Handle_SetFlat() {
933 m_pCurStates->m_GeneralState.SetFlatness(GetNumber(0));
934 }
935
Handle_BeginImageData()936 void CPDF_StreamContentParser::Handle_BeginImageData() {}
937
Handle_SetLineJoin()938 void CPDF_StreamContentParser::Handle_SetLineJoin() {
939 m_pCurStates->m_GraphState.SetLineJoin(
940 static_cast<CFX_GraphStateData::LineJoin>(GetInteger(0)));
941 }
942
Handle_SetLineCap()943 void CPDF_StreamContentParser::Handle_SetLineCap() {
944 m_pCurStates->m_GraphState.SetLineCap(
945 static_cast<CFX_GraphStateData::LineCap>(GetInteger(0)));
946 }
947
Handle_SetCMYKColor_Fill()948 void CPDF_StreamContentParser::Handle_SetCMYKColor_Fill() {
949 if (m_ParamCount != 4)
950 return;
951
952 m_pCurStates->m_ColorState.SetFillColor(
953 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceCMYK),
954 GetNumbers(4));
955 }
956
Handle_SetCMYKColor_Stroke()957 void CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke() {
958 if (m_ParamCount != 4)
959 return;
960
961 m_pCurStates->m_ColorState.SetStrokeColor(
962 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceCMYK),
963 GetNumbers(4));
964 }
965
Handle_LineTo()966 void CPDF_StreamContentParser::Handle_LineTo() {
967 if (m_ParamCount != 2)
968 return;
969
970 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kLine);
971 }
972
Handle_MoveTo()973 void CPDF_StreamContentParser::Handle_MoveTo() {
974 if (m_ParamCount != 2)
975 return;
976
977 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kMove);
978 ParsePathObject();
979 }
980
Handle_SetMiterLimit()981 void CPDF_StreamContentParser::Handle_SetMiterLimit() {
982 m_pCurStates->m_GraphState.SetMiterLimit(GetNumber(0));
983 }
984
Handle_MarkPlace()985 void CPDF_StreamContentParser::Handle_MarkPlace() {}
986
Handle_EndPath()987 void CPDF_StreamContentParser::Handle_EndPath() {
988 AddPathObject(CFX_FillRenderOptions::FillType::kNoFill, RenderType::kFill);
989 }
990
Handle_SaveGraphState()991 void CPDF_StreamContentParser::Handle_SaveGraphState() {
992 auto pStates = std::make_unique<CPDF_AllStates>();
993 pStates->Copy(*m_pCurStates);
994 m_StateStack.push_back(std::move(pStates));
995 }
996
Handle_RestoreGraphState()997 void CPDF_StreamContentParser::Handle_RestoreGraphState() {
998 if (m_StateStack.empty())
999 return;
1000 std::unique_ptr<CPDF_AllStates> pStates = std::move(m_StateStack.back());
1001 m_StateStack.pop_back();
1002 m_pCurStates->Copy(*pStates);
1003 }
1004
Handle_Rectangle()1005 void CPDF_StreamContentParser::Handle_Rectangle() {
1006 float x = GetNumber(3);
1007 float y = GetNumber(2);
1008 float w = GetNumber(1);
1009 float h = GetNumber(0);
1010 AddPathRect(x, y, w, h);
1011 }
1012
AddPathRect(float x,float y,float w,float h)1013 void CPDF_StreamContentParser::AddPathRect(float x, float y, float w, float h) {
1014 AddPathPoint({x, y}, CFX_Path::Point::Type::kMove);
1015 AddPathPoint({x + w, y}, CFX_Path::Point::Type::kLine);
1016 AddPathPoint({x + w, y + h}, CFX_Path::Point::Type::kLine);
1017 AddPathPoint({x, y + h}, CFX_Path::Point::Type::kLine);
1018 AddPathPointAndClose({x, y}, CFX_Path::Point::Type::kLine);
1019 }
1020
Handle_SetRGBColor_Fill()1021 void CPDF_StreamContentParser::Handle_SetRGBColor_Fill() {
1022 if (m_ParamCount != 3)
1023 return;
1024
1025 m_pCurStates->m_ColorState.SetFillColor(
1026 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceRGB),
1027 GetNumbers(3));
1028 }
1029
Handle_SetRGBColor_Stroke()1030 void CPDF_StreamContentParser::Handle_SetRGBColor_Stroke() {
1031 if (m_ParamCount != 3)
1032 return;
1033
1034 m_pCurStates->m_ColorState.SetStrokeColor(
1035 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceRGB),
1036 GetNumbers(3));
1037 }
1038
Handle_SetRenderIntent()1039 void CPDF_StreamContentParser::Handle_SetRenderIntent() {}
1040
Handle_CloseStrokePath()1041 void CPDF_StreamContentParser::Handle_CloseStrokePath() {
1042 Handle_ClosePath();
1043 AddPathObject(CFX_FillRenderOptions::FillType::kNoFill, RenderType::kStroke);
1044 }
1045
Handle_StrokePath()1046 void CPDF_StreamContentParser::Handle_StrokePath() {
1047 AddPathObject(CFX_FillRenderOptions::FillType::kNoFill, RenderType::kStroke);
1048 }
1049
Handle_SetColor_Fill()1050 void CPDF_StreamContentParser::Handle_SetColor_Fill() {
1051 int nargs = std::min(m_ParamCount, 4U);
1052 m_pCurStates->m_ColorState.SetFillColor(nullptr, GetNumbers(nargs));
1053 }
1054
Handle_SetColor_Stroke()1055 void CPDF_StreamContentParser::Handle_SetColor_Stroke() {
1056 int nargs = std::min(m_ParamCount, 4U);
1057 m_pCurStates->m_ColorState.SetStrokeColor(nullptr, GetNumbers(nargs));
1058 }
1059
Handle_SetColorPS_Fill()1060 void CPDF_StreamContentParser::Handle_SetColorPS_Fill() {
1061 RetainPtr<CPDF_Object> pLastParam = GetObject(0);
1062 if (!pLastParam)
1063 return;
1064
1065 if (!pLastParam->IsName()) {
1066 m_pCurStates->m_ColorState.SetFillColor(nullptr, GetColors());
1067 return;
1068 }
1069
1070 // A valid |pLastParam| implies |m_ParamCount| > 0, so GetNamedColors() call
1071 // below is safe.
1072 RetainPtr<CPDF_Pattern> pPattern = FindPattern(GetString(0));
1073 if (!pPattern)
1074 return;
1075
1076 std::vector<float> values = GetNamedColors();
1077 m_pCurStates->m_ColorState.SetFillPattern(std::move(pPattern), values);
1078 }
1079
Handle_SetColorPS_Stroke()1080 void CPDF_StreamContentParser::Handle_SetColorPS_Stroke() {
1081 RetainPtr<CPDF_Object> pLastParam = GetObject(0);
1082 if (!pLastParam)
1083 return;
1084
1085 if (!pLastParam->IsName()) {
1086 m_pCurStates->m_ColorState.SetStrokeColor(nullptr, GetColors());
1087 return;
1088 }
1089
1090 // A valid |pLastParam| implies |m_ParamCount| > 0, so GetNamedColors() call
1091 // below is safe.
1092 RetainPtr<CPDF_Pattern> pPattern = FindPattern(GetString(0));
1093 if (!pPattern)
1094 return;
1095
1096 std::vector<float> values = GetNamedColors();
1097 m_pCurStates->m_ColorState.SetStrokePattern(std::move(pPattern), values);
1098 }
1099
Handle_ShadeFill()1100 void CPDF_StreamContentParser::Handle_ShadeFill() {
1101 RetainPtr<CPDF_ShadingPattern> pShading = FindShading(GetString(0));
1102 if (!pShading)
1103 return;
1104
1105 if (!pShading->IsShadingObject() || !pShading->Load())
1106 return;
1107
1108 CFX_Matrix matrix = m_pCurStates->m_CTM * m_mtContentToUser;
1109 auto pObj = std::make_unique<CPDF_ShadingObject>(GetCurrentStreamIndex(),
1110 pShading, matrix);
1111 SetGraphicStates(pObj.get(), false, false, false);
1112 CFX_FloatRect bbox =
1113 pObj->m_ClipPath.HasRef() ? pObj->m_ClipPath.GetClipBox() : m_BBox;
1114 if (pShading->IsMeshShading())
1115 bbox.Intersect(GetShadingBBox(pShading.Get(), pObj->matrix()));
1116 pObj->SetRect(bbox);
1117 m_pObjectHolder->AppendPageObject(std::move(pObj));
1118 }
1119
Handle_SetCharSpace()1120 void CPDF_StreamContentParser::Handle_SetCharSpace() {
1121 m_pCurStates->m_TextState.SetCharSpace(GetNumber(0));
1122 }
1123
Handle_MoveTextPoint()1124 void CPDF_StreamContentParser::Handle_MoveTextPoint() {
1125 m_pCurStates->m_TextLinePos += GetPoint(0);
1126 m_pCurStates->m_TextPos = m_pCurStates->m_TextLinePos;
1127 }
1128
Handle_MoveTextPoint_SetLeading()1129 void CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading() {
1130 Handle_MoveTextPoint();
1131 m_pCurStates->m_TextLeading = -GetNumber(0);
1132 }
1133
Handle_SetFont()1134 void CPDF_StreamContentParser::Handle_SetFont() {
1135 m_pCurStates->m_TextState.SetFontSize(GetNumber(0));
1136 RetainPtr<CPDF_Font> pFont = FindFont(GetString(1));
1137 if (pFont)
1138 m_pCurStates->m_TextState.SetFont(std::move(pFont));
1139 }
1140
FindResourceHolder(const ByteString & type)1141 RetainPtr<CPDF_Dictionary> CPDF_StreamContentParser::FindResourceHolder(
1142 const ByteString& type) {
1143 if (!m_pResources)
1144 return nullptr;
1145
1146 RetainPtr<CPDF_Dictionary> pDict = m_pResources->GetMutableDictFor(type);
1147 if (pDict)
1148 return pDict;
1149
1150 if (m_pResources == m_pPageResources || !m_pPageResources)
1151 return nullptr;
1152
1153 return m_pPageResources->GetMutableDictFor(type);
1154 }
1155
FindResourceObj(const ByteString & type,const ByteString & name)1156 RetainPtr<CPDF_Object> CPDF_StreamContentParser::FindResourceObj(
1157 const ByteString& type,
1158 const ByteString& name) {
1159 RetainPtr<CPDF_Dictionary> pHolder = FindResourceHolder(type);
1160 return pHolder ? pHolder->GetMutableDirectObjectFor(name) : nullptr;
1161 }
1162
FindFont(const ByteString & name)1163 RetainPtr<CPDF_Font> CPDF_StreamContentParser::FindFont(
1164 const ByteString& name) {
1165 RetainPtr<CPDF_Dictionary> pFontDict(
1166 ToDictionary(FindResourceObj("Font", name)));
1167 if (!pFontDict) {
1168 return CPDF_Font::GetStockFont(m_pDocument, CFX_Font::kDefaultAnsiFontName);
1169 }
1170 RetainPtr<CPDF_Font> pFont = CPDF_DocPageData::FromDocument(m_pDocument)
1171 ->GetFont(std::move(pFontDict));
1172 if (pFont) {
1173 // Save `name` for later retrieval by the CPDF_TextObject that uses the
1174 // font.
1175 pFont->SetResourceName(name);
1176 if (pFont->IsType3Font()) {
1177 pFont->AsType3Font()->SetPageResources(m_pResources.Get());
1178 pFont->AsType3Font()->CheckType3FontMetrics();
1179 }
1180 }
1181 return pFont;
1182 }
1183
FindColorSpace(const ByteString & name)1184 RetainPtr<CPDF_ColorSpace> CPDF_StreamContentParser::FindColorSpace(
1185 const ByteString& name) {
1186 if (name == "Pattern")
1187 return CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kPattern);
1188
1189 if (name == "DeviceGray" || name == "DeviceCMYK" || name == "DeviceRGB") {
1190 ByteString defname = "Default";
1191 defname += name.Last(name.GetLength() - 7);
1192 RetainPtr<const CPDF_Object> pDefObj =
1193 FindResourceObj("ColorSpace", defname);
1194 if (!pDefObj) {
1195 if (name == "DeviceGray") {
1196 return CPDF_ColorSpace::GetStockCS(
1197 CPDF_ColorSpace::Family::kDeviceGray);
1198 }
1199 if (name == "DeviceRGB")
1200 return CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceRGB);
1201
1202 return CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceCMYK);
1203 }
1204 return CPDF_DocPageData::FromDocument(m_pDocument)
1205 ->GetColorSpace(pDefObj.Get(), nullptr);
1206 }
1207 RetainPtr<const CPDF_Object> pCSObj = FindResourceObj("ColorSpace", name);
1208 if (!pCSObj)
1209 return nullptr;
1210 return CPDF_DocPageData::FromDocument(m_pDocument)
1211 ->GetColorSpace(pCSObj.Get(), nullptr);
1212 }
1213
FindPattern(const ByteString & name)1214 RetainPtr<CPDF_Pattern> CPDF_StreamContentParser::FindPattern(
1215 const ByteString& name) {
1216 RetainPtr<CPDF_Object> pPattern = FindResourceObj("Pattern", name);
1217 if (!pPattern || (!pPattern->IsDictionary() && !pPattern->IsStream()))
1218 return nullptr;
1219 return CPDF_DocPageData::FromDocument(m_pDocument)
1220 ->GetPattern(std::move(pPattern), m_pCurStates->m_ParentMatrix);
1221 }
1222
FindShading(const ByteString & name)1223 RetainPtr<CPDF_ShadingPattern> CPDF_StreamContentParser::FindShading(
1224 const ByteString& name) {
1225 RetainPtr<CPDF_Object> pPattern = FindResourceObj("Shading", name);
1226 if (!pPattern || (!pPattern->IsDictionary() && !pPattern->IsStream()))
1227 return nullptr;
1228 return CPDF_DocPageData::FromDocument(m_pDocument)
1229 ->GetShading(std::move(pPattern), m_pCurStates->m_ParentMatrix);
1230 }
1231
AddTextObject(const ByteString * pStrs,float fInitKerning,const std::vector<float> & kernings,size_t nSegs)1232 void CPDF_StreamContentParser::AddTextObject(const ByteString* pStrs,
1233 float fInitKerning,
1234 const std::vector<float>& kernings,
1235 size_t nSegs) {
1236 RetainPtr<CPDF_Font> pFont = m_pCurStates->m_TextState.GetFont();
1237 if (!pFont)
1238 return;
1239
1240 if (fInitKerning != 0) {
1241 if (pFont->IsVertWriting())
1242 m_pCurStates->m_TextPos.y -= GetVerticalTextSize(fInitKerning);
1243 else
1244 m_pCurStates->m_TextPos.x -= GetHorizontalTextSize(fInitKerning);
1245 }
1246 if (nSegs == 0)
1247 return;
1248
1249 const TextRenderingMode text_mode =
1250 pFont->IsType3Font() ? TextRenderingMode::MODE_FILL
1251 : m_pCurStates->m_TextState.GetTextMode();
1252 {
1253 auto pText = std::make_unique<CPDF_TextObject>(GetCurrentStreamIndex());
1254 pText->SetResourceName(pFont->GetResourceName());
1255 SetGraphicStates(pText.get(), true, true, true);
1256 if (TextRenderingModeIsStrokeMode(text_mode)) {
1257 pdfium::span<float> pCTM = pText->m_TextState.GetMutableCTM();
1258 pCTM[0] = m_pCurStates->m_CTM.a;
1259 pCTM[1] = m_pCurStates->m_CTM.c;
1260 pCTM[2] = m_pCurStates->m_CTM.b;
1261 pCTM[3] = m_pCurStates->m_CTM.d;
1262 }
1263 pText->SetSegments(pStrs, kernings, nSegs);
1264 pText->SetPosition(
1265 m_mtContentToUser.Transform(m_pCurStates->m_CTM.Transform(
1266 m_pCurStates->m_TextMatrix.Transform(CFX_PointF(
1267 m_pCurStates->m_TextPos.x,
1268 m_pCurStates->m_TextPos.y + m_pCurStates->m_TextRise)))));
1269
1270 m_pCurStates->m_TextPos +=
1271 pText->CalcPositionData(m_pCurStates->m_TextHorzScale);
1272 if (TextRenderingModeIsClipMode(text_mode))
1273 m_ClipTextList.push_back(pText->Clone());
1274 m_pObjectHolder->AppendPageObject(std::move(pText));
1275 }
1276 if (!kernings.empty() && kernings[nSegs - 1] != 0) {
1277 if (pFont->IsVertWriting())
1278 m_pCurStates->m_TextPos.y -= GetVerticalTextSize(kernings[nSegs - 1]);
1279 else
1280 m_pCurStates->m_TextPos.x -= GetHorizontalTextSize(kernings[nSegs - 1]);
1281 }
1282 }
1283
GetHorizontalTextSize(float fKerning) const1284 float CPDF_StreamContentParser::GetHorizontalTextSize(float fKerning) const {
1285 return GetVerticalTextSize(fKerning) * m_pCurStates->m_TextHorzScale;
1286 }
1287
GetVerticalTextSize(float fKerning) const1288 float CPDF_StreamContentParser::GetVerticalTextSize(float fKerning) const {
1289 return fKerning * m_pCurStates->m_TextState.GetFontSize() / 1000;
1290 }
1291
GetCurrentStreamIndex()1292 int32_t CPDF_StreamContentParser::GetCurrentStreamIndex() {
1293 auto it =
1294 std::upper_bound(m_StreamStartOffsets.begin(), m_StreamStartOffsets.end(),
1295 m_pSyntax->GetPos() + m_StartParseOffset);
1296 return (it - m_StreamStartOffsets.begin()) - 1;
1297 }
1298
Handle_ShowText()1299 void CPDF_StreamContentParser::Handle_ShowText() {
1300 ByteString str = GetString(0);
1301 if (!str.IsEmpty())
1302 AddTextObject(&str, 0, std::vector<float>(), 1);
1303 }
1304
Handle_ShowText_Positioning()1305 void CPDF_StreamContentParser::Handle_ShowText_Positioning() {
1306 RetainPtr<CPDF_Array> pArray = ToArray(GetObject(0));
1307 if (!pArray)
1308 return;
1309
1310 size_t n = pArray->size();
1311 size_t nsegs = 0;
1312 for (size_t i = 0; i < n; i++) {
1313 RetainPtr<const CPDF_Object> pDirectObject = pArray->GetDirectObjectAt(i);
1314 if (pDirectObject && pDirectObject->IsString())
1315 nsegs++;
1316 }
1317 if (nsegs == 0) {
1318 for (size_t i = 0; i < n; i++) {
1319 float fKerning = pArray->GetFloatAt(i);
1320 if (fKerning != 0)
1321 m_pCurStates->m_TextPos.x -= GetHorizontalTextSize(fKerning);
1322 }
1323 return;
1324 }
1325 std::vector<ByteString> strs(nsegs);
1326 std::vector<float> kernings(nsegs);
1327 size_t iSegment = 0;
1328 float fInitKerning = 0;
1329 for (size_t i = 0; i < n; i++) {
1330 RetainPtr<const CPDF_Object> pObj = pArray->GetDirectObjectAt(i);
1331 if (!pObj)
1332 continue;
1333
1334 if (pObj->IsString()) {
1335 ByteString str = pObj->GetString();
1336 if (str.IsEmpty())
1337 continue;
1338 strs[iSegment] = std::move(str);
1339 kernings[iSegment++] = 0;
1340 } else {
1341 float num = pObj->GetNumber();
1342 if (iSegment == 0)
1343 fInitKerning += num;
1344 else
1345 kernings[iSegment - 1] += num;
1346 }
1347 }
1348 AddTextObject(strs.data(), fInitKerning, kernings, iSegment);
1349 }
1350
Handle_SetTextLeading()1351 void CPDF_StreamContentParser::Handle_SetTextLeading() {
1352 m_pCurStates->m_TextLeading = GetNumber(0);
1353 }
1354
Handle_SetTextMatrix()1355 void CPDF_StreamContentParser::Handle_SetTextMatrix() {
1356 m_pCurStates->m_TextMatrix = GetMatrix();
1357 OnChangeTextMatrix();
1358 m_pCurStates->m_TextPos = CFX_PointF();
1359 m_pCurStates->m_TextLinePos = CFX_PointF();
1360 }
1361
OnChangeTextMatrix()1362 void CPDF_StreamContentParser::OnChangeTextMatrix() {
1363 CFX_Matrix text_matrix(m_pCurStates->m_TextHorzScale, 0.0f, 0.0f, 1.0f, 0.0f,
1364 0.0f);
1365 text_matrix.Concat(m_pCurStates->m_TextMatrix);
1366 text_matrix.Concat(m_pCurStates->m_CTM);
1367 text_matrix.Concat(m_mtContentToUser);
1368 pdfium::span<float> pTextMatrix =
1369 m_pCurStates->m_TextState.GetMutableMatrix();
1370 pTextMatrix[0] = text_matrix.a;
1371 pTextMatrix[1] = text_matrix.c;
1372 pTextMatrix[2] = text_matrix.b;
1373 pTextMatrix[3] = text_matrix.d;
1374 }
1375
Handle_SetTextRenderMode()1376 void CPDF_StreamContentParser::Handle_SetTextRenderMode() {
1377 TextRenderingMode mode;
1378 if (SetTextRenderingModeFromInt(GetInteger(0), &mode))
1379 m_pCurStates->m_TextState.SetTextMode(mode);
1380 }
1381
Handle_SetTextRise()1382 void CPDF_StreamContentParser::Handle_SetTextRise() {
1383 m_pCurStates->m_TextRise = GetNumber(0);
1384 }
1385
Handle_SetWordSpace()1386 void CPDF_StreamContentParser::Handle_SetWordSpace() {
1387 m_pCurStates->m_TextState.SetWordSpace(GetNumber(0));
1388 }
1389
Handle_SetHorzScale()1390 void CPDF_StreamContentParser::Handle_SetHorzScale() {
1391 if (m_ParamCount != 1) {
1392 return;
1393 }
1394 m_pCurStates->m_TextHorzScale = GetNumber(0) / 100;
1395 OnChangeTextMatrix();
1396 }
1397
Handle_MoveToNextLine()1398 void CPDF_StreamContentParser::Handle_MoveToNextLine() {
1399 m_pCurStates->m_TextLinePos.y -= m_pCurStates->m_TextLeading;
1400 m_pCurStates->m_TextPos = m_pCurStates->m_TextLinePos;
1401 }
1402
Handle_CurveTo_23()1403 void CPDF_StreamContentParser::Handle_CurveTo_23() {
1404 AddPathPoint(m_PathCurrent, CFX_Path::Point::Type::kBezier);
1405 AddPathPoint(GetPoint(2), CFX_Path::Point::Type::kBezier);
1406 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
1407 }
1408
Handle_SetLineWidth()1409 void CPDF_StreamContentParser::Handle_SetLineWidth() {
1410 m_pCurStates->m_GraphState.SetLineWidth(GetNumber(0));
1411 }
1412
Handle_Clip()1413 void CPDF_StreamContentParser::Handle_Clip() {
1414 m_PathClipType = CFX_FillRenderOptions::FillType::kWinding;
1415 }
1416
Handle_EOClip()1417 void CPDF_StreamContentParser::Handle_EOClip() {
1418 m_PathClipType = CFX_FillRenderOptions::FillType::kEvenOdd;
1419 }
1420
Handle_CurveTo_13()1421 void CPDF_StreamContentParser::Handle_CurveTo_13() {
1422 AddPathPoint(GetPoint(2), CFX_Path::Point::Type::kBezier);
1423 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
1424 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
1425 }
1426
Handle_NextLineShowText()1427 void CPDF_StreamContentParser::Handle_NextLineShowText() {
1428 Handle_MoveToNextLine();
1429 Handle_ShowText();
1430 }
1431
Handle_NextLineShowText_Space()1432 void CPDF_StreamContentParser::Handle_NextLineShowText_Space() {
1433 m_pCurStates->m_TextState.SetWordSpace(GetNumber(2));
1434 m_pCurStates->m_TextState.SetCharSpace(GetNumber(1));
1435 Handle_NextLineShowText();
1436 }
1437
Handle_Invalid()1438 void CPDF_StreamContentParser::Handle_Invalid() {}
1439
AddPathPoint(const CFX_PointF & point,CFX_Path::Point::Type type)1440 void CPDF_StreamContentParser::AddPathPoint(const CFX_PointF& point,
1441 CFX_Path::Point::Type type) {
1442 // If the path point is the same move as the previous one and neither of them
1443 // closes the path, then just skip it.
1444 if (type == CFX_Path::Point::Type::kMove && !m_PathPoints.empty() &&
1445 !m_PathPoints.back().m_CloseFigure &&
1446 m_PathPoints.back().m_Type == type && m_PathCurrent == point) {
1447 return;
1448 }
1449
1450 m_PathCurrent = point;
1451 if (type == CFX_Path::Point::Type::kMove) {
1452 m_PathStart = point;
1453 if (!m_PathPoints.empty() &&
1454 m_PathPoints.back().IsTypeAndOpen(CFX_Path::Point::Type::kMove)) {
1455 m_PathPoints.back().m_Point = point;
1456 return;
1457 }
1458 } else if (m_PathPoints.empty()) {
1459 return;
1460 }
1461 m_PathPoints.emplace_back(point, type, /*close=*/false);
1462 }
1463
AddPathPointAndClose(const CFX_PointF & point,CFX_Path::Point::Type type)1464 void CPDF_StreamContentParser::AddPathPointAndClose(
1465 const CFX_PointF& point,
1466 CFX_Path::Point::Type type) {
1467 m_PathCurrent = point;
1468 if (m_PathPoints.empty())
1469 return;
1470
1471 m_PathPoints.emplace_back(point, type, /*close=*/true);
1472 }
1473
AddPathObject(CFX_FillRenderOptions::FillType fill_type,RenderType render_type)1474 void CPDF_StreamContentParser::AddPathObject(
1475 CFX_FillRenderOptions::FillType fill_type,
1476 RenderType render_type) {
1477 std::vector<CFX_Path::Point> path_points;
1478 path_points.swap(m_PathPoints);
1479 CFX_FillRenderOptions::FillType path_clip_type = m_PathClipType;
1480 m_PathClipType = CFX_FillRenderOptions::FillType::kNoFill;
1481
1482 if (path_points.empty())
1483 return;
1484
1485 if (path_points.size() == 1) {
1486 if (path_clip_type != CFX_FillRenderOptions::FillType::kNoFill) {
1487 CPDF_Path path;
1488 path.AppendRect(0, 0, 0, 0);
1489 m_pCurStates->m_ClipPath.AppendPathWithAutoMerge(
1490 path, CFX_FillRenderOptions::FillType::kWinding);
1491 return;
1492 }
1493
1494 CFX_Path::Point& point = path_points.front();
1495 if (point.m_Type != CFX_Path::Point::Type::kMove || !point.m_CloseFigure ||
1496 m_pCurStates->m_GraphState.GetLineCap() !=
1497 CFX_GraphStateData::LineCap::kRound) {
1498 return;
1499 }
1500
1501 // For round line cap only: When a path moves to a point and immediately
1502 // gets closed, we can treat it as drawing a path from this point to itself
1503 // and closing the path. This should not apply to butt line cap or
1504 // projecting square line cap since they should not be rendered.
1505 point.m_CloseFigure = false;
1506 path_points.emplace_back(point.m_Point, CFX_Path::Point::Type::kLine,
1507 /*close=*/true);
1508 }
1509
1510 if (path_points.back().IsTypeAndOpen(CFX_Path::Point::Type::kMove))
1511 path_points.pop_back();
1512
1513 CPDF_Path path;
1514 for (const auto& point : path_points) {
1515 if (point.m_CloseFigure)
1516 path.AppendPointAndClose(point.m_Point, point.m_Type);
1517 else
1518 path.AppendPoint(point.m_Point, point.m_Type);
1519 }
1520
1521 CFX_Matrix matrix = m_pCurStates->m_CTM * m_mtContentToUser;
1522 bool bStroke = render_type == RenderType::kStroke;
1523 if (bStroke || fill_type != CFX_FillRenderOptions::FillType::kNoFill) {
1524 auto pPathObj = std::make_unique<CPDF_PathObject>(GetCurrentStreamIndex());
1525 pPathObj->set_stroke(bStroke);
1526 pPathObj->set_filltype(fill_type);
1527 pPathObj->path() = path;
1528 SetGraphicStates(pPathObj.get(), true, false, true);
1529 pPathObj->SetPathMatrix(matrix);
1530 m_pObjectHolder->AppendPageObject(std::move(pPathObj));
1531 }
1532 if (path_clip_type != CFX_FillRenderOptions::FillType::kNoFill) {
1533 if (!matrix.IsIdentity())
1534 path.Transform(matrix);
1535 m_pCurStates->m_ClipPath.AppendPathWithAutoMerge(path, path_clip_type);
1536 }
1537 }
1538
Parse(pdfium::span<const uint8_t> pData,uint32_t start_offset,uint32_t max_cost,const std::vector<uint32_t> & stream_start_offsets)1539 uint32_t CPDF_StreamContentParser::Parse(
1540 pdfium::span<const uint8_t> pData,
1541 uint32_t start_offset,
1542 uint32_t max_cost,
1543 const std::vector<uint32_t>& stream_start_offsets) {
1544 DCHECK(start_offset < pData.size());
1545
1546 // Parsing will be done from within |pDataStart|.
1547 pdfium::span<const uint8_t> pDataStart = pData.subspan(start_offset);
1548 m_StartParseOffset = start_offset;
1549 if (m_RecursionState->parsed_set.size() > kMaxFormLevel ||
1550 pdfium::Contains(m_RecursionState->parsed_set, pDataStart.data())) {
1551 return fxcrt::CollectionSize<uint32_t>(pDataStart);
1552 }
1553
1554 m_StreamStartOffsets = stream_start_offsets;
1555
1556 ScopedSetInsertion<const uint8_t*> scoped_insert(
1557 &m_RecursionState->parsed_set, pDataStart.data());
1558
1559 uint32_t init_obj_count = m_pObjectHolder->GetPageObjectCount();
1560 AutoNuller<std::unique_ptr<CPDF_StreamParser>> auto_clearer(&m_pSyntax);
1561 m_pSyntax = std::make_unique<CPDF_StreamParser>(
1562 pDataStart, m_pDocument->GetByteStringPool());
1563
1564 while (true) {
1565 uint32_t cost = m_pObjectHolder->GetPageObjectCount() - init_obj_count;
1566 if (max_cost && cost >= max_cost) {
1567 break;
1568 }
1569 switch (m_pSyntax->ParseNextElement()) {
1570 case CPDF_StreamParser::ElementType::kEndOfData:
1571 return m_pSyntax->GetPos();
1572 case CPDF_StreamParser::ElementType::kKeyword:
1573 OnOperator(m_pSyntax->GetWord());
1574 ClearAllParams();
1575 break;
1576 case CPDF_StreamParser::ElementType::kNumber:
1577 AddNumberParam(m_pSyntax->GetWord());
1578 break;
1579 case CPDF_StreamParser::ElementType::kName: {
1580 auto word = m_pSyntax->GetWord();
1581 AddNameParam(word.Last(word.GetLength() - 1));
1582 break;
1583 }
1584 default:
1585 AddObjectParam(m_pSyntax->GetObject());
1586 }
1587 }
1588 return m_pSyntax->GetPos();
1589 }
1590
ParsePathObject()1591 void CPDF_StreamContentParser::ParsePathObject() {
1592 float params[6] = {};
1593 int nParams = 0;
1594 int last_pos = m_pSyntax->GetPos();
1595 while (true) {
1596 CPDF_StreamParser::ElementType type = m_pSyntax->ParseNextElement();
1597 bool bProcessed = true;
1598 switch (type) {
1599 case CPDF_StreamParser::ElementType::kEndOfData:
1600 return;
1601 case CPDF_StreamParser::ElementType::kKeyword: {
1602 ByteStringView strc = m_pSyntax->GetWord();
1603 int len = strc.GetLength();
1604 if (len == 1) {
1605 switch (strc[0]) {
1606 case kPathOperatorSubpath:
1607 AddPathPoint({params[0], params[1]},
1608 CFX_Path::Point::Type::kMove);
1609 nParams = 0;
1610 break;
1611 case kPathOperatorLine:
1612 AddPathPoint({params[0], params[1]},
1613 CFX_Path::Point::Type::kLine);
1614 nParams = 0;
1615 break;
1616 case kPathOperatorCubicBezier1:
1617 AddPathPoint({params[0], params[1]},
1618 CFX_Path::Point::Type::kBezier);
1619 AddPathPoint({params[2], params[3]},
1620 CFX_Path::Point::Type::kBezier);
1621 AddPathPoint({params[4], params[5]},
1622 CFX_Path::Point::Type::kBezier);
1623 nParams = 0;
1624 break;
1625 case kPathOperatorCubicBezier2:
1626 AddPathPoint(m_PathCurrent, CFX_Path::Point::Type::kBezier);
1627 AddPathPoint({params[0], params[1]},
1628 CFX_Path::Point::Type::kBezier);
1629 AddPathPoint({params[2], params[3]},
1630 CFX_Path::Point::Type::kBezier);
1631 nParams = 0;
1632 break;
1633 case kPathOperatorCubicBezier3:
1634 AddPathPoint({params[0], params[1]},
1635 CFX_Path::Point::Type::kBezier);
1636 AddPathPoint({params[2], params[3]},
1637 CFX_Path::Point::Type::kBezier);
1638 AddPathPoint({params[2], params[3]},
1639 CFX_Path::Point::Type::kBezier);
1640 nParams = 0;
1641 break;
1642 case kPathOperatorClosePath:
1643 Handle_ClosePath();
1644 nParams = 0;
1645 break;
1646 default:
1647 bProcessed = false;
1648 break;
1649 }
1650 } else if (len == 2) {
1651 if (strc[0] == kPathOperatorRectangle[0] &&
1652 strc[1] == kPathOperatorRectangle[1]) {
1653 AddPathRect(params[0], params[1], params[2], params[3]);
1654 nParams = 0;
1655 } else {
1656 bProcessed = false;
1657 }
1658 } else {
1659 bProcessed = false;
1660 }
1661 if (bProcessed) {
1662 last_pos = m_pSyntax->GetPos();
1663 }
1664 break;
1665 }
1666 case CPDF_StreamParser::ElementType::kNumber: {
1667 if (nParams == 6)
1668 break;
1669
1670 FX_Number number(m_pSyntax->GetWord());
1671 params[nParams++] = number.GetFloat();
1672 break;
1673 }
1674 default:
1675 bProcessed = false;
1676 }
1677 if (!bProcessed) {
1678 m_pSyntax->SetPos(last_pos);
1679 return;
1680 }
1681 }
1682 }
1683
1684 // static
FindKeyAbbreviationForTesting(ByteStringView abbr)1685 ByteStringView CPDF_StreamContentParser::FindKeyAbbreviationForTesting(
1686 ByteStringView abbr) {
1687 return FindFullName(kInlineKeyAbbr, abbr);
1688 }
1689
1690 // static
FindValueAbbreviationForTesting(ByteStringView abbr)1691 ByteStringView CPDF_StreamContentParser::FindValueAbbreviationForTesting(
1692 ByteStringView abbr) {
1693 return FindFullName(kInlineValueAbbr, abbr);
1694 }
1695
1696 CPDF_StreamContentParser::ContentParam::ContentParam() = default;
1697
1698 CPDF_StreamContentParser::ContentParam::~ContentParam() = default;
1699