~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//
// WidgetBackend.cs
//
// Authors:
//       Carlos Alberto Cortez <calberto.cortez@gmail.com>
//       Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2011 Carlos Alberto Cortez
// Copyright (c) 2012 Xamarin, 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.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using SWM = System.Windows.Media;
using SWC = System.Windows.Controls; // When we need to resolve ambigituies.
using SW = System.Windows; // When we need to resolve ambigituies.

using Xwt.Backends;
using Xwt.Engine;
using Color = Xwt.Drawing.Color;

namespace Xwt.WPFBackend
{
	public abstract class WidgetBackend
		: Backend, IWidgetBackend, IWpfWidgetBackend
	{
		IWidgetEventSink eventSink;
		WidgetEvent enabledEvents;
		DragDropEffects currentDragEffect;
		FrameworkElement widget;

		class DragDropData
		{
			// Source
			public bool AutodetectDrag;
			public Rect DragRect;
			// Target
			public TransferDataType [] TargetTypes = new TransferDataType [0];
		}

		DragDropData dragDropInfo;

		const WidgetEvent dragDropEvents = WidgetEvent.DragDropCheck | WidgetEvent.DragDrop | WidgetEvent.DragOver | WidgetEvent.DragOverCheck;

		// Set to true when measuring a natural size for this widget
		bool gettingNaturalSize;

		// Set to true when calculating the default preferred size of the widget
		bool calculatingPreferredSize;

		void IWidgetBackend.Initialize (IWidgetEventSink eventSink)
		{
			this.eventSink = eventSink;
			Initialize ();
		}

		protected virtual void Initialize ()
		{
		}
		
		~WidgetBackend ()
		{
			Dispose (false);
		}
		
		public void Dispose ()
		{
			GC.SuppressFinalize (this);
			Dispose (true);
		}
		
		protected virtual void Dispose (bool disposing)
		{
		}

		public IWidgetEventSink EventSink {
			get { return eventSink; }
		}

		public object NativeWidget {
			get { return Widget; }
		}

		public new Widget Frontend {
			get { return (Widget) base.Frontend; }
		}

		public FrameworkElement Widget {
			get { return widget; }
			set
			{
				widget = value;
				if (widget is IWpfWidget)
					((IWpfWidget)widget).Backend = this;
				widget.InvalidateMeasure ();
			}
		}

		Color? customBackgroundColor;

		public virtual Color BackgroundColor {
			get {
				if (customBackgroundColor.HasValue)
					return customBackgroundColor.Value;

				return DataConverter.ToXwtColor (GetWidgetColor ());
			}
			set {
				customBackgroundColor = value;
				SetWidgetColor (value);
			}
		}

		SWM.Color GetWidgetColor ()
		{
			if (Widget is Control) {
				var control = (Control)Widget;
				if (control.Background != null)
					return ((SWM.SolidColorBrush)control.Background).Color;
			} else if (Widget is SWC.Panel) {
				var panel = (SWC.Panel)Widget;
				if (panel.Background != null)
					return ((SWM.SolidColorBrush)panel.Background).Color;
			}

			return SystemColors.ControlColor;
		}

		void SetWidgetColor (Color value)
		{
			if ((Widget is Control))
				((Control)Widget).Background = ResPool.GetSolidBrush (value);
			if ((Widget is System.Windows.Controls.Panel))
				((SWC.Panel)Widget).Background = ResPool.GetSolidBrush (value);
		}

		public bool UsingCustomBackgroundColor {
			get { return customBackgroundColor.HasValue; }
		}

		public virtual object Font {
			get { return GetWidgetFont (); }
			set {
				SetWidgetFont ((FontData)value);
			}
		}

		FontData GetWidgetFont ()
		{
			if (!(Widget is Control)) {
				double size = FontBackendHandler.GetPointsFromDeviceUnits (SystemFonts.MessageFontSize);

				return new FontData (SystemFonts.MessageFontFamily, size, Drawing.FontSizeUnit.Points) {
					Style = SystemFonts.MessageFontStyle,
					Weight = SystemFonts.MessageFontWeight
				};
			}

			return FontData.FromControl ((Control)Widget);
		}

		void SetWidgetFont (FontData font)
		{
			if (!(Widget is Control))
				return;

			var control = (Control)Widget;
			control.FontFamily = font.Family;
			control.FontSize = font.GetDeviceIndependentPixelSize (control);
			control.FontStyle = font.Style;
			control.FontWeight = font.Weight;
			control.FontStretch = font.Stretch;
		}

		public bool CanGetFocus {
			get { return Widget.Focusable; }
			set { Widget.Focusable = value; }
		}

		public bool HasFocus {
			get { return Widget.IsFocused; }
		}

		public void SetFocus ()
		{
			Widget.Focus ();
		}

		public virtual bool Sensitive {
			get { return Widget.IsEnabled; }
			set { Widget.IsEnabled = value; }
		}

		public Size Size {
			get { return new Size (Widget.ActualWidth, Widget.ActualHeight); }
		}

		public virtual bool Visible {
			get { return Widget.Visibility == Visibility.Visible; }
			set { Widget.Visibility = value ? Visibility.Visible : Visibility.Collapsed; }
		}

		public string TooltipText {
			get { return Widget.ToolTip.ToString (); }
			set { Widget.ToolTip = value; }
		}

		public static FrameworkElement GetFrameworkElement (IWidgetBackend backend)
		{
			return backend == null ? null : (FrameworkElement)backend.NativeWidget;
		}

		public Point ConvertToScreenCoordinates (Point widgetCoordinates)
		{
			double wratio = WidthPixelRatio;
			double hratio = HeightPixelRatio;

			var p = Widget.PointToScreen (new System.Windows.Point (
				widgetCoordinates.X / wratio, widgetCoordinates.Y / hratio));

			return new Point (p.X * wratio, p.Y * hratio);
		}

		SW.Size lastNaturalSize;

		void GetWidgetDesiredSize (double availableWidth, double availableHeight, out SW.Size minSize, out SW.Size naturalSize)
		{
			// Calculates the desired size of widget.

			if (!Widget.IsMeasureValid) {
				try {
					calculatingPreferredSize = true;
					gettingNaturalSize = true;
					Widget.Measure (new System.Windows.Size (availableWidth, availableHeight));
					lastNaturalSize = Widget.DesiredSize;
					gettingNaturalSize = false;

					Widget.InvalidateMeasure ();
					Widget.Measure (new System.Windows.Size (availableWidth, availableHeight));
				}
				finally {
					calculatingPreferredSize = false;
					gettingNaturalSize = false;
				}
			}
			minSize = Widget.DesiredSize;
			naturalSize = lastNaturalSize;
		}

		// The GetPreferred* methods are called when the corresponding OnGetPreferred* methods in the
		// XWT widget are not overriden, or if they are overriden and the new implementation calls
		// base.OnGetPreferred*. For this reason, we have to ensure that the widget's MeasureOverride
		// method doesn't end calling the frontend OnGetPreferred* methods. To avoid it we set
		// the calculatingPreferredSize flag to true, and we check this flag in MeasureOverride

		public virtual WidgetSize GetPreferredWidth ()
		{
			SW.Size minSize, natSize;
			Widget.InvalidateMeasure ();
			GetWidgetDesiredSize (Double.PositiveInfinity, Double.PositiveInfinity, out minSize, out natSize);
			return new WidgetSize (minSize.Width * WidthPixelRatio - Frontend.Margin.HorizontalSpacing, natSize.Width * WidthPixelRatio - Frontend.Margin.HorizontalSpacing);
		}

		public virtual WidgetSize GetPreferredHeight ()
		{
			SW.Size minSize, natSize;
			Widget.InvalidateMeasure ();
			GetWidgetDesiredSize (Double.PositiveInfinity, Double.PositiveInfinity, out minSize, out natSize);
			return new WidgetSize (minSize.Height * WidthPixelRatio - Frontend.Margin.VerticalSpacing, natSize.Height * HeightPixelRatio - Frontend.Margin.VerticalSpacing);
		}

		public virtual WidgetSize GetPreferredWidthForHeight (double height)
		{
			SW.Size minSize, natSize;
			Widget.InvalidateMeasure ();
			GetWidgetDesiredSize (Double.PositiveInfinity, height, out minSize, out natSize);
			return new WidgetSize (minSize.Width * WidthPixelRatio - Frontend.Margin.HorizontalSpacing, natSize.Width * WidthPixelRatio - Frontend.Margin.HorizontalSpacing);
		}

		public virtual WidgetSize GetPreferredHeightForWidth (double width)
		{
			SW.Size minSize, natSize;
			Widget.InvalidateMeasure ();
			GetWidgetDesiredSize (width, Double.PositiveInfinity, out minSize, out natSize);
			return new WidgetSize (minSize.Height * HeightPixelRatio - Frontend.Margin.VerticalSpacing, natSize.Height * HeightPixelRatio - Frontend.Margin.VerticalSpacing);
		}

		/// <summary>
		/// A default implementation of MeasureOverride to be used by all WPF widgets
		/// </summary>
		/// <param name="constraint">Size constraints</param>
		/// <param name="wpfMeasure">Size returned by the base MeasureOverride</param>
		/// <returns></returns>
		public System.Windows.Size MeasureOverride (System.Windows.Size constraint, System.Windows.Size wpfMeasure)
		{
			// Calculate the natural size, if that's what is being measured

			if (gettingNaturalSize) {
				var defNaturalSize = eventSink.GetDefaultNaturalSize ();

				// -2 means use the WPF default, -1 use the XWT default, any other other value is used as custom natural size
				var nw = DefaultNaturalWidth;
				if (nw == -1) {
					nw = defNaturalSize.Width;
					if (nw == 0)
						nw = wpfMeasure.Width;
					wpfMeasure.Width = nw;
				}
				else if (nw != -2)
					wpfMeasure.Width = nw;

				var nh = DefaultNaturalHeight;
				if (nh == -1) {
					nh = defNaturalSize.Height;
					if (nh == 0)
						nh = wpfMeasure.Height;
					wpfMeasure.Height = nh;
				}
				else if (nh != -2)
					wpfMeasure.Height = nh;
			}

			// If we are calculating the default preferred size of the widget we end here.
			// See note above about when GetPreferred* methods are called.
			if (calculatingPreferredSize)
				return wpfMeasure;

			Toolkit.Invoke (delegate
			{
				if (eventSink.GetSizeRequestMode () == SizeRequestMode.HeightForWidth) {
					// Calculate the preferred width through the frontend if there is an overriden OnGetPreferredWidth, but only do it
					// if we are not given a constraint. If there is a width constraint, we'll use that constraint value for calculating the height 
					if ((enabledEvents & WidgetEvent.PreferredWidthCheck) != 0 && constraint.Width == Double.PositiveInfinity) {
						var ws = eventSink.OnGetPreferredWidth ();
						wpfMeasure.Width = constraint.Width = gettingNaturalSize ? ws.NaturalSize : ws.MinSize;
					}

					// Now calculate the preferred height for that width, also using the override if available
					if ((enabledEvents & WidgetEvent.PreferredHeightForWidthCheck) != 0) {
						var ws = eventSink.OnGetPreferredHeightForWidth (constraint.Width);
						wpfMeasure.Height = gettingNaturalSize ? ws.NaturalSize : ws.MinSize;
					}
				}
				else {
					// Calculate the preferred height through the frontend, if there is an overriden OnGetPreferredHeight
					if ((enabledEvents & WidgetEvent.PreferredHeightCheck) != 0 && constraint.Height == Double.PositiveInfinity) {
						var ws = eventSink.OnGetPreferredHeight ();
						wpfMeasure.Height = constraint.Height = gettingNaturalSize ? ws.NaturalSize : ws.MinSize;
					}

					// Now calculate the preferred width for that height, also using the override if available
					if ((enabledEvents & WidgetEvent.PreferredWidthForHeightCheck) != 0) {
						var ws = eventSink.OnGetPreferredWidthForHeight (constraint.Height);
						wpfMeasure.Width = gettingNaturalSize ? ws.NaturalSize : ws.MinSize;
					}
				}
			});
			return wpfMeasure;
		}

		/// <summary>
		/// Natural width for the widget. It can be any arbitrary custom value, 
		/// or -1 if the XWT defined default has to be used, 
		/// or -2 if the WPF desired size has to be used (this is the default)
		/// </summary>
		protected virtual double DefaultNaturalWidth {
			get { return -2; }
		}

		/// <summary>
		/// Natural width for the widget. It can be any arbitrary custom value, 
		/// or -1 if the XWT defined default has to be used, 
		/// or -2 if the WPF desired size has to be used (this is the default)
		/// </summary>
		protected virtual double DefaultNaturalHeight
		{
			get { return -2; }
		}

		public void SetMinSize (double width, double height)
		{
			if (width == -1)
				Widget.ClearValue (FrameworkElement.MinWidthProperty);
			else
				Widget.MinWidth = width / WidthPixelRatio;

			if (height == -1)
				Widget.ClearValue (FrameworkElement.MinHeightProperty);
			else
				Widget.MinHeight = height / HeightPixelRatio;
		}

		public void SetNaturalSize (double width, double height)
		{
			if (width == -1)
				Widget.ClearValue (FrameworkElement.WidthProperty);
			else
				Widget.Width = width / WidthPixelRatio;

			if (height == -1)
				Widget.ClearValue (FrameworkElement.HeightProperty);
			else
				Widget.Height = height / HeightPixelRatio;
		}

		public void SetCursor (CursorType cursor)
		{
			if (cursor == CursorType.Arrow)
				Widget.Cursor = Cursors.Arrow;
			else if (cursor == CursorType.Crosshair)
				Widget.Cursor = Cursors.Cross;
			else if (cursor == CursorType.Hand)
				Widget.Cursor = Cursors.Hand;
			else if (cursor == CursorType.IBeam)
				Widget.Cursor = Cursors.IBeam;
			else if (cursor == CursorType.ResizeDown)
				Widget.Cursor = Cursors.SizeNS;
			else if (cursor == CursorType.ResizeUp)
				Widget.Cursor = Cursors.SizeNS;
			else if (cursor == CursorType.ResizeUpDown)
				Widget.Cursor = Cursors.SizeNS;
			else if (cursor == CursorType.ResizeLeft)
				Widget.Cursor = Cursors.SizeWE;
			else if (cursor == CursorType.ResizeRight)
				Widget.Cursor = Cursors.SizeWE;
			else if (cursor == CursorType.ResizeLeftRight)
				widget.Cursor = Cursors.SizeWE;
		}
		
		public virtual void UpdateLayout ()
		{
			Xwt.Widget frontend = (Xwt.Widget)Frontend;
			widget.Margin = new Thickness (frontend.Margin.Left, frontend.Margin.Top, frontend.Margin.Right, frontend.Margin.Bottom);
		}

		public override void EnableEvent (object eventId)
		{
			if (eventId is WidgetEvent) {
				var ev = (WidgetEvent)eventId;
				switch (ev) {
					case WidgetEvent.KeyPressed:
						Widget.KeyDown += WidgetKeyDownHandler;
						break;
					case WidgetEvent.KeyReleased:
						Widget.KeyDown += WidgetKeyUpHandler;
						break;
					case WidgetEvent.ButtonPressed:
						Widget.MouseDown += WidgetMouseDownHandler;
						break;
					case WidgetEvent.ButtonReleased:
						Widget.MouseUp += WidgetMouseUpHandler;
						break;
					case WidgetEvent.GotFocus:
						Widget.GotFocus += WidgetGotFocusHandler;
						break;
					case WidgetEvent.LostFocus:
						Widget.LostFocus += WidgetLostFocusHandler;
						break;
					case WidgetEvent.MouseEntered:
						Widget.MouseEnter += WidgetMouseEnteredHandler;
						break;
					case WidgetEvent.MouseExited:
						Widget.MouseLeave += WidgetMouseExitedHandler;
						break;
					case WidgetEvent.MouseMoved:
						Widget.MouseMove += WidgetMouseMoveHandler;
						break;
					case WidgetEvent.BoundsChanged:
						Widget.SizeChanged += WidgetOnSizeChanged;
						break;
					case WidgetEvent.MouseScrolled:
						Widget.MouseWheel += WidgetMouseWheelHandler;
						break;
				}

				if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) {
					// Enabling a drag&drop event for the first time
					Widget.DragOver += WidgetDragOverHandler;
					Widget.Drop += WidgetDropHandler;
					widget.DragLeave += WidgetDragLeaveHandler;
				}

				enabledEvents |= ev;
			}
		}

		public override void DisableEvent (object eventId)
		{
			if (eventId is WidgetEvent) {
				var ev = (WidgetEvent)eventId;
				switch (ev) {
					case WidgetEvent.KeyPressed:
						Widget.KeyDown -= WidgetKeyDownHandler;
						break;
					case WidgetEvent.KeyReleased:
						Widget.KeyUp -= WidgetKeyUpHandler;
						break;
					case WidgetEvent.ButtonPressed:
						Widget.MouseDown -= WidgetMouseDownHandler;
						break;
					case WidgetEvent.ButtonReleased:
						Widget.MouseUp -= WidgetMouseUpHandler;
						break;
					case WidgetEvent.MouseEntered:
						Widget.MouseEnter -= WidgetMouseEnteredHandler;
						break;
					case WidgetEvent.MouseExited:
						Widget.MouseLeave -= WidgetMouseExitedHandler;
						break;
					case WidgetEvent.MouseMoved:
						Widget.MouseMove -= WidgetMouseMoveHandler;
						break;
					case WidgetEvent.BoundsChanged:
						Widget.SizeChanged -= WidgetOnSizeChanged;
						break;
					case WidgetEvent.MouseScrolled:
						Widget.MouseWheel -= WidgetMouseWheelHandler;
						break;
				}

				enabledEvents &= ~ev;

				if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) {
					// All drag&drop events have been disabled
					Widget.DragOver -= WidgetDragOverHandler;
					Widget.Drop -= WidgetDropHandler;
					Widget.DragLeave -= WidgetDragLeaveHandler;
				}
			}
		}

		protected double WidthPixelRatio
		{
			get
			{
				PresentationSource source = PresentationSource.FromVisual (Widget);
				if (source == null)
					return 1;

				Matrix m = source.CompositionTarget.TransformToDevice;
				return m.M11;
			}
		}

		protected double HeightPixelRatio
		{
			get
			{
				PresentationSource source = PresentationSource.FromVisual (Widget);
				if (source == null)
					return 1;

				Matrix m = source.CompositionTarget.TransformToDevice;
				return m.M22;
			}
		}

		protected double DPI
		{
			get { return WidthPixelRatio * 96; }
		}

		void WidgetKeyDownHandler (object sender, System.Windows.Input.KeyEventArgs e)
		{
			KeyEventArgs args;
			if (MapToXwtKeyArgs (e, out args)) {
				Toolkit.Invoke (delegate {
					eventSink.OnKeyPressed (args);
				});
				if (args.Handled)
					e.Handled = true;
			}
		}

		void WidgetKeyUpHandler (object sender, System.Windows.Input.KeyEventArgs e)
		{
			KeyEventArgs args;
			if (MapToXwtKeyArgs (e, out args)) {
				Toolkit.Invoke (delegate {
					eventSink.OnKeyReleased (args);
				});
				if (args.Handled)
					e.Handled = true;
			}
		}

		bool MapToXwtKeyArgs (System.Windows.Input.KeyEventArgs e, out KeyEventArgs result)
		{
			result = null;

			var key = KeyboardUtil.TranslateToXwtKey (e.Key);
			if ((int)key == 0)
				return false;

			result = new KeyEventArgs (key, KeyboardUtil.GetModifiers (), e.IsRepeat, e.Timestamp);
			return true;
		}

		void WidgetMouseDownHandler (object o, MouseButtonEventArgs e)
		{
			var args = ToXwtButtonArgs (e);
			Toolkit.Invoke (delegate () {
				eventSink.OnButtonPressed (args);
			});
			if (args.Handled)
				e.Handled = true;
		}

		void WidgetMouseUpHandler (object o, MouseButtonEventArgs e)
		{
			var args = ToXwtButtonArgs (e);
			Toolkit.Invoke (delegate () {
				eventSink.OnButtonReleased (args);
			});
			if (args.Handled)
				e.Handled = true;
		}

		ButtonEventArgs ToXwtButtonArgs (MouseButtonEventArgs e)
		{
			var pos = e.GetPosition (Widget);
			return new ButtonEventArgs () {
				X = pos.X * WidthPixelRatio,
				Y = pos.Y * HeightPixelRatio,
				MultiplePress = e.ClickCount,
				Button = e.ChangedButton.ToXwtButton ()
			};
		}

		void WidgetGotFocusHandler (object o, RoutedEventArgs e)
		{
			Toolkit.Invoke (this.eventSink.OnGotFocus);
		}

		void WidgetLostFocusHandler (object o, RoutedEventArgs e)
		{
			Toolkit.Invoke (eventSink.OnLostFocus);
		}

		DragDropData DragDropInfo {
			get {
				if (dragDropInfo == null)
					dragDropInfo = new DragDropData ();

				return dragDropInfo;
			}
		}

		private static ImageAdorner Adorner;
		private static AdornerLayer AdornedLayer;
		private static System.Windows.Window AdornedWindow;

		private SW.Window GetParentWindow()
		{
			FrameworkElement current = Widget;
			while (current != null) {
				if (current is SW.Window)
					return (SW.Window)current;

				current = VisualTreeHelper.GetParent (current) as FrameworkElement;
			}

			return null;
		}

		public void DragStart (DragStartData data)
		{
			if (data.Data == null)
				throw new ArgumentNullException ("data");
			
			DataObject dataObj = data.Data.ToDataObject();

			if (data.ImageBackend != null) {
				AdornedWindow = GetParentWindow ();
				AdornedWindow.AllowDrop = true;

				var e = (UIElement)AdornedWindow.Content;

				Adorner = new ImageAdorner (e, data.ImageBackend);

				AdornedLayer = AdornerLayer.GetAdornerLayer (e);
				AdornedLayer.Add (Adorner);

				AdornedWindow.DragOver += AdornedWindowOnDragOver;
			}

			Widget.Dispatcher.BeginInvoke ((Action)(() => {
				var effect = DragDrop.DoDragDrop (Widget, dataObj, data.DragAction.ToWpfDropEffect ());

				OnDragFinished (this, new DragFinishedEventArgs (effect == DragDropEffects.Move));

				if (Adorner != null) {
					AdornedLayer.Remove (Adorner);
					AdornedLayer = null;
					Adorner = null;

					AdornedWindow.AllowDrop = false;
					AdornedWindow.DragOver -= AdornedWindowOnDragOver;
					AdornedWindow = null;
				}
			}));
		}

		private void AdornedWindowOnDragOver (object sender, System.Windows.DragEventArgs e)
		{
			WidgetDragOverHandler (sender, e);
		}

		public void SetDragTarget (TransferDataType [] types, DragDropAction dragAction)
		{
			DragDropInfo.TargetTypes = types == null ? new TransferDataType [0] : types;
			Widget.AllowDrop = true;
		}

		public void SetDragSource (TransferDataType [] types, DragDropAction dragAction)
		{
			if (DragDropInfo.AutodetectDrag)
				return; // Drag auto detect has been already activated.

			DragDropInfo.AutodetectDrag = true;
			Widget.MouseUp += WidgetMouseUpForDragHandler;
			Widget.MouseMove += WidgetMouseMoveForDragHandler;
		}

		private void SetupDragRect (MouseEventArgs e)
		{
			var width = SystemParameters.MinimumHorizontalDragDistance;
			var height = SystemParameters.MinimumVerticalDragDistance;
			var loc = e.GetPosition (Widget);
			DragDropInfo.DragRect = new Rect (loc.X - width / 2, loc.Y - height / 2, width, height);
		}

		void WidgetMouseUpForDragHandler (object o, EventArgs e)
		{
			DragDropInfo.DragRect = Rect.Empty;
		}

		void WidgetMouseMoveForDragHandler (object o, MouseEventArgs e)
		{
			if ((enabledEvents & WidgetEvent.DragStarted) == 0)
				return;
			if (e.LeftButton != MouseButtonState.Pressed)
				return;

			if (DragDropInfo.DragRect.IsEmpty)
				SetupDragRect (e);

			if (DragDropInfo.DragRect.Contains (e.GetPosition (Widget)))
				return;

			DragStartData dragData = null;
			Toolkit.Invoke (delegate {
				dragData = eventSink.OnDragStarted ();
			});

			if (dragData != null)
				DragStart (dragData);

			DragDropInfo.DragRect = Rect.Empty;
		}

		static DragDropAction DetectDragAction (DragDropKeyStates keys)
		{
			if ((keys & DragDropKeyStates.ControlKey) == DragDropKeyStates.ControlKey) {
				if ((keys & DragDropKeyStates.ShiftKey) == DragDropKeyStates.ShiftKey)
					return DragDropAction.Link;
				else
					return DragDropAction.Copy;
			}

			return DragDropAction.Move;
		}

		static void FillDataStore (TransferDataStore store, IDataObject data, TransferDataType [] types)
		{
			foreach (var type in types) {
				string format = type.ToWpfDataFormat ();
				if (!data.GetDataPresent (format)) {
					// This is a workaround to support type names which don't include the assembly name.
					// It eases integration with Windows DND.
					format = NormalizeTypeName (format);
					if (!data.GetDataPresent (format))
						continue;
				}

				var value = data.GetData (format);
				if (type == TransferDataType.Text)
					store.AddText ((string)value);
				else if (type == TransferDataType.Uri) {
					var uris = ((string [])value).Select (f => new Uri (f)).ToArray ();
					store.AddUris (uris);
				} else if (value is byte[])
					store.AddValue (type, (byte[]) value);
				else
					store.AddValue (type, value);
			}
		}

		static string NormalizeTypeName (string dataType)
		{
			// If the string is a fully qualified type name, strip the assembly name
			int i = dataType.IndexOf (',');
			if (i == -1)
				return dataType;
			string asmName = dataType.Substring (i + 1).Trim ();
			try {
				new System.Reflection.AssemblyName (asmName);
			}
			catch {
				return dataType;
			}
			return dataType.Substring (0, i).Trim ();
		}

		protected virtual void OnDragFinished (object sender, DragFinishedEventArgs e)
		{
			Toolkit.Invoke (delegate {
				this.eventSink.OnDragFinished (e);
			});
		}

		protected virtual void OnDragOver (object sender, DragOverEventArgs e)
		{
			Toolkit.Invoke (delegate {
				eventSink.OnDragOver (e);
			});
		}

		protected virtual void OnDragLeave (object sender, EventArgs e)
		{
			Toolkit.Invoke (delegate {
				eventSink.OnDragLeave (e);
			});
		}

		void WidgetDragOverHandler (object sender, System.Windows.DragEventArgs e)
		{
			var types = e.Data.GetFormats ().Select (t => t.ToXwtTransferType ()).ToArray ();
			var pos = e.GetPosition (Widget).ToXwtPoint ();
			var proposedAction = DetectDragAction (e.KeyStates);

			e.Handled = true; // Prevent default handlers from being used.

			if (Adorner != null) {
				var w = GetParentWindow ();
				var v = (UIElement)w.Content;

				if (w != AdornedWindow) {
					AdornedLayer.Remove (Adorner);

					AdornedWindow.AllowDrop = false;
					AdornedWindow.DragOver -= AdornedWindowOnDragOver;

					AdornedWindow = w;
					AdornedWindow.AllowDrop = true;
					AdornedWindow.DragOver += AdornedWindowOnDragOver;

					AdornedLayer = AdornerLayer.GetAdornerLayer (v);
					AdornedLayer.Add (Adorner);
				}

				Adorner.Offset = e.GetPosition (v);
			}

			if ((enabledEvents & WidgetEvent.DragOverCheck) > 0) {
				var checkArgs = new DragOverCheckEventArgs (pos, types, proposedAction);
				Toolkit.Invoke (delegate {
					eventSink.OnDragOverCheck (checkArgs);
				});
				if (checkArgs.AllowedAction == DragDropAction.None) {
					e.Effects = currentDragEffect = DragDropEffects.None;
					return;
				}
				if (checkArgs.AllowedAction != DragDropAction.Default) {
					e.Effects = currentDragEffect = checkArgs.AllowedAction.ToWpfDropEffect ();
					return;
				}
			}

			if ((enabledEvents & WidgetEvent.DragOver) > 0) {
				var store = new TransferDataStore ();
				FillDataStore (store, e.Data, DragDropInfo.TargetTypes);

				var args = new DragOverEventArgs (pos, store, proposedAction);
				OnDragOver (sender, args);
				if (args.AllowedAction == DragDropAction.None) {
					e.Effects = currentDragEffect = DragDropEffects.None;
					return;
				}
				if (args.AllowedAction != DragDropAction.Default) {
					e.Effects = currentDragEffect = args.AllowedAction.ToWpfDropEffect ();
					return;
				}
			}

			e.Effects = currentDragEffect = proposedAction.ToWpfDropEffect ();
		}

		void WidgetDropHandler (object sender, System.Windows.DragEventArgs e)
		{
			WidgetDragLeaveHandler (sender, e);

			var types = e.Data.GetFormats ().Select (t => t.ToXwtTransferType ()).ToArray ();
			var pos = e.GetPosition (Widget).ToXwtPoint ();
			var actualEffect = currentDragEffect;

			e.Handled = true; // Prevent default handlers from being used.
			e.Effects = DragDropEffects.None;

			if ((enabledEvents & WidgetEvent.DragDropCheck) > 0) {
				var checkArgs = new DragCheckEventArgs (pos, types, actualEffect.ToXwtDropAction ());
				bool res = Toolkit.Invoke (delegate {
					eventSink.OnDragDropCheck (checkArgs);
				});

				if (checkArgs.Result == DragDropResult.Canceled || !res) {
					e.Effects = DragDropEffects.None;
					return;
				}
			}

			if ((enabledEvents & WidgetEvent.DragDrop) > 0) {
				var store = new TransferDataStore ();
				FillDataStore (store, e.Data, DragDropInfo.TargetTypes);

				var args = new DragEventArgs (pos, store, actualEffect.ToXwtDropAction ());
				Toolkit.Invoke (delegate {
					eventSink.OnDragDrop (args);
				});

				if (args.Success)
					e.Effects = actualEffect;
			}
		}

		void WidgetDragLeaveHandler (object sender, System.Windows.DragEventArgs e)
		{
			OnDragLeave (sender, e);
		}

		private void WidgetMouseEnteredHandler (object sender, MouseEventArgs e)
		{
			Toolkit.Invoke (eventSink.OnMouseEntered);
		}

		private void WidgetMouseExitedHandler (object sender, MouseEventArgs e)
		{
			Toolkit.Invoke (eventSink.OnMouseExited);
		}

		private void WidgetMouseMoveHandler (object sender, MouseEventArgs e)
		{
			Toolkit.Invoke (() => {
				var p = e.GetPosition (Widget);
				eventSink.OnMouseMoved (new MouseMovedEventArgs (
					e.Timestamp, p.X * WidthPixelRatio, p.Y * HeightPixelRatio));
			});
		}

		private int mouseScrollCumulation = 0;

		private void WidgetMouseWheelHandler (object sender, MouseWheelEventArgs e)
		{
			mouseScrollCumulation += e.Delta;
			int jumps = mouseScrollCumulation / 120;
			mouseScrollCumulation %= 120;
			var p = e.GetPosition(Widget);
			Toolkit.Invoke (delegate {
				for (int i = 0; i < jumps; i++) {
					eventSink.OnMouseScrolled(new MouseScrolledEventArgs(
						e.Timestamp, p.X * WidthPixelRatio, p.Y * HeightPixelRatio, ScrollDirection.Up));
				}
				for (int i = 0; i > jumps; i--) {
					eventSink.OnMouseScrolled(new MouseScrolledEventArgs(
						e.Timestamp, p.X * WidthPixelRatio, p.Y * HeightPixelRatio, ScrollDirection.Down));
				}
			});
		}

		private void WidgetOnSizeChanged (object sender, SizeChangedEventArgs e)
		{
			if (Widget.IsVisible)
				Toolkit.Invoke (this.eventSink.OnBoundsChanged);
		}
	}

	public interface IWpfWidgetBackend
	{
		FrameworkElement Widget { get; }
	}

	public interface IWpfWidget
	{
		WidgetBackend Backend { get; set; }
	}
}