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
use std::{ptr, mem};
use winapi::*;
use math::*;
use brush::{self, Brush};
use geometry::Geometry;
use error::D2D1Error;
use stroke_style::StrokeStyle;
use factory::Factory;
use comptr::ComPtr;
use helpers::{GetRaw, FromRaw, ToWide};
use directwrite::{TextFormat, TextLayout};

/// This trait is intended to be implemented by external APIs who would
/// like to allow a Direct2D interface for drawing onto them. Since the
/// Direct2D creation APIs require more information, this will likely be
/// implemented on Builder objects which contain enough context about
/// the actual backing structure and what needs to be done to set it up.
pub unsafe trait RenderTargetBacking {
    /// The ID2D1RenderTarget's ownership is passed out of the function and as such
    /// the caller is now responsible for ensuring the pointer will receive its
    /// Release() call.
    fn create_target(self, factory: &mut ID2D1Factory) -> Result<*mut ID2D1RenderTarget, HRESULT>;
}

#[derive(Clone, Debug)]
pub struct RenderTarget {
    ptr: ComPtr<ID2D1RenderTarget>,
}

#[derive(Copy, Clone, Debug)]
pub struct RenderTag {
    pub file_line: &'static str,
}

struct RenderTagRaw(usize, usize);

#[macro_export]
macro_rules! make_render_tag {
    () => {
        RenderTag {
            file: concat!(file!(), ':', line!())
        }
    }
}

#[macro_export]
macro_rules! set_render_tag {
    ($rt:ident) => {
        $rt.set_tag(make_render_tag!());
    }
}

impl RenderTarget {
    unsafe fn rt<'a>(&self) -> &'a mut ID2D1RenderTarget {
        &mut *self.ptr.raw_value()
    }

    pub unsafe fn hwnd_rt(&self) -> Option<ComPtr<ID2D1HwndRenderTarget>> {
        self.ptr.query_interface().ok()
    }

    unsafe fn make_tag(tag1: D2D1_TAG, tag2: D2D1_TAG) -> Option<RenderTag> {
        if tag1 == 0 {
            None
        } else {
            let raw = RenderTagRaw(tag1 as usize, tag2 as usize);
            let tag = mem::transmute(raw);
            Some(tag)
        }
    }

    pub fn get_factory(&mut self) -> Factory {
        unsafe {
            let mut factory = ComPtr::<ID2D1Factory>::new();
            self.rt().GetFactory(factory.raw_addr());

            Factory::from_ptr(factory)
        }
    }

    pub fn get_size(&self) -> SizeF {
        unsafe {
            let mut size = mem::uninitialized();
            self.rt().GetSize(&mut size);
            SizeF(size)
        }
    }

    pub fn create_solid_color_brush<C: Into<ColorF>>(&self,
                                                     color: C,
                                                     props: &BrushProperties)
                                                     -> Result<brush::SolidColor, D2D1Error> {
        unsafe {
            let mut ptr = ComPtr::<ID2D1SolidColorBrush>::new();
            let result = self.rt().CreateSolidColorBrush(&color.into().0, &props.0, ptr.raw_addr());

            if SUCCEEDED(result) {
                Ok(FromRaw::from_raw(ptr.raw_value()))
            } else {
                Err(From::from(result))
            }
        }
    }

    pub fn begin_draw(&mut self) {
        unsafe {
            self.rt().BeginDraw();
        }
    }

    pub fn end_draw(&mut self) -> Result<(), (D2D1Error, Option<RenderTag>)> {
        let mut tag1 = 0;
        let mut tag2 = 0;
        unsafe {
            let result = self.rt().EndDraw(&mut tag1, &mut tag2);

            if SUCCEEDED(result) {
                Ok(())
            } else {
                let tag = RenderTarget::make_tag(tag1, tag2);
                Err((From::from(result), tag))
            }
        }
    }

    pub fn set_tag(&mut self, tag: RenderTag) {
        unsafe {
            let RenderTagRaw(tag1, tag2) = mem::transmute(tag);
            self.rt().SetTags(tag1 as u64, tag2 as u64)
        };
    }

    pub fn get_tag(&mut self) -> Option<RenderTag> {
        let mut tag1 = 0;
        let mut tag2 = 0;
        unsafe {
            self.rt().GetTags(&mut tag1, &mut tag2);
            RenderTarget::make_tag(tag1, tag2)
        }
    }

    pub fn flush(&mut self) -> Result<(), (D2D1Error, Option<RenderTag>)> {
        let mut tag1 = 0;
        let mut tag2 = 0;
        unsafe {
            let result = self.rt().Flush(&mut tag1, &mut tag2);

            if SUCCEEDED(result) {
                Ok(())
            } else {
                let tag = RenderTarget::make_tag(tag1, tag2);
                Err((From::from(result), tag))
            }
        }
    }

    pub fn clear(&mut self, color: &ColorF) {
        unsafe {
            self.rt().Clear(&color.0);
        }
    }

    pub fn draw_line<B: Brush>(&mut self,
                               p0: &Point2F,
                               p1: &Point2F,
                               brush: &B,
                               stroke_width: f32,
                               stroke_style: Option<&StrokeStyle>) {
        unsafe {
            let stroke_style = match stroke_style {
                Some(s) => s.get_ptr(),
                None => ptr::null_mut(),
            };

            self.rt().DrawLine(p0.0, p1.0, brush.get_ptr(), stroke_width, stroke_style)
        }
    }

    pub fn draw_rectangle<B: Brush>(&mut self,
                                    rect: &RectF,
                                    brush: &B,
                                    stroke_width: f32,
                                    stroke_style: Option<&StrokeStyle>) {
        unsafe {
            let stroke_style = match stroke_style {
                Some(s) => s.get_ptr(),
                None => ptr::null_mut(),
            };

            self.rt().DrawRectangle(&rect.0, brush.get_ptr(), stroke_width, stroke_style);
        }
    }

    pub fn fill_rectangle<B: Brush>(&mut self, rect: &RectF, brush: &B) {
        unsafe {
            self.rt().FillRectangle(&rect.0, brush.get_ptr());
        }
    }

    pub fn draw_rounded_rectangle<B: Brush>(&mut self,
                                            rect: &RoundedRect,
                                            brush: &B,
                                            stroke_width: f32,
                                            stroke_style: Option<&StrokeStyle>) {
        unsafe {
            let stroke_style = match stroke_style {
                Some(s) => s.get_ptr(),
                None => ptr::null_mut(),
            };

            self.rt().DrawRoundedRectangle(&rect.0, brush.get_ptr(), stroke_width, stroke_style);
        }
    }

    pub fn fill_rounded_rectangle<B: Brush>(&mut self, rect: &RoundedRect, brush: &B) {
        unsafe {
            self.rt().FillRoundedRectangle(&rect.0, brush.get_ptr());
        }
    }

    pub fn draw_ellipse<B: Brush>(&mut self,
                                  ellipse: &Ellipse,
                                  brush: &B,
                                  stroke_width: f32,
                                  stroke_style: Option<&StrokeStyle>) {
        unsafe {
            let stroke_style = match stroke_style {
                Some(s) => s.get_ptr(),
                None => ptr::null_mut(),
            };

            self.rt().DrawEllipse(&ellipse.0, brush.get_ptr(), stroke_width, stroke_style);
        }
    }

    pub fn fill_ellipse<B: Brush>(&mut self, ellipse: &Ellipse, brush: &B) {
        unsafe {
            self.rt().FillEllipse(&ellipse.0, brush.get_ptr());
        }
    }

    pub fn draw_geometry<G: Geometry, B: Brush>(&mut self,
                                                geometry: &G,
                                                brush: &B,
                                                stroke_width: f32,
                                                stroke_style: Option<&StrokeStyle>) {
        unsafe {
            let stroke_style = match stroke_style {
                Some(s) => s.get_ptr(),
                None => ptr::null_mut(),
            };

            self.rt().DrawGeometry(geometry.get_ptr(),
                                   brush.get_ptr(),
                                   stroke_width,
                                   stroke_style);
        }
    }

    pub fn fill_geometry<G: Geometry, B: Brush>(&mut self, geometry: &G, brush: &B) {
        unsafe {
            self.rt().FillGeometry(geometry.get_ptr(), brush.get_ptr(), ptr::null_mut());
        }
    }

    pub fn fill_geometry_with_opacity<G: Geometry, B: Brush, OB: Brush>(&mut self,
                                                                        geometry: &G,
                                                                        brush: &B,
                                                                        opacity_brush: &OB) {
        unsafe {
            self.rt().FillGeometry(geometry.get_ptr(), brush.get_ptr(), opacity_brush.get_ptr());
        }
    }

    pub fn draw_text<B: Brush>(&mut self,
                               text: &str,
                               format: &TextFormat,
                               layout_rect: &RectF,
                               foreground_brush: &B,
                               options: &[DrawTextOption]) {
        let text = text.to_wide_null();
        let mut draw_options = D2D1_DRAW_TEXT_OPTIONS_NONE.0;
        for &option in options {
            draw_options |= option as u32;
        }

        unsafe {
            let format = format.get_raw();
            self.rt().DrawText(text.as_ptr(),
                               text.len() as u32,
                               format,
                               &layout_rect.0,
                               foreground_brush.get_ptr(),
                               D2D1_DRAW_TEXT_OPTIONS(draw_options),
                               DWRITE_MEASURING_MODE_NATURAL);
        }
    }

    pub fn draw_text_layout<B: Brush>(&mut self,
                                      origin: &Point2F,
                                      layout: &TextLayout,
                                      brush: &B,
                                      options: &[DrawTextOption]) {
        let mut draw_options = D2D1_DRAW_TEXT_OPTIONS_NONE.0;
        for &option in options {
            draw_options |= option as u32;
        }

        unsafe {
            let layout = layout.get_raw();
            self.rt().DrawTextLayout(origin.0,
                                     layout,
                                     brush.get_ptr(),
                                     D2D1_DRAW_TEXT_OPTIONS(draw_options));
        }
    }
}

impl GetRaw for RenderTarget {
    type Raw = ID2D1RenderTarget;
    unsafe fn get_raw(&self) -> *mut ID2D1RenderTarget {
        self.ptr.raw_value()
    }
}

impl FromRaw for RenderTarget {
    type Raw = ID2D1RenderTarget;
    unsafe fn from_raw(raw: *mut ID2D1RenderTarget) -> Self {
        RenderTarget { ptr: ComPtr::attach(raw) }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum DrawTextOption {
    NoSnap = 1,
    Clip = 2,
    EnableColorFont = 4,
}