Compare commits

..
Author SHA1 Message Date
John Colvin fc1cc34257 fix flickering pnl hyperlink hover background 2019-11-18 17:35:55 -06:00
John Colvin 0359a9d840 fix flickering mview hyperlink hover background 2019-11-18 17:19:16 -06:00
John Colvin ad6e1e04ad Merge remote-tracking branch 'origin/master' into mview-popups2 2019-11-18 16:13:42 -06:00
John Colvin 8074e0d9e6 remove unused file (SWP.cs) 2019-11-15 17:05:29 -06:00
John Colvin b310b461ea PNLView - HyperlinkCell mouse hover animation 2019-11-14 15:15:35 -06:00
John Colvin e16864d2d6 PNLView - set Hyperlink/TextCell 'SnapToDevicePixels' to true 2019-11-14 15:13:52 -06:00
John Colvin ccb192887a PNLView - get rid of magic const row height 2019-11-14 15:13:40 -06:00
John Colvin 5e6b048013 PNLView.xaml - factor out common TextCell props into base style 2019-11-14 14:51:51 -06:00
John Colvin 29f230507c PNLView.xaml - factor out common HyperlinkCell props into base style 2019-11-14 14:51:48 -06:00
John Colvin a54830cde3 set HyperlinkCell 'HyperlinkClickMode' default to 'Anywhere' 2019-11-14 13:10:51 -06:00
John Colvin e210c987e7 remove HyperlinkColumn props 'padding' and 'HyperlinkClickMode' (callers should set them through the ElementStyle prop) 2019-11-14 13:09:23 -06:00
John Colvin 52e9380a0f add 'AffectsRender' flag to Hyperlink/TextCell HorizontalContentAlignment dps 2019-11-14 12:05:43 -06:00
John Colvin 6cdd637251 fix Hyperlink/TextCell padding (actually use it) 2019-11-14 11:36:21 -06:00
John Colvin 96f030f4dc after opening, mview remembers subsequent security criteria changes in workspace 2019-11-13 23:32:53 -06:00
John Colvin 64b1b903a1 mview synth fills popup only shows fills of synth root algos 2019-11-13 23:15:00 -06:00
John Colvin 788eb90715 mview mini ob only shows working orders 2019-11-13 21:29:46 -06:00
John Colvin 69738643e5 mview mini orderbook only shows exchange orders for outrights, spreader orders for synths 2019-11-13 21:29:24 -06:00
John Colvin 6c25d16822 fix mview sorting (use new ColumnSortManager) 2019-11-13 21:08:27 -06:00
John Colvin 2ba10d1a97 MarketViewVM - move local methods (in constructor) to bottom 2019-11-13 21:08:27 -06:00
John Colvin 28f7b4e892 mview order ticket popup closes on send 2019-11-13 21:08:27 -06:00
John Colvin 0090a1ca36 mview toolbar menu items open regular windows instead of minis (for now) 2019-11-13 21:08:27 -06:00
John Colvin 5885dd4f6a mview fills/orderbook toolbar menu items open the new popups 2019-11-13 21:08:27 -06:00
John Colvin 7fb254f373 DIYGridRowsPresenter initialization in Loaded callback is idempotent (Loaded event not always followed by Unloaded event) 2019-11-13 21:08:27 -06:00
John Colvin 765d0cb63f mview popups use AutoHideScrollBar to prevent scrollbars from covering data 2019-11-13 21:08:27 -06:00
John Colvin 4770f875d0 mview 'Position' column shows day position (uses position service) 2019-11-13 21:08:27 -06:00
John Colvin 534f248fbf tweak HyperlinkCell focus/mouse capture logic 2019-11-13 21:08:27 -06:00
John Colvin 3d27735006 clean up DIYGrid TextColumn (mimic recent changes in HyperlinkColumn) 2019-11-13 21:08:27 -06:00
John Colvin 1bbe8d0af3 fix TextCell alignment issues 2019-11-13 21:08:27 -06:00
John Colvin 87ab2c1ca2 SP-257 mview working orders popup 2019-11-13 21:08:27 -06:00
John Colvin 17b40452b5 hamburger spruce 2019-11-13 21:08:27 -06:00
John Colvin 4bb159311f add 'Freeze' prop to BrushExtension 2019-11-13 21:08:26 -06:00
John Colvin 06935d525a add ITimeAndSalesGridSettingsMigrationRule 2019-11-13 21:08:26 -06:00
John Colvin 97df614bc0 DIYGridCellHoverAdorner 2019-11-13 21:08:26 -06:00
John Colvin cd1fab327e refactor DIYGrid.SelectionHighlight to be Color instead of Brush (also fixes drag rect adorner bug, where the color wouldn't respond to settings changes) 2019-11-13 21:08:26 -06:00
John Colvin ec1dde8342 HighPerformanceRow does not depend on TColumn 2019-11-13 21:08:26 -06:00
John Colvin 2a10b83d19 fix typo in ColumnGeometry (was assigning 'left' to 'unclicpped_left') 2019-11-13 21:08:26 -06:00
John Colvin c88d773734 add 'HyperlinkClickMode' to HyperlinkCell to support cmd on click anywhere 2019-11-13 21:08:26 -06:00
John Colvin 82b199412e fix HyperlinkCell HorizontalAlignment binding 2019-11-13 21:08:26 -06:00
John Colvin 870b892b8f market view row 'inside working orders' comparison to bbo was backwards 2019-11-13 21:08:26 -06:00
John Colvin 128e0e0877 MarketViewVM does not derive from SecurityMDGrid 2019-11-13 21:08:26 -06:00
John Colvin 1673763937 clip mview animations to scroll content presnter bounds 2019-11-13 21:08:26 -06:00
John Colvin ee16430896 factor out pnl auxiliary popups for general use (mview) 2019-11-13 21:08:26 -06:00
John Colvin 424c83bdfd introduce WindowStyle.UnsafeWindow dp 2019-11-13 21:08:26 -06:00
John Colvin f28884e4c6 refactor ChildBounds extensions to be for UIElement 2019-11-13 21:08:26 -06:00
John Colvin 3bcfee558d OrderTypeItem template uses Rectangle instead of Badge (the latter has some unresolved rounding issues) 2019-11-13 21:07:07 -06:00
John Colvin ec9967f9f0 WPFHelper.measure_content() rounds to layout correctly 2019-11-13 21:07:07 -06:00
John Colvin 0191856733 fix WPFHelper.measure_visual_content - 'left edge' calculation for right align; 'bottom edge' for bottom align 2019-11-13 21:07:07 -06:00
John Colvin c26c145b2f fix HyperlinkCell Alignment issues 2019-11-13 21:07:07 -06:00
John Colvin 077b8d615c DIYGrid CellRender.draw_text with layout rounding 2019-11-13 21:07:07 -06:00
30 changed files with 486 additions and 790 deletions

No files matched your search

-5
View File
@@ -6,14 +6,9 @@ insert_anchor_links = "right"
+++
## 2.14.0
### User Visible Changes
- All ladders can now be recentered by (shift or alt) + double clicking over the Price column in a ladder
- Added a Max Order Quantity setting to the Safety Checks tab on the Ladder settings. This setting allows for a user-defined maximum order quantity.
- Added a Price Display Format setting to the Market Price and Size Display tab on the Ladder settings. This setting allows for price levels in the ladder to be displayed without a decimal separator.
- Synthetic instrument creation with 3 legs no longer defaults to butterfly quantites
### Bug Fixes
- Fixed an issue where market transition were not observed by IAlgoOrder
- Fixed a bug in error reporting
- Fixed a bug in the PnL window where specifying a certain grouping order would lead to a UI failure
## 2.13.0
### User Visible Changes
+2 -2
View File
@@ -39,7 +39,7 @@ namespace bts {
_relay.set_token(_token.Value);
_dispose.Add(
_ss.Value.subscribei_metadata()
.Select(upd => upd.all.Where(i => i.HasStrategy).ToDictionary(i => i.SecurityKey, i => i.Strategy))
.Select(upd => upd.all.ToDictionary(i => i.SecurityKey, i => i.Strategy))
.Subscribe(t => {
var deleted_synthetic_keys = new HashSet<uint>(t.Where(kv => kv.Value.Deleted).Select(kv => kv.Key));
// add back 'undeleted' synthetics
@@ -64,4 +64,4 @@ namespace bts {
Task.Run(run);
}
}
}
}
@@ -83,7 +83,7 @@ namespace mbts.spark {
};
_rows_view.LiveFilteringProperties.Add(nameof(Row.is_visible));
// Important: these selected_security/md wrappers should be instantiated in the constructor (rather than lazily),
// to prevent situations where callers subscribe to the selected_rows.CollectionChanged event before the wrappers do.
// to prevent situations where callers subscribe up to the selected_rows.CollectionChanged event before the wrappers do.
// This way, the wrappers are protected from unintended side effects of the foreign callbacks, as they will always receive CollectionChange notifications first.
selected_securities = selected_rows.SelectObservable(r => r.security);
selected_security_mds = selected_rows.SelectObservable(r => r.security_md);
@@ -4,6 +4,7 @@ using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.extensions;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
@@ -147,7 +148,7 @@ namespace mbts.ui.spark {
void _show_popup(object content, object header) {
var resources = new AuxiliaryDataResources();
resources.MergedDictionaries.Add(new AutoHideScrollbarResources());
resources.MergedDictionaries.Add(new ScrollBarResources());
_show_popup(content, header, resources);
}
@@ -161,7 +162,7 @@ namespace mbts.ui.spark {
Resources = resources ?? new AuxiliaryDataResources()
};
view.Style = view.Resources[AuxiliaryDataResources.PopupChildStyleKey] as Style;
_popup_man.show_async(view).ignore();
_popup_man.show(view);
}
static class CommandImpl {
@@ -174,4 +175,4 @@ namespace mbts.ui.spark {
}
class MarketViewRowView : DIYGrid.HighPerformanceRow<MarketViewVM.Row> { }
}
}
@@ -94,11 +94,14 @@ namespace bts.shell {
public static fills.FillsSettings DefaultAuxiliaryFills {
get {
var col_keys = new HashSet<mbts.ui.spark.FillsView.Columns>(
fills.FillsSettings.mini_column_keys);
col_keys.Add(mbts.ui.spark.FillsView.Columns.Account);
var grid = fills.FillsSettings.MiniGridSettings;
//if (grid.columns.TryGetFirst(c => c.id == nameof(mbts.ui.spark.FillsView.Columns.Side), out var side_col, out int side_col_pos)) {
// var cols = grid.columns.ToList();
// cols[side_col_pos] = side_col.with(is_visible: false);
// grid = grid.with(cols);
//}
var rv = fills.FillsSettings.Default();
rv.grid = fills.FillsSettings.create_grid(col_keys);
rv.grid = grid;
return rv;
}
}
@@ -1,5 +1,4 @@
using bts.collections;
using mbts.ui;
using mbts.ui;
using mbts.ui.settings;
using ProtoBuf;
using System;
@@ -35,27 +34,11 @@ namespace bts.shell.fills {
public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion);
public static GridSettings MiniGridSettings => GridSettings.Default.with(DefaultColumns.Mini.all, DefaultColumns.Mini.sorting_criterion);
public static IEnumerable<Columns> mini_column_keys => DefaultColumns.Mini.mini_cols_data.Keys;
public IReadOnlyList<SortingCriteria> sorting_criterion => _sorting_criteria ?? (_sorting_criteria = DefaultColumns.default_sorting_criterion.ToList());
public uint[] root_securities { get; set; }
public static FillsSettings Default() =>
new FillsSettings(null, null, new FillsFilterStates(), null);
public static GridSettings create_grid(IEnumerable<Columns> keys) {
var key_set = keys as ISet<Columns> ?? new HashSet<Columns>(keys.empty_if_null());
var grid = DefaultGridSettings;
var cols = new LazyMutatorList<GridColumnSettings>(grid.columns);
for (int i = 0; i < cols.Count; i++) {
var c = cols[i];
if (c.is_visible != key_set.Contains(c.strong_id<Columns>()))
cols[i] = c.with(is_visible: !c.is_visible);
}
if (cols.IsMutated)
grid = grid.with(cols);
return grid;
}
public uint[] root_securities { get; set; }
static class DefaultColumns {
public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security);
@@ -102,21 +85,21 @@ namespace bts.shell.fills {
}
public static class Mini {
public static readonly IReadOnlyDictionary<Columns, (bool is_visible, double? width_override)> mini_cols_data =
static readonly IReadOnlyDictionary<Columns, (bool is_visible, double? width_override)> _mini_cols_data =
new Dictionary<Columns, (bool is_visible, double? width_override)> {
{ Columns.Security, (true, null) },
{ Columns.FillTime, (true, ShortColumnWidths.Time) },
{ Columns.OrderType, (true, ShortColumnWidths.OrderType) },
{ Columns.Side, (true, ShortColumnWidths.Side) },
{ Columns.Size, (true, ShortColumnWidths.Size) },
{ Columns.Price, (true, ShortColumnWidths.Price) }
{ Columns.Price, (true, ShortColumnWidths.Price) },
};
public static IEnumerable<GridColumnSettings> all => DefaultColumns.all.Select(_convert);
public static IEnumerable<SortingCriteria> sorting_criterion => default_sorting_criterion.Where(c => _try_get_data(c.col_name, out (bool is_visible, double? _) d) && d.is_visible);
static bool _try_get_data(string id_str, out (bool is_visible, double? width_override) data) {
if (Enum.TryParse(id_str, out Columns k) && mini_cols_data.TryGetValue(k, out data))
if (Enum.TryParse(id_str, out Columns k) && _mini_cols_data.TryGetValue(k, out data))
return true;
data = default;
return false;
@@ -129,4 +112,4 @@ namespace bts.shell.fills {
}
}
}
}
}
@@ -467,10 +467,6 @@ namespace mbts.spark {
settings_invalidated?.Invoke();
}
public void recenter_all_ladders() {
_bus?.post(SparkTags.RequestRecenterLadder, null);
}
public Task send_order_async((double price, Side? side, MouseButton button) args) {
if (order_properties_vm != null && args.button != MouseButton.Middle) {
var size_from_alternate = args.button == MouseButton.Right;
@@ -488,14 +488,8 @@ namespace mbts.spark {
protected override void OnMouseDoubleClick(MouseButtonEventArgs e) {
var column = _column_for_point(e.GetPosition(this));
if (column.column_type == ColumnType.Price) {
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift) ||
Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) {
_vm?.recenter_all_ladders();
} else {
_scroll_to_center();
}
}
if (column.column_type == ColumnType.Price)
_scroll_to_center();
}
#region Row Utility Methods
@@ -7,7 +7,6 @@ using mbts.ui;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
namespace bts.shell {
internal class OrderBookWindowFactory : ShellWindowFactory<OrderBookStartupData> {
@@ -27,14 +26,6 @@ namespace bts.shell {
}
public override Task<IShellWindow> load(OrderBookStartupData state) {
// A fairly major grid settings revamp is in the works,
// which will correctly negotiate background color settings as defined at the grid and column level.
// The hack is neccessary bc a previously benign bug (which has been fixed in this 'mview popups' patch) in the GridSettingsVM
// always changed the grid background color to black.
// Fortunately, the bug only affects the OrderBook as other windows use SimpleGridSettingsVM, which does not have such a bug.
if (state != null && !state.orderbook_grid.general.enable_background_color && state.orderbook_grid.general.background_color.argb_color().A > 0) {
state.orderbook_grid.general = state.orderbook_grid.general.with(background: Colors.Transparent.rgb_color());
}
var settings_manager = new WindowSettingsManager<OrderBookGridSettings>(_settings_hub, state.grid_settings_wrapper(),
us => us.order_book_grid ?? OrderBookStartupData.DefaultGrid,
(us, s) => us.with(order_book_grid: s));
@@ -1,223 +1,220 @@
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 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();
// move anchor cols to the left, order wrt grouping hierarchy
List<GridColumnSettings> new_cols = null;
IEnumerable<GridColumnSettings> cols = s.grid.columns;
var sorted_anchors = anchor_items.OrderBy(a => a.anchor_index).ToList();
for (int i = 0; i < sorted_anchors.Count; i++) {
if (GridSettingsHelper.try_find_column(cols, sorted_anchors[i].key, out var match, out int pos) && pos != i) {
if (new_cols == null) {
new_cols = s.grid.columns.ToList();
// set cols to new_cols so subsequent position lookups
// take previous column order manipulations into account.
cols = new_cols;
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]);
}
new_cols.RemoveAt(pos);
new_cols.Insert(i, match);
}
}
// 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 == null ? null : s.grid.with(columns: new_cols),
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 = 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);
}
}
}
@@ -90,11 +90,12 @@ namespace bts.shell.pnl {
}
int? _try_compare_groups(CollectionViewGroup x, CollectionViewGroup y) {
if (x?.Name is IPNLCellData xcell && y?.Name is IPNLCellData ycell) {
var comp = _get_column_comparer(xcell.column);
return comp.value_comparer.Compare(xcell.value, ycell.value);
}
return null;
if (x == null || y == null)
return null;
var xcell = (IPNLCellData)x.Name;
var ycell = (IPNLCellData)y.Name;
var comp = _get_column_comparer(xcell.column);
return comp.value_comparer.Compare(xcell.value, ycell.value);
}
}
}
}
@@ -4,7 +4,6 @@
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:bv="clr-namespace:bts.view"
xmlns:ft="clr-namespace:mbts.spark.filters"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
@@ -12,7 +11,6 @@
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
FocusManager.IsFocusScope="True"
u:WindowStyle.UnsafeWindow="{Binding Path='(u:WindowStyle.UnsafeWindow)', RelativeSource={RelativeSource AncestorType=bv:SparkWindowView}}"
Background="{StaticResource CommonBackground}"
Tag="{Binding ElementName=_grid}"
>
@@ -680,8 +678,8 @@
c:DataGridFilterProperties.FilterActive="{Binding DataContext.security_filter.active, Source={u:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.security_filter.open, Source={u:DirectReference _grid}}"
key="Security"
data_member_path="security_cell.cell_data"
sort_member_path="security"
sort_member_path="security_cell.cell_data"
data_member_path="security"
HeaderTemplate="{StaticResource AnchorableColumnHeaderTemplate}"
/>
<!--Security Key-->
@@ -388,7 +388,7 @@ namespace bts.shell.pnl {
Resources = new AuxiliaryDataResources()
};
view.Style = view.Resources[AuxiliaryDataResources.PopupChildStyleKey] as Style;
_popup_man.show_async(view).ignore();
_popup_man.show(view);
}
class PNLGroupDescription : PropertyGroupDescription, IEquatable<PNLGroupDescription> {
@@ -241,8 +241,6 @@ namespace mbts.ui.native
[DllImport("user32")]
public static extern bool IsWindow(IntPtr handle);
[DllImport("user32", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool ShowWindow(HandleRef hWnd, int nCmdShow);
}
@@ -257,21 +255,6 @@ namespace mbts.ui.native
TRANSPARENT = 0x20
}
public enum SW {
SW_HIDE = 0x0000,
SW_SHOWNORMAL = 0x0001,
SW_SHOWMINIMIZED = 0x0002,
SW_MAXIMIZE = 0x0003,
SW_SHOWNOACTIVATE = 0x0004,
SW_SHOW = 0x0005,
SW_MINIMIZE = 0x0006,
SW_SHOWMINNOACTIVATE = 0x0007,
SW_SHOWNA = 0x0008,
SW_RESTORE = 0x0009,
SW_SHOWDEFAULT = 0x000A,
SW_FORCEMINIMIZE = 0x000B,
}
[Flags]
public enum SWP : uint
{
@@ -289,10 +272,8 @@ namespace mbts.ui.native
SWP_NOOWNERZORDER = 0x0200,
// Don’t send WM_WINDOWPOSCHANGING
SWP_NOSENDCHANGING = 0x0400,
SWP_ASYNCWINDOWPOS = 0x4000,
TOPMOST_FLAGS = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING,
POP_TOPMOST_FLAGS = SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING
TOPMOST_FLAGS = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSENDCHANGING
}
public enum SPI : uint
@@ -1,5 +1,5 @@
<ResourceDictionary
x:Class="mbts.ui.controls.AutoHideScrollbarResources"
x:Class="mbts.ui.controls.ScrollBarResources"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
@@ -1,15 +1,77 @@
using mbts.ui.converters;
using mbts.ui.extensions;
using System;
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using mbts.ui.native;
using bts;
using System.Windows.Controls.Primitives;
using System.Threading.Tasks;
using mbts.spark;
using mbts.ui.converters;
using mbts.ui.extensions;
namespace mbts.ui.controls {
partial class AutoHideScrollbarResources : ResourceDictionary {
public AutoHideScrollbarResources() =>
partial class ScrollBarResources : ResourceDictionary {
static ScrollBarResources() =>
IsActiveProperty = IsActivePropertyKey.DependencyProperty;
public ScrollBarResources() =>
InitializeComponent();
#region IsActive
static readonly DependencyPropertyKey IsActivePropertyKey =
DependencyProperty.RegisterAttachedReadOnly("IsActive", typeof(bool), typeof(ScrollBarResources), new PropertyMetadata(false));
public static readonly DependencyProperty IsActiveProperty;
public static bool GetIsActive(DependencyObject d) => (bool)d.GetValue(IsActivePropertyKey.DependencyProperty);
static void SetIsActive(DependencyObject d, bool value) => d.SetValue(IsActivePropertyKey, value);
#endregion
#region LastChangeTime
static readonly DependencyPropertyKey LastChangeTimePropertyKey =
DependencyProperty.RegisterAttachedReadOnly("LastChangeTime", typeof(DateTime), typeof(ScrollBarResources),
new PropertyMetadata(DateTime.MinValue, OnLastChangeTimeChanged));
private static void OnLastChangeTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (!GetIsActive(d)) {
if (e.NewValue is DateTime dt) {
}
}
}
public static readonly DependencyProperty LastChangeTimeProperty;
public static DateTime GetLastChangeTime(DependencyObject d) => (DateTime)d.GetValue(LastChangeTimePropertyKey.DependencyProperty);
static void SetLastChangeTime(DependencyObject d, DateTime value) => d.SetValue(LastChangeTimePropertyKey, value);
#endregion
void ScrollViewer_ScrollChangeTime(object sender, ScrollChangedEventArgs e) {
//ScrollViewer scroll_backing = null;
//if (e.HorizontalChange != 0) {
//}
//ScrollViewer scroll() => scroll_backing ?? (scroll_backing = (ScrollViewer)sender);
}
private void PART_VerticalScrollBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
if (sender is ScrollBar sb) {
}
}
}
class AutoHideScrollBar : ScrollBar {
@@ -5,7 +5,10 @@ using mbts.ui.utility.text;
using System;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
@@ -48,7 +51,7 @@ namespace mbts.ui.controls {
if (value) {
_mouse_over_click_area_op = WorkLoop.Start(
$"Evaluate {nameof(HyperlinkCell)} {nameof(IsMouseOverClickArea)}",
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(10),
DispatcherPriority.Input,
_on_mouse_changed,
WorkLoop.default_excessive_cycle_ratio);
@@ -95,8 +98,8 @@ namespace mbts.ui.controls {
_border_stroke_pen_backing;
static HyperlinkCell() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(HyperlinkCell), new FrameworkPropertyMetadata(typeof(HyperlinkCell)));
IsMouseOverClickAreaProperty = IsMouseOverClickAreaPropertyKey.DependencyProperty;
DefaultStyleKeyProperty.OverrideMetadata(typeof(HyperlinkCell), new FrameworkPropertyMetadata(typeof(HyperlinkCell)));
WPFHelper.override_metadata<HorizontalAlignment, HyperlinkCell>(
HorizontalAlignmentProperty,
FrameworkPropertyMetadataOptions.AffectsArrange |
@@ -5,7 +5,6 @@ using mbts.ui.extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
@@ -13,7 +12,6 @@ using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace mbts.ui.spark {
class DIYGridPopupManager {
@@ -21,6 +19,8 @@ namespace mbts.ui.spark {
readonly FrameworkElement _owner;
readonly ScrollContentPresenter _scroll_content;
readonly ICollection<Visual> _children;
Popup _active_popup;
bool _is_activating_popup;
public static DIYGridPopupManager create(FrameworkElement owner) =>
create(owner, new VisualCollectionWrapper(new VisualCollection(owner)));
@@ -39,7 +39,22 @@ namespace mbts.ui.spark {
_children = children;
}
public void show(FrameworkElement view) {
public Popup active_popup {
get => _active_popup;
set {
if (_active_popup != value) {
_active_popup = value;
if (_active_popup != null) {
_is_activating_popup = true;
_active_popup.IsOpen = false;
_active_popup.IsOpen = true;
_is_activating_popup = false;
}
}
}
}
public async void show(FrameworkElement view, int delay_measure_ms = 100) {
var layout = _grid.GetColumnGeometry().ToList();
if (layout.Count == 0)
return;
@@ -54,88 +69,49 @@ namespace mbts.ui.spark {
var top_left = _scroll_content.PointToScreenPixels(
col.unclipped_left - x_origin,
Math.Ceiling(mouse_pos.Y / _grid.RowHeight) * _grid.RowHeight);
var popup = _mk_popup(_owner, view, top_left);
// attach to [parent] win
IDisposable win_hook = null, win_pos_hook = null;
Point last_pt = default;
bool initialized = false;
WindowStyle.AddUnsafeWindowChangedHandler(popup, on_unsafe_win_changed);
popup.SetBinding(WindowStyle.UnsafeWindowProperty, new Binding {
Path = new PropertyPath(WindowStyle.UnsafeWindowProperty),
Source = _owner,
Mode = BindingMode.OneWay
});
popup.Closed += on_closed;
void on_unsafe_win_changed(object sender, RoutedPropertyChangedEventArgs<Window> e) {
var win = e.NewValue;
Disposable.dispose(ref win_pos_hook);
if (win != null) {
if (!initialized) {
// The popup's offset is initialized to the screen coordinates (further adjustments are made according to the delta),
// so last_pt must be initialized to the window's top left.
last_pt = new Point(win.Left, win.Top);
initialized = true;
}
popup.SetCurrentValue(WindowStyle.UnsafeWindowProperty, win);
win_pos_hook = win.ObserveTopLeft()
.SubscribeOn(win.Dispatcher)
.ObserveOnDispatcher(DispatcherPriority.Normal)
.Subscribe(pt => {
popup.HorizontalOffset += pt.X - last_pt.X;
popup.VerticalOffset += pt.Y - last_pt.Y;
last_pt = pt;
});
}
}
void on_closed(object sender, EventArgs e) {
popup.Closed -= on_closed;
WindowStyle.RemoveUnsafeWindowChangedHandler(_owner, on_unsafe_win_changed);
Disposable.dispose(ref win_pos_hook);
Disposable.dispose(ref win_hook);
}
}
public async Task show_async(FrameworkElement view, int delay_measure_ms = 100) {
if (delay_measure_ms > 0)
await Task.Delay(delay_measure_ms);
view.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
show(view);
}
ZPopup _mk_popup(FrameworkElement owner, FrameworkElement view, Point offset) {
// popup
var popup = new ZPopup {
PlacementTarget = _grid,
Placement = PlacementMode.Absolute,
Child = view,
HorizontalOffset = offset.X,
VerticalOffset = offset.Y,
IsOpen = true,
HorizontalOffset = top_left.X,
VerticalOffset = top_left.Y,
StaysOpen = false
};
popup.SetBinding(WindowStyle.UnsafeWindowProperty, new Binding {
Source = _owner,
Path = new PropertyPath(WindowStyle.UnsafeWindowProperty)
});
view.InputBindings.Add(new KeyBinding(ApplicationCommands.Close, Key.Escape, ModifierKeys.None));
view.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (s, e) => popup.IsOpen = false));
var hooks = Disposable.Create(
view.SubscribePreviewMouseDown(on_view_preview_mouse_down),
view.ConnectDataContext<IRequestViewClose>(rvc => {
rvc.RequestClose += on_request_close;
return Disposable.Create(() => rvc.RequestClose -= on_request_close);
void on_request_close(object sender, EventArgs e) =>
popup.IsOpen = false;
}),
PopupViewController.enable_drag_move(_owner, popup));
view.PreviewMouseDown += on_view_preview_mouse_down;
view.ConnectDataContext<IRequestViewClose>(rvc => {
rvc.RequestClose += on_request_close;
return Disposable.Create(() => rvc.RequestClose -= on_request_close);
void on_request_close(object sender, EventArgs e) {
popup.IsOpen = false;
}
});
var drag_hooks = PopupViewController.enable_drag_move(_owner, popup);
_active_popup = popup;
_children.Add(popup);
_owner.ReleaseMouseCapture();
popup.Closed += on_closed;
FocusManager.SetIsFocusScope(view, true);
Keyboard.Focus(view);
view.Focus();
return popup;
//
void on_closed(object sender, EventArgs e) {
Disposable.dispose(ref hooks);
if (_is_activating_popup && popup == _active_popup) {
return;
}
view.PreviewMouseDown -= on_view_preview_mouse_down;
Disposable.dispose(ref drag_hooks);
popup.ReleaseMouseCapture();
if (Mouse.Captured == _owner)
_owner.ReleaseMouseCapture();
@@ -143,19 +119,8 @@ namespace mbts.ui.spark {
_children.Remove(popup);
}
async void on_view_preview_mouse_down(object sender, MouseButtonEventArgs e) {
if (WindowStyle.GetUnsafeWindow(popup) is Window win) {
//bool activated = false;
await win.Dispatcher.InvokeAsync(() => {
if (!win.IsActive) {
win.Activate();
//activated = true;
}
});
//if (activated)
popup.BringToFront();
}
}
void on_view_preview_mouse_down(object sender, MouseButtonEventArgs e) =>
active_popup = popup;
}
}
}
@@ -134,16 +134,8 @@ namespace mbts.spark {
foreach (IGrouping<TPredicateData, CellAnimation> g in animations)
animation_map.AddOrUpdate(g.Key, p => animation_tuple(c: g), (p, t) => t.cell_animations.AddRange(g));
}
var gs = new GridSettings(
font_family.name(),
font_size,
font_weight,
font_color.color.rgb_color(),
selection_highlight.color.rgb_color(),
col_settings);
if (show_background_color)
gs = gs.with(background: background_color.color.rgb_color());
return _create_settings_obj(gs,
return _create_settings_obj(new GridSettings(font_family.name(), font_size, font_weight, font_color.color.rgb_color(), selection_highlight.color.rgb_color(), col_settings,
background: background_color.color.with((byte)(MathUtils.within_range(0, 1, background_color.opacity) * 255.0)).rgb_color()),
animation_map.Select(kv => PredicateAnimations.create_data<TRowData, TPredicateData>(kv.Key, kv.Value.cell_animations, kv.Value.row_animations, kv.Value.sounds)));
//
(List<RowAnimation> row_animations, List<SoundNotification> sounds, List<CellAnimation> cell_animations) animation_tuple(IEnumerable<RowAnimation> r = null, IEnumerable<SoundNotification> s = null, IGrouping<TPredicateData, CellAnimation> c = null) =>
@@ -34,7 +34,7 @@
3) A ridiculously long MultiBinding, that has child bindings to the ActualWidth of each sibling visual element,
which are summed by the Converter to yield the total occupied width.
4) Finally: a visible textblock, with a MaxWidth bound to the minimum of the 'desired width' and the 'available width - occupied width.'
5) A new computer, to replace the one that was defenestrated after the frustratingly long journey to this solution.
5) A new computer, to replace the one that was defenestrated out of frustration on the long journey to this solution.
-->
<Canvas>
<TextBlock x:Name="PART_ContextHidden" FontWeight="Bold" Padding="1,0,0,0" Text="{Binding context}" Visibility="Hidden"/>
@@ -130,4 +130,4 @@
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="Template" Value="{StaticResource PopupChildTemplate}"/>
</Style>
</ResourceDictionary>
</ResourceDictionary>
@@ -1,5 +1,4 @@
using mbts.ui.dpi;
using System;
using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
@@ -56,33 +55,23 @@ namespace mbts.ui.controls {
}
}
/// <summary>
/// Enables drag move behavior by incrementing the popoup's <see cref="Popup.HorizontalOffset"/> and <see cref="Popup.VerticalOffset"/> properties
/// according to the mouse drag delta.
/// </summary>
/// <param name="surface">The element to initiate drag ops.</param>
/// <param name="popup">The popup to exhibit drag move behavior.</param>
/// <param name="adjust_to_actual_offset">
/// Whether or not the drag delta should be calculated by the popup's position actual position on the screen, or the popup's offset values
/// (the latter are not neccesarily within the bounds of the screen).
/// </param>
/// <returns>An <see cref="IDisposable"/> that will disable the drag behavior when disposed.</returns>
public static IDisposable enable_drag_move(FrameworkElement surface, Popup popup, bool adjust_to_actual_offset = true) {
var child = popup.Child;
Point offset = get_offset();
public static IDisposable enable_drag_move(FrameworkElement surface, Popup popup) {
Point? last_drag_pt = null;
return DragDropHelper.subscribe_drag_coordinates(surface, popup.Child as FrameworkElement).Subscribe(drag_pt => {
child = popup.Child;
offset = get_offset();
if (drag_pt.HasValue) {
var d = drag_pt.Value;
var rs = surface.RenderSize;
if (last_drag_pt.HasValue) {
(popup.HorizontalOffset, popup.VerticalOffset) =
offset.plus(drag_pt.Value.minus(last_drag_pt.Value)).deconstruct();
popup.HorizontalOffset += d.X - last_drag_pt.Value.X;
popup.VerticalOffset += d.Y - last_drag_pt.Value.Y;
last_drag_pt = d;
} else {
popup.SetCurrentValue(Popup.StaysOpenProperty, true);
last_drag_pt = d;
Mouse.Capture(surface);
}
} else {
last_drag_pt = null;
if (popup.StaysOpen) {
// popup.Child must be focused BEFORE the StaysOpen binding target (i.e., the popup itself) is updated;
// Otherwise, if StaysOpen becomes false as a result of the update,
@@ -96,13 +85,7 @@ namespace mbts.ui.controls {
surface.ReleaseMouseCapture();
}
}
last_drag_pt = drag_pt;
});
Point get_offset() =>
adjust_to_actual_offset ?
(child == null ? default : child.PointToScreenPixels(default)) :
new Point(popup.HorizontalOffset, popup.VerticalOffset);
}
}
}
+74 -199
View File
@@ -1,232 +1,107 @@
using bts;
using mbts.ui.native;
using mbts.ui.native;
using System;
using System.Runtime.InteropServices;
using System.Reactive.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
namespace mbts.ui.controls {
/// <summary>
/// A <see cref="Popup"/> that can change parent windows (according to the <see cref="WindowStyle.UnsafeWindowProperty"/>).
/// Also unlike normal popups, it vanishes when its parent window is minimized, and reappears when it is restored/maximized.
/// Popup with an adjustable 'Z' order (ordinary Popup control is always top-most).
/// </summary>
class ZPopup : Popup {
static int _id_counter;
static ZPopup _topmost_zpopup;
readonly LoggerContext _log;
IDisposable _window_sub;
Window _window;
bool _is_parent_changing;
bool _is_top_most;
public ZPopup() {
_log = new LoggerContext(Log.Ui, $"ZPop {ID} - ", null);
SetCurrentValue(IDProperty, Interlocked.Increment(ref _id_counter));
WindowStyle.AddUnsafeWindowChangedHandler(this, _on_unsafe_window_changed);
}
static ZPopup() =>
ChildProperty.OverrideMetadata(typeof(ZPopup), new FrameworkPropertyMetadata(OnChildChanged));
// The ID property helped diagnose issues during developement, by making it easy to keep track of popup instances
// (the heavy logging in this class provides additional diagnostic aid).
// As window activation/focus issues are nearly impossible to debug in the traditional debugger;
// (the active window (and focus) changes to the debugger window when break points are hit),
// such aids have proven quite useful.
#region ID
public static readonly DependencyProperty IDProperty =
WPFHelper.create_dp<int, ZPopup>(nameof(ID));
public ZPopup() =>
WindowStyle.AddUnsafeWindowChangedHandler(this, (s, e) => _on_window(e.NewValue));
public int ID {
get { return (int)GetValue(IDProperty); }
set { SetValue(IDProperty, value); }
#region IsTopMost
public static readonly DependencyProperty IsTopMostProperty =
WPFHelper.create_dp<bool, ZPopup>(nameof(IsTopMost), (o, v) => o._set_top_most_state(v));
public bool IsTopMost {
get { return (bool)GetValue(IsTopMostProperty); }
set { SetValue(IsTopMostProperty, value); }
}
#endregion
public void BringToFront() {
/// The logic below assumes that there will only be a single generation of <see cref="ZPopup"/>s
/// (i.e., that there won't be any <see cref="ZPopup"/>s nested inside of another <see cref="ZPopup"/>).
/// Don't reset the popup's position if it is already topmost wrt the other <see cref="ZPopup"/>s;
/// this prevents this popup from covering an open child <see cref="Popup"/>, as it would become the topmost of all windows.
if (Interlocked.Exchange(ref _topmost_zpopup, this) != this) {
// Reset the unsafe window hooks, so the callbacks are moved to the back of the invocation list.
// As each popup window is assigned the 'TopMost' z position in the parent window 'Activated' callback, and 'NoTopMost' in the 'Deactivated' callback,
// the relative z positions of sibling popups (i.e., w/ a common parent window) are a reverse linear translation of the invocation list (a LIFO/Stack arrangment).
WindowStyle.RemoveUnsafeWindowChangedHandler(this, _on_unsafe_window_changed);
WindowStyle.AddUnsafeWindowChangedHandler(this, _on_unsafe_window_changed);
_on_window(_window, false);
protected override void OnOpened(EventArgs e) =>
_set_top_most_state(IsTopMost);
static void OnChildChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is ZPopup zp) {
if (e.OldValue is UIElement old_child)
old_child.PreviewMouseLeftButtonDown -= zp.OnChildPreviewMouseLeftButtonDown;
if (e.NewValue is UIElement new_child)
new_child.PreviewMouseLeftButtonDown += zp.OnChildPreviewMouseLeftButtonDown;
}
}
protected override void OnClosed(EventArgs e) {
_log.info($"disposing parent window sub - reason: {(_is_parent_changing ? "parent change" : "closed")}.");
void OnChildPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) =>
SetCurrentValue(IsTopMostProperty, true);
void _on_window(Window win) {
Disposable.dispose(ref _window_sub);
// base.OnClose invokes the Closed event - don't do that if parent is changing.
// Reason: when the parent changes, the popup must be closed then reopened to detach from the old presentation source.
// Popups are quite the pain in the ass, lemme tell ya! (it might even be worth it to do a custom implementation, rather than derive from msoft's Popup).
if (!_is_parent_changing)
base.OnClosed(e);
}
protected override void OnOpened(EventArgs e) {
// Links that explain the nuances of SetWindowPos:
// https://www.pinvoke.net/default.aspx/user32.setwindowpos
// https://devblogs.microsoft.com/oldnewthing/20051121-10/?p=33263
// Links to the Popup base class code that calls SetWindowPos:
// https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/Primitives/Popup.cs,4fabcf08378ac9be,references
// https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Controls/Primitives/Popup.cs,fef52e73f7d51076
// https://referencesource.microsoft.com/#WindowsBase/Shared/MS/Win32/UnsafeNativeMethodsCLR.cs,d9c926e7b8eb6e2c
/// The main purpose of this class is to maintain the popup window's Z index so that it is always just above the main/parent window (and beneath every other window on top of it);
/// in other words, this should always be the case: popup_win.ZIndex == parent_win.ZIndex + 1.
/// Brief notes on window z order, which can be manipulated via <see cref="native.NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, SWP)"/>:
/// - There are 2 'z order' groups of windows
/// 1) 'Normal' windows: windows displayed via <see cref="Window.Show"/> (including the shell windows in BTS), and non-modal dialogs
/// 2) 'TopMost' windows: modal dialogs, and popups; these windows are always on top of 'Normal' windows.
/// The base class <see cref="Popup"/> was not designed to behave this way.
/// In the base class, when the popup is opened, a call to set the window's [z]position (<see cref="NativeMethods.SetWindowPos(IntPtr, IntPtr, int, int, int, int, SWP)"/>)
/// is made with <see cref="NativeMethods.HWND_TOPMOST"/> as the 'insertAfter' param (just before this method is called).
/// Positioning the popup window just above the main window (wrt z order) requires 2 calls:
/// 1) a call to remove it from the 'TopMost' group (this call is idempotent and safe to make every time the popup is displayed),
/// 2) a call to set it on top of the 'Normal' windows.
_set_top_most(NativeMethods.HWND_NOTOPMOST, "intializing z position on opened (1/2)");
}
static string _win_handle_name(IntPtr? handle) {
if (handle.HasValue) {
if (handle.Value == NativeMethods.HWND_BOTTOM)
return "Bottom";
if (handle.Value == NativeMethods.HWND_TOP)
return "Top";
if (handle.Value == NativeMethods.HWND_TOPMOST)
return "TopMost";
if (handle.Value == NativeMethods.HWND_NOTOPMOST)
return "NoTopMost";
return "Custom";
}
return "Null";
}
void _on_unsafe_window_changed(object sender, RoutedPropertyChangedEventArgs<Window> e) =>
_on_window(e.NewValue);
async void _on_window(Window win, bool reopen = true) {
Disposable.dispose(ref _window_sub);
var old_win = _window;
_window = win;
if (win == null)
return;
/// the lock object can be local to this method,
/// bc <see cref="_window_sub"/> will [always]be disposed on the same thread (this instance's dispatcher).
object locker = new object();
bool cancel = false;
Action unhook = null;
if (reopen && IsOpen && old_win != null) {
// close then reopen to force the base class to detach from the old presentation source
// then reattach to the new one
_log.info("Parent window changed - closing then reopneing popup to detach from previous parent's presentation source.");
_is_parent_changing = true;
SetCurrentValue(IsOpenProperty, false);
/// Use <see cref="DispatcherPriority.ApplicationIdle"/> priority to ensure that the
/// base class's calls to detach the popup from the old presentation source are executed before the popup is reopened.
/// This is not a time sensitive op, so ApplicationIdle might be the most apprioriate priority regardless.
await Dispatcher.InvokeAsync(() => {
SetCurrentValue(IsOpenProperty, true);
_is_parent_changing = false;
}, DispatcherPriority.ApplicationIdle);
}
_window_sub = Disposable.Create(() => {
lock (locker) {
if (unhook != null) {
unhook();
unhook = null;
Thread.MemoryBarrier();
if (win != null) {
var src = Observable.Create<bool>(o => {
o.OnNext(win.IsActive);
win.Activated += on_activated;
win.Deactivated += on_deactivated;
return Disposable.Create(() => {
win.Activated -= on_activated;
win.Deactivated -= on_deactivated;
});
void on_activated(object sender, EventArgs e) => o.OnNext(true);
void on_deactivated(object sender, EventArgs e) => o.OnNext(false);
})
.SubscribeOn(win.Dispatcher)
.OnDispatcher();
_window_sub = src.Subscribe(v => {
if (v == _is_top_most) {
/// <see cref="IsTopMost"/> is already equal to this value;
/// explicitly refresh the child's z index.
_set_top_most_state(v);
} else {
cancel = true;
/// <see cref="_set_top_most_state(bool)"/> will be called in the dependency prop changed callback
SetCurrentValue(IsTopMostProperty, v);
}
}
});
await win.Dispatcher.InvokeAsync(() => {
lock (locker) {
if (!cancel) {
win.Activated += on_activated;
win.Deactivated += on_deactivated;
win.StateChanged += on_state_changed;
if (win.IsActive) {
_set_top_most(NativeMethods.HWND_TOPMOST, "new parent window is [initially] active");
}
unhook = () => {
win.Dispatcher.InvokeAsync(() => {
win.Activated -= on_activated;
win.Deactivated -= on_deactivated;
win.StateChanged -= on_state_changed;
});
}
}
async void _set_top_most_state(bool value) {
_is_top_most = value;
if (Child != null && (PresentationSource.FromVisual(Child) is HwndSource hwnd_source)) {
var hwnd = hwnd_source.Handle;
if (NativeMethods.GetWindowRect(hwnd, out var rect)) {
if (value) {
var win = _window;
if (win != null) {
// bring popup to the front by activating parent window
await win.Dispatcher.InvokeAsync(() => {
// as this is an async op,
// check that the window hasn't changed, and IsTopMost is still true before activating
if (win == _window && _is_top_most)
win.Activate();
});
};
}
void on_activated(object sender, EventArgs e) =>
_set_top_most(NativeMethods.HWND_TOPMOST, "parent window activated");
void on_deactivated(object sender, EventArgs e) {
_set_top_most(NativeMethods.HWND_NOTOPMOST, "parent window deactivated 1/2");
_set_top_most(NativeMethods.HWND_TOP, "parent window deactivated 2/2");
}
void on_state_changed(object sender, EventArgs e) {
switch (win.WindowState) {
case WindowState.Minimized: {
if (_try_get_handle(out var handle))
NativeMethods.ShowWindow(new HandleRef(null, handle), (int)SW.SW_HIDE);
}
break;
case WindowState.Maximized:
case WindowState.Normal: {
if (_try_get_handle(out var handle))
NativeMethods.ShowWindow(new HandleRef(null, handle), (int)SW.SW_SHOW);
}
break;
} else {
// bring popup [alone]to the front.
NativeMethods.SetWindowPos(hwnd, NativeMethods.HWND_TOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, SWP.TOPMOST_FLAGS);
}
} else {
NativeMethods.SetWindowPos(hwnd, NativeMethods.HWND_NOTOPMOST, rect.Left, rect.Top, (int)Width, (int)Height, SWP.TOPMOST_FLAGS);
}
}
});
}
void _set_top_most(IntPtr? insert_after = null, string reason = "n/a") {
var flags = SWP.TOPMOST_FLAGS;
if (!Dispatcher.CheckAccess()) {
flags |= SWP.SWP_ASYNCWINDOWPOS;
}
if (!_try_get_insert_after(insert_after, out var ia_handle)) {
_log.info($"Ignored setting top most because an explicit 'insert after' handle was not specified, and the parent window's handle was not found - reason (for attempt): {reason}.");
} else if (_try_get_handle(out var handle) && NativeMethods.GetWindowRect(handle, out var rect)) {
_log.info($"setting top most - reason: {reason}; insert after handle: {_win_handle_name(insert_after)}.");
NativeMethods.SetWindowPos(handle, ia_handle, rect.Left, rect.Top, (int)Width, (int)Height, flags);
} else {
_log.info($"Ignored setting top most because the child window's handle was not found - reason (for attempt): {reason}; insert after handle: {_win_handle_name(insert_after)}.");
}
}
bool _try_get_handle(out IntPtr handle) {
if (Child != null && PresentationSource.FromVisual(Child) is HwndSource hwnd) {
handle = hwnd.Handle;
return true;
}
handle = default;
return false;
}
bool _try_get_insert_after(IntPtr? curr, out IntPtr result) {
if (curr.HasValue) {
result = curr.Value;
} else if (_window != null && PresentationSource.FromVisual(_window) is HwndSource hwnd) {
result = hwnd.Handle;
} else {
result = default;
return false;
}
return true;
}
}
}
@@ -1,5 +1,4 @@
using bts.utils;
using mbts.ui.utility.text;
using mbts.ui.utility.text;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -57,22 +56,6 @@ namespace mbts.ui.extensions {
public static IDisposable DeferInvalidateVisual(this UIElement target) =>
Disposable.Create(target.InvalidateVisual);
public static IObservable<Point> ObserveTopLeft(this Window win) =>
Observable.Create<Point>(o => {
var last_pt = new Point(win.Left, win.Top);
o.OnNext(last_pt);
win.LocationChanged += on_location_changed;
return Disposable.Create(() => win.LocationChanged -= on_location_changed);
void on_location_changed(object sender, EventArgs e) =>
notify();
void notify() {
if (Swap.compare_exchange(ref last_pt, new Point(win.Left, win.Top)))
o.OnNext(last_pt);
}
});
public static IDisposable SubscribeGotFocus(this UIElement target, RoutedEventHandler callback) {
target.GotFocus += callback;
return Disposable.Create(() => target.GotFocus -= callback);
@@ -35,12 +35,6 @@ namespace mbts.ui {
public static (double x, double y) deconstruct(this Point point) =>
(point.X, point.Y);
public static Point minus(this Point point, Point other) =>
new Point(point.X - other.X, point.Y - other.Y);
public static Point plus(this Point point, Point other) =>
new Point(point.X + other.X, point.Y + other.Y);
public static object get_template_child(this Control control, string name) {
if (control == null) throw new ArgumentNullException(nameof(control));
return control?.Template?.FindName(name, control);
@@ -57,7 +57,7 @@ namespace mbts.ui.shell {
set {
if (_owner != value) {
_owner = value;
_try_set_unsafe_window();
_try_set_wpf_bus();
}
}
}
@@ -237,7 +237,7 @@ namespace mbts.ui.shell {
Disposable.dispose(ref _hwnd_host);
}
void _try_set_unsafe_window() {
void _try_set_wpf_bus() {
if (_owner != null && document?.Content != null) {
document.Content.Dispatcher.InvokeAsync(() =>
WindowStyle.SetUnsafeWindow(document.Content, _owner));
+25 -17
View File
@@ -1,17 +1,25 @@
using mbts.utils;
using System.Windows.Input;
namespace mbts.ui.utilities {
static class MouseHelper {
public static MouseButtonState button_state(MouseButton button) {
switch (button) {
case MouseButton.Left: return Mouse.LeftButton;
case MouseButton.Middle: return Mouse.MiddleButton;
case MouseButton.Right: return Mouse.RightButton;
case MouseButton.XButton1: return Mouse.XButton1;
case MouseButton.XButton2: return Mouse.XButton2;
default: throw ExceptionBuilder.Argument.unexpected_case(button, nameof(button));
}
}
}
}
using mbts.ui.dpi;
using mbts.utils;
using System.Windows;
using System.Windows.Input;
namespace mbts.ui.utilities {
static class MouseHelper {
public static Point get_absolute_position() {
var wf_pt = System.Windows.Forms.Control.MousePosition;
return new Point(wf_pt.X * HighDpiExtensions.pixel_unit, wf_pt.Y * HighDpiExtensions.pixel_unit);
}
public static MouseButtonState button_state(MouseButton button) {
switch (button) {
case MouseButton.Left: return Mouse.LeftButton;
case MouseButton.Middle: return Mouse.MiddleButton;
case MouseButton.Right: return Mouse.RightButton;
case MouseButton.XButton1: return Mouse.XButton1;
case MouseButton.XButton2: return Mouse.XButton2;
default: throw ExceptionBuilder.Argument.unexpected_case(button, nameof(button));
}
}
}
}
@@ -1,84 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace bts.collections {
/// <summary>
/// Implements both <see cref="IReadOnlyList{T}"/> and <see cref="IList{T}"/>, as a wrapper around a source list.
/// When (not before) a mutation method of the latter interface is called (for the first time), the source list will be copied to a new instance of <see cref="List{T}"/>,
/// which will become the target of all subsequent calls to methods of either interface.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
class LazyMutatorList<T> : IList<T>, IReadOnlyList<T> {
IReadOnlyList<T> _result;
List<T> _mutable_backing;
public LazyMutatorList(IReadOnlyList<T> source) =>
_result = source ?? throw new ArgumentNullException(nameof(source));
public T this[int index] {
get => _result[index];
set => _mutable[index] = value;
}
public int Count => _result.Count;
public bool IsReadOnly => false;
public bool IsMutated => _mutable_backing != null;
public IReadOnlyList<T> Result => _result;
public List<T> MutatedResult => _mutable_backing ?? throw new InvalidOperationException("List has not been mutated.");
IList<T> _mutable {
get {
if (_mutable_backing == null) {
_mutable_backing = new List<T>(_result.Count);
for (int i = 0; i < _result.Count; i++)
_mutable.Add(_result[i]);
_result = _mutable_backing;
}
return _mutable_backing;
}
}
public void Add(T item) =>
_mutable.Add(item);
public void Clear() =>
_mutable.Clear();
public bool Contains(T item) =>
IndexOf(item) >= 0;
public void CopyTo(T[] array, int arrayIndex) {
var r = _result;
for (int i = 0; i < r.Count; i++)
array[i + arrayIndex] = r[i];
}
public int IndexOf(T item) {
var r = _result;
for (int i = 0; i < r.Count; i++) {
if (EqualityComparer<T>.Default.Equals(r[i], item))
return i;
}
return -1;
}
public void Insert(int index, T item) =>
_mutable.Insert(index, item);
public bool Remove(T item) =>
_mutable.Remove(item);
public void RemoveAt(int index) =>
_mutable.RemoveAt(index);
public IEnumerator<T> GetEnumerator() =>
(_mutable_backing ?? _result).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
-16
View File
@@ -1,16 +0,0 @@
using System.Collections.Generic;
namespace bts.utils {
public static class Swap {
public static bool compare_exchange<T>(ref T store, T new_value) =>
compare_exchange(ref store, new_value, EqualityComparer<T>.Default);
public static bool compare_exchange<T>(ref T store, T new_value, IEqualityComparer<T> comparer) {
if (!comparer.Equals(store, new_value)) {
store = new_value;
return true;
}
return false;
}
}
}
+7 -10
View File
@@ -12,22 +12,19 @@ env SDK_ROOT=/sdk \
SDK_VERSION=$SDK_VERSION \
SDK_BUILD_DATE=$SDK_BUILD_DATE
# copy sdk
COPY include/ /sdk/include/
COPY lib/ /sparkbin/
COPY externals /sdk/externals/
COPY spark.conf /sparkdata/conf/
COPY futures.coconut /sparkdata/data/replay/futures.coconut
# add user bts
RUN groupadd --gid 1000 $USERNAME && \
useradd -s /bin/bash --uid 1000 --gid 1000 -m $USERNAME && \
mkdir -p /sparkbin/plugins && \
mkdir /sparkdata && \
ln -s /sparkbin/ sdk/lib && \
echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \
chmod 0440 /etc/sudoers.d/$USERNAME && \
chown -R bts.bts /sparkbin/plugins && \
chown -R bts.bts /sparkdata
# copy sdk
COPY include/ /sdk/include/
COPY lib/ /sparkbin/
COPY externals /sdk/externals/
COPY spark.conf /sparkdata/conf/
COPY --chown=$USERNAME futures.coconut /sparkdata/data/replay/futures.coconut
@@ -1,6 +0,0 @@
1. Verify pressing the shift or alt key while double clicking in the Price column in a Ladder Window recenters ALL ladders
Launch 2 ladders
Scroll both ladders so they are no longer centered at mid market
Press the shift + double click while over the Price column
You should observe both scrolled ladders are now centered once again
The countdown timer is also reset via this spacebar action. This is more informational; I don't expect you to wait to verify that the timer is reset.