Files
spark/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs
T

450 lines
22 KiB
C#

using bts.collections;
using bts.utils;
using mbts.collections;
using mbts.persist;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using mbts.ui.spark;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace mbts.spark {
interface IWindowSettingsVM<T> where T : class {
void load(T value);
T get_result();
}
class ShellSettingsDialogVM<T, TVM> : ViewModelBase, IRequestViewClose, IDisposable, IWillLetYouKnowWhenIDispose where T : class, IEquatable<T> where TVM : IWindowSettingsVM<T> {
readonly Property<bool> _use_default;
readonly DialogSkirtItem _ok_item, _apply_item, _cancel_item, _apply_to_defaults_item;
readonly DelegateProperty<IEnumerable<DialogSkirtItem>> _left_skirt_items;
readonly List<IDisposable> _resources = new List<IDisposable>(2); // initialize with 2 capacity bc the only potential disposables are the instance/default vms
string _title;
public ShellSettingsDialogVM(IWindowSettingsManager<T> settings_manager, Func<UserSettings, T> get_factory_settings, string settings_file_ext, Func<T, TVM> vm_factory, Func<T, T> merge_with_current = null, bool show_save_as_defaults = true) {
if (merge_with_current == null)
merge_with_current = s => s;
// by default, each new window will use their own instance settings
_use_default = backing(nameof(use_default), settings_manager.instance_settings == null);
default_vm = vm_factory(settings_manager.default_settings);
// instance vm is what will always be visible on the screen
instance_vm = vm_factory(settings_manager.current_settings());
// items
const string import_group = "i", export_group = "e";
(string name, string[] extensions) file_filter = ($"{settings_file_ext} settings files", new[] { settings_file_ext });
var import_to_custom_cmd = FileDialogCommand.import_proto<T>(s => instance_vm.load(s), type_name: settings_file_ext, filter_items: file_filter);
var export_to_custom_cmd = FileDialogCommand.export_proto(() => instance_vm.get_result(), filter_items: file_filter);
action_menu_items = new IMenuItemVM[] {
new MenuItemVM("Load Settings File ...", import_to_custom_cmd, Icons.Import, import_group),
new MenuItemVM("Save Settings File ...", export_to_custom_cmd, Icons.Export, export_group),
new MenuItemVM("Load Factory Defaults",
new DelegateCommand(() => instance_vm.load(get_factory_settings(UserSettings.factory_defaults))),
Icons.Factory
)
};
_left_skirt_items = backing(nameof(left_skirt_items), left_skirt_factory);
_apply_item = new DialogSkirtItem("Apply", new DelegateCommand(() => {
use_default = false;
apply();
}));
_ok_item = new DialogSkirtItem("OK", new DelegateCommand(() => {
use_default = false;
apply();
close();
})) { is_default = true };
_cancel_item = new DialogSkirtItem("Cancel", new DelegateCommand(close)) { is_cancel = true };
_apply_to_defaults_item = new DialogSkirtItem("Save As Defaults", new DelegateCommand(() => {
use_default = true;
apply();
close();
}), ui.spark.LadderSettingsDialog.ResetToFactoryKey);
// maybe dispose vms
if (instance_vm is IDisposable dispose_ivm)
_resources.Add(dispose_ivm);
if (default_vm is IDisposable dispose_dvm)
_resources.Add(dispose_dvm);
// local methods
void apply() {
var result = merge_with_current(instance_vm.get_result());
if (!use_default) {
settings_manager.instance_settings = result;
} else {
settings_manager.instance_settings = null;
// copy the current instance settings and persist
if (!result.safe_equals(settings_manager.default_settings))
settings_manager.save_default_settings(result).ignore();
}
}
void close() => RequestClose?.Invoke(this, new EventArgs());
IEnumerable<DialogSkirtItem> left_skirt_factory() {
if (show_save_as_defaults)
yield return _apply_to_defaults_item;
};
}
public event EventHandler RequestClose;
public event Action<bool> OnDisposed;
public string title { get => _title; set => Set(ref _title, value); }
public TVM instance_vm { get; }
public TVM default_vm { get; }
public IReadOnlyCollection<IMenuItemVM> action_menu_items { get; }
public IEnumerable<DialogSkirtItem> left_skirt_items => _left_skirt_items.Value;
public IEnumerable<DialogSkirtItem> right_skirt_items {
get {
yield return _apply_item;
yield return _ok_item;
yield return _cancel_item;
}
}
public bool use_default {
get => _use_default.Value;
set => _use_default.Value = value;
}
public void Dispose() {
Disposable.dispose(_resources);
OnDisposed?.Invoke(true);
}
}
class ProfiledShellSettingsDialogVM<T, TVM, TProfile> : DisposableViewModelBase, IRequestViewClose where T : class, IEquatable<T> where TVM : class, IValueFactory<T>, IObservable<T> where TProfile : ISettingsProfile<T> {
readonly IComparer<SettingsProfile<T>> _key_comp = Comparer<uint>.Default.wrap(SettingsProfile<T>.key_fn);
readonly Property<ProfileVM> _selected_profile;
readonly Func<T, TVM> _vm_factory;
readonly ProfileVM _local_profile;
string _title;
bool _is_copy_menu_open;
DialogSkirtItem _apply_item, _ok_item, _cancel_item;
MenuItemVM _import_item, _export_item, _load_factory_item;
public ProfiledShellSettingsDialogVM(ISettingsProfileService<T> profile_service, Func<UserSettings, T> get_fallback, Func<T, TVM> vm_factory, Func<T, T> normalize, T init, string file_ext, Func<T, T, bool> profile_equals = null, uint settings_id = 0) {
_vm_factory = vm_factory;
if (profile_equals == null)
profile_equals = EqualityComparer<T>.Default.Equals;
// profile collections
var skip_local = profiles.WrapSkip(1);
var skip_local_wrapper = skip_local.WrapSelector(
p => new SettingsProfile<T>(p.id, p.name, p.value.create(), p.security_criteria),
ns => new ProfileVM(ns.id, vm_factory(ns.value), ns.name, ns.security_criteria, target_value: ns.value));
profiles.Add(_local_profile = new ProfileVM(0, vm_factory(init), "Custom", template_key: ShellSettingsDialog.LocalProfileItemTemplateKey, target_value: init));
_selected_profile = backing(nameof(selected_profile), _local_profile);
// dialog skirt items
_apply_item = new DialogSkirtItem("Apply", new DelegateCommand(apply));
_ok_item = new DialogSkirtItem("OK", new DelegateCommand(new Action(apply) + close)) { is_default = true };
_cancel_item = new DialogSkirtItem("Cancel", new DelegateCommand(close)) { is_cancel = true };
// cmds
add_profile_cmd = new DelegateCommand(begin_add_profile);
copy_profile_cmd = new DelegateCommand<ProfileVM>(copy_profile);
revert_profile_cmd = ObservantCommand.create(revert_profile, ProfileVM.subscribe_is_dirty_fn, out var revert_profile_observer);
save_profile_cmd = ObservantCommand.create(save_profile, ProfileVM.subscribe_is_global_dirty_fn, out var save_profile_observer);
save_profile_as_cmd = ObservantCommand.create(begin_save_profile_as, ProfileVM.is_global_fn, out var save_as_observer);
save_all_cmd = ObservantCommand.create(save_all, out var save_all_observer);
delete_profile_cmd = ObservantCommand.create(delete, ProfileVM.is_global_fn, out var delete_observer);
// toolbar
const string import_group = "i", export_group = "e";
(string name, string[] extensions) file_filter = ($"{file_ext} settings files", new[] { file_ext });
var import_cmd = FileDialogCommand.import_proto<T>(s => selected_profile?.load_value_from(s), type_name: file_ext, filter_items: file_filter);
var export_cmd = FileDialogCommand.export_proto(() => instance_vm.create(), filter_items: file_filter);
_load_factory_item = new MenuItemVM("Load Factory Defaults", new DelegateCommand(() => selected_profile?.load_value_from(get_fallback(UserSettings.factory_defaults))), Icons.Factory);
_import_item = new MenuItemVM("Load Settings File ...", import_cmd, Icons.Import, import_group);
_export_item = new MenuItemVM("Save Settings File ...", export_cmd, Icons.Export, export_group);
//
var is_global_dirty_mon = new ReactiveThresholdMonitor<ProfileVM>(ProfileVM.subscribe_is_global_dirty_fn);
_dispose = Disposable.Create(
ObservableAutoWrapper.connect_item_hooks(profiles, p => Disposable.Create(is_global_dirty_mon.join(p), p)),
is_global_dirty_mon.Subscribe(save_all_observer),
_selected_profile.observe_current(true).Subscribe(v => {
revert_profile_observer.OnNext(v);
save_profile_observer.OnNext(v);
save_as_observer.OnNext(v);
delete_observer.OnNext(v);
RaisePropertyChanged(nameof(instance_vm));
}),
profile_service.subscribe_all().OnDispatcher().Subscribe(table => {
var prev_selected_name = selected_profile?.name;
skip_local_wrapper.RemoveSorted(table.removed, _key_comp);
foreach (var ns in table.changed) {
int i = CollectionHelper.binary_search(skip_local_wrapper, ns, _key_comp);
if (i >= 0)
skip_local[i].commit(ns.with(value: normalize(ns.value)));
}
foreach (var ns in table.added) {
int i = CollectionHelper.binary_search(skip_local_wrapper, ns, _key_comp);
if (i >= 0)
continue;
i = ~i;
var temp = ns.with(value: normalize(ns.value));
if (settings_id == temp.id) {
settings_id = 0;
if (profile_equals(temp.value, init)) {
if (!temp.value.Equals(init)) {
// they aren't exactly equal (don't overwrite any props in 'init' - use it to create the vm)
temp = temp.with(value: init);
}
skip_local_wrapper.Insert(i, temp);
selected_profile = skip_local[i];
continue;
}
}
skip_local_wrapper.Insert(i, temp);
}
}));
void apply() {
if (selected_profile != null) {
var newval = selected_profile.create();
if (selected_profile.id != 0)
profile_service.add_or_update(newval);
selected_profile.commit_current();
applied?.Invoke(newval);
}
}
void close() => RequestClose?.Invoke(this, new EventArgs());
void delete(ProfileVM target) {
if (target.id != 0 && BTSMessageBox.Confirm($"Are you sure you want to delete '{target.name}?'", "Settings Profile"))
profile_service.remove(target.id);
}
void copy_profile(ProfileVM target) {
if (selected_profile != null) {
if (target == null) {
// copy to new
var profile = selected_profile.create().with(0, $"{selected_profile.name} - Copy");
target = new ProfileVM(profile_service.add_or_update(profile), _vm_factory(profile.value), profile.name);
}
target.load_value_from(selected_profile.create().value);
is_copy_menu_open = false;
selected_profile = target;
}
}
// cmd impl
void begin_add_profile() => choose_name_dialog("New Profile", selected_profile, (t, n) => save_profile_as(null, n)).Show();
void begin_save_profile_as(ProfileVM target) => choose_name_dialog($"Rename '{target.name}'", target, (t, n) => save_profile_as(t ?? target, n)).Show();
void revert_profile(ProfileVM target) => target?.revert();
void save_profile(ProfileVM target) => save_profile_as(target, target?.name);
//
void save_profile_as(ProfileVM target, string name) {
if (name == null || selected_profile == null)
return;
SettingsProfile<T> val;
if (target != null) {
// overwrite target profile
val = selected_profile.create().with(name: name);
target.commit(val);
selected_profile = target;
profile_service.add_or_update(val);
} else {
// create new profile (set id=0 so 'store' knows to add a new profile, rather than update an existing one)
val = selected_profile.create().with(0, name);
uint id = profile_service.add_or_update(val);
/// Add the new profile to (<see cref="profiles"/>) so it can then be assigned to <see cref="selected_profile"/> without being immediately unselected.
/// remember: val needs the new id before it can be added.
val = val.with(id);
// the save process is asynchronous now, but if that were to change, the new setting vm would have been added (already) in the iobservable settings callback.
// check that a vm with this id doesn't already exist before adding it .
int i = CollectionHelper.binary_search(skip_local_wrapper, val, _key_comp);
if (i < 0)
skip_local_wrapper.Insert(i = ~i, val);
selected_profile = skip_local[i];
}
}
void save_all() =>
profile_service.add_or_update(skip_local.Select(p => p.create()));
Window choose_name_dialog(string title, ProfileVM target, Action<ProfileVM, string> commit) {
var text_box = new TextBox { Width = 160, Margin = new Thickness(8, 0, 0, 0), Text = target?.name ?? string.Empty };
Behavior.SetFocusOnLoaded(text_box, true);
WPFTextBoxAutoComplete.AutoCompleteBehavior.SetAutoCompleteItemsSource(text_box, skip_local.Select(vm => vm.name).ToList());
// panel
var panel = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(8) };
panel.Children.Add(new TextBlock { Text = "Name:", VerticalAlignment = VerticalAlignment.Center });
panel.Children.Add(text_box);
// dialog
var dialog = new OKCancelDialog {
Title = title,
OKCommand = new DelegateCommand(() => commit(skip_local.FirstOrDefault(vm => vm.name == text_box.Text), text_box.Text)),
CoreContent = panel,
Topmost = true
};
dialog.move_to_mouse(-100, -80);
return dialog;
}
}
public event Action<SettingsProfile<T>> applied;
public event EventHandler RequestClose;
public string title { get => _title; set => Set(ref _title, value); }
public ObservableCollection<ProfileVM> profiles { get; } = new ObservableCollection<ProfileVM>();
public ProfileVM selected_profile {
get => _selected_profile.Value;
set {
if (_selected_profile.set_new(value) && value != null)
value.is_selected = true;
}
}
public TVM instance_vm => selected_profile?.value;
public bool is_copy_menu_open { get => _is_copy_menu_open; set => Set(ref _is_copy_menu_open, value); }
public ICommand add_profile_cmd { get; }
public ICommand copy_profile_cmd { get; }
public ICommand delete_profile_cmd { get; }
public ICommand revert_profile_cmd { get; }
public ICommand edit_profile_securities_cmd { get; }
public ICommand save_profile_cmd { get; }
public ICommand save_profile_as_cmd { get; }
public ICommand save_all_cmd { get; }
public IEnumerable<IMenuItemVM> action_menu_items {
get {
yield return _import_item;
yield return _export_item;
yield return _load_factory_item;
}
}
public IEnumerable<DialogSkirtItem> left_skirt_items { get { yield break; } }
public IEnumerable<DialogSkirtItem> right_skirt_items {
get {
yield return _apply_item;
yield return _ok_item;
yield return _cancel_item;
}
}
public class ProfileVM : ViewModelBase, IValueFactory<SettingsProfile<T>>, IEquatable<ProfileVM>, ITemplateSelectorKey, IDisposable {
// static delegates
public static readonly Func<ProfileVM, bool> is_global_fn = p => p != null && p.is_global;
public static readonly Func<ProfileVM, IObservable<bool>> subscribe_is_global_dirty_fn = p => p?.is_global ?? false ? p.subscribe_is_dirty() : Observable.Return(false);
public static readonly Func<ProfileVM, IObservable<bool>> subscribe_is_dirty_fn = p => p != null ? p.subscribe_is_dirty() : Observable.Return(false);
//
readonly DeferrableActionWrapper _refresh_is_dirty;
readonly DelegateProperty<bool> _is_dirty;
//
SecurityCriteria _security_criteria;
SettingsProfile<T> _committed, _last_result;
T _target_value;
string _name, _template_key;
bool _is_selected;
IDisposable _dispose;
public ProfileVM(uint id, TVM value, string name, SecurityCriteria security_criteria = null, string template_key = null, T target_value = null) {
this.id = id;
this.value = value;
_name = name;
_security_criteria = security_criteria;
_template_key = template_key;
_target_value = target_value;
_committed = _last_result = create();
_is_dirty = backing(nameof(is_dirty), () => !_last_result.Equals(_committed));
_refresh_is_dirty = new DeferrableActionWrapper(_is_dirty.refresh);
var sub = value.Subscribe(v => {
_last_result = _last_result.with(value: v);
_refresh_is_dirty.execute();
_on_value_changed();
});
_dispose = value is IDisposable d ? Disposable.Create(sub, d) : sub;
}
void _on_value_changed() {
if (_target_value != null && is_dirty && _last_result.value.Equals(_target_value)) {
_target_value = null;
_committed = _last_result;
_refresh_is_dirty.execute();
}
}
public uint id { get; }
public TVM value { get; }
public string name {
get => _name;
set {
if (Set(ref _name, value)) {
_last_result = _last_result.with(name: value);
_is_dirty.refresh();
}
}
}
public bool is_global => id != 0;
public bool is_dirty => _is_dirty.Value;
public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); }
public SecurityCriteria security_criteria {
get => _security_criteria;
set {
if (Set(ref _security_criteria, value)) {
_last_result = _last_result.with(security_criteria: security_criteria);
_is_dirty.refresh();
}
}
}
string ITemplateSelectorKey.key => _template_key;
public SettingsProfile<T> create() =>
new SettingsProfile<T>(id, name, value.create(), security_criteria);
public void load_from(SettingsProfile<T> data) {
using (_refresh_is_dirty.defer_execution()) {
_load_from(data);
/// assign directly to <see cref="_last_result"/>, to capture props that aren't visible in the dialog (i.e., props that are manipulated in the main window)
_last_result = data;
}
_on_value_changed();
}
public void load_value_from(T value) {
using (_refresh_is_dirty.defer_execution())
this.value.load_from(value);
_on_value_changed();
}
public void commit(SettingsProfile<T> data) {
using (_refresh_is_dirty.defer_execution())
_load_from(_committed = data);
_on_value_changed();
}
public void commit_current() {
_committed = _last_result;
_target_value = _committed.value;
_refresh_is_dirty.execute();
_on_value_changed();
}
public void revert() {
using (_refresh_is_dirty.defer_execution()) {
_load_from(_committed);
_last_result = _committed;
}
_on_value_changed();
}
public IObservable<bool> subscribe_is_dirty() => _is_dirty.observe_current(true);
public void Dispose() => Disposable.dispose(ref _dispose);
public bool Equals(ProfileVM other) => id == other?.id;
public override bool Equals(object obj) => Equals(obj as ProfileVM);
public override int GetHashCode() => id.GetHashCode();
public override string ToString() => _name;
void _load_from(SettingsProfile<T> data) {
_target_value = data.value;
name = data.name;
security_criteria = data.security_criteria;
value.load_from(data.value);
}
}
}
}