forked from Tencent/libpag
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPAGXOptimizer.cpp
More file actions
1796 lines (1682 loc) · 64.6 KB
/
Copy pathPAGXOptimizer.cpp
File metadata and controls
1796 lines (1682 loc) · 64.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2026 Tencent. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// unless required by applicable law or agreed to in writing, software distributed under the
// license is distributed on an "as is" basis, without warranties or conditions of any kind,
// either express or implied. see the license for the specific language governing permissions
// and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "pagx/PAGXOptimizer.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include "PAGXOptimizerOptions.h"
#include "pagx/nodes/Composition.h"
#include "pagx/nodes/Ellipse.h"
#include "pagx/nodes/Fill.h"
#include "pagx/nodes/Font.h"
#include "pagx/nodes/GlyphRun.h"
#include "pagx/nodes/Group.h"
#include "pagx/nodes/Image.h"
#include "pagx/nodes/ImagePattern.h"
#include "pagx/nodes/Layer.h"
#include "pagx/nodes/LayoutNode.h"
#include "pagx/nodes/Path.h"
#include "pagx/nodes/PathData.h"
#include "pagx/nodes/Rectangle.h"
#include "pagx/nodes/SolidColor.h"
#include "pagx/nodes/Stroke.h"
#include "pagx/nodes/Text.h"
#include "pagx/types/PathVerb.h"
#include "pagx/utils/VerifyUtils.h"
namespace pagx {
// ============================================================================
// Shared layer/element classification predicates — single source-of-truth in
// pagx/utils/VerifyUtils.h, used by verify, resolve, and optimizer. Keeping
// them in one place avoids silent drift when new Layer attributes are introduced.
// ============================================================================
namespace {
// ----------------------------------------------------------------------------
// Forward declarations for every helper defined below. Keeping them together
// here lets any function call any other regardless of definition order, so the
// bodies below can be arranged by topic instead of by topological sort.
// ----------------------------------------------------------------------------
struct PainterSignature;
bool HasUnresolvedImport(const Layer* layer);
bool LayerNeedsKeeping(const Layer* layer, const std::unordered_set<const Layer*>& maskRefs);
bool LayoutNodeHasConstraints(const LayoutNode* node);
bool ElementHasConstraints(Element* element);
bool IsDefaultTransformGroup(const Group* group);
bool IsLayerStructurallyEmpty(const Layer* layer);
void CollectMaskRefsFromLayer(const Layer* layer, std::unordered_set<const Layer*>& refs);
void CollectMaskRefs(const std::vector<Layer*>& layers, std::unordered_set<const Layer*>& refs);
Group* WrapShellLayerAsGroup(PAGXDocument* doc, Layer* layer);
bool TryReadAxisAlignedRect(const PathData* data, float& cx, float& cy, float& w, float& h);
bool TryReadEllipse(const PathData* data, float& cx, float& cy, float& w, float& h);
Element* TryCanonicalizePath(PAGXDocument* doc, Path* path);
bool TryConvertRectMaskToScrollRect(Layer* layer);
bool RectMaskToScrollRectInLayer(Layer* layer);
bool ColorSourcesEqual(const ColorSource* a, const ColorSource* b);
bool FillsEqual(const Fill* a, const Fill* b);
bool StrokesEqual(const Stroke* a, const Stroke* b);
bool PaintersEqual(const Element* a, const Element* b);
PainterSignature ComputePainterSignature(const Group* group);
bool PainterSignaturesEqual(const PainterSignature& a, const PainterSignature& b);
bool PruneEmptyInElements(std::vector<Element*>& elements);
bool PruneEmptyInGroup(Group* group);
bool PruneEmptyInLayer(Layer* layer, const std::unordered_set<const Layer*>& maskRefs);
bool PruneEmptyTopLevel(std::vector<Layer*>& layers, bool parentHasLayout,
const std::unordered_set<const Layer*>& maskRefs);
bool CanonicalizePathsInElements(PAGXDocument* doc, std::vector<Element*>& elements);
bool CanonicalizePathsInLayer(PAGXDocument* doc, Layer* layer);
bool DowngradeShellChildrenInLayer(PAGXDocument* doc, Layer* layer,
const std::unordered_set<const Layer*>& maskRefs);
bool DowngradeShellChildren(PAGXDocument* doc, std::vector<Layer*>& layers,
const std::unordered_set<const Layer*>& maskRefs);
bool IsMergeableShellLayer(const Layer* layer, const std::unordered_set<const Layer*>& maskRefs);
bool ChildFillsParent(const Layer* parent, const Layer* child);
bool ChildHasNoPaintAffectingEffect(const Layer* child);
bool CanAbsorbFillingChild(const Layer* parent, const Layer* child,
const std::unordered_set<const Layer*>& maskRefs);
void AbsorbFillingChild(Layer* parent, Layer* child);
bool CanDropShellParent(const Layer* parent, const Layer* child,
const std::unordered_set<const Layer*>& maskRefs);
bool CollapseSingleChildLayersInList(std::vector<Layer*>& layers,
const std::unordered_set<const Layer*>& maskRefs);
template <class T>
void BeginMutation(std::vector<T>& source, std::vector<T>& result, size_t upTo, bool& changed);
bool MergeAdjacentShellLayersInList(PAGXDocument* doc, std::vector<Layer*>& layers,
bool parentHasLayout,
const std::unordered_set<const Layer*>& maskRefs);
bool MergeAdjacentShellLayersRecursive(PAGXDocument* doc, std::vector<Layer*>& layers,
bool parentHasLayout,
const std::unordered_set<const Layer*>& maskRefs);
bool MergeAdjacentShellLayers(PAGXDocument* doc, std::vector<Layer*>& topLevel,
const std::unordered_set<const Layer*>& maskRefs);
bool UnwrapRedundantFirstGroupInElements(std::vector<Element*>& elements);
bool UnwrapRedundantFirstGroupRecursive(std::vector<Element*>& elements);
bool UnwrapRedundantFirstGroupInLayer(Layer* layer);
bool MergeAdjacentGroupsInElements(std::vector<Element*>& elements);
bool MergeAdjacentGroupsRecursive(std::vector<Element*>& elements);
bool MergeAdjacentGroupsInLayer(Layer* layer);
void RecomputeMaskRefs(PAGXDocument* doc, std::unordered_set<const Layer*>& refs);
std::string PathDataSignature(const PathData* data);
void RewritePathDataInElements(std::vector<Element*>& elements,
const std::unordered_map<PathData*, PathData*>& redirect);
void RewritePathDataInLayer(Layer* layer, const std::unordered_map<PathData*, PathData*>& redirect);
bool DedupPathDataResources(PAGXDocument* doc);
void CollectRefsFromElement(const Element* element, std::unordered_set<std::string>& refs);
void CollectRefsFromLayer(const Layer* layer, std::unordered_set<std::string>& refs);
void CollectReferencedIds(const PAGXDocument* doc, std::unordered_set<std::string>& refs);
bool IsResourceNode(NodeType type);
bool PruneUnreferencedResources(PAGXDocument* doc);
int OptimizeLayerList(PAGXDocument* doc, std::vector<Layer*>& layers,
std::unordered_set<const Layer*>& maskRefs,
const PAGXOptimizerOptions& options, bool* converged);
// ----------------------------------------------------------------------------
// Helper definitions start here.
// ----------------------------------------------------------------------------
bool HasUnresolvedImport(const Layer* layer) {
return !layer->importDirective.source.empty() || !layer->importDirective.content.empty();
}
bool LayerNeedsKeeping(const Layer* layer, const std::unordered_set<const Layer*>& maskRefs) {
if (maskRefs.find(layer) != maskRefs.end()) {
return true;
}
return false;
}
bool LayoutNodeHasConstraints(const LayoutNode* node) {
if (node == nullptr) {
return false;
}
return node->hasConstraints();
}
bool ElementHasConstraints(Element* element) {
return LayoutNodeHasConstraints(LayoutNode::AsLayoutNode(element));
}
// Group is a no-op container: identity transform, default alpha, no layout,
// no constraint frame, no padding.
bool IsDefaultTransformGroup(const Group* group) {
if (group->alpha != 1.0f) {
return false;
}
if (group->position.x != 0 || group->position.y != 0) {
return false;
}
if (group->anchor.x != 0 || group->anchor.y != 0) {
return false;
}
if (group->rotation != 0) {
return false;
}
if (group->scale.x != 1 || group->scale.y != 1) {
return false;
}
if (group->skew != 0) {
return false;
}
if (group->skewAxis != 0) {
return false;
}
if (!std::isnan(group->width) || !std::isnan(group->height)) {
return false;
}
if (!std::isnan(group->percentWidth) || !std::isnan(group->percentHeight)) {
return false;
}
if (!group->padding.isZero()) {
return false;
}
if (!std::isnan(group->left) || !std::isnan(group->right) || !std::isnan(group->top) ||
!std::isnan(group->bottom) || !std::isnan(group->centerX) || !std::isnan(group->centerY)) {
return false;
}
return true;
}
void CollectMaskRefsFromLayer(const Layer* layer, std::unordered_set<const Layer*>& refs) {
if (layer == nullptr) {
return;
}
if (layer->mask != nullptr) {
refs.insert(layer->mask);
CollectMaskRefsFromLayer(layer->mask, refs);
}
CollectMaskRefs(layer->children, refs);
}
void CollectMaskRefs(const std::vector<Layer*>& layers, std::unordered_set<const Layer*>& refs) {
for (auto* layer : layers) {
CollectMaskRefsFromLayer(layer, refs);
}
}
// ----------------------------------------------------------------------------
// Layer -> Group conversion
// ----------------------------------------------------------------------------
// Wraps a downgradable shell Layer's contents in a new Group, transferring customData. Caller
// must have verified the layer is downgradable and is responsible for removing it from the
// owning list. Returns nullptr if the layer is not safely downgradable (callers must check
// IsLayerShell + children.empty() first).
Group* WrapShellLayerAsGroup(PAGXDocument* doc, Layer* layer) {
auto* group = doc->makeNode<Group>();
group->elements = std::move(layer->contents);
layer->contents.clear();
// Transfer customData and sourceLine so verify diagnostics still point to the right place.
group->customData = std::move(layer->customData);
layer->customData.clear();
if (group->sourceLine == -1) {
group->sourceLine = layer->sourceLine;
}
return group;
}
// ----------------------------------------------------------------------------
// Path canonicalization (mirrors verify's DetectPathToPrimitives).
// ----------------------------------------------------------------------------
bool TryReadAxisAlignedRect(const PathData* data, float& cx, float& cy, float& w, float& h) {
auto& verbs = data->verbs();
// Accept two well-formed axis-aligned rectangle encodings:
// 5 verbs: Move + 3 Line + Close (SVG `<rect>` / importer canonical form — the Close
// implicitly draws the fourth edge back to the start).
// 6 verbs: Move + 4 Line + Close (SVG `<path d="M... L... L... L... L... Z">` where the
// author emitted the final edge as an explicit Line
// before closing — commonly produced by path editors).
// Any other verb count cannot describe a pure axis-aligned rectangle.
if (verbs.size() != 5 && verbs.size() != 6) {
return false;
}
if (verbs[0] != PathVerb::Move) {
return false;
}
for (size_t i = 1; i + 1 < verbs.size(); i++) {
if (verbs[i] != PathVerb::Line) {
return false;
}
}
if (verbs.back() != PathVerb::Close) {
return false;
}
auto& pts = data->points();
size_t pointCount = pts.size();
if (pointCount < 4) {
return false;
}
for (size_t i = 0; i < pointCount; i++) {
auto& p1 = pts[i];
auto& p2 = pts[(i + 1) % pointCount];
float dx = std::abs(p2.x - p1.x);
float dy = std::abs(p2.y - p1.y);
if (dx > 0.01f && dy > 0.01f) {
return false;
}
}
float minX = pts[0].x, maxX = pts[0].x;
float minY = pts[0].y, maxY = pts[0].y;
for (size_t i = 1; i < pointCount; i++) {
minX = std::min(minX, pts[i].x);
maxX = std::max(maxX, pts[i].x);
minY = std::min(minY, pts[i].y);
maxY = std::max(maxY, pts[i].y);
}
w = maxX - minX;
h = maxY - minY;
if (w < 0.01f || h < 0.01f) {
return false;
}
cx = (minX + maxX) * 0.5f;
cy = (minY + maxY) * 0.5f;
return true;
}
bool TryReadEllipse(const PathData* data, float& cx, float& cy, float& w, float& h) {
auto& verbs = data->verbs();
if (verbs.size() != 6) {
return false;
}
if (verbs[0] != PathVerb::Move) {
return false;
}
for (int i = 1; i <= 4; i++) {
if (verbs[i] != PathVerb::Cubic) {
return false;
}
}
if (verbs[5] != PathVerb::Close) {
return false;
}
auto& pts = data->points();
if (pts.size() < 13) {
return false;
}
Point onCurve[4];
onCurve[0] = pts[0];
onCurve[1] = pts[3];
onCurve[2] = pts[6];
onCurve[3] = pts[9];
float minX = onCurve[0].x, maxX = onCurve[0].x;
float minY = onCurve[0].y, maxY = onCurve[0].y;
for (int i = 1; i < 4; i++) {
minX = std::min(minX, onCurve[i].x);
maxX = std::max(maxX, onCurve[i].x);
minY = std::min(minY, onCurve[i].y);
maxY = std::max(maxY, onCurve[i].y);
}
cx = (minX + maxX) * 0.5f;
cy = (minY + maxY) * 0.5f;
float rx = (maxX - minX) * 0.5f;
float ry = (maxY - minY) * 0.5f;
if (rx < 0.01f || ry < 0.01f) {
return false;
}
bool foundTop = false, foundBottom = false, foundLeft = false, foundRight = false;
static constexpr float TOLERANCE = 1.0f;
for (int i = 0; i < 4; i++) {
float dx = std::abs(onCurve[i].x - cx);
float dy = std::abs(onCurve[i].y - cy);
if (dx < TOLERANCE && std::abs(dy - ry) < TOLERANCE) {
if (onCurve[i].y < cy) {
foundTop = true;
} else {
foundBottom = true;
}
} else if (dy < TOLERANCE && std::abs(dx - rx) < TOLERANCE) {
if (onCurve[i].x < cx) {
foundLeft = true;
} else {
foundRight = true;
}
}
}
if (!(foundTop && foundBottom && foundLeft && foundRight)) {
return false;
}
// Standard cubic Bezier approximation constant for quarter-circle arcs: 4*(sqrt(2)-1)/3.
static constexpr float KAPPA = 0.5522847f;
// Maximum absolute pixel deviation allowed between an actual cubic control point and the ideal
// KAPPA-derived control point when recognizing an ellipse from a 4-cubic path.
static constexpr float CP_TOLERANCE = 2.0f;
float expectedCpOffsetX = rx * KAPPA;
float expectedCpOffsetY = ry * KAPPA;
for (int seg = 0; seg < 4; seg++) {
Point cp1 = pts[1 + seg * 3];
Point cp2 = pts[2 + seg * 3];
Point segStart = (seg == 0) ? pts[0] : pts[seg * 3];
Point segEnd = pts[3 + seg * 3];
float cp1DistX = std::abs(cp1.x - segStart.x);
float cp1DistY = std::abs(cp1.y - segStart.y);
float cp2DistX = std::abs(cp2.x - segEnd.x);
float cp2DistY = std::abs(cp2.y - segEnd.y);
bool cp1Valid =
(cp1DistX < CP_TOLERANCE && std::abs(cp1DistY - expectedCpOffsetY) < CP_TOLERANCE) ||
(cp1DistY < CP_TOLERANCE && std::abs(cp1DistX - expectedCpOffsetX) < CP_TOLERANCE);
bool cp2Valid =
(cp2DistX < CP_TOLERANCE && std::abs(cp2DistY - expectedCpOffsetY) < CP_TOLERANCE) ||
(cp2DistY < CP_TOLERANCE && std::abs(cp2DistX - expectedCpOffsetX) < CP_TOLERANCE);
if (!cp1Valid || !cp2Valid) {
return false;
}
}
w = rx * 2.0f;
h = ry * 2.0f;
return true;
}
// Replace `path` in-place with a Rectangle/Ellipse if eligible. Returns the new element to
// substitute (which may be the same path if no rewrite happened).
Element* TryCanonicalizePath(PAGXDocument* doc, Path* path) {
if (path->data == nullptr || path->data->isEmpty()) {
return path;
}
if (path->reversed) {
return path;
}
if (ElementHasConstraints(path)) {
return path;
}
if (!path->customData.empty()) {
return path;
}
float cx = 0, cy = 0, w = 0, h = 0;
if (TryReadAxisAlignedRect(path->data, cx, cy, w, h)) {
auto* rect = doc->makeNode<Rectangle>();
rect->position = {path->position.x + cx, path->position.y + cy};
rect->size = {w, h};
rect->sourceLine = path->sourceLine;
return rect;
}
if (TryReadEllipse(path->data, cx, cy, w, h)) {
auto* ellipse = doc->makeNode<Ellipse>();
ellipse->position = {path->position.x + cx, path->position.y + cy};
ellipse->size = {w, h};
ellipse->sourceLine = path->sourceLine;
return ellipse;
}
return path;
}
// ----------------------------------------------------------------------------
// Rectangular alpha mask -> scrollRect rewrite.
//
// An alpha mask whose only contents are a single axis-aligned Rectangle painted with an opaque
// Fill is exactly equivalent to clipping the parent layer with that same rectangle. We express
// the result via scrollRect (which lives in the layer's local coordinate space) rather than
// clipToBounds, because clipToBounds requires resolved layer bounds and would shift coordinates
// when the layer doesn't already declare a frame.
// ----------------------------------------------------------------------------
bool TryConvertRectMaskToScrollRect(Layer* layer) {
if (layer->mask == nullptr) {
return false;
}
if (layer->maskType != MaskType::Alpha) {
return false;
}
if (layer->hasScrollRect) {
return false;
}
auto* m = layer->mask;
if (m->x != 0 || m->y != 0) {
return false;
}
if (!m->matrix.isIdentity()) {
return false;
}
if (!m->matrix3D.isIdentity()) {
return false;
}
if (m->alpha != 1.0f) {
return false;
}
if (m->blendMode != BlendMode::Normal) {
return false;
}
if (!m->styles.empty() || !m->filters.empty()) {
return false;
}
// `id` / `name` on the mask layer come from SVG <clipPath>'s identifier and don't carry
// user-meaningful state — the mask layer itself stays in doc->layers (hidden) after we
// detach the mask reference, so any other consumer can still resolve it. Only customData
// truly blocks the rewrite.
if (!m->customData.empty()) {
return false;
}
if (m->contents.size() != 2) {
return false;
}
if (m->contents[0]->nodeType() != NodeType::Rectangle) {
return false;
}
if (m->contents[1]->nodeType() != NodeType::Fill) {
return false;
}
auto* rect = static_cast<Rectangle*>(m->contents[0]);
if (rect->roundness != 0) {
return false;
}
if (rect->reversed) {
return false;
}
if (LayoutNodeHasConstraints(rect)) {
return false;
}
if (!rect->customData.empty()) {
return false;
}
auto* fill = static_cast<Fill*>(m->contents[1]);
if (fill->alpha < 0.999f) {
return false;
}
if (fill->blendMode != BlendMode::Normal) {
return false;
}
if (fill->color != nullptr) {
if (fill->color->nodeType() != NodeType::SolidColor) {
return false;
}
auto* sc = static_cast<const SolidColor*>(fill->color);
if (sc->color.alpha < 0.999f) {
return false;
}
}
// tgfx's scrollRect uses (x,y) as a scroll offset (the rect's top-left maps to the layer's
// local (0,0)). To preserve the original positioning we have to translate the layer by the
// same (left, top) — which we can only do safely when the user layer has no rotation/scale
// (any 2x2 distortion would warp that compensation vector), no 3D matrix, and no
// constraint-based positioning (where x/y are inputs to the layout solver rather than the
// final translation). A pure-translation matrix is fine: it commutes with the layer-local
// pre-translation the scrollRect introduces, so adding (left, top) to layer.x/y produces
// the same parent-space final transform whether the matrix translates first or not. This
// matters after a PAGX -> SVG -> PAGX round trip, which re-imports the translation we
// previously baked into x/y as a 2D matrix attribute.
if (layer->matrix.a != 1.0f || layer->matrix.b != 0.0f || layer->matrix.c != 0.0f ||
layer->matrix.d != 1.0f) {
return false;
}
if (!layer->matrix3D.isIdentity()) {
return false;
}
if (LayoutNodeHasConstraints(layer)) {
return false;
}
// If the layer already declares an explicit frame size, leave it alone — overwriting an
// author-supplied width/height could change layout semantics for downstream consumers.
if (!std::isnan(layer->width) || !std::isnan(layer->height)) {
return false;
}
float left = rect->position.x - rect->size.width * 0.5f;
float top = rect->position.y - rect->size.height * 0.5f;
layer->scrollRect = {left, top, rect->size.width, rect->size.height};
layer->hasScrollRect = true;
layer->x += left;
layer->y += top;
// The displayed area collapses to exactly the scrollRect's size after this rewrite. Pin the
// layer's frame to those dimensions so layoutBounds() reflects the visible region instead of
// the (much larger) un-clipped child extent — otherwise verify's child-exceeds-parent check
// (which only suppresses on the parent's clip, not the child's) would fire false positives.
layer->width = rect->size.width;
layer->height = rect->size.height;
layer->mask = nullptr;
return true;
}
bool RectMaskToScrollRectInLayer(Layer* layer) {
bool changed = TryConvertRectMaskToScrollRect(layer);
for (auto* child : layer->children) {
changed |= RectMaskToScrollRectInLayer(child);
}
return changed;
}
// ----------------------------------------------------------------------------
// Painter signature (used to decide whether two Groups can merge geometry).
//
// The *Equal helpers below intentionally encode the *optimizer's* notion of "safe to treat as the
// same painter when merging adjacent groups": shared resources compare by pointer identity (so two
// references to the same `<gradient id="g1"/>` collapse), inline SolidColor literals compare by
// value, and every other inline color source (gradient, ImagePattern) is treated as opaque unless
// the same pointer is reused. This is more conservative than a generic structural equality, and it
// is not reused anywhere else in the codebase — promoting these to a shared utility would push the
// conservative semantics onto unrelated call sites, so they stay file-local on purpose.
// ----------------------------------------------------------------------------
// A painter's color source can be either a shared resource (compare by pointer identity, since
// resources have meaningful IDs) or an inline literal. Two inline literals are considered equal
// only when both are SolidColor with identical Color values. Anything else (gradients, image
// patterns) is treated as opaque: only equal when the SAME pointer is used.
bool ColorSourcesEqual(const ColorSource* a, const ColorSource* b) {
if (a == b) {
return true;
}
if (a == nullptr || b == nullptr) {
return false;
}
if (a->nodeType() != b->nodeType()) {
return false;
}
// For shared resource references (i.e. nodes registered in PAGXDocument::nodes by id) the
// SVG importer reuses the same instance, so a == b will already be true above. For inline
// SolidColor literals we compare values.
if (a->nodeType() == NodeType::SolidColor) {
auto* sa = static_cast<const SolidColor*>(a);
auto* sb = static_cast<const SolidColor*>(b);
return sa->color == sb->color;
}
return false;
}
bool FillsEqual(const Fill* a, const Fill* b) {
if (a->alpha != b->alpha) {
return false;
}
if (a->blendMode != b->blendMode) {
return false;
}
if (a->fillRule != b->fillRule) {
return false;
}
if (a->placement != b->placement) {
return false;
}
return ColorSourcesEqual(a->color, b->color);
}
bool StrokesEqual(const Stroke* a, const Stroke* b) {
if (a->width != b->width) {
return false;
}
if (a->alpha != b->alpha) {
return false;
}
if (a->blendMode != b->blendMode) {
return false;
}
if (a->cap != b->cap) {
return false;
}
if (a->join != b->join) {
return false;
}
if (a->miterLimit != b->miterLimit) {
return false;
}
if (a->dashOffset != b->dashOffset) {
return false;
}
if (a->dashAdaptive != b->dashAdaptive) {
return false;
}
if (a->align != b->align) {
return false;
}
if (a->placement != b->placement) {
return false;
}
if (a->dashes != b->dashes) {
return false;
}
return ColorSourcesEqual(a->color, b->color);
}
bool PaintersEqual(const Element* a, const Element* b) {
if (a == b) {
return true;
}
if (a == nullptr || b == nullptr) {
return false;
}
if (a->nodeType() != b->nodeType()) {
return false;
}
if (a->nodeType() == NodeType::Fill) {
return FillsEqual(static_cast<const Fill*>(a), static_cast<const Fill*>(b));
}
if (a->nodeType() == NodeType::Stroke) {
return StrokesEqual(static_cast<const Stroke*>(a), static_cast<const Stroke*>(b));
}
return false;
}
struct PainterSignature {
// Trailing-painter elements; an empty signature means the Group has no painters
// (so it has no shared painter scope to compare).
std::vector<Element*> painters;
bool valid = false;
};
PainterSignature ComputePainterSignature(const Group* group) {
PainterSignature sig;
bool foundPainter = false;
for (auto* el : group->elements) {
if (IsPainter(el->nodeType())) {
foundPainter = true;
sig.painters.push_back(el);
} else if (foundPainter) {
// A non-painter after a painter means painters don't form a clean trailing block.
sig.valid = false;
sig.painters.clear();
return sig;
}
}
if (!foundPainter) {
return sig;
}
sig.valid = true;
return sig;
}
bool PainterSignaturesEqual(const PainterSignature& a, const PainterSignature& b) {
if (!a.valid || !b.valid) {
return false;
}
if (a.painters.size() != b.painters.size()) {
return false;
}
for (size_t i = 0; i < a.painters.size(); i++) {
if (!PaintersEqual(a.painters[i], b.painters[i])) {
return false;
}
}
return true;
}
// ============================================================================
// Rule implementations. Each rule mutates `doc` in place and returns true if
// any change was made.
// ============================================================================
// Recursively prune empty Layers (no contents/children/composition, no constraints, not
// referenced as a mask, not a layout participant) and empty Groups.
bool PruneEmptyInElements(std::vector<Element*>& elements) {
bool changed = false;
size_t writeIdx = 0;
for (size_t i = 0; i < elements.size(); i++) {
auto* el = elements[i];
if (el->nodeType() == NodeType::Group) {
auto* group = static_cast<Group*>(el);
changed |= PruneEmptyInGroup(group);
bool empty = group->elements.empty() && std::isnan(group->width) &&
std::isnan(group->height) && !LayoutNodeHasConstraints(group) &&
group->padding.isZero() && group->customData.empty();
if (empty) {
changed = true;
continue;
}
}
elements[writeIdx++] = el;
}
if (writeIdx != elements.size()) {
elements.resize(writeIdx);
changed = true;
}
return changed;
}
bool PruneEmptyInGroup(Group* group) {
return PruneEmptyInElements(group->elements);
}
// A Layer is "structurally empty" when it has no contents/children/composition AND no
// size/percent-size/size-dependent constraint that would still let it occupy space (e.g.
// as a backdrop-blur surface). On such a layer every other attribute — filters, styles,
// mask, alpha, blendMode, hasScrollRect, clipToBounds, id, name, etc. — applies to a
// region of zero area and produces no rendering, so dropping the layer is observably
// equivalent. This matches verify's DetectEmptyLayer rule exactly; we intentionally do
// NOT consult HasLayerOnlyFeatures here because that helper conservatively keeps layers
// that carry purely-cosmetic attributes (filter on nothing, mask on nothing, ...) and
// would let the optimizer disagree with verify after a PAGX <-> SVG round trip drops a
// shape leaving behind a shell layer.
bool IsLayerStructurallyEmpty(const Layer* layer) {
if (!layer->contents.empty() || !layer->children.empty() || layer->composition != nullptr) {
return false;
}
if (!std::isnan(layer->width) || !std::isnan(layer->height)) {
return false;
}
if (!std::isnan(layer->percentWidth) || !std::isnan(layer->percentHeight)) {
return false;
}
// Size-dependent constraints (right/bottom/centerX/centerY) still resolve to a finite
// box at layout time, so the layer can render via filters / background blur. left/top
// alone only translate, so an otherwise-empty layer with just left/top is still empty.
if (!std::isnan(layer->right) || !std::isnan(layer->bottom) || !std::isnan(layer->centerX) ||
!std::isnan(layer->centerY)) {
return false;
}
if (!layer->customData.empty()) {
return false;
}
if (HasUnresolvedImport(layer)) {
return false;
}
return true;
}
bool PruneEmptyInLayer(Layer* layer, const std::unordered_set<const Layer*>& maskRefs) {
bool changed = false;
changed |= PruneEmptyInElements(layer->contents);
bool layerHasLayout = layer->layout != LayoutMode::None;
// Recurse into children first so empty subtrees collapse bottom-up.
size_t writeIdx = 0;
for (size_t i = 0; i < layer->children.size(); i++) {
auto* child = layer->children[i];
changed |= PruneEmptyInLayer(child, maskRefs);
bool inParentLayout = layerHasLayout && child->includeInLayout;
if (IsLayerStructurallyEmpty(child) && !inParentLayout && !LayerNeedsKeeping(child, maskRefs)) {
changed = true;
continue;
}
layer->children[writeIdx++] = child;
}
if (writeIdx != layer->children.size()) {
layer->children.resize(writeIdx);
changed = true;
}
return changed;
}
bool PruneEmptyTopLevel(std::vector<Layer*>& layers, bool parentHasLayout,
const std::unordered_set<const Layer*>& maskRefs) {
bool changed = false;
size_t writeIdx = 0;
for (size_t i = 0; i < layers.size(); i++) {
auto* layer = layers[i];
changed |= PruneEmptyInLayer(layer, maskRefs);
bool inParentLayout = parentHasLayout && layer->includeInLayout;
if (IsLayerStructurallyEmpty(layer) && !inParentLayout && !LayerNeedsKeeping(layer, maskRefs)) {
changed = true;
continue;
}
layers[writeIdx++] = layer;
}
if (writeIdx != layers.size()) {
layers.resize(writeIdx);
changed = true;
}
return changed;
}
// ----------------------------------------------------------------------------
// Canonicalize Path nodes inside Layers/Groups.
// ----------------------------------------------------------------------------
bool CanonicalizePathsInElements(PAGXDocument* doc, std::vector<Element*>& elements) {
bool changed = false;
for (auto& el : elements) {
if (el->nodeType() == NodeType::Path) {
auto* path = static_cast<Path*>(el);
auto* replacement = TryCanonicalizePath(doc, path);
if (replacement != el) {
el = replacement;
changed = true;
}
} else if (el->nodeType() == NodeType::Group) {
auto* group = static_cast<Group*>(el);
changed |= CanonicalizePathsInElements(doc, group->elements);
}
}
return changed;
}
bool CanonicalizePathsInLayer(PAGXDocument* doc, Layer* layer) {
bool changed = false;
changed |= CanonicalizePathsInElements(doc, layer->contents);
// Mask subtrees carry their own Path children (e.g. SVG <clipPath> typically imports each
// <rect> as Path data). Rewriting those Paths to Rectangle primitives is the prerequisite
// for TryConvertRectMaskToScrollRect to recognize the mask as an axis-aligned alpha rect.
if (layer->mask != nullptr) {
changed |= CanonicalizePathsInLayer(doc, layer->mask);
}
for (auto* child : layer->children) {
changed |= CanonicalizePathsInLayer(doc, child);
}
return changed;
}
// ----------------------------------------------------------------------------
// Downgrade-shell-children: when a parent Layer has no contents, no layout,
// and ALL children are shell+downgradable Layers without further children,
// rewrite each child as a Group inside the parent's contents.
// ----------------------------------------------------------------------------
bool DowngradeShellChildrenInLayer(PAGXDocument* doc, Layer* layer,
const std::unordered_set<const Layer*>& maskRefs) {
bool changed = false;
for (auto* child : layer->children) {
changed |= DowngradeShellChildrenInLayer(doc, child, maskRefs);
}
if (layer->layout != LayoutMode::None) {
return changed;
}
if (layer->children.empty()) {
return changed;
}
if (!layer->contents.empty()) {
return changed; // mixed: paint order would change
}
for (auto* child : layer->children) {
if (!child->children.empty()) {
return changed;
}
if (!IsLayerShell(child)) {
return changed;
}
if (LayerNeedsKeeping(child, maskRefs)) {
return changed;
}
if (HasUnresolvedImport(child)) {
return changed;
}
}
// All children are downgradable.
for (auto* child : layer->children) {
if (child->contents.empty() && child->customData.empty()) {
// Empty shell layer with nothing to wrap — drop entirely.
continue;
}
auto* group = WrapShellLayerAsGroup(doc, child);
layer->contents.push_back(group);
}
layer->children.clear();
return true;
}
bool DowngradeShellChildren(PAGXDocument* doc, std::vector<Layer*>& layers,
const std::unordered_set<const Layer*>& maskRefs) {
bool changed = false;
for (auto* layer : layers) {
changed |= DowngradeShellChildrenInLayer(doc, layer, maskRefs);
}
return changed;
}
// ----------------------------------------------------------------------------
// Merge-adjacent-shell-layers: in a sibling list, runs of consecutive shell
// Layers (no children, downgradable) are replaced by a single Layer containing
// one Group per source Layer.
//
// The single Layer wrapper is necessary at the top level (and for a child run
// when there are surrounding non-downgradable siblings) so paint order is
// preserved. When the entire sibling list is downgradable inside a parent
// Layer, DowngradeShellChildren handles it earlier (no wrapper needed).
// ----------------------------------------------------------------------------
bool IsMergeableShellLayer(const Layer* layer, const std::unordered_set<const Layer*>& maskRefs) {
if (!layer->children.empty()) {
return false;
}
return IsLayerShell(layer) && !LayerNeedsKeeping(layer, maskRefs) && !HasUnresolvedImport(layer);
}
// Backfills `result` with the first `upTo` entries of `source` the first time a mutation happens.
// Used by the adjacent-shell/group mergers, whose common case is "no change to the list" — we
// want to avoid allocating a result vector until a mutation is actually detected.
template <class T>
void BeginMutation(std::vector<T>& source, std::vector<T>& result, size_t upTo, bool& changed) {
if (changed) {
return;
}
changed = true;
result.reserve(source.size());
result.insert(result.end(), source.begin(), source.begin() + static_cast<ptrdiff_t>(upTo));
}
bool MergeAdjacentShellLayersInList(PAGXDocument* doc, std::vector<Layer*>& layers,
bool parentHasLayout,
const std::unordered_set<const Layer*>& maskRefs) {
if (parentHasLayout) {
return false;
}
if (layers.size() < 2) {
return false;
}
std::vector<Layer*> result;
bool changed = false;
size_t i = 0;
while (i < layers.size()) {
if (!IsMergeableShellLayer(layers[i], maskRefs)) {
if (changed) {
result.push_back(layers[i]);
}
i++;
continue;
}
size_t j = i + 1;
while (j < layers.size() && IsMergeableShellLayer(layers[j], maskRefs)) {
j++;
}
if (j - i < 2) {
if (changed) {
result.push_back(layers[i]);
}