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

MacObjectValueTreeView.cs « Mac « ObjectValue « MonoDevelop.Debugger « MonoDevelop.Debugger « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f0e8816a96e11b94a958484a55f5c0a09f00d36b (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
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
//
// MacObjectValueTreeView.cs
//
// Author:
//       Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2019 Microsoft Corp.
//
// 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.Text;
using System.Collections.Generic;

using AppKit;
using Foundation;
using CoreGraphics;

using Mono.Debugging.Evaluation;

using MonoDevelop.Core;
using MonoDevelop.Ide.Commands;
using MonoDevelop.Components.Commands;

namespace MonoDevelop.Debugger
{
	public class MacObjectValueTreeView : NSOutlineView, IObjectValueTreeView
	{
		static readonly NSFont DefaultSystemFont = NSFont.UserFontOfSize (0);

		const int MinimumNameColumnWidth = 45;
		const int MinimumValueColumnWidth = 75;
		const int MinimumTypeColumnWidth = 30;

		MacObjectValueTreeViewDelegate treeViewDelegate;
		MacObjectValueTreeViewDataSource dataSource;

		readonly NSTableColumn nameColumn;
		readonly NSTableColumn valueColumn;
		readonly NSTableColumn typeColumn;
		readonly NSTableColumn pinColumn;
		readonly bool allowPopupMenu;
		readonly bool rootPinVisible;
		readonly bool compactView;

		PinnedWatch pinnedWatch;

		PreviewButtonIcon currentHoverIcon;
		nint currentHoverRow = -1;
		bool allowEditing;
		bool disposed;

		public MacObjectValueTreeView (
			IObjectValueDebuggerService debuggerService,
			ObjectValueTreeViewController controller,
			bool allowEditing,
			bool headersVisible,
			bool compactView,
			bool allowPinning,
			bool allowPopupMenu,
			bool rootPinVisible)
		{
			DebuggerService = debuggerService;
			Controller = controller;

			this.rootPinVisible = rootPinVisible;
			this.allowPopupMenu = allowPopupMenu;
			this.allowEditing = allowEditing;
			this.compactView = compactView;

			DataSource = dataSource = new MacObjectValueTreeViewDataSource (this, controller.Root, controller.AllowWatchExpressions);
			Delegate = treeViewDelegate = new MacObjectValueTreeViewDelegate (this);
			ColumnAutoresizingStyle = compactView ? NSTableViewColumnAutoresizingStyle.None : NSTableViewColumnAutoresizingStyle.Uniform;
			treeViewDelegate.SelectionChanged += OnSelectionChanged;
			UsesAlternatingRowBackgroundColors = true;
			FocusRingType = NSFocusRingType.None;
			AutoresizesOutlineColumn = false;
			AllowsColumnResizing = !compactView;
			SetCustomFont (null);

			var resizingMask = compactView ? NSTableColumnResizing.None : NSTableColumnResizing.UserResizingMask | NSTableColumnResizing.Autoresizing;

			nameColumn = new NSTableColumn ("name") { Editable = controller.AllowWatchExpressions, MinWidth = MinimumNameColumnWidth, ResizingMask = resizingMask };
			nameColumn.Title = GettextCatalog.GetString ("Name");
			nameColumn.Width = MinimumNameColumnWidth * 2;
			AddColumn (nameColumn);

			OutlineTableColumn = nameColumn;

			valueColumn = new NSTableColumn ("value") { Editable = controller.AllowEditing, MinWidth = MinimumValueColumnWidth, ResizingMask = resizingMask };
			valueColumn.Title = GettextCatalog.GetString ("Value");
			valueColumn.Width = MinimumValueColumnWidth * 2;
			if (compactView)
				valueColumn.MaxWidth = 800;
			AddColumn (valueColumn);

			if (!compactView) {
				typeColumn = new NSTableColumn ("type") { Editable = false, MinWidth = MinimumTypeColumnWidth, ResizingMask = resizingMask };
				typeColumn.Title = GettextCatalog.GetString ("Type");
				typeColumn.Width = MinimumTypeColumnWidth * 2;
				AddColumn (typeColumn);
			}

			if (allowPinning) {
				pinColumn = new NSTableColumn ("pin") { Editable = false, ResizingMask = NSTableColumnResizing.None };
				pinColumn.MinWidth = pinColumn.MaxWidth = pinColumn.Width = MacDebuggerObjectPinView.MinWidth;
				AddColumn (pinColumn);
			}

			if (headersVisible) {
				HeaderView.AlphaValue = 1.0f;
			} else {
				HeaderView = null;
			}

			PreviewWindowManager.WindowClosed += OnPreviewWindowClosed;

			// disable implicit animations
			WantsLayer = true;
			Layer.Actions = new NSDictionary (
				"actions", NSNull.Null,
				"contents", NSNull.Null,
				"hidden", NSNull.Null,
				"onLayout", NSNull.Null,
				"onOrderIn", NSNull.Null,
				"onOrderOut", NSNull.Null,
				"position", NSNull.Null,
				"sublayers", NSNull.Null,
				"transform", NSNull.Null,
				"bounds", NSNull.Null);
		}

		public ObjectValueTreeViewController Controller {
			get; private set;
		}

		public bool CompactView {
			get { return compactView; }
		}

		internal NSFont CustomFont {
			get; private set;
		}

		public IObjectValueDebuggerService DebuggerService {
			get; private set;
		}

		/// <summary>
		/// Gets a value indicating whether the user should be able to edit values in the tree
		/// </summary>
		public bool AllowEditing {
			get => allowEditing;
			set {
				if (allowEditing != value) {
					allowEditing = value;
					ReloadData ();
				}
			}
		}

		/// <summary>
		/// Gets a value indicating whether or not the user should be able to expand nodes in the tree.
		/// </summary>
		public bool AllowExpanding { get; set; }

		/// <summary>
		/// Gets a value indicating whether the user should be able to add watch expressions to the tree
		/// </summary>
		public bool AllowWatchExpressions {
			get { return dataSource.AllowWatchExpressions; }
		}

		/// <summary>
		/// Gets or sets the pinned watch for the view. When a watch is pinned, the view should display only this value
		/// </summary>
		public PinnedWatch PinnedWatch {
			get => pinnedWatch;
			set {
				if (pinnedWatch != value && pinColumn != null) {
					pinnedWatch = value;
					Runtime.RunInMainThread (() => {
						if (pinColumn == null)
							return;
						if (value == null) {
							pinColumn.MinWidth = pinColumn.MaxWidth = pinColumn.Width = MacDebuggerObjectPinView.MinWidth;
						} else {
							pinColumn.MinWidth = pinColumn.MaxWidth = pinColumn.Width = MacDebuggerObjectPinView.MaxWidth;
						}
					}).Ignore ();
				}
			}
		}

		/// <summary>
		/// Gets a value indicating the offset required for pinned watches
		/// </summary>
		public int PinnedWatchOffset {
			get {
				return (int) Frame.Height;
			}
		}

		/// <summary>
		/// Gets the optimal tooltip window width in order to display the name/value/pin columns w/o truncation.
		/// </summary>
		public nfloat OptimalTooltipWidth {
			get; private set;
		}

		// Note: this resizing method is the one used by debugger tooltips and pinned watches in the editor
		void OptimizeColumnSizes ()
		{
			if (!compactView || Superview == null || RowCount == 0)
				return;

			nfloat nameWidth = MinimumNameColumnWidth;
			nfloat valueWidth = MinimumValueColumnWidth;

			for (nint row = 0; row < RowCount; row++) {
				var item = (MacObjectValueNode) ItemAtRow (row);

				item.Measure (this);

				var totalNameWidth = item.OptimalXOffset + item.OptimalNameWidth;
				if (totalNameWidth > nameWidth)
					nameWidth = NMath.Min (totalNameWidth, nameColumn.MaxWidth);

				if (item.OptimalValueWidth > valueWidth)
					valueWidth = NMath.Min (item.OptimalValueWidth, valueColumn.MaxWidth);
			}

			bool changed = false;

			if ((int) nameColumn.Width != (int) nameWidth) {
				nameColumn.Width = nameWidth;
				changed = true;
			}

			if ((int) valueColumn.Width != (int) valueWidth) {
				valueColumn.Width = valueWidth;
				changed = true;
			}

			if (changed) {
				var optimalTooltipWidth = nameWidth + valueWidth + pinColumn.Width + IntercellSpacing.Width * 2;
				OptimalTooltipWidth = optimalTooltipWidth;
			}

			// we almost always need to recalculate the size - particularly if the widths don't
			// change but the row count did.
			OnResized ();
			SetNeedsDisplayInRect (Frame);
		}

		static NSFont GetNSFontFromPangoFontDescription (Pango.FontDescription fontDescription)
		{
			if (fontDescription == null)
				return null;

			return NSFontManager.SharedFontManager.FontWithFamilyWorkaround (
				fontDescription.Family,
				fontDescription.Style == Pango.Style.Italic || fontDescription.Style == Pango.Style.Oblique
					? NSFontTraitMask.Italic
					: 0,
				NormalizeWeight (fontDescription.Weight),
				fontDescription.Size / (nfloat) Pango.Scale.PangoScale);

			/// <summary>
			/// Normalizes a Pango font weight (100-1000 scale) to a weight
			/// suitable for NSFontDescription.FontWithFamily (0-15 scale).
			/// </summary>
			int NormalizeWeight (Pango.Weight pangoWeight)
			{
				double Normalize (double value, double inMin, double inMax, double outMin, double outMax)
					=> (outMax - outMin) / (inMax - inMin) * (value - inMax) + outMax;

				return (int) Math.Round (Normalize ((int) pangoWeight, 100, 1000, 0, 15));
			}
		}

		nfloat CalculateRowHeight (NSFont font)
		{
			using (var layoutManager = new NSLayoutManager ()) {
				layoutManager.TypesetterBehavior = NSTypesetterBehavior.Specific_10_4;
				layoutManager.UsesScreenFonts = false;

				return layoutManager.DefaultLineHeightForFont (font);
			}
		}

		internal void SetCustomFont (Pango.FontDescription fontDescription)
		{
			if (fontDescription != null) {
				CustomFont = GetNSFontFromPangoFontDescription (fontDescription);
			} else {
				CustomFont = DefaultSystemFont;
			}

			// Note: We need a minimum of 16px for the icons and an added 2px for vertical spacing
			RowHeight = NMath.Max (CalculateRowHeight (CustomFont), 18.0f);
			ReloadData ();
		}

		internal void QueueResize ()
		{
		}

		public override void ViewDidMoveToWindow ()
		{
			base.ViewDidMoveToWindow ();
			OptimizeColumnSizes ();
		}

		public override void ViewDidUnhide ()
		{
			base.ViewDidHide ();
			OptimizeColumnSizes ();
		}

		/// <summary>
		/// Triggered when the view tries to expand a node. This may trigger a load of
		/// the node's children
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeExpand;

		public void ExpandNode (ObjectValueNode node)
		{
			NodeExpand?.Invoke (this, new ObjectValueNodeEventArgs (node));
		}

		public override void ExpandItem (NSObject item, bool expandChildren)
		{
			NSAnimationContext.BeginGrouping ();
			NSAnimationContext.CurrentContext.Duration = 0;
			base.ExpandItem (item, expandChildren);
			NSAnimationContext.EndGrouping ();
			OptimizeColumnSizes ();
		}

		public override void ExpandItem (NSObject item)
		{
			NSAnimationContext.BeginGrouping ();
			NSAnimationContext.CurrentContext.Duration = 0;
			base.ExpandItem (item);
			NSAnimationContext.EndGrouping ();
			OptimizeColumnSizes ();
		}

		/// <summary>
		/// Triggered when the view tries to collapse a node.
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeCollapse;

		public void CollapseNode (ObjectValueNode node)
		{
			NodeCollapse?.Invoke (this, new ObjectValueNodeEventArgs (node));
		}

		public override void CollapseItem (NSObject item, bool collapseChildren)
		{
			NSAnimationContext.BeginGrouping ();
			NSAnimationContext.CurrentContext.Duration = 0;
			base.CollapseItem (item, collapseChildren);
			NSAnimationContext.EndGrouping ();
			OptimizeColumnSizes ();
		}

		public override void CollapseItem (NSObject item)
		{
			NSAnimationContext.BeginGrouping ();
			NSAnimationContext.CurrentContext.Duration = 0;
			base.CollapseItem (item);
			NSAnimationContext.EndGrouping ();
			OptimizeColumnSizes ();
		}

		/// <summary>
		/// Triggered when the view requests a node to fetch more of it's children
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeLoadMoreChildren;

		internal void LoadMoreChildren (ObjectValueNode node)
		{
			NodeLoadMoreChildren?.Invoke (this, new ObjectValueNodeEventArgs (node));
		}

		/// <summary>
		/// Triggered when the view needs the node to be refreshed
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeRefresh;

		internal void Refresh (ObjectValueNode node)
		{
			NodeRefresh?.Invoke (this, new ObjectValueNodeEventArgs (node));
		}

		/// <summary>
		/// Triggered when the view needs to know if the node can be edited
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeGetCanEdit;

		internal bool GetCanEditNode (ObjectValueNode node)
		{
			var args = new ObjectValueNodeEventArgs (node);
			NodeGetCanEdit?.Invoke (this, args);
			return args.Response is bool b && b;
		}

		/// <summary>
		/// Triggered when the node's value has been edited by the user
		/// </summary>
		public event EventHandler<ObjectValueEditEventArgs> NodeEditValue;

		internal bool GetEditValue (ObjectValueNode node, string newText)
		{
			var args = new ObjectValueEditEventArgs (node, newText);
			NodeEditValue?.Invoke (this, args);
			return args.Response is bool b && b;
		}

		/// <summary>
		/// Triggered when the user removes a node (an expression)
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeRemoved;

		/// <summary>
		/// Triggered when the user pins the node
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodePinned;

		void CreatePinnedWatch (ObjectValueNode node)
		{
			var expression = node.Expression;

			if (string.IsNullOrEmpty (expression))
				return;

			if (PinnedWatch != null) {
				// Note: the row that the user just pinned will no longer be visible once
				// all of the root children are collapsed.
				currentHoverRow = -1;

				foreach (var child in dataSource.Root.Children)
					CollapseItem (child, true);
			}

			NodePinned?.Invoke (this, new ObjectValueNodeEventArgs (node));
		}

		public void Pin (ObjectValueNode node)
		{
			CreatePinnedWatch (node);
		}

		/// <summary>
		/// Triggered when the pinned watch is removed by the user
		/// </summary>
		public event EventHandler<EventArgs> NodeUnpinned;

		public void Unpin (ObjectValueNode node)
		{
			NodeUnpinned?.Invoke (this, EventArgs.Empty);
		}

		/// <summary>
		/// Triggered when the visualiser for the node should be shown
		/// </summary>
		public event EventHandler<ObjectValueNodeEventArgs> NodeShowVisualiser;

		internal bool ShowVisualizer (ObjectValueNode node)
		{
			var args = new ObjectValueNodeEventArgs (node);
			NodeShowVisualiser?.Invoke (this, args);
			return args.Response is bool b && b;
		}

		/// <summary>
		/// Triggered when an expression is added to the tree by the user
		/// </summary>
		public event EventHandler<ObjectValueExpressionEventArgs> ExpressionAdded;

		internal void OnExpressionAdded (string expression)
		{
			ExpressionAdded?.Invoke (this, new ObjectValueExpressionEventArgs (null, expression));
		}

		/// <summary>
		/// Triggered when an expression is edited by the user
		/// </summary>
		public event EventHandler<ObjectValueExpressionEventArgs> ExpressionEdited;

		internal void OnExpressionEdited (ObjectValueNode node, string expression)
		{
			ExpressionEdited?.Invoke (this, new ObjectValueExpressionEventArgs (node, expression));
		}

		/// <summary>
		/// Triggered when the user starts editing a node
		/// </summary>
		public event EventHandler StartEditing;

		internal void OnStartEditing ()
		{
			StartEditing?.Invoke (this, EventArgs.Empty);
		}

		/// <summary>
		/// Triggered when the user stops editing a node
		/// </summary>
		public new event EventHandler EndEditing;

		internal void OnEndEditing ()
		{
			EndEditing?.Invoke (this, EventArgs.Empty);
		}

		void OnEvaluationCompleted (ObjectValueNode node, ObjectValueNode[] replacementNodes)
		{
			if (disposed)
				return;

			dataSource.Replace (node, replacementNodes);
			OptimizeColumnSizes ();
		}

		public void LoadEvaluatedNode (ObjectValueNode node, ObjectValueNode[] replacementNodes)
		{
			OnEvaluationCompleted (node, replacementNodes);
		}

		void OnChildrenLoaded (ObjectValueNode node, int startIndex, int count)
		{
			if (disposed)
				return;

			dataSource.ReloadChildren (node);
			OptimizeColumnSizes ();
		}

		public void LoadNodeChildren (ObjectValueNode node, int startIndex, int count)
		{
			OnChildrenLoaded (node, startIndex, count);
		}

		public void OnNodeExpanded (ObjectValueNode node)
		{
			if (disposed)
				return;

			if (node.IsExpanded) {
				// if the node is _still_ expanded then adjust UI and scroll
				if (dataSource.TryGetValue (node, out var item)) {
					if (!IsItemExpanded (item))
						ExpandItem (item);
				}

				// TODO: all this scrolling kind of seems awkward
				//if (path != null)
				//	ScrollToCell (path, expCol, true, 0f, 0f);
			}
		}

		void IObjectValueTreeView.Cleared ()
		{
			dataSource.Clear ();
		}

		void IObjectValueTreeView.Appended (ObjectValueNode node)
		{
			dataSource.Append (node);
		}

		void IObjectValueTreeView.Appended (IList<ObjectValueNode> nodes)
		{
			dataSource.Append (nodes);
		}

		static CGPoint ConvertPointFromEvent (NSView view, NSEvent theEvent)
		{
			var point = theEvent.LocationInWindow;

			if (view.Window != null && theEvent.WindowNumber != view.Window.WindowNumber) {
				var rect = theEvent.Window.ConvertRectToScreen (new CGRect (point, new CGSize (1, 1)));
				rect = view.Window.ConvertRectFromScreen (rect);
				point = rect.Location;
			}

			return view.ConvertPointFromView (point, null);
		}

		void UpdatePreviewIcon (nint row, PreviewButtonIcon icon)
		{
			if (row >= RowCount)
				return;

			var rowView = GetRowView (row, false);

			if (rowView != null) {
				var nameView = (MacDebuggerObjectNameView) rowView.ViewAtColumn (0);

				nameView?.SetPreviewButtonIcon (icon);
			}
		}

		void UpdatePinIcon (nint row, bool hover)
		{
			if (row >= RowCount)
				return;

			if (pinColumn == null)
				return;

			var rowView = GetRowView (row, false);

			if (rowView != null) {
				var pinView = (MacDebuggerObjectPinView) rowView.ViewAtColumn (ColumnCount - 1);

				pinView?.SetMouseHover (hover);
			}
		}

		void UpdateCellViewIcons (NSEvent theEvent)
		{
			var point = ConvertPointFromEvent (this, theEvent);
			var row = GetRow (point);

			if (row != currentHoverRow) {
				if (currentHoverRow != -1) {
					UpdatePreviewIcon (currentHoverRow, PreviewButtonIcon.Hidden);
					currentHoverIcon = PreviewButtonIcon.Hidden;
					UpdatePinIcon (currentHoverRow, false);
				}
				currentHoverRow = row;
			}

			if (row == -1)
				return;

			PreviewButtonIcon icon;

			if (GetColumn (point) == 0) {
				icon = PreviewButtonIcon.Hover;
			} else {
				icon = PreviewButtonIcon.RowHover;
			}

			currentHoverIcon = icon;

			if (IsRowSelected (row))
				icon = PreviewButtonIcon.Selected;

			UpdatePreviewIcon (row, icon);
			UpdatePinIcon (row, true);
		}

		void OnPreviewWindowClosed (object sender, EventArgs args)
		{
			if (currentHoverRow != -1) {
				UpdatePreviewIcon (currentHoverRow, PreviewButtonIcon.Hidden);
				currentHoverIcon = PreviewButtonIcon.Hidden;
			}
		}

		public override void MouseEntered (NSEvent theEvent)
		{
			UpdateCellViewIcons (theEvent);
			base.MouseEntered (theEvent);
		}

		public override void MouseExited (NSEvent theEvent)
		{
			if (currentHoverRow != -1) {
				UpdatePreviewIcon (currentHoverRow, PreviewButtonIcon.Hidden);
				currentHoverIcon = PreviewButtonIcon.Hidden;
				currentHoverRow = -1;

				UpdatePinIcon (currentHoverRow, false);
			}

			base.MouseExited (theEvent);
		}

		public override void MouseMoved (NSEvent theEvent)
		{
			UpdateCellViewIcons (theEvent);
			base.MouseMoved (theEvent);
		}

		internal static bool ValidObjectForPreviewIcon (ObjectValueNode node)
		{
			var obj = node.GetDebuggerObjectValue ();
			if (obj == null)
				return false;

			if (obj.IsNull)
				return false;

			if (obj.IsPrimitive) {
				//obj.DisplayValue.Contains ("|") is special case to detect enum with [Flags]
				return obj.TypeName == "string" || (obj.DisplayValue != null && obj.DisplayValue.Contains ("|"));
			}

			if (string.IsNullOrEmpty (obj.TypeName))
				return false;

			return true;
		}

		void OnSelectionChanged (object sender, EventArgs e)
		{
			if (currentHoverRow == -1)
				return;

			var row = SelectedRow;

			if (SelectedRowCount == 0 || row != currentHoverRow) {
				// reset back to what the unselected icon would be
				UpdatePreviewIcon (currentHoverRow, currentHoverIcon);
				return;
			}

			UpdatePreviewIcon (currentHoverRow, PreviewButtonIcon.Selected);
		}

		public event EventHandler Resized;

		void OnResized ()
		{
			Resized?.Invoke (this, EventArgs.Empty);
		}

		[CommandUpdateHandler (EditCommands.SelectAll)]
		protected void UpdateSelectAll (CommandInfo cmd)
		{
			cmd.Enabled = Controller.Root.Children.Count > 0;
		}

		[CommandHandler (EditCommands.SelectAll)]
		protected void OnSelectAll ()
		{
			SelectAll (this);
		}

		[CommandHandler (EditCommands.Copy)]
		protected void OnCopy ()
		{
			if (SelectedRowCount == 0)
				return;

			var str = new StringBuilder ();
			var needsNewLine = false;

			var selectedRows = SelectedRows;
			foreach (var row in selectedRows) {
				var item = (MacObjectValueNode) ItemAtRow ((nint) row);

				if (item.Target is AddNewExpressionObjectValueNode ||
					item.Target is ShowMoreValuesObjectValueNode ||
					item.Target is LoadingObjectValueNode)
					break;

				if (needsNewLine)
					str.AppendLine ();

				needsNewLine = true;

				var value = item.Target.DisplayValue;
				var type = item.Target.TypeName;

				if (type == "string") {
					var objVal = item.Target.GetDebuggerObjectValue ();

					if (objVal != null) {
						try {
							// HACK: we need a better abstraction of the stack frame, better yet would be to not really need it in the view
							var opt = DebuggerService.Frame.GetStackFrame ().DebuggerSession.Options.EvaluationOptions.Clone ();
							opt.EllipsizeStrings = false;

							var rawValue = (string) objVal.GetRawValue (opt);

							value = '"' + Mono.Debugging.Evaluation.ExpressionEvaluator.EscapeString (rawValue) + '"';
						} catch (EvaluatorException) {
							// fall back to using the DisplayValue that we would have used anyway...
						}
					}
				}

				str.Append (value);
			}

			var clipboard = NSPasteboard.GeneralPasteboard;

			clipboard.ClearContents ();
			clipboard.SetStringForType (str.ToString (), NSPasteboard.NSPasteboardTypeString);

			//Gtk.Clipboard.Get (Gdk.Selection.Clipboard).Text = str.ToString ();
		}

		void OnCopy (object sender, EventArgs args)
		{
			OnCopy ();
		}

		[CommandHandler (EditCommands.Delete)]
		[CommandHandler (EditCommands.DeleteKey)]
		protected void OnDelete ()
		{
			var nodesToDelete = new List<ObjectValueNode> ();
			var selectedRows = SelectedRows;

			foreach (var row in selectedRows) {
				var item = (MacObjectValueNode) ItemAtRow ((nint) row);

				// The user is only allowed to delete top-level nodes. It doesn't make sense to allow
				// deleting child nodes of anything else.
				if (!(item.Target.Parent is RootObjectValueNode))
					continue;

				nodesToDelete.Add (item.Target);
			}

			foreach (var node in nodesToDelete)
				NodeRemoved?.Invoke (this, new ObjectValueNodeEventArgs (node));
		}

		void OnDelete (object sender, EventArgs args)
		{
			OnDelete ();
		}

		bool CanDelete (out bool enabled)
		{
			enabled = false;

			if (!AllowWatchExpressions)
				return false;

			if (SelectedRowCount == 0)
				return false;

			enabled = true;

			var selectedRows = SelectedRows;
			foreach (var row in selectedRows) {
				var item = (MacObjectValueNode) ItemAtRow ((nint) row);

				if (!(item.Target.Parent is RootObjectValueNode)) {
					enabled = false;
					break;
				}
			}

			return true;
		}

		[CommandUpdateHandler (EditCommands.Delete)]
		[CommandUpdateHandler (EditCommands.DeleteKey)]
		protected void OnUpdateDelete (CommandInfo cinfo)
		{
			cinfo.Visible = CanDelete (out bool enabled);
			cinfo.Enabled = enabled;
		}

		[CommandHandler (DebugCommands.AddWatch)]
		protected void OnAddWatch ()
		{
			var expressions = new List<string> ();
			var selectedRows = SelectedRows;

			foreach (var row in selectedRows) {
				var item = (MacObjectValueNode) ItemAtRow ((nint) row);
				var expression = item.Target.Expression;

				if (!string.IsNullOrEmpty (expression))
					expressions.Add (expression);
			}

			foreach (var expression in expressions)
				DebuggingService.AddWatch (expression);
		}

		void OnAddWatch (object sender, EventArgs args)
		{
			OnAddWatch ();
		}

		bool CanAddWatch (out bool enabled)
		{
			enabled = SelectedRowCount > 0;

			return true;
		}

		[CommandUpdateHandler (DebugCommands.AddWatch)]
		protected void OnUpdateAddWatch (CommandInfo cinfo)
		{
			cinfo.Visible = CanAddWatch (out bool enabled);
			cinfo.Enabled = enabled;
		}

		[CommandHandler (EditCommands.Rename)]
		protected void OnRename ()
		{
			if (SelectedRow == -1)
				return;

			var nameView = (MacDebuggerObjectNameView) GetView (0, SelectedRow, false);

			nameView.TextField.BecomeFirstResponder ();
		}

		void OnRename (object sender, EventArgs args)
		{
			OnRename ();
		}

		bool CanRename (out bool enabled)
		{
			enabled = SelectedRowCount == 1 && SelectedRow != -1;

			return AllowWatchExpressions;
		}

		[CommandUpdateHandler (EditCommands.Rename)]
		protected void OnUpdateRename (CommandInfo cinfo)
		{
			cinfo.Visible = CanRename (out bool enabled);
			cinfo.Enabled = enabled;
		}

		public override NSMenu MenuForEvent (NSEvent theEvent)
		{
			if (!allowPopupMenu)
				return null;

			var point = ConvertPointFromEvent (this, theEvent);
			var row = GetRow (point);

			if (row < 0)
				return null;

			var menu = new NSMenu ();
			bool enabled;

			if (CanAddWatch (out enabled)) {
				menu.AddItem (new NSMenuItem (GettextCatalog.GetString ("Add Watch"), OnAddWatch) {
					Enabled = enabled
				});
				menu.AddItem (NSMenuItem.SeparatorItem);
			}

			menu.AddItem (new NSMenuItem (GettextCatalog.GetString ("Copy"), OnCopy));

			if (CanRename (out enabled)) {
				menu.AddItem (new NSMenuItem (GettextCatalog.GetString ("Rename"), OnRename) {
					Enabled = enabled
				});
			}

			if (CanDelete (out enabled)) {
				menu.AddItem (new NSMenuItem (GettextCatalog.GetString ("Delete"), OnDelete) {
					Enabled = enabled
				});
			}

			return menu;
		}

		protected override void Dispose (bool disposing)
		{
			if (disposing && !disposed) {
				PreviewWindowManager.WindowClosed -= OnPreviewWindowClosed;
				PreviewWindowManager.DestroyWindow ();
				treeViewDelegate.SelectionChanged -= OnSelectionChanged;
				treeViewDelegate.Dispose ();
				treeViewDelegate = null;
				dataSource.Dispose ();
				dataSource = null;
				disposed = true;
			}

			base.Dispose (disposing);
		}
	}
}