wintf 0.0.3

Windows Tategaki Framework - Rust UI library with Japanese vertical text support
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
// `ID2D1CommandSink*_Impl` のコールバックは `*const T` を受け取り無条件に deref するため
// `clippy::not_unsafe_ptr_arg_deref` が発火するが、**`unsafe fn` へ変えることはできない**——
// 署名は `windows` クレートの `#[implement]` が生成するトレイト側で固定されており、実装側に
// 変更の自由が無い(安全性の表明先が存在しない)。
//
// SAFETY 根拠は各コールバック(代表例は `SetTransform`)のコメントに記す: 本トレイトの
// コールバックは D2D1 ランタイムのコマンドリスト再生(`ID2D1CommandList::Stream`)からのみ
// 呼ばれ、値構造体への `*const` 引数は D2D1 が記録済みコマンドから渡す非 null ポインタである
// (null 許容の引数は windows-rs 側で `Option`/null チェック付き `as_ref` へ写像済み)。
// 無条件 deref の前提は `debug_assert!(!p.is_null())` で debug ビルドが検査する。
//
// ゆえに本モジュールに限り lint を許可する(診断を消すのではなく、表明できない理由と
// 成立根拠を明記したうえでの限定許可)。
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use std::cell::RefCell;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::Graphics::DirectWrite::*;
use windows::core::*;
use windows_numerics::*;

use super::command_types::*;

#[implement(ID2D1CommandSink5)]
#[derive(Clone, Debug)]
pub struct RecCommandSink {
    commands: RefCell<Vec<DrawCommand>>,
}

impl RecCommandSink {
    pub fn new() -> Self {
        Self {
            commands: RefCell::new(Vec::new()),
        }
    }

    pub fn clear(&mut self) {
        self.commands.borrow_mut().clear();
    }

    pub fn push(&self, command: DrawCommand) {
        self.commands.borrow_mut().push(command);
    }

    pub fn commands(&self) -> &Vec<DrawCommand> {
        // This is tricky because we can't return a reference to the inside of a RefCell.
        // For now, let's assume the caller will handle this. A better API might be needed.
        // A quick fix is to make this method unsafe or change its signature.
        // Let's try to make it work by returning a Ref<Vec<...>>
        // But the original signature returns &Vec.
        // Let's comment it out for now and see if it's used.
        // &self.commands
        todo!()
    }
}

impl ID2D1CommandSink_Impl for RecCommandSink_Impl {
    fn BeginDraw(&self) -> Result<()> {
        self.push(DrawCommand::BeginDraw);
        Ok(())
    }

    fn EndDraw(&self) -> Result<()> {
        self.push(DrawCommand::EndDraw);
        Ok(())
    }

    fn SetAntialiasMode(&self, antialiasmode: D2D1_ANTIALIAS_MODE) -> Result<()> {
        self.push(DrawCommand::SetAntialiasMode(SetAntialiasMode::new(
            antialiasmode,
        )));
        Ok(())
    }
    fn SetTags(&self, tag1: u64, tag2: u64) -> Result<()> {
        self.push(DrawCommand::SetTags(SetTags::new(tag1, tag2)));
        Ok(())
    }
    fn SetTextAntialiasMode(&self, textantialiasmode: D2D1_TEXT_ANTIALIAS_MODE) -> Result<()> {
        self.push(DrawCommand::SetTextAntialiasMode(
            SetTextAntialiasMode::new(textantialiasmode),
        ));
        Ok(())
    }

    fn SetTextRenderingParams(
        &self,
        textrenderingparams: Ref<IDWriteRenderingParams>,
    ) -> Result<()> {
        self.push(DrawCommand::SetTextRenderingParams(
            SetTextRenderingParams::new(textrenderingparams.as_ref()),
        ));
        Ok(())
    }

    fn SetTransform(&self, transform: *const Matrix3x2) -> Result<()> {
        // SAFETY 根拠: ID2D1CommandSink の各コールバックは D2D1 ランタイムの
        // コマンドリスト再生(ID2D1CommandList::Stream)からのみ呼ばれ、
        // 値構造体への *const 引数(transform/rect/cliprect/layerparameters1)は
        // D2D1 が記録済みコマンドから渡す非 null ポインタである(null 許容の
        // 引数は windows-rs 側で Option/null チェック付き as_ref に写像済み)。
        // 無条件 deref の前提を debug ビルドで検査する。
        debug_assert!(!transform.is_null());
        let transform = unsafe { *transform };
        self.push(DrawCommand::SetTransform(SetTransform::new(transform)));
        Ok(())
    }

    fn SetPrimitiveBlend(&self, primitiveblend: D2D1_PRIMITIVE_BLEND) -> Result<()> {
        self.push(DrawCommand::SetPrimitiveBlend(SetPrimitiveBlend::new(
            primitiveblend,
        )));
        Ok(())
    }

    fn SetUnitMode(&self, unitmode: D2D1_UNIT_MODE) -> Result<()> {
        self.push(DrawCommand::SetUnitMode(SetUnitMode::new(unitmode)));
        Ok(())
    }

    fn Clear(&self, color: *const D2D1_COLOR_F) -> Result<()> {
        let color = unsafe { color.as_ref() }.cloned();
        self.push(DrawCommand::Clear(Clear::new(color)));
        Ok(())
    }

    fn DrawGlyphRun(
        &self,
        baselineorigin: &Vector2,
        glyphrun: *const DWRITE_GLYPH_RUN,
        glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
        foregroundbrush: Ref<ID2D1Brush>,
        measuringmode: DWRITE_MEASURING_MODE,
    ) -> Result<()> {
        unsafe {
            // SAFETY 根拠: DWRITE_GLYPH_RUN 契約上 glyphIndices は必須フィールド
            // (glyphAdvances/glyphOffsets と異なり null 不許可)であり、D2D1 は
            // 記録時に検証済みのグリフランのみを再生する。from_raw_parts は
            // len == 0 でも非 null・整列済みポインタを要求するため、
            // 前提を debug ビルドで検査する(glyphCount as usize は
            // u32 → usize の拡大変換のみで切り捨てなし)。
            debug_assert!(!glyphrun.is_null());
            let glyph_run = &*glyphrun;
            debug_assert!(!glyph_run.glyphIndices.is_null());
            let glyph_indices =
                std::slice::from_raw_parts(glyph_run.glyphIndices, glyph_run.glyphCount as usize)
                    .to_vec();
            let glyph_advances = if glyph_run.glyphAdvances.is_null() {
                Vec::new()
            } else {
                std::slice::from_raw_parts(glyph_run.glyphAdvances, glyph_run.glyphCount as usize)
                    .to_vec()
            };
            let glyph_offsets = if glyph_run.glyphOffsets.is_null() {
                Vec::new()
            } else {
                std::slice::from_raw_parts(glyph_run.glyphOffsets, glyph_run.glyphCount as usize)
                    .to_vec()
            };

            self.push(DrawCommand::DrawGlyphRun(DrawGlyphRun::new(
                *baselineorigin,
                glyph_run.fontFace.as_ref().unwrap(),
                glyph_run.fontEmSize,
                glyph_indices,
                glyph_advances,
                glyph_offsets,
                glyph_run.isSideways.as_bool(),
                glyph_run.bidiLevel,
                glyphrundescription.as_ref().cloned(),
                foregroundbrush.as_ref().unwrap(),
                measuringmode,
            )));
        }
        Ok(())
    }

    fn DrawLine(
        &self,
        point0: &Vector2,
        point1: &Vector2,
        brush: Ref<ID2D1Brush>,
        strokewidth: f32,
        strokestyle: Ref<ID2D1StrokeStyle>,
    ) -> Result<()> {
        self.push(DrawCommand::DrawLine(DrawLine::new(
            *point0,
            *point1,
            brush.as_ref().unwrap(),
            strokewidth,
            strokestyle.as_ref(),
        )));
        Ok(())
    }

    fn DrawGeometry(
        &self,
        geometry: Ref<ID2D1Geometry>,
        brush: Ref<ID2D1Brush>,
        strokewidth: f32,
        strokestyle: Ref<ID2D1StrokeStyle>,
    ) -> Result<()> {
        self.push(DrawCommand::DrawGeometry(DrawGeometry::new(
            geometry.as_ref().unwrap(),
            brush.as_ref().unwrap(),
            strokewidth,
            strokestyle.as_ref(),
        )));
        Ok(())
    }

    fn DrawRectangle(
        &self,
        rect: *const D2D_RECT_F,
        brush: Ref<ID2D1Brush>,
        strokewidth: f32,
        strokestyle: Ref<ID2D1StrokeStyle>,
    ) -> Result<()> {
        // SAFETY 根拠: SetTransform の注記参照(D2D1 再生契約により非 null)。
        debug_assert!(!rect.is_null());
        let rect = unsafe { *rect };
        self.push(DrawCommand::DrawRectangle(DrawRectangle::new(
            rect,
            brush.as_ref().unwrap(),
            strokewidth,
            strokestyle.as_ref(),
        )));
        Ok(())
    }

    fn DrawBitmap(
        &self,
        bitmap: Ref<ID2D1Bitmap>,
        destinationrectangle: *const D2D_RECT_F,
        opacity: f32,
        interpolationmode: D2D1_INTERPOLATION_MODE,
        sourcerectangle: *const D2D_RECT_F,
        perspectivetransform: *const Matrix4x4,
    ) -> Result<()> {
        self.push(DrawCommand::DrawBitmap(DrawBitmap::new(
            bitmap.as_ref().unwrap(),
            unsafe { destinationrectangle.as_ref() }.cloned(),
            opacity,
            interpolationmode,
            unsafe { sourcerectangle.as_ref() }.cloned(),
            unsafe { perspectivetransform.as_ref() }.cloned(),
        )));
        Ok(())
    }

    fn DrawImage(
        &self,
        image: Ref<ID2D1Image>,
        targetoffset: *const Vector2,
        imagerectangle: *const D2D_RECT_F,
        interpolationmode: D2D1_INTERPOLATION_MODE,
        compositemode: D2D1_COMPOSITE_MODE,
    ) -> Result<()> {
        self.push(DrawCommand::DrawImage(DrawImage::new(
            image.as_ref().unwrap(),
            unsafe { targetoffset.as_ref() }.cloned(),
            unsafe { imagerectangle.as_ref() }.cloned(),
            interpolationmode,
            compositemode,
        )));
        Ok(())
    }

    fn DrawGdiMetafile(
        &self,
        gdimetafile: Ref<ID2D1GdiMetafile>,
        targetoffset: *const Vector2,
    ) -> Result<()> {
        self.push(DrawCommand::DrawGdiMetafile2(DrawGdiMetafile2::new(
            gdimetafile.as_ref().unwrap(),
            unsafe { targetoffset.as_ref() }.cloned(),
        )));
        Ok(())
    }

    fn FillMesh(&self, mesh: Ref<ID2D1Mesh>, brush: Ref<ID2D1Brush>) -> Result<()> {
        self.push(DrawCommand::FillMesh(FillMesh::new(
            mesh.as_ref().unwrap(),
            brush.as_ref().unwrap(),
        )));
        Ok(())
    }

    fn FillOpacityMask(
        &self,
        opacitymask: Ref<ID2D1Bitmap>,
        brush: Ref<ID2D1Brush>,
        destinationrectangle: *const D2D_RECT_F,
        sourcerectangle: *const D2D_RECT_F,
    ) -> Result<()> {
        self.push(DrawCommand::FillOpacityMask(FillOpacityMask::new(
            opacitymask.as_ref().unwrap(),
            brush.as_ref().unwrap(),
            unsafe { destinationrectangle.as_ref() }.cloned(),
            unsafe { sourcerectangle.as_ref() }.cloned(),
        )));
        Ok(())
    }

    fn FillGeometry(
        &self,
        geometry: Ref<ID2D1Geometry>,
        brush: Ref<ID2D1Brush>,
        opacitybrush: Ref<ID2D1Brush>,
    ) -> Result<()> {
        self.push(DrawCommand::FillGeometry(FillGeometry::new(
            geometry.as_ref().unwrap(),
            brush.as_ref().unwrap(),
            opacitybrush.as_ref(),
        )));
        Ok(())
    }

    fn FillRectangle(&self, rect: *const D2D_RECT_F, brush: Ref<ID2D1Brush>) -> Result<()> {
        // SAFETY 根拠: SetTransform の注記参照(D2D1 再生契約により非 null)。
        debug_assert!(!rect.is_null());
        let rect = unsafe { *rect };
        self.push(DrawCommand::FillRectangle(FillRectangle::new(
            rect,
            brush.as_ref().unwrap(),
        )));
        Ok(())
    }

    fn PushAxisAlignedClip(
        &self,
        cliprect: *const D2D_RECT_F,
        antialiasmode: D2D1_ANTIALIAS_MODE,
    ) -> Result<()> {
        // SAFETY 根拠: SetTransform の注記参照(D2D1 再生契約により非 null)。
        debug_assert!(!cliprect.is_null());
        let cliprect = unsafe { *cliprect };
        self.push(DrawCommand::PushAxisAlignedClip(PushAxisAlignedClip::new(
            cliprect,
            antialiasmode,
        )));
        Ok(())
    }

    fn PushLayer(
        &self,
        layerparameters1: *const D2D1_LAYER_PARAMETERS1,
        layer: Ref<ID2D1Layer>,
    ) -> Result<()> {
        // SAFETY 根拠: SetTransform の注記参照(D2D1 再生契約により非 null)。
        debug_assert!(!layerparameters1.is_null());
        let params = unsafe { &*layerparameters1 };
        self.push(DrawCommand::PushLayer(PushLayer::new(
            params.contentBounds,
            params.geometricMask.as_ref(),
            params.maskAntialiasMode,
            params.maskTransform,
            params.opacity,
            params.opacityBrush.as_ref(),
            params.layerOptions,
            layer.as_ref(),
        )));
        Ok(())
    }

    fn PopAxisAlignedClip(&self) -> Result<()> {
        self.push(DrawCommand::PopAxisAlignedClip);
        Ok(())
    }

    fn PopLayer(&self) -> Result<()> {
        self.push(DrawCommand::PopLayer);
        Ok(())
    }
}

impl ID2D1CommandSink1_Impl for RecCommandSink_Impl {
    fn SetPrimitiveBlend1(&self, primitiveblend: D2D1_PRIMITIVE_BLEND) -> Result<()> {
        self.push(DrawCommand::SetPrimitiveBlend1(SetPrimitiveBlend1::new(
            primitiveblend,
        )));
        Ok(())
    }
}

impl ID2D1CommandSink2_Impl for RecCommandSink_Impl {
    fn DrawInk(
        &self,
        ink: Ref<ID2D1Ink>,
        brush: Ref<ID2D1Brush>,
        inkstyle: Ref<ID2D1InkStyle>,
    ) -> Result<()> {
        self.push(DrawCommand::DrawInk(DrawInk::new(
            ink.as_ref().unwrap(),
            brush.as_ref().unwrap(),
            inkstyle.as_ref(),
        )));
        Ok(())
    }
    fn DrawGradientMesh(&self, gradientmesh: Ref<ID2D1GradientMesh>) -> Result<()> {
        self.push(DrawCommand::DrawGradientMesh(DrawGradientMesh::new(
            gradientmesh.as_ref().unwrap(),
        )));
        Ok(())
    }
    fn DrawGdiMetafile(
        &self,
        gdimetafile: Ref<ID2D1GdiMetafile>,
        destinationrectangle: *const D2D_RECT_F,
        sourcerectangle: *const D2D_RECT_F,
    ) -> Result<()> {
        self.push(DrawCommand::DrawGdiMetafile(DrawGdiMetafile::new(
            gdimetafile.as_ref().unwrap(),
            unsafe { destinationrectangle.as_ref() }.cloned(),
            unsafe { sourcerectangle.as_ref() }.cloned(),
        )));
        Ok(())
    }
}

impl ID2D1CommandSink3_Impl for RecCommandSink_Impl {
    fn DrawSpriteBatch(
        &self,
        spritebatch: Ref<ID2D1SpriteBatch>,
        startindex: u32,
        spritecount: u32,
        bitmap: Ref<ID2D1Bitmap>,
        interpolationmode: D2D1_BITMAP_INTERPOLATION_MODE,
        spriteoptions: D2D1_SPRITE_OPTIONS,
    ) -> Result<()> {
        self.push(DrawCommand::DrawSpriteBatch(DrawSpriteBatch::new(
            spritebatch.as_ref().unwrap(),
            startindex,
            spritecount,
            bitmap.as_ref().unwrap(),
            interpolationmode,
            spriteoptions,
        )));
        Ok(())
    }
}

impl ID2D1CommandSink4_Impl for RecCommandSink_Impl {
    fn SetPrimitiveBlend2(&self, primitiveblend: D2D1_PRIMITIVE_BLEND) -> Result<()> {
        self.push(DrawCommand::SetPrimitiveBlend2(SetPrimitiveBlend2::new(
            primitiveblend,
        )));
        Ok(())
    }
}

impl ID2D1CommandSink5_Impl for RecCommandSink_Impl {
    fn BlendImage(
        &self,
        image: Ref<ID2D1Image>,
        blendmode: D2D1_BLEND_MODE,
        targetoffset: *const Vector2,
        imagerectangle: *const D2D_RECT_F,
        interpolationmode: D2D1_INTERPOLATION_MODE,
    ) -> Result<()> {
        self.push(DrawCommand::BlendImage(BlendImage::new(
            image.as_ref().unwrap(),
            blendmode,
            unsafe { targetoffset.as_ref() }.cloned(),
            unsafe { imagerectangle.as_ref() }.cloned(),
            interpolationmode,
        )));
        Ok(())
    }
}