make pnl settings pretty

This commit is contained in:
John Colvin committed 2019-10-26 16:26:36 -05:00
1 parent 89d2652619
commit 7b8d45c229
20 files changed
+1425 -1298

No files matched your search

@@ -1,375 +1,377 @@
using bts.api;
using bts.collections;
using bts.settings;
using bts.shell.pnl;
using bts.spark;
using bts.utils;
using mbts;
using mbts.config;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace bts.shell {
class PNLWindowFactory : ShellWindowFactory<PNLSaveState> {
const string _window_type = "PNL", _window_title = "PNL";
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly UserSettingsHub _settings_hub;
readonly PNLConfig _pnl_conf;
readonly IShellWindowThreadIDProvider _thread_id_provider;
public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, _window_type) {
_bus = bus;
_orders_model = orders_model;
_settings_hub = settings_hub;
_pnl_conf = new PNLConfig(Configuration.get<bts.config.PNLOptions>());
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get<bts.config.MultiThreadedWindows>().pnl);
_dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show);
}
public override Task<IShellWindow> load(PNLSaveState state) =>
Task.FromResult(_create(state.settings));
void _show(PNLSettings settings) =>
_bus.post(SparkTags.ShowWindow, _create(settings));
IShellWindow _create(PNLSettings settings) {
var settings_manager = _settings_hub.create_pnl_settings_manager(settings);
// Need to keep a local copy of the columns, since they are defined in xaml (not the viewmodel), and get_save_state may be called on a non-dispatcher thread.
// If that happens, we would be unable to access _grid.Columns, and thus unable to get the current column settings.
// Use an ImmutableList to avoid any threading issues when responding to CollectionChanged events on the dispatcher thread.
ImmutableList<DIYGrid.ColumnBase> cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty;
return SparkWindow<PNLSaveState>.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => {
var vm = new PNLVM(_bus, _orders_model, settings ?? PNLSettings.Default);
var content = new PNLView {
DataContext = vm
};
vm.sorting_changed += sh => {
try {
DIYGridSortHelper.set_sort_directions(sh, content._grid.Columns);
} catch { }
};
vm.SubscribeDisposed(
DIYGridSortHelper.observe_active_comparers<PNLView.Columns, PNLRowVM>(content._grid, PNLVM.get_column_comparer)
.OnDispatcher()
.Subscribe(sh => vm.sorting_hierarchy = sh.Select(s => (s.key, s.direction)).ToList()));
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
Func<PNLSaveState> get_save_state = () => {
var cols = cached_columns.ToArray(c => c.create());
var filters = vm.get_filters_states();
var sorting_criterion = vm.sorting_hierarchy.Select(tup => new SortingCriteria(tup.key.ToString(), tup.direction == ListSortDirection.Ascending)).ToArray();
var calc_type = vm.calculation_type;
var state = settings_manager.instance_settings;
if (state == null) {
// don't use defaults if the user manipulated the window state outside of the settings dialog (e.g., resized column(s) via drag, or changed sort/filter)
var defaults = settings_manager.default_settings;
if (calc_type == defaults.calculation_type &&
defaults.sorting_criterion.SequenceEqual(sorting_criterion) &&
defaults.grid.columns.SequenceEqual(cols) && defaults.filters.safe_equals(filters)) {
// the user's current state still matches the defaults (i.e., no outside manipulation was performed); return null so this window will use the latest default settings when restored
return new PNLSaveState { use_defaults = true, settings = null };
}
state = defaults;
}
// assign latest values, as they may have be modified outside of the settings dialog (in which case the settings manager would be out of date)
state = state.with(
sorting_criterion,
vm.anchors,
filters,
state.grid.with(columns: cols, background: vm.grid_background_color.rgb_color()),
calc_type,
vm.header_row_display);
return new PNLSaveState { use_defaults = false, settings = state };
};
IEnumerable<SparkCommand> commands = new[] {
new SparkCommandCommand("Collapse All", Icons.RightArrow, new DelegateCommand(() => vm.set_all_expanded(false))),
new SparkCommandCommand("Expand All", Icons.DownArrow, new DelegateCommand(() => vm.set_all_expanded(true))),
new SparkCommandCommand("Play", Icons.Play, new DelegateCommand(() => vm.is_paused = false)) {
show_in_context_menu = _pnl_conf.show_pause_resume,
show_in_toolbar = _pnl_conf.show_pause_resume
},
new SparkCommandCommand("Pause", Icons.Pause, new DelegateCommand(() => vm.is_paused = true)) {
show_in_context_menu = _pnl_conf.show_pause_resume,
show_in_toolbar = _pnl_conf.show_pause_resume
},
SparkCommands.window_settings_command(new DialogCommand(() => {
settings_manager.instance_settings = get_save_state().settings;
var dialog_vm = new ShellSettingsDialogVM<PNLSettings, PNLSettingsVM>(
settings_manager,
us => us.pnl,
UserSettings.FileExtensions.PNL,
s => new PNLSettingsVM(s));
var dialog = new ShellSettingsDialog { DataContext = dialog_vm };
dialog_vm.RequestClose += on_request_close;
return dialog;
void on_request_close(object sender, EventArgs e) =>
WindowUtilities.force_close(dialog);
}))
};
IDisposable dispose = Disposable.Create(
settings_manager.subscribe_current().OnDispatcher().Subscribe(s => {
vm.load_from(s);
var col_setting_map = s.grid.columns.ToDictionary(c => c.id);
var fallback_family = new FontFamily(s.grid.font_family);
// group
var group_col_setting_map = s.group_columns.ToDictionary(c => c.id);
var group_appearance = s.group_cell_appearance.to_appearance();
// header
var header_col_setting_map = s.header_columns.ToDictionary(c => c.id);
var header_appearance = s.header_cell_appearance.to_appearance();
//
foreach (var c in content._grid.Columns.OfType<PNLColumn>()) {
if (col_setting_map.TryGetValue(c.id, out var cs)) {
c.load_from(cs);
}
if (group_col_setting_map.TryGetValue(c.id, out var gcs)) {
c.load_group_params(
group_appearance.font_size,
gcs.font_weight_override ?? group_appearance.font_weight,
gcs.font_color_override ?? group_appearance.foreground,
group_appearance.font_family);
}
if (header_col_setting_map.TryGetValue(c.id, out var hcs)) {
c.load_header_params(
header_appearance.font_size,
hcs.font_weight_override ?? header_appearance.font_weight,
hcs.font_color_override ?? header_appearance.foreground,
header_appearance.font_family);
}
}
CollectionHelper.sync_with_never_duplicate(content._grid.Columns, s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
}),
content._grid.Columns.Subscribe((s, e) => {
switch (e.Action) {
case NotifyCollectionChangedAction.Add: add_new(); break;
case NotifyCollectionChangedAction.Remove: remove_old(); break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
remove_old();
add_new();
break;
case NotifyCollectionChangedAction.Reset:
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
break;
}
void add_new() =>
cached_columns = e.NewStartingIndex >= 0 ?
cached_columns.InsertRange(e.NewStartingIndex, e.NewItems.OfType<DIYGrid.ColumnBase>()) :
cached_columns.AddRange(e.NewItems.OfType<DIYGrid.ColumnBase>());
void remove_old() =>
cached_columns = e.OldStartingIndex >= 0 ?
cached_columns.RemoveRange(e.OldStartingIndex, e.OldItems.Count) :
cached_columns.RemoveRange(e.OldItems.OfType<DIYGrid.ColumnBase>());
}),
Disposable.wrap_collection(commands.OfType<IDisposable>()),
vm);
return (content, commands, get_save_state, dispose);
},
min_width_offset: SystemParameters.HorizontalScrollBarButtonWidth + 8,
min_height_offset: 60);
}
readonly struct PNLConfig {
public readonly bool
enable_animations,
show_pause_resume;
public PNLConfig(bts.config.PNLOptions options) {
enable_animations = options.enable_animations;
show_pause_resume = options.show_pause_resume;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class AddMissingAnimationsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null && (
_apply(ref settings, settings.animations, PNLSettings.default_animations, (s, anims) => s.with(animations: anims)) |
_apply(ref settings, settings.group_header_animations, PNLSettings.default_group_header_animations, (s, anims) => s.with(group_header_animations: anims)) |
_apply(ref settings, settings.header_row_animations, PNLSettings.default_header_row_animations, (s, anims) => s.with(header_row_animations: anims)))) {
//
new_settings = settings;
return true;
}
new_settings = null;
return false;
}
static bool _apply(ref PNLSettings settings, IEnumerable<PNLAnimationTriggerData> actual_triggers, IEnumerable<PNLAnimationTriggerData> default_triggers, Func<PNLSettings, PNLAnimationTriggerData[], PNLSettings> set_triggers) {
if (_apply(actual_triggers, default_triggers, out var result)) {
settings = set_triggers(settings, actual_triggers.Concat(result).ToArray());
return true;
}
return false;
}
static bool _apply(IEnumerable<PNLAnimationTriggerData> actual_triggers, IEnumerable<PNLAnimationTriggerData> default_triggers, out IEnumerable<PNLAnimationTriggerData> result) {
var default_trigger_map = default_triggers.ToDictionary(t => t.expression);
var actual_trigger_map = actual_triggers.ToImmutableDictionary(t => t.expression);
var snapshot = actual_trigger_map;
foreach (var kv in snapshot) {
if (default_trigger_map.TryGetValue(kv.Key, out var default_anims)) {
// assume 1 animation per column
var actual_col_anims = kv.Value.animations.ToDictionaryCrushed(a => a.column);
var default_col_anims = default_anims.animations.ToDictionaryCrushed(a => a.column);
actual_col_anims.Difference(default_col_anims,
out var exclusive_actual,
out var exclusive_defaults,
out var diff);
var new_col_anims = exclusive_defaults.ToList();
if (new_col_anims.Count > 0) {
// add the original col animations to the new ones (combine them)
new_col_anims.AddRange(actual_col_anims);
actual_trigger_map = actual_trigger_map.SetItem(kv.Key, kv.Value.with(animations: new_col_anims.Select(col_anim => col_anim.Value).ToArray()));
}
}
}
foreach (var kv in default_trigger_map) {
if (!actual_trigger_map.ContainsKey(kv.Key))
actual_trigger_map = actual_trigger_map.Add(kv.Key, kv.Value);
}
if (actual_trigger_map != snapshot) {
result = actual_trigger_map.Values;
return true;
}
result = null;
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class AddMissingColumnsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null) {
var defaults = PNLSettings.Default;
if (_apply(ref settings, settings.grid.columns, defaults.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) |
_apply(ref settings, settings.group_columns, defaults.group_columns, (s, cols) => s.with(group_columns: cols)) |
_apply(ref settings, settings.header_columns, defaults.header_columns, (s, cols) => s.with(header_columns: cols))) {
new_settings = settings;
return true;
}
}
new_settings = null;
return false;
}
static bool _apply(ref PNLSettings settings, IEnumerable<GridColumnSettings> actual_columns, IEnumerable<GridColumnSettings> default_columns, Func<PNLSettings, IEnumerable<GridColumnSettings>, PNLSettings> set_columns) {
if (GridSettingsHelper.add_missing_columns(actual_columns, default_columns, out var new_cols)) {
settings = set_columns(settings, new_cols);
return true;
}
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class RemoveColumnsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null) {
if (_apply(ref settings, settings.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) |
_apply(ref settings, settings.group_columns, (s, cols) => s.with(group_columns: cols)) |
_apply(ref settings, settings.header_columns, (s, cols) => s.with(header_columns: cols))) {
new_settings = settings;
return true;
}
}
new_settings = null;
return false;
}
bool _apply(ref PNLSettings settings, IEnumerable<GridColumnSettings> columns, Func<PNLSettings, IEnumerable<GridColumnSettings>, PNLSettings> set_columns) {
if (_apply(columns, out var new_cols)) {
settings = set_columns(settings, new_cols);
return true;
}
return false;
}
bool _apply(IEnumerable<GridColumnSettings> columns, out IEnumerable<GridColumnSettings> result) {
var col_list = columns.ToList();
int orig_count = col_list.Count;
col_list.RemoveWhere(c => !Enum.TryParse<PNLView.Columns>(c.id, true, out var _));
if (col_list.Count < orig_count) {
result = col_list;
return true;
}
result = null;
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class RemoveColumnAnimationsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null) {
if (_apply(ref settings, settings.animations, (s, t) => s.with(animations: t)) |
_apply(ref settings, settings.group_header_animations, (s, t) => s.with(group_header_animations: t)) |
_apply(ref settings, settings.header_row_animations, (s, t) => s.with(header_row_animations: t))) {
new_settings = settings;
return true;
}
}
new_settings = null;
return false;
}
bool _apply(ref PNLSettings settings, IEnumerable<PNLAnimationTriggerData> triggers, Func<PNLSettings, IEnumerable<PNLAnimationTriggerData>, PNLSettings> set_triggers) {
if (_apply(triggers, out var new_triggers)) {
settings = set_triggers(settings, new_triggers);
return true;
}
return false;
}
bool _apply(IEnumerable<PNLAnimationTriggerData> triggers, out IEnumerable<PNLAnimationTriggerData> result) {
var trigger_map = triggers.ToImmutableDictionary(t => t.expression);
var snapshot = trigger_map;
foreach (var t in trigger_map.Values) {
var anims = t.animations.ToList();
int orig_count = anims.Count;
anims.RemoveWhere(a => !Enum.IsDefined(typeof(PNLView.Columns), a.column));
if (anims.Count < orig_count)
trigger_map = trigger_map.SetItem(t.expression, t.with(animations: anims.ToArray()));
}
if (trigger_map != snapshot) {
result = trigger_map.Values;
return true;
}
result = null;
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class EnableGridBackgroundColorMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null && !settings.grid.enable_background_color) {
new_settings = settings.with(grid: settings.grid.with(enable_background_color: true));
return true;
}
new_settings = null;
return false;
}
}
}
using bts.api;
using bts.collections;
using bts.settings;
using bts.shell.pnl;
using bts.spark;
using bts.utils;
using mbts;
using mbts.config;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace bts.shell {
class PNLWindowFactory : ShellWindowFactory<PNLSaveState> {
const string _window_type = "PNL", _window_title = "PNL";
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly UserSettingsHub _settings_hub;
readonly PNLConfig _pnl_conf;
readonly IShellWindowThreadIDProvider _thread_id_provider;
public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, _window_type) {
_bus = bus;
_orders_model = orders_model;
_settings_hub = settings_hub;
_pnl_conf = new PNLConfig(Configuration.get<bts.config.PNLOptions>());
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get<bts.config.MultiThreadedWindows>().pnl);
_dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show);
}
public override Task<IShellWindow> load(PNLSaveState state) =>
Task.FromResult(_create(state.settings));
void _show(PNLSettings settings) =>
_bus.post(SparkTags.ShowWindow, _create(settings));
IShellWindow _create(PNLSettings settings) {
var settings_manager = _settings_hub.create_pnl_settings_manager(settings);
// Need to keep a local copy of the columns, since they are defined in xaml (not the viewmodel), and get_save_state may be called on a non-dispatcher thread.
// If that happens, we would be unable to access _grid.Columns, and thus unable to get the current column settings.
// Use an ImmutableList to avoid any threading issues when responding to CollectionChanged events on the dispatcher thread.
ImmutableList<DIYGrid.ColumnBase> cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty;
return SparkWindow<PNLSaveState>.create(_window_type, _window_title, _bus, this, Icons.Accounting, _thread_id_provider.next_id(), () => {
var vm = new PNLVM(_bus, _orders_model, settings ?? PNLSettings.Default);
var content = new PNLView {
DataContext = vm
};
vm.sorting_changed += sh => {
try {
DIYGridSortHelper.set_sort_directions(sh, content._grid.Columns);
} catch { }
};
vm.SubscribeDisposed(
DIYGridSortHelper.observe_active_comparers<PNLView.Columns, PNLRowVM>(content._grid, PNLVM.get_column_comparer)
.OnDispatcher()
.Subscribe(sh => vm.sorting_hierarchy = sh.Select(s => (s.key, s.direction)).ToList()));
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
Func<PNLSaveState> get_save_state = () => {
var cols = cached_columns.ToArray(c => c.create());
var filters = vm.get_filters_states();
var sorting_criterion = vm.sorting_hierarchy.Select(tup => new SortingCriteria(tup.key.ToString(), tup.direction == ListSortDirection.Ascending)).ToArray();
var calc_type = vm.calculation_type;
var state = settings_manager.instance_settings;
if (state == null) {
// don't use defaults if the user manipulated the window state outside of the settings dialog (e.g., resized column(s) via drag, or changed sort/filter)
var defaults = settings_manager.default_settings;
if (calc_type == defaults.calculation_type &&
defaults.sorting_criterion.SequenceEqual(sorting_criterion) &&
defaults.grid.columns.SequenceEqual(cols) && defaults.filters.safe_equals(filters)) {
// the user's current state still matches the defaults (i.e., no outside manipulation was performed); return null so this window will use the latest default settings when restored
return new PNLSaveState { use_defaults = true, settings = null };
}
state = defaults;
}
// assign latest values, as they may have be modified outside of the settings dialog (in which case the settings manager would be out of date)
state = state.with(
sorting_criterion,
vm.anchors,
filters,
state.grid.with(columns: cols, background: vm.grid_background_color.rgb_color()),
calc_type,
vm.header_row_display);
return new PNLSaveState { use_defaults = false, settings = state };
};
IEnumerable<SparkCommand> commands = new[] {
new SparkCommandCommand("Collapse All", Icons.RightArrow, new DelegateCommand(() => vm.set_all_expanded(false))),
new SparkCommandCommand("Expand All", Icons.DownArrow, new DelegateCommand(() => vm.set_all_expanded(true))),
new SparkCommandCommand("Play", Icons.Play, new DelegateCommand(() => vm.is_paused = false)) {
show_in_context_menu = _pnl_conf.show_pause_resume,
show_in_toolbar = _pnl_conf.show_pause_resume
},
new SparkCommandCommand("Pause", Icons.Pause, new DelegateCommand(() => vm.is_paused = true)) {
show_in_context_menu = _pnl_conf.show_pause_resume,
show_in_toolbar = _pnl_conf.show_pause_resume
},
SparkCommands.window_settings_command(new DialogCommand(() => {
settings_manager.instance_settings = get_save_state().settings;
var dialog_vm = new ShellSettingsDialogVM<PNLSettings, PNLSettingsVM>(
settings_manager,
us => us.pnl,
UserSettings.FileExtensions.PNL,
s => new PNLSettingsVM(s));
var dialog = new ShellSettingsDialog { DataContext = dialog_vm };
dialog_vm.RequestClose += on_request_close;
return dialog;
void on_request_close(object sender, EventArgs e) =>
WindowUtilities.force_close(dialog);
}))
};
IDisposable dispose = Disposable.Create(
settings_manager.subscribe_current().OnDispatcher().Subscribe(s => {
vm.load_from(s);
var col_setting_map = s.grid.columns.ToDictionary(c => c.id);
var fallback_family = new FontFamily(s.grid.font_family);
// group
var group_col_setting_map = s.group_columns.ToDictionary(c => c.id);
var group_appearance = s.group_cell_appearance.to_appearance();
// header
var header_col_setting_map = s.header_columns.ToDictionary(c => c.id);
var header_appearance = s.header_cell_appearance.to_appearance();
//
foreach (var c in content._grid.Columns.OfType<PNLColumn>()) {
if (col_setting_map.TryGetValue(c.id, out var cs)) {
c.load_from(cs);
}
if (group_col_setting_map.TryGetValue(c.id, out var gcs)) {
c.load_group_params(
group_appearance.font_size,
gcs.font_weight_override ?? group_appearance.font_weight,
gcs.font_color_override ?? group_appearance.foreground,
group_appearance.font_family);
}
if (header_col_setting_map.TryGetValue(c.id, out var hcs)) {
c.load_header_params(
header_appearance.font_size,
hcs.font_weight_override ?? header_appearance.font_weight,
hcs.font_color_override ?? header_appearance.foreground,
header_appearance.font_family);
}
}
CollectionHelper.sync_with_never_duplicate(content._grid.Columns, s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
}),
content._grid.Columns.Subscribe((s, e) => {
switch (e.Action) {
case NotifyCollectionChangedAction.Add: add_new(); break;
case NotifyCollectionChangedAction.Remove: remove_old(); break;
case NotifyCollectionChangedAction.Replace:
case NotifyCollectionChangedAction.Move:
remove_old();
add_new();
break;
case NotifyCollectionChangedAction.Reset:
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
break;
}
void add_new() =>
cached_columns = e.NewStartingIndex >= 0 ?
cached_columns.InsertRange(e.NewStartingIndex, e.NewItems.OfType<DIYGrid.ColumnBase>()) :
cached_columns.AddRange(e.NewItems.OfType<DIYGrid.ColumnBase>());
void remove_old() =>
cached_columns = e.OldStartingIndex >= 0 ?
cached_columns.RemoveRange(e.OldStartingIndex, e.OldItems.Count) :
cached_columns.RemoveRange(e.OldItems.OfType<DIYGrid.ColumnBase>());
}),
Disposable.wrap_collection(commands.OfType<IDisposable>()),
vm);
return (content, commands, get_save_state, dispose);
},
min_width_offset: SystemParameters.HorizontalScrollBarButtonWidth + 8,
min_height_offset: 60);
}
readonly struct PNLConfig {
public readonly bool
enable_animations,
show_pause_resume;
public PNLConfig(bts.config.PNLOptions options) {
enable_animations = options.enable_animations;
show_pause_resume = options.show_pause_resume;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class AddMissingAnimationsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null && (
_apply(ref settings, settings.animations, PNLSettings.default_animations, (s, anims) => s.with(animations: anims)) |
_apply(ref settings, settings.group_header_animations, PNLSettings.default_group_header_animations, (s, anims) => s.with(group_header_animations: anims)) |
_apply(ref settings, settings.header_row_animations, PNLSettings.default_header_row_animations, (s, anims) => s.with(header_row_animations: anims)))) {
//
new_settings = settings;
return true;
}
new_settings = null;
return false;
}
static bool _apply(ref PNLSettings settings, IEnumerable<PNLAnimationTriggerData> actual_triggers, IEnumerable<PNLAnimationTriggerData> default_triggers, Func<PNLSettings, PNLAnimationTriggerData[], PNLSettings> set_triggers) {
if (_apply(actual_triggers, default_triggers, out var result)) {
settings = set_triggers(settings, actual_triggers.Concat(result).ToArray());
return true;
}
return false;
}
static bool _apply(IEnumerable<PNLAnimationTriggerData> actual_triggers, IEnumerable<PNLAnimationTriggerData> default_triggers, out IEnumerable<PNLAnimationTriggerData> result) {
var default_trigger_map = default_triggers.ToDictionary(t => t.expression);
var actual_trigger_map = actual_triggers.ToImmutableDictionary(t => t.expression);
var snapshot = actual_trigger_map;
foreach (var kv in snapshot) {
if (default_trigger_map.TryGetValue(kv.Key, out var default_anims)) {
// assume 1 animation per column
var actual_col_anims = kv.Value.animations.ToDictionaryCrushed(a => a.column);
var default_col_anims = default_anims.animations.ToDictionaryCrushed(a => a.column);
actual_col_anims.Difference(default_col_anims,
out var exclusive_actual,
out var exclusive_defaults,
out var diff);
var new_col_anims = exclusive_defaults.ToList();
if (new_col_anims.Count > 0) {
// add the original col animations to the new ones (combine them)
new_col_anims.AddRange(actual_col_anims);
actual_trigger_map = actual_trigger_map.SetItem(kv.Key, kv.Value.with(animations: new_col_anims.Select(col_anim => col_anim.Value).ToArray()));
}
}
}
foreach (var kv in default_trigger_map) {
if (!actual_trigger_map.ContainsKey(kv.Key))
actual_trigger_map = actual_trigger_map.Add(kv.Key, kv.Value);
}
if (actual_trigger_map != snapshot) {
result = actual_trigger_map.Values;
return true;
}
result = null;
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class AddMissingColumnsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null) {
var defaults = PNLSettings.Default;
if (_apply(ref settings, settings.grid.columns, defaults.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) |
_apply(ref settings, settings.group_columns, defaults.group_columns, (s, cols) => s.with(group_columns: cols)) |
_apply(ref settings, settings.header_columns, defaults.header_columns, (s, cols) => s.with(header_columns: cols))) {
new_settings = settings;
return true;
}
}
new_settings = null;
return false;
}
static bool _apply(ref PNLSettings settings, IEnumerable<GridColumnSettings> actual_columns, IEnumerable<GridColumnSettings> default_columns, Func<PNLSettings, IEnumerable<GridColumnSettings>, PNLSettings> set_columns) {
if (GridSettingsHelper.add_missing_columns(actual_columns, default_columns, out var new_cols)) {
settings = set_columns(settings, new_cols);
return true;
}
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class RemoveColumnsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null) {
if (_apply(ref settings, settings.grid.columns, (s, cols) => s.with(grid: s.grid.with(cols))) |
_apply(ref settings, settings.group_columns, (s, cols) => s.with(group_columns: cols)) |
_apply(ref settings, settings.header_columns, (s, cols) => s.with(header_columns: cols))) {
new_settings = settings;
return true;
}
}
new_settings = null;
return false;
}
bool _apply(ref PNLSettings settings, IEnumerable<GridColumnSettings> columns, Func<PNLSettings, IEnumerable<GridColumnSettings>, PNLSettings> set_columns) {
if (_apply(columns, out var new_cols)) {
settings = set_columns(settings, new_cols);
return true;
}
return false;
}
bool _apply(IEnumerable<GridColumnSettings> columns, out IEnumerable<GridColumnSettings> result) {
var col_list = columns.ToList();
int orig_count = col_list.Count;
col_list.RemoveWhere(c => !Enum.TryParse<PNLView.Columns>(c.id, true, out var _));
if (col_list.Count < orig_count) {
result = col_list;
return true;
}
result = null;
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class RemoveColumnAnimationsMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null) {
if (_apply(ref settings, settings.animations, (s, t) => s.with(animations: t)) |
_apply(ref settings, settings.group_header_animations, (s, t) => s.with(group_header_animations: t)) |
_apply(ref settings, settings.header_row_animations, (s, t) => s.with(header_row_animations: t))) {
new_settings = settings;
return true;
}
}
new_settings = null;
return false;
}
bool _apply(ref PNLSettings settings, IEnumerable<PNLAnimationTriggerData> triggers, Func<PNLSettings, IEnumerable<PNLAnimationTriggerData>, PNLSettings> set_triggers) {
if (_apply(triggers, out var new_triggers)) {
settings = set_triggers(settings, new_triggers);
return true;
}
return false;
}
bool _apply(IEnumerable<PNLAnimationTriggerData> triggers, out IEnumerable<PNLAnimationTriggerData> result) {
var trigger_map = triggers.ToImmutableDictionary(t => t.expression);
var snapshot = trigger_map;
foreach (var t in trigger_map.Values) {
var anims = t.animations.ToList();
int orig_count = anims.Count;
anims.RemoveWhere(a => !Enum.IsDefined(typeof(PNLView.Columns), a.column));
if (anims.Count < orig_count)
trigger_map = trigger_map.SetItem(t.expression, t.with(animations: anims.ToArray()));
}
if (trigger_map != snapshot) {
result = trigger_map.Values;
return true;
}
result = null;
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class EnableGridBackgroundColorMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null && !settings.grid.enable_background_color) {
new_settings = settings.with(grid: settings.grid.with(enable_background_color: true));
return true;
}
new_settings = null;
return false;
}
}
}
}
@@ -0,0 +1,8 @@
using mbts.ui.viewmodels;
namespace bts.shell.pnl {
class PNLAnchorHierarchyVM : ItemOrderParameterVM<PNLView.Columns> {
public PNLAnchorHierarchyVM()
: base("", PNLSettings.anchorable_columns) { }
}
}
@@ -1,122 +1,88 @@
using bts.proto;
using bts.collections;
using bts.proto;
using mbts;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utility.text;
using mbts.ui.viewmodels;
using System;
using System.Windows;
using System.Windows.Media;
using FontFamily = System.Windows.Media.FontFamily;
namespace bts.shell.pnl {
class PNLCellAppearanceOverrideVM : ViewModelBase {
bool
_is_background_overridden,
_is_font_color_overridden,
_is_font_weight_overridden,
_is_font_family_overridden,
_is_font_size_overridden;
class PNLCellAppearanceOverrideVM : ParameterGroupVM {
public PNLCellAppearanceOverrideVM(string display_name, string rule = null) : base(display_name) {
parameters.AddRange(background, font_color, font_weight);
background.can_override = true;
font_color.can_override = true;
font_weight.can_override = true;
}
FontWeight _font_weight_override;
FontFamily _font_family_override;
double _font_size_override = double.NaN;
// background
public bool is_background_overridden { get => _is_background_overridden; set => Set(ref _is_background_overridden, value); }
public ColorPickerPopupVM background_override { get; } = new ColorPickerPopupVM {
bind_opacity_to_alpha = true,
opacity = 1
};
// font color
public bool is_font_color_overridden { get => _is_font_color_overridden; set => Set(ref _is_font_color_overridden, value); }
public ColorPickerPopupVM font_color_override { get; } = new ColorPickerPopupVM();
// font weight
public bool is_font_weight_overridden { get => _is_font_weight_overridden; set => Set(ref _is_font_weight_overridden, value); }
public FontWeight font_weight_override { get => _font_weight_override; set => Set(ref _font_weight_override, value); }
// font family
public bool is_font_family_overriden { get => _is_font_family_overridden; set => Set(ref _is_font_family_overridden, value); }
public FontFamily font_family_override { get => _font_family_override; set => Set(ref _font_family_override, value); }
// font size
public bool is_font_size_overriden { get => _is_font_size_overridden; set => Set(ref _is_font_size_overridden, value); }
public double font_size_override { get => _font_size_override; set => Set(ref _font_size_override, value); }
public ColorOverrideParameterVM background { get; } = new ColorOverrideParameterVM("Background");
public ColorOverrideParameterVM font_color { get; } = new ColorOverrideParameterVM("Font Color");
public FontWeightOverrideParameterVM font_weight { get; } = new FontWeightOverrideParameterVM("Font Weight");
public GridColumnSettings apply_to(GridColumnSettings target) =>
target.with(
font_weight_override: new NullableFontWeightProto(is_font_weight_overridden ? font_weight_override : (FontWeight?)null),
font_color_override: new NullableColorProto(is_font_color_overridden ? font_color_override.color : (Color?)null),
background_color_override: new NullableColorProto(is_background_overridden ? background_override.color : (Color?)null));
font_weight_override: new NullableFontWeightProto(font_weight.effective_is_overridden ? font_weight.override_value : (FontWeight?)null),
font_color_override: new NullableColorProto(font_color.effective_is_overridden ? font_color.override_value : (Color?)null),
background_color_override: new NullableColorProto(background.effective_is_overridden ? background.override_value : (Color?)null));
public void load(GridColumnSettings settings) {
if (settings != null)
load(settings.font_weight_override, settings.font_color_override, settings.background_color_override);
public IDisposable connect_default_values(GridSettingsVM grid_defaults) =>
Disposable.Create(
grid_defaults.subscribe_font().Subscribe(v => {
font_weight.family = v.family;
font_weight.default_value = v.weight;
font_weight.size = v.size;
}),
grid_defaults.subscribe_font_color().Subscribe(v => {
font_color.default_value = v;
}),
grid_defaults.subscribe_background().Subscribe(v => {
background.default_value = v;
}));
public PNLAnimation create(PNLView.Columns col_key) {
var rv = new PNLAnimation {
column = col_key
};
if (background.effective_is_overridden)
rv.background = background.override_value.rgb_color();
if (font_color.effective_is_overridden)
rv.foreground = font_color.override_value.rgb_color();
if (font_weight.effective_is_overridden)
rv.font_weight = font_weight.override_value.ToOpenTypeWeight();
return rv;
}
public void load(FontParamsProto font_params) {
if (font_params == null)
return;
public void load(GridColumnSettings value) {
// font weight
is_font_weight_overridden = font_params.font_weight > 0;
if (is_font_weight_overridden)
font_weight_override = FontWeight.FromOpenTypeWeight(font_params.font_weight);
font_weight.is_overridden = value.font_weight_override.HasValue;
if (font_weight.is_overridden)
font_weight.override_value = value.font_weight_override.Value;
// font color
is_font_color_overridden = font_params.font_color > 0;
if (is_font_color_overridden)
font_color_override.color = font_params.font_color.rgb_color();
// font family
if (!string.IsNullOrEmpty(font_params.font_family)) {
font_family_override = new FontFamily(font_params.font_family);
}
if (!double.IsNaN(font_params.font_size) && font_params.font_size > 0) {
font_size_override = font_params.font_size;
} else {
font_size_override = double.NaN;
}
}
public void load(PNLAnimation animation) {
if (animation != null)
load(
animation.font_weight.HasValue ? FontWeight.FromOpenTypeWeight(animation.font_weight.Value) : (FontWeight?)null,
animation.foreground?.argb_color(),
animation.background?.argb_color());
}
public void load(FontWeight? font_weight, Color? font_color, Color? background) {
// font weight
is_font_weight_overridden = font_weight.HasValue;
if (is_font_weight_overridden)
font_weight_override = font_weight.Value;
// font color
is_font_color_overridden = font_color.HasValue;
if (is_font_color_overridden)
font_color_override.color = font_color.Value;
font_color.is_overridden = value.font_color_override.HasValue;
if (font_color.is_overridden)
font_color.override_value = value.font_color_override.Value;
// background
is_background_overridden = background.HasValue;
if (background.HasValue)
background_override.color = background.Value;
background.is_overridden = value.background_color_override.HasValue;
if (background.is_overridden)
background.override_value = value.background_color_override.Value;
}
public PNLAnimation to_animation(PNLView.Columns key) =>
new PNLAnimation {
column = key,
foreground = is_font_color_overridden ? font_color_override.color.rgb_color() : (uint?)null,
background = is_background_overridden ? background_override.color.rgb_color() : (uint?)null,
font_weight = is_font_weight_overridden ? font_weight_override.ToOpenTypeWeight() : (int?)null
};
public PNLCellAppearanceProto to_appearance_proto() =>
new PNLCellAppearanceProto {
background = is_background_overridden ? background_override.color.rgb_color() : (uint?)null,
font_params = to_font_params()
};
public FontParamsProto to_font_params() =>
new FontParamsProto {
typeface = new TypefaceProto(
font_family_override?.name(),
is_font_weight_overridden ? font_weight_override.ToOpenTypeWeight() : 0),
font_color = is_font_color_overridden ? font_color_override.color.rgb_color() : 0,
font_size = font_size_override
};
public void load(PNLAnimation value) {
// font weight
font_weight.is_overridden = value.font_weight.HasValue && value.font_weight.Value > 0;
if (font_weight.is_overridden)
font_weight.override_value = FontWeight.FromOpenTypeWeight(value.font_weight.Value);
// font color
font_color.is_overridden = value.foreground.HasValue;
if (font_color.is_overridden)
font_color.override_value = value.foreground.Value.argb_color();
// background
background.is_overridden = value.background.HasValue;
if (background.is_overridden)
background.override_value = value.background.Value.argb_color();
}
}
}
@@ -1,34 +1,51 @@
using mbts.ui.controls;
using mbts.ui.shell;
using System.Windows;
using FontFamily = System.Windows.Media.FontFamily;
using bts.collections;
using mbts.ui.viewmodels;
namespace bts.shell.pnl {
class PNLCellAppearanceVM : ViewModelBase {
FontWeight _font_weight;
FontFamily _font_family;
double _font_size = double.NaN;
class PNLHeaderRowCellAppearanceVM : ParameterGroupVM {
readonly FontParameterVM _font = new FontParameterVM("Font");
readonly ColorParameterVM
_background = new ColorParameterVM("Background"),
_font_color = new ColorParameterVM("Font Color");
readonly BooleanParameterVM
_show_totals = new BooleanParameterVM("Show Totals"),
_show_selected_totals = new BooleanParameterVM("Show Selected Totals");
public ColorPickerPopupVM background { get; } = new ColorPickerPopupVM { bind_opacity_to_alpha = true, opacity = 1 };
public ColorPickerPopupVM font_color { get; } = new ColorPickerPopupVM();
public FontWeight font_weight { get => _font_weight; set => Set(ref _font_weight, value); }
public FontFamily font_family { get => _font_family; set => Set(ref _font_family, value); }
public double font_size { get => _font_size; set => Set(ref _font_size, value); }
public PNLHeaderRowCellAppearanceVM() : base("Header Row Display") {
parameters.AddRange(
HeaderedParameterGroupVM.create("Fonts/Colors", _font, _font_color, _background),
HeaderedParameterGroupVM.create("Display", _show_totals, _show_selected_totals));
}
public PNLHeaderRowDisplay display {
get {
var rv = PNLHeaderRowDisplay.None;
if (_show_totals.value)
rv |= PNLHeaderRowDisplay.Total;
if (_show_selected_totals.value)
rv |= PNLHeaderRowDisplay.SelectedTotal;
return rv;
}
set {
_show_totals.value = (display & PNLHeaderRowDisplay.Total) != 0;
_show_selected_totals.value = (display & PNLHeaderRowDisplay.SelectedTotal) != 0;
}
}
public PNLCellAppearance to_appearance() =>
new PNLCellAppearance(font_color.color, background.color, font_weight, font_family, font_size);
new PNLCellAppearance(_font_color.value, _background.value, _font.weight, _font.family, _font.size);
public void load(PNLCellAppearance appearance) {
if (appearance.background.HasValue)
background.color = appearance.background.Value;
_background.value = appearance.background.Value;
if (appearance.foreground.HasValue)
font_color.color = appearance.foreground.Value;
_font_color.value = appearance.foreground.Value;
if (appearance.font_family != null)
font_family = appearance.font_family;
_font.family = appearance.font_family;
if (appearance.font_weight.HasValue)
font_weight = appearance.font_weight.Value;
_font.weight = appearance.font_weight.Value;
if (appearance.font_size > 0)
font_size = appearance.font_size;
_font.size = appearance.font_size;
}
}
}
@@ -1,133 +1,216 @@
using bts.collections;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.ui.viewmodels;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
namespace bts.shell.pnl {
class PNLColumnVM : ViewModelBase, ISimpleColumnVM {
readonly SimpleGridSettingsVM _owner;
readonly PNLView.Columns _pnl_id;
object _selected_item;
string _display_name;
bool _is_visible;
double _width;
HorizontalAlignment _horizontal_alignment;
class PNLModularCellAppearanceVM : TabularParameterGroupVM {
public static PNLModularCellAppearanceVM create(PNLColumnCellAppearanceVM default_cell_appearance, IReadOnlyObservableCollection<object> rules) {
var composite = new ObservableAggregateCollection<object>(new ObservableCollection<object> { default_cell_appearance });
composite.add_collection(rules);
return new PNLModularCellAppearanceVM(composite) {
selected_item = default_cell_appearance
};
}
public PNLColumnVM(SimpleGridSettingsVM owner, PNLView.Columns id) {
_owner = owner;
_pnl_id = id;
default_column_vm.PropertyChanged += echo;
void echo(object sender, PropertyChangedEventArgs e) {
switch (e.PropertyName) {
case nameof(is_font_weight_overridden):
case nameof(is_font_color_overridden):
RaisePropertyChanged(e.PropertyName);
PNLModularCellAppearanceVM(ObservableCollection<object> parameters) : base("", parameters) { }
}
class PNLColumnCellAppearanceVM : ParameterGroupVM {
PNLCellAppearanceOverrideVM _selected_cell_mode;
public static Rule create_rule(string rule) =>
new Rule(rule);
public PNLColumnCellAppearanceVM(string display_name) : base(display_name) {
parameters.AddRange(default_vm, group_vm, header_vm);
_selected_cell_mode = default_vm;
}
public PNLCellAppearanceOverrideVM selected_cell_mode { get => _selected_cell_mode; set => Set(ref _selected_cell_mode, value); }
public PNLCellAppearanceOverrideVM default_vm { get; } = new PNLCellAppearanceOverrideVM("Row") { is_expanded = true };
public PNLCellAppearanceOverrideVM group_vm { get; } = new PNLCellAppearanceOverrideVM("Group Row");
public PNLCellAppearanceOverrideVM header_vm { get; } = new PNLCellAppearanceOverrideVM("Header Row");
IEnumerable<PNLCellAppearanceOverrideVM> _cell_modes {
get {
yield return default_vm;
yield return group_vm;
yield return header_vm;
}
}
public IDisposable connect_default_values(GridSettingsVM grid_defaults) =>
new System.Reactive.Disposables.CompositeDisposable(
_cell_modes.Select(c => c.connect_default_values(grid_defaults)));
public class Rule : PNLColumnCellAppearanceVM {
public Rule(string rule_text) : base($"When {DisplayNameHelper.expression_snake_to_title_case(rule_text)}") =>
this.rule_text = rule_text;
public string rule_text { get; }
}
}
class PNLColumnSettingsVM : GridColumnSettingsVM {
readonly ObservableAggregateCollection<object> _cell_appearance_groups = new ObservableAggregateCollection<object>();
readonly _AutoRuleTabsWrapperVM _fonts_and_colors;
readonly PNLView.Columns _key;
public PNLColumnSettingsVM(PNLView.Columns key) : base(null) {
_key = key;
_fonts_and_colors = new _AutoRuleTabsWrapperVM("Fonts/Colors", key);
column_layout = new HeaderedParameterGroupVM("Column Layout", new ObservableCollection<object> {
header, width, horizontal_alignment
});
apply_flags(GridColumnSettingsFeatureFlags.None);
}
public HeaderedParameterGroupVM column_layout { get; }
public HeaderedParameterGroupVM fonts_and_colors => _fonts_and_colors;
public PNLColumnCellAppearanceVM default_cell_appearance => _fonts_and_colors.cell_appearance;
IEnumerable<PNLCellAppearanceOverrideVM> _all_cell_modes =>
_fonts_and_colors.parameters
.OfType<PNLColumnCellAppearanceVM>()
.SelectMany(c => c.parameters.OfType<PNLCellAppearanceOverrideVM>());
public void load_from(GridColumnSettings value, IReadOnlyDictionary<string, PNLAnimation> triggers, GridColumnSettings group, IReadOnlyDictionary<string, PNLAnimation> group_triggers, IReadOnlyDictionary<string, PNLAnimation> header_triggers, GridColumnSettings header) {
load_from(value);
_fonts_and_colors.load_from(value, triggers, group, group_triggers, header_triggers, header);
}
public IEnumerable<(string expression, PNLAnimation row, PNLAnimation group, PNLAnimation header)> get_triggers() =>
_fonts_and_colors.create();
public IDisposable connect_default_values(GridSettingsVM grid_defaults) =>
_fonts_and_colors.connect_default_values(grid_defaults);
public override string ToString() => "Default";
public override void sync_params() =>
parameters.SetItems(column_layout, fonts_and_colors);
/// <summary>
/// This class stores a <see cref="PNLColumnCellAppearanceVM"/> instance in a collection of parameters, and automatically replaces it with a <see cref="PNLModularCellAppearanceVM"/> when rules are loaded.
/// Conversely, it replaces the <see cref="PNLModularCellAppearanceVM"/> with the original instance when rules are unloaded.
/// The impetus: A special 'TabControl' based DataTemplate is defined in PNLSettingsView.xaml as the default for content of type <see cref="PNLModularCellAppearanceVM"/>.
/// </summary>
class _AutoRuleTabsWrapperVM : HeaderedParameterGroupVM {
public readonly PNLColumnCellAppearanceVM cell_appearance;
readonly ObservableAggregateCollection<object> _composite_parameters;
readonly ObservableCollection<PNLColumnCellAppearanceVM.Rule> _rules = new ObservableCollection<PNLColumnCellAppearanceVM.Rule>();
readonly IReadOnlyObservableCollection<object> _wrapped_rules;
readonly DeferrableActionWrapper _sync_params;
PNLModularCellAppearanceVM _cell_appearance_rules;
PNLView.Columns _id;
public _AutoRuleTabsWrapperVM(string display_name, PNLView.Columns id)
: this(display_name, id, new ObservableAggregateCollection<object>()) { }
_AutoRuleTabsWrapperVM(string display_name, PNLView.Columns id, ObservableAggregateCollection<object> parameters) : base(display_name, parameters) {
_id = id;
_composite_parameters = parameters;
cell_appearance = new PNLColumnCellAppearanceVM("Default");
_wrapped_rules = _rules.CastObservable<PNLColumnCellAppearanceVM.Rule, object>();
//_wrapped_rules = _rules.SelectObservable<PNLColumnCellAppearanceVM, object>(_ => _, obj => (PNLColumnCellAppearanceVM)obj);
// If there are no rules present, the view should display a flat list of font/colors parameters.
// If there are rules present, the view should use TabItems to represent each rule its associated font/color parameters,
// as well as an additional Tab for the 'defaults.'
// It is the responsibility of this class, as the viewmodel, to organize the parameters appropriately.
// Listen to rules.CollectionChanged events, and toggle between the 'flat list of default parameters' and the TabItem groups when rules.Count > 0 changes.
_composite_parameters.add_collection(cell_appearance.parameters);
_composite_parameters.add_collection(_wrapped_rules);
bool rules_present = false;
_sync_params = new DeferrableActionWrapper(sync_params);
_rules.CollectionChanged += (s, e) => _sync_params.execute();
void sync_params() {
if (rules_present != _rules.Count > 0) {
rules_present = !rules_present;
_composite_parameters.clear_collections();
if (rules_present) {
if (_cell_appearance_rules == null) {
_cell_appearance_rules = PNLModularCellAppearanceVM.create(cell_appearance, _wrapped_rules);
}
_composite_parameters.insert_collection(0, new ObservableCollection<object> { _cell_appearance_rules });
} else {
_composite_parameters.insert_collection(0, new ObservableCollection<object> { cell_appearance });
}
}
}
}
public IEnumerable<(string rule, PNLAnimation row, PNLAnimation group, PNLAnimation header)> create() =>
_rules.Select(r => (r.rule_text, r.default_vm.create(_id), r.group_vm.create(_id), r.header_vm.create(_id)));
public void load_from(GridColumnSettings value, IReadOnlyDictionary<string, PNLAnimation> triggers, GridColumnSettings group, IReadOnlyDictionary<string, PNLAnimation> group_triggers, IReadOnlyDictionary<string, PNLAnimation> header_triggers, GridColumnSettings header) {
using (_sync_params.defer_execution()) {
_rules.Clear();
cell_appearance.default_vm.load(value);
cell_appearance.group_vm.load(group);
cell_appearance.header_vm.load(header);
foreach (var kv in triggers) {
var rule_vm = PNLColumnCellAppearanceVM.create_rule(kv.Key);
rule_vm.default_vm.load(kv.Value);
if (group_triggers.TryGetValue(kv.Key, out var g)) {
rule_vm.group_vm.load(g);
}
if (header_triggers.TryGetValue(kv.Key, out var h))
rule_vm.header_vm.load(h);
_rules.Add(rule_vm);
}
}
}
GridSettingsVM _grid_defaults;
public IDisposable connect_default_values(GridSettingsVM grid_defaults) {
Log.assert(_grid_defaults == null && grid_defaults != null);
if (_rules.Count > 0) { }
_grid_defaults = grid_defaults;
_rules.CollectionChanged += _wtf;
_wtf(_rules, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
return Disposable.Create(
cell_appearance.connect_default_values(grid_defaults),
ObservableAutoWrapper.connect_item_hooks(_rules, r => r.connect_default_values(grid_defaults)),
ObservableAutoWrapper.connect_item_hooks(parameters,
obj => {
if (obj is PNLColumnCellAppearanceVM cell_app) {
return cell_app.connect_default_values(grid_defaults);
} else if (obj is PNLCellAppearanceOverrideVM cell_app_over) {
return cell_app_over.connect_default_values(grid_defaults);
}
return null;
}));
}
private void _wtf(object sender, NotifyCollectionChangedEventArgs e) {
if (_rules.Count > 0) {
}
switch (e.Action) {
case NotifyCollectionChangedAction.Reset:
break;
case NotifyCollectionChangedAction.Add:
break;
case NotifyCollectionChangedAction.Remove:
break;
default:
break;
}
}
}
public PNLCellAppearanceOverrideVM default_column_vm { get; } = new PNLCellAppearanceOverrideVM();
public PNLCellAppearanceOverrideVM group_column_vm { get; } = new PNLCellAppearanceOverrideVM();
public PNLCellAppearanceOverrideVM header_column_vm { get; } = new PNLCellAppearanceOverrideVM();
//
public ObservableCollection<PNLRuleColumnVM> rule_columns { get; } = new ObservableCollection<PNLRuleColumnVM>();
public object selected_item {
get => _selected_item;
set {
if (value != null)
Set(ref _selected_item, value);
}
}
public string id { get => _pnl_id.ToString(); set => Log.assert(value == _pnl_id.ToString()); }
public string display_name { get => _display_name; set => Set(ref _display_name, value); }
public double width { get => _width; set => Set(ref _width, value); }
public bool is_visible { get => _is_visible; set => Set(ref _is_visible, value); }
public bool is_font_color_overridden {
get => default_column_vm.is_font_color_overridden;
set => default_column_vm.is_font_color_overridden = value;
}
public HorizontalAlignment horizontal_alignment { get => _horizontal_alignment; set => Set(ref _horizontal_alignment, value); }
public ColorPickerPopupVM font_color_override => default_column_vm.font_color_override;
public bool is_font_weight_overridden { get => default_column_vm.is_font_weight_overridden; set => default_column_vm.is_font_weight_overridden = value; }
public FontWeight font_weight_override { get => default_column_vm.font_weight_override; set => default_column_vm.font_weight_override = value; }
public void apply_flags(GridColumnSettingsFeatureFlags flags) { }
public GridColumnSettings create() {
var result = new GridColumnSettings(id: id, display_name: display_name, is_visible: is_visible, horizontal_alignment: horizontal_alignment, width: width);
result = default_column_vm.apply_to(result);
return result;
}
public void load_from(GridColumnSettings value) {
_assert_id(value.id);
default_column_vm.load(value);
display_name = value.display_name;
width = value.width;
is_visible = value.is_visible;
horizontal_alignment = value.horizontal_alignment;
}
public void load_from(GridColumnSettings value, IReadOnlyDictionary<string, PNLAnimation> triggers, GridColumnSettings group, IReadOnlyDictionary<string, PNLAnimation> group_triggers, IReadOnlyDictionary<string, PNLAnimation> header_triggers, GridColumnSettings header) {
_assert_id(value.id);
load_from(value);
if (group != null)
group_column_vm.load(group);
if (header != null)
header_column_vm.load(header);
rule_columns.SetItems(triggers.Select(kv => {
var rule_col = new PNLRuleColumnVM(kv.Key);
rule_col.load_from(kv.Value, group_triggers.GetValueOrDefault(kv.Key), header_triggers.GetValueOrDefault(kv.Key));
return rule_col;
}));
}
public IEnumerable<(string expression, PNLAnimation row, PNLAnimation group, PNLAnimation header)> get_triggers() {
foreach (var col in rule_columns)
yield return (col.rule_text, col.row_params.to_animation(_pnl_id), col.group_params.to_animation(_pnl_id), col.header_params.to_animation(_pnl_id));
}
void _assert_id(string id) =>
Log.assert(id == _pnl_id.ToString(), $"PNLColumn id string '{id}' does not match the expected {typeof(PNLView.Columns)} key '{_pnl_id}.'");
public override string ToString() => "Default";
}
class PNLRuleColumnVM : ViewModelBase, IEquatable<PNLRuleColumnVM> {
public PNLRuleColumnVM(string rule_text) =>
this.rule_text = rule_text;
public string rule_text { get; }
public PNLCellAppearanceOverrideVM row_params { get; } = new PNLCellAppearanceOverrideVM();
public PNLCellAppearanceOverrideVM group_params { get; } = new PNLCellAppearanceOverrideVM();
public PNLCellAppearanceOverrideVM header_params { get; } = new PNLCellAppearanceOverrideVM();
public void load_from(PNLAnimation row, PNLAnimation group, PNLAnimation header) {
row_params.load(row);
group_params.load(group);
header_params.load(header);
}
public bool Equals(PNLRuleColumnVM other) =>
other != null && rule_text == other.rule_text;
public override bool Equals(object obj) => Equals(obj as PNLRuleColumnVM);
public override int GetHashCode() => rule_text.GetHashCode();
public override string ToString() => rule_text;
}
}
@@ -1,58 +1,60 @@
using bts.collections;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using bts.utils;
using mbts.ui.utility;
using mbts.ui.viewmodels;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using System.Linq;
using System.Windows.Media;
using FontFamily = System.Windows.Media.FontFamily;
namespace bts.shell.pnl {
class PNLGroupRowAppearanceVM : ViewModelBase, IValueFactory<(PNLCellAppearance appearance, IReadOnlyList<Color> background_colors)> {
FontWeight _font_weight;
FontFamily _font_family;
double _font_size = double.NaN;
class PNLGroupRowCellAppearanceVM : ParameterGroupVM {
readonly PNLAlternatingRowBackgroundVM _alternating_background_vm = new PNLAlternatingRowBackgroundVM();
readonly ColorParameterVM _font_color = new ColorParameterVM("Font Color");
readonly FontParameterVM _font = new FontParameterVM("Font");
public PNLGroupRowAppearanceVM() {
add_background_cmd = new DelegateCommand(_add_background);
// 4 elements is enough to alternate through any reasonable number of groups,
// and clicking to add new backgrounds seems awkward
for (int i = 0; i < 4; i++)
_add_background();
public PNLGroupRowCellAppearanceVM() : base("Group") {
parameters.AddRange(
new HeaderedParameterGroupVM("Fonts/Colors", new ObservableCollection<object> { _font, _font_color }),
_alternating_background_vm);
}
public ObservableCollection<NamedColorPickerPopupVM> background_colors { get; } = new ObservableCollection<NamedColorPickerPopupVM>();
public ColorPickerPopupVM font_color { get; } = new ColorPickerPopupVM();
public FontWeight font_weight { get => _font_weight; set => Set(ref _font_weight, value); }
public FontFamily font_family { get => _font_family; set => Set(ref _font_family, value); }
public double font_size { get => _font_size; set => Set(ref _font_size, value); }
public ICommand add_background_cmd { get; }
ObservableCollection<ColorParameterVM> _alternating_backgrounds => _alternating_background_vm.items;
public (PNLCellAppearance appearance, IReadOnlyList<Color> background_colors) create() =>
(new PNLCellAppearance(font_color.color, Colors.Transparent, font_weight, font_family, font_size),
background_colors.WrapSelectorRO(cp => cp.color));
public (PNLCellAppearance appearance, IReadOnlyList<Color> alternating_backgrounds) create() =>
(new PNLCellAppearance(_font_color.value, Colors.Transparent, _font.weight, _font.family, _font.size),
_alternating_backgrounds.Cast<ColorParameterVM>().Select(vm => vm.value).ToList());
public void load_from((PNLCellAppearance appearance, IReadOnlyList<Color> background_colors) value) {
var (app, bg_colors) = value;
// background colors
while (background_colors.Count < bg_colors.Count)
_add_background();
for (int i = 0; i < bg_colors.Count; i++)
background_colors[i].color = bg_colors[i];
//
if (app.foreground.HasValue) font_color.color = app.foreground.Value;
if (app.font_family != null) font_family = app.font_family;
if (app.font_weight.HasValue) font_weight = app.font_weight.Value;
if (app.font_size > 0) font_size = app.font_size;
public void load((PNLCellAppearance appearance, IReadOnlyList<Color> alternating_backgrounds) value) {
var (appearance, alternating_backgrounds) = value;
for (int i = 0; i < alternating_backgrounds.Count; i++) {
if (_alternating_backgrounds.Count > i) {
var vm = _alternating_backgrounds[i];
vm.value = alternating_backgrounds[i];
}
}
while (alternating_backgrounds.Count > _alternating_backgrounds.Count)
_alternating_backgrounds.Add(new ColorParameterVM($"Background {_alternating_backgrounds.Count}") {
value = alternating_backgrounds[_alternating_backgrounds.Count]
});
while (_alternating_backgrounds.Count > alternating_backgrounds.Count)
_alternating_backgrounds.RemoveAt(alternating_backgrounds.Count);
CollectionHelper.add_or_update_existing(_alternating_backgrounds, alternating_backgrounds, c => new ColorParameterVM("") { value = c }, (vm, c) => ((ColorParameterVM)vm).value = c);
if (appearance.foreground.HasValue)
_font_color.value = appearance.foreground.Value;
if (appearance.font_family != null)
_font.family = appearance.font_family;
if (appearance.font_weight.HasValue)
_font.weight = appearance.font_weight.Value;
if (appearance.font_size > 0)
_font.size = appearance.font_size;
}
}
void _add_background() =>
background_colors.Add(new NamedColorPickerPopupVM {
bind_opacity_to_alpha = true,
name = $"Background {background_colors.Count + 1}"
});
class PNLAlternatingRowBackgroundVM : HeaderedParameterGroupVM {
public PNLAlternatingRowBackgroundVM() : base("Alternating Backgrounds") =>
ObservableAutoWrapper.connect(items, parameters, c => c);
public ObservableCollection<ColorParameterVM> items { get; } = new ObservableCollection<ColorParameterVM>();
}
}
@@ -1,220 +1,145 @@
using bts.collections;
using bts.utils;
using mbts;
using mbts.collections;
using mbts.expression;
using mbts.spark;
using mbts.ui;
using mbts.ui.settings;
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.Collections.Specialized;
using System.Dynamic;
using System.Linq;
using ColumnKeys = bts.shell.pnl.PNLView.Columns;
namespace bts.shell.pnl {
class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM<PNLSettings>, IValueFactory<PNLSettings>, IObservable<PNLSettings>, ITemplateSelectorKey {
readonly IReadOnlyDictionary<ColumnKeys, AnchorItemVM> _anchor_cache;
readonly DeferrableActionWrapper _sync_anchors;
PNLCalculationType _calculation_type;
PNLHeaderRowDisplay _header_row_display;
PNLSettings _last_loaded;
public PNLSettingsVM(PNLSettings settings) {
// init anchor cache, deferrable resync
_anchor_cache = PNLSettings.anchorable_columns.ToDictionary(k => k, k => new AnchorItemVM(this, k));
_sync_anchors = new DeferrableActionWrapper(() => {
for (int i = 0; i < anchor_items.Count; i++) {
anchor_items[i].anchor_index = i + 1;
anchor_items[i].refresh();
}
});
core_settings_vm = new SimpleGridSettingsVM(column_factory: col_settings => {
var col_vm = new PNLColumnVM(core_settings_vm, EnumHelper.parse<ColumnKeys>(col_settings.id));
col_vm.load_from(col_settings);
return col_vm;
});
core_settings_vm.selection_highlight.bind_opacity_to_alpha = true;
_dispose = Disposable.Create(
anchor_items.Subscribe((s, e) => _sync_anchors.execute()));
load(settings);
}
public IEnumerable<AnchorItemVM> anchor_item_headers => _anchor_cache.Values;
public ObservableCollection<AnchorItemVM> anchor_items { get; } = new ObservableCollection<AnchorItemVM>();
public SimpleGridSettingsVM core_settings_vm { get; }
public PNLGroupRowAppearanceVM group_row_defaults { get; } = new PNLGroupRowAppearanceVM();
public PNLCellAppearanceVM header_row_defaults { get; } = new PNLCellAppearanceVM();
public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); }
public IEnumerable<PNLCalculationType> calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite);
public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); }
public IEnumerable<PNLHeaderRowDisplay> header_row_display_options => PNLSettings.header_row_display_options;
string ITemplateSelectorKey.key => GridSettingsTemplateKeys.PNL;
public PNLSettings get_result() {
var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded);
s.calculation_type = _calculation_type;
s.grid = core_settings_vm.create();
using bts.collections;
using mbts;
using mbts.expression;
using mbts.spark;
using mbts.ui;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.spark;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using ColumnKeys = bts.shell.pnl.PNLView.Columns;
namespace bts.shell.pnl {
class PNLSettingsVM : DisposableViewModelBase, IWindowSettingsVM<PNLSettings>, IValueFactory<PNLSettings>, IObservable<PNLSettings>, ITemplateSelectorKey {
PNLCalculationType _calculation_type;
PNLSettings _last_loaded;
public PNLSettingsVM(PNLSettings settings) {
core_settings_vm = new GridSettingsVM();
columns = core_settings_vm.columns.CastObservable<GridColumnSettingsVM, PNLColumnSettingsVM>();
load(settings);
_dispose = ObservableAutoWrapper.connect_item_hooks(columns, col => col.connect_default_values(core_settings_vm));
}
public PNLAnchorHierarchyVM anchor_hierarcy { get; } = new PNLAnchorHierarchyVM();
public GridSettingsVM core_settings_vm { get; }
public PNLGroupRowCellAppearanceVM group_row_defaults { get; } = new PNLGroupRowCellAppearanceVM();
public PNLHeaderRowCellAppearanceVM header_row_defaults { get; } = new PNLHeaderRowCellAppearanceVM();
public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); }
public IEnumerable<PNLCalculationType> calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite);
public IReadOnlyObservableCollection<PNLColumnSettingsVM> columns { get; }
string ITemplateSelectorKey.key => GridSettingsTemplateKeys.PNL;
public PNLSettings get_result() {
var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded);
s.calculation_type = _calculation_type;
s.grid = core_settings_vm.get_result();
// move anchor cols to the left, order wrt grouping hierarchy
var new_cols = new Lazy<List<GridColumnSettings>>(() => s.grid.columns.ToList());
for (int i = 0; i < s.grid.columns.Count; i++) {
var key = s.grid.columns[i].strong_id<ColumnKeys>();
if (_anchor_cache.TryGetValue(key, out var a) && a.anchor_index.HasValue) {
// anchor index is 1 based, subtract 1 to get 0 based
int anchor_index = a.anchor_index.Value - 1;
if (anchor_index != i && anchor_index >= 0 && anchor_index < s.grid.columns.Count) {
new_cols.Value.RemoveAt(i);
new_cols.Value.Insert(anchor_index, s.grid.columns[i]);
}
int anchor_index = anchor_hierarcy.value.indexOf(key);
if (anchor_index != i && anchor_index >= 0) {
new_cols.Value.RemoveAt(i);
new_cols.Value.Insert(anchor_index, s.grid.columns[i]);
}
}
// rule-based animations
var trigger_anims = core_settings_vm.columns
.OfType<PNLColumnVM>()
.SelectMany(c => c.get_triggers())
.GroupBy(tup => tup.expression)
.Where(g => CoreExpressionEvaluator<PNLRowData>.validate(g.Key))
.Select(g => (
expression: g.Key,
animations: g.ToArray()))
.ToList();
var normalized_anims = trigger_anims
.Where(tup => CoreExpressionEvaluator<PNLNormalizedData>.validate(tup.expression))
.ToList();
s = s.with(anchors: anchor_items.Select(vm => vm.key),
grid: new_cols.IsValueCreated ? s.grid.with(columns: new_cols.Value) : null,
group_columns: core_settings_vm.columns.OfType<PNLColumnVM>().Select(c => {
var col_settings = c.create();
col_settings = c.group_column_vm.apply_to(col_settings);
return col_settings;
}),
header_columns: core_settings_vm.columns.OfType<PNLColumnVM>().Select(c => {
var col_settings = c.create();
col_settings = c.header_column_vm.apply_to(col_settings);
return col_settings;
}),
animations: trigger_anims.Select(
ta => new PNLAnimationTriggerData {
expression = ta.expression,
animations = Array.ConvertAll(ta.animations, t => t.row)
}),
group_header_animations: normalized_anims
.Select(
ta => new PNLAnimationTriggerData {
expression = ta.expression,
animations = Array.ConvertAll(ta.animations, t => t.group)
}),
header_row_animations: normalized_anims.Select(
ta => new PNLAnimationTriggerData {
expression = ta.expression,
animations = Array.ConvertAll(ta.animations, t => t.header)
}));
s.header_row_display = header_row_display;
s.header_cell_appearance = PNLCellAppearanceProto.from_appearance(header_row_defaults.to_appearance());
// group
var (group_cell_appearance, group_row_background_colors) = group_row_defaults.create();
s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_cell_appearance);
s.group_background_colors.SetItems(group_row_background_colors.Select(c => c.rgb_color()));
//
return s;
}
public void load(PNLSettings value) {
_last_loaded = value;
header_row_defaults.load(value.header_cell_appearance.to_appearance());
group_row_defaults.load_from((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color())));
var column_map = _map_column_data(value.grid.columns, value.animations);
var group_column_map = _map_column_data(value.group_columns, value.group_header_animations);
var header_column_map = _map_column_data(value.header_columns, value.header_row_animations);
core_settings_vm.load_from(value.grid);
for (int i = 0; i < core_settings_vm.columns.Count; i++) {
var col_vm = core_settings_vm.columns[i] as PNLColumnVM ?? throw new InvalidOperationException($"In {nameof(PNLSettingsVM)}, all columns should be of type {typeof(PNLColumnVM)}.");
var key = EnumHelper.parse<ColumnKeys>(col_vm.id);
var (col_settings, trigger_animations) = column_map[key];
var group_data = group_column_map.GetNullable(key);
var header_data = header_column_map.GetNullable(key);
col_vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings);
}
using (_sync_anchors.defer_execution())
anchor_items.WrapSelector(a => a.key, k => _anchor_cache[k]).sync_with(value.anchors.Intersect(PNLSettings.anchorable_columns));
header_row_display = value.header_row_display;
calculation_type = value.calculation_type;
}
PNLSettings IValueFactory<PNLSettings>.create() => get_result();
void IValueFactory<PNLSettings>.load_from(PNLSettings value) => load(value);
IDisposable IObservable<PNLSettings>.Subscribe(IObserver<PNLSettings> observer) => throw new NotImplementedException();
static Dictionary<ColumnKeys, (GridColumnSettings settings, Dictionary<string, PNLAnimation> triggers)> _map_column_data(IEnumerable<GridColumnSettings> columns, IEnumerable<PNLAnimationTriggerData> triggers) {
var map = columns.ToDictionary(
c => c.strong_id<ColumnKeys>(),
c => (settings: c, triggers: new Dictionary<string, PNLAnimation>()));
foreach (var trig in triggers) {
foreach (var anim in trig.animations) {
if (map.TryGetValue(anim.column, out var col_data))
col_data.triggers[trig.expression] = anim;
}
}
return map;
}
void _append_or_remove_anchor(ColumnKeys key, bool include) {
if (!_anchor_cache.TryGetValue(key, out var vm))
throw new KeyNotFoundException($"Column key '{key}' is not anchorable (expected one of: {string.Join(", ", PNLSettings.anchorable_columns)}).");
if (vm.include == include)
return;
if (include) {
if (anchor_items.Any(a => a.key == key))
throw new InvalidOperationException($"{nameof(anchor_items)} already contains an element with key '{key}.'");
anchor_items.Add(vm);
vm.anchor_index = anchor_items.Count;
} else {
if (!anchor_items.Remove(vm))
throw new InvalidOperationException($"{nameof(anchor_items)} does not contain an element with key '{key}.'");
vm.anchor_index = null;
}
_sync_anchors.execute();
}
public class AnchorItemVM : ViewModelBase, IEquatable<AnchorItemVM> {
readonly PNLSettingsVM _owner;
int? _anchor_index;
public AnchorItemVM(PNLSettingsVM owner, ColumnKeys key) {
_owner = owner;
this.key = key;
}
public ColumnKeys key { get; }
public bool include { get => anchor_index.HasValue; set => _owner._append_or_remove_anchor(key, value); }
public int? anchor_index { get => _anchor_index; set => Set(ref _anchor_index, value); }
public void refresh() =>
RaisePropertyChanged(nameof(include), nameof(anchor_index));
public bool Equals(AnchorItemVM other) =>
other != null && key == other.key;
public override bool Equals(object obj) =>
Equals(obj as AnchorItemVM);
public override int GetHashCode() =>
key.GetHashCode();
public override string ToString() =>
EnumHelper.get_display_name(key);
}
}
}
// rule-based animations
var trigger_anims = columns
.SelectMany(c => c.get_triggers())
.GroupBy(tup => tup.expression)
.Where(g => CoreExpressionEvaluator<PNLRowData>.validate(g.Key))
.Select(g => (
expression: g.Key,
animations: g.ToArray()))
.ToList();
var normalized_anims = trigger_anims
.Where(tup => CoreExpressionEvaluator<PNLNormalizedData>.validate(tup.expression))
.ToList();
s = s.with(anchors: anchor_hierarcy.value,
grid: new_cols.IsValueCreated ? s.grid.with(columns: new_cols.Value) : null,
group_columns: columns.Select(c => {
var col_settings = c.create();
col_settings = c.default_cell_appearance.group_vm.apply_to(col_settings);
return col_settings;
}),
header_columns: columns.Select(c => {
var col_settings = c.create();
col_settings = c.default_cell_appearance.header_vm.apply_to(col_settings);
return col_settings;
}),
animations: trigger_anims.Select(
ta => new PNLAnimationTriggerData {
expression = ta.expression,
animations = Array.ConvertAll(ta.animations, t => t.row)
}),
group_header_animations: normalized_anims
.Select(
ta => new PNLAnimationTriggerData {
expression = ta.expression,
animations = Array.ConvertAll(ta.animations, t => t.group)
}),
header_row_animations: normalized_anims.Select(
ta => new PNLAnimationTriggerData {
expression = ta.expression,
animations = Array.ConvertAll(ta.animations, t => t.header)
}));
s.header_row_display = header_row_defaults.display;
s.header_cell_appearance = PNLCellAppearanceProto.from_appearance(header_row_defaults.to_appearance());
// group
var (group_cell_appearance, group_row_background_colors) = group_row_defaults.create();
s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_cell_appearance);
s.group_background_colors.SetItems(group_row_background_colors.Select(c => c.rgb_color()));
//
return s;
}
public void load(PNLSettings value) {
_last_loaded = value;
header_row_defaults.load(value.header_cell_appearance.to_appearance());
group_row_defaults.load((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color())));
var column_map = _map_column_data(value.grid.columns, value.animations);
var group_column_map = _map_column_data(value.group_columns, value.group_header_animations);
var header_column_map = _map_column_data(value.header_columns, value.header_row_animations);
core_settings_vm.load(value.grid, false);
using (core_settings_vm.begin_change_columns()) {
core_settings_vm.columns.SetItems(value.grid.columns.Select(c => {
var key = EnumHelper.parse<ColumnKeys>(c.id);
var vm = new PNLColumnSettingsVM(key);
var (col_settings, trigger_animations) = column_map[key];
var group_data = group_column_map.GetNullable(key);
var header_data = header_column_map.GetNullable(key);
vm.load_from(col_settings, trigger_animations, group_data?.settings, group_data?.triggers, header_data?.triggers, header_data?.settings);
return vm;
}));
}
anchor_hierarcy.value = value.anchors.Intersect(PNLSettings.anchorable_columns);
header_row_defaults.display = value.header_row_display;
calculation_type = value.calculation_type;
}
PNLSettings IValueFactory<PNLSettings>.create() => get_result();
void IValueFactory<PNLSettings>.load_from(PNLSettings value) => load(value);
IDisposable IObservable<PNLSettings>.Subscribe(IObserver<PNLSettings> observer) => throw new NotImplementedException();
static Dictionary<ColumnKeys, (GridColumnSettings settings, Dictionary<string, PNLAnimation> triggers)> _map_column_data(IEnumerable<GridColumnSettings> columns, IEnumerable<PNLAnimationTriggerData> triggers) {
var map = columns.ToDictionary(
c => c.strong_id<ColumnKeys>(),
c => (settings: c, triggers: new Dictionary<string, PNLAnimation>()));
foreach (var trig in triggers) {
foreach (var anim in trig.animations) {
if (map.TryGetValue(anim.column, out var col_data))
col_data.triggers[trig.expression] = anim;
}
}
return map;
}
}
}
@@ -291,7 +291,7 @@ namespace bts.shell.pnl {
};
public void load_from(PNLSettings settings) {
selection_highlight = settings.grid.selection_highlight.to_brush();
selection_highlight = settings.grid.selection_highlight.to_argb_brush();
grid_background_color = settings.grid.background;
calculation_type = settings.calculation_type;
if (settings.filters != null) {
@@ -0,0 +1,174 @@
<UserControl
x:Class="mbts.ui.spark.PNLSettingsView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pnl="clr-namespace:bts.shell.pnl"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:vm="clr-namespace:mbts.ui.viewmodels"
Content="{Binding}"
>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<usp:GridSettingsResources/>
</ResourceDictionary.MergedDictionaries>
<DataTemplate DataType="{x:Type pnl:PNLColumnSettingsVM}">
<ItemsControl ItemsSource="{Binding parameters}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:OrderedItemParameterVM}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="IncludeToggle" VerticalAlignment="Top" Margin="0,4,0,0" Width="22" IsChecked="{Binding value}">
<CheckBox.Height>
<Binding Path="ActualHeight" ElementName="AnchorBorder">
<Binding.Converter>
<!--Offset Margin.Top-->
<cv:DoubleSubtractionConverter Value="4"/>
</Binding.Converter>
</Binding>
</CheckBox.Height>
</CheckBox>
<Border x:Name="AnchorBorder" Grid.Column="1" BorderBrush="Transparent" BorderThickness="0,4,4,4" MinWidth="120" Padding="6,8" Cursor="{StaticResource {x:Static u:CursorsEx.GrabKey}}">
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
<u:CheckedStateDefinition Source="{u:DirectReference IncludeToggle}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver"/>
<VisualState Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Cursor">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource {x:Static u:CursorsEx.GrabbingKey}}"/>
</ObjectAnimationUsingKeyFrames>
<ColorAnimation Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Duration="0" To="{x:Static u:BTSColors.header_alternate_color}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup Name="CheckedStates">
<VisualState Name="Unchecked"/>
<VisualState Name="Checked">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="KeyIcon" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<DoubleAnimation Storyboard.TargetName="AnchorIndex" Storyboard.TargetProperty="Opacity" BeginTime="0" Duration="0" To="1"/>
<ColorAnimation Storyboard.TargetName="ColumnNameText" Storyboard.TargetProperty="Foreground.Color" BeginTime="0" Duration="0" To="Gold"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border.Resources>
<u:CursorsEx/>
</Border.Resources>
<Border.Background>
<SolidColorBrush Color="{x:Static u:BTSColors.header_color}"/>
</Border.Background>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image x:Name="KeyIcon" Height="11" Opacity="0">
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Geometry="{Binding Source={StaticResource {x:Static u:Icons.KeyGeometryKey}}}" Brush="Gold"/>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
<TextBlock x:Name="AnchorIndex" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="16,0,0,-2" FontSize="8.5" Foreground="Gold" Opacity="0">
<TextBlock.Text>
<Binding Path="checked_index">
<Binding.Converter>
<cv:IntAdditionConverter Value="1"/>
</Binding.Converter>
</Binding>
</TextBlock.Text>
</TextBlock>
<TextBlock x:Name="ColumnNameText" Grid.Column="1" Margin="6,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" FontWeight="Bold" Text="{Binding}">
<TextBlock.Foreground>
<SolidColorBrush Color="{x:Static u:BTSColors.header_text_color}"/>
</TextBlock.Foreground>
</TextBlock>
</Grid>
</Border>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLAnchorHierarchyVM}">
<Grid Margin="12,8">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock FontStyle="Italic">
<Run>
Check the groups you would like to use.
</Run>
<LineBreak/>
<Run>
Drag and drop them to change the grouping order.
</Run>
</TextBlock>
<ItemsControl
Grid.Row="1"
AllowDrop="True"
HorizontalAlignment="Left"
ItemsSource="{Binding items}"
Margin="0,8,0,0"
Loaded="_anchor_items_loaded"
>
</ItemsControl>
</Grid>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<UserControl.ContentTemplate>
<DataTemplate DataType="{x:Type pnl:PNLSettingsVM}">
<Grid>
<u:BindingProxy x:Name="ActionMenuItemsViewProxy" Value="{DynamicResource ActionMenuItemsView}"/>
<c:ActionMenu ItemsSource="{Binding Path='(u:BindingProxy.Value).(CollectionViewSource.View)', ElementName=ActionMenuItemsViewProxy}">
<ItemsControl.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource ComboBox.DelineatedGroupContainerStyle.DynamicFill}"/>
</ItemsControl.GroupStyle>
</c:ActionMenu>
<TabControl MinWidth="600" Margin="0,2,0,0" Style="{StaticResource FlatTabControl}">
<TabItem Header="Grid">
<ItemsControl
Grid.IsSharedSizeScope="True"
ItemsSource="{Binding core_settings_vm.parameters}"
/>
</TabItem>
<TabItem Header="Grouping" Content="{Binding anchor_hierarcy}"/>
<TabItem Header="Group Row Display">
<ItemsControl
Grid.IsSharedSizeScope="True"
ItemsSource="{Binding group_row_defaults.parameters}"
/>
</TabItem>
<TabItem Header="Header Row Display">
<ItemsControl
Grid.IsSharedSizeScope="True"
ItemsSource="{Binding header_row_defaults.parameters}"
/>
</TabItem>
<TabItem Header="Columns" Content="{Binding core_settings_vm}" ContentTemplate="{StaticResource ColumnsTabContent}"/>
</TabControl>
</Grid>
</DataTemplate>
</UserControl.ContentTemplate>
</UserControl>
@@ -0,0 +1,129 @@
using bts;
using mbts.ui.controls.adorners;
using mbts.ui.extensions;
using mbts.utils;
using System;
using System.Collections;
using System.Reactive.Disposables;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.ui.spark {
/// <summary>
/// Interaction logic for PNLSettingsView.xaml
/// </summary>
partial class PNLSettingsView : UserControl {
public PNLSettingsView() =>
InitializeComponent();
IDisposable _anchor_items_drag_drop_behavior;
void _anchor_items_loaded(object sender, RoutedEventArgs e) {
// connecting this drag/drop behavior is idempotent, just in case Loaded happens twice
Disposable.dispose(ref _anchor_items_drag_drop_behavior);
if (!(sender is ItemsControl ic))
return;
var root_grid = Window.GetWindow(ic)?.Content as Grid;
bool is_dragging = false;
IDisposable drag_op = null;
var cursor_resources = new Lazy<CursorsEx>();
_anchor_items_drag_drop_behavior = Disposable.Create(() => Disposable.dispose(ref drag_op));
DragDropHelper.subscribe_drag_start(ic).Subscribe(pt => {
if (!is_dragging &&
ic.InputHitTest(pt) is DependencyObject d &&
ic.ContainerFromElement(d) is FrameworkElement item_view &&
ic.ItemContainerGenerator.ItemFromContainer(item_view) is object item &&
item != DependencyProperty.UnsetValue) {
//
item_view.SetCurrentValue(OpacityProperty, 0.5);
is_dragging = true;
var sz = item_view.RenderSize;
var dv = new DrawingVisual();
using (var dc = dv.RenderOpen())
dc.DrawRoundedRectangle(new VisualBrush(item_view) { Stretch = Stretch.Uniform }, null, new Rect(sz), 0, 0);
SetCurrentValue(CursorProperty, Cursors.ScrollWE);
SetCurrentValue(AllowDropProperty, true);
is_dragging = true;
Disposable.replace(ref drag_op, new CompositeDisposable {
MouseTraceAdorner.trace_drag(root_grid, dv, sz),
DragDropHelper.connect_vertical_insertion_adorner(ic, root_grid),
this.SubscribePreviewDrop(on_drop),
this.SubscribePreviewMouseUp(on_preview_mouse_up),
this.SubscribePreviewDragOver(on_drag),
this.SubscribePreviewDragLeave(on_drag),
this.SubscribePreviewDragEnter(on_drag),
() => {
ClearValue(CursorProperty);
ClearValue(AllowDropProperty);
item_view.ClearValue(OpacityProperty);
is_dragging = false;
}});
DragDrop.DoDragDrop(this, new DataObject(DataFormats.StringFormat, item), DragDropEffects.Move);
}
});
void on_drag(object s, DragEventArgs de) =>
de.Effects = DragDropEffects.Move;
void on_drop(object _, DragEventArgs drop_e) {
drop_e.Handled = true;
if (!is_dragging)
return;
Disposable.dispose(ref drag_op);
if (drop_e.Data.GetDataPresent(DataFormats.StringFormat) &&
drop_e.Data.GetData(DataFormats.StringFormat) is object from &&
ic.ItemsSource is IList anchor_items &&
anchor_items.Count > 1) {
//
var pt = drop_e.GetPosition(this);
if (!(InputHitTest(pt) is DependencyObject hit))
return;
try {
int from_i = anchor_items.IndexOf(from);
// Set the container to the first item who's right edge is left of pt.X (or the last item if none satisfy that condition).
// The logic presumes that the items are laid out in a single, horizontal line, from left to right
// (not the most elegant way to get the drop target, but it's effective).
int to_i = -1;
if (!(ic.ContainerFromElement(hit) is FrameworkElement drop_target)) {
for (to_i = 0; to_i < ic.Items.Count; to_i++) {
if (ic.ItemContainerGenerator.ContainerFromIndex(to_i) is FrameworkElement c) {
drop_target = c;
var tl = c.TranslatePoint(new Point(0, 0), this);
var bottom_edge = tl.Y + c.ActualHeight;
if (bottom_edge >= pt.Y)
break;
}
}
} else if (drop_target.DataContext is object to) {
to_i = anchor_items.IndexOf(to);
var drop_target_pt = TranslatePoint(pt, drop_target);
if (drop_target_pt.Y > drop_target.ActualHeight / 2) {
// target is "Between drop_target and the item below it"
if (from_i > to_i)
to_i++;
} else {
// target is "Between drop_target and the item above it"
if (from_i < to_i) {
to_i--;
}
}
}
if (to_i < 0)
return;
if (to_i >= anchor_items.Count)
to_i = anchor_items.Count - 1;
if (from_i >= 0)
anchor_items.Move(from_i, to_i);
} catch (Exception ex) {
Log.Ui.warn($"Error dropping anchor hiearchy item in pnl settings dialog: {ex}.");
}
}
}
void on_preview_mouse_up(object _, MouseButtonEventArgs __) =>
Disposable.dispose(ref drag_op);
}
}
}
@@ -79,6 +79,15 @@ namespace mbts.ui.shell {
// ensure notifications will be in on the same thread as IProperty<T>.Subscribe (don't use .Select extension)
Observable.Create<T>(o => property.Subscribe(ch => o.OnNext(ch.newval)));
public static IObservable<T> SubscribeValue<T>(this IProperty<T> property, bool start_immediately) =>
start_immediately ?
// ensure notifications will be in on the same thread as IProperty<T>.Subscribe (don't use .Select extension)
Observable.Create<T>(o => {
o.OnNext(property.Value);
return property.Subscribe(ch => o.OnNext(ch.newval));
}) :
SubscribeValue(property);
//public static IDisposable S
public static IProperty<T> block_reentrancy<T>(this IProperty<T> source) =>
@@ -31,10 +31,14 @@ namespace mbts.spark {
string _id = string.Empty;
GridColumnSettings _settings;
public GridColumnSettingsVM() {
public GridColumnSettingsVM()
: this(GridColumnSettingsFeatureFlags.None) { }
protected GridColumnSettingsVM(GridColumnSettingsFeatureFlags? init_flags) {
if (font_color.override_value.A == 0)
font_color.set_override(font_color.override_value.with(255));
apply_flags(GridColumnSettingsFeatureFlags.None);
if (init_flags.HasValue)
apply_flags(init_flags.Value);
}
public string id { get => _id; private set => Set(ref _id, value); }
@@ -557,6 +557,39 @@
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:TabularParameterGroupVM}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TabControl
Grid.Row="1"
Background="Transparent"
BorderThickness="0,1,0,0"
VerticalAlignment="Stretch"
ItemsSource="{Binding parameters}"
SelectedItem="{Binding selected_item}"
DisplayMemberPath="name"
Style="{StaticResource FlatTabControl}"
>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem" BasedOn="{StaticResource FlatTabItem}">
<Setter Property="Header" Value="{Binding name}"/>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<ItemsControl ItemsSource="{Binding parameters}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:BooleanParameterVM}">
<Border Grid.ColumnSpan="3" Background="{u:Brush Transparent}" Height="{StaticResource ParamRowHeight}" HorizontalAlignment="Stretch">
<u:StateManager.Groups>
@@ -115,14 +115,23 @@ namespace mbts.spark {
IEnumerable<object> _visible_parameters {
get {
yield return _selection_highlight;
var fonts_and_colors = HeaderedParameterGroupVM.create("Fonts/Colors", _font_vm, _font_color);
if (_background_enabled)
yield return _background;
yield return _font_vm;
yield return _font_color;
fonts_and_colors.parameters.Add(_background);
fonts_and_colors.parameters.Add(_selection_highlight);
yield return fonts_and_colors;
}
}
public IDisposable begin_change_columns() {
var curr_col_id = current_column?.id;
return Disposable.Create(() => {
if (curr_col_id == null || !columns.TryGetFirst(c => c.id == curr_col_id, out var curr_column))
curr_column = columns.FirstOrDefault();
_current_column.set(curr_column);
});
}
public GridSettings get_result() {
var col_settings = new List<GridColumnSettings>();
foreach (var c in columns) {
@@ -140,7 +149,10 @@ namespace mbts.spark {
enable_background_color: _background_enabled);
}
public void load(GridSettings settings) {
public void load(GridSettings settings) =>
load(settings, true);
public void load(GridSettings settings, bool sync_columns) {
_font_vm.family = new FontFamily(settings.font_family);
_font_vm.weight = settings.font_weight;
_font_vm.size = settings.font_size;
@@ -152,22 +164,30 @@ namespace mbts.spark {
// assuming bind_opacity_to_alpha on the picker.
_background_enabled = settings.enable_background_color;
_background.value = settings.background;
var curr_col_id = current_column?.id;
columns.SetItems(settings.columns.Select(col => {
var vm = new GridColumnSettingsVM();
vm.load_from(col);
// reapply our favorite column flags
// this comes in handy when performing Load From Factory - the editor will contain
// a consistent view of what can be overridden and what cannot
if (_column_flags.TryGetValue(vm.id, out GridColumnSettingsFeatureFlags flags))
vm.apply_flags(flags);
return vm;
}));
if (curr_col_id == null || !columns.TryGetFirst(c => c.id == curr_col_id, out var curr_column))
curr_column = columns.FirstOrDefault();
_current_column.set(curr_column);
if (sync_columns) {
using (begin_change_columns()) {
columns.SetItems(settings.columns.Select(col => {
var vm = new GridColumnSettingsVM();
vm.load_from(col);
// reapply our favorite column flags
// this comes in handy when performing Load From Factory - the editor will contain
// a consistent view of what can be overridden and what cannot
if (_column_flags.TryGetValue(vm.id, out GridColumnSettingsFeatureFlags flags))
vm.apply_flags(flags);
return vm;
}));
}
}
_parameters.sync_with(_visible_parameters);
}
public IObservable<Color> subscribe_background() =>
_background.SubscribeValue(true);
public IObservable<Color> subscribe_font_color() =>
_font_color.SubscribeValue(true);
public IObservable<(FontFamily family, FontWeight weight, double size)> subscribe_font() =>
_font_vm.SubscribeValue(true);
}
}
@@ -0,0 +1,24 @@
using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
namespace mbts.ui.converters {
[ValueConversion(typeof(int), typeof(int))]
class IntAdditionConverter : IValueConverter {
public int Value { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is int i)
return i + Value;
return new ValidationResult(false, "Not an integer.");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is int i)
return i - Value;
return new ValidationResult(false, "Not an integer.");
}
}
}
@@ -4,7 +4,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ice="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
xmlns:orderbook="clr-namespace:bts.shell.orderbook"
xmlns:pnl="clr-namespace:bts.shell.pnl"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
@@ -99,62 +98,6 @@
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLCellAppearanceVM}">
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush2}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Font</TextBlock>
<c:PopupControl Grid.Column="2" Style="{StaticResource FontPickerPopupControl}"/>
<TextBlock Grid.Row="2" VerticalAlignment="Center">Font Color (default)</TextBlock>
<c:ColorPickerPopupWithOpacitySlider Grid.Row="2" Grid.Column="2" HorizontalAlignment="Stretch" SelectedColor="{Binding font_color.color}" Palettes="{Binding font_color.palettes}" CanUserEditOpacity="False"/>
<TextBlock Grid.Row="4" VerticalAlignment="Center">Background</TextBlock>
<c:ColorPickerPopupWithOpacitySlider Grid.Row="4" Grid.Column="2" HorizontalAlignment="Stretch" SelectedColor="{Binding background.color}" SelectedOpacity="{Binding background.opacity}" Palettes="{Binding background.palettes}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLGroupRowAppearanceVM}">
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush2}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Font</TextBlock>
<c:PopupControl Grid.Column="2" Style="{StaticResource FontPickerPopupControl}"/>
<TextBlock Grid.Row="2" VerticalAlignment="Center">Font Color (default)</TextBlock>
<c:ColorPickerPopupWithOpacitySlider Grid.Row="2" Grid.Column="2" HorizontalAlignment="Stretch" SelectedColor="{Binding font_color.color}" Palettes="{Binding font_color.palettes}" CanUserEditOpacity="False"/>
<TabControl Grid.Row="4" Grid.ColumnSpan="3" ItemsSource="{Binding background_colors}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<c:ColorPickerPopupWithOpacitySlider Margin="4" HorizontalAlignment="Stretch" SelectedColor="{Binding color}" SelectedOpacity="{Binding opacity}" Palettes="{Binding palettes}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
</DataTemplate>
<Style x:Key="CopyProfileTargetButton" TargetType="Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Height" Value="22"/>
@@ -253,95 +196,6 @@
</u:StyleSelectorKeyValue>
</u:KeyedStyleSelector>
<DataTemplate x:Key="AnchorItemContentTemplate">
<Border Padding="4">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="IsComboBoxItemStates">
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Height="11">
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Geometry="{Binding Source={StaticResource {x:Static u:Icons.KeyGeometryKey}}}" Brush="Gold"/>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="16,0,0,4" FontSize="8.5" Text="{Binding DataContext.anchor_index, RelativeSource={RelativeSource AncestorType=ComboBox}}">
<TextBlock.Foreground>
<SolidColorBrush Color="{x:Static anchor_color, MemberType={u:Nested u:BTSColors.PNL}}"/>
</TextBlock.Foreground>
<TextBlock.Visibility>
<Binding RelativeSource="{RelativeSource AncestorType=ComboBoxItem}">
<Binding.Converter>
<cv:ValueConverterPipe>
<StaticResource ResourceKey="IsNullConverter"/>
<cv:BooleanToVisibilityConverter/>
</cv:ValueConverterPipe>
</Binding.Converter>
</Binding>
</TextBlock.Visibility>
</TextBlock>
<TextBlock Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Normal" Foreground="Gold" Text="{Binding}"/>
</Grid>
</Border>
</DataTemplate>
<DataTemplate x:Key="AnchorItemTemplate">
<Border BorderBrush="Transparent" BorderThickness="4" Padding="6,8" Cursor="{StaticResource {x:Static u:CursorsEx.GrabKey}}">
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:MouseStateDefinition MouseSource="{Binding Group.Target, RelativeSource={RelativeSource Self}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="MouseStates">
<VisualState Name="Normal"/>
<VisualState Name="MouseOver"/>
<VisualState Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Cursor">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource {x:Static u:CursorsEx.GrabbingKey}}"/>
</ObjectAnimationUsingKeyFrames>
<ColorAnimation Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Duration="0" To="{x:Static u:BTSColors.header_alternate_color}"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border.Resources>
<u:CursorsEx/>
</Border.Resources>
<Border.Background>
<SolidColorBrush Color="{x:Static u:BTSColors.header_color}"/>
</Border.Background>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Height="11">
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Geometry="{Binding Source={StaticResource {x:Static u:Icons.KeyGeometryKey}}}" Brush="Gold"/>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="16,0,0,-2" FontSize="8.5" Foreground="Gold" Text="{Binding anchor_index}"/>
<TextBlock Grid.Column="1" Margin="6,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" FontWeight="Bold" Foreground="Gold" Text="{Binding}"/>
</Grid>
</Border>
</DataTemplate>
<u:KeyedTemplateSelector x:Key="GridSettingsTemplateSelector">
<u:TemplateSelectorKeyValue Key="{x:Static usp:GridSettingsTemplateKeys.SimpleGrid}">
<DataTemplate>
@@ -571,162 +425,7 @@
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static usp:GridSettingsTemplateKeys.PNL}">
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<c:ActionMenu HorizontalAlignment="Right" Margin="0,2,0,0" ItemsSource="{Binding DataContext.action_menu_items, RelativeSource={RelativeSource AncestorType=usp:ShellSettingsDialog}}"/>
<usp:GridSettingsView
Grid.Row="1"
DataContext="{Binding core_settings_vm}"
GridSectionContent="{Binding DataContext.instance_vm, RelativeSource={RelativeSource AncestorType=usp:ShellSettingsDialog}}"
CellContentTemplate="{DynamicResource PNLCellContentTemplate}"
>
<usp:GridSettingsView.GridSectionContentTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush3}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TabControl Grid.IsSharedSizeScope="True" VerticalAlignment="Top" Height="150" Padding="10">
<TabItem Header="Grouping" Content="{Binding}">
<TabItem.ContentTemplate>
<DataTemplate>
<GroupBox Grid.Column="3" Grid.RowSpan="3" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
<GroupBox.Resources>
<u:CursorsEx/>
</GroupBox.Resources>
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<TextBlock>Grouping</TextBlock>
<c:HelpButton>
<c:HelpButton.Resources>
<Style x:Key="HelpButtonToolTipStyleKey" TargetType="ToolTip">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock>
<Run>Check the group parameters you would like to use.</Run>
<LineBreak/>
<Run FontStyle="Italic">Hint: drag/drop the items below to change the grouping hierarchy.</Run>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</c:HelpButton.Resources>
</c:HelpButton>
<ItemsControl ItemsSource="{Binding anchor_item_headers}" ItemsPanel="{StaticResource HorizontalItemsPanelTemplate}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Margin="4,0,0,0" Content="{Binding key}" ContentTemplate="{StaticResource EnumDescriptionTemplate}" IsChecked="{Binding include}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</GroupBox.Header>
<ItemsControl
HorizontalAlignment="Left"
VerticalAlignment="Top"
AllowDrop="True"
ItemsSource="{Binding anchor_items}"
ItemTemplate="{StaticResource AnchorItemTemplate}"
ItemsPanel="{StaticResource HorizontalItemsPanelTemplate}"
Loaded="_pnl_anchor_items_loaded"
/>
</GroupBox>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
<TabItem Header="Grid" Content="{Binding core_settings_vm}">
<TabItem.ContentTemplate>
<DataTemplate>
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush2}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Font</TextBlock>
<c:PopupControl Grid.Column="2" HorizontalAlignment="Stretch" Style="{StaticResource FontPickerPopupControl}"/>
<TextBlock Grid.Row="2" VerticalAlignment="Center">Font Color (default)</TextBlock>
<c:ColorPickerPopupWithOpacitySlider Grid.Row="2" Grid.Column="2" HorizontalAlignment="Stretch" DataContext="{Binding font_color}" CanUserEditOpacity="False"/>
<TextBlock Grid.Row="4" VerticalAlignment="Center">Selection Highlight</TextBlock>
<c:ColorPickerPopupWithOpacitySlider Grid.Row="4" Grid.Column="2" HorizontalAlignment="Stretch" DataContext="{Binding selection_highlight}"/>
<TextBlock Grid.Row="6" VerticalAlignment="Center">Background</TextBlock>
<c:ColorPickerPopupWithOpacitySlider
Grid.Row="6"
Grid.Column="2"
HorizontalAlignment="Stretch"
SelectedColor="{Binding background.color}"
SelectedOpacity="{Binding background.opacity}"
Palettes="{Binding background.palettes}"
/>
</Grid>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
<TabItem Header="Group Row Defaults" Content="{Binding group_row_defaults}"/>
<TabItem Header="Header Row Display" Content="{Binding}">
<TabItem.ContentTemplate>
<DataTemplate DataType="{x:Type pnl:PNLSettingsVM}">
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush2}}" MaxWidth="{Binding Source={StaticResource HorizontalPush2}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ContentControl Grid.ColumnSpan="3" Content="{Binding header_row_defaults}"/>
<TextBlock Grid.Row="2" VerticalAlignment="Center">Display</TextBlock>
<ComboBox Grid.Row="2" Grid.Column="2" HorizontalAlignment="Stretch" ItemsSource="{Binding header_row_display_options}" ItemTemplate="{StaticResource EnumFlagsDescriptionTemplate}" SelectedItem="{Binding header_row_display}"/>
</Grid>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
<TabItem Header="Calculation" Content="{Binding}">
<TabItem.ContentTemplate>
<DataTemplate>
<Grid VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush2}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Calculation</TextBlock>
<ComboBox
Grid.Column="2"
HorizontalAlignment="Stretch"
ItemsSource="{Binding calculation_types}"
SelectedItem="{Binding calculation_type}"
ItemTemplate="{StaticResource EnumDescriptionTemplate}"
/>
</Grid>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</TabControl>
</Grid>
</DataTemplate>
</usp:GridSettingsView.GridSectionContentTemplate>
</usp:GridSettingsView>
</Grid>
<usp:PNLSettingsView/>
</DataTemplate>
</u:TemplateSelectorKeyValue>
</u:KeyedTemplateSelector>
@@ -1,14 +1,4 @@
using bts.shell.pnl;
using mbts.utils;
using mbts.ui.extensions;
using System;
using System.Collections.ObjectModel;
using System.Reactive.Disposables;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using mbts.ui.controls.adorners;
using System.Windows;
namespace mbts.ui.spark {
/// <summary>
@@ -24,102 +14,6 @@ namespace mbts.ui.spark {
LocalProfileItemTemplateKey = "LocalProfileItemTemplate",
SaveAsStyleKey = "SaveAsStyle",
SecurityMapKey = "SecurityMap";
#region PNL
// TODO: need to break up ShellSettingsDialog components into smaller parts, so the various settings dialogs can be more easily customized.
// Until then, certain esoteric behaviors for specific dialogs (e.g., pnl anchor items drag/drop behavior) will reside in this class.
IDisposable _pnl_anchor_items_drag_drop_behavior;
void _pnl_anchor_items_loaded(object sender, RoutedEventArgs e) {
// connecting this drag/drop behavior is idempotent, just in case Loaded happens twice
Disposable.dispose(ref _pnl_anchor_items_drag_drop_behavior);
if (!(sender is ItemsControl ic))
return;
bool is_dragging = false;
IDisposable drag_op = null;
var cursor_resources = new Lazy<CursorsEx>();
_pnl_anchor_items_drag_drop_behavior = Disposable.Create(() => Disposable.dispose(ref drag_op));
DragDropHelper.subscribe_drag_start(ic).Subscribe(pt => {
if (!is_dragging &&
ic.InputHitTest(pt) is DependencyObject d &&
ic.ContainerFromElement(d) is FrameworkElement item_view &&
ic.ItemContainerGenerator.ItemFromContainer(item_view) is object item &&
item != DependencyProperty.UnsetValue) {
//
item_view.SetCurrentValue(OpacityProperty, 0.5);
is_dragging = true;
var sz = item_view.RenderSize;
var dv = new DrawingVisual();
using (var dc = dv.RenderOpen())
dc.DrawRoundedRectangle(new VisualBrush(item_view) { Stretch = Stretch.Uniform }, null, new Rect(sz), 0, 0);
SetCurrentValue(CursorProperty, Cursors.ScrollWE);
SetCurrentValue(AllowDropProperty, true);
is_dragging = true;
Disposable.replace(ref drag_op, new CompositeDisposable {
MouseTraceAdorner.trace_drag(root_grid, dv, sz),
DragDropHelper.connect_horizontal_insertion_adorner(ic, root_grid),
this.SubscribePreviewDrop(on_drop),
this.SubscribePreviewMouseUp(on_preview_mouse_up),
this.SubscribePreviewDragOver(on_drag),
this.SubscribePreviewDragLeave(on_drag),
this.SubscribePreviewDragEnter(on_drag),
() => {
ClearValue(CursorProperty);
ClearValue(AllowDropProperty);
item_view.ClearValue(OpacityProperty);
is_dragging = false;
}});
DragDrop.DoDragDrop(this, new DataObject(DataFormats.StringFormat, item), DragDropEffects.Move);
}
});
void on_drag(object s, DragEventArgs de) =>
de.Effects = DragDropEffects.Move;
void on_drop(object _, DragEventArgs drop_e) {
drop_e.Handled = true;
if (!is_dragging)
return;
Disposable.dispose(ref drag_op);
if (drop_e.Data.GetDataPresent(DataFormats.StringFormat) &&
drop_e.Data.GetData(DataFormats.StringFormat) is PNLSettingsVM.AnchorItemVM from &&
ic.ItemsSource is ObservableCollection<PNLSettingsVM.AnchorItemVM> anchor_items &&
anchor_items.Count > 1) {
//
var pt = drop_e.GetPosition(this);
if (!(InputHitTest(pt) is DependencyObject hit))
return;
int from_i = anchor_items.IndexOf(from);
// Set the container to the first item who's right edge is left of pt.X (or the last item if none satisfy that condition).
// The logic presumes that the items are laid out in a single, horizontal line, from left to right
// (not the most elegant way to get the drop target, but it's effective).
int to_i = -1;
if (!(ic.ContainerFromElement(hit) is FrameworkElement drop_target)) {
for (to_i = 0; to_i < ic.Items.Count; to_i++) {
if (ic.ItemContainerGenerator.ContainerFromIndex(to_i) is FrameworkElement c) {
drop_target = c;
var tl = c.TranslatePoint(new Point(0, 0), this);
var right_edge = tl.X + c.ActualWidth;
if (right_edge >= pt.X)
break;
}
}
} else if (drop_target.DataContext is PNLSettingsVM.AnchorItemVM to) {
to_i = anchor_items.IndexOf(to);
}
if (to_i < 0)
return;
if (to_i >= anchor_items.Count)
to_i = anchor_items.Count - 1;
if (from_i >= 0)
anchor_items.Move(from_i, to_i);
}
}
void on_preview_mouse_up(object _, MouseButtonEventArgs __) =>
Disposable.dispose(ref drag_op);
}
#endregion
}
static class GridSettingsTemplateKeys {
@@ -24,6 +24,9 @@ namespace mbts.ui.utilities {
SnakeToTitleCaseConverter = ValueConverter.create(obj => snake_to_title_case(obj?.ToString())),
ExpressionSnakeToTitleCaseConverter = ValueConverter.create(obj => snake_to_title_case(obj?.ToString(), @"[A-Za-z0-9_\-\s\(\)<>=]*"));
public static string expression_snake_to_title_case(string expression, TextCapitalizationFormat capitalization_format = TextCapitalizationFormat.Default) =>
snake_to_title_case(expression, @"[A-Za-z0-9_\-\s\(\)<>=]*");
// Adds spaces to CamelCase => "Camel Case"
public static string camel_to_title_case(string name, TextCapitalizationFormat capitalization_format = TextCapitalizationFormat.Default) {
if (name != null) {
@@ -24,6 +24,19 @@ namespace mbts.ui.utility {
return Enum.GetValues(t);
}
// TODO: avoid boxing
public static T add_flags<T>(T value, T flags) where T : struct {
var v = (long)(object)value;
var f = (long)(object)flags;
return (T)(object)(v | f);
}
public static T remove_flags<T>(T value, T flags) where T : struct {
var v = (long)(object)value;
var f = (long)(object)flags;
return (T)(object)((v ^ f) & v);
}
public static T parse<T>(string name) where T : struct /*(Enum, more specifically)*/ {
if (!typeof(T).IsEnum) throw new InvalidOperationException($"{typeof(T)} is not an enum type.");
if (!Enum.TryParse(name, true, out T result)) throw new ArgumentException(nameof(name), "Does not match any of the values");
@@ -0,0 +1,122 @@
using bts.collections;
using bts.utils;
using mbts.collections;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace mbts.ui.viewmodels {
class OrderedItemParameterVM : BooleanParameterVM {
int _index, _checked_index;
public OrderedItemParameterVM(string name) : base(name) { }
public int index {
get => _index;
set => Set(ref _index, value);
}
public int checked_index {
get => _checked_index;
set => Set(ref _checked_index, value);
}
}
class ItemOrderParameterVM<T> : ParameterVM<IEnumerable<T>>, IDisposable {
readonly ObservableList<Item> _items = new ObservableList<Item>();
//readonly IReadOnlyObservableCollection<Item> _checked_items;
readonly IList<T> _wrapped_keys;
readonly DeferrableActionWrapper _refresh_indices, _refresh_value, _load_value;
IDisposable _dispose;
public ItemOrderParameterVM(string name)
: base(name) { }
public ItemOrderParameterVM(string name, IEnumerable<T> items)
: this(name, items, EqualityComparer<T>.Default) { }
public ItemOrderParameterVM(string name, IEnumerable<T> available_items, IEqualityComparer<T> comparer)
: base(name) {
_wrapped_keys = _items.WrapSelector(item => item.key, k => new Item(k));
_wrapped_keys.AddRange(available_items);
//_checked_items = ObservableFilterCollection.create(_items, item => item.value);
_refresh_indices = new DeferrableActionWrapper(refresh_indices);
_refresh_value = new DeferrableActionWrapper(refresh_value);
_load_value = new DeferrableActionWrapper(load_value);
// If this class is ever used with large collections,
// the 'refresh_indices' method may need to be optimized.
// It is naturally an O(n) op, but execution could be throttled.
refresh_indices();
_dispose = Disposable.Create(
ObservableAutoWrapper.connect_item_hooks(items,
item => item.SubscribeValue().Subscribe(_ => _refresh_indices.execute())),
items.Subscribe((s, e) => _refresh_indices.execute()));
//
void refresh_indices() {
int checked_index = 0;
for (int i = 0; i < items.Count; i++) {
items[i].index = i;
items[i].checked_index = checked_index;
if (items[i].value)
checked_index++;
}
}
void refresh_value() {
using (_refresh_value.supress_execution())
value = _checked_keys.ToList();
}
void load_value() {
using (_load_value.supress_execution())
using (_refresh_indices.defer_execution()) {
foreach (var v in _items)
v.value = false;
int i = 0;
foreach (var v in value) {
int curr_pos = _wrapped_keys.IndexOf(v);
if (curr_pos >= 0) {
_items[curr_pos].value = true;
if (curr_pos != i)
_items.Move(curr_pos, i++);
}
}
}
}
}
public IReadOnlyObservableCollection<OrderedItemParameterVM> items => _items;
IEnumerable<T> _checked_keys =>
_items.Where(i => i.value).Select(i => i.key);
public void Dispose() =>
Disposable.dispose(ref _dispose);
protected override void on_changed_end(IEnumerable<T> oldval, IEnumerable<T> newval) =>
_load_value.execute();
public class Item : OrderedItemParameterVM, IEquatable<Item> {
public Item(T key) : base(EnumHelper.get_display_name(key)) =>
this.key = key;
public T key { get; }
public bool Equals(Item other) =>
other != null &&
EqualityComparer<T>.Default.Equals(key, other.key);
public override bool Equals(object obj) =>
Equals(obj as Item);
public override int GetHashCode() =>
key.GetHashCode();
public override string ToString() =>
EnumHelper.get_display_name(key);
}
}
}