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
use crate::utility::*;
use crate::*;
use windows::core::Interface;
use windows::{
    Foundation::Numerics::*,
    Win32::Graphics::{DirectWrite::*, Dxgi::*, Imaging::*},
    Win32::System::Com::*,
};

pub struct DrawCommand<'a> {
    device_context: &'a ID2D1DeviceContext,
    dwrite_factory: &'a IDWriteFactory5,
}

impl<'a> DrawCommand<'a> {
    #[inline]
    pub fn clear(&self, color: impl Into<Rgba>) {
        unsafe {
            let color: D2D1_COLOR_F = Inner(color.into()).into();
            self.device_context.Clear(&color);
        }
    }

    #[inline]
    pub fn fill(&self, object: &impl Fill, brush: &Brush) {
        object.fill(self.device_context, &brush.handle());
    }

    #[inline]
    pub fn stroke(
        &self,
        object: &impl Stroke,
        brush: &Brush,
        width: f32,
        style: Option<&StrokeStyle>,
    ) {
        object.stroke(
            self.device_context,
            &brush.handle(),
            width,
            style.map(|s| s.0.clone()),
        );
    }

    #[inline]
    pub fn draw_text(
        &self,
        text: &str,
        format: &TextFormat,
        brush: &Brush,
        origin: impl Into<Point>,
    ) {
        let layout = TextLayout::new(
            &self.dwrite_factory.cast().unwrap(),
            text,
            format,
            TextAlignment::Leading,
            None,
        );
        if let Ok(layout) = layout {
            self.draw_text_layout(&layout, brush, origin);
        }
    }

    #[inline]
    pub fn draw_text_layout(&self, layout: &TextLayout, brush: &Brush, origin: impl Into<Point>) {
        layout.draw(&self.device_context, brush, origin.into());
    }

    #[inline]
    pub fn draw_image(
        &self,
        image: &Image,
        dest_rect: impl Into<Rect>,
        src_rect: Option<Rect>,
        interpolation: Interpolation,
    ) {
        image.draw(
            &self.device_context,
            dest_rect.into(),
            src_rect,
            interpolation,
        );
    }

    #[inline]
    pub fn clip(&self, rect: impl Into<Rect>, f: impl FnOnce(&DrawCommand)) {
        let rect: D2D_RECT_F = Inner(rect.into()).into();
        unsafe {
            self.device_context
                .PushAxisAlignedClip(&rect, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
            f(self);
            self.device_context.PopAxisAlignedClip();
        }
    }

    #[inline]
    pub fn set_offset(&self, point: impl Into<Point>) {
        let point = point.into();
        let m = Matrix3x2::translation(point.x, point.y);
        unsafe {
            self.device_context.SetTransform(&m);
        }
    }
}

pub trait Backend {
    type RenderTarget: Target;

    fn device_context(&self) -> &ID2D1DeviceContext;
    fn d2d1_factory(&self) -> &ID2D1Factory1;
    fn back_buffers(
        &self,
        swap_chain: &IDXGISwapChain1,
    ) -> windows::core::Result<Vec<Self::RenderTarget>>;
    fn render_target(&self, target: &impl Interface) -> windows::core::Result<Self::RenderTarget>;
    fn begin_draw(&self, target: &Self::RenderTarget);
    fn end_draw(&self, target: &Self::RenderTarget);
}

#[derive(Clone)]
pub struct Factory {
    d2d1_factory: ID2D1Factory1,
    device_context: ID2D1DeviceContext,
    dwrite_factory: IDWriteFactory5,
    wic_imaging_factory: IWICImagingFactory,
}

impl Factory {
    #[inline]
    pub fn create_gradient_stop_collection<U>(
        &self,
        stops: &[U],
    ) -> windows::core::Result<GradientStopCollection>
    where
        U: Into<GradientStop> + Clone,
    {
        GradientStopCollection::new(&self.device_context, stops)
    }

    #[inline]
    pub fn create_solid_color_brush(&self, color: impl Into<Rgba>) -> windows::core::Result<Brush> {
        Brush::solid_color(&self.device_context, color)
    }

    #[inline]
    pub fn create_linear_gradient_brush(
        &self,
        start: impl Into<Point>,
        end: impl Into<Point>,
        stop_collection: &GradientStopCollection,
    ) -> windows::core::Result<Brush> {
        Brush::linear_gradient(&self.device_context, start, end, stop_collection)
    }

    #[inline]
    pub fn create_radial_gradient_brush(
        &self,
        center: impl Into<Point>,
        offset: impl Into<Point>,
        radius: impl Into<Vector>,
        stop_collection: &GradientStopCollection,
    ) -> windows::core::Result<Brush> {
        Brush::radial_gradient(
            &self.device_context,
            center,
            offset,
            radius,
            stop_collection,
        )
    }

    #[inline]
    pub fn create_path(&self) -> PathBuilder {
        let geometry = unsafe { self.d2d1_factory.CreatePathGeometry().unwrap() };
        PathBuilder::new(geometry)
    }

    #[inline]
    pub fn create_stroke_style(
        &self,
        props: &StrokeStyleProperties,
    ) -> windows::core::Result<StrokeStyle> {
        StrokeStyle::new(&self.d2d1_factory, props)
    }

    #[inline]
    pub fn create_text_format(
        &self,
        font: &Font,
        size: impl Into<f32>,
        style: Option<&TextStyle>,
    ) -> windows::core::Result<TextFormat> {
        TextFormat::new(&self.dwrite_factory, font, size.into(), style)
    }

    #[inline]
    pub fn create_text_layout(
        &self,
        text: impl AsRef<str>,
        format: &TextFormat,
        alignment: TextAlignment,
        size: Option<Size>,
    ) -> windows::core::Result<TextLayout> {
        TextLayout::new(
            &self.dwrite_factory.clone().into(),
            text.as_ref(),
            format,
            alignment,
            size,
        )
    }

    #[inline]
    pub fn create_image(&self, loader: impl ImageLoader) -> windows::core::Result<Image> {
        Image::new(&self.device_context, &self.wic_imaging_factory, loader)
    }
}

unsafe impl Send for Factory {}
unsafe impl Sync for Factory {}

#[derive(Clone)]
pub struct Context<T> {
    backend: T,
    dwrite_factory: IDWriteFactory5,
    wic_imaging_factory: IWICImagingFactory,
}

impl<T> Context<T>
where
    T: Backend + Clone,
{
    #[inline]
    pub fn new(backend: T) -> windows::core::Result<Self> {
        unsafe {
            let dwrite_factory =
                DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, &IDWriteFactory5::IID)?.cast()?;
            let wic_imaging_factory =
                CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
            Ok(Self {
                backend,
                dwrite_factory,
                wic_imaging_factory,
            })
        }
    }

    #[inline]
    pub fn create_factory(&self) -> Factory {
        Factory {
            d2d1_factory: self.backend.d2d1_factory().clone(),
            device_context: self.backend.device_context().clone(),
            dwrite_factory: self.dwrite_factory.clone(),
            wic_imaging_factory: self.wic_imaging_factory.clone(),
        }
    }

    #[inline]
    pub fn backend(&self) -> &T {
        &self.backend
    }

    #[inline]
    pub fn create_back_buffers(
        &self,
        swap_chain: &impl Interface,
    ) -> windows::core::Result<Vec<T::RenderTarget>> {
        let swap_chain: IDXGISwapChain1 = swap_chain.cast()?;
        let ret = self.backend.back_buffers(&swap_chain);
        ret
    }

    #[inline]
    pub fn create_render_target(
        &self,
        target: &impl Interface,
    ) -> windows::core::Result<T::RenderTarget> {
        self.backend.render_target(target)
    }

    #[inline]
    pub fn set_dpi(&self, dpi: f32) {
        unsafe {
            self.backend.device_context().SetDpi(dpi, dpi);
        }
    }

    pub fn draw<R>(&self, target: &T::RenderTarget, f: impl FnOnce(&DrawCommand) -> R) -> R {
        let device_context = self.backend.device_context();
        unsafe {
            self.backend.begin_draw(target);
            device_context.SetTarget(target.bitmap());
            device_context.BeginDraw();
            let ret = f(&DrawCommand {
                device_context: self.backend.device_context(),
                dwrite_factory: &self.dwrite_factory,
            });
            device_context
                .EndDraw(std::ptr::null_mut(), std::ptr::null_mut())
                .unwrap();
            device_context.SetTarget(None);
            self.backend.end_draw(target);
            ret
        }
    }
}