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

PropertiesViewModel.cs « ViewModels « Xamarin.PropertyEditing - github.com/xamarin/Xamarin.PropertyEditing.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 40f8c62e96c6c897d5e86e71b15f2ecb88f4752c (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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.PropertyEditing.Drawing;

namespace Xamarin.PropertyEditing.ViewModels
{
	internal abstract class PropertiesViewModel
		: NotifyingObject, INotifyDataErrorInfo
	{
		public PropertiesViewModel (TargetPlatform targetPlatform)
		{
			if (targetPlatform == null)
				throw new ArgumentNullException (nameof(targetPlatform));

			TargetPlatform = targetPlatform;

			this.selectedObjects.CollectionChanged += OnSelectedObjectsChanged;
		}

		public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

		public IResourceProvider ResourceProvider
		{
			get { return this.resourceProvider; }
			set
			{
				if (this.resourceProvider == value)
					return;

				this.resourceProvider = value;
				UpdateResourceProvider();
				OnPropertyChanged();
			}
		}

		/// <remarks>Consumers should check for <see cref="INotifyCollectionChanged"/> and hook appropriately.</remarks>
		public IReadOnlyList<EditorViewModel> Properties => this.editors;

		public IReadOnlyList<EventViewModel> Events => this.events;

		public ICollection<object> SelectedObjects => this.selectedObjects;

		public string TypeName
		{
			get { return this.typeName; }
			private set
			{
				if (this.typeName == value)
					return;

				this.typeName = value;
				OnPropertyChanged ();
			}
		}

		public bool IsObjectNameable => this.nameable != null;

		public bool IsObjectNameReadOnly
		{
			get { return this.nameReadOnly; }
			private set
			{
				if (this.nameReadOnly == value)
					return;

				this.nameReadOnly = value;
				OnPropertyChanged ();
			}
		}

		public string ObjectName
		{
			get { return this.objectName; }
			set
			{
				if (this.objectName == value)
					return;

				SetObjectName (value);
			}
		}

		public bool EventsEnabled
		{
			get { return this.eventsEnabled; }
			private set
			{
				if (this.eventsEnabled == value)
					return;

				this.eventsEnabled = value;
				OnPropertyChanged ();
			}
		}

		public TargetPlatform TargetPlatform
		{
			get;
		}

		public bool HasErrors => this.errors.IsValueCreated && this.errors.Value.Count > 0;

		protected IReadOnlyList<IObjectEditor> ObjectEditors => this.objEditors;

		public IEnumerable GetErrors (string propertyName)
		{
			if (!this.errors.IsValueCreated)
				return Enumerable.Empty<string> ();

			string error;
			if (this.errors.Value.TryGetValue (propertyName, out error))
				return new[] { error };

			return Enumerable.Empty<string> ();
		}

		/// <param name="newError">The error message or <c>null</c> to clear the error.</param>
		protected void SetError (string property, string newError)
		{
			if (this.errors.IsValueCreated) {
				string prevError;
				if (this.errors.Value.TryGetValue (property, out prevError)) {
					if (prevError == newError)
						return;
				}
			}

			if (newError == null)
				this.errors.Value.Remove (property);
			else
				this.errors.Value[property] = newError;

			OnErrorsChanged (new DataErrorsChangedEventArgs (property));
		}

		// TODO: Consider having the property hooks at the top level and a map of IPropertyInfo -> PropertyViewModel
		// the hash lookup would be likely faster than doing a property info compare in every property and would
		// reduce the number event attach/detatches

		protected virtual async void OnSelectedObjectsChanged (object sender, NotifyCollectionChangedEventArgs e)
		{
			var tcs = new TaskCompletionSource<bool> ();
			var existingTask = Interlocked.Exchange (ref this.busyTask, tcs.Task);
			if (existingTask != null)
				await existingTask;

			IObjectEditor[] newEditors = null;
			IObjectEditor[] removedEditors = null;

			switch (e.Action) {
				case NotifyCollectionChangedAction.Add: {
					newEditors = await AddEditorsAsync (e.NewItems);
					break;
				}

				case NotifyCollectionChangedAction.Remove:
					removedEditors = new IObjectEditor[e.OldItems.Count];
					for (int i = 0; i < e.OldItems.Count; i++) {
						IObjectEditor editor = this.objEditors.First (oe => oe?.Target == e.OldItems[i]);
						INotifyCollectionChanged notifier = editor.Properties as INotifyCollectionChanged;
						if (notifier != null)
							notifier.CollectionChanged -= OnObjectEditorPropertiesChanged;

						removedEditors[i] = editor;
						this.objEditors.Remove (editor);
					}
					break;

				case NotifyCollectionChangedAction.Replace:
				case NotifyCollectionChangedAction.Move:
				case NotifyCollectionChangedAction.Reset: {
					removedEditors = new IObjectEditor[this.objEditors.Count];
					for (int i = 0; i < removedEditors.Length; i++) {
						removedEditors[i] = this.objEditors[i];
						INotifyCollectionChanged notifier = removedEditors[i]?.Properties as INotifyCollectionChanged;
						if (notifier != null)
							notifier.CollectionChanged -= OnObjectEditorPropertiesChanged;
					}

					this.objEditors.Clear ();

					newEditors = await AddEditorsAsync (this.selectedObjects);
					break;
				}
			}

			UpdateMembers (removedEditors, newEditors);
			tcs.SetResult (true);
		}

		protected virtual void OnAddEditors (IEnumerable<EditorViewModel> editors)
		{
		}

		protected virtual void OnRemoveEditors (IEnumerable<EditorViewModel> editors)
		{
		}

		protected virtual void OnClearProperties()
		{
		}

		private IResourceProvider resourceProvider;
		private INameableObject nameable;
		private bool nameReadOnly;
		private bool eventsEnabled;
		private string typeName, objectName;
		private readonly List<IObjectEditor> objEditors = new List<IObjectEditor> ();
		private readonly ObservableCollectionEx<EditorViewModel> editors = new ObservableCollectionEx<EditorViewModel> ();
		private readonly ObservableCollectionEx<object> selectedObjects = new ObservableCollectionEx<object> ();
		private readonly ObservableCollectionEx<EventViewModel> events = new ObservableCollectionEx<EventViewModel> (); 
		private readonly Lazy<Dictionary<string, string>> errors = new Lazy<Dictionary<string, string>>();

		private void OnErrorsChanged (DataErrorsChangedEventArgs e)
		{
			ErrorsChanged?.Invoke (this, e);
		}

		private void AddProperties (IEnumerable<EditorViewModel> newEditors)
		{
			this.editors.AddRange (newEditors);
			OnAddEditors (newEditors);
		}

		private void RemoveProperties (IEnumerable<EditorViewModel> oldEditors)
		{
			this.editors.RemoveRange (oldEditors);
			OnRemoveEditors (oldEditors);
		}

		private async void SetObjectName (string value)
		{
			if (this.nameable == null)
				return;

			try {
				await this.nameable.SetNameAsync (value);
			} catch (Exception ex) {
				AggregateException aggregate = ex as AggregateException;
				if (aggregate != null) {
					aggregate = aggregate.Flatten ();
					ex = aggregate.InnerExceptions[0];
				}

				SetError (nameof(ObjectName), ex.ToString());
			} finally {
				SetCurrentObjectName (value, isReadonly: false);
			}
		}

		private void SetNameable (INameableObject nameable)
		{
			this.nameable = nameable;
			OnPropertyChanged (nameof (IsObjectNameable));
		}

		private void SetCurrentObjectName (string value, bool isReadonly)
		{
			IsObjectNameReadOnly = isReadonly;
			this.objectName = value;
			OnPropertyChanged (nameof (ObjectName));
		}

		private void ClearMembers()
		{
			TypeName = null;
			SetNameable (null);
			SetCurrentObjectName (null, isReadonly: true);
			this.editors.Clear ();
			this.events.Clear ();
			OnClearProperties ();
		}

		private void UpdateMembers (IObjectEditor[] removedEditors = null, IObjectEditor[] newEditors = null)
		{
			if (this.objEditors.Count == 0) {
				ClearMembers ();
				return;
			}

			IObjectEditor editor = this.objEditors[0];

			Task<string> nameQuery = null;
			INameableObject firstNameable = editor as INameableObject;
			if (this.objEditors.Count == 1) {
				nameQuery = firstNameable?.GetNameAsync ();
			}

			IObjectEventEditor events = editor as IObjectEventEditor;
			var newEventSet = new HashSet<IEventInfo> (events?.Events ?? Enumerable.Empty<IEventInfo> ());

			bool knownProperties = (editor?.KnownProperties?.Count ?? 0) > 0;
			string newTypeName = editor?.TargetType.Name;
			var newPropertySet = new HashSet<IPropertyInfo> (editor?.Properties ?? Enumerable.Empty<IPropertyInfo>());
			for (int i = 1; i < this.objEditors.Count; i++) {
				editor = this.objEditors[i];
				if (editor == null)
					continue;

				newPropertySet.IntersectWith (editor.Properties);

				if (editor is IObjectEventEditor) {
					events = (IObjectEventEditor)editor;
					newEventSet.IntersectWith (events.Events);
				}

				if (firstNameable == null)
					firstNameable = editor as INameableObject;

				if (newTypeName != editor.TargetType.Name)
					newTypeName = String.Format (PropertyEditing.Properties.Resources.MultipleTypesSelected, this.objEditors.Count);
			}

			TypeName = newTypeName;

			UpdateProperties (newPropertySet, removedEditors, newEditors);

			EventsEnabled = events != null;
			UpdateEvents (newEventSet, removedEditors, newEditors);

			string name = (this.objEditors.Count > 1) ? String.Format (PropertyEditing.Properties.Resources.MultipleObjectsSelected, this.objEditors.Count) : PropertyEditing.Properties.Resources.NoName;
			if (this.objEditors.Count == 1) {
				string tname = nameQuery?.Result;
				if (tname != null)
					name = tname;
			}

			SetNameable (firstNameable);
			SetCurrentObjectName (name, this.objEditors.Count > 1);
		}

		private void UpdateEvents (HashSet<IEventInfo> newSet, IObjectEditor[] removedEditors = null, IObjectEditor[] newEditors = null)
		{
			if (this.objEditors.Count > 1) {
				this.events.Clear ();
				return;
			}

			var toRemove = new List<EventViewModel> ();
			foreach (EventViewModel vm in this.events.ToArray ()) {
				if (!newSet.Remove (vm.Event)) {
					toRemove.Add (vm);
					vm.Editors.Clear ();
					continue;
				}

				if (removedEditors != null) {
					for (int i = 0; i < removedEditors.Length; i++)
						vm.Editors.Remove (removedEditors[i]);
				}

				if (newEditors != null) {
					for (int i = 0; i < newEditors.Length; i++)
						vm.Editors.Add (newEditors[i]);
				}
			}

			if (toRemove.Count > 0)
				this.events.RemoveRange (toRemove);
			if (newSet.Count > 0) {
				this.events.Reset (this.events.Concat (newSet.Select (i => new EventViewModel (TargetPlatform, i, this.objEditors))).OrderBy (e => e.Event.Name).ToArray());
			}
		}

		private void UpdateProperties (HashSet<IPropertyInfo> newSet, IObjectEditor[] removedEditors = null, IObjectEditor[] newEditors = null)
		{
			List<PropertyViewModel> toRemove = new List<PropertyViewModel> ();
			foreach (PropertyViewModel vm in this.editors.ToArray ()) {
				if (!newSet.Remove (vm.Property)) {
					toRemove.Add (vm);
					vm.Editors.Clear ();
					continue;
				}

				if (removedEditors != null) {
					for (int i = 0; i < removedEditors.Length; i++)
						vm.Editors.Remove (removedEditors[i]);
				}

				if (newEditors != null) {
					for (int i = 0; i < newEditors.Length; i++)
						vm.Editors.Add (newEditors[i]);
				}
			}

			if (toRemove.Count > 0)
				RemoveProperties (toRemove);
			if (newSet.Count > 0)
				AddProperties (newSet.Select (GetViewModel));
		}

		private async Task<IObjectEditor[]> AddEditorsAsync (IList newItems)
		{
			Task<IObjectEditor>[] newEditorTasks = new Task<IObjectEditor>[newItems.Count];
			for (int i = 0; i < newEditorTasks.Length; i++) {
				newEditorTasks[i] = TargetPlatform.EditorProvider.GetObjectEditorAsync (newItems[i]);
			}

			IObjectEditor[] newEditors = await Task.WhenAll (newEditorTasks);
			for (int i = 0; i < newEditors.Length; i++) {
				IObjectEditor editor = newEditors[i];
				if (editor == null)
					continue;

				var notifier = editor.Properties as INotifyCollectionChanged;
				if (notifier != null)
					notifier.CollectionChanged += OnObjectEditorPropertiesChanged;
			}

			this.objEditors.AddRange (newEditors);
			return newEditors;
		}

		private void UpdateResourceProvider()
		{
			foreach (PropertyViewModel vm in this.editors) {
				vm.ResourceProvider = this.resourceProvider;
			}
		}

		private void OnObjectEditorPropertiesChanged (object sender, NotifyCollectionChangedEventArgs e)
		{
			UpdateMembers();
		}

		private PropertyViewModel GetViewModel (IPropertyInfo property)
		{
			var vm = GetViewModelCore (property);
			vm.ResourceProvider = ResourceProvider;
			return vm;
		}

		private PropertyViewModel GetViewModelCore (IPropertyInfo property)
		{
			Type[] interfaces = property.GetType ().GetInterfaces ();

			Type hasPredefinedValues = interfaces.FirstOrDefault (t => t.IsGenericType && t.GetGenericTypeDefinition () == typeof(IHavePredefinedValues<>));
			if (hasPredefinedValues != null) {
				bool combinable = (bool) hasPredefinedValues.GetProperty (nameof(IHavePredefinedValues<bool>.IsValueCombinable)).GetValue (property);
				Type type = combinable
					? typeof(CombinablePropertyViewModel<>).MakeGenericType (hasPredefinedValues.GenericTypeArguments[0])
					: typeof(PredefinedValuesViewModel<>).MakeGenericType (hasPredefinedValues.GenericTypeArguments[0]);

				return (PropertyViewModel) Activator.CreateInstance (type, TargetPlatform, property, this.objEditors);
			}

			if (ViewModelMap.TryGetValue (property.Type, out var vmFactory))
				return vmFactory (TargetPlatform, property, this.objEditors);
			
			return new StringPropertyViewModel (TargetPlatform, property, this.objEditors);
		}

		private Task busyTask;

		private static readonly Dictionary<Type, Func<TargetPlatform, IPropertyInfo, IEnumerable<IObjectEditor>, PropertyViewModel>> ViewModelMap = new Dictionary<Type, Func<TargetPlatform, IPropertyInfo, IEnumerable<IObjectEditor>, PropertyViewModel>> {
			{ typeof(string), (tp,p,e) => new StringPropertyViewModel (tp, p, e) },
			{ typeof(bool), (tp,p,e) => new PropertyViewModel<bool?> (tp, p, e) },
			{ typeof(float), (tp,p,e) => new NumericPropertyViewModel<float?> (tp, p, e) },
			{ typeof(double), (tp,p,e) => new NumericPropertyViewModel<double?> (tp, p, e) },
			{ typeof(int), (tp,p,e) => new NumericPropertyViewModel<int?> (tp, p, e) },
			{ typeof(long), (tp,p,e) => new NumericPropertyViewModel<long?> (tp, p, e) },
			{ typeof(CommonSolidBrush), (tp,p,e) => new BrushPropertyViewModel(tp, p, e, new[] {CommonBrushType.NoBrush, CommonBrushType.Solid, CommonBrushType.MaterialDesign, CommonBrushType.Resource }) },
			{ typeof(CommonColor), (tp,p,e) => new BrushPropertyViewModel(tp, p, e, new[] {CommonBrushType.NoBrush, CommonBrushType.Solid, CommonBrushType.MaterialDesign, CommonBrushType.Resource }) },
			{ typeof(CommonBrush), (tp,p,e) => new BrushPropertyViewModel(tp, p, e) },
			{ typeof(CommonPoint), (tp,p,e) => new PointPropertyViewModel (tp, p, e) },
			{ typeof(CommonSize), (tp,p,e) => new SizePropertyViewModel (tp, p, e) },
			{ typeof(CommonRectangle), (tp,p,e) => new RectanglePropertyViewModel (tp, p, e) },
			{ typeof(CommonThickness), (tp,p,e) => new ThicknessPropertyViewModel (tp, p, e) },
			{ typeof(IList), (tp,p,e) => new CollectionPropertyViewModel (tp,p,e) },
			{ typeof(object), (tp,p,e) => new ObjectPropertyViewModel (tp,p,e) },
		};
	}
}