From 730174b6ffc6cd6627ef7262fb65c4743e2dd7ff Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 6 Jan 2022 18:30:00 -0500 Subject: [PATCH] Support multiple props w/ same name in detect_property_changes It is possible for a type to have multiple properties with the same name if that type is a reference type that inherits from a parent type, and hides one of the parent types properties with the 'new' keyword --- .../spark/core/Utility/ViewModelBase.cs | 1784 ++++++++--------- 1 file changed, 892 insertions(+), 892 deletions(-) diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index 945b1570c..1dab27f68 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -1,892 +1,892 @@ -using bts.collections; - -using mbts.ui.utility; -using mbts.utils; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Linq; -using System.Linq.Expressions; -using System.Reactive.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using System.Windows.Input; - -namespace mbts.ui.shell { - interface IRaiseNotifyPropertyChanged { - void raise_notify_property_changed(string prop); - } - - interface IValidationViewModel : IRaiseNotifyPropertyChanged { - void set_error(string property, string message); - void clear_error(string property); - } - - interface IProperty : IObservable<(T oldval, T newval)> { - event PropertyChange Changing, Changed; - T Value { get; set; } - } - - interface IUserProperty : IProperty { - bool setter_called { get; } - void bypass_setter(T value); - } - - public delegate void PropertyChange(T oldval, T newval); - - static class ValidationViewModelExtensions { - public static void assert(this IValidationViewModel vm, bool condition, string property, string message) { - if (condition) vm.clear_error(property); - else vm.set_error(property, message); - } - - public static IObservable subscribe_has_errors(this INotifyDataErrorInfo vm, bool start_immediately = false) => - Observable.Create(o => { - bool last_value = vm.HasErrors; - if (start_immediately) - o.OnNext(vm.HasErrors); - vm.ErrorsChanged += on_errors_changed; - return Disposable.Create(() => vm.ErrorsChanged -= on_errors_changed); - void on_errors_changed(object sender, DataErrorsChangedEventArgs e) { - if (vm.HasErrors != last_value) - o.OnNext(last_value = !last_value); - } - }); - - public static IObservable SubscribeValue(this IProperty property) => - // ensure notifications will be in on the same thread as IProperty.Subscribe (don't use .Select extension) - Observable.Create(o => property.Subscribe(ch => o.OnNext(ch.newval))); - - public static IProperty block_reentrancy(this IProperty source) => - new GatedPropertyWrapper(source); - - /// Blocks re-entrancy in setter. - class GatedPropertyWrapper : IProperty { - bool _is_updating; - readonly IProperty _source; - - public GatedPropertyWrapper(IProperty source) => - _source = source; - - public event PropertyChange Changing { add => _source.Changing += value; remove => _source.Changing -= value; } - public event PropertyChange Changed { add => _source.Changed += value; remove => _source.Changed -= value; } - - public T Value { - get => _source.Value; - set { - if (!_is_updating) { - _is_updating = true; - _source.Value = value; - _is_updating = false; - } - } - } - - public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _source.Subscribe(observer); - } - } - - public class ViewModelBase : INotifyPropertyChanged, IRaiseNotifyPropertyChanged { - public ViewModelBase() { - _props = new Lazy(() => { - return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); - }); - } - protected void RaisePropertyChanged([CallerMemberName] string property = "") { - if (PropertyChanged != null) { - PropertyChanged(this, new PropertyChangedEventArgs(property)); - } - } - - protected void RaisePropertyChanged(params string[] properties) { - if (PropertyChanged != null) { - foreach (var prop in properties) { RaisePropertyChanged(prop); } - } - } - - void IRaiseNotifyPropertyChanged.raise_notify_property_changed(string prop) => - RaisePropertyChanged(prop); - - protected bool Set(ref T backing, T value, [CallerMemberName] string name = "") => - Set(ref backing, value, EqualityComparer.Default, name); - - protected bool Set(ref T backing, T value, [CallerMemberName] string name = "", params string[] dependent_props) { - if (Set(ref backing, value, EqualityComparer.Default, name)) { - RaisePropertyChanged(dependent_props); - return true; - } - return false; - } - - protected bool Set(ref T backing, T value, IEqualityComparer comparer, [CallerMemberName] string name = "") { - if (!comparer.Equals(backing, value)) { - backing = value; - RaisePropertyChanged(name); - return true; - } - return false; - } - - protected bool Set(ref T backing, T value, out T old_value, [CallerMemberName] string name = "") => - Set(ref backing, value, out old_value, EqualityComparer.Default, name); - - protected bool Set(ref T backing, T value, out T old_value, IEqualityComparer comparer, [CallerMemberName] string name = "") { - old_value = backing; - if (!comparer.Equals(backing, value)) { - backing = value; - RaisePropertyChanged(name); - return true; - } - return false; - } - - public event PropertyChangedEventHandler PropertyChanged; - - private Lazy _props; - - - #region Object Diffing - public interface IObjSnapshot : IDisposable { - bool revert { get; set; } - } - - public class ObjSnapshot : IObjSnapshot { - readonly ViewModelBase _target; - readonly Dictionary _snapshot; - readonly IReadOnlyList _props; - - public ObjSnapshot(ViewModelBase viewModelBase, IReadOnlyList props) { - _target = viewModelBase; - _props = props; - _snapshot = snap(); - } - - public bool revert { get; set; } - - public void Dispose() { - var cur = snap(); - foreach (var kv in cur) { - object oldv = _snapshot[kv.Key]; - object newv = cur[kv.Key]; - if (!Equals(oldv, newv)) { - var prop = kv.Key.property; - if (revert && prop.CanWrite) - prop.SetValue(_target, oldv); - _target.RaisePropertyChanged(prop.Name); - } - } - } - - Dictionary snap() => - // NOTE: in the future we can optimize prop.GetValue() if needed - _props.ToDictionary(prop => new PropertyKeyWrapper(prop), prop => prop.GetValue(_target)); - - private class PropertyKeyWrapper : IEquatable { - public readonly PropertyInfo property; - public PropertyKeyWrapper(PropertyInfo property) => this.property = property; - public bool Equals(PropertyKeyWrapper other) => other != null && other.property.Name == property.Name; - public override bool Equals(object obj) => Equals(obj as PropertyKeyWrapper); - public override int GetHashCode() => property.Name.GetHashCode(); - } - } - - // Automatic (but shallow) property change notifications based on local object modifications - public ObjSnapshot detect_property_changes(params string[] props) { - if (props.Length == 0) return new ObjSnapshot(this, _props.Value); - else return new ObjSnapshot(this, _props.Value.Intersect(props, p => p.Name).ToList()); - } - - public ObjSnapshot detect_property_changes_except(params string[] props) { - if (props.Length == 0) return new ObjSnapshot(this, _props.Value); - else return new ObjSnapshot(this, _props.Value.Except(props, p => p.Name).ToList()); - } - #endregion - - #region automatic property - // use nameof() to add compile time checks - protected Property backing(string name, T default_value = default(T)) => - backing(name, EqualityComparer.Default, default_value); - - protected Property backing(string name, IEqualityComparer comparer, T default_value = default(T)) { - return new Property(this, name, comparer, default_value); - } - - protected Property backing(Expression> member, T default_value) { - var exp = (MemberExpression)member.Body; - return new Property(this, exp.Member.Name, default_value); - } - - // WILL invoke the get_value delegate - protected DelegateProperty backing(string name, Func get_value, params string[] invalidating_props) { - return new DelegateProperty(this, name, get_value, invalidating_props); - } - - // will NOT invoke the get_value delegate - protected DelegateProperty backing(string name, Func get_value, T default_value, params string[] invalidating_props) => - new DelegateProperty(this, name, get_value, default_value, invalidating_props); - - protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert) => - new PropertyAutoWrapper(this, name, initial_model, convert, EqualityComparer.Default); - - protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert, IEqualityComparer comparer) => - new PropertyAutoWrapper(this, name, initial_model, convert, comparer); - - protected DelegatePropertyAutoWrapper backing(string name, Func get_model, Func convert) => - new DelegatePropertyAutoWrapper(this, name, get_model, convert, EqualityComparer.Default); - - protected class Property : IProperty { - readonly string _propname; - readonly IEqualityComparer _comparer; - readonly ViewModelBase _owner; - T _value; - - public Property(ViewModelBase owner, string name, T default_value) - : this(owner, name, EqualityComparer.Default, default_value) { } - - public Property(ViewModelBase owner, string name, IEqualityComparer comparer, T default_value) { - _owner = owner; - _propname = name; - _comparer = comparer; - _value = default_value; - } - - public event PropertyChange Changing, Changed; - - public string name => _propname; - - public void set(T value) => - set_new(value); - - public bool set_new(T value) { - if (!Equals(value, _value)) { - Changing?.Invoke(_value, value); - var old = _value; - _value = value; - Changed?.Invoke(old, value); - _owner.RaisePropertyChanged(_propname); - return true; - } - return false; - } - - public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => - Subscribe((oldval, newval) => observer.OnNext((oldval, newval))); - - public IDisposable Subscribe(PropertyChange callback) { - Changed += callback; - return Disposable.Create(() => Changed -= callback); - } - - public IObservable observe_current(bool start_immediately = false) { - var source = this.Select(vals => vals.newval); - if (start_immediately) - source = source.StartWith(() => _value); - return source; - } - - public T Value { - get { return _value; } - set { set(value); } - } - } - - protected class DelegateProperty : Property { - public DelegateProperty(ViewModelBase owner, string name, Func get_value, params string[] invalidating_props) - : this(owner, name, get_value, get_value(), invalidating_props) { } - - public DelegateProperty(ViewModelBase owner, string name, Func get_value, T default_value, params string[] invalidating_props) - : base(owner, name, default_value) { - _get_value = get_value; - if (invalidating_props != null && invalidating_props.Length > 0) { - var iprop_set = new HashSet(invalidating_props); - owner.PropertyChanged += (s, e) => { - if (iprop_set.Contains(e.PropertyName)) - refresh(); - }; - } - } - - readonly Func _get_value; - - public void refresh() => set(_get_value()); - public bool refresh_new() => set_new(_get_value()); - } - - /// - /// Inspired by ObservableAutoWrapper, a read/write TModel property is used to create a readonly TView property. - /// - protected class PropertyAutoWrapper : IObservable<((TModel model, TView view) oldval, (TModel model, TView view) newval)> { - readonly ViewModelBase _owner; - readonly Func _convert; - readonly IEqualityComparer _comparer; - readonly string _prop_name; - TModel _model; - TView _view; - - public PropertyAutoWrapper(ViewModelBase owner, string name, TModel initial_value, Func convert, IEqualityComparer comparer) { - _owner = owner; - _prop_name = name; - _model = initial_value; - _convert = convert; - _comparer = comparer; - _view = convert(_model); - } - - public event PropertyChange<(TModel model, TView view)> changing, changed; - - public string name => _prop_name; - public TModel model { get => _model; set => set(value); } - public TView view => _view; - - public void set(TModel model) => - set_new(model); - - public bool set_new(TModel model) { - if (_comparer.Equals(model, _model)) - return false; - TView new_view = _convert(model); - changing?.Invoke((_model, _view), (model, new_view)); - TView old_view = _view; - TModel old_model = _model; - _model = model; - _view = new_view; - changed?.Invoke((old_model, old_view), (_model, _view)); - _owner.RaisePropertyChanged(_prop_name); - return true; - } - - public IDisposable Subscribe(IObserver<((TModel model, TView view) oldval, (TModel model, TView view) newval)> observer) { - changed += pch; - return Disposable.Create(() => changed -= pch); - void pch((TModel, TView) o, (TModel, TView) n) => observer.OnNext((o, n)); - } - - public IObservable<(TModel model, TView view)> observe_current(bool start_immediately = false) { - var source = this.Select(vals => vals.newval); - if (start_immediately) - source = source.StartWith((_model, _view)); - return source; - } - } - - protected class DelegatePropertyAutoWrapper : PropertyAutoWrapper { - readonly Func _get_model; - - public DelegatePropertyAutoWrapper(ViewModelBase owner, string name, Func get_model, Func convert, IEqualityComparer comparer) - : base(owner, name, get_model(), convert, comparer) => _get_model = get_model; - - public void refresh() => set(_get_model()); - } - - /// - /// A thin wrapper around Property<T> that trips a 'setter_called' flag when the value is set through value-property-setter (i.e., through User interaction). - /// Note: This is class is particularly useful when a default/settings-based value arrives late, and the viewmodel must decide whether or not to override the current value. - /// - protected class UserProperty : IUserProperty { - readonly Property _prop_model; - - public UserProperty(Property prop_model) => - _prop_model = prop_model; - - public event PropertyChange Changing { add { _prop_model.Changing += value; } remove { _prop_model.Changing -= value; } } - public event PropertyChange Changed { add { _prop_model.Changed += value; } remove { _prop_model.Changed -= value; } } - - public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _prop_model.Subscribe(observer); - public IObservable observe_current(bool start_immediately = false) => _prop_model.observe_current(start_immediately); - - public T Value { - get => _prop_model.Value; - set { - setter_called = true; - _prop_model.set(value); - } - } - public bool setter_called { get; private set; } - - /// - /// Sets the value without tripping the 'setter_called' flag. - /// - public void bypass_setter(T value) => _prop_model.set(value); - /// - /// Sets 'setter_called' to false. - /// - public void reset() => setter_called = false; - - public void on_inline_prop(InlineUserProperty inline_prop) { - if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) - bypass_setter(inline_prop.value); - } - - public void on_inline_prop(InlineUserProperty inline_prop, Func select) { - if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) - bypass_setter(select(inline_prop.value)); - } - } - - #endregion - - protected class ObservablePropertySink : Property, IObserver { - public ObservablePropertySink(ViewModelBase owner, string name, T default_val) : base(owner, name, default_val) { } - public void OnCompleted() { } - public void OnError(Exception error) { } - - public void OnNext(T value) { set(value); } - } - } - - public class RequestViewCloseViewModelBase : ViewModelBase, IRequestViewClose { - public void TryClose() { - RequestClose?.Invoke(this, new EventArgs()); - } - - public event EventHandler RequestClose; - } - - public static class RequestViewCloseExtensions { - public static ICommand close_command(this shell.RequestViewCloseViewModelBase rvc) { - return new DelegateCommand(rvc.TryClose); - } - } - - public class VMValueWrapper : ViewModelBase where T : IEquatable { - public VMValueWrapper(T val) { _val = val; } - T _val; - public T value { get { return _val; } set { if (value == null || !value.Equals(_val)) { _val = value; RaisePropertyChanged(); } } } - } - - // Adds set_error and clear_error to ViewModelBase - public class ViewModelBaseWithValidation : ViewModelBase, INotifyDataErrorInfo, IValidationViewModel { - Dictionary _errors = new Dictionary(); - - protected bool assert(bool condition, [CallerMemberName] string property = "", string message = null) { - if (condition) { - clear_error(property); - return true; - } else if (!_errors.TryGetValue(property, out string result) || !string.Equals(message, result)) { - _errors[property] = message; - FireErrorsChanged(property); - } - return false; - } - - protected bool has_errors(string property) => - _errors.ContainsKey(property); - - protected void set_error(string property, string message, bool ignore_if_already_error = false) { - if (!_errors.ContainsKey(property) || !ignore_if_already_error) { - _errors[property] = message; - FireErrorsChanged(property); - } - } - void IValidationViewModel.set_error(string property, string message) => set_error(property, message); - - protected void clear_error(string property) { - if (_errors.ContainsKey(property)) { - _errors.Remove(property); - FireErrorsChanged(property); - } - } - void IValidationViewModel.clear_error(string property) => clear_error(property); - - protected async Task assert_flash_error(bool test, params string[] properties) { - if (!test) await flash_error(properties); - else { - foreach (var prop in properties) - clear_error(prop); - } - } - - protected async Task flash_error_msg(string msg, TimeSpan duration, params string[] properties) { - foreach (var prop in properties) - set_error(prop, msg); - await Task.Delay(duration); - foreach (var prop in properties) - clear_error(prop); - } - - protected async Task flash_error_msg(string msg, params string[] properties) => - await flash_error_msg(msg, mbts.spark.SparkUtils.UI.ErrorFlashDuration, properties); - - protected async Task flash_error(params string[] properties) => - await flash_error_msg(string.Empty, properties); - - protected IDisposable validation() { - IEnumerable current = _errors.Keys.ToList(); - _errors.Clear(); - return _validation(current); - } - - protected IDisposable validation(params string[] properties) { - IEnumerable current = _errors.Keys.Intersect(properties).ToList(); - foreach (var p in current) _errors.Remove(p); - return _validation(current); - } - - protected void validation_assert(bool test, string messsage, params string[] properties) { - if (!test) { - foreach (var prop in properties) { - set_error(prop, messsage); - } - } - } - - IDisposable _validation(IEnumerable validating_properties) => - Disposable.Create(() => { - foreach (var property in validating_properties) - if (!_errors.ContainsKey(property)) - FireErrorsChanged(property); - }); - - - void FireErrorsChanged(string property) { - ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(property)); - } - - #region INotifyDataErrorInfo - public event EventHandler ErrorsChanged; - - public System.Collections.IEnumerable GetErrors(string propertyName) { - if (!string.IsNullOrEmpty(propertyName)) { - if (_errors.TryGetValue(propertyName, out string error)) { - yield return error; - } - } - } - - public bool HasErrors { - get { return _errors.Count != 0; } - } - - public IEnumerable AllErrors { get { return _errors.Values; } } - #endregion - - protected Property backing(string name, T default_value, IEnumerable> validation_steps, bool validate_now = false) { - void run_validation(T val) { - foreach (var pv in validation_steps) { - (bool valid, string msg) = pv.validate(val); - assert(valid, name, msg); - } - }; - - var prop = new Property(this, name, default_value); - prop.Changed += (old_val, new_val) => run_validation(new_val); - if (validate_now) { - run_validation(prop.Value); - } - return prop; - } - - protected UserProperty user_backing(string name, T default_value = default) => - new UserProperty(backing(name, default_value)); - - protected UserProperty user_backing(Property property) => - new UserProperty(property); - - - // TODO: maybe include a revert_on_error flag? - protected class PropertyValidation { - public readonly Func validate; - - public PropertyValidation(Func validate) => - this.validate = val => (validate(val), null); - - public PropertyValidation(Func validate) => - this.validate = validate; - } - } - - public abstract class DisposableViewModelBase : ViewModelBaseWithValidation, IPropertyChangedDemuxer, IDisposable, IWillLetYouKnowWhenIDispose { - protected IDisposable _dispose = null; - List _observable_properties_backing; - List _observable_properties => _observable_properties_backing ?? (_observable_properties_backing = new List()); - PropertyChangedDemuxer _property_changed_demuxer_backing; - - IPropertyChangedDemuxer _property_changed_demuxer => - _property_changed_demuxer_backing ?? (_property_changed_demuxer_backing = new PropertyChangedDemuxer(this)); - - IObservable IPropertyChangedDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); - IObservable IObservableDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); - void IObserver.OnNext(PropertyChangedEventArgs value) => _property_changed_demuxer.OnNext(value); - void IObserver.OnError(Exception error) => _property_changed_demuxer.OnError(error); - void IObserver.OnCompleted() => _property_changed_demuxer.OnCompleted(); - - internal IPropertyChangedDemuxer as_demuxer() => this; - - protected Property backing(string name, IObservable source, T default_value = default(T)) { - var prop = new ObservablePropertySink(this, name, default_value); - _observable_properties.Add(source.Subscribe(prop)); - return prop; - } - - /// - /// Use this generic overload when the [T]value must be created from the [TData]data on this thread, and a simple observable.Select() call will not work. - /// Note: UI settings in particular may find this useful, as brushes and other Freezable types are not inherently thread safe. - /// - protected Property backing(string name, IObservable source, Func select, T default_value = default) { - var prop = new ObservablePropertySink(this, name, default_value); - _observable_properties.Add(source.OnDispatcher().Subscribe(d => prop.set(select(d)))); - return prop; - } - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => - backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// This overload makes it a little easier to access the overload where a message is supplied to the validation logic. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. /// - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => - backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IReadOnlyList> validation_steps) => - backing(name, items, desired_item, select_default, EqualityComparer.Default, validation_steps); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - /// The selected_item property name. - /// The observable sequence of items. - /// The observable sequence of a desired item. - /// The fallback function to select an item by default. - /// The item-matching function used to preserve a selected item when new items arrive. - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer) => - backing(name, items, desired_item, select_default, comparer, new List>(0)); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - /// The selected_item property name. - /// The observable sequence of items. - /// The observable sequence of a desired item. - /// The fallback function to select an item by default. - /// The item-matching function used to preserve a selected item when new items arrive. - /// The validation steps to take when selected_item changes. - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { - var prop = new SelectorProperty(this, name, select_default, comparer, validation_steps); - attach(prop, items, desired_item); - return prop; - } - - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func item_to_value, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { - var prop = new SelectorProperty(this, name, item_to_value, select_default, comparer, validation_steps); - attach(prop, items, desired_item); - return prop; - } - - protected void attach(SelectorProperty selector_property, IObservable> items, IObservable> desired_item) { - _observable_properties.Add(items.OnDispatcher().Subscribe(selector_property)); - _observable_properties.Add(desired_item.OnDispatcher().Subscribe(selector_property)); - } - - protected void set_dispose(IDisposable disposable) { - if (_dispose != null) throw new InvalidOperationException("Cannot set disposable twice"); - _dispose = disposable; - } - protected void set_dispose(params IDisposable[] garbage) { - set_dispose(Disposable.Create(garbage)); - } - - protected void observe_property(Property property, Action callback) => - observe_property(property, (o, n) => callback()); - - protected void observe_property(Property property, PropertyChange callback) => - concat_disposable(property.Subscribe(t => callback(t.oldval, t.newval))); - - protected T concated_disposable(T disposable) where T : IDisposable { - concat_disposable(disposable); - return disposable; - } - - protected void concat_disposable(params IDisposable[] disposables) { - if (!(_dispose is System.Reactive.Disposables.CompositeDisposable cd)) { - cd = new System.Reactive.Disposables.CompositeDisposable(); - if (_dispose != null) - cd.Add(_dispose); - _dispose = cd; - } - cd.AddRange(disposables); - } - - protected virtual void Dispose(bool disposing) { } - public void Dispose() { - Disposable.dispose(ref _dispose); - Disposable.dispose(_observable_properties_backing); - Disposable.dispose(ref _property_changed_demuxer_backing); - Dispose(true); - OnDisposed?.Invoke(true); - } - - protected class SelectorProperty : SelectorProperty { - public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) - : base(owner, prop_name, i => i, select_default, comparer, validation_steps) { } - } - - /// - /// Designed to observe an items source, and a [settings-driven] desired item. When a new desired item is observed, it will evaluate it's current state and determine if it should be assigned to the selected_item. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - protected class SelectorProperty : IObserver>, IObserver>, IObservable<(TValue oldval, TValue newval)> { - readonly DisposableViewModelBase _owner; - readonly string _prop_name; - readonly IReadOnlyList> _validation_steps; - readonly ObservableCollection _items = new ObservableCollection(); - readonly Func _select_default; - readonly IEqualityComparer _value_comparer; - readonly Func _item_to_value; - TValue _selected_item; - InlineUserProperty _desired_item = new InlineUserProperty(); - bool _is_user_selected_item, _is_items_source_changing; - - public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func item_to_value, Func select_default, IEqualityComparer value_comparer, IReadOnlyList> validation_steps) { - _owner = owner; - _prop_name = prop_name; - _item_to_value = item_to_value; - _select_default = select_default; - _value_comparer = value_comparer ?? EqualityComparer.Default; - _validation_steps = validation_steps; - items = new ReadOnlyObservableCollection(_items); - } - - public event SelectionChanged Changing, Changed; - - public ReadOnlyObservableCollection items { get; } - - public TValue selected_item { - get => _selected_item; - set => _set_selected_item(value, (_is_user_selected_item = !_is_items_source_changing) ? SelectionReason.UserSelectedNewValue : SelectionReason.CurrentValueWasRemoved); - } - - public IDisposable Subscribe(IObserver<(TValue oldval, TValue newval)> observer) => - Subscribe((oldval, newval, reason) => observer.OnNext((oldval, newval))); - - public IDisposable Subscribe(SelectionChanged callback) { - Changed += callback; - return Disposable.Create(() => Changed -= callback); - } - - public IObservable observe_current(bool start_now = false) { - var source = this.Select(vals => vals.newval); - if (start_now) - source = source.StartWith(selected_item); - return source; - } - - void IObserver>.OnNext(InlineUserProperty iup) { - _desired_item = iup; - _try_auto_select(); - } - void IObserver>.OnError(Exception error) { } - void IObserver>.OnCompleted() { } - - void IObserver>.OnNext(IEnumerable value) { - _is_items_source_changing = true; - if (_is_user_selected_item) { - var curr_selected_item = selected_item; - _items.sync_with(value); - if (_try_match_item(curr_selected_item, out TValue match)) { - _is_user_selected_item = true; - _set_selected_item(match, SelectionReason.CurrentValueWasRestored); - } else { - _is_user_selected_item = false; - _try_auto_select(); - } - } else { - _items.sync_with(value); - _try_auto_select(); - } - _is_items_source_changing = false; - } - void IObserver>.OnError(Exception error) { } - void IObserver>.OnCompleted() { } - - void _run_validation(TValue val) { - var invalid_steps = _validation_steps.Select(v => v.validate(val)).Where(r => !r.valid); - if (invalid_steps.Count() > 0) { - var error_msg = string.Join("\n", invalid_steps.Where(r => !string.IsNullOrEmpty(r.msg)).Select(r => r.msg)); - _owner.set_error(_prop_name, error_msg, true); - } else _owner.clear_error(_prop_name); - } - - void _try_auto_select() { - if (_is_user_selected_item) { - // if we have a user-selected item and the _desired_item for which we might want to set as the selected item - // isn't force_override, then no change - if (!_desired_item.force_override) { - return; - } - if (desired_item_valid() && _desired_item.force_override && _try_match_item(_desired_item.value, out TValue match)) { - _set_selected_item(match, SelectionReason.SettingsMandatedSelection); - return; - } - } else if (desired_item_valid() && _try_match_item(_desired_item.value, out TValue match)) { - _set_selected_item(match, SelectionReason.SettingsMandatedSelection); - return; - } - if (_try_match_item(_select_default(), out TValue default_match)) { - _set_selected_item(default_match, SelectionReason.Other); - } else { - // the _set_selected_item has never been entered, so validation has never ran, force it here - // so that if some value is required, the valdiation logic will catch it - _run_validation(selected_item); - } - bool desired_item_valid() => (_desired_item?.has_value).GetValueOrDefault(); - } - - void _set_selected_item(TValue value, SelectionReason reason) { - if (!_value_comparer.Equals(value, _selected_item)) { - Changing?.Invoke(_selected_item, value, reason); - var old = _selected_item; - _selected_item = value; - Changed?.Invoke(old, value, reason); - _owner.RaisePropertyChanged(_prop_name); - _run_validation(value); - } - } - - bool _try_match_item(TValue value, out TValue match) { - foreach (TItem item in _items) { - TValue v = _item_to_value(item); - if (_value_comparer.Equals(v, value)) { - match = v; - return true; - } - } - match = default; - return false; - } - - bool _try_match_item(TItem item, out TValue match) => - _try_match_item(_item_to_value(item), out match); - } - - public event Action OnDisposed; - } - - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - static class NotifyDataErrorInfoExtensions { - public static IDisposable subscribe_errors_changed(this INotifyDataErrorInfo self, EventHandler callback) { - self.ErrorsChanged += callback; - return Disposable.Create(() => self.ErrorsChanged -= callback); - } - } -} +using bts.collections; + +using mbts.ui.utility; +using mbts.utils; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reactive.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Input; + +namespace mbts.ui.shell { + interface IRaiseNotifyPropertyChanged { + void raise_notify_property_changed(string prop); + } + + interface IValidationViewModel : IRaiseNotifyPropertyChanged { + void set_error(string property, string message); + void clear_error(string property); + } + + interface IProperty : IObservable<(T oldval, T newval)> { + event PropertyChange Changing, Changed; + T Value { get; set; } + } + + interface IUserProperty : IProperty { + bool setter_called { get; } + void bypass_setter(T value); + } + + public delegate void PropertyChange(T oldval, T newval); + + static class ValidationViewModelExtensions { + public static void assert(this IValidationViewModel vm, bool condition, string property, string message) { + if (condition) vm.clear_error(property); + else vm.set_error(property, message); + } + + public static IObservable subscribe_has_errors(this INotifyDataErrorInfo vm, bool start_immediately = false) => + Observable.Create(o => { + bool last_value = vm.HasErrors; + if (start_immediately) + o.OnNext(vm.HasErrors); + vm.ErrorsChanged += on_errors_changed; + return Disposable.Create(() => vm.ErrorsChanged -= on_errors_changed); + void on_errors_changed(object sender, DataErrorsChangedEventArgs e) { + if (vm.HasErrors != last_value) + o.OnNext(last_value = !last_value); + } + }); + + public static IObservable SubscribeValue(this IProperty property) => + // ensure notifications will be in on the same thread as IProperty.Subscribe (don't use .Select extension) + Observable.Create(o => property.Subscribe(ch => o.OnNext(ch.newval))); + + public static IProperty block_reentrancy(this IProperty source) => + new GatedPropertyWrapper(source); + + /// Blocks re-entrancy in setter. + class GatedPropertyWrapper : IProperty { + bool _is_updating; + readonly IProperty _source; + + public GatedPropertyWrapper(IProperty source) => + _source = source; + + public event PropertyChange Changing { add => _source.Changing += value; remove => _source.Changing -= value; } + public event PropertyChange Changed { add => _source.Changed += value; remove => _source.Changed -= value; } + + public T Value { + get => _source.Value; + set { + if (!_is_updating) { + _is_updating = true; + _source.Value = value; + _is_updating = false; + } + } + } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _source.Subscribe(observer); + } + } + + public class ViewModelBase : INotifyPropertyChanged, IRaiseNotifyPropertyChanged { + public ViewModelBase() { + _props = new Lazy(() => { + return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); + }); + } + protected void RaisePropertyChanged([CallerMemberName] string property = "") { + if (PropertyChanged != null) { + PropertyChanged(this, new PropertyChangedEventArgs(property)); + } + } + + protected void RaisePropertyChanged(params string[] properties) { + if (PropertyChanged != null) { + foreach (var prop in properties) { RaisePropertyChanged(prop); } + } + } + + void IRaiseNotifyPropertyChanged.raise_notify_property_changed(string prop) => + RaisePropertyChanged(prop); + + protected bool Set(ref T backing, T value, [CallerMemberName] string name = "") => + Set(ref backing, value, EqualityComparer.Default, name); + + protected bool Set(ref T backing, T value, [CallerMemberName] string name = "", params string[] dependent_props) { + if (Set(ref backing, value, EqualityComparer.Default, name)) { + RaisePropertyChanged(dependent_props); + return true; + } + return false; + } + + protected bool Set(ref T backing, T value, IEqualityComparer comparer, [CallerMemberName] string name = "") { + if (!comparer.Equals(backing, value)) { + backing = value; + RaisePropertyChanged(name); + return true; + } + return false; + } + + protected bool Set(ref T backing, T value, out T old_value, [CallerMemberName] string name = "") => + Set(ref backing, value, out old_value, EqualityComparer.Default, name); + + protected bool Set(ref T backing, T value, out T old_value, IEqualityComparer comparer, [CallerMemberName] string name = "") { + old_value = backing; + if (!comparer.Equals(backing, value)) { + backing = value; + RaisePropertyChanged(name); + return true; + } + return false; + } + + public event PropertyChangedEventHandler PropertyChanged; + + private Lazy _props; + + + #region Object Diffing + public interface IObjSnapshot : IDisposable { + bool revert { get; set; } + } + + public class ObjSnapshot : IObjSnapshot { + readonly ViewModelBase _target; + readonly Dictionary _snapshot; + readonly IReadOnlyList _props; + + public ObjSnapshot(ViewModelBase viewModelBase, IReadOnlyList props) { + _target = viewModelBase; + _props = props; + _snapshot = snap(); + } + + public bool revert { get; set; } + + public void Dispose() { + var cur = snap(); + foreach (var kv in cur) { + object oldv = _snapshot[kv.Key]; + object newv = cur[kv.Key]; + if (!Equals(oldv, newv)) { + var prop = kv.Key.property; + if (revert && prop.CanWrite) + prop.SetValue(_target, oldv); + _target.RaisePropertyChanged(prop.Name); + } + } + } + + Dictionary snap() => + // NOTE: in the future we can optimize prop.GetValue() if needed + _props.ToDictionaryCrushed(prop => new PropertyKeyWrapper(prop), prop => prop.GetValue(_target)); + + private class PropertyKeyWrapper : IEquatable { + public readonly PropertyInfo property; + public PropertyKeyWrapper(PropertyInfo property) => this.property = property; + public bool Equals(PropertyKeyWrapper other) => other != null && other.property.Name == property.Name; + public override bool Equals(object obj) => Equals(obj as PropertyKeyWrapper); + public override int GetHashCode() => property.Name.GetHashCode(); + } + } + + // Automatic (but shallow) property change notifications based on local object modifications + public ObjSnapshot detect_property_changes(params string[] props) { + if (props.Length == 0) return new ObjSnapshot(this, _props.Value); + else return new ObjSnapshot(this, _props.Value.Intersect(props, p => p.Name).ToList()); + } + + public ObjSnapshot detect_property_changes_except(params string[] props) { + if (props.Length == 0) return new ObjSnapshot(this, _props.Value); + else return new ObjSnapshot(this, _props.Value.Except(props, p => p.Name).ToList()); + } + #endregion + + #region automatic property + // use nameof() to add compile time checks + protected Property backing(string name, T default_value = default(T)) => + backing(name, EqualityComparer.Default, default_value); + + protected Property backing(string name, IEqualityComparer comparer, T default_value = default(T)) { + return new Property(this, name, comparer, default_value); + } + + protected Property backing(Expression> member, T default_value) { + var exp = (MemberExpression)member.Body; + return new Property(this, exp.Member.Name, default_value); + } + + // WILL invoke the get_value delegate + protected DelegateProperty backing(string name, Func get_value, params string[] invalidating_props) { + return new DelegateProperty(this, name, get_value, invalidating_props); + } + + // will NOT invoke the get_value delegate + protected DelegateProperty backing(string name, Func get_value, T default_value, params string[] invalidating_props) => + new DelegateProperty(this, name, get_value, default_value, invalidating_props); + + protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert) => + new PropertyAutoWrapper(this, name, initial_model, convert, EqualityComparer.Default); + + protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert, IEqualityComparer comparer) => + new PropertyAutoWrapper(this, name, initial_model, convert, comparer); + + protected DelegatePropertyAutoWrapper backing(string name, Func get_model, Func convert) => + new DelegatePropertyAutoWrapper(this, name, get_model, convert, EqualityComparer.Default); + + protected class Property : IProperty { + readonly string _propname; + readonly IEqualityComparer _comparer; + readonly ViewModelBase _owner; + T _value; + + public Property(ViewModelBase owner, string name, T default_value) + : this(owner, name, EqualityComparer.Default, default_value) { } + + public Property(ViewModelBase owner, string name, IEqualityComparer comparer, T default_value) { + _owner = owner; + _propname = name; + _comparer = comparer; + _value = default_value; + } + + public event PropertyChange Changing, Changed; + + public string name => _propname; + + public void set(T value) => + set_new(value); + + public bool set_new(T value) { + if (!Equals(value, _value)) { + Changing?.Invoke(_value, value); + var old = _value; + _value = value; + Changed?.Invoke(old, value); + _owner.RaisePropertyChanged(_propname); + return true; + } + return false; + } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => + Subscribe((oldval, newval) => observer.OnNext((oldval, newval))); + + public IDisposable Subscribe(PropertyChange callback) { + Changed += callback; + return Disposable.Create(() => Changed -= callback); + } + + public IObservable observe_current(bool start_immediately = false) { + var source = this.Select(vals => vals.newval); + if (start_immediately) + source = source.StartWith(() => _value); + return source; + } + + public T Value { + get { return _value; } + set { set(value); } + } + } + + protected class DelegateProperty : Property { + public DelegateProperty(ViewModelBase owner, string name, Func get_value, params string[] invalidating_props) + : this(owner, name, get_value, get_value(), invalidating_props) { } + + public DelegateProperty(ViewModelBase owner, string name, Func get_value, T default_value, params string[] invalidating_props) + : base(owner, name, default_value) { + _get_value = get_value; + if (invalidating_props != null && invalidating_props.Length > 0) { + var iprop_set = new HashSet(invalidating_props); + owner.PropertyChanged += (s, e) => { + if (iprop_set.Contains(e.PropertyName)) + refresh(); + }; + } + } + + readonly Func _get_value; + + public void refresh() => set(_get_value()); + public bool refresh_new() => set_new(_get_value()); + } + + /// + /// Inspired by ObservableAutoWrapper, a read/write TModel property is used to create a readonly TView property. + /// + protected class PropertyAutoWrapper : IObservable<((TModel model, TView view) oldval, (TModel model, TView view) newval)> { + readonly ViewModelBase _owner; + readonly Func _convert; + readonly IEqualityComparer _comparer; + readonly string _prop_name; + TModel _model; + TView _view; + + public PropertyAutoWrapper(ViewModelBase owner, string name, TModel initial_value, Func convert, IEqualityComparer comparer) { + _owner = owner; + _prop_name = name; + _model = initial_value; + _convert = convert; + _comparer = comparer; + _view = convert(_model); + } + + public event PropertyChange<(TModel model, TView view)> changing, changed; + + public string name => _prop_name; + public TModel model { get => _model; set => set(value); } + public TView view => _view; + + public void set(TModel model) => + set_new(model); + + public bool set_new(TModel model) { + if (_comparer.Equals(model, _model)) + return false; + TView new_view = _convert(model); + changing?.Invoke((_model, _view), (model, new_view)); + TView old_view = _view; + TModel old_model = _model; + _model = model; + _view = new_view; + changed?.Invoke((old_model, old_view), (_model, _view)); + _owner.RaisePropertyChanged(_prop_name); + return true; + } + + public IDisposable Subscribe(IObserver<((TModel model, TView view) oldval, (TModel model, TView view) newval)> observer) { + changed += pch; + return Disposable.Create(() => changed -= pch); + void pch((TModel, TView) o, (TModel, TView) n) => observer.OnNext((o, n)); + } + + public IObservable<(TModel model, TView view)> observe_current(bool start_immediately = false) { + var source = this.Select(vals => vals.newval); + if (start_immediately) + source = source.StartWith((_model, _view)); + return source; + } + } + + protected class DelegatePropertyAutoWrapper : PropertyAutoWrapper { + readonly Func _get_model; + + public DelegatePropertyAutoWrapper(ViewModelBase owner, string name, Func get_model, Func convert, IEqualityComparer comparer) + : base(owner, name, get_model(), convert, comparer) => _get_model = get_model; + + public void refresh() => set(_get_model()); + } + + /// + /// A thin wrapper around Property<T> that trips a 'setter_called' flag when the value is set through value-property-setter (i.e., through User interaction). + /// Note: This is class is particularly useful when a default/settings-based value arrives late, and the viewmodel must decide whether or not to override the current value. + /// + protected class UserProperty : IUserProperty { + readonly Property _prop_model; + + public UserProperty(Property prop_model) => + _prop_model = prop_model; + + public event PropertyChange Changing { add { _prop_model.Changing += value; } remove { _prop_model.Changing -= value; } } + public event PropertyChange Changed { add { _prop_model.Changed += value; } remove { _prop_model.Changed -= value; } } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _prop_model.Subscribe(observer); + public IObservable observe_current(bool start_immediately = false) => _prop_model.observe_current(start_immediately); + + public T Value { + get => _prop_model.Value; + set { + setter_called = true; + _prop_model.set(value); + } + } + public bool setter_called { get; private set; } + + /// + /// Sets the value without tripping the 'setter_called' flag. + /// + public void bypass_setter(T value) => _prop_model.set(value); + /// + /// Sets 'setter_called' to false. + /// + public void reset() => setter_called = false; + + public void on_inline_prop(InlineUserProperty inline_prop) { + if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) + bypass_setter(inline_prop.value); + } + + public void on_inline_prop(InlineUserProperty inline_prop, Func select) { + if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) + bypass_setter(select(inline_prop.value)); + } + } + + #endregion + + protected class ObservablePropertySink : Property, IObserver { + public ObservablePropertySink(ViewModelBase owner, string name, T default_val) : base(owner, name, default_val) { } + public void OnCompleted() { } + public void OnError(Exception error) { } + + public void OnNext(T value) { set(value); } + } + } + + public class RequestViewCloseViewModelBase : ViewModelBase, IRequestViewClose { + public void TryClose() { + RequestClose?.Invoke(this, new EventArgs()); + } + + public event EventHandler RequestClose; + } + + public static class RequestViewCloseExtensions { + public static ICommand close_command(this shell.RequestViewCloseViewModelBase rvc) { + return new DelegateCommand(rvc.TryClose); + } + } + + public class VMValueWrapper : ViewModelBase where T : IEquatable { + public VMValueWrapper(T val) { _val = val; } + T _val; + public T value { get { return _val; } set { if (value == null || !value.Equals(_val)) { _val = value; RaisePropertyChanged(); } } } + } + + // Adds set_error and clear_error to ViewModelBase + public class ViewModelBaseWithValidation : ViewModelBase, INotifyDataErrorInfo, IValidationViewModel { + Dictionary _errors = new Dictionary(); + + protected bool assert(bool condition, [CallerMemberName] string property = "", string message = null) { + if (condition) { + clear_error(property); + return true; + } else if (!_errors.TryGetValue(property, out string result) || !string.Equals(message, result)) { + _errors[property] = message; + FireErrorsChanged(property); + } + return false; + } + + protected bool has_errors(string property) => + _errors.ContainsKey(property); + + protected void set_error(string property, string message, bool ignore_if_already_error = false) { + if (!_errors.ContainsKey(property) || !ignore_if_already_error) { + _errors[property] = message; + FireErrorsChanged(property); + } + } + void IValidationViewModel.set_error(string property, string message) => set_error(property, message); + + protected void clear_error(string property) { + if (_errors.ContainsKey(property)) { + _errors.Remove(property); + FireErrorsChanged(property); + } + } + void IValidationViewModel.clear_error(string property) => clear_error(property); + + protected async Task assert_flash_error(bool test, params string[] properties) { + if (!test) await flash_error(properties); + else { + foreach (var prop in properties) + clear_error(prop); + } + } + + protected async Task flash_error_msg(string msg, TimeSpan duration, params string[] properties) { + foreach (var prop in properties) + set_error(prop, msg); + await Task.Delay(duration); + foreach (var prop in properties) + clear_error(prop); + } + + protected async Task flash_error_msg(string msg, params string[] properties) => + await flash_error_msg(msg, mbts.spark.SparkUtils.UI.ErrorFlashDuration, properties); + + protected async Task flash_error(params string[] properties) => + await flash_error_msg(string.Empty, properties); + + protected IDisposable validation() { + IEnumerable current = _errors.Keys.ToList(); + _errors.Clear(); + return _validation(current); + } + + protected IDisposable validation(params string[] properties) { + IEnumerable current = _errors.Keys.Intersect(properties).ToList(); + foreach (var p in current) _errors.Remove(p); + return _validation(current); + } + + protected void validation_assert(bool test, string messsage, params string[] properties) { + if (!test) { + foreach (var prop in properties) { + set_error(prop, messsage); + } + } + } + + IDisposable _validation(IEnumerable validating_properties) => + Disposable.Create(() => { + foreach (var property in validating_properties) + if (!_errors.ContainsKey(property)) + FireErrorsChanged(property); + }); + + + void FireErrorsChanged(string property) { + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(property)); + } + + #region INotifyDataErrorInfo + public event EventHandler ErrorsChanged; + + public System.Collections.IEnumerable GetErrors(string propertyName) { + if (!string.IsNullOrEmpty(propertyName)) { + if (_errors.TryGetValue(propertyName, out string error)) { + yield return error; + } + } + } + + public bool HasErrors { + get { return _errors.Count != 0; } + } + + public IEnumerable AllErrors { get { return _errors.Values; } } + #endregion + + protected Property backing(string name, T default_value, IEnumerable> validation_steps, bool validate_now = false) { + void run_validation(T val) { + foreach (var pv in validation_steps) { + (bool valid, string msg) = pv.validate(val); + assert(valid, name, msg); + } + }; + + var prop = new Property(this, name, default_value); + prop.Changed += (old_val, new_val) => run_validation(new_val); + if (validate_now) { + run_validation(prop.Value); + } + return prop; + } + + protected UserProperty user_backing(string name, T default_value = default) => + new UserProperty(backing(name, default_value)); + + protected UserProperty user_backing(Property property) => + new UserProperty(property); + + + // TODO: maybe include a revert_on_error flag? + protected class PropertyValidation { + public readonly Func validate; + + public PropertyValidation(Func validate) => + this.validate = val => (validate(val), null); + + public PropertyValidation(Func validate) => + this.validate = validate; + } + } + + public abstract class DisposableViewModelBase : ViewModelBaseWithValidation, IPropertyChangedDemuxer, IDisposable, IWillLetYouKnowWhenIDispose { + protected IDisposable _dispose = null; + List _observable_properties_backing; + List _observable_properties => _observable_properties_backing ?? (_observable_properties_backing = new List()); + PropertyChangedDemuxer _property_changed_demuxer_backing; + + IPropertyChangedDemuxer _property_changed_demuxer => + _property_changed_demuxer_backing ?? (_property_changed_demuxer_backing = new PropertyChangedDemuxer(this)); + + IObservable IPropertyChangedDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); + IObservable IObservableDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); + void IObserver.OnNext(PropertyChangedEventArgs value) => _property_changed_demuxer.OnNext(value); + void IObserver.OnError(Exception error) => _property_changed_demuxer.OnError(error); + void IObserver.OnCompleted() => _property_changed_demuxer.OnCompleted(); + + internal IPropertyChangedDemuxer as_demuxer() => this; + + protected Property backing(string name, IObservable source, T default_value = default(T)) { + var prop = new ObservablePropertySink(this, name, default_value); + _observable_properties.Add(source.Subscribe(prop)); + return prop; + } + + /// + /// Use this generic overload when the [T]value must be created from the [TData]data on this thread, and a simple observable.Select() call will not work. + /// Note: UI settings in particular may find this useful, as brushes and other Freezable types are not inherently thread safe. + /// + protected Property backing(string name, IObservable source, Func select, T default_value = default) { + var prop = new ObservablePropertySink(this, name, default_value); + _observable_properties.Add(source.OnDispatcher().Subscribe(d => prop.set(select(d)))); + return prop; + } + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => + backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// This overload makes it a little easier to access the overload where a message is supplied to the validation logic. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. /// + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => + backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IReadOnlyList> validation_steps) => + backing(name, items, desired_item, select_default, EqualityComparer.Default, validation_steps); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + /// The selected_item property name. + /// The observable sequence of items. + /// The observable sequence of a desired item. + /// The fallback function to select an item by default. + /// The item-matching function used to preserve a selected item when new items arrive. + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer) => + backing(name, items, desired_item, select_default, comparer, new List>(0)); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + /// The selected_item property name. + /// The observable sequence of items. + /// The observable sequence of a desired item. + /// The fallback function to select an item by default. + /// The item-matching function used to preserve a selected item when new items arrive. + /// The validation steps to take when selected_item changes. + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { + var prop = new SelectorProperty(this, name, select_default, comparer, validation_steps); + attach(prop, items, desired_item); + return prop; + } + + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func item_to_value, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { + var prop = new SelectorProperty(this, name, item_to_value, select_default, comparer, validation_steps); + attach(prop, items, desired_item); + return prop; + } + + protected void attach(SelectorProperty selector_property, IObservable> items, IObservable> desired_item) { + _observable_properties.Add(items.OnDispatcher().Subscribe(selector_property)); + _observable_properties.Add(desired_item.OnDispatcher().Subscribe(selector_property)); + } + + protected void set_dispose(IDisposable disposable) { + if (_dispose != null) throw new InvalidOperationException("Cannot set disposable twice"); + _dispose = disposable; + } + protected void set_dispose(params IDisposable[] garbage) { + set_dispose(Disposable.Create(garbage)); + } + + protected void observe_property(Property property, Action callback) => + observe_property(property, (o, n) => callback()); + + protected void observe_property(Property property, PropertyChange callback) => + concat_disposable(property.Subscribe(t => callback(t.oldval, t.newval))); + + protected T concated_disposable(T disposable) where T : IDisposable { + concat_disposable(disposable); + return disposable; + } + + protected void concat_disposable(params IDisposable[] disposables) { + if (!(_dispose is System.Reactive.Disposables.CompositeDisposable cd)) { + cd = new System.Reactive.Disposables.CompositeDisposable(); + if (_dispose != null) + cd.Add(_dispose); + _dispose = cd; + } + cd.AddRange(disposables); + } + + protected virtual void Dispose(bool disposing) { } + public void Dispose() { + Disposable.dispose(ref _dispose); + Disposable.dispose(_observable_properties_backing); + Disposable.dispose(ref _property_changed_demuxer_backing); + Dispose(true); + OnDisposed?.Invoke(true); + } + + protected class SelectorProperty : SelectorProperty { + public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) + : base(owner, prop_name, i => i, select_default, comparer, validation_steps) { } + } + + /// + /// Designed to observe an items source, and a [settings-driven] desired item. When a new desired item is observed, it will evaluate it's current state and determine if it should be assigned to the selected_item. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + protected class SelectorProperty : IObserver>, IObserver>, IObservable<(TValue oldval, TValue newval)> { + readonly DisposableViewModelBase _owner; + readonly string _prop_name; + readonly IReadOnlyList> _validation_steps; + readonly ObservableCollection _items = new ObservableCollection(); + readonly Func _select_default; + readonly IEqualityComparer _value_comparer; + readonly Func _item_to_value; + TValue _selected_item; + InlineUserProperty _desired_item = new InlineUserProperty(); + bool _is_user_selected_item, _is_items_source_changing; + + public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func item_to_value, Func select_default, IEqualityComparer value_comparer, IReadOnlyList> validation_steps) { + _owner = owner; + _prop_name = prop_name; + _item_to_value = item_to_value; + _select_default = select_default; + _value_comparer = value_comparer ?? EqualityComparer.Default; + _validation_steps = validation_steps; + items = new ReadOnlyObservableCollection(_items); + } + + public event SelectionChanged Changing, Changed; + + public ReadOnlyObservableCollection items { get; } + + public TValue selected_item { + get => _selected_item; + set => _set_selected_item(value, (_is_user_selected_item = !_is_items_source_changing) ? SelectionReason.UserSelectedNewValue : SelectionReason.CurrentValueWasRemoved); + } + + public IDisposable Subscribe(IObserver<(TValue oldval, TValue newval)> observer) => + Subscribe((oldval, newval, reason) => observer.OnNext((oldval, newval))); + + public IDisposable Subscribe(SelectionChanged callback) { + Changed += callback; + return Disposable.Create(() => Changed -= callback); + } + + public IObservable observe_current(bool start_now = false) { + var source = this.Select(vals => vals.newval); + if (start_now) + source = source.StartWith(selected_item); + return source; + } + + void IObserver>.OnNext(InlineUserProperty iup) { + _desired_item = iup; + _try_auto_select(); + } + void IObserver>.OnError(Exception error) { } + void IObserver>.OnCompleted() { } + + void IObserver>.OnNext(IEnumerable value) { + _is_items_source_changing = true; + if (_is_user_selected_item) { + var curr_selected_item = selected_item; + _items.sync_with(value); + if (_try_match_item(curr_selected_item, out TValue match)) { + _is_user_selected_item = true; + _set_selected_item(match, SelectionReason.CurrentValueWasRestored); + } else { + _is_user_selected_item = false; + _try_auto_select(); + } + } else { + _items.sync_with(value); + _try_auto_select(); + } + _is_items_source_changing = false; + } + void IObserver>.OnError(Exception error) { } + void IObserver>.OnCompleted() { } + + void _run_validation(TValue val) { + var invalid_steps = _validation_steps.Select(v => v.validate(val)).Where(r => !r.valid); + if (invalid_steps.Count() > 0) { + var error_msg = string.Join("\n", invalid_steps.Where(r => !string.IsNullOrEmpty(r.msg)).Select(r => r.msg)); + _owner.set_error(_prop_name, error_msg, true); + } else _owner.clear_error(_prop_name); + } + + void _try_auto_select() { + if (_is_user_selected_item) { + // if we have a user-selected item and the _desired_item for which we might want to set as the selected item + // isn't force_override, then no change + if (!_desired_item.force_override) { + return; + } + if (desired_item_valid() && _desired_item.force_override && _try_match_item(_desired_item.value, out TValue match)) { + _set_selected_item(match, SelectionReason.SettingsMandatedSelection); + return; + } + } else if (desired_item_valid() && _try_match_item(_desired_item.value, out TValue match)) { + _set_selected_item(match, SelectionReason.SettingsMandatedSelection); + return; + } + if (_try_match_item(_select_default(), out TValue default_match)) { + _set_selected_item(default_match, SelectionReason.Other); + } else { + // the _set_selected_item has never been entered, so validation has never ran, force it here + // so that if some value is required, the valdiation logic will catch it + _run_validation(selected_item); + } + bool desired_item_valid() => (_desired_item?.has_value).GetValueOrDefault(); + } + + void _set_selected_item(TValue value, SelectionReason reason) { + if (!_value_comparer.Equals(value, _selected_item)) { + Changing?.Invoke(_selected_item, value, reason); + var old = _selected_item; + _selected_item = value; + Changed?.Invoke(old, value, reason); + _owner.RaisePropertyChanged(_prop_name); + _run_validation(value); + } + } + + bool _try_match_item(TValue value, out TValue match) { + foreach (TItem item in _items) { + TValue v = _item_to_value(item); + if (_value_comparer.Equals(v, value)) { + match = v; + return true; + } + } + match = default; + return false; + } + + bool _try_match_item(TItem item, out TValue match) => + _try_match_item(_item_to_value(item), out match); + } + + public event Action OnDisposed; + } + + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + static class NotifyDataErrorInfoExtensions { + public static IDisposable subscribe_errors_changed(this INotifyDataErrorInfo self, EventHandler callback) { + self.ErrorsChanged += callback; + return Disposable.Create(() => self.ErrorsChanged -= callback); + } + } +}