Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CairoExtensions.cs « MonoDevelop.Components « MonoDevelop.Ide « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3a2127083316535213c23e9be651e49e0e8a3d97 (plain)
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
//
// CairoExtensions.cs
//
// Author:
//   Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Reflection;
using System.Runtime.InteropServices;

using Gdk;
using Cairo;
using MonoDevelop.Core;

namespace MonoDevelop.Components
{
    [Flags]
    public enum CairoCorners
    {
        None = 0,
        TopLeft = 1,
        TopRight = 2,
        BottomLeft = 4,
        BottomRight = 8,
        All = 15
    }

    public static class CairoExtensions
    {
		internal const string LIBCAIRO = "libcairo-2.dll";
		public static Cairo.Rectangle ToCairoRect (this Gdk.Rectangle rect)
		{
			return new Cairo.Rectangle (rect.X, rect.Y, rect.Width, rect.Height);
		}

        public static Surface CreateSurfaceForPixbuf (Context cr, Pixbuf pixbuf)
        {
			Surface surface;
			using (var t = cr.GetTarget ()) {
				surface = t.CreateSimilar (t.Content, pixbuf.Width, pixbuf.Height);
			}
			using (Context surface_cr = new Context (surface)) {
				CairoHelper.SetSourcePixbuf (surface_cr, pixbuf, 0, 0);
				surface_cr.Paint ();
				surface_cr.Dispose ();
			}
            return surface;
        }

        public static Cairo.Color AlphaBlend (Cairo.Color ca, Cairo.Color cb, double alpha)
        {
            return new Cairo.Color (
                (1.0 - alpha) * ca.R + alpha * cb.R,
                (1.0 - alpha) * ca.G + alpha * cb.G,
                (1.0 - alpha) * ca.B + alpha * cb.B);
        }
		public static Gdk.Color CairoColorToGdkColor(Cairo.Color color)
        {
            return new Gdk.Color ((byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
        }

        public static Cairo.Color GdkColorToCairoColor(Gdk.Color color)
        {
            return GdkColorToCairoColor(color, 1.0);
        }

        public static Cairo.Color GdkColorToCairoColor(Gdk.Color color, double alpha)
        {
            return new Cairo.Color(
                (double)(color.Red >> 8) / 255.0,
                (double)(color.Green >> 8) / 255.0,
                (double)(color.Blue >> 8) / 255.0,
                alpha);
        }

        public static Cairo.Color RgbToColor (uint rgbColor)
        {
            return RgbaToColor ((rgbColor << 8) | 0x000000ff);
        }

        public static Cairo.Color RgbaToColor (uint rgbaColor)
        {
            return new Cairo.Color (
                (byte)(rgbaColor >> 24) / 255.0,
                (byte)(rgbaColor >> 16) / 255.0,
                (byte)(rgbaColor >> 8) / 255.0,
                (byte)(rgbaColor & 0x000000ff) / 255.0);
        }

		public static Cairo.Color InterpolateColors (Cairo.Color start, Cairo.Color end, float amount)
		{
			return new Cairo.Color (start.R + (end.R - start.R) * amount,
			                        start.G + (end.G - start.G) * amount,
			                        start.B + (end.B - start.B) * amount,
			                        start.A + (end.A - start.A) * amount);
		}

        public static bool ColorIsDark (Cairo.Color color)
        {
            double h, s, b;
            HsbFromColor (color, out h, out s, out b);
            return b < 0.5;
        }

        public static void HsbFromColor(Cairo.Color color, out double hue,
            out double saturation, out double brightness)
        {
            double min, max, delta;
            double red = color.R;
            double green = color.G;
            double blue = color.B;

            hue = 0;
            saturation = 0;
            brightness = 0;

            if(red > green) {
                max = Math.Max(red, blue);
                min = Math.Min(green, blue);
            } else {
                max = Math.Max(green, blue);
                min = Math.Min(red, blue);
            }

            brightness = (max + min) / 2;

            if(Math.Abs(max - min) < 0.0001) {
                hue = 0;
                saturation = 0;
            } else {
                saturation = brightness <= 0.5
                    ? (max - min) / (max + min)
                    : (max - min) / (2 - max - min);

                delta = max - min;

                if(red == max) {
                    hue = (green - blue) / delta;
                } else if(green == max) {
                    hue = 2 + (blue - red) / delta;
                } else if(blue == max) {
                    hue = 4 + (red - green) / delta;
                }

                hue *= 60;
                if(hue < 0) {
                    hue += 360;
                }
            }
        }

        private static double Modula(double number, double divisor)
        {
            return ((int)number % divisor) + (number - (int)number);
        }

        public static Cairo.Color ColorFromHsb(double hue, double saturation, double brightness)
        {
            int i;
            double [] hue_shift = { 0, 0, 0 };
            double [] color_shift = { 0, 0, 0 };
            double m1, m2, m3;

            m2 = brightness <= 0.5
                ? brightness * (1 + saturation)
                : brightness + saturation - brightness * saturation;

            m1 = 2 * brightness - m2;

            hue_shift[0] = hue + 120;
            hue_shift[1] = hue;
            hue_shift[2] = hue - 120;

            color_shift[0] = color_shift[1] = color_shift[2] = brightness;

            i = saturation == 0 ? 3 : 0;

            for(; i < 3; i++) {
                m3 = hue_shift[i];

                if(m3 > 360) {
                    m3 = Modula(m3, 360);
                } else if(m3 < 0) {
                    m3 = 360 - Modula(Math.Abs(m3), 360);
                }

                if(m3 < 60) {
                    color_shift[i] = m1 + (m2 - m1) * m3 / 60;
                } else if(m3 < 180) {
                    color_shift[i] = m2;
                } else if(m3 < 240) {
                    color_shift[i] = m1 + (m2 - m1) * (240 - m3) / 60;
                } else {
                    color_shift[i] = m1;
                }
            }

            return new Cairo.Color(color_shift[0], color_shift[1], color_shift[2]);
        }

        public static Cairo.Color ColorShade (Cairo.Color @base, double ratio)
        {
            double h, s, b;

            HsbFromColor (@base, out h, out s, out b);

            b = Math.Max (Math.Min (b * ratio, 1), 0);
            s = Math.Max (Math.Min (s * ratio, 1), 0);

            Cairo.Color color = ColorFromHsb (h, s, b);
            color.A = @base.A;
            return color;
        }

        public static Cairo.Color ColorAdjustBrightness(Cairo.Color @base, double br)
        {
            double h, s, b;
            HsbFromColor(@base, out h, out s, out b);
            b = Math.Max(Math.Min(br, 1), 0);
            return ColorFromHsb(h, s, b);
        }

        public static string ColorGetHex (Cairo.Color color, bool withAlpha = false)
        {
            if (withAlpha) {
                return String.Format("#{0:x2}{1:x2}{2:x2}{3:x2}", (byte)(color.R * 255), (byte)(color.G * 255),
                    (byte)(color.B * 255), (byte)(color.A * 255));
            } else {
                return String.Format("#{0:x2}{1:x2}{2:x2}", (byte)(color.R * 255), (byte)(color.G * 255),
                    (byte)(color.B * 255));
            }
        }

        public static void RoundedRectangle(this Cairo.Context cr, double x, double y, double w, double h, double r)
        {
            RoundedRectangle(cr, x, y, w, h, r, CairoCorners.All, false);
        }

		public static void RoundedRectangle(this Cairo.Context cr, double x, double y, double w, double h,
            double r, CairoCorners corners)
        {
            RoundedRectangle(cr, x, y, w, h, r, corners, false);
        }

		public static void RoundedRectangle(this Cairo.Context cr, double x, double y, double w, double h,
            double r, CairoCorners corners, bool topBottomFallsThrough)
        {
            if(topBottomFallsThrough && corners == CairoCorners.None) {
                cr.MoveTo(x, y - r);
                cr.LineTo(x, y + h + r);
                cr.MoveTo(x + w, y - r);
                cr.LineTo(x + w, y + h + r);
                return;
            } else if(r < 0.0001 || corners == CairoCorners.None) {
                cr.Rectangle(x, y, w, h);
                return;
            }

            if((corners & (CairoCorners.TopLeft | CairoCorners.TopRight)) == 0 && topBottomFallsThrough) {
                y -= r;
                h += r;
                cr.MoveTo(x + w, y);
            } else {
                if((corners & CairoCorners.TopLeft) != 0) {
                    cr.MoveTo(x + r, y);
                } else {
                    cr.MoveTo(x, y);
                }

                if((corners & CairoCorners.TopRight) != 0) {
                    cr.Arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
                } else {
                    cr.LineTo(x + w, y);
                }
            }

            if((corners & (CairoCorners.BottomLeft | CairoCorners.BottomRight)) == 0 && topBottomFallsThrough) {
                h += r;
                cr.LineTo(x + w, y + h);
                cr.MoveTo(x, y + h);
                cr.LineTo(x, y + r);
                cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
            } else {
                if((corners & CairoCorners.BottomRight) != 0) {
                    cr.Arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
                } else {
                    cr.LineTo(x + w, y + h);
                }

                if((corners & CairoCorners.BottomLeft) != 0) {
                    cr.Arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
                } else {
                    cr.LineTo(x, y + h);
                }

                if((corners & CairoCorners.TopLeft) != 0) {
                    cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
                } else {
                    cr.LineTo(x, y);
                }
            }
        }

		static void ShadowGradient (Cairo.Gradient lg, double strength)
		{
			lg.AddColorStop (0, new Cairo.Color (0, 0, 0, strength));
			lg.AddColorStop (1.0/6.0, new Cairo.Color (0, 0, 0, .85 * strength));
			lg.AddColorStop (2.0/6.0, new Cairo.Color (0, 0, 0, .54 * strength));
			lg.AddColorStop (3.0/6.0, new Cairo.Color (0, 0, 0, .24 * strength));
			lg.AddColorStop (4.0/6.0, new Cairo.Color (0, 0, 0, .07 * strength));
			lg.AddColorStop (5.0/6.0, new Cairo.Color (0, 0, 0, .01 * strength));
			lg.AddColorStop (1, new Cairo.Color (0, 0, 0, 0));
		}

		// VERY SLOW, only use on cached renders
		public static void RenderOuterShadow (this Cairo.Context self, Gdk.Rectangle area, int size, int rounding, double strength)
		{
			area.Inflate (-1, -1);
			size++;

			int doubleRounding = rounding * 2;
			// left side
			self.Rectangle (area.X - size, area.Y + rounding, size, area.Height - doubleRounding - 1);
			using (var lg = new LinearGradient (area.X, 0, area.X - size, 0)) {
				ShadowGradient (lg, strength);
				self.SetSource (lg);
				self.Fill ();
			}

			// right side
			self.Rectangle (area.Right, area.Y + rounding, size, area.Height - doubleRounding - 1);
			using (var lg = new LinearGradient (area.Right, 0, area.Right + size, 0)) {
				ShadowGradient (lg, strength);
				self.SetSource (lg);
				self.Fill ();
			}

			// top side
			self.Rectangle (area.X + rounding, area.Y - size, area.Width - doubleRounding - 1, size);
			using (var lg = new LinearGradient (0, area.Y, 0, area.Y - size)) {
				ShadowGradient (lg, strength);
				self.SetSource (lg);
				self.Fill ();
			}

			// bottom side
			self.Rectangle (area.X + rounding, area.Bottom, area.Width - doubleRounding - 1, size);
			using (var lg = new LinearGradient (0, area.Bottom, 0, area.Bottom + size)) {
				ShadowGradient (lg, strength);
				self.SetSource (lg);
				self.Fill ();
			}

			// top left corner
			self.Rectangle (area.X - size, area.Y - size, size + rounding, size + rounding);
			using (var rg = new RadialGradient (area.X + rounding, area.Y + rounding, rounding, area.X + rounding, area.Y + rounding, size + rounding)) {
				ShadowGradient (rg, strength);
				self.SetSource (rg);
				self.Fill ();
			}

			// top right corner
			self.Rectangle (area.Right - rounding, area.Y - size, size + rounding, size + rounding);
			using (var rg = new RadialGradient (area.Right - rounding, area.Y + rounding, rounding, area.Right - rounding, area.Y + rounding, size + rounding)) {
				ShadowGradient (rg, strength);
				self.SetSource (rg);
				self.Fill ();
			}

			// bottom left corner
			self.Rectangle (area.X - size, area.Bottom - rounding, size + rounding, size + rounding);
			using (var rg = new RadialGradient (area.X + rounding, area.Bottom - rounding, rounding, area.X + rounding, area.Bottom - rounding, size + rounding)) {
				ShadowGradient (rg, strength);
				self.SetSource (rg);
				self.Fill ();
			}

			// bottom right corner
			self.Rectangle (area.Right - rounding, area.Bottom - rounding, size + rounding, size + rounding);
			using (var rg = new RadialGradient (area.Right - rounding, area.Bottom - rounding, rounding, area.Right - rounding, area.Bottom - rounding, size + rounding)) {
				ShadowGradient (rg, strength);
				self.SetSource (rg);
				self.Fill ();
			}
		}

		[DllImport (LIBCAIRO, CallingConvention = CallingConvention.Cdecl)]
		static extern IntPtr cairo_pattern_set_extend(IntPtr pattern, CairoExtend extend);

		[DllImport (LIBCAIRO, CallingConvention=CallingConvention.Cdecl)]
		internal static extern IntPtr cairo_get_source (IntPtr cr);

		enum CairoExtend {
			CAIRO_EXTEND_NONE,
			CAIRO_EXTEND_REPEAT,
			CAIRO_EXTEND_REFLECT,
			CAIRO_EXTEND_PAD
		}

		public static void RenderTiled (this Cairo.Context self, Gtk.Widget target, Xwt.Drawing.Image source, Gdk.Rectangle area, Gdk.Rectangle clip, double opacity = 1)
		{
			var ctx = Xwt.Toolkit.CurrentEngine.WrapContext (target, self);
			ctx.Save ();
			ctx.Rectangle (clip.X, clip.Y, clip.Width, clip.Height);
			ctx.Clip ();
			ctx.Pattern = new Xwt.Drawing.ImagePattern (source);
			ctx.Rectangle (area.X, area.Y, area.Width, area.Height);
			ctx.Fill ();
			ctx.Restore ();
		}

        public static void DisposeContext (Cairo.Context cr)
        {
            cr.Dispose ();
        }

        private struct CairoInteropCall
        {
            public string Name;
            public MethodInfo ManagedMethod;
            public bool CallNative;

            public CairoInteropCall (string name)
            {
                Name = name;
                ManagedMethod = null;
                CallNative = false;
            }
        }

        private static bool CallCairoMethod (Cairo.Context cr, ref CairoInteropCall call)
        {
            if (call.ManagedMethod == null && !call.CallNative) {
                MemberInfo [] members = typeof (Cairo.Context).GetMember (call.Name, MemberTypes.Method,
                    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);

                if (members != null && members.Length > 0 && members[0] is MethodInfo) {
                    call.ManagedMethod = (MethodInfo)members[0];
                } else {
                    call.CallNative = true;
                }
            }

            if (call.ManagedMethod != null) {
                call.ManagedMethod.Invoke (cr, null);
                return true;
            }

            return false;
        }

        private static bool native_push_pop_exists = true;

		[DllImport (LIBCAIRO, CallingConvention = CallingConvention.Cdecl)]
        private static extern void cairo_push_group (IntPtr ptr);
        private static CairoInteropCall cairo_push_group_call = new CairoInteropCall ("PushGroup");

        public static void PushGroup (Cairo.Context cr)
        {
            if (!native_push_pop_exists) {
                return;
            }

            try {
                if (!CallCairoMethod (cr, ref cairo_push_group_call)) {
                    cairo_push_group (cr.Handle);
                }
            } catch {
                native_push_pop_exists = false;
            }
        }

		[DllImport (LIBCAIRO, CallingConvention = CallingConvention.Cdecl)]
        private static extern void cairo_pop_group_to_source (IntPtr ptr);
        private static CairoInteropCall cairo_pop_group_to_source_call = new CairoInteropCall ("PopGroupToSource");

        public static void PopGroupToSource (Cairo.Context cr)
		{
			if (!native_push_pop_exists) {
				return;
			}

			try {
				if (!CallCairoMethod (cr, ref cairo_pop_group_to_source_call)) {
					cairo_pop_group_to_source (cr.Handle);
				}
			} catch (EntryPointNotFoundException) {
				native_push_pop_exists = false;
			}
		}

		public static Cairo.Color ParseColor (string s, double alpha = 1)
		{
			if (s.StartsWith ("#"))
				s = s.Substring (1);
			if (s.Length == 3)
				s = "" + s[0]+s[0]+s[1]+s[1]+s[2]+s[2];
			double r = ((double) int.Parse (s.Substring (0,2), System.Globalization.NumberStyles.HexNumber)) / 255;
			double g = ((double) int.Parse (s.Substring (2,2), System.Globalization.NumberStyles.HexNumber)) / 255;
			double b = ((double) int.Parse (s.Substring (4,2), System.Globalization.NumberStyles.HexNumber)) / 255;
			return new Cairo.Color (r, g, b, alpha);
		}

		public static ImageSurface LoadImage (Assembly assembly, string resource)
		{
			byte[] buffer;
			using (var stream = assembly.GetManifestResourceStream (resource)) {
				buffer = new byte [stream.Length];
				stream.Read (buffer, 0, (int)stream.Length);
			}
/* This should work, but doesn't:
			using (var px = new Gdk.Pixbuf (buffer)) 
				return new ImageSurface (px.Pixels, Format.Argb32, px.Width, px.Height, px.Rowstride);*/

			// Workaround: loading from file name.
			var tmp = System.IO.Path.GetTempFileName ();
			System.IO.File.WriteAllBytes (tmp, buffer);
			var img = new ImageSurface (tmp);
			System.IO.File.Delete (tmp);
			return img;
		}

		public static Cairo.Color MultiplyAlpha (this Cairo.Color self, double alpha)
		{
			return new Cairo.Color (self.R, self.G, self.B, self.A * alpha);
		}

		public static void CachedDraw (this Cairo.Context self, ref SurfaceWrapper surface, Gdk.Point position, Gdk.Size size, 
		                               object parameters = null, float opacity = 1.0f, Action<Cairo.Context, float> draw = null, double? forceScale = null)
		{
			self.CachedDraw (ref surface, new Gdk.Rectangle (position, size), parameters, opacity, draw, forceScale);
		}

		public static void CachedDraw (this Cairo.Context self, ref SurfaceWrapper surface, Gdk.Rectangle region, 
		                               object parameters = null, float opacity = 1.0f, Action<Cairo.Context, float> draw = null, double? forceScale = null)
		{
			double displayScale = forceScale.HasValue ? forceScale.Value : QuartzSurface.GetRetinaScale (self);
			int targetWidth = (int) (region.Width * displayScale);
			int targetHeight = (int) (region.Height * displayScale);

			bool redraw = false;
			if (surface == null || surface.Width != targetWidth || surface.Height != targetHeight) {
				if (surface != null)
					surface.Dispose ();
				surface = new SurfaceWrapper (self, targetWidth, targetHeight);
				redraw = true;
			} else if ((surface.Data == null && parameters != null) || (surface.Data != null && !surface.Data.Equals (parameters))) {
				redraw = true;
			}


			if (redraw) {
				surface.Data = parameters;
				using (var context = new Cairo.Context (surface.Surface)) {
					context.Operator = Operator.Clear;
					context.Paint();
					context.Operator = Operator.Over;
					context.Save ();
					context.Scale (displayScale, displayScale);
					draw(context, 1.0f);
					context.Restore ();
				}
			}

			self.Save ();
			self.Translate (region.X, region.Y);
			self.Scale (1 / displayScale, 1 / displayScale);
			self.SetSourceSurface (surface.Surface, 0, 0);
			self.PaintWithAlpha (opacity);
			self.Restore ();
		}
	}

	public class SurfaceWrapper : IDisposable
	{
		public Cairo.Surface Surface { get; private set; }
		public int Width { get; private set; }
		public int Height { get; private set; }
		public object Data { get; set; }

		public SurfaceWrapper (Cairo.Context similar, int width, int height)
		{
			if (Platform.IsMac) {
				Surface = new QuartzSurface (Cairo.Format.ARGB32, width, height);
			} else if (Platform.IsWindows) {
				using (var target = similar.GetTarget ()) {
					Surface = target.CreateSimilar (Cairo.Content.ColorAlpha, width, height);
				}
			} else {
				Surface = new ImageSurface (Cairo.Format.ARGB32, width, height);
			}
			Width = width;
			Height = height;
		}

		public SurfaceWrapper (Cairo.Context similar, Gdk.Pixbuf source)
		{
			Cairo.Surface surface;
			// There is a bug in Cairo for OSX right now that prevents creating additional accellerated surfaces.
			if (Platform.IsMac) {
				surface = new QuartzSurface (Format.ARGB32, source.Width, source.Height);
			} else if (Platform.IsWindows) {
				using (var t = similar.GetTarget ()) {
					surface = t.CreateSimilar (Content.ColorAlpha, source.Width, source.Height);
				}
			} else {
				surface = new ImageSurface (Format.ARGB32, source.Width, source.Height);
			}

			using (Context context = new Context (surface)) {
				Gdk.CairoHelper.SetSourcePixbuf (context, source, 0, 0);
				context.Paint ();
			}

			Surface = surface;
			Width = source.Width;
			Height = source.Height;
		}

		public void Dispose ()
		{
			if (Surface != null) {
				((IDisposable)Surface).Dispose ();
			}
		}
	}

	public class QuartzSurface : Cairo.Surface
	{
		const string CoreGraphics = "/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/CoreGraphics";

		[DllImport (CairoExtensions.LIBCAIRO, CallingConvention = CallingConvention.Cdecl)]
		static extern IntPtr cairo_quartz_surface_create (Cairo.Format format, uint width, uint height);

		[DllImport (CairoExtensions.LIBCAIRO, CallingConvention = CallingConvention.Cdecl)]
		static extern IntPtr cairo_quartz_surface_get_cg_context (IntPtr surface);

		[DllImport (CairoExtensions.LIBCAIRO, CallingConvention = CallingConvention.Cdecl)]
		static extern IntPtr cairo_get_target (IntPtr context);

		[DllImport (CoreGraphics, EntryPoint="CGContextConvertRectToDeviceSpace", CallingConvention = CallingConvention.Cdecl)]
		static extern CGRect32 CGContextConvertRectToDeviceSpace32 (IntPtr contextRef, CGRect32 cgrect);

		[DllImport (CoreGraphics, EntryPoint="CGContextConvertRectToDeviceSpace", CallingConvention = CallingConvention.Cdecl)]
		static extern CGRect64 CGContextConvertRectToDeviceSpace64 (IntPtr contextRef, CGRect64 cgrect);

		public static double GetRetinaScale (Cairo.Context context)  {
			if (!Platform.IsMac)
				return 1;

			// Use C call to avoid dispose bug in cairo bindings for OSX
			var cgContext = cairo_quartz_surface_get_cg_context (cairo_get_target (context.Handle));

			if (IntPtr.Size == 8)
				return CGContextConvertRectToDeviceSpace64 (cgContext, CGRect64.Unit).X;

			return CGContextConvertRectToDeviceSpace32 (cgContext, CGRect32.Unit).X;
		}

		struct CGRect32
		{
			public CGRect32 (float x, float y, float width, float height)
			{
				this.X = x;
				this.Y = y;
				this.Width = width;
				this.Height = height;
			}

			public float X, Y, Width, Height;

			public static CGRect32 Unit {
				get {
					return new CGRect32 (1, 1, 1, 1);
				}
			}
		}

		struct CGRect64
		{
			public CGRect64 (double x, double y, double width, double height)
			{
				this.X = x;
				this.Y = y;
				this.Width = width;
				this.Height = height;
			}

			public double X, Y, Width, Height;

			public static CGRect64 Unit {
				get {
					return new CGRect64 (1, 1, 1, 1);
				}
			}
		}

		public QuartzSurface (Cairo.Format format, int width, int height)
			: base (cairo_quartz_surface_create (format, (uint)width, (uint)height), true)
		{
		}
	}
}