impl new PNL settings dialog

This commit is contained in:
John Colvin committed 2019-08-19 13:15:00 -05:00
1 parent a36f9278d5
commit efa07fe96e
12 files changed
+1666 -312

No files matched your search

@@ -1,198 +1,213 @@
using bts.api;
using bts.collections;
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 System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
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) {
if (settings != null) {
var def_grid = PNLSettings.DefaultGridSettings;
// add missing columns (i.e., if new cols were added after this workspace was saved)
if (settings.grid.columns.Count != def_grid.columns.Count) {
settings.grid.columns.difference_hard(def_grid.columns, out var added, out var removed, EqualityComparer.Create<GridColumnSettings, string>(c => c.id));
var new_cols = settings.grid.columns.ToList();
for (int i = 0; i < added.Count; i++) {
var col = added[i];
new_cols.Add(col);
}
settings.grid = settings.grid.with(columns: new_cols);
}
}
var settings_manager = new WindowSettingsManager<PNLSettings>(_settings_hub,
settings,
get: us => us.pnl,
set: (us, pnl) => us.with(pnl: pnl));
// 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(), () => {
IEnumerable<SortingCriteria> last_sorting_criterion = null;
var vm = new PNLVM(_bus, _orders_model, settings ?? PNLSettings.Default);
var content = new PNLView {
DataContext = vm
};
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
Func<PNLSaveState> get_save_state = () => {
if (last_sorting_criterion == null)
last_sorting_criterion = PNLSettings.Default.sorting_criterion;
var cols = cached_columns.ToArray(c => c.create());
var filters = vm.get_filters_states();
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(last_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(
last_sorting_criterion,
vm.anchors,
filters,
state.grid.with(columns: cols),
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
}
};
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);
}
}
vm.rows_view.set_sort_descriptions(s.sorting_criterion, content._grid.Columns);
CollectionHelper.sync_with_never_duplicate(content._grid.Columns, s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
}),
vm.rows_view
.subscribe_sorting_criterion(sm => content._grid.Columns.TryGetFirst(dc => dc.sort_member_path == sm, out var match) ? match.id : null)
.Subscribe(sc => last_sorting_criterion = sc),
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;
}
}
}
}
using bts.api;
using bts.collections;
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.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) {
if (settings != null) {
var def_grid = PNLSettings.DefaultGridSettings;
// add missing columns (i.e., if new cols were added after this workspace was saved)
if (settings.grid.columns.Count != def_grid.columns.Count) {
settings.grid.columns.difference_hard(def_grid.columns, out var added, out var removed, EqualityComparer.Create<GridColumnSettings, string>(c => c.id));
var new_cols = settings.grid.columns.ToList();
for (int i = 0; i < added.Count; i++) {
var col = added[i];
new_cols.Add(col);
}
settings.grid = settings.grid.with(columns: new_cols);
}
}
var settings_manager = new WindowSettingsManager<PNLSettings>(_settings_hub,
settings,
get: us => us.pnl,
set: (us, pnl) => us.with(pnl: pnl));
// 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(), () => {
IEnumerable<SortingCriteria> last_sorting_criterion = null;
var vm = new PNLVM(_bus, _orders_model, settings ?? PNLSettings.Default);
var content = new PNLView {
DataContext = vm
};
cached_columns = ImmutableList<DIYGrid.ColumnBase>.Empty.AddRange(content._grid.Columns);
Func<PNLSaveState> get_save_state = () => {
if (last_sorting_criterion == null)
last_sorting_criterion = PNLSettings.Default.sorting_criterion;
var cols = cached_columns.ToArray(c => c.create());
var filters = vm.get_filters_states();
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(last_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(
last_sorting_criterion,
vm.anchors,
filters,
state.grid.with(columns: cols),
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);
}
}
vm.rows_view.set_sort_descriptions(s.sorting_criterion, content._grid.Columns);
CollectionHelper.sync_with_never_duplicate(content._grid.Columns, s.grid.columns, cs => {
throw new InvalidOperationException();
}, c => c.id.ToLower(), cs => cs.id.ToLower());
}),
vm.rows_view
.subscribe_sorting_criterion(sm => content._grid.Columns.TryGetFirst(dc => dc.sort_member_path == sm, out var match) ? match.id : null)
.Subscribe(sc => last_sorting_criterion = sc),
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;
}
}
}
}
@@ -0,0 +1,275 @@
using bts.collections;
using bts.proto;
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.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Media;
using FontFamily = System.Windows.Media.FontFamily;
namespace bts.shell.pnl {
class PNLCellAppearanceParamsVM : ViewModelBase {
FontWeight _font_weight;
FontFamily _font_family;
double _font_size = double.NaN;
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 PNLCellAppearance to_appearance() =>
new PNLCellAppearance(font_color.color, background.color, font_weight, font_family, font_size);
public void load(PNLCellAppearance appearance) {
if (appearance.background.HasValue)
background.color = appearance.background.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;
}
}
class PNLColumnParamsVM : ViewModelBase {
bool
_is_background_overridden,
_is_font_color_overridden,
_is_font_weight_overridden,
_is_font_family_overridden,
_is_font_size_overridden;
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 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_override: new NullableColorProto(is_background_overridden ? background_override.color : (Color?)null));
public void load(GridColumnSettings settings) {
if (settings != null)
load(settings.font_weight_override, settings.font_color_override, settings.background_override);
}
public void load(FontParamsProto font_params) {
if (font_params == null)
return;
// 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 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;
// background
is_background_overridden = background.HasValue;
if (background.HasValue)
background_override.color = background.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,
foreground = is_font_color_overridden ? font_color_override.color.rgb_color() : (uint?)null,
font_params = to_font_params()
};
public FontParamsProto to_font_params() =>
new FontParamsProto {
font_color = is_font_color_overridden ? font_color_override.color.rgb_color() : 0,
font_weight = is_font_weight_overridden ? font_weight_override.ToOpenTypeWeight() : 0,
font_family = font_family_override?.name(),
font_size = font_size_override
};
}
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;
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);
break;
}
}
}
public PNLColumnParamsVM default_column_vm { get; } = new PNLColumnParamsVM();
public PNLColumnParamsVM group_column_vm { get; } = new PNLColumnParamsVM();
public PNLColumnParamsVM header_column_vm { get; } = new PNLColumnParamsVM();
//
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 : ViewModelBaseWithValidation, IEquatable<PNLRuleColumnVM> {
public PNLRuleColumnVM(string rule_text) =>
this.rule_text = rule_text;
public string rule_text { get; }
public PNLColumnParamsVM row_params { get; } = new PNLColumnParamsVM();
public PNLColumnParamsVM group_params { get; } = new PNLColumnParamsVM();
public PNLColumnParamsVM header_params { get; } = new PNLColumnParamsVM();
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;
}
}
@@ -0,0 +1,211 @@
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
IDictionary<string, object> raw_anchor_cache = new ExpandoObject();
raw_anchor_cache.AddRange(PNLSettings.anchorable_columns
.Select(k => new KeyValuePair<string, object>(k.ToString(), new AnchorItemVM(this, k))));
_anchor_cache =
MappedDictionary.create(
new ReadOnlyDictionary<string, object>(anchor_vm = raw_anchor_cache),
ConvertUtils.CastDelegate<object, AnchorItemVM>.value,
EnumHelper.parse<ColumnKeys>,
k => k.ToString());
_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;
}) {
can_edit_background = true
};
core_settings_vm.selection_highlight.bind_opacity_to_alpha = true;
_dispose = Disposable.Create(
anchor_items.Subscribe((s, e) => _sync_anchors.execute()));
load(settings);
}
public dynamic anchor_vm { get; }
public ObservableCollection<AnchorItemVM> anchor_items { get; } = new ObservableCollection<AnchorItemVM>();
public SimpleGridSettingsVM core_settings_vm { get; }
public PNLCellAppearanceParamsVM group_row_defaults { get; } = new PNLCellAppearanceParamsVM();
public PNLCellAppearanceParamsVM header_row_defaults { get; } = new PNLCellAppearanceParamsVM();
public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); }
public IEnumerable<PNLCalculationType> calculation_types { get; } = EnumHelper.get_values_except(PNLCalculationType.None);
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();
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),
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());
s.group_cell_appearance = PNLCellAppearanceProto.from_appearance(group_row_defaults.to_appearance());
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());
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);
}
}
}
@@ -19,6 +19,7 @@ namespace mbts.ui {
[DisplayInfo(name = "Default Header")]
public static BTSColor header { get { return BTSCoreColors.base_blue; } }
public static Color header_color => header;
public static Brush header_brush { get { return _header_brush; } }
public static BTSColor header_text { get { return BTSCoreColors.white; } }
public static Color header_text_color => header_text;
@@ -27,6 +28,7 @@ namespace mbts.ui {
public static BTSColor header_border { get { return new BTSColor(0x63,0x8A,0xCC); } }
public static Brush header_text_brush { get { return _header_text_brush; } }
public static BTSColor header_alternate { get { return BTSCoreColors.blue_grey; } }
public static Color header_alternate_color => header_alternate;
public static BTSColor disabled_text { get { return BTSCoreColors.gray_light; } }
public static BTSColor pinkalicious { get { return new BTSColor(0xff, 0x33, 0x99); } }
@@ -0,0 +1,66 @@
using mbts.ui.extensions;
using mbts.utils;
using System;
using System.Reactive.Disposables;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.ui.controls.adorners {
class MouseTraceAdorner : Adorner {
readonly Visual _trace_visual;
readonly Size _trace_visual_size;
MouseTraceAdorner(UIElement adorned_element, Visual trace_visual, Size trace_visual_size)
: base(adorned_element) {
_trace_visual = trace_visual;
_trace_visual_size = trace_visual_size;
AddVisualChild(trace_visual);
IsHitTestVisible = false;
HorizontalAlignment = HorizontalAlignment.Left;
VerticalAlignment = VerticalAlignment.Top;
}
protected override int VisualChildrenCount => 1;
public static IDisposable trace(FrameworkElement target, Visual trace_visual, Size trace_visual_size) {
var mta = new MouseTraceAdorner(target, trace_visual, trace_visual_size);
move_to(Mouse.GetPosition(target));
mta.attach();
return new CompositeDisposable {
target.SubscribePreviewMouseMove(on_mouse),
target.SubscribeMouseEnter(on_mouse),
target.SubscribeMouseLeave(on_mouse),
mta.detach
};
void on_mouse(object s, MouseEventArgs e) =>
move_to(e.GetPosition(target));
void move_to(Point pt) =>
mta.RenderTransform = new TranslateTransform(pt.X, pt.Y);
}
public static IDisposable trace_drag(FrameworkElement target, Visual trace_visual, Size trace_visual_size) {
var mta = new MouseTraceAdorner(target, trace_visual, trace_visual_size);
move_to(Mouse.GetPosition(target));
mta.attach();
return new CompositeDisposable {
target.SubscribePreviewDragOver(on_drag),
target.SubscribePreviewDragLeave(on_drag),
target.SubscribePreviewDragEnter(on_drag),
mta.detach
};
void on_drag(object s, DragEventArgs e) =>
move_to(e.GetPosition(target));
void move_to(Point pt) =>
mta.RenderTransform = new TranslateTransform(pt.X, pt.Y);
}
protected override Visual GetVisualChild(int index) =>
index == 0 ? _trace_visual : throw new ArgumentOutOfRangeException(nameof(index));
protected override Size MeasureOverride(Size constraint) => _trace_visual_size;
}
}
@@ -4,6 +4,8 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:proto="clr-namespace:bts.proto"
xmlns:m="clr-namespace:mbts"
xmlns:sp="clr-namespace:mbts.spark"
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"
@@ -314,6 +316,357 @@
/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="DefaultCellContentTemplate">
<Grid>
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:StateDefinition State="{Binding Path='Group.Target.DataContext.can_override_display_name', RelativeSource={RelativeSource Self}, Converter={x:Static usp:GridSettingsView.DisplayNameVisualStateConverter}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:GridSettingsView.VisualStateNames.DisplayName}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:GridSettingsView.VisualStateNames.DisplayName}}"/>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:GridSettingsView.VisualStateNames.DisplayName}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="display_name_text_box" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="display_name_text_box" Storyboard.TargetProperty="(FrameworkElement.ToolTip)">
<DiscreteObjectKeyFrame KeyTime="0" Value="(N/A)"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock>Header</TextBlock>
<TextBox x:Name="display_name_text_box" Grid.Column="2" ToolTipService.ShowOnDisabled="True" Text="{Binding display_name}"/>
<TextBlock Grid.Row="2">Width</TextBlock>
<c:TickUpDownDouble Grid.Row="2" Grid.Column="2" Value="{Binding width}" Format="0.##"/>
<TextBlock Grid.Row="4">Horizontal Alignment</TextBlock>
<ComboBox Grid.Row="4" Grid.Column="2" ItemsSource="{u:EnumBindingSource Type=HorizontalAlignment}" SelectedItem="{Binding horizontal_alignment}"/>
<CheckBox Grid.Row="6" VerticalAlignment="Center" IsEnabled="{Binding can_override_font_weight}" IsChecked="{Binding is_font_weight_overridden}">Override Font Weight</CheckBox>
<ComboBox
Grid.Row="6"
Grid.Column="2"
Visibility="{Binding is_font_weight_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
ItemsSource="{Binding DataContext.font_family, Converter={StaticResource FontFamilyWeightsConverter}, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}}"
SelectedItem="{Binding font_weight_override}"
/>
<ComboBox Grid.Row="6" Grid.Column="2" Visibility="{Binding is_font_weight_overridden, Converter={StaticResource FalseVisibilityConverter}}" Style="{StaticResource DisabledPlaceholderComboBox}"/>
<CheckBox Grid.Row="8" VerticalAlignment="Top" IsEnabled="{Binding can_override_font_color}" IsChecked="{Binding is_font_color_overridden}">Override Font Color</CheckBox>
<c:ColorPickerPopup
Grid.Row="8"
Grid.Column="2"
DataContext="{Binding font_color_override}"
VerticalAlignment="Top"
Visibility="{Binding DataContext.current_column.is_font_color_overridden, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}}"
/>
<ComboBox
Grid.Row="8"
Grid.Column="2"
VerticalAlignment="Top"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLColumnParamsVM}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Row="0" VerticalAlignment="Center" IsEnabled="{Binding can_override_font_weight}" IsChecked="{Binding is_font_weight_overridden}">Override Font Weight</CheckBox>
<ComboBox
Grid.Row="0"
Grid.Column="2"
Visibility="{Binding is_font_weight_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
ItemsSource="{Binding DataContext.font_family, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}, Converter={StaticResource FontFamilyWeightsConverter}}"
SelectedItem="{Binding font_weight_override}"
/>
<ComboBox Grid.Row="0" Grid.Column="2" Visibility="{Binding is_font_weight_overridden, Converter={StaticResource FalseVisibilityConverter}}" Style="{StaticResource DisabledPlaceholderComboBox}"/>
<CheckBox Grid.Row="2" VerticalAlignment="Top" IsChecked="{Binding is_font_color_overridden}">Override Font Color</CheckBox>
<c:ColorPickerPopup
Grid.Row="2"
Grid.Column="2"
SelectedColor="{Binding font_color_override.color}"
Palettes="{Binding font_color_override.palettes}"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
<ComboBox
Grid.Row="2"
Grid.Column="2"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
<CheckBox Grid.Row="4" VerticalAlignment="Top" IsChecked="{Binding is_background_overridden}">Override Background</CheckBox>
<c:ColorPickerPopup
Grid.Row="4"
Grid.Column="2"
SelectedColor="{Binding background_override.color}"
Palettes="{Binding background_override.palettes}"
IsEnabled="{Binding is_background_overridden}"
/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="PNLColumnTemplate" DataType="{x:Type pnl:PNLColumnVM}">
<StackPanel Grid.IsSharedSizeScope="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock>Header</TextBlock>
<TextBox x:Name="display_name_text_box" Grid.Column="2" ToolTipService.ShowOnDisabled="True" Text="{Binding display_name}"/>
<TextBlock Grid.Row="2">Width</TextBlock>
<c:TickUpDownDouble Grid.Row="2" Grid.Column="2" Value="{Binding width}" Format="0.##"/>
<TextBlock Grid.Row="4">Horizontal Alignment</TextBlock>
<ComboBox Grid.Row="4" Grid.Column="2" ItemsSource="{u:EnumBindingSource Type=HorizontalAlignment}" SelectedItem="{Binding horizontal_alignment}"/>
</Grid>
<GroupBox Margin="0,8,0,0" Header="Rows" Content="{Binding default_column_vm}"/>
<GroupBox Margin="0,8,0,0" Header="Group Header Rows" Content="{Binding group_column_vm}"/>
<GroupBox Margin="0,8,0,0" Header="Total/Selected Rows" Content="{Binding header_column_vm}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLRuleColumnVM}">
<StackPanel Grid.IsSharedSizeScope="True">
<GroupBox Header="Rows" DataContext="{Binding row_params}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Row="0" VerticalAlignment="Center" IsEnabled="{Binding can_override_font_weight}" IsChecked="{Binding is_font_weight_overridden}">Override Font Weight</CheckBox>
<ComboBox
Grid.Row="0"
Grid.Column="2"
Visibility="{Binding is_font_weight_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
ItemsSource="{Binding DataContext.font_family, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}, Converter={StaticResource FontFamilyWeightsConverter}}"
SelectedItem="{Binding font_weight_override}"
/>
<!--Group-->
<ComboBox Grid.Row="0" Grid.Column="2" Visibility="{Binding is_font_weight_overridden, Converter={StaticResource FalseVisibilityConverter}}" Style="{StaticResource DisabledPlaceholderComboBox}"/>
<CheckBox Grid.Row="2" VerticalAlignment="Top" IsChecked="{Binding is_font_color_overridden}">Override Font Color</CheckBox>
<c:ColorPickerPopup
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
SelectedColor="{Binding font_color_override.color}"
Palettes="{Binding font_color_override.palettes}"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
<ComboBox
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
<CheckBox Grid.Row="4" VerticalAlignment="Top" IsChecked="{Binding is_background_overridden}">Override Background</CheckBox>
<c:ColorPickerPopup
Grid.Row="4"
Grid.Column="2"
VerticalAlignment="Top"
SelectedColor="{Binding background_override.color}"
Palettes="{Binding background_override.palettes}"
Visibility="{Binding is_background_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
</Grid>
</GroupBox>
<GroupBox Header="Group Header Rows" DataContext="{Binding group_params}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Row="0" VerticalAlignment="Center" IsEnabled="{Binding can_override_font_weight}" IsChecked="{Binding is_font_weight_overridden}">Override Font Weight</CheckBox>
<ComboBox
Grid.Row="0"
Grid.Column="2"
Visibility="{Binding is_font_weight_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
ItemsSource="{Binding DataContext.font_family, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}, Converter={StaticResource FontFamilyWeightsConverter}}"
SelectedItem="{Binding font_weight_override}"
/>
<!--Group-->
<ComboBox Grid.Row="0" Grid.Column="2" Visibility="{Binding is_font_weight_overridden, Converter={StaticResource FalseVisibilityConverter}}" Style="{StaticResource DisabledPlaceholderComboBox}"/>
<CheckBox Grid.Row="2" VerticalAlignment="Top" IsChecked="{Binding is_font_color_overridden}">Override Font Color</CheckBox>
<c:ColorPickerPopup
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
SelectedColor="{Binding font_color_override.color}"
Palettes="{Binding font_color_override.palettes}"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
<ComboBox
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
<CheckBox Grid.Row="4" VerticalAlignment="Top" IsChecked="{Binding is_background_overridden}">Override Background</CheckBox>
<c:ColorPickerPopup
Grid.Row="4"
Grid.Column="2"
VerticalAlignment="Top"
SelectedColor="{Binding background_override.color}"
Palettes="{Binding background_override.palettes}"
Visibility="{Binding is_background_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
</Grid>
</GroupBox>
<GroupBox Header="Total/Selected Rows" DataContext="{Binding header_params}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="name_col"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Row="0" VerticalAlignment="Center" IsEnabled="{Binding can_override_font_weight}" IsChecked="{Binding is_font_weight_overridden}">Override Font Weight</CheckBox>
<ComboBox
Grid.Row="0"
Grid.Column="2"
Visibility="{Binding is_font_weight_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
ItemsSource="{Binding DataContext.font_family, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}, Converter={StaticResource FontFamilyWeightsConverter}}"
SelectedItem="{Binding font_weight_override}"
/>
<!--Group-->
<ComboBox Grid.Row="0" Grid.Column="2" Visibility="{Binding is_font_weight_overridden, Converter={StaticResource FalseVisibilityConverter}}" Style="{StaticResource DisabledPlaceholderComboBox}"/>
<CheckBox Grid.Row="2" VerticalAlignment="Top" IsChecked="{Binding is_font_color_overridden}">Override Font Color</CheckBox>
<c:ColorPickerPopup
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
SelectedColor="{Binding font_color_override.color}"
Palettes="{Binding font_color_override.palettes}"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
<ComboBox
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
Visibility="{Binding is_font_color_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
<CheckBox Grid.Row="4" VerticalAlignment="Top" IsChecked="{Binding is_background_overridden}">Override Background</CheckBox>
<c:ColorPickerPopup
Grid.Row="4"
Grid.Column="2"
VerticalAlignment="Top"
SelectedColor="{Binding background_override.color}"
Palettes="{Binding background_override.palettes}"
Visibility="{Binding is_background_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
<ComboBox
Grid.Row="2"
Grid.Column="2"
VerticalAlignment="Top"
Visibility="{Binding is_background_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
</Grid>
</GroupBox>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="PNLCellContentTemplate" DataType="{x:Type pnl:PNLColumnVM}">
<!--The 'Delay' addresses a side effect (it's a wpf bug) when changing the SelectedItem in TabControls,
where null values are propagated to binding targets of the previous SelectedItem -->
<TabControl x:Name="column_tabs" Padding="8" SelectedItem="{Binding selected_item, Delay=100}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="HeaderTemplateSelector">
<Setter.Value>
<u:DataTypeTemplateSelector>
<DataTemplate DataType="{x:Type pnl:PNLRuleColumnVM}">
<TextBlock Text="{Binding rule_text, Converter={x:Static ut:DisplayNameHelper.ExpressionSnakeToTitleCaseConverter}}"/>
</DataTemplate>
<u:DataTypeTemplateSelector.Default>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</u:DataTypeTemplateSelector.Default>
</u:DataTypeTemplateSelector>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
<TabControl.ItemsSource>
<CompositeCollection>
<CollectionContainer>
<CollectionContainer.Collection>
<x:Array Type="{x:Type TabItem}">
<TabItem Header="Default" Content="{Binding}" ContentTemplate="{StaticResource PNLColumnTemplate}"/>
</x:Array>
</CollectionContainer.Collection>
</CollectionContainer>
<CollectionContainer Collection="{Binding DataContext.rule_columns, Source={u:DirectReference column_tabs}}"/>
</CompositeCollection>
</TabControl.ItemsSource>
</TabControl>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<Grid Margin="{StaticResource FullPadding}">
@@ -554,7 +907,7 @@
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalGap}}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<c:DragDropListBox Grid.RowSpan="3" MinWidth="200" ItemsSource="{Binding columns}" SelectedItem="{Binding current_column}">
<c:DragDropListBox Grid.RowSpan="3" MinWidth="200" MaxHeight="500" ItemsSource="{Binding columns}" SelectedItem="{Binding current_column}">
<c:DragDropListBox.ItemContainerStyle>
<Style TargetType="c:DraggableListBoxItem">
<Setter Property="Cursor" Value="Arrow"/>
@@ -590,10 +943,10 @@
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="visibility_toggle" ToolTipService.ShowOnDisabled="True" IsChecked="{Binding is_visible}"/>
<StackPanel Grid.Column="2" Orientation="Horizontal">
<TextBlock Text="{Binding id, Converter={x:Static ut:DisplayNameHelper.CamelCaseSpacesConverter}}"/>
<TextBlock Margin="2,0,0,0" FontStyle="Italic" Text="{Binding display_name, Mode=OneWay, StringFormat='{} ({0})'}">
<CheckBox x:Name="visibility_toggle" ToolTipService.ShowOnDisabled="True" IsChecked="{Binding is_visible}" Focusable="False"/>
<StackPanel Grid.Column="2" Orientation="Horizontal" Focusable="False">
<TextBlock Text="{Binding id, Converter={x:Static ut:DisplayNameHelper.CamelCaseSpacesConverter}}" Focusable="False"/>
<TextBlock Margin="2,0,0,0" FontStyle="Italic" Text="{Binding display_name, Mode=OneWay, StringFormat='{} ({0})'}" Focusable="False">
<TextBlock.Visibility>
<MultiBinding Converter="{x:Static usp:GridSettingsView.ColumnDisplayNameVisibilityConverter}">
<Binding Path="id" Converter="{x:Static ut:DisplayNameHelper.CamelCaseSpacesConverter}"/>
@@ -606,80 +959,10 @@
</DataTemplate>
</c:DragDropListBox.ItemTemplate>
</c:DragDropListBox>
<GroupBox Grid.Column="2" MinWidth="280">
<GroupBox Grid.Column="2" MinWidth="280" Content="{Binding current_column}" ContentTemplate="{Binding CellContentTemplate, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}}">
<GroupBox.Header>
<TextBlock Text="{Binding current_column.display_name, StringFormat='{}\'{0}\' Cell Appearance'}"/>
</GroupBox.Header>
<Grid x:Name="column_content_root">
<u:StateManager.Groups>
<u:StateGroupsManager>
<u:StateDefinitionCollection>
<u:StateDefinition State="{Binding DataContext.current_column.can_override_display_name, Source={u:DirectReference column_content_root}, Converter={x:Static usp:GridSettingsView.DisplayNameVisualStateConverter}}"/>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:GridSettingsView.VisualStateNames.DisplayName}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:GridSettingsView.VisualStateNames.DisplayName}}"/>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:GridSettingsView.VisualStateNames.DisplayName}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="display_name_text_box" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="display_name_text_box" Storyboard.TargetProperty="(FrameworkElement.ToolTip)">
<DiscreteObjectKeyFrame KeyTime="0" Value="(N/A)"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock>Header</TextBlock>
<TextBox x:Name="display_name_text_box" Grid.Column="2" ToolTipService.ShowOnDisabled="True" Text="{Binding current_column.display_name}"/>
<TextBlock Grid.Row="2">Width</TextBlock>
<c:TickUpDownDouble Grid.Row="2" Grid.Column="2" Value="{Binding current_column.width}"/>
<TextBlock Grid.Row="4">Horizontal Alignment</TextBlock>
<ComboBox Grid.Row="4" Grid.Column="2" ItemsSource="{u:EnumBindingSource Type=HorizontalAlignment}" SelectedItem="{Binding current_column.horizontal_alignment}"/>
<CheckBox Grid.Row="6" VerticalAlignment="Center" IsEnabled="{Binding current_column.can_override_font_weight}" IsChecked="{Binding current_column.is_font_weight_overridden}">Override Font Weight</CheckBox>
<ComboBox
Grid.Row="6"
Grid.Column="2"
Visibility="{Binding current_column.is_font_weight_overridden, Converter={StaticResource BooleanToVisibilityConverter}}"
ItemsSource="{Binding font_family, Converter={StaticResource FontFamilyWeightsConverter}}"
SelectedItem="{Binding current_column.font_weight_override}"
/>
<ComboBox Grid.Row="6" Grid.Column="2" Visibility="{Binding current_column.is_font_weight_overridden, Converter={StaticResource FalseVisibilityConverter}}" Style="{StaticResource DisabledPlaceholderComboBox}"/>
<CheckBox Grid.Row="8" VerticalAlignment="Top" IsEnabled="{Binding current_column.can_override_font_color}" IsChecked="{Binding current_column.is_font_color_overridden}">Override Font Color</CheckBox>
<c:ColorPickerPopup
Grid.Row="8"
Grid.Column="2"
DataContext="{Binding current_column.font_color_override}"
VerticalAlignment="Top"
Visibility="{Binding DataContext.current_column.is_font_color_overridden, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource AncestorType=usp:GridSettingsView}}"
/>
<ComboBox
Grid.Row="8"
Grid.Column="2"
VerticalAlignment="Top"
Visibility="{Binding current_column.is_font_color_overridden, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
</Grid>
</GroupBox>
<!--TODO: Make this visible when cell animations are ready-->
<GroupBox Grid.Row="2" Grid.Column="2" VerticalAlignment="Top" Visibility="Collapsed">
@@ -38,6 +38,16 @@ namespace mbts.ui.spark {
}
#endregion
#region CellContentTemplate
public static readonly DependencyProperty CellContentTemplateProperty =
WPFHelper.create_dp<DataTemplate, GridSettingsView>(nameof(CellContentTemplate));
public DataTemplate CellContentTemplate {
get => GetValue(CellContentTemplateProperty) as DataTemplate;
set => SetValue(CellContentTemplateProperty, value);
}
#endregion
public static IMultiValueConverter ColumnDisplayNameVisibilityConverter =>
ValueConverter.create<string, string, Visibility>((id, header) => id == header ? Visibility.Collapsed : Visibility.Visible);
@@ -39,9 +39,13 @@ namespace mbts.spark {
readonly Property<bool> _show_predicate_animations, _show_cell_predicate_animations;
readonly DeferrableActionWrapper _update;
readonly IReadOnlyDictionary<string, GridColumnSettingsFeatureFlags> _column_flags;
readonly Func<GridColumnSettings, ISimpleColumnVM> _column_factory;
bool _can_edit_background;
ColorPickerPopupVM _background;
public SimpleGridSettingsVM(IReadOnlyDictionary<string, GridColumnSettingsFeatureFlags> column_flags = null) {
public SimpleGridSettingsVM(IReadOnlyDictionary<string, GridColumnSettingsFeatureFlags> column_flags = null, Func<GridColumnSettings, ISimpleColumnVM> column_factory = null) {
_column_flags = column_flags ?? new Dictionary<string, GridColumnSettingsFeatureFlags>();
_column_factory = column_factory ?? _default_column_factory;
_font_family = backing(nameof(font_family), TextUtils.StandardFontFamily);
_font_size = backing(nameof(font_size), FontSizes.Small);
_font_weight = backing(nameof(font_weight), FontWeights.Normal);
@@ -79,8 +83,10 @@ namespace mbts.spark {
public FontWeight font_weight { get => _font_weight.Value; set => _font_weight.set(value); }
public ColorPickerPopupVM font_color { get; } = new ColorPickerPopupVM();
public ColorPickerPopupVM selection_highlight { get; } = new ColorPickerPopupVM();
public ColorPickerPopupVM background => _background ?? (_background = new ColorPickerPopupVM { bind_opacity_to_alpha = true, opacity = 1 });
public double font_size { get => _font_size.Value; set => _font_size.set(value); }
public bool enable_sound_triggers => false;
public bool can_edit_background { get => _can_edit_background; set => Set(ref _can_edit_background, value); }
public bool show_predicate_animations { get => _show_predicate_animations.Value; set => _show_predicate_animations.set(value); }
public bool show_cell_predicate_animations { get => _show_cell_predicate_animations.Value; set => _show_cell_predicate_animations.set(value); }
public IReadOnlyList<DialogSkirtItem> dialog_skirt_items => new[] {
@@ -102,8 +108,18 @@ namespace mbts.spark {
}
}
public GridSettings create() =>
new GridSettings(font_family.name(), font_size, font_weight, font_color.color.rgb_color(), selection_highlight.to_proto(), columns.Select(c => c.create()));
public GridSettings create() {
var rv = new GridSettings(
font_family.name(),
font_size,
font_weight,
font_color.color.rgb_color(),
selection_highlight.to_proto(),
columns.Select(c => c.create()));
if (can_edit_background)
rv = rv.with(background: background.color.rgb_color());
return rv;
}
public void load_from(GridSettings value) {
if (value == null)
@@ -115,22 +131,26 @@ namespace mbts.spark {
selection_highlight.load_from(value.selection_highlight.to_brush());
_font_size.set(value.font_size);
var curr_col_id = current_column?.id;
columns.SetItems(value.columns.Select(col => {
var vm = new SimpleColumnVM(this);
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;
}));
columns.SetItems(value.columns.Select(_column_factory));
if (curr_col_id == null || !columns.TryGetFirst(c => c.id == curr_col_id, out ISimpleColumnVM curr_column))
curr_column = columns.FirstOrDefault();
_current_column.set(curr_column);
if (can_edit_background)
background.color = value.background;
}
}
ISimpleColumnVM _default_column_factory(GridColumnSettings col_settings) {
var vm = new SimpleColumnVM(this);
vm.load_from(col_settings);
// 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;
}
void IWindowSettingsVM<GridSettings>.load(GridSettings value) => load_from(value);
GridSettings IWindowSettingsVM<GridSettings>.get_result() => create();
}
@@ -1,4 +1,6 @@
using bts;
using bts.utils;
using mbts.ui.extensions;
using mbts.ui.shell;
using System;
using System.Diagnostics;
@@ -33,6 +35,39 @@ namespace mbts.ui {
private static DragDropDocumentPreview _dddp;
public static IObservable<Point> subscribe_drag_start(FrameworkElement element) =>
Observable.Create<Point>(o => {
Point? mouse_down = null, drag_start = null;
element.MouseDown += on_mouse_down;
element.MouseMove += on_mouse_move;
element.MouseUp += on_mouse_up;
return Disposable.Create(() => {
element.MouseDown -= on_mouse_down;
element.MouseMove -= on_mouse_move;
element.MouseUp -= on_mouse_up;
});
// callbacks
void on_mouse_up(object sender, MouseButtonEventArgs e) {
mouse_down = null;
drag_start = null;
}
void on_mouse_move(object sender, MouseEventArgs e) {
if (mouse_down.HasValue) {
var curr_pt = e.GetPosition(element);
if (is_sufficient_delta(mouse_down.Value, curr_pt)) {
e.Handled = true;
drag_start = curr_pt;
mouse_down = null;
o.OnNext(curr_pt);
}
}
}
void on_mouse_down(object sender, MouseButtonEventArgs e) {
drag_start = null;
mouse_down = e.GetPosition(element);
}
});
public static IObservable<Point?> subscribe_drag_coordinates(FrameworkElement element) =>
Observable.Create<Point?>(o => {
Point? mouse_down = null, drag_start = null;
@@ -70,6 +105,57 @@ namespace mbts.ui {
}
});
public static IDisposable connect_horizontal_insertion_adorner(ItemsControl container, FrameworkElement root = null) {
HorizontalInsertionAdorner insertion_adorner = null;
UIElement target = null;
TargetSide target_side = TargetSide.LEFT;
if (root == null)
root = container;
return Disposable.Create(
root.SubscribePreviewDragEnter(on_drag_enter),
root.SubscribePreviewDragLeave((s, e) => remove_adorner()),
root.SubscribePreviewDragOver(on_drag_over),
root.SubscribePreviewDrop((s, e) => remove_adorner()),
Disposable.Create(remove_adorner));
void on_drag_over(object sender, DragEventArgs e) {
_determine_drop_target(e);
_update_insertion_adorner();
e.Effects = DragDropEffects.Move;
e.Handled = true;
}
void on_drag_enter(object sender, DragEventArgs e) {
_determine_drop_target(e);
_update_insertion_adorner();
e.Effects = e.AllowedEffects;
}
// Draw an indicator where the drop will insert the item
void _update_insertion_adorner() {
if (insertion_adorner == null) {
insertion_adorner = new HorizontalInsertionAdorner(target, target_side);
} else insertion_adorner.Side = target_side;
}
void _determine_drop_target(DragEventArgs e) {
target = null;
var pt = e.GetPosition(container);
pt.X = MathUtils.within_range(0, container.ActualWidth - 2, pt.X);
pt.Y = MathUtils.within_range(0, container.ActualHeight - 2, pt.Y);
//if (e.OriginalSource is DependencyObject) {
if (container.InputHitTest(pt) is DependencyObject hit) {
target = container.ContainerFromElement(hit) as UIElement;
if (target != null) {
Point target_position = e.GetPosition(target);
target_side = target_position.X < (target.RenderSize.Width / 2) ? TargetSide.LEFT : TargetSide.RIGHT;
}
}
}
void remove_adorner() {
if (insertion_adorner != null) {
insertion_adorner.Detach();
insertion_adorner = null;
}
}
}
[Conditional("DEBUG")]
private static void log(string message, params object[] args) {
Console.WriteLine(message, args);
@@ -137,6 +137,11 @@ namespace mbts.ui.extensions {
return Disposable.Create(() => target.PreviewDragOver -= callback);
}
public static IDisposable SubscribePreviewDragEnter(this UIElement target, DragEventHandler callback) {
target.PreviewDragEnter += callback;
return Disposable.Create(() => target.PreviewDragEnter -= callback);
}
public static IDisposable SubscribePreviewDragLeave(this UIElement target, DragEventHandler callback) {
target.PreviewDragLeave += callback;
return Disposable.Create(() => target.PreviewDragLeave -= callback);
@@ -4,6 +4,7 @@
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"
@@ -39,6 +40,36 @@
<cv:ValueMap x:Key="TabHeaderFontWeightConverter" Default="{u:FontWeight Normal}">
<cv:KeyValue Key="{u:True}" Value="{u:FontWeight Bold}"/>
</cv:ValueMap>
<!--Styles (Shared/Common)-->
<Style x:Key="FontPickerPopupControl" TargetType="c:PopupControl">
<Setter Property="Background" Value="{StaticResource ComboBox.Static.Background}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Padding" Value="6,2"/>
<Setter Property="MinHeight" Value="24"/>
<Setter Property="Header" Value="{Binding}"/>
<Setter Property="Content" Value="{Binding}"/>
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock FontFamily="{Binding font_family}" FontSize="{Binding font_size}" FontWeight="{Binding font_weight}">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}, {1:#0.##} pt">
<Binding Path="font_family"/>
<Binding Path="font_size"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<c:FontPicker SelectedFontFamily="{Binding font_family}" SelectedFontSize="{Binding font_size}" SelectedFontWeight="{Binding font_weight}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<!--DataTemplates-->
<DataTemplate x:Key="GridSectionCoreContentTemplate">
<Grid>
@@ -47,8 +78,6 @@
<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/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
@@ -57,16 +86,7 @@
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock>Font</TextBlock>
<Grid Grid.Column="2" HorizontalAlignment="Left" Width="{StaticResource ControlLongWidth}">
<c:PopupControl HorizontalAlignment="Stretch" Header="{Binding}" Background="{StaticResource ComboBox.Static.Background}">
<c:PopupControl.HeaderTemplate>
<DataTemplate>
<TextBlock FontFamily="{Binding font_family}" FontSize="{Binding font_size}" FontWeight="{Binding font_weight}" Margin="4,0" Text="{Binding font_display_name}" />
</DataTemplate>
</c:PopupControl.HeaderTemplate>
<c:FontPicker SelectedFontFamily="{Binding font_family}" SelectedFontSize="{Binding font_size}" SelectedFontWeight="{Binding font_weight}"/>
</c:PopupControl>
</Grid>
<c:PopupControl Grid.Column="2" Style="{StaticResource FontPickerPopupControl}"/>
<TextBlock Grid.Row="2">Font Color (default)</TextBlock>
<c:ColorPickerPopupWithOpacitySlider Grid.Row="2" Grid.Column="2" HorizontalAlignment="Left" Width="{StaticResource ControlLongWidth}" DataContext="{Binding font_color}" CanUserEditOpacity="False"/>
<TextBlock Grid.Row="4">Selection Highlight</TextBlock>
@@ -74,6 +94,29 @@
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLCellAppearanceParamsVM}">
<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>
<Style x:Key="CopyProfileTargetButton" TargetType="Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Height" Value="22"/>
@@ -171,6 +214,94 @@
</Style>
</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}">
@@ -182,7 +313,7 @@
</Grid.RowDefinitions>
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="1" Fill="{StaticResource HeaderBackgroundBorderBrush}"/>
<c:ActionMenu HorizontalAlignment="Right" Margin="0,2,0,0" ItemsSource="{Binding instance_vm.action_menu_items}"/>
<usp:GridSettingsView Grid.Row="1" Margin="8,-8,8,8" GridSectionContent="{Binding}" GridSectionContentTemplate="{StaticResource GridSectionCoreContentTemplate}"/>
<usp:GridSettingsView Grid.Row="1" Margin="8,-8,8,8" GridSectionContent="{Binding}" GridSectionContentTemplate="{StaticResource GridSectionCoreContentTemplate}" CellContentTemplate="{DynamicResource DefaultCellContentTemplate}"/>
</Grid>
</DataTemplate>
</u:TemplateSelectorKeyValue>
@@ -402,7 +533,7 @@
</Grid.RowDefinitions>
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="1" Fill="{StaticResource HeaderBackgroundBorderBrush}"/>
<c:ActionMenu HorizontalAlignment="Right" Margin="0,2,0,0" ItemsSource="{Binding instance_vm.action_menu_items}"/>
<usp:GridSettingsView Grid.Row="1" Margin="8,-8,8,8" DataContext="{Binding core_settings_vm}" GridSectionContent="{Binding DataContext.instance_vm, RelativeSource={RelativeSource AncestorType=usp:ShellSettingsDialog}}">
<usp:GridSettingsView Grid.Row="1" Margin="8,-8,8,8" DataContext="{Binding core_settings_vm}" GridSectionContent="{Binding DataContext.instance_vm, RelativeSource={RelativeSource AncestorType=usp:ShellSettingsDialog}}" CellContentTemplate="{DynamicResource DefaultCellContentTemplate}">
<usp:GridSettingsView.GridSectionContentTemplate>
<DataTemplate>
<StackPanel Grid.IsSharedSizeScope="True">
@@ -428,20 +559,163 @@
</Grid>
</DataTemplate>
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static usp:GridSettingsTemplateKeys.PNL}">
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="1" Fill="{StaticResource HeaderBackgroundBorderBrush}"/>
<c:ActionMenu HorizontalAlignment="Right" Margin="0,2,0,0" ItemsSource="{Binding instance_vm.action_menu_items}"/>
<usp:GridSettingsView
Grid.Row="1"
Margin="8,-8,8,8"
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="140" Padding="10">
<TabItem Header="Grid" Content="{Binding core_settings_vm}">
<TabItem.ContentTemplate>
<DataTemplate>
<Grid>
<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/>
</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="Total/Selected Row Defaults" Content="{Binding header_row_defaults}"/>
<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>
<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>
<CheckBox Margin="4,0,0,0" IsChecked="{Binding anchor_vm.Account.include}">Account</CheckBox>
<CheckBox Margin="4,0,0,0" IsChecked="{Binding anchor_vm.Exchange.include}">Exchange</CheckBox>
<CheckBox Margin="4,0,0,0" IsChecked="{Binding anchor_vm.Symbol.include}">Symbol</CheckBox>
<CheckBox Margin="4,0,0,0" IsChecked="{Binding anchor_vm.Security.include}">Security</CheckBox>
</StackPanel>
</GroupBox.Header>
<ItemsControl
HorizontalAlignment="Left"
VerticalAlignment="Top"
AllowDrop="True"
ItemsSource="{Binding anchor_items}"
ItemTemplate="{StaticResource AnchorItemTemplate}"
Loaded="_pnl_anchor_items_loaded"
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</GroupBox>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</TabControl>
</Grid>
</DataTemplate>
</usp:GridSettingsView.GridSectionContentTemplate>
</usp:GridSettingsView>
</Grid>
</DataTemplate>
</u:TemplateSelectorKeyValue>
</u:KeyedTemplateSelector>
</Window.Resources>
<Grid Margin="{x:Static u:WindowStyle.NegativeResizeBorderThickness}">
<Grid x:Name="root_grid" Margin="{x:Static u:WindowStyle.NegativeResizeBorderThickness}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<ContentControl
VerticalAlignment="Top"
Content="{Binding instance_vm}"
ContentTemplateSelector="{StaticResource GridSettingsTemplateSelector}"
/>
</ScrollViewer>
<ContentControl
VerticalAlignment="Top"
HorizontalAlignment="Stretch"
Content="{Binding instance_vm}"
ContentTemplateSelector="{StaticResource GridSettingsTemplateSelector}"
/>
<c:DialogSkirt
Grid.Row="1"
LeftItems="{Binding left_skirt_items}"
@@ -461,4 +735,4 @@
</c:DialogSkirt.Background>
</c:DialogSkirt>
</Grid>
</Window>
</Window>
@@ -1,4 +1,14 @@
using System.Windows;
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;
namespace mbts.ui.spark {
/// <summary>
@@ -14,12 +24,109 @@ 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 {
public const string
SimpleGrid = nameof(SimpleGrid),
Ladder = nameof(Ladder),
OrderBook = nameof(OrderBook);
OrderBook = nameof(OrderBook),
PNL = nameof(PNL);
}
}