rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
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
use crate::wmf::converter::{
    svg::{device_context::BlitDestRect, node::Node, util::url_string, Fill},
    *,
};

#[derive(Clone, Debug, snafu::prelude::Snafu)]
pub enum TernaryRasterOperationError {
    #[snafu(display("no brush specified: {cause}"))]
    NoBrush { cause: String },
    #[snafu(display("no source bitmap specified: {cause}"))]
    NoSource { cause: String },
}

#[derive(PartialEq)]
struct BrushOnlyRopKey {
    rect: [i32; 4],
    fill: String,
    clip_id: Option<String>,
    clip_rect: Option<[i32; 4]>,
}

#[derive(Default)]
pub struct BrushOnlyRopSequence {
    state: Option<BrushOnlyRopSequenceState>,
    suppressed_elements: Vec<usize>,
    vector_masks: Vec<(usize, Node, String, [i32; 4])>,
    bitmap_masks: Vec<(usize, String, [i32; 4])>,
}

enum BrushOnlyRopSequenceState {
    AwaitDpa {
        key: BrushOnlyRopKey,
        expected_element_count: usize,
    },
    AwaitFinalPatInvert {
        key: BrushOnlyRopKey,
        expected_element_count: usize,
        mask_definition_index: Option<usize>,
        mask_rect: [i32; 4],
    },
    AwaitFinalVectorInvert {
        key: BrushOnlyRopKey,
        expected_element_count: usize,
        mask: Node,
    },
}

impl BrushOnlyRopSequence {
    /// 마지막 XOR까지 확인한 뒤에만 중간 연산을 역흑백 마스크로 바꾼다.
    /// 마스크 밖에서는 두 XOR이 상쇄되어 바탕이 남고 검정 부분에는 브러시 색이 남는다.
    fn observe(
        &mut self,
        operation: TernaryRasterOperation,
        key: BrushOnlyRopKey,
        element_count: usize,
        mask_definition_index: Option<usize>,
    ) -> bool {
        let state = std::mem::take(&mut self.state);
        match (state, operation) {
            (
                Some(BrushOnlyRopSequenceState::AwaitFinalVectorInvert {
                    key: previous_key,
                    expected_element_count,
                    mask,
                }),
                TernaryRasterOperation::PATINVERT,
            ) if key == previous_key && element_count == expected_element_count => {
                // (D ⊕ P) ∧ M ⊕ P는 흰 마스크에서 D, 검은 마스크에서 P다.
                // 두 바깥 XOR 사각형 대신 같은 윤곽의 역흑백 마스크만 표시한다.
                self.suppressed_elements.push(element_count - 2);
                self.vector_masks.push((
                    element_count - 1,
                    mask,
                    previous_key.fill,
                    previous_key.rect,
                ));
                true
            }
            (
                Some(BrushOnlyRopSequenceState::AwaitDpa {
                    key: previous_key,
                    expected_element_count,
                }),
                TernaryRasterOperation::DPA,
            ) if element_count == expected_element_count
                && key.clip_id == previous_key.clip_id
                && key.clip_rect == previous_key.clip_rect =>
            {
                // 중간 B 영역은 바깥 XOR의 A와 달라도 된다. 흰 마스크에서는
                // 이전 바탕, 검은 마스크에서는 A 안의 P 또는 A 밖의 검정이 남는다.
                let mask_definition_index =
                    mask_definition_index.filter(|_| key.rect[2] > 0 && key.rect[3] > 0);
                self.state = Some(BrushOnlyRopSequenceState::AwaitFinalPatInvert {
                    key: previous_key,
                    expected_element_count: element_count + 1,
                    mask_definition_index,
                    mask_rect: key.rect,
                });
                false
            }
            (
                Some(BrushOnlyRopSequenceState::AwaitFinalPatInvert {
                    key: previous_key,
                    expected_element_count,
                    mask_definition_index,
                    mask_rect,
                }),
                TernaryRasterOperation::PATINVERT,
            ) if key == previous_key && element_count == expected_element_count => {
                if mask_definition_index.is_some() {
                    // (D ⊕ P) ∧ M ⊕ P는 M=흰색에서 D, M=검정에서 P다.
                    // 첫 단색 칠을 지우고 중간 DPa의 실제 패턴으로 P를 마스킹한다.
                    // 팔레트·비트를 버리면 반투명 패널과 바탕의 색이 달라진다.
                    self.suppressed_elements.push(element_count - 2);
                    self.bitmap_masks
                        .push((element_count - 1, previous_key.fill, mask_rect));
                }
                true
            }
            (_, TernaryRasterOperation::PATINVERT) => {
                self.state = Some(BrushOnlyRopSequenceState::AwaitDpa {
                    key,
                    expected_element_count: element_count + 1,
                });
                false
            }
            _ => false,
        }
    }

    pub fn observe_vector_mask(
        &mut self,
        mask: &Node,
        brush: &Brush,
        draw_mode: Option<BinaryRasterOperation>,
        bounds: [i32; 4],
        clip: (Option<&str>, Option<&Rect>),
        element_count: usize,
    ) {
        let Some(BrushOnlyRopSequenceState::AwaitDpa {
            key,
            expected_element_count,
        }) = self.state.take()
        else {
            return;
        };
        let (clip_id, clip_rect) = clip;
        let clip_rect = clip_rect.map(|r| {
            [
                i32::from(r.left),
                i32::from(r.top),
                i32::from(r.right),
                i32::from(r.bottom),
            ]
        });
        let [x, y, width, height] = key.rect;
        if expected_element_count != element_count
            || draw_mode != Some(BinaryRasterOperation::R2_MASKPEN)
            || !Self::brush_is_monochrome_mask(Some(brush))
            || mask.attr("stroke") != Some("none")
            || !key.fill.starts_with('#')
            || key.clip_id.as_deref() != clip_id
            || key.clip_rect != clip_rect
            || width <= 0
            || height <= 0
            || bounds[0] < x
            || bounds[1] < y
            || i64::from(bounds[2]) > i64::from(x) + i64::from(width)
            || i64::from(bounds[3]) > i64::from(y) + i64::from(height)
        {
            return;
        }
        self.state = Some(BrushOnlyRopSequenceState::AwaitFinalVectorInvert {
            key,
            expected_element_count: element_count + 1,
            mask: mask.clone(),
        });
    }

    pub fn finish(
        self,
        mut definitions: Vec<Node>,
        mut elements: Vec<Node>,
    ) -> (Vec<Node>, Vec<Node>) {
        let bitmap_masks: Vec<_> = self
            .bitmap_masks
            .into_iter()
            .map(|(index, color, rect)| {
                let mask = elements[index]
                    .clone()
                    .set("id", format!("rop_bitmap_source{index}"));
                let paint = elements[index - 1].clone().set("fill", &color);
                (index, mask, color, rect, Some(paint))
            })
            .collect();
        for (kind, (index, mask, color, [x, y, width, height], paint)) in self
            .vector_masks
            .into_iter()
            .map(|(index, mask, color, rect)| ("vector", (index, mask, color, rect, None)))
            .chain(bitmap_masks.into_iter().map(|mask| ("bitmap", mask)))
        {
            let filter_id = format!("rop_{kind}_inverse{}", definitions.len());
            let mask_id = format!("rop_{kind}_mask{}", definitions.len());
            let transfer = Node::new("feComponentTransfer")
                .add(
                    Node::new("feFuncR")
                        .set("type", "table")
                        .set("tableValues", "1 0"),
                )
                .add(
                    Node::new("feFuncG")
                        .set("type", "table")
                        .set("tableValues", "1 0"),
                )
                .add(
                    Node::new("feFuncB")
                        .set("type", "table")
                        .set("tableValues", "1 0"),
                );
            definitions.push(
                Node::new("filter")
                    .set("id", &filter_id)
                    .set("color-interpolation-filters", "sRGB")
                    .add(transfer),
            );
            definitions.push(
                Node::new("mask")
                    .set("id", &mask_id)
                    .set("maskUnits", "userSpaceOnUse")
                    .set("mask-type", "luminance")
                    .set("x", x)
                    .set("y", y)
                    .set("width", width)
                    .set("height", height)
                    .add(mask.set("filter", url_string(format!("#{filter_id}").as_str()))),
            );
            let mask_url = url_string(format!("#{mask_id}").as_str());
            if let Some(paint) = paint {
                // B의 검정과 A의 브러시 색을 먼저 합성한 뒤 마스크를 한 번 적용한다.
                // 개별 칠에 따로 적용하면 보간된 마스크 경계의 alpha가 중복된다.
                // B의 viewport와 같은 viewBox이므로 원문 장치 좌표는 그대로다.
                let black = elements[index].clone().set("fill", "black");
                elements[index] = Node::new("svg")
                    .set("x", x)
                    .set("y", y)
                    .set("width", width)
                    .set("height", height)
                    .set("viewBox", format!("{x} {y} {width} {height}"))
                    .set("mask", &mask_url)
                    .add(black)
                    .add(paint);
            } else {
                elements[index] = elements[index]
                    .clone()
                    .set("fill", color)
                    .set("mask", &mask_url);
            }
        }
        // Indices are recorded in emission order. Do not remove nodes while
        // collecting: doing so would change IDs or invalidate later indices.
        let elements = elements
            .into_iter()
            .enumerate()
            .filter_map(|(index, node)| {
                self.suppressed_elements
                    .binary_search(&index)
                    .is_err()
                    .then_some(node)
            })
            .collect();
        (definitions, elements)
    }

    /// One bit is a palette index, not proof of a black/white mask.
    /// Palette-indexed brushes cannot be classified without resolving the DC.
    fn brush_is_monochrome_mask(brush: Option<&Brush>) -> bool {
        let Some(Brush::DIBPatternPT {
            color_usage: ColorUsage::DIB_RGB_COLORS,
            brush_hatch,
        }) = brush
        else {
            return false;
        };
        if !matches!(
            brush_hatch.dib_header_info.bit_count(),
            BitCount::BI_BITCOUNT_1
        ) {
            return false;
        }
        let colors = match &brush_hatch.colors {
            Colors::RGBQuad(colors) if colors.len() == 2 => [
                [colors[0].red, colors[0].green, colors[0].blue],
                [colors[1].red, colors[1].green, colors[1].blue],
            ],
            Colors::RGBTriple(colors) if colors.len() == 2 => [
                [colors[0].red, colors[0].green, colors[0].blue],
                [colors[1].red, colors[1].green, colors[1].blue],
            ],
            _ => return false,
        };
        matches!(
            colors,
            [[0, 0, 0], [255, 255, 255]] | [[255, 255, 255], [0, 0, 0]]
        )
    }

    fn clear_if_unrelated(&mut self, operation: TernaryRasterOperation) {
        if !matches!(
            operation,
            TernaryRasterOperation::PATINVERT | TernaryRasterOperation::DPA
        ) {
            self.state = None;
        }
    }
}

pub struct TernaryRasterOperator {
    operation: TernaryRasterOperation,
    /// [#6617] 장치 좌표로 정규화한 목적 사각형(`DeviceContext::blit_dest_rect`).
    rect: BlitDestRect,
    brush: Option<Brush>,
    source: Option<Source>,
    /// 원본 DIB에서 읽을 사각형. 음수 크기는 원본 축의 반전이다.
    source_rect: Option<BitmapSourceRect>,
    /// StretchDIB의 상향식 DIB는 원점이 왼쪽 아래에 있다.
    source_bottom_up: bool,
    clip_id: Option<String>,
    clip_rect: Option<[i32; 4]>,
}

#[derive(Clone, Copy)]
struct BitmapSourceRect {
    x: i16,
    y: i16,
    width: i16,
    height: i16,
}

enum Source {
    Bitmap16(Bitmap16),
    Bitmap(DeviceIndependentBitmap),
}

impl TernaryRasterOperator {
    pub fn new(operation: TernaryRasterOperation, rect: BlitDestRect) -> Self {
        Self {
            operation,
            rect,
            brush: None,
            source: None,
            source_rect: None,
            source_bottom_up: false,
            clip_id: None,
            clip_rect: None,
        }
    }

    /// 목적 사각형과, 뒤집힌 축이 있으면 그 축을 되돌리는 `transform`.
    ///
    /// [#6140] SVG 의 `width`/`height` 는 음수를 오류로 규정하므로 사각형은 항상 양수 크기로
    /// 두고 뒤집힘을 요소 자신의 `transform` 으로 표현한다. [#6617] 어느 축이 뒤집히는지는
    /// 논리 폭/높이 부호가 아니라 장치 좌표에서 정한다(`DeviceContext::blit_dest_rect`) —
    /// y-up 창의 음수 높이 DIB 는 뒤집히지 않는다.
    fn normalized_rect(&self) -> (i32, i32, i32, i32, Option<String>) {
        let BlitDestRect {
            x,
            y,
            width,
            height,
            flip_x,
            flip_y,
        } = self.rect;
        let mut parts = Vec::new();
        if flip_x {
            parts.push(format!("translate({},0) scale(-1,1)", 2 * x + width));
        }
        if flip_y {
            parts.push(format!("translate(0,{}) scale(1,-1)", 2 * y + height));
        }
        let transform = (!parts.is_empty()).then(|| parts.join(" "));
        (x, y, width, height, transform)
    }

    pub(super) fn image_node(rect: BlitDestRect, data_url: String) -> Node {
        let (x, y, width, height, transform) =
            Self::new(TernaryRasterOperation::SRCCOPY, rect).normalized_rect();
        let image = Node::new("image")
            .set("x", x)
            .set("y", y)
            .set("width", width)
            .set("height", height)
            .set("preserveAspectRatio", "none")
            .set("href", data_url);
        match transform {
            Some(transform) => image.set("transform", transform),
            None => image,
        }
    }

    pub fn brush(mut self, brush: Brush) -> Self {
        self.brush = brush.into();
        self
    }

    pub fn clip(mut self, clip_id: Option<&str>, clip_rect: Option<&Rect>) -> Self {
        self.clip_id = clip_id.map(str::to_owned);
        // INTERSECTCLIPRECT changes the DC without issuing an SVG clip ID.
        // Track both representations before cancelling any raster draw.
        self.clip_rect = clip_rect.map(|rect| {
            [
                i32::from(rect.left),
                i32::from(rect.top),
                i32::from(rect.right),
                i32::from(rect.bottom),
            ]
        });
        self
    }

    pub fn source_bitmap16(mut self, source: Bitmap16) -> Self {
        self.source = Source::Bitmap16(source).into();
        self
    }

    pub fn source_bitmap(mut self, source: DeviceIndependentBitmap) -> Self {
        self.source = Source::Bitmap(source).into();
        self
    }

    /// DIB 전송 레코드의 원본 사각형을 목적 사각형과 별도로 보존한다.
    pub fn source_rectangle(mut self, x: i16, y: i16, width: i16, height: i16) -> Self {
        self.source_rect = Some(BitmapSourceRect {
            x,
            y,
            width,
            height,
        });
        self
    }

    /// StretchDIB의 원본 좌표가 아래쪽을 원점으로 삼는 경우에 지정한다.
    pub fn bottom_up_source(mut self) -> Self {
        self.source_bottom_up = true;
        self
    }

    fn bitmap_node(&self, bitmap: Bitmap, dimensions: (usize, usize)) -> Option<Node> {
        let (x, y, width, height, transform) = self.normalized_rect();
        let Some(source) = self.source_rect else {
            let image = Node::new("image")
                .set("x", x)
                .set("y", y)
                .set("width", width)
                .set("height", height)
                .set("preserveAspectRatio", "none")
                .set("href", bitmap.as_data_url());
            return Some(match transform {
                Some(transform) => image.set("transform", transform),
                None => image,
            });
        };
        if source.width == 0 || source.height == 0 || dimensions.0 == 0 || dimensions.1 == 0 {
            return None;
        }
        // 전체 원본은 직접 전송한다. 부분 원본에는 명시적 viewport가 필요하다.
        if source.x == 0
            && source.y == 0
            && usize::try_from(source.width).ok() == Some(dimensions.0)
            && usize::try_from(source.height).ok() == Some(dimensions.1)
        {
            let image = Node::new("image")
                .set("x", x)
                .set("y", y)
                .set("width", width)
                .set("height", height)
                // WMF 비트맵 전송은 원본 비율과 달라도 목적 사각형을 채운다.
                .set("preserveAspectRatio", "none")
                .set("href", bitmap.as_data_url());
            return Some(match transform {
                Some(transform) => image.set("transform", transform),
                None => image,
            });
        }
        let sx = i64::from(source.x);
        let sw = i64::from(source.width);
        let sh = i64::from(source.height);
        let sy = if self.source_bottom_up {
            i64::try_from(dimensions.1).ok()? - i64::from(source.y) - sh
        } else {
            i64::from(source.y)
        };
        let mut image = Node::new("image")
            .set("x", 0)
            .set("y", 0)
            .set("width", dimensions.0)
            .set("height", dimensions.1)
            .set("preserveAspectRatio", "none")
            .set("href", bitmap.as_data_url());
        let mut source_transforms = Vec::new();
        if sw < 0 {
            source_transforms.push(format!("translate({},0) scale(-1,1)", 2 * sx + sw));
        }
        if sh < 0 {
            source_transforms.push(format!("translate(0,{}) scale(1,-1)", 2 * sy + sh));
        }
        if !source_transforms.is_empty() {
            image = image.set("transform", source_transforms.join(" "));
        }
        let viewport = Node::new("svg")
            .set("x", x)
            .set("y", y)
            .set("width", width)
            .set("height", height)
            .set(
                "viewBox",
                format!(
                    "{} {} {} {}",
                    sx.min(sx + sw),
                    sy.min(sy + sh),
                    sw.abs(),
                    sh.abs()
                ),
            )
            .set("preserveAspectRatio", "none")
            .set("overflow", "hidden")
            .add(image);
        // nested SVG의 transform은 구현마다 다르게 소비하므로 바깥 그룹에 둔다.
        Some(match transform {
            Some(transform) => Node::new("g").set("transform", transform).add(viewport),
            None => viewport,
        })
    }

    fn source_bitmap_node(&mut self) -> Option<Node> {
        let dib = match self.source.take()? {
            Source::Bitmap16(data) => DeviceIndependentBitmap::from(data),
            Source::Bitmap(data) => data,
        };
        let dimensions = (dib.dib_header_info.width(), dib.dib_header_info.height());
        self.bitmap_node(Bitmap::from(dib), dimensions)
    }

    pub fn run(
        mut self,
        definitions: &mut Vec<Node>,
        brush_only_rop_sequence: &mut BrushOnlyRopSequence,
        element_count: usize,
    ) -> Result<Option<Node>, TernaryRasterOperationError> {
        brush_only_rop_sequence.clear_if_unrelated(self.operation);

        if self.operation.use_selected_brush() && self.brush.is_none() {
            return Err(TernaryRasterOperationError::NoBrush {
                cause: format!(
                    "TernaryRasterOperation {:?} cannot access brush.",
                    self.operation,
                ),
            });
        }

        if self.operation.use_source() && self.source.is_none() {
            return Err(TernaryRasterOperationError::NoSource {
                cause: format!(
                    "TernaryRasterOperation {:?} cannot access source bitmap.",
                    self.operation,
                ),
            });
        }

        let result: Node = match self.operation {
            TernaryRasterOperation::BLACKNESS => Node::new("rect")
                .set("x", self.rect.x)
                .set("y", self.rect.y)
                .set("width", self.rect.width)
                .set("height", self.rect.height)
                .set("stroke", "none")
                .set("fill", "black"),
            TernaryRasterOperation::SRCCOPY => {
                let Some(image) = self.source_bitmap_node() else {
                    return Ok(None);
                };
                image
            }
            TernaryRasterOperation::PATCOPY => {
                let fill = match Fill::from(self.brush.clone().unwrap()) {
                    Fill::Pattern { pattern } => {
                        let id = Self::issue_id(definitions);
                        definitions.push(pattern.set("id", id.as_str()));
                        url_string(format!("#{id}").as_str())
                    }
                    Fill::Value { value } => value,
                };

                Node::new("rect")
                    .set("x", self.rect.x)
                    .set("y", self.rect.y)
                    .set("width", self.rect.width)
                    .set("height", self.rect.height)
                    .set("fill", fill.as_str())
            }
            TernaryRasterOperation::WHITENESS => Node::new("rect")
                .set("x", self.rect.x)
                .set("y", self.rect.y)
                .set("width", self.rect.width)
                .set("height", self.rect.height)
                .set("stroke", "none")
                .set("fill", "white"),
            // 미지원 연산의 칠을 버리지 않는 기존 PATCOPY 폴백이다(#6469).
            // 완전한 XOR → 흑백 DPa → XOR는 상태 기계가 실제 비트맵/벡터
            // 마스크로 확정한다. 세 단색 칠과 같은 연산이라고 가정하지 않는다.
            // 다른 팔레트·불완전한 순서 등은 아직 이 근사 경로에 남아 있다.
            operation if operation.use_selected_brush() && !operation.use_source() => {
                info!(
                    ?operation,
                    "approximating brush-only TernaryRasterOperation as PATCOPY"
                );
                let is_mask = BrushOnlyRopSequence::brush_is_monochrome_mask(self.brush.as_ref());
                let mut mask_definition_index = None;
                let fill = match Fill::from(self.brush.clone().unwrap()) {
                    Fill::Pattern { pattern } => {
                        let id = Self::issue_id(definitions);
                        if is_mask {
                            mask_definition_index = Some(definitions.len());
                        }
                        definitions.push(pattern.set("id", id.as_str()));
                        url_string(format!("#{id}").as_str())
                    }
                    Fill::Value { value } => value,
                };

                // `PATINVERT`(D ⊕ P)는 확인된 연속 관용구 안에서만 상쇄한다.
                //
                //   PATINVERT(gray) → DPa(패턴) → PATINVERT(gray)
                //
                // 출력 요소 순서상 연속한 세 연산만 확정한다. 전역 이력에서
                // 같은 키를 찾아 독립된 후속 칠까지 지우지 않는다.
                let key = BrushOnlyRopKey {
                    rect: [self.rect.x, self.rect.y, self.rect.width, self.rect.height],
                    fill: fill.clone(),
                    clip_id: self.clip_id,
                    clip_rect: self.clip_rect,
                };
                if brush_only_rop_sequence.observe(
                    operation,
                    key,
                    element_count,
                    mask_definition_index,
                ) {
                    return Ok(None);
                }

                Node::new("rect")
                    .set("x", self.rect.x)
                    .set("y", self.rect.y)
                    .set("width", self.rect.width)
                    .set("height", self.rect.height)
                    .set("fill", fill.as_str())
            }
            operation if operation.use_source() => {
                info!(
                    ?operation,
                    "approximating source TernaryRasterOperation as SRCCOPY"
                );
                let Some(image) = self.source_bitmap_node() else {
                    return Ok(None);
                };
                image
            }
            operation => {
                info!(?operation, "TernaryRasterOperation is not implemented");

                return Ok(None);
            }
        };

        Ok(Some(result))
    }

    #[inline]
    fn issue_id(definitions: &[Node]) -> String {
        format!("rop_pat{}", definitions.len())
    }
}

impl From<ColorRef> for RGBQuad {
    fn from(v: ColorRef) -> Self {
        let ColorRef {
            red,
            green,
            blue,
            reserved,
        } = v;
        Self {
            red,
            green,
            blue,
            reserved,
        }
    }
}