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

ViewBackend.cs « Xwt.Mac « Xwt.XamMac - github.com/mono/xwt.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f98488816f82e057f3d10ab2c2613b63964b5088 (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
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
// 
// ViewBackend.cs
//  
// Author:
//       Lluis Sanchez <lluis@xamarin.com>
// 
// Copyright (c) 2011 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.Generic;
using System.Linq;
using System.Xml;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;


namespace Xwt.Mac
{
	public abstract class ViewBackend<T,S>: ViewBackend where T:NSView where S:IWidgetEventSink
	{
		public new S EventSink {
			get { return (S) base.EventSink; }
		}
		
		public new T Widget {
			get { return (T) base.Widget; }
		}
	}

	public abstract class ViewBackend: IWidgetBackend
	{
		Widget frontend;
		IWidgetEventSink eventSink;
		IViewObject viewObject;
		WidgetEvent currentEvents;
		bool autosize;
		Size lastFittingSize;
		bool sizeCalcPending = true;
		bool sensitive = true;
		bool canGetFocus = true;
		Xwt.Drawing.Color backgroundColor;

		void IBackend.InitializeBackend (object frontend, ApplicationContext context)
		{
			ApplicationContext = context;
			this.frontend = (Widget) frontend;
		}
		
		void IWidgetBackend.Initialize (IWidgetEventSink sink)
		{
			eventSink = (IWidgetEventSink) sink;
			Initialize ();
			ResetFittingSize ();
			canGetFocus = Widget.AcceptsFirstResponder ();
		}

		/// <summary>
		/// To be called when the widget is a root and is not inside a Xwt window. For example, when it is in a popover or a tooltip
		/// In that case, the widget has to listen to the change event of the children and resize itself
		/// </summary>
		public void SetAutosizeMode (bool autosize)
		{
			this.autosize = autosize;
			if (autosize)
				AutoUpdateSize ();
		}

		
		public virtual void Initialize ()
		{
		}
		
		public IWidgetEventSink EventSink {
			get { return eventSink; }
		}
		
		public Widget Frontend {
			get {
				return this.frontend;
			}
		}
		
		public ApplicationContext ApplicationContext {
			get;
			private set;
		}
		
		public object NativeWidget {
			get {
				return Widget;
			}
		}
		
		public NSView Widget {
			get { return (NSView) ViewObject.View; }
		}
		
		public IViewObject ViewObject {
			get { return viewObject; }
			set {
				viewObject = value;
				if (viewObject.Backend == null)
					viewObject.Backend = this;
			}
		}

		public string Name { get; set; }
		
		public bool Visible {
			get { return !Widget.Hidden; }
			set { Widget.Hidden = !value; }
		}

		public double Opacity {
			get { return Widget.AlphaValue; }
			set { Widget.AlphaValue = (float)value; }
		}
		
		public virtual bool Sensitive {
			get { return sensitive; }
			set {
				sensitive = value;
				UpdateSensitiveStatus (Widget, sensitive && ParentIsSensitive (Widget));
			}
		}

		static bool ParentIsSensitive (NSView view)
		{
			var parent = view.Superview;
			if ((parent as NSControl)?.Enabled == false)
				return false;
			if (parent == null) {
				var wb = view.Window as WindowBackend;
				return wb == null || wb.Sensitive;
			}
			if ((parent as IViewObject)?.Backend.Sensitive == false)
				return false;
			return ParentIsSensitive (parent);
		}

		internal void UpdateSensitiveStatus (NSView view, bool parentIsSensitive)
		{
			if (view is NSControl)
				((NSControl)view).Enabled = parentIsSensitive && sensitive;

			foreach (var s in view.Subviews) {
				if ((s is IViewObject) && (((IViewObject)s).Backend != null))
					((IViewObject)s).Backend.UpdateSensitiveStatus (s, parentIsSensitive);
				else
					UpdateSensitiveStatus (s, sensitive && parentIsSensitive);
			}
		}

		public virtual bool CanGetFocus {
			get { return canGetFocus; }
			set {
				canGetFocus = value;
				if (!Widget.AcceptsFirstResponder ())
					canGetFocus = false;
			}
		}
		
		public virtual bool HasFocus {
			get {
				return Widget.Window != null && Widget.Window.FirstResponder == Widget;
			}
		}
		
		public virtual void SetFocus ()
		{
			if (Widget.Window != null && CanGetFocus)
				Widget.Window.MakeFirstResponder (Widget);
		}
		
		public string TooltipText {
			get {
				return Widget.ToolTip;
			}
			set {
				if (value != null)
					Widget.ToolTip = value;
				else if (Widget.ToolTip != null) {
					Widget.ToolTip = string.Empty;
					Widget.RemoveAllToolTips ();
				}
			}
		}
		
		public void NotifyPreferredSizeChanged ()
		{
			EventSink.OnPreferredSizeChanged ();
		}

		internal NSCursor Cursor { get; private set; }

		public void SetCursor (CursorType cursor)
		{
			if (cursor == CursorType.Arrow)
				Cursor = NSCursor.ArrowCursor;
			else if (cursor == CursorType.Crosshair)
				Cursor = NSCursor.CrosshairCursor;
			else if (cursor == CursorType.Hand)
				Cursor = NSCursor.OpenHandCursor;
			else if (cursor == CursorType.Hand2)
				Cursor = NSCursor.PointingHandCursor;
			else if (cursor == CursorType.IBeam)
				Cursor = NSCursor.IBeamCursor;
			else if (cursor == CursorType.ResizeDown)
				Cursor = NSCursor.ResizeDownCursor;
			else if (cursor == CursorType.ResizeUp)
				Cursor = NSCursor.ResizeUpCursor;
			else if (cursor == CursorType.ResizeLeft)
				Cursor = NSCursor.ResizeLeftCursor;
			else if (cursor == CursorType.ResizeRight)
				Cursor = NSCursor.ResizeRightCursor;
			else if (cursor == CursorType.ResizeLeftRight)
				Cursor = NSCursor.ResizeLeftRightCursor;
			else if (cursor == CursorType.ResizeUpDown)
				Cursor = NSCursor.ResizeUpDownCursor;
			else if (cursor == CursorType.Invisible)
				// TODO: load transparent cursor
				Cursor = NSCursor.ArrowCursor;
			else if (cursor == CursorType.Move)
				Cursor = NSCursor.ClosedHandCursor;
			else if (cursor == CursorType.DragCopy)
				Cursor = NSCursor.DragCopyCursor;
			else if (cursor == CursorType.NotAllowed)
				Cursor = NSCursor.OperationNotAllowedCursor;
			else
				Cursor = NSCursor.ArrowCursor;
			// immediately invalidate cursor rects, if the view is visible
			ViewObject?.View?.Window?.InvalidateCursorRectsForView(ViewObject.View);
		}
		
		~ViewBackend ()
		{
			Dispose (false);
		}
		
		public void Dispose ()
		{
			GC.SuppressFinalize (this);
			Dispose (true);
		}
		
		protected virtual void Dispose (bool disposing)
		{
		}
		
		Size IWidgetBackend.Size {
			get { return new Size (Widget.WidgetWidth (), Widget.WidgetHeight ()); }
		}
		
		public static NSView GetWidget (IWidgetBackend w)
		{
			return ((ViewBackend)w).Widget;
		}

		public static NSView GetWidget (Widget w)
		{
			return GetWidget ((IWidgetBackend)Toolkit.GetBackend (w));
		}

		public static NSView GetWidgetWithPlacement (IWidgetBackend childBackend)
		{
			var backend = (ViewBackend)childBackend;
			var child = backend.Widget;
			var wrapper = child.Superview as WidgetPlacementWrapper;
			if (wrapper != null)
				return wrapper;

			if (!NeedsAlignmentWrapper (backend.Frontend))
				return child;

			wrapper = new WidgetPlacementWrapper ();
			wrapper.SetChild (child, backend.Frontend);
			return wrapper;
		}

		public static NSView SetChildPlacement (IWidgetBackend childBackend)
		{
			var backend = (ViewBackend)childBackend;
			var child = backend.Widget;
			var wrapper = child.Superview as WidgetPlacementWrapper;
			var fw = backend.Frontend;

			if (!NeedsAlignmentWrapper (fw)) {
				if (wrapper != null) {
					var parent = wrapper.Superview;
					child.RemoveFromSuperview ();
					ReplaceSubview (wrapper, child);
				}
				return child;
			}

			if (wrapper == null) {
				wrapper = new WidgetPlacementWrapper ();
				var f = child.Frame;
				ReplaceSubview (child, wrapper);
				wrapper.SetChild (child, backend.Frontend);
				wrapper.Frame = f;
			} else
				wrapper.UpdateChildPlacement ();
			return wrapper;
		}

		public static void RemoveChildPlacement (NSView w)
		{
			if (w == null)
				return;
			if (w is WidgetPlacementWrapper) {
				var wp = (WidgetPlacementWrapper)w;
				wp.Subviews [0].RemoveFromSuperview ();
			}
		}
		
		static bool NeedsAlignmentWrapper (Widget fw)
		{
			return fw.HorizontalPlacement != WidgetPlacement.Fill || fw.VerticalPlacement != WidgetPlacement.Fill || fw.Margin.VerticalSpacing != 0 || fw.Margin.HorizontalSpacing != 0;
		}

		public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
		{
			SetChildPlacement (childBackend);
		}

		public static void ReplaceSubview (NSView oldChild, NSView newChild)
		{
			var vo = oldChild as IViewObject;
			if (vo != null && vo.Backend.Frontend.GetInternalParent () != null) {
				var ba = vo.Backend.Frontend.GetInternalParent ().GetBackend () as ViewBackend;
				if (ba != null) {
					ba.ReplaceChild (oldChild, newChild);
					return;
				}
			}
			var f = oldChild.Frame;
			oldChild.Superview.ReplaceSubviewWith (oldChild, newChild);
			newChild.Frame = f;
		}

		public virtual void ReplaceChild (NSView oldChild, NSView newChild)
		{
			var f = oldChild.Frame;
			oldChild.Superview.ReplaceSubviewWith (oldChild, newChild);
			newChild.Frame = f;
		}

		FontData customFont;

		public virtual object Font {
			get {
				if (customFont != null)
					return customFont;

				NSFont font = null;
				var widget = Widget;
				if (widget is CustomAlignedContainer)
					widget = ((CustomAlignedContainer)widget).Child;
				if (widget is NSControl)
					font = ((NSControl)(object)widget).Font;
				else if (widget is NSText)
					font = ((NSText)(object)widget).Font;
				else
					font = NSFont.ControlContentFontOfSize (NSFont.SystemFontSize);
				return customFont = FontData.FromFont (font);
			}
			set {
				customFont = (FontData) value;
				var widget = Widget;
				if (widget is CustomAlignedContainer)
					widget = ((CustomAlignedContainer)widget).Child;
				if (widget is NSControl)
					((NSControl)(object)widget).Font = customFont.Font;
				if (widget is NSText)
					((NSText)(object)widget).Font = customFont.Font;
				ResetFittingSize ();
			}
		}
		
		public virtual Xwt.Drawing.Color BackgroundColor {
			get {
				return this.backgroundColor;
			}
			set {
				this.backgroundColor = value;
				if (Widget.Layer == null)
					Widget.WantsLayer = true;
				Widget.Layer.BackgroundColor = value.ToCGColor ();
			}
		}
		
		#region IWidgetBackend implementation

		public Point ConvertToParentCoordinates (Point widgetCoordinates)
		{
			var location =  Widget.WidgetLocation ();
			location.X += widgetCoordinates.X;
			location.Y += widgetCoordinates.Y;
			return location;
		}

		public Point ConvertToWindowCoordinates (Point widgetCoordinates)
		{
			return Widget.ConvertPointToView (widgetCoordinates.ToCGPoint (), null).ToXwtPoint ();
		}

		public Point ConvertToScreenCoordinates (Point widgetCoordinates)
		{
			var lo = Widget.ConvertPointToView (new CGPoint ((nfloat)widgetCoordinates.X, (nfloat)widgetCoordinates.Y), null);
			lo = Widget.Window.ConvertRectToScreen (new CGRect (lo, CGSize.Empty)).Location;
			return MacDesktopBackend.ToDesktopRect (new CGRect (lo.X, lo.Y, 0, Widget.IsFlipped ? 0 : Widget.Frame.Height)).Location;
		}
		
		protected virtual Size GetNaturalSize ()
		{
			if (sizeCalcPending) {
				sizeCalcPending = false;
				var f = Widget.Frame;
				SizeToFit ();
				lastFittingSize = new Size (Widget.WidgetWidth (), Widget.WidgetHeight ());
				Widget.Frame = f;
			}
			return lastFittingSize;
		}

		public virtual Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
		{
			return GetNaturalSize ();
		}
		
		protected double minWidth = -1, minHeight = -1;
		
		public void SetMinSize (double width, double height)
		{
			minWidth = width;
			minHeight = height;
		}

		protected void ResetFittingSize ()
		{
			sizeCalcPending = true;
		}

		public void SizeToFit ()
		{
			OnSizeToFit ();
//			if (minWidth != -1 && Widget.Frame.Width < minWidth || minHeight != -1 && Widget.Frame.Height < minHeight)
//				Widget.SetFrameSize (new SizeF (Math.Max (Widget.Frame.Width, (float)minWidth), Math.Max (Widget.Frame.Height, (float)minHeight)));
		}
		
		protected virtual Size CalcFittingSize ()
		{
			return Size.Zero;
		}

		static readonly Selector sizeToFitSel = new Selector ("sizeToFit");

		protected virtual void OnSizeToFit ()
		{
			if (Widget.RespondsToSelector (sizeToFitSel)) {
				Messaging.void_objc_msgSend (Widget.Handle, sizeToFitSel.Handle);
			} else {
				var s = CalcFittingSize ();
				if (!s.IsZero)
					Widget.SetFrameSize (new CGSize ((nfloat)s.Width, (nfloat)s.Height));
			}
		}
		
		public void SetSizeRequest (double width, double height)
		{
			// Nothing to do
		}
		
		public virtual void UpdateLayout ()
		{
			if (autosize)
				AutoUpdateSize ();
		}

		void AutoUpdateSize ()
		{	var s = Frontend.Surface.GetPreferredSize ();
			Widget.SetFrameSize (new CGSize ((nfloat)s.Width, (nfloat)s.Height));
		}
		
		public virtual void EnableEvent (object eventId)
		{
			if (eventId is WidgetEvent) {
				WidgetEvent ev = (WidgetEvent) eventId;
				currentEvents |= ev;
				switch (ev) {
				case WidgetEvent.GotFocus:
				case WidgetEvent.LostFocus:
					SetupFocusEvents (Widget.GetType ());
					break;
				}
			}
		}
		
		public virtual void DisableEvent (object eventId)
		{
			if (eventId is WidgetEvent) {
				WidgetEvent ev = (WidgetEvent) eventId;
				currentEvents &= ~ev;
			}
		}
		
		static Selector draggingEnteredSel = new Selector ("draggingEntered:");
		static Selector draggingUpdatedSel = new Selector ("draggingUpdated:");
		static Selector draggingExitedSel = new Selector ("draggingExited:");
		static Selector prepareForDragOperationSel = new Selector ("prepareForDragOperation:");
		static Selector performDragOperationSel = new Selector ("performDragOperation:");
		static Selector concludeDragOperationSel = new Selector ("concludeDragOperation:");
		static Selector becomeFirstResponderSel = new Selector ("becomeFirstResponder");
		static Selector resignFirstResponderSel = new Selector ("resignFirstResponder");

		static DelegateIntPtrIntPtrIntPtrNSDragOperation draggingEnteredDelegate = new DelegateIntPtrIntPtrIntPtrNSDragOperation(DraggingEntered);
		static DelegateIntPtrIntPtrIntPtrNSDragOperation draggingUpdatedDelegate = new DelegateIntPtrIntPtrIntPtrNSDragOperation(DraggingUpdated);
		static DelegateIntPtrIntPtrIntPtrVoid draggingExitedDelegate = new DelegateIntPtrIntPtrIntPtrVoid(DraggingExited);
		static DelegateIntPtrIntPtrIntPtrBool prepareForDragOperationDelegate = new DelegateIntPtrIntPtrIntPtrBool(PrepareForDragOperation);
		static DelegateIntPtrIntPtrIntPtrBool performDragOperationDelegate = new DelegateIntPtrIntPtrIntPtrBool(PerformDragOperation);
		static DelegateIntPtrIntPtrIntPtrVoid concludeDragOperationDelegate = new DelegateIntPtrIntPtrIntPtrVoid(ConcludeDragOperation);

		static HashSet<Type> typesConfiguredForDragDrop = new HashSet<Type> ();
		static HashSet<Type> typesConfiguredForFocusEvents = new HashSet<Type> ();

		static void SetupForDragDrop (Type type)
		{
			lock (typesConfiguredForDragDrop) {
				if (typesConfiguredForDragDrop.Add (type)) {
					Class c = new Class (type);
					c.AddMethod (draggingEnteredSel.Handle, draggingEnteredDelegate, "i@:@");
					c.AddMethod (draggingUpdatedSel.Handle, draggingUpdatedDelegate, "i@:@");
					c.AddMethod (draggingExitedSel.Handle, draggingExitedDelegate, "v@:@");
					c.AddMethod (prepareForDragOperationSel.Handle, prepareForDragOperationDelegate, "B@:@");
					c.AddMethod (performDragOperationSel.Handle, performDragOperationDelegate, "B@:@");
					c.AddMethod (concludeDragOperationSel.Handle, concludeDragOperationDelegate, "v@:@");
				}
			}
		}

		delegate bool DelegateIntPtrIntPtrBool(IntPtr p1, IntPtr p2);
		delegate NSDragOperation DelegateIntPtrIntPtrIntPtrNSDragOperation(IntPtr p1, IntPtr p2, IntPtr p3);
		delegate void DelegateIntPtrIntPtrIntPtrVoid(IntPtr p1, IntPtr p2, IntPtr p3);
		delegate bool DelegateIntPtrIntPtrIntPtrBool(IntPtr p1, IntPtr p2, IntPtr p3);

		static DelegateIntPtrIntPtrBool onBecomeFirstResponderDelegate = new DelegateIntPtrIntPtrBool(OnBecomeFirstResponder);
		static DelegateIntPtrIntPtrBool onResignFirstResponderDelegate = new DelegateIntPtrIntPtrBool(OnResignFirstResponder);

		static void SetupFocusEvents (Type type)
		{
			lock (typesConfiguredForFocusEvents) {
				if (typesConfiguredForFocusEvents.Add (type)) {
					Class c = new Class (type);
					c.AddMethod (becomeFirstResponderSel.Handle, onBecomeFirstResponderDelegate, "B@:");
					c.AddMethod (resignFirstResponderSel.Handle, onResignFirstResponderDelegate, "B@:");
				}
			}
		}
		
		public void DragStart (DragStartData sdata)
		{
			var lo = Widget.ConvertPointToBase (new CGPoint (Widget.Bounds.X, Widget.Bounds.Y));
			lo = Widget.Window.ConvertBaseToScreen (lo);
			var ml = NSEvent.CurrentMouseLocation;
			var pb = NSPasteboard.FromName (NSPasteboard.NSDragPasteboardName);
			if (pb == null)
				throw new InvalidOperationException ("Could not get pasteboard");
			if (sdata.Data == null)
				throw new ArgumentNullException ("data");
			InitPasteboard (pb, sdata.Data);
			var img = (NSImage)sdata.ImageBackend;
			var pos = new CGPoint (ml.X - lo.X - (float)sdata.HotX, lo.Y - ml.Y - (float)sdata.HotY + img.Size.Height);
			Widget.DragImage (img, pos, new CGSize (0, 0), NSApplication.SharedApplication.CurrentEvent, pb, Widget, true);
		}
		
		public void SetDragSource (TransferDataType[] types, DragDropAction dragAction)
		{
		}
		
		public void SetDragTarget (TransferDataType[] types, DragDropAction dragAction)
		{
			SetupForDragDrop (Widget.GetType ());
			var dtypes = types.Select (ToNSDragType).ToArray ();
			Widget.RegisterForDraggedTypes (dtypes);
		}
		
		static NSDragOperation DraggingEntered (IntPtr sender, IntPtr sel, IntPtr dragInfo)
		{
			return DraggingUpdated (sender, sel, dragInfo);
		}
		
		static NSDragOperation DraggingUpdated (IntPtr sender, IntPtr sel, IntPtr dragInfo)
		{
			IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
			if (ob == null)
				return NSDragOperation.None;
			var backend = ob.Backend;

			var di = Runtime.GetINativeObject<INSDraggingInfo> (dragInfo, owns: false);
			var types = di.DraggingPasteboard.Types.Select (ToXwtDragType).ToArray ();
			var pos = backend.Widget.ConvertPointFromView (di.DraggingLocation, null).ToXwtPoint ();
			
			if ((backend.currentEvents & WidgetEvent.DragOverCheck) != 0) {
				var args = new DragOverCheckEventArgs (pos, types, ConvertAction (di.DraggingSourceOperationMask));
				backend.OnDragOverCheck (di, args);
				if (args.AllowedAction == DragDropAction.None)
					return NSDragOperation.None;
				if (args.AllowedAction != DragDropAction.Default)
					return ConvertAction (args.AllowedAction);
			}
			
			if ((backend.currentEvents & WidgetEvent.DragOver) != 0) {
				TransferDataStore store = new TransferDataStore ();
				FillDataStore (store, di.DraggingPasteboard, ob.View.RegisteredDragTypes ());
				var args = new DragOverEventArgs (pos, store, ConvertAction (di.DraggingSourceOperationMask));
				backend.OnDragOver (di, args);
				if (args.AllowedAction == DragDropAction.None)
					return NSDragOperation.None;
				if (args.AllowedAction != DragDropAction.Default)
					return ConvertAction (args.AllowedAction);
			}
			
			return di.DraggingSourceOperationMask;
		}
		
		static void DraggingExited (IntPtr sender, IntPtr sel, IntPtr dragInfo)
		{
			IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
			if (ob != null) {
				var backend = ob.Backend;
				backend.ApplicationContext.InvokeUserCode (delegate {
					backend.eventSink.OnDragLeave (EventArgs.Empty);
				});
			}
		}
		
		static bool PrepareForDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo)
		{
			IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
			if (ob == null)
				return false;
			
			var backend = ob.Backend;

			var di = Runtime.GetINativeObject<INSDraggingInfo> (dragInfo, owns: false);
			var types = di.DraggingPasteboard.Types.Select (ToXwtDragType).ToArray ();
			var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y);
			
			if ((backend.currentEvents & WidgetEvent.DragDropCheck) != 0) {
				var args = new DragCheckEventArgs (pos, types, ConvertAction (di.DraggingSourceOperationMask));
				bool res = backend.ApplicationContext.InvokeUserCode (delegate {
					backend.eventSink.OnDragDropCheck (args);
				});
				if (args.Result == DragDropResult.Canceled || !res)
					return false;
			}
			return true;
		}
		
		static bool PerformDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo)
		{
			IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
			if (ob == null)
				return false;
			
			var backend = ob.Backend;
			
			var di = Runtime.GetINativeObject<INSDraggingInfo> (dragInfo, owns: false);
			var pos = new Point (di.DraggingLocation.X, di.DraggingLocation.Y);
			
			if ((backend.currentEvents & WidgetEvent.DragDrop) != 0) {
				TransferDataStore store = new TransferDataStore ();
				FillDataStore (store, di.DraggingPasteboard, ob.View.RegisteredDragTypes ());
				var args = new DragEventArgs (pos, store, ConvertAction (di.DraggingSourceOperationMask));
				backend.ApplicationContext.InvokeUserCode (delegate {
					backend.eventSink.OnDragDrop (args);
				});
				return args.Success;
			} else
				return false;
		}
		
		static void ConcludeDragOperation (IntPtr sender, IntPtr sel, IntPtr dragInfo)
		{
			Console.WriteLine ("ConcludeDragOperation");
		}
		
		protected virtual void OnDragOverCheck (INSDraggingInfo di, DragOverCheckEventArgs args)
		{
			ApplicationContext.InvokeUserCode (delegate {
				eventSink.OnDragOverCheck (args);
			});
		}
		
		protected virtual void OnDragOver (INSDraggingInfo di, DragOverEventArgs args)
		{
			ApplicationContext.InvokeUserCode (delegate {
				eventSink.OnDragOver (args);
			});
		}
		
		void InitPasteboard (NSPasteboard pb, TransferDataSource data)
		{
			pb.ClearContents ();

			foreach (var t in data.DataTypes) {
				// Support dragging text internally and externally
				if (t == TransferDataType.Text) {
					pb.AddTypes(new string[] { NSPasteboard.NSStringType }, null);
					pb.SetStringForType((string)data.GetValue(t), NSPasteboard.NSStringType);
				}
				// For other well known types, we don't currently support dragging them
				else if (t == TransferDataType.Uri || t == TransferDataType.Image || t == TransferDataType.Rtf || t == TransferDataType.Html)
					;
				// For internal types, provided serialized data
				else {
					object value = data.GetValue (t);
					NSData serializedData = NSData.FromArray (TransferDataSource.SerializeValue (value));
					pb.SetDataForType (serializedData, t.Id);
				}
			}
		}

		static void FillDataStore (TransferDataStore store, NSPasteboard pb, string[] types)
		{
			foreach (var t in types) {
				if (!pb.Types.Contains (t))
					continue;
				if (t == NSPasteboard.NSStringType)
					store.AddText (pb.GetStringForType (t));
				else if (t == NSPasteboard.NSFilenamesType) {
					string data = pb.GetStringForType (t);
					XmlDocument doc = new XmlDocument ();
					doc.XmlResolver = null; // Avoid DTD validation
					doc.LoadXml (data);
					store.AddUris (doc.SelectNodes ("/plist/array/string").Cast<XmlElement> ().Select (e => new Uri (e.InnerText)).ToArray ());
				}
			}
		}
		
		static NSDragOperation ConvertAction (DragDropAction action)
		{
			NSDragOperation res = (NSDragOperation)0;
			if ((action & DragDropAction.Copy) != 0)
				res |= NSDragOperation.Copy;
			if ((action & DragDropAction.Move) != 0)
				res |= NSDragOperation.Move;
			if ((action & DragDropAction.Link) != 0)
				res |= NSDragOperation.Link;
			return res;
		}
		
		static DragDropAction ConvertAction (NSDragOperation action)
		{
			if (action == NSDragOperation.AllObsolete)
				return DragDropAction.All;
			DragDropAction res = (DragDropAction)0;
			if ((action & NSDragOperation.Copy) != 0)
				res |= DragDropAction.Copy;
			if ((action & NSDragOperation.Move) != 0)
				res |= DragDropAction.Move;
			if ((action & NSDragOperation.Link) != 0)
				res |= DragDropAction.Link;
			return res;
		}
		
		static string ToNSDragType (TransferDataType type)
		{
			if (type == TransferDataType.Text) return NSPasteboard.NSStringType;
			if (type == TransferDataType.Uri) return NSPasteboard.NSFilenamesType;
			if (type == TransferDataType.Image) return NSPasteboard.NSPictType;
			if (type == TransferDataType.Rtf) return NSPasteboard.NSRtfType;
			if (type == TransferDataType.Html) return NSPasteboard.NSHtmlType;
			return type.Id;
		}
		
		static TransferDataType ToXwtDragType (string type)
		{
			if (type == NSPasteboard.NSStringType)
				return TransferDataType.Text;
			if (type == NSPasteboard.NSFilenamesType)
				return TransferDataType.Uri;
			if (type == NSPasteboard.NSPictType)
				return TransferDataType.Image;
			if (type == NSPasteboard.NSRtfType)
				return TransferDataType.Rtf;
			if (type == NSPasteboard.NSHtmlType)
				return TransferDataType.Html;
			return TransferDataType.FromId (type);
		}

		static bool OnBecomeFirstResponder (IntPtr sender, IntPtr sel)
		{
			IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
			var canGetIt = ob.Backend.canGetFocus;
			if (canGetIt)
				ob.Backend.ApplicationContext.InvokeUserCode (ob.Backend.EventSink.OnGotFocus);
			return canGetIt;
		}
		
		static bool OnResignFirstResponder (IntPtr sender, IntPtr sel)
		{
			IViewObject ob = Runtime.GetNSObject (sender) as IViewObject;
			ob.Backend.ApplicationContext.InvokeUserCode (ob.Backend.EventSink.OnLostFocus);
			return true;
		}

		#endregion
	}

	sealed class WidgetPlacementWrapper: NSView, IViewObject
	{
		NSView child;
		Widget w;

		public WidgetPlacementWrapper ()
		{
		}

		NSView IViewObject.View {
			get { return this; }
		}

		ViewBackend IViewObject.Backend {
			get {
				var vo = child as IViewObject;
				return vo != null ? vo.Backend : null;
			}
			set {
				var vo = child as IViewObject;
				if (vo != null)
					vo.Backend = value;
			}
		}

		public override bool IsFlipped {
			get {
				return true;
			}
		}

		public void SetChild (NSView child, Widget w)
		{
			this.child = child;
			this.w = w;
			AddSubview (child);
		}

		public override void SetFrameSize (CGSize newSize)
		{
			base.SetFrameSize (newSize);
			if (w != null)
				UpdateChildPlacement ();
		}

		public void UpdateChildPlacement ()
		{
			double cheight = Frame.Height - w.Margin.VerticalSpacing;
			double cwidth = Frame.Width - w.Margin.HorizontalSpacing;
			double cx = w.MarginLeft;
			double cy = w.MarginTop;

			var s = w.Surface.GetPreferredSize (cwidth, cheight);
			if (w.HorizontalPlacement != WidgetPlacement.Fill) {
				cx += (cwidth - s.Width) * w.HorizontalPlacement.GetValue ();
				cwidth = s.Width;
			}
			if (w.VerticalPlacement != WidgetPlacement.Fill) {
				cy += (cheight - s.Height) * w.VerticalPlacement.GetValue ();
				cheight = s.Height;
			}
			child.Frame = new CGRect ((nfloat)cx, (nfloat)cy, (nfloat)cwidth, (nfloat)cheight);
		}
	}

#if false
	public class DragPasteboardDataProvider : NSObject, INSPasteboardItemDataProvider
	{
		TransferDataSource dataSource;

		DragPasteboardDataProvider(TransferDataSource dataSource)
        {
			this.dataSource = dataSource;
		}

		public void ProvideDataForType (NSPasteboard pasteboard, NSPasteboardItem item, string type)
		{
			TransferDataType desiredTransferDataType = TransferDataType.FromId (type);

			// Currently we only support internal types here, transferring their data via serializing
			object value = dataSource.GetValue (desiredTransferDataType);
			NSData data = NSData.FromArray (TransferDataSource.SerializeValue (value));

			pasteboard.SetDataForType (data, type);
		}

		public void FinishedWithDataProvider (NSPasteboard pasteboard)
		{
		}
	}
#endif
}