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

ObjectValueTreeViewController.cs « 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: 13ebca43b2da812048b0ccbfca159368cfd18c9d (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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
//
// ObjectValueTreeViewController.cs
//
// Author:
//       gregm <gregm@microsoft.com>
//
// Copyright (c) 2019 Microsoft
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using Mono.Debugging.Client;

using MonoDevelop.Core;
using MonoDevelop.Components;

namespace MonoDevelop.Debugger
{
	public enum PreviewButtonIcon
	{
		None,
		Hidden,
		RowHover,
		Hover,
		Active,
		Selected,
	}

	public interface IObjectValueDebuggerService
	{
		bool CanQueryDebugger { get; }
		IStackFrame Frame { get; }
		Task<CompletionData> GetCompletionDataAsync (string expression, CancellationToken token);
	}

	public class ObjectValueTreeViewController : IObjectValueDebuggerService
	{
		readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource ();
		public const int MaxEnumerableChildrenToFetch = 20;

		IObjectValueTreeView view;
		IDebuggerService debuggerService;
		bool allowWatchExpressions;
		bool allowEditing;
		bool allowExpanding = true;

		/// <summary>
		/// Holds a dictionary of tasks that are fetching children values of the given node
		/// </summary>
		readonly Dictionary<ObjectValueNode, Task<int>> childFetchTasks = new Dictionary<ObjectValueNode, Task<int>> ();

		/// <summary>
		/// Holds a dictionary of arbitrary objects for nodes that are currently "Evaluating" by the debugger
		/// When the node has completed evaluation ValueUpdated event will be fired, passing the given object
		/// </summary>
		readonly Dictionary<ObjectValueNode, object> evaluationWatches = new Dictionary<ObjectValueNode, object> ();

		/// <summary>
		/// Holds a dictionary of node paths and the values. Used to show values that have changed from one frame to the next.
		/// </summary>
		readonly Dictionary<string, CheckpointState> oldValues = new Dictionary<string, CheckpointState> ();

		public ObjectValueTreeViewController (bool allowWatchExpressions = false)
		{
			AllowWatchExpressions = allowWatchExpressions;
			Root = new RootObjectValueNode ();
		}

		public IDebuggerService Debugger {
			get {
				if (debuggerService == null) {
					debuggerService = OnGetDebuggerService ();
				}

				return debuggerService;
			}
		}

		public ObjectValueNode Root { get; private set; }

		public IStackFrame Frame { get; 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 {
				allowEditing = value;
				if (view != null) {
					view.AllowEditing = value;
				}
			}
		}

		/// <summary>
		/// Gets a value indicating whether or not the user should be able to expand nodes in the tree.
		/// </summary>
		public bool AllowExpanding {
			get => allowExpanding;
			set {
				allowExpanding = value;
				if (view != null) {
					view.AllowExpanding = value;
				}
			}
		}

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

		public PinnedWatch PinnedWatch {
			get { return view?.PinnedWatch; }
			set {
				if (view != null) {
					view.PinnedWatch = value;
				}
			}
		}

		public PinnedWatchLocation PinnedWatchLocation {
			get; set;
		}

		public bool CanQueryDebugger {
			get {
				return Debugger.IsConnected && Debugger.IsPaused;
			}
		}

		protected void ConfigureView (IObjectValueTreeView control)
		{
			view = control;

			view.AllowExpanding = AllowExpanding;
			view.PinnedWatch = PinnedWatch;

			view.NodeExpand += OnViewNodeExpand;
			view.NodeCollapse += OnViewNodeCollapse;
			view.NodeLoadMoreChildren += OnViewNodeLoadMoreChildren;
			view.ExpressionAdded += OnViewExpressionAdded;
			view.ExpressionEdited += OnViewExpressionEdited;
			view.NodeRefresh += OnViewNodeRefresh;
			view.NodeGetCanEdit += OnViewNodeCanEdit;
			view.NodeEditValue += OnViewNodeEditValue;
			view.NodeRemoved += OnViewNodeRemoved;
			view.NodePinned += OnViewNodePinned;
			view.NodeUnpinned += OnViewNodeUnpinned;
			view.NodeShowVisualiser += OnViewNodeShowVisualiser;
		}

		public GtkObjectValueTreeView GetGtkControl (bool headersVisible = true, bool compactView = false, bool allowPinning = false, bool allowPopupMenu = true, bool rootPinVisible = false)
		{
			if (view != null)
				throw new InvalidOperationException ("You can only get the control once for each controller instance");

			var control = new GtkObjectValueTreeView (this, this, AllowEditing, headersVisible, compactView, allowPinning, allowPopupMenu, rootPinVisible);

			ConfigureView (control);

			return control;
		}

		public MacObjectValueTreeView GetMacControl (bool headersVisible = true, bool compactView = false, bool allowPinning = false, bool allowPopupMenu = true, bool rootPinVisible = false)
		{
			if (view != null)
				throw new InvalidOperationException ("You can only get the control once for each controller instance");

			var control = new MacObjectValueTreeView (this, this, AllowEditing, headersVisible, compactView, allowPinning, allowPopupMenu, rootPinVisible);

			ConfigureView (control);

			return control;
		}

		public Control GetControl (bool headersVisible = true, bool compactView = false, bool allowPinning = false, bool allowPopupMenu = true, bool rootPinVisible = false)
		{
			if (Platform.IsMac)
				return GetMacControl (headersVisible, compactView, allowPinning, allowPopupMenu, rootPinVisible);

			return GetGtkControl (headersVisible, compactView, allowPinning, allowPopupMenu, rootPinVisible);
		}

		public void CancelAsyncTasks ()
		{
			cancellationTokenSource.Cancel ();
		}

		/// <summary>
		/// Clears the controller of nodes and resets the root to a new empty node
		/// </summary>
		public void ClearValues ()
		{
			((RootObjectValueNode) Root).Clear ();

			Runtime.RunInMainThread (() => {
				view.Cleared ();
			}).Ignore ();
		}

		/// <summary>
		/// Clear everything
		/// </summary>
		public void ClearAll ()
		{
			ClearEvaluationCompletionRegistrations ();
			ClearValues ();
		}

		/// <summary>
		/// Adds values to the root node, eg locals or watch expressions
		/// </summary>
		public void AddValue (ObjectValueNode value)
		{
			((RootObjectValueNode) Root).AddValue (value);
			RegisterNode (value);

			Runtime.RunInMainThread (() => {
				LoggingService.LogInfo ("Appending value '{0}' to tree view", value.Name);
				view.Appended (value);
			}).Ignore ();
		}

		/// <summary>
		/// Adds values to the root node, eg locals or watch expressions
		/// </summary>
		public void AddValues (IEnumerable<ObjectValueNode> values)
		{
			var nodes = values.ToList ();

			((RootObjectValueNode) Root).AddValues (nodes);

			foreach (var node in nodes)
				RegisterNode (node);

			Runtime.RunInMainThread (() => {
				view.Appended (nodes);
			}).Ignore ();
		}

		public async Task<CompletionData> GetCompletionDataAsync (string expression, CancellationToken token)
		{
			if (CanQueryDebugger && Frame != null) {
				// TODO: improve how we get at the underlying real stack frame
				return await DebuggingService.GetCompletionDataAsync (Frame.GetStackFrame (), expression, token);
			}

			return null;
		}

		void CreatePinnedWatch (string expression, int height)
		{
			var watch = new PinnedWatch ();

			if (PinnedWatch != null) {
				watch.Location = PinnedWatch.Location;
				watch.OffsetX = PinnedWatch.OffsetX;
				watch.OffsetY = PinnedWatch.OffsetY + height + 5;
			} else {
				watch.Location = PinnedWatchLocation;
				watch.OffsetX = -1; // means that the watch should be placed at the line coordinates defined by watch.Line
				watch.OffsetY = -1;
			}

			watch.Expression = expression;
			DebuggingService.PinnedWatches.Add (watch);
		}

		void RemovePinnedWatch ()
		{
			DebuggingService.PinnedWatches.Remove (PinnedWatch);
		}

		void RemoveValue (ObjectValueNode node)
		{
			var toplevel = node.Parent is RootObjectValueNode;
			int index;

			if (node.Parent != null) {
				index = node.Parent.Children.IndexOf (node);
			} else {
				index = -1;
			}

			UnregisterNode (node);
			OnEvaluationCompleted (node, new ObjectValueNode[0]);

			if (AllowWatchExpressions && toplevel && index != -1)
				ExpressionRemoved?.Invoke (this, new ExpressionRemovedEventArgs (index, node.Name));
		}

		// TODO: can we improve this
		public string GetDisplayValueWithVisualisers (ObjectValueNode node, out bool showViewerButton)
		{
			showViewerButton = false;
			if (node == null)
				return null;

			string result;
			showViewerButton = !node.IsNull && Debugger.HasValueVisualizers (node);

			if (!node.IsNull && Debugger.HasInlineVisualizer (node)) {
				try {
					result = node.GetInlineVisualisation ();
				} catch (Exception) {
					result = node.GetDisplayValue ();
				}
			} else {
				result = node.GetDisplayValue ();
			}

			return result;
		}

		#region Checkpoints
		public void ChangeCheckpoint ()
		{
			// clear old values,
			// iterate over all the nodes and store the values so we can compare
			// on the next update
			oldValues.Clear ();
			if (Root != null) {
				ChangeCheckpoint (Root);
			}
		}

		public void ResetChangeTracking ()
		{
			oldValues.Clear ();
		}

		/// <summary>
		/// Returns true if the value of the node is different from it's last value
		/// at the last checkpoint. Returns false if the node was not scanned at the
		/// last checkpoint
		/// </summary>
		public bool GetNodeHasChangedSinceLastCheckpoint (ObjectValueNode node)
		{
			if (oldValues.TryGetValue (node.Path, out CheckpointState checkpointState)) {
				return node.Value != checkpointState.Value;
			}

			return false;
		}

		/// <summary>
		/// Returns true if the node was expanded when the last checkpoint was made
		/// </summary>
		public bool GetNodeWasExpandedAtLastCheckpoint (ObjectValueNode node)
		{
			if (oldValues.TryGetValue (node.Path, out CheckpointState checkpointState)) {
				return checkpointState.Expanded;
			}

			return false;
		}
		#endregion

		#region Expressions

		public event EventHandler<ExpressionAddedEventArgs> ExpressionAdded;
		public event EventHandler<ExpressionChangedEventArgs> ExpressionChanged;
		public event EventHandler<ExpressionRemovedEventArgs> ExpressionRemoved;

		public void AddExpression (string expression)
		{
			if (!AllowWatchExpressions) {
				LoggingService.LogInfo ("Watch expressions not allowed.");
				return;
			}

			LoggingService.LogInfo ("Evaluating expression '{0}'", expression);
			var node = Frame.EvaluateExpression (expression);
			AddValue (node);

			ExpressionAdded?.Invoke (this, new ExpressionAddedEventArgs (expression));
		}

		public void AddExpressions (IList<string> expressions)
		{
			if (!AllowWatchExpressions)
				return;

			if (Frame != null) {
				var nodes = Frame.EvaluateExpressions (expressions);
				AddValues (nodes);

				var expressionAdded = ExpressionAdded;
				if (expressionAdded != null) {
					foreach (var expression in expressions)
						expressionAdded (this, new ExpressionAddedEventArgs (expression));
				}
			}
		}

		bool EditExpression (ObjectValueNode node, string newExpression)
		{
			var oldExpression = node.Name;

			if (oldExpression == newExpression)
				return false;

			int index = node.Parent.Children.IndexOf (node);

			UnregisterNode (node);
			if (string.IsNullOrEmpty (newExpression)) {
				// we want the expression removed from the tree
				OnEvaluationCompleted (node, new ObjectValueNode[0]);
				ExpressionRemoved?.Invoke (this, new ExpressionRemovedEventArgs (index, oldExpression));
				return true;
			}

			var expressionNode = Frame.EvaluateExpression (newExpression);
			RegisterNode (expressionNode);
			OnEvaluationCompleted (node, new ObjectValueNode[] { expressionNode });
			ExpressionChanged?.Invoke (this, new ExpressionChangedEventArgs (index, oldExpression, newExpression));

			return true;
		}

		public void ReEvaluateExpressions ()
		{
			if (!AllowWatchExpressions)
				return;

			foreach (var node in Root.Children)
				node.Refresh ();
		}
		#endregion

		/// <summary>
		/// Returns true if the node can be edited
		/// </summary>
		bool CanEditObject (ObjectValueNode node)
		{
			if (AllowEditing) {
				if (node.IsUnknown) {
					if (Frame != null) {
						return false;
					}
				}

				return node.CanEdit;
			}

			return false;
		}

		/// <summary>
		/// Edits the value of the node and returns a value indicating whether the node's value changed from
		/// when the node was initially loaded from the debugger
		/// </summary>
		bool EditNodeValue (ObjectValueNode node, string newValue)
		{
			if (node == null || !AllowEditing)
				return false;

			try {
				if (node.Value == newValue)
					return false;

				// make sure we set an old value for this node so we can show that it has changed
				if (!oldValues.TryGetValue (node.Path, out CheckpointState state)) {
					oldValues[node.Path] = new CheckpointState (node);
				}

				// ensure the parent and node are in the checkpoint and expanded
				// so that the tree expands the node we just edited when refreshed
				EnsureNodeIsExpandedInCheckpoint (node);

				node.SetValue (newValue);
			} catch (Exception ex) {
				LoggingService.LogError ($"Could not set value for object '{node.Name}'", ex);
				return false;
			}

			// now, refresh the parent
			var parent = node.Parent; /*FindNode (node.ParentId);*/
			if (parent != null) {
				parent.Refresh ();
				RegisterForEvaluationCompletion (parent, true);
			}

			// the locals pad, for example, will reload all the values once this is fired
			// prior to reloading, a new checkpoint will be made
			Debugger.NotifyVariableChanged ();

			return true;
		}

		bool ShowNodeValueVisualizer (ObjectValueNode node)
		{
			if (node != null) {

				// make sure we set an old value for this node so we can show that it has changed
				if (!oldValues.TryGetValue (node.Path, out CheckpointState state)) {
					oldValues[node.Path] = new CheckpointState (node);
				}

				// ensure the parent and node are in the checkpoint and expanded
				// so that the tree expands the node we just edited when refreshed
				EnsureNodeIsExpandedInCheckpoint (node);

				if (Debugger.ShowValueVisualizer (node)) {
					// the value of the node changed so now refresh the parent
					var parent = node.Parent; /*FindNode (node.ParentId);*/
					if (parent != null) {
						parent.Refresh ();
						RegisterForEvaluationCompletion (parent, true);
					}

					return true;
				}
			}

			return false;
		}

		void EnsureNodeIsExpandedInCheckpoint (ObjectValueNode node)
		{
			var parent = node.Parent; /*FindNode (node.ParentId);*/

			while (parent != null && parent != Root) {
				if (oldValues.TryGetValue (parent.Path, out CheckpointState state)) {
					state.Expanded = true;
				} else {
					oldValues[parent.Path] = new CheckpointState (parent) { Expanded = true };
				}

				parent = parent.Parent; /*FindNode (parent.ParentId);*/
			}
		}

		void RefreshNode (ObjectValueNode node)
		{
			if (node == null)
				return;

			if (CanQueryDebugger && Frame != null) {
				UnregisterForEvaluationCompletion (node);

				var options = Frame.CloneSessionEvaluationOpions ();
				options.AllowMethodEvaluation = true;
				options.AllowToStringCalls = true;
				options.AllowTargetInvoke = true;
				options.EllipsizeStrings = false;

				node.Refresh (options);

				RegisterForEvaluationCompletion (node);
			}
		}

		#region View event handlers
		void OnViewNodeExpand (object sender, ObjectValueNodeEventArgs e)
		{
			ExpandNodeAsync (e.Node).Ignore ();
		}

		void OnViewNodeCollapse (object sender, ObjectValueNodeEventArgs e)
		{
			e.Node.IsExpanded = false;
		}

		void OnViewNodeLoadMoreChildren (object sender, ObjectValueNodeEventArgs e)
		{
			FetchMoreChildrenAsync (e.Node).Ignore ();
		}

		void OnViewExpressionAdded (object sender, ObjectValueExpressionEventArgs e)
		{
			LoggingService.LogInfo ("ObjectValueTreeViewController.OnViewExpressionAdded");
			AddExpression (e.Expression);
		}

		void OnViewExpressionEdited (object sender, ObjectValueExpressionEventArgs e)
		{
			EditExpression (e.Node, e.Expression);
		}

		void OnViewNodeRefresh (object sender, ObjectValueNodeEventArgs e)
		{
			RefreshNode (e.Node);
		}

		void OnViewNodeCanEdit (object sender, ObjectValueNodeEventArgs e)
		{
			e.Response = CanEditObject (e.Node);
		}

		void OnViewNodeEditValue (object sender, ObjectValueEditEventArgs e)
		{
			e.Response = EditNodeValue (e.Node, e.NewValue);
		}

		void OnViewNodeRemoved (object sender, ObjectValueNodeEventArgs e)
		{
			RemoveValue (e.Node);
		}

		void OnViewNodeShowVisualiser (object sender, ObjectValueNodeEventArgs e)
		{
			e.Response = ShowNodeValueVisualizer (e.Node);
		}

		void OnViewNodePinned (object sender, ObjectValueNodeEventArgs e)
		{
			CreatePinnedWatch (e.Node.Expression, view.PinnedWatchOffset);
		}

		void OnViewNodeUnpinned (object sender, EventArgs e)
		{
			RemovePinnedWatch ();
		}

		#endregion

		#region Fetching and loading children
		/// <summary>
		/// Marks a node as expanded and fetches children for the node if they have not been already fetched
		/// </summary>
		async Task ExpandNodeAsync (ObjectValueNode node)
		{
			// if we think the node is expanded already, no need to trigger this again
			if (node.IsExpanded)
				return;

			node.IsExpanded = true;

			int loadedCount = 0;
			if (node.IsEnumerable) {
				// if we already have some loaded, don't load more - that is a specific user gesture
				if (node.Children.Count == 0) {
					// page the children in, instead of loading them all at once
					loadedCount = await FetchChildrenAsync (node, MaxEnumerableChildrenToFetch, cancellationTokenSource.Token);
				}
			} else {
				loadedCount = await FetchChildrenAsync (node, 0, cancellationTokenSource.Token);
			}

			await Runtime.RunInMainThread (() => {
				// tell the view about the children, even if there are, in fact, none
				view.LoadNodeChildren (node, 0, node.Children.Count);

				view.OnNodeExpanded (node);
			});
		}

		async Task<int> FetchMoreChildrenAsync (ObjectValueNode node)
		{
			if (node.ChildrenLoaded) {
				return 0;
			}

			try {
				if (childFetchTasks.TryGetValue (node, out Task<int> task)) {
					// there is already a task to fetch the children
					return await task;
				}

				try {
					var oldCount = node.Children.Count;
					var result = await node.LoadChildrenAsync (MaxEnumerableChildrenToFetch, cancellationTokenSource.Token);

					// if any of them are still evaluating register for
					// a completion event so that we can tell the UI
					for (int i = oldCount; i < oldCount + result; i++) {
						var c = node.Children[i];
						RegisterNode (c);
					}

					// always send the event so that the UI can determine if the node has finished loading.
					OnChildrenLoaded (node, oldCount, result);

					return result;
				} finally {
					childFetchTasks.Remove (node);
				}
			} catch (Exception ex) {
				LoggingService.LogInternalError (ex);
			}

			return 0;
		}

		/// <summary>
		/// Fetches the child nodes and returns the count of new children that were loaded.
		/// The children will be in node.Children.
		/// </summary>
		async Task<int> FetchChildrenAsync (ObjectValueNode node, int count, CancellationToken cancellationToken)
		{
			if (node.ChildrenLoaded) {
				return 0;
			}

			try {
				if (childFetchTasks.TryGetValue (node, out Task<int> task)) {
					// there is already a task to fetch the children
					return await task;
				}

				try {
					int result = 0;
					if (count > 0) {
						var oldCount = node.Children.Count;
						result = await node.LoadChildrenAsync (count, cancellationToken);

						// if any of them are still evaluating register for
						// a completion event so that we can tell the UI
						for (int i = oldCount; i < oldCount + result; i++) {
							var c = node.Children[i];
							RegisterNode (c);
						}
					} else {
						result = await node.LoadChildrenAsync (cancellationToken);

						// if any of them are still evaluating register for
						// a completion event so that we can tell the UI
						foreach (var c in node.Children) {
							RegisterNode (c);
						}
					}

					return result;
				} finally {
					childFetchTasks.Remove (node);
				}
			} catch (Exception ex) {
				LoggingService.LogInternalError (ex);
			}

			return 0;
		}
		#endregion

		#region Evaluation watches
		/// <summary>
		/// Registers the ValueChanged event for a node where IsEvaluating is true. If the node is not evaluating, and
		/// sendImmediatelyIfNotEvaluating is true, then fire OnEvaluatingNodeValueChanged immediately 
		/// </summary>
		void RegisterForEvaluationCompletion (ObjectValueNode node, bool sendImmediatelyIfNotEvaluating = false)
		{
			if (node.IsEvaluating) {
				evaluationWatches[node] = null;
				node.ValueChanged += OnEvaluatingNodeValueChanged;
			} else if (sendImmediatelyIfNotEvaluating) {
				OnEvaluatingNodeValueChanged (node, EventArgs.Empty);
			}
		}

		/// <summary>
		/// Removes the ValueChanged handler from the node
		/// </summary>
		void UnregisterForEvaluationCompletion (ObjectValueNode node)
		{
			if (node != null) {
				node.ValueChanged -= OnEvaluatingNodeValueChanged;
				evaluationWatches.Remove (node);
			}
		}

		/// <summary>
		/// Removes all ValueChanged handlers for evaluating nodes
		/// </summary>
		void ClearEvaluationCompletionRegistrations ()
		{
			foreach (var node in evaluationWatches.Keys) {
				node.ValueChanged -= OnEvaluatingNodeValueChanged;
			}

			evaluationWatches.Clear ();
		}

		#endregion

		protected virtual IDebuggerService OnGetDebuggerService ()
		{
			return new ObjectValueDebuggerService ();
		}

		/// <summary>
		/// Registers the node in the index and sets a watch for evaluating nodes
		/// </summary>
		void RegisterNode (ObjectValueNode node)
		{
			if (node != null) {
				RegisterForEvaluationCompletion (node);
			}
		}

		void UnregisterNode (ObjectValueNode node)
		{
			if (node != null) {
				UnregisterForEvaluationCompletion (node);
			}
		}

		/// <summary>
		/// Creates a checkpoint of the value of the node and any children that are expanded
		/// </summary>
		void ChangeCheckpoint (ObjectValueNode node)
		{
			oldValues[node.Path] = new CheckpointState (node);

			if (node.IsExpanded) {
				foreach (var child in node.Children) {
					ChangeCheckpoint (child);
				}
			}
		}

		#region Event triggers
		void OnChildrenLoaded (ObjectValueNode node, int index, int count)
		{
			Runtime.RunInMainThread (() => {
				view.LoadNodeChildren (node, index, count);
			}).Ignore ();
		}

		/// <summary>
		/// Triggered in response to ValueChanged on a node
		/// </summary>
		void OnEvaluatingNodeValueChanged (object sender, EventArgs e)
		{
			if (sender is ObjectValueNode node) {
				UnregisterForEvaluationCompletion (node);

				if (sender is IEvaluatingGroupObjectValueNode evalGroupNode) {
					if (evalGroupNode.IsEvaluatingGroup) {
						var replacementNodes = evalGroupNode.GetEvaluationGroupReplacementNodes ();

						foreach (var newNode in replacementNodes) {
							RegisterNode (newNode);
						}

						OnEvaluationCompleted (sender as ObjectValueNode, replacementNodes);
					} else {
						OnEvaluationCompleted (sender as ObjectValueNode);
					}
				} else {
					OnEvaluationCompleted (sender as ObjectValueNode);
				}
			}
		}

		void OnEvaluationCompleted (ObjectValueNode node)
		{
			Runtime.RunInMainThread (() => {
				view.LoadEvaluatedNode (node, new ObjectValueNode[] { node });
			}).Ignore ();
		}

		void OnEvaluationCompleted (ObjectValueNode node, ObjectValueNode[] replacementNodes)
		{
			// `node` returns us a set of new nodes that need to be replaced into the children
			// of node.parent. This should only be applicable to direct children of the root since
			// this construct is to support placehold values for "locals" etc
			if (node.Parent is ISupportChildObjectValueNodeReplacement replacerParent) {
				replacerParent.ReplaceChildNode (node, replacementNodes);
			}

			Runtime.RunInMainThread (() => {
				view.LoadEvaluatedNode (node, replacementNodes);
			}).Ignore ();
		}
		#endregion

		class CheckpointState
		{
			public CheckpointState (ObjectValueNode node)
			{
				Expanded = node.IsExpanded;
				Value = node.Value;
			}

			public bool Expanded { get; set; }
			public string Value { get; set; }
		}

		public static string GetIcon (ObjectValueFlags flags)
		{
			if ((flags & ObjectValueFlags.Field) != 0 && (flags & ObjectValueFlags.ReadOnly) != 0)
				return "md-literal";

			string global = (flags & ObjectValueFlags.Global) != 0 ? "static-" : string.Empty;
			string source;

			switch (flags & ObjectValueFlags.OriginMask) {
			case ObjectValueFlags.Property: source = "property"; break;
			case ObjectValueFlags.Type: source = "class"; global = string.Empty; break;
			case ObjectValueFlags.Method: source = "method"; break;
			case ObjectValueFlags.Literal: return "md-literal";
			case ObjectValueFlags.Namespace: return "md-name-space";
			case ObjectValueFlags.Group: return "md-open-resource-folder";
			case ObjectValueFlags.Field: source = "field"; break;
			case ObjectValueFlags.Variable: return "md-variable";
			default: return "md-empty";
			}

			string access;
			switch (flags & ObjectValueFlags.AccessMask) {
			case ObjectValueFlags.Private: access = "private-"; break;
			case ObjectValueFlags.Internal: access = "internal-"; break;
			case ObjectValueFlags.InternalProtected:
			case ObjectValueFlags.Protected: access = "protected-"; break;
			default: access = string.Empty; break;
			}

			return "md-" + access + global + source;
		}

		public static string GetPreviewButtonIcon (PreviewButtonIcon icon)
		{
			switch (icon) {
			case PreviewButtonIcon.Hidden: return "md-empty";
			case PreviewButtonIcon.RowHover: return "md-preview-normal";
			case PreviewButtonIcon.Hover: return "md-preview-hover";
			case PreviewButtonIcon.Active: return "md-preview-active";
			case PreviewButtonIcon.Selected: return "md-preview-selected";
			default: return null;
			}
		}
	}

	#region Extension methods and helpers
	/// <summary>
	/// Helper class to mimic existing API
	/// </summary>
	public static class ObjectValueTreeViewControllerExtensions
	{
		public static void SetStackFrame (this ObjectValueTreeViewController controller, StackFrame frame)
		{
			controller.Frame = new ProxyStackFrame (frame);
		}

		public static StackFrame GetStackFrame (this ObjectValueTreeViewController controller)
		{
			return (controller.Frame as ProxyStackFrame)?.StackFrame;
		}

		public static StackFrame GetStackFrame (this IStackFrame frame)
		{
			return (frame as ProxyStackFrame)?.StackFrame;
		}

		public static void AddValue (this ObjectValueTreeViewController controller, ObjectValue value)
		{
			controller.AddValue (new DebuggerObjectValueNode (value));
		}

		public static void AddValues (this ObjectValueTreeViewController controller, IEnumerable<ObjectValue> values)
		{
			controller.AddValues (values.Select (value => new DebuggerObjectValueNode (value)));
		}

		public static string[] GetExpressions (this ObjectValueTreeViewController controller)
		{
			// given that expressions are only supported by themselves (ie not mixed with locals for example)
			// and they are all children of the root, we can mimic a list of expressions by just grabbing the
			// name property of the root children
			if (controller.Root == null)
				return new string[0];

			return controller.Root.Children.Select (c => c.Name).ToArray ();
		}
	}

	public static class ObjectValueNodeExtensions
	{
		public static string GetDisplayValue (this ObjectValueNode node)
		{
			if (node.DisplayValue == null)
				return "(null)";

			if (node.DisplayValue.Length > 1000) {
				// Truncate the string to stop the UI from hanging
				// when calculating the size for very large amounts
				// of text.
				return node.DisplayValue.Substring (0, 1000) + "…";
			}

			return node.DisplayValue;
		}

		public static ObjectValue GetDebuggerObjectValue (this ObjectValueNode node)
		{
			if (node != null && node is DebuggerObjectValueNode val) {
				return val.DebuggerObject;
			}

			return null;
		}

		public static bool GetIsEvaluatingGroup (this ObjectValueNode node)
		{
			return (node is IEvaluatingGroupObjectValueNode evg && evg.IsEvaluatingGroup);
		}

		public static string GetInlineVisualisation (this ObjectValueNode node)
		{
			// TODO: this is not possible to mock as it is
			if (node is DebuggerObjectValueNode val) {
				return DebuggingService.GetInlineVisualizer (val.DebuggerObject).InlineVisualize (val.DebuggerObject);
			}

			return node.GetDisplayValue ();
		}
	}
	#endregion
}