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 pObj->SetGraphicsResourceNames(m_pCurStates->m_GraphicsResourceNames);
433 }
434
435 // static
436 CPDF_StreamContentParser::OpCodes
InitializeOpCodes()437 CPDF_StreamContentParser::InitializeOpCodes() {
438 return OpCodes({
439 {FXBSTR_ID('"', 0, 0, 0),
440 &CPDF_StreamContentParser::Handle_NextLineShowText_Space},
441 {FXBSTR_ID('\'', 0, 0, 0),
442 &CPDF_StreamContentParser::Handle_NextLineShowText},
443 {FXBSTR_ID('B', 0, 0, 0),
444 &CPDF_StreamContentParser::Handle_FillStrokePath},
445 {FXBSTR_ID('B', '*', 0, 0),
446 &CPDF_StreamContentParser::Handle_EOFillStrokePath},
447 {FXBSTR_ID('B', 'D', 'C', 0),
448 &CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary},
449 {FXBSTR_ID('B', 'I', 0, 0), &CPDF_StreamContentParser::Handle_BeginImage},
450 {FXBSTR_ID('B', 'M', 'C', 0),
451 &CPDF_StreamContentParser::Handle_BeginMarkedContent},
452 {FXBSTR_ID('B', 'T', 0, 0), &CPDF_StreamContentParser::Handle_BeginText},
453 {FXBSTR_ID('C', 'S', 0, 0),
454 &CPDF_StreamContentParser::Handle_SetColorSpace_Stroke},
455 {FXBSTR_ID('D', 'P', 0, 0),
456 &CPDF_StreamContentParser::Handle_MarkPlace_Dictionary},
457 {FXBSTR_ID('D', 'o', 0, 0),
458 &CPDF_StreamContentParser::Handle_ExecuteXObject},
459 {FXBSTR_ID('E', 'I', 0, 0), &CPDF_StreamContentParser::Handle_EndImage},
460 {FXBSTR_ID('E', 'M', 'C', 0),
461 &CPDF_StreamContentParser::Handle_EndMarkedContent},
462 {FXBSTR_ID('E', 'T', 0, 0), &CPDF_StreamContentParser::Handle_EndText},
463 {FXBSTR_ID('F', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPathOld},
464 {FXBSTR_ID('G', 0, 0, 0),
465 &CPDF_StreamContentParser::Handle_SetGray_Stroke},
466 {FXBSTR_ID('I', 'D', 0, 0),
467 &CPDF_StreamContentParser::Handle_BeginImageData},
468 {FXBSTR_ID('J', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineCap},
469 {FXBSTR_ID('K', 0, 0, 0),
470 &CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke},
471 {FXBSTR_ID('M', 0, 0, 0),
472 &CPDF_StreamContentParser::Handle_SetMiterLimit},
473 {FXBSTR_ID('M', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace},
474 {FXBSTR_ID('Q', 0, 0, 0),
475 &CPDF_StreamContentParser::Handle_RestoreGraphState},
476 {FXBSTR_ID('R', 'G', 0, 0),
477 &CPDF_StreamContentParser::Handle_SetRGBColor_Stroke},
478 {FXBSTR_ID('S', 0, 0, 0), &CPDF_StreamContentParser::Handle_StrokePath},
479 {FXBSTR_ID('S', 'C', 0, 0),
480 &CPDF_StreamContentParser::Handle_SetColor_Stroke},
481 {FXBSTR_ID('S', 'C', 'N', 0),
482 &CPDF_StreamContentParser::Handle_SetColorPS_Stroke},
483 {FXBSTR_ID('T', '*', 0, 0),
484 &CPDF_StreamContentParser::Handle_MoveToNextLine},
485 {FXBSTR_ID('T', 'D', 0, 0),
486 &CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading},
487 {FXBSTR_ID('T', 'J', 0, 0),
488 &CPDF_StreamContentParser::Handle_ShowText_Positioning},
489 {FXBSTR_ID('T', 'L', 0, 0),
490 &CPDF_StreamContentParser::Handle_SetTextLeading},
491 {FXBSTR_ID('T', 'c', 0, 0),
492 &CPDF_StreamContentParser::Handle_SetCharSpace},
493 {FXBSTR_ID('T', 'd', 0, 0),
494 &CPDF_StreamContentParser::Handle_MoveTextPoint},
495 {FXBSTR_ID('T', 'f', 0, 0), &CPDF_StreamContentParser::Handle_SetFont},
496 {FXBSTR_ID('T', 'j', 0, 0), &CPDF_StreamContentParser::Handle_ShowText},
497 {FXBSTR_ID('T', 'm', 0, 0),
498 &CPDF_StreamContentParser::Handle_SetTextMatrix},
499 {FXBSTR_ID('T', 'r', 0, 0),
500 &CPDF_StreamContentParser::Handle_SetTextRenderMode},
501 {FXBSTR_ID('T', 's', 0, 0),
502 &CPDF_StreamContentParser::Handle_SetTextRise},
503 {FXBSTR_ID('T', 'w', 0, 0),
504 &CPDF_StreamContentParser::Handle_SetWordSpace},
505 {FXBSTR_ID('T', 'z', 0, 0),
506 &CPDF_StreamContentParser::Handle_SetHorzScale},
507 {FXBSTR_ID('W', 0, 0, 0), &CPDF_StreamContentParser::Handle_Clip},
508 {FXBSTR_ID('W', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOClip},
509 {FXBSTR_ID('b', 0, 0, 0),
510 &CPDF_StreamContentParser::Handle_CloseFillStrokePath},
511 {FXBSTR_ID('b', '*', 0, 0),
512 &CPDF_StreamContentParser::Handle_CloseEOFillStrokePath},
513 {FXBSTR_ID('c', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_123},
514 {FXBSTR_ID('c', 'm', 0, 0),
515 &CPDF_StreamContentParser::Handle_ConcatMatrix},
516 {FXBSTR_ID('c', 's', 0, 0),
517 &CPDF_StreamContentParser::Handle_SetColorSpace_Fill},
518 {FXBSTR_ID('d', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetDash},
519 {FXBSTR_ID('d', '0', 0, 0),
520 &CPDF_StreamContentParser::Handle_SetCharWidth},
521 {FXBSTR_ID('d', '1', 0, 0),
522 &CPDF_StreamContentParser::Handle_SetCachedDevice},
523 {FXBSTR_ID('f', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPath},
524 {FXBSTR_ID('f', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillPath},
525 {FXBSTR_ID('g', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Fill},
526 {FXBSTR_ID('g', 's', 0, 0),
527 &CPDF_StreamContentParser::Handle_SetExtendGraphState},
528 {FXBSTR_ID('h', 0, 0, 0), &CPDF_StreamContentParser::Handle_ClosePath},
529 {FXBSTR_ID('i', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetFlat},
530 {FXBSTR_ID('j', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineJoin},
531 {FXBSTR_ID('k', 0, 0, 0),
532 &CPDF_StreamContentParser::Handle_SetCMYKColor_Fill},
533 {FXBSTR_ID('l', 0, 0, 0), &CPDF_StreamContentParser::Handle_LineTo},
534 {FXBSTR_ID('m', 0, 0, 0), &CPDF_StreamContentParser::Handle_MoveTo},
535 {FXBSTR_ID('n', 0, 0, 0), &CPDF_StreamContentParser::Handle_EndPath},
536 {FXBSTR_ID('q', 0, 0, 0),
537 &CPDF_StreamContentParser::Handle_SaveGraphState},
538 {FXBSTR_ID('r', 'e', 0, 0), &CPDF_StreamContentParser::Handle_Rectangle},
539 {FXBSTR_ID('r', 'g', 0, 0),
540 &CPDF_StreamContentParser::Handle_SetRGBColor_Fill},
541 {FXBSTR_ID('r', 'i', 0, 0),
542 &CPDF_StreamContentParser::Handle_SetRenderIntent},
543 {FXBSTR_ID('s', 0, 0, 0),
544 &CPDF_StreamContentParser::Handle_CloseStrokePath},
545 {FXBSTR_ID('s', 'c', 0, 0),
546 &CPDF_StreamContentParser::Handle_SetColor_Fill},
547 {FXBSTR_ID('s', 'c', 'n', 0),
548 &CPDF_StreamContentParser::Handle_SetColorPS_Fill},
549 {FXBSTR_ID('s', 'h', 0, 0), &CPDF_StreamContentParser::Handle_ShadeFill},
550 {FXBSTR_ID('v', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_23},
551 {FXBSTR_ID('w', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineWidth},
552 {FXBSTR_ID('y', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_13},
553 });
554 }
555
OnOperator(ByteStringView op)556 void CPDF_StreamContentParser::OnOperator(ByteStringView op) {
557 static const pdfium::base::NoDestructor<OpCodes> s_OpCodes(
558 InitializeOpCodes());
559
560 auto it = s_OpCodes->find(op.GetID());
561 if (it != s_OpCodes->end())
562 (this->*it->second)();
563 }
564
Handle_CloseFillStrokePath()565 void CPDF_StreamContentParser::Handle_CloseFillStrokePath() {
566 Handle_ClosePath();
567 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kStroke);
568 }
569
Handle_FillStrokePath()570 void CPDF_StreamContentParser::Handle_FillStrokePath() {
571 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kStroke);
572 }
573
Handle_CloseEOFillStrokePath()574 void CPDF_StreamContentParser::Handle_CloseEOFillStrokePath() {
575 AddPathPointAndClose(m_PathStart, CFX_Path::Point::Type::kLine);
576 AddPathObject(CFX_FillRenderOptions::FillType::kEvenOdd, RenderType::kStroke);
577 }
578
Handle_EOFillStrokePath()579 void CPDF_StreamContentParser::Handle_EOFillStrokePath() {
580 AddPathObject(CFX_FillRenderOptions::FillType::kEvenOdd, RenderType::kStroke);
581 }
582
Handle_BeginMarkedContent_Dictionary()583 void CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary() {
584 RetainPtr<CPDF_Object> pProperty = GetObject(0);
585 if (!pProperty)
586 return;
587
588 ByteString tag = GetString(1);
589 std::unique_ptr<CPDF_ContentMarks> new_marks =
590 m_ContentMarksStack.top()->Clone();
591
592 if (pProperty->IsName()) {
593 ByteString property_name = pProperty->GetString();
594 RetainPtr<CPDF_Dictionary> pHolder = FindResourceHolder("Properties");
595 if (!pHolder || !pHolder->GetDictFor(property_name))
596 return;
597 new_marks->AddMarkWithPropertiesHolder(tag, std::move(pHolder),
598 property_name);
599 } else if (pProperty->IsDictionary()) {
600 new_marks->AddMarkWithDirectDict(tag, ToDictionary(pProperty));
601 } else {
602 return;
603 }
604 m_ContentMarksStack.push(std::move(new_marks));
605 }
606
Handle_BeginImage()607 void CPDF_StreamContentParser::Handle_BeginImage() {
608 FX_FILESIZE savePos = m_pSyntax->GetPos();
609 auto pDict = m_pDocument->New<CPDF_Dictionary>();
610 while (true) {
611 CPDF_StreamParser::ElementType type = m_pSyntax->ParseNextElement();
612 if (type == CPDF_StreamParser::ElementType::kKeyword) {
613 if (m_pSyntax->GetWord() != "ID") {
614 m_pSyntax->SetPos(savePos);
615 return;
616 }
617 }
618 if (type != CPDF_StreamParser::ElementType::kName) {
619 break;
620 }
621 auto word = m_pSyntax->GetWord();
622 ByteString key(word.Last(word.GetLength() - 1));
623 auto pObj = m_pSyntax->ReadNextObject(false, false, 0);
624 if (pObj && !pObj->IsInline()) {
625 pDict->SetNewFor<CPDF_Reference>(key, m_pDocument, pObj->GetObjNum());
626 } else {
627 pDict->SetFor(key, std::move(pObj));
628 }
629 }
630 ReplaceAbbr(pDict);
631 RetainPtr<const CPDF_Object> pCSObj;
632 if (pDict->KeyExist("ColorSpace")) {
633 pCSObj = pDict->GetDirectObjectFor("ColorSpace");
634 if (pCSObj->IsName()) {
635 ByteString name = pCSObj->GetString();
636 if (name != "DeviceRGB" && name != "DeviceGray" && name != "DeviceCMYK") {
637 pCSObj = FindResourceObj("ColorSpace", name);
638 if (pCSObj && pCSObj->IsInline())
639 pDict->SetFor("ColorSpace", pCSObj->Clone());
640 }
641 }
642 }
643 pDict->SetNewFor<CPDF_Name>("Subtype", "Image");
644 RetainPtr<CPDF_Stream> pStream =
645 m_pSyntax->ReadInlineStream(m_pDocument, std::move(pDict), pCSObj.Get());
646 while (true) {
647 CPDF_StreamParser::ElementType type = m_pSyntax->ParseNextElement();
648 if (type == CPDF_StreamParser::ElementType::kEndOfData)
649 break;
650
651 if (type != CPDF_StreamParser::ElementType::kKeyword)
652 continue;
653
654 if (m_pSyntax->GetWord() == "EI")
655 break;
656 }
657 CPDF_ImageObject* pObj =
658 AddImageFromStream(std::move(pStream), /*resource_name=*/"");
659 // Record the bounding box of this image, so rendering code can draw it
660 // properly.
661 if (pObj && pObj->GetImage()->IsMask())
662 m_pObjectHolder->AddImageMaskBoundingBox(pObj->GetRect());
663 }
664
Handle_BeginMarkedContent()665 void CPDF_StreamContentParser::Handle_BeginMarkedContent() {
666 std::unique_ptr<CPDF_ContentMarks> new_marks =
667 m_ContentMarksStack.top()->Clone();
668 new_marks->AddMark(GetString(0));
669 m_ContentMarksStack.push(std::move(new_marks));
670 }
671
Handle_BeginText()672 void CPDF_StreamContentParser::Handle_BeginText() {
673 m_pCurStates->m_TextMatrix = CFX_Matrix();
674 OnChangeTextMatrix();
675 m_pCurStates->m_TextPos = CFX_PointF();
676 m_pCurStates->m_TextLinePos = CFX_PointF();
677 }
678
Handle_CurveTo_123()679 void CPDF_StreamContentParser::Handle_CurveTo_123() {
680 AddPathPoint(GetPoint(4), CFX_Path::Point::Type::kBezier);
681 AddPathPoint(GetPoint(2), CFX_Path::Point::Type::kBezier);
682 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
683 }
684
Handle_ConcatMatrix()685 void CPDF_StreamContentParser::Handle_ConcatMatrix() {
686 m_pCurStates->m_CTM = GetMatrix() * m_pCurStates->m_CTM;
687 OnChangeTextMatrix();
688 }
689
Handle_SetColorSpace_Fill()690 void CPDF_StreamContentParser::Handle_SetColorSpace_Fill() {
691 RetainPtr<CPDF_ColorSpace> pCS = FindColorSpace(GetString(0));
692 if (!pCS)
693 return;
694
695 m_pCurStates->m_ColorState.GetMutableFillColor()->SetColorSpace(
696 std::move(pCS));
697 }
698
Handle_SetColorSpace_Stroke()699 void CPDF_StreamContentParser::Handle_SetColorSpace_Stroke() {
700 RetainPtr<CPDF_ColorSpace> pCS = FindColorSpace(GetString(0));
701 if (!pCS)
702 return;
703
704 m_pCurStates->m_ColorState.GetMutableStrokeColor()->SetColorSpace(
705 std::move(pCS));
706 }
707
Handle_SetDash()708 void CPDF_StreamContentParser::Handle_SetDash() {
709 RetainPtr<CPDF_Array> pArray = ToArray(GetObject(1));
710 if (!pArray)
711 return;
712
713 m_pCurStates->SetLineDash(pArray.Get(), GetNumber(0), 1.0f);
714 }
715
Handle_SetCharWidth()716 void CPDF_StreamContentParser::Handle_SetCharWidth() {
717 m_Type3Data[0] = GetNumber(1);
718 m_Type3Data[1] = GetNumber(0);
719 m_bColored = true;
720 }
721
Handle_SetCachedDevice()722 void CPDF_StreamContentParser::Handle_SetCachedDevice() {
723 for (int i = 0; i < 6; i++) {
724 m_Type3Data[i] = GetNumber(5 - i);
725 }
726 m_bColored = false;
727 }
728
Handle_ExecuteXObject()729 void CPDF_StreamContentParser::Handle_ExecuteXObject() {
730 ByteString name = GetString(0);
731 if (name == m_LastImageName && m_pLastImage && m_pLastImage->GetStream() &&
732 m_pLastImage->GetStream()->GetObjNum()) {
733 CPDF_ImageObject* pObj = AddLastImage();
734 // Record the bounding box of this image, so rendering code can draw it
735 // properly.
736 if (pObj && pObj->GetImage()->IsMask())
737 m_pObjectHolder->AddImageMaskBoundingBox(pObj->GetRect());
738 return;
739 }
740
741 RetainPtr<CPDF_Stream> pXObject(ToStream(FindResourceObj("XObject", name)));
742 if (!pXObject)
743 return;
744
745 ByteString type;
746 if (pXObject->GetDict())
747 type = pXObject->GetDict()->GetByteStringFor("Subtype");
748
749 if (type == "Form") {
750 if (m_RecursionState->form_count > kFormCountLimit) {
751 return;
752 }
753
754 const bool is_first = m_RecursionState->form_count == 0;
755 ++m_RecursionState->form_count;
756 AddForm(std::move(pXObject), name);
757 if (is_first) {
758 m_RecursionState->form_count = 0;
759 }
760 return;
761 }
762
763 if (type == "Image") {
764 CPDF_ImageObject* pObj =
765 pXObject->IsInline()
766 ? AddImageFromStream(ToStream(pXObject->Clone()), name)
767 : AddImageFromStreamObjNum(pXObject->GetObjNum(), name);
768
769 m_LastImageName = std::move(name);
770 if (pObj) {
771 m_pLastImage = pObj->GetImage();
772 if (m_pLastImage->IsMask())
773 m_pObjectHolder->AddImageMaskBoundingBox(pObj->GetRect());
774 }
775 }
776 }
777
AddForm(RetainPtr<CPDF_Stream> pStream,const ByteString & name)778 void CPDF_StreamContentParser::AddForm(RetainPtr<CPDF_Stream> pStream,
779 const ByteString& name) {
780 CPDF_AllStates status;
781 status.m_GeneralState = m_pCurStates->m_GeneralState;
782 status.m_GraphState = m_pCurStates->m_GraphState;
783 status.m_ColorState = m_pCurStates->m_ColorState;
784 status.m_TextState = m_pCurStates->m_TextState;
785 auto form = std::make_unique<CPDF_Form>(
786 m_pDocument, m_pPageResources, std::move(pStream), m_pResources.Get());
787 form->ParseContent(&status, nullptr, m_RecursionState);
788
789 CFX_Matrix matrix = m_pCurStates->m_CTM * m_mtContentToUser;
790 auto pFormObj = std::make_unique<CPDF_FormObject>(GetCurrentStreamIndex(),
791 std::move(form), matrix);
792 pFormObj->SetResourceName(name);
793 pFormObj->SetGraphicsResourceNames(m_pCurStates->m_GraphicsResourceNames);
794 if (!m_pObjectHolder->BackgroundAlphaNeeded() &&
795 pFormObj->form()->BackgroundAlphaNeeded()) {
796 m_pObjectHolder->SetBackgroundAlphaNeeded(true);
797 }
798 pFormObj->CalcBoundingBox();
799 SetGraphicStates(pFormObj.get(), true, true, true);
800 m_pObjectHolder->AppendPageObject(std::move(pFormObj));
801 }
802
AddImageFromStream(RetainPtr<CPDF_Stream> pStream,const ByteString & name)803 CPDF_ImageObject* CPDF_StreamContentParser::AddImageFromStream(
804 RetainPtr<CPDF_Stream> pStream,
805 const ByteString& name) {
806 if (!pStream)
807 return nullptr;
808
809 auto pImageObj = std::make_unique<CPDF_ImageObject>(GetCurrentStreamIndex());
810 pImageObj->SetResourceName(name);
811 pImageObj->SetImage(
812 pdfium::MakeRetain<CPDF_Image>(m_pDocument, std::move(pStream)));
813
814 return AddImageObject(std::move(pImageObj));
815 }
816
AddImageFromStreamObjNum(uint32_t stream_obj_num,const ByteString & name)817 CPDF_ImageObject* CPDF_StreamContentParser::AddImageFromStreamObjNum(
818 uint32_t stream_obj_num,
819 const ByteString& name) {
820 auto pImageObj = std::make_unique<CPDF_ImageObject>(GetCurrentStreamIndex());
821 pImageObj->SetResourceName(name);
822 pImageObj->SetImage(
823 CPDF_DocPageData::FromDocument(m_pDocument)->GetImage(stream_obj_num));
824
825 return AddImageObject(std::move(pImageObj));
826 }
827
AddLastImage()828 CPDF_ImageObject* CPDF_StreamContentParser::AddLastImage() {
829 DCHECK(m_pLastImage);
830
831 auto pImageObj = std::make_unique<CPDF_ImageObject>(GetCurrentStreamIndex());
832 pImageObj->SetResourceName(m_LastImageName);
833 pImageObj->SetImage(CPDF_DocPageData::FromDocument(m_pDocument)
834 ->GetImage(m_pLastImage->GetStream()->GetObjNum()));
835
836 return AddImageObject(std::move(pImageObj));
837 }
838
AddImageObject(std::unique_ptr<CPDF_ImageObject> pImageObj)839 CPDF_ImageObject* CPDF_StreamContentParser::AddImageObject(
840 std::unique_ptr<CPDF_ImageObject> pImageObj) {
841 SetGraphicStates(pImageObj.get(), pImageObj->GetImage()->IsMask(), false,
842 false);
843
844 CFX_Matrix ImageMatrix = m_pCurStates->m_CTM * m_mtContentToUser;
845 pImageObj->SetImageMatrix(ImageMatrix);
846
847 CPDF_ImageObject* pRet = pImageObj.get();
848 m_pObjectHolder->AppendPageObject(std::move(pImageObj));
849 return pRet;
850 }
851
GetColors() const852 std::vector<float> CPDF_StreamContentParser::GetColors() const {
853 DCHECK(m_ParamCount > 0);
854 return GetNumbers(m_ParamCount);
855 }
856
GetNamedColors() const857 std::vector<float> CPDF_StreamContentParser::GetNamedColors() const {
858 DCHECK(m_ParamCount > 0);
859 const uint32_t nvalues = m_ParamCount - 1;
860 std::vector<float> values(nvalues);
861 for (size_t i = 0; i < nvalues; ++i)
862 values[i] = GetNumber(m_ParamCount - i - 1);
863 return values;
864 }
865
Handle_MarkPlace_Dictionary()866 void CPDF_StreamContentParser::Handle_MarkPlace_Dictionary() {}
867
Handle_EndImage()868 void CPDF_StreamContentParser::Handle_EndImage() {}
869
Handle_EndMarkedContent()870 void CPDF_StreamContentParser::Handle_EndMarkedContent() {
871 // First element is a sentinel, so do not pop it, ever. This may come up if
872 // the EMCs are mismatched with the BMC/BDCs.
873 if (m_ContentMarksStack.size() > 1)
874 m_ContentMarksStack.pop();
875 }
876
Handle_EndText()877 void CPDF_StreamContentParser::Handle_EndText() {
878 if (m_ClipTextList.empty())
879 return;
880
881 if (TextRenderingModeIsClipMode(m_pCurStates->m_TextState.GetTextMode()))
882 m_pCurStates->m_ClipPath.AppendTexts(&m_ClipTextList);
883
884 m_ClipTextList.clear();
885 }
886
Handle_FillPath()887 void CPDF_StreamContentParser::Handle_FillPath() {
888 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kFill);
889 }
890
Handle_FillPathOld()891 void CPDF_StreamContentParser::Handle_FillPathOld() {
892 AddPathObject(CFX_FillRenderOptions::FillType::kWinding, RenderType::kFill);
893 }
894
Handle_EOFillPath()895 void CPDF_StreamContentParser::Handle_EOFillPath() {
896 AddPathObject(CFX_FillRenderOptions::FillType::kEvenOdd, RenderType::kFill);
897 }
898
Handle_SetGray_Fill()899 void CPDF_StreamContentParser::Handle_SetGray_Fill() {
900 m_pCurStates->m_ColorState.SetFillColor(
901 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceGray),
902 GetNumbers(1));
903 }
904
Handle_SetGray_Stroke()905 void CPDF_StreamContentParser::Handle_SetGray_Stroke() {
906 m_pCurStates->m_ColorState.SetStrokeColor(
907 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceGray),
908 GetNumbers(1));
909 }
910
Handle_SetExtendGraphState()911 void CPDF_StreamContentParser::Handle_SetExtendGraphState() {
912 ByteString name = GetString(0);
913 RetainPtr<CPDF_Dictionary> pGS =
914 ToDictionary(FindResourceObj("ExtGState", name));
915 if (!pGS)
916 return;
917
918 CHECK(!name.IsEmpty());
919 m_pCurStates->m_GraphicsResourceNames.push_back(std::move(name));
920 m_pCurStates->ProcessExtGS(pGS.Get(), this);
921 }
922
Handle_ClosePath()923 void CPDF_StreamContentParser::Handle_ClosePath() {
924 if (m_PathPoints.empty())
925 return;
926
927 if (m_PathStart.x != m_PathCurrent.x || m_PathStart.y != m_PathCurrent.y) {
928 AddPathPointAndClose(m_PathStart, CFX_Path::Point::Type::kLine);
929 } else {
930 m_PathPoints.back().m_CloseFigure = true;
931 }
932 }
933
Handle_SetFlat()934 void CPDF_StreamContentParser::Handle_SetFlat() {
935 m_pCurStates->m_GeneralState.SetFlatness(GetNumber(0));
936 }
937
Handle_BeginImageData()938 void CPDF_StreamContentParser::Handle_BeginImageData() {}
939
Handle_SetLineJoin()940 void CPDF_StreamContentParser::Handle_SetLineJoin() {
941 m_pCurStates->m_GraphState.SetLineJoin(
942 static_cast<CFX_GraphStateData::LineJoin>(GetInteger(0)));
943 }
944
Handle_SetLineCap()945 void CPDF_StreamContentParser::Handle_SetLineCap() {
946 m_pCurStates->m_GraphState.SetLineCap(
947 static_cast<CFX_GraphStateData::LineCap>(GetInteger(0)));
948 }
949
Handle_SetCMYKColor_Fill()950 void CPDF_StreamContentParser::Handle_SetCMYKColor_Fill() {
951 if (m_ParamCount != 4)
952 return;
953
954 m_pCurStates->m_ColorState.SetFillColor(
955 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceCMYK),
956 GetNumbers(4));
957 }
958
Handle_SetCMYKColor_Stroke()959 void CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke() {
960 if (m_ParamCount != 4)
961 return;
962
963 m_pCurStates->m_ColorState.SetStrokeColor(
964 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceCMYK),
965 GetNumbers(4));
966 }
967
Handle_LineTo()968 void CPDF_StreamContentParser::Handle_LineTo() {
969 if (m_ParamCount != 2)
970 return;
971
972 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kLine);
973 }
974
Handle_MoveTo()975 void CPDF_StreamContentParser::Handle_MoveTo() {
976 if (m_ParamCount != 2)
977 return;
978
979 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kMove);
980 ParsePathObject();
981 }
982
Handle_SetMiterLimit()983 void CPDF_StreamContentParser::Handle_SetMiterLimit() {
984 m_pCurStates->m_GraphState.SetMiterLimit(GetNumber(0));
985 }
986
Handle_MarkPlace()987 void CPDF_StreamContentParser::Handle_MarkPlace() {}
988
Handle_EndPath()989 void CPDF_StreamContentParser::Handle_EndPath() {
990 AddPathObject(CFX_FillRenderOptions::FillType::kNoFill, RenderType::kFill);
991 }
992
Handle_SaveGraphState()993 void CPDF_StreamContentParser::Handle_SaveGraphState() {
994 auto pStates = std::make_unique<CPDF_AllStates>();
995 pStates->Copy(*m_pCurStates);
996 m_StateStack.push_back(std::move(pStates));
997 }
998
Handle_RestoreGraphState()999 void CPDF_StreamContentParser::Handle_RestoreGraphState() {
1000 if (m_StateStack.empty())
1001 return;
1002 std::unique_ptr<CPDF_AllStates> pStates = std::move(m_StateStack.back());
1003 m_StateStack.pop_back();
1004 m_pCurStates->Copy(*pStates);
1005 }
1006
Handle_Rectangle()1007 void CPDF_StreamContentParser::Handle_Rectangle() {
1008 float x = GetNumber(3);
1009 float y = GetNumber(2);
1010 float w = GetNumber(1);
1011 float h = GetNumber(0);
1012 AddPathRect(x, y, w, h);
1013 }
1014
AddPathRect(float x,float y,float w,float h)1015 void CPDF_StreamContentParser::AddPathRect(float x, float y, float w, float h) {
1016 AddPathPoint({x, y}, CFX_Path::Point::Type::kMove);
1017 AddPathPoint({x + w, y}, CFX_Path::Point::Type::kLine);
1018 AddPathPoint({x + w, y + h}, CFX_Path::Point::Type::kLine);
1019 AddPathPoint({x, y + h}, CFX_Path::Point::Type::kLine);
1020 AddPathPointAndClose({x, y}, CFX_Path::Point::Type::kLine);
1021 }
1022
Handle_SetRGBColor_Fill()1023 void CPDF_StreamContentParser::Handle_SetRGBColor_Fill() {
1024 if (m_ParamCount != 3)
1025 return;
1026
1027 m_pCurStates->m_ColorState.SetFillColor(
1028 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceRGB),
1029 GetNumbers(3));
1030 }
1031
Handle_SetRGBColor_Stroke()1032 void CPDF_StreamContentParser::Handle_SetRGBColor_Stroke() {
1033 if (m_ParamCount != 3)
1034 return;
1035
1036 m_pCurStates->m_ColorState.SetStrokeColor(
1037 CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceRGB),
1038 GetNumbers(3));
1039 }
1040
Handle_SetRenderIntent()1041 void CPDF_StreamContentParser::Handle_SetRenderIntent() {}
1042
Handle_CloseStrokePath()1043 void CPDF_StreamContentParser::Handle_CloseStrokePath() {
1044 Handle_ClosePath();
1045 AddPathObject(CFX_FillRenderOptions::FillType::kNoFill, RenderType::kStroke);
1046 }
1047
Handle_StrokePath()1048 void CPDF_StreamContentParser::Handle_StrokePath() {
1049 AddPathObject(CFX_FillRenderOptions::FillType::kNoFill, RenderType::kStroke);
1050 }
1051
Handle_SetColor_Fill()1052 void CPDF_StreamContentParser::Handle_SetColor_Fill() {
1053 int nargs = std::min(m_ParamCount, 4U);
1054 m_pCurStates->m_ColorState.SetFillColor(nullptr, GetNumbers(nargs));
1055 }
1056
Handle_SetColor_Stroke()1057 void CPDF_StreamContentParser::Handle_SetColor_Stroke() {
1058 int nargs = std::min(m_ParamCount, 4U);
1059 m_pCurStates->m_ColorState.SetStrokeColor(nullptr, GetNumbers(nargs));
1060 }
1061
Handle_SetColorPS_Fill()1062 void CPDF_StreamContentParser::Handle_SetColorPS_Fill() {
1063 RetainPtr<CPDF_Object> pLastParam = GetObject(0);
1064 if (!pLastParam)
1065 return;
1066
1067 if (!pLastParam->IsName()) {
1068 m_pCurStates->m_ColorState.SetFillColor(nullptr, GetColors());
1069 return;
1070 }
1071
1072 // A valid |pLastParam| implies |m_ParamCount| > 0, so GetNamedColors() call
1073 // below is safe.
1074 RetainPtr<CPDF_Pattern> pPattern = FindPattern(GetString(0));
1075 if (!pPattern)
1076 return;
1077
1078 std::vector<float> values = GetNamedColors();
1079 m_pCurStates->m_ColorState.SetFillPattern(std::move(pPattern), values);
1080 }
1081
Handle_SetColorPS_Stroke()1082 void CPDF_StreamContentParser::Handle_SetColorPS_Stroke() {
1083 RetainPtr<CPDF_Object> pLastParam = GetObject(0);
1084 if (!pLastParam)
1085 return;
1086
1087 if (!pLastParam->IsName()) {
1088 m_pCurStates->m_ColorState.SetStrokeColor(nullptr, GetColors());
1089 return;
1090 }
1091
1092 // A valid |pLastParam| implies |m_ParamCount| > 0, so GetNamedColors() call
1093 // below is safe.
1094 RetainPtr<CPDF_Pattern> pPattern = FindPattern(GetString(0));
1095 if (!pPattern)
1096 return;
1097
1098 std::vector<float> values = GetNamedColors();
1099 m_pCurStates->m_ColorState.SetStrokePattern(std::move(pPattern), values);
1100 }
1101
Handle_ShadeFill()1102 void CPDF_StreamContentParser::Handle_ShadeFill() {
1103 RetainPtr<CPDF_ShadingPattern> pShading = FindShading(GetString(0));
1104 if (!pShading)
1105 return;
1106
1107 if (!pShading->IsShadingObject() || !pShading->Load())
1108 return;
1109
1110 CFX_Matrix matrix = m_pCurStates->m_CTM * m_mtContentToUser;
1111 auto pObj = std::make_unique<CPDF_ShadingObject>(GetCurrentStreamIndex(),
1112 pShading, matrix);
1113 SetGraphicStates(pObj.get(), false, false, false);
1114 CFX_FloatRect bbox =
1115 pObj->m_ClipPath.HasRef() ? pObj->m_ClipPath.GetClipBox() : m_BBox;
1116 if (pShading->IsMeshShading())
1117 bbox.Intersect(GetShadingBBox(pShading.Get(), pObj->matrix()));
1118 pObj->SetRect(bbox);
1119 m_pObjectHolder->AppendPageObject(std::move(pObj));
1120 }
1121
Handle_SetCharSpace()1122 void CPDF_StreamContentParser::Handle_SetCharSpace() {
1123 m_pCurStates->m_TextState.SetCharSpace(GetNumber(0));
1124 }
1125
Handle_MoveTextPoint()1126 void CPDF_StreamContentParser::Handle_MoveTextPoint() {
1127 m_pCurStates->m_TextLinePos += GetPoint(0);
1128 m_pCurStates->m_TextPos = m_pCurStates->m_TextLinePos;
1129 }
1130
Handle_MoveTextPoint_SetLeading()1131 void CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading() {
1132 Handle_MoveTextPoint();
1133 m_pCurStates->m_TextLeading = -GetNumber(0);
1134 }
1135
Handle_SetFont()1136 void CPDF_StreamContentParser::Handle_SetFont() {
1137 m_pCurStates->m_TextState.SetFontSize(GetNumber(0));
1138 RetainPtr<CPDF_Font> pFont = FindFont(GetString(1));
1139 if (pFont)
1140 m_pCurStates->m_TextState.SetFont(std::move(pFont));
1141 }
1142
FindResourceHolder(const ByteString & type)1143 RetainPtr<CPDF_Dictionary> CPDF_StreamContentParser::FindResourceHolder(
1144 const ByteString& type) {
1145 if (!m_pResources)
1146 return nullptr;
1147
1148 RetainPtr<CPDF_Dictionary> pDict = m_pResources->GetMutableDictFor(type);
1149 if (pDict)
1150 return pDict;
1151
1152 if (m_pResources == m_pPageResources || !m_pPageResources)
1153 return nullptr;
1154
1155 return m_pPageResources->GetMutableDictFor(type);
1156 }
1157
FindResourceObj(const ByteString & type,const ByteString & name)1158 RetainPtr<CPDF_Object> CPDF_StreamContentParser::FindResourceObj(
1159 const ByteString& type,
1160 const ByteString& name) {
1161 RetainPtr<CPDF_Dictionary> pHolder = FindResourceHolder(type);
1162 return pHolder ? pHolder->GetMutableDirectObjectFor(name) : nullptr;
1163 }
1164
FindFont(const ByteString & name)1165 RetainPtr<CPDF_Font> CPDF_StreamContentParser::FindFont(
1166 const ByteString& name) {
1167 RetainPtr<CPDF_Dictionary> pFontDict(
1168 ToDictionary(FindResourceObj("Font", name)));
1169 if (!pFontDict) {
1170 return CPDF_Font::GetStockFont(m_pDocument, CFX_Font::kDefaultAnsiFontName);
1171 }
1172 RetainPtr<CPDF_Font> pFont = CPDF_DocPageData::FromDocument(m_pDocument)
1173 ->GetFont(std::move(pFontDict));
1174 if (pFont) {
1175 // Save `name` for later retrieval by the CPDF_TextObject that uses the
1176 // font.
1177 pFont->SetResourceName(name);
1178 if (pFont->IsType3Font()) {
1179 pFont->AsType3Font()->SetPageResources(m_pResources.Get());
1180 pFont->AsType3Font()->CheckType3FontMetrics();
1181 }
1182 }
1183 return pFont;
1184 }
1185
FindColorSpace(const ByteString & name)1186 RetainPtr<CPDF_ColorSpace> CPDF_StreamContentParser::FindColorSpace(
1187 const ByteString& name) {
1188 if (name == "Pattern")
1189 return CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kPattern);
1190
1191 if (name == "DeviceGray" || name == "DeviceCMYK" || name == "DeviceRGB") {
1192 ByteString defname = "Default";
1193 defname += name.Last(name.GetLength() - 7);
1194 RetainPtr<const CPDF_Object> pDefObj =
1195 FindResourceObj("ColorSpace", defname);
1196 if (!pDefObj) {
1197 if (name == "DeviceGray") {
1198 return CPDF_ColorSpace::GetStockCS(
1199 CPDF_ColorSpace::Family::kDeviceGray);
1200 }
1201 if (name == "DeviceRGB")
1202 return CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceRGB);
1203
1204 return CPDF_ColorSpace::GetStockCS(CPDF_ColorSpace::Family::kDeviceCMYK);
1205 }
1206 return CPDF_DocPageData::FromDocument(m_pDocument)
1207 ->GetColorSpace(pDefObj.Get(), nullptr);
1208 }
1209 RetainPtr<const CPDF_Object> pCSObj = FindResourceObj("ColorSpace", name);
1210 if (!pCSObj)
1211 return nullptr;
1212 return CPDF_DocPageData::FromDocument(m_pDocument)
1213 ->GetColorSpace(pCSObj.Get(), nullptr);
1214 }
1215
FindPattern(const ByteString & name)1216 RetainPtr<CPDF_Pattern> CPDF_StreamContentParser::FindPattern(
1217 const ByteString& name) {
1218 RetainPtr<CPDF_Object> pPattern = FindResourceObj("Pattern", name);
1219 if (!pPattern || (!pPattern->IsDictionary() && !pPattern->IsStream()))
1220 return nullptr;
1221 return CPDF_DocPageData::FromDocument(m_pDocument)
1222 ->GetPattern(std::move(pPattern), m_pCurStates->m_ParentMatrix);
1223 }
1224
FindShading(const ByteString & name)1225 RetainPtr<CPDF_ShadingPattern> CPDF_StreamContentParser::FindShading(
1226 const ByteString& name) {
1227 RetainPtr<CPDF_Object> pPattern = FindResourceObj("Shading", name);
1228 if (!pPattern || (!pPattern->IsDictionary() && !pPattern->IsStream()))
1229 return nullptr;
1230 return CPDF_DocPageData::FromDocument(m_pDocument)
1231 ->GetShading(std::move(pPattern), m_pCurStates->m_ParentMatrix);
1232 }
1233
AddTextObject(const ByteString * pStrs,float fInitKerning,const std::vector<float> & kernings,size_t nSegs)1234 void CPDF_StreamContentParser::AddTextObject(const ByteString* pStrs,
1235 float fInitKerning,
1236 const std::vector<float>& kernings,
1237 size_t nSegs) {
1238 RetainPtr<CPDF_Font> pFont = m_pCurStates->m_TextState.GetFont();
1239 if (!pFont)
1240 return;
1241
1242 if (fInitKerning != 0) {
1243 if (pFont->IsVertWriting())
1244 m_pCurStates->m_TextPos.y -= GetVerticalTextSize(fInitKerning);
1245 else
1246 m_pCurStates->m_TextPos.x -= GetHorizontalTextSize(fInitKerning);
1247 }
1248 if (nSegs == 0)
1249 return;
1250
1251 const TextRenderingMode text_mode =
1252 pFont->IsType3Font() ? TextRenderingMode::MODE_FILL
1253 : m_pCurStates->m_TextState.GetTextMode();
1254 {
1255 auto pText = std::make_unique<CPDF_TextObject>(GetCurrentStreamIndex());
1256 pText->SetResourceName(pFont->GetResourceName());
1257 SetGraphicStates(pText.get(), true, true, true);
1258 if (TextRenderingModeIsStrokeMode(text_mode)) {
1259 pdfium::span<float> pCTM = pText->m_TextState.GetMutableCTM();
1260 pCTM[0] = m_pCurStates->m_CTM.a;
1261 pCTM[1] = m_pCurStates->m_CTM.c;
1262 pCTM[2] = m_pCurStates->m_CTM.b;
1263 pCTM[3] = m_pCurStates->m_CTM.d;
1264 }
1265 pText->SetSegments(pStrs, kernings, nSegs);
1266 pText->SetPosition(
1267 m_mtContentToUser.Transform(m_pCurStates->m_CTM.Transform(
1268 m_pCurStates->m_TextMatrix.Transform(CFX_PointF(
1269 m_pCurStates->m_TextPos.x,
1270 m_pCurStates->m_TextPos.y + m_pCurStates->m_TextRise)))));
1271
1272 m_pCurStates->m_TextPos +=
1273 pText->CalcPositionData(m_pCurStates->m_TextHorzScale);
1274 if (TextRenderingModeIsClipMode(text_mode))
1275 m_ClipTextList.push_back(pText->Clone());
1276 m_pObjectHolder->AppendPageObject(std::move(pText));
1277 }
1278 if (!kernings.empty() && kernings[nSegs - 1] != 0) {
1279 if (pFont->IsVertWriting())
1280 m_pCurStates->m_TextPos.y -= GetVerticalTextSize(kernings[nSegs - 1]);
1281 else
1282 m_pCurStates->m_TextPos.x -= GetHorizontalTextSize(kernings[nSegs - 1]);
1283 }
1284 }
1285
GetHorizontalTextSize(float fKerning) const1286 float CPDF_StreamContentParser::GetHorizontalTextSize(float fKerning) const {
1287 return GetVerticalTextSize(fKerning) * m_pCurStates->m_TextHorzScale;
1288 }
1289
GetVerticalTextSize(float fKerning) const1290 float CPDF_StreamContentParser::GetVerticalTextSize(float fKerning) const {
1291 return fKerning * m_pCurStates->m_TextState.GetFontSize() / 1000;
1292 }
1293
GetCurrentStreamIndex()1294 int32_t CPDF_StreamContentParser::GetCurrentStreamIndex() {
1295 auto it =
1296 std::upper_bound(m_StreamStartOffsets.begin(), m_StreamStartOffsets.end(),
1297 m_pSyntax->GetPos() + m_StartParseOffset);
1298 return (it - m_StreamStartOffsets.begin()) - 1;
1299 }
1300
Handle_ShowText()1301 void CPDF_StreamContentParser::Handle_ShowText() {
1302 ByteString str = GetString(0);
1303 if (!str.IsEmpty())
1304 AddTextObject(&str, 0, std::vector<float>(), 1);
1305 }
1306
Handle_ShowText_Positioning()1307 void CPDF_StreamContentParser::Handle_ShowText_Positioning() {
1308 RetainPtr<CPDF_Array> pArray = ToArray(GetObject(0));
1309 if (!pArray)
1310 return;
1311
1312 size_t n = pArray->size();
1313 size_t nsegs = 0;
1314 for (size_t i = 0; i < n; i++) {
1315 RetainPtr<const CPDF_Object> pDirectObject = pArray->GetDirectObjectAt(i);
1316 if (pDirectObject && pDirectObject->IsString())
1317 nsegs++;
1318 }
1319 if (nsegs == 0) {
1320 for (size_t i = 0; i < n; i++) {
1321 float fKerning = pArray->GetFloatAt(i);
1322 if (fKerning != 0)
1323 m_pCurStates->m_TextPos.x -= GetHorizontalTextSize(fKerning);
1324 }
1325 return;
1326 }
1327 std::vector<ByteString> strs(nsegs);
1328 std::vector<float> kernings(nsegs);
1329 size_t iSegment = 0;
1330 float fInitKerning = 0;
1331 for (size_t i = 0; i < n; i++) {
1332 RetainPtr<const CPDF_Object> pObj = pArray->GetDirectObjectAt(i);
1333 if (!pObj)
1334 continue;
1335
1336 if (pObj->IsString()) {
1337 ByteString str = pObj->GetString();
1338 if (str.IsEmpty())
1339 continue;
1340 strs[iSegment] = std::move(str);
1341 kernings[iSegment++] = 0;
1342 } else {
1343 float num = pObj->GetNumber();
1344 if (iSegment == 0)
1345 fInitKerning += num;
1346 else
1347 kernings[iSegment - 1] += num;
1348 }
1349 }
1350 AddTextObject(strs.data(), fInitKerning, kernings, iSegment);
1351 }
1352
Handle_SetTextLeading()1353 void CPDF_StreamContentParser::Handle_SetTextLeading() {
1354 m_pCurStates->m_TextLeading = GetNumber(0);
1355 }
1356
Handle_SetTextMatrix()1357 void CPDF_StreamContentParser::Handle_SetTextMatrix() {
1358 m_pCurStates->m_TextMatrix = GetMatrix();
1359 OnChangeTextMatrix();
1360 m_pCurStates->m_TextPos = CFX_PointF();
1361 m_pCurStates->m_TextLinePos = CFX_PointF();
1362 }
1363
OnChangeTextMatrix()1364 void CPDF_StreamContentParser::OnChangeTextMatrix() {
1365 CFX_Matrix text_matrix(m_pCurStates->m_TextHorzScale, 0.0f, 0.0f, 1.0f, 0.0f,
1366 0.0f);
1367 text_matrix.Concat(m_pCurStates->m_TextMatrix);
1368 text_matrix.Concat(m_pCurStates->m_CTM);
1369 text_matrix.Concat(m_mtContentToUser);
1370 pdfium::span<float> pTextMatrix =
1371 m_pCurStates->m_TextState.GetMutableMatrix();
1372 pTextMatrix[0] = text_matrix.a;
1373 pTextMatrix[1] = text_matrix.c;
1374 pTextMatrix[2] = text_matrix.b;
1375 pTextMatrix[3] = text_matrix.d;
1376 }
1377
Handle_SetTextRenderMode()1378 void CPDF_StreamContentParser::Handle_SetTextRenderMode() {
1379 TextRenderingMode mode;
1380 if (SetTextRenderingModeFromInt(GetInteger(0), &mode))
1381 m_pCurStates->m_TextState.SetTextMode(mode);
1382 }
1383
Handle_SetTextRise()1384 void CPDF_StreamContentParser::Handle_SetTextRise() {
1385 m_pCurStates->m_TextRise = GetNumber(0);
1386 }
1387
Handle_SetWordSpace()1388 void CPDF_StreamContentParser::Handle_SetWordSpace() {
1389 m_pCurStates->m_TextState.SetWordSpace(GetNumber(0));
1390 }
1391
Handle_SetHorzScale()1392 void CPDF_StreamContentParser::Handle_SetHorzScale() {
1393 if (m_ParamCount != 1) {
1394 return;
1395 }
1396 m_pCurStates->m_TextHorzScale = GetNumber(0) / 100;
1397 OnChangeTextMatrix();
1398 }
1399
Handle_MoveToNextLine()1400 void CPDF_StreamContentParser::Handle_MoveToNextLine() {
1401 m_pCurStates->m_TextLinePos.y -= m_pCurStates->m_TextLeading;
1402 m_pCurStates->m_TextPos = m_pCurStates->m_TextLinePos;
1403 }
1404
Handle_CurveTo_23()1405 void CPDF_StreamContentParser::Handle_CurveTo_23() {
1406 AddPathPoint(m_PathCurrent, CFX_Path::Point::Type::kBezier);
1407 AddPathPoint(GetPoint(2), CFX_Path::Point::Type::kBezier);
1408 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
1409 }
1410
Handle_SetLineWidth()1411 void CPDF_StreamContentParser::Handle_SetLineWidth() {
1412 m_pCurStates->m_GraphState.SetLineWidth(GetNumber(0));
1413 }
1414
Handle_Clip()1415 void CPDF_StreamContentParser::Handle_Clip() {
1416 m_PathClipType = CFX_FillRenderOptions::FillType::kWinding;
1417 }
1418
Handle_EOClip()1419 void CPDF_StreamContentParser::Handle_EOClip() {
1420 m_PathClipType = CFX_FillRenderOptions::FillType::kEvenOdd;
1421 }
1422
Handle_CurveTo_13()1423 void CPDF_StreamContentParser::Handle_CurveTo_13() {
1424 AddPathPoint(GetPoint(2), CFX_Path::Point::Type::kBezier);
1425 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
1426 AddPathPoint(GetPoint(0), CFX_Path::Point::Type::kBezier);
1427 }
1428
Handle_NextLineShowText()1429 void CPDF_StreamContentParser::Handle_NextLineShowText() {
1430 Handle_MoveToNextLine();
1431 Handle_ShowText();
1432 }
1433
Handle_NextLineShowText_Space()1434 void CPDF_StreamContentParser::Handle_NextLineShowText_Space() {
1435 m_pCurStates->m_TextState.SetWordSpace(GetNumber(2));
1436 m_pCurStates->m_TextState.SetCharSpace(GetNumber(1));
1437 Handle_NextLineShowText();
1438 }
1439
Handle_Invalid()1440 void CPDF_StreamContentParser::Handle_Invalid() {}
1441
AddPathPoint(const CFX_PointF & point,CFX_Path::Point::Type type)1442 void CPDF_StreamContentParser::AddPathPoint(const CFX_PointF& point,
1443 CFX_Path::Point::Type type) {
1444 // If the path point is the same move as the previous one and neither of them
1445 // closes the path, then just skip it.
1446 if (type == CFX_Path::Point::Type::kMove && !m_PathPoints.empty() &&
1447 !m_PathPoints.back().m_CloseFigure &&
1448 m_PathPoints.back().m_Type == type && m_PathCurrent == point) {
1449 return;
1450 }
1451
1452 m_PathCurrent = point;
1453 if (type == CFX_Path::Point::Type::kMove) {
1454 m_PathStart = point;
1455 if (!m_PathPoints.empty() &&
1456 m_PathPoints.back().IsTypeAndOpen(CFX_Path::Point::Type::kMove)) {
1457 m_PathPoints.back().m_Point = point;
1458 return;
1459 }
1460 } else if (m_PathPoints.empty()) {
1461 return;
1462 }
1463 m_PathPoints.emplace_back(point, type, /*close=*/false);
1464 }
1465
AddPathPointAndClose(const CFX_PointF & point,CFX_Path::Point::Type type)1466 void CPDF_StreamContentParser::AddPathPointAndClose(
1467 const CFX_PointF& point,
1468 CFX_Path::Point::Type type) {
1469 m_PathCurrent = point;
1470 if (m_PathPoints.empty())
1471 return;
1472
1473 m_PathPoints.emplace_back(point, type, /*close=*/true);
1474 }
1475
AddPathObject(CFX_FillRenderOptions::FillType fill_type,RenderType render_type)1476 void CPDF_StreamContentParser::AddPathObject(
1477 CFX_FillRenderOptions::FillType fill_type,
1478 RenderType render_type) {
1479 std::vector<CFX_Path::Point> path_points;
1480 path_points.swap(m_PathPoints);
1481 CFX_FillRenderOptions::FillType path_clip_type = m_PathClipType;
1482 m_PathClipType = CFX_FillRenderOptions::FillType::kNoFill;
1483
1484 if (path_points.empty())
1485 return;
1486
1487 if (path_points.size() == 1) {
1488 if (path_clip_type != CFX_FillRenderOptions::FillType::kNoFill) {
1489 CPDF_Path path;
1490 path.AppendRect(0, 0, 0, 0);
1491 m_pCurStates->m_ClipPath.AppendPathWithAutoMerge(
1492 path, CFX_FillRenderOptions::FillType::kWinding);
1493 return;
1494 }
1495
1496 CFX_Path::Point& point = path_points.front();
1497 if (point.m_Type != CFX_Path::Point::Type::kMove || !point.m_CloseFigure ||
1498 m_pCurStates->m_GraphState.GetLineCap() !=
1499 CFX_GraphStateData::LineCap::kRound) {
1500 return;
1501 }
1502
1503 // For round line cap only: When a path moves to a point and immediately
1504 // gets closed, we can treat it as drawing a path from this point to itself
1505 // and closing the path. This should not apply to butt line cap or
1506 // projecting square line cap since they should not be rendered.
1507 point.m_CloseFigure = false;
1508 path_points.emplace_back(point.m_Point, CFX_Path::Point::Type::kLine,
1509 /*close=*/true);
1510 }
1511
1512 if (path_points.back().IsTypeAndOpen(CFX_Path::Point::Type::kMove))
1513 path_points.pop_back();
1514
1515 CPDF_Path path;
1516 for (const auto& point : path_points) {
1517 if (point.m_CloseFigure)
1518 path.AppendPointAndClose(point.m_Point, point.m_Type);
1519 else
1520 path.AppendPoint(point.m_Point, point.m_Type);
1521 }
1522
1523 CFX_Matrix matrix = m_pCurStates->m_CTM * m_mtContentToUser;
1524 bool bStroke = render_type == RenderType::kStroke;
1525 if (bStroke || fill_type != CFX_FillRenderOptions::FillType::kNoFill) {
1526 auto pPathObj = std::make_unique<CPDF_PathObject>(GetCurrentStreamIndex());
1527 pPathObj->set_stroke(bStroke);
1528 pPathObj->set_filltype(fill_type);
1529 pPathObj->path() = path;
1530 SetGraphicStates(pPathObj.get(), true, false, true);
1531 pPathObj->SetPathMatrix(matrix);
1532 m_pObjectHolder->AppendPageObject(std::move(pPathObj));
1533 }
1534 if (path_clip_type != CFX_FillRenderOptions::FillType::kNoFill) {
1535 if (!matrix.IsIdentity())
1536 path.Transform(matrix);
1537 m_pCurStates->m_ClipPath.AppendPathWithAutoMerge(path, path_clip_type);
1538 }
1539 }
1540
Parse(pdfium::span<const uint8_t> pData,uint32_t start_offset,uint32_t max_cost,const std::vector<uint32_t> & stream_start_offsets)1541 uint32_t CPDF_StreamContentParser::Parse(
1542 pdfium::span<const uint8_t> pData,
1543 uint32_t start_offset,
1544 uint32_t max_cost,
1545 const std::vector<uint32_t>& stream_start_offsets) {
1546 DCHECK(start_offset < pData.size());
1547
1548 // Parsing will be done from within |pDataStart|.
1549 pdfium::span<const uint8_t> pDataStart = pData.subspan(start_offset);
1550 m_StartParseOffset = start_offset;
1551 if (m_RecursionState->parsed_set.size() > kMaxFormLevel ||
1552 pdfium::Contains(m_RecursionState->parsed_set, pDataStart.data())) {
1553 return fxcrt::CollectionSize<uint32_t>(pDataStart);
1554 }
1555
1556 m_StreamStartOffsets = stream_start_offsets;
1557
1558 ScopedSetInsertion<const uint8_t*> scoped_insert(
1559 &m_RecursionState->parsed_set, pDataStart.data());
1560
1561 uint32_t init_obj_count = m_pObjectHolder->GetPageObjectCount();
1562 AutoNuller<std::unique_ptr<CPDF_StreamParser>> auto_clearer(&m_pSyntax);
1563 m_pSyntax = std::make_unique<CPDF_StreamParser>(
1564 pDataStart, m_pDocument->GetByteStringPool());
1565
1566 while (true) {
1567 uint32_t cost = m_pObjectHolder->GetPageObjectCount() - init_obj_count;
1568 if (max_cost && cost >= max_cost) {
1569 break;
1570 }
1571 switch (m_pSyntax->ParseNextElement()) {
1572 case CPDF_StreamParser::ElementType::kEndOfData:
1573 return m_pSyntax->GetPos();
1574 case CPDF_StreamParser::ElementType::kKeyword:
1575 OnOperator(m_pSyntax->GetWord());
1576 ClearAllParams();
1577 break;
1578 case CPDF_StreamParser::ElementType::kNumber:
1579 AddNumberParam(m_pSyntax->GetWord());
1580 break;
1581 case CPDF_StreamParser::ElementType::kName: {
1582 auto word = m_pSyntax->GetWord();
1583 AddNameParam(word.Last(word.GetLength() - 1));
1584 break;
1585 }
1586 default:
1587 AddObjectParam(m_pSyntax->GetObject());
1588 }
1589 }
1590 return m_pSyntax->GetPos();
1591 }
1592
ParsePathObject()1593 void CPDF_StreamContentParser::ParsePathObject() {
1594 float params[6] = {};
1595 int nParams = 0;
1596 int last_pos = m_pSyntax->GetPos();
1597 while (true) {
1598 CPDF_StreamParser::ElementType type = m_pSyntax->ParseNextElement();
1599 bool bProcessed = true;
1600 switch (type) {
1601 case CPDF_StreamParser::ElementType::kEndOfData:
1602 return;
1603 case CPDF_StreamParser::ElementType::kKeyword: {
1604 ByteStringView strc = m_pSyntax->GetWord();
1605 int len = strc.GetLength();
1606 if (len == 1) {
1607 switch (strc[0]) {
1608 case kPathOperatorSubpath:
1609 AddPathPoint({params[0], params[1]},
1610 CFX_Path::Point::Type::kMove);
1611 nParams = 0;
1612 break;
1613 case kPathOperatorLine:
1614 AddPathPoint({params[0], params[1]},
1615 CFX_Path::Point::Type::kLine);
1616 nParams = 0;
1617 break;
1618 case kPathOperatorCubicBezier1:
1619 AddPathPoint({params[0], params[1]},
1620 CFX_Path::Point::Type::kBezier);
1621 AddPathPoint({params[2], params[3]},
1622 CFX_Path::Point::Type::kBezier);
1623 AddPathPoint({params[4], params[5]},
1624 CFX_Path::Point::Type::kBezier);
1625 nParams = 0;
1626 break;
1627 case kPathOperatorCubicBezier2:
1628 AddPathPoint(m_PathCurrent, CFX_Path::Point::Type::kBezier);
1629 AddPathPoint({params[0], params[1]},
1630 CFX_Path::Point::Type::kBezier);
1631 AddPathPoint({params[2], params[3]},
1632 CFX_Path::Point::Type::kBezier);
1633 nParams = 0;
1634 break;
1635 case kPathOperatorCubicBezier3:
1636 AddPathPoint({params[0], params[1]},
1637 CFX_Path::Point::Type::kBezier);
1638 AddPathPoint({params[2], params[3]},
1639 CFX_Path::Point::Type::kBezier);
1640 AddPathPoint({params[2], params[3]},
1641 CFX_Path::Point::Type::kBezier);
1642 nParams = 0;
1643 break;
1644 case kPathOperatorClosePath:
1645 Handle_ClosePath();
1646 nParams = 0;
1647 break;
1648 default:
1649 bProcessed = false;
1650 break;
1651 }
1652 } else if (len == 2) {
1653 if (strc[0] == kPathOperatorRectangle[0] &&
1654 strc[1] == kPathOperatorRectangle[1]) {
1655 AddPathRect(params[0], params[1], params[2], params[3]);
1656 nParams = 0;
1657 } else {
1658 bProcessed = false;
1659 }
1660 } else {
1661 bProcessed = false;
1662 }
1663 if (bProcessed) {
1664 last_pos = m_pSyntax->GetPos();
1665 }
1666 break;
1667 }
1668 case CPDF_StreamParser::ElementType::kNumber: {
1669 if (nParams == 6)
1670 break;
1671
1672 FX_Number number(m_pSyntax->GetWord());
1673 params[nParams++] = number.GetFloat();
1674 break;
1675 }
1676 default:
1677 bProcessed = false;
1678 }
1679 if (!bProcessed) {
1680 m_pSyntax->SetPos(last_pos);
1681 return;
1682 }
1683 }
1684 }
1685
1686 // static
FindKeyAbbreviationForTesting(ByteStringView abbr)1687 ByteStringView CPDF_StreamContentParser::FindKeyAbbreviationForTesting(
1688 ByteStringView abbr) {
1689 return FindFullName(kInlineKeyAbbr, abbr);
1690 }
1691
1692 // static
FindValueAbbreviationForTesting(ByteStringView abbr)1693 ByteStringView CPDF_StreamContentParser::FindValueAbbreviationForTesting(
1694 ByteStringView abbr) {
1695 return FindFullName(kInlineValueAbbr, abbr);
1696 }
1697
1698 CPDF_StreamContentParser::ContentParam::ContentParam() = default;
1699
1700 CPDF_StreamContentParser::ContentParam::~ContentParam() = default;
1701