feat: Add Stream Reports shell window

This commit is contained in:
John Colvin committed 2025-11-15 12:16:31 -05:00
1 parent 6ed6a36ee1
commit da96744f7f
22 files changed
+841 -4

No files matched your search

@@ -4,16 +4,20 @@ namespace mbts.spark {
using bts.api.analytics;
using bts.api.core;
using bts.collections;
using bts.md;
using bts.shell;
using bts.shell.pnl;
using bts.spark;
using Bts.DataStreamCore;
using mbts.analytics;
using mbts.persist;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using Spark.Analytics;
using Spark.Core.Data;
using Spark.Core.Disposables;
using Spark.Core.Reactive;
@@ -35,6 +39,7 @@ namespace mbts.spark {
readonly IBus _bus;
readonly IWindowManager _wm;
readonly List<IShellWindowFactory> _window_factories;
readonly IUserPersist persist;
IDisposable _dispose;
@@ -46,20 +51,34 @@ namespace mbts.spark {
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
Lazy<UserTuple> user) {
Lazy<UserTuple> user,
IUserPersist persist,
IEnumerable<IDataStreamFactory> streamFactories) {
_wm = wm;
_bus = bus;
this.persist = persist;
var reports_demuxer = new TableUpdateDemuxer<ReportImmutable?, int>(default, false);
var nullable_reports_src = bus.subscribe(SparkTags.ReportBlackboardTags.ListTag)
.Table(r => r.Id)
.Select(
r => new ReportImmutable?(r),
r => r?.Id ?? throw new ArgumentNullException(nameof(r)));
var streamReportsSrc = Observable.Create<IReadOnlyDictionary<string, StreamReport>>(
o => persist.subscribe<StreamReport>(
StreamReport.PersistTopic,
".*",
rs => o.OnNext(rs.ToDictionary(r => r.key, r => r.value))))
.Replay(1);
var streamFactoryList = streamFactories.ToList();
var streamFactory = streamFactoryList.Count == 1
? streamFactoryList[0]
: new CompositeDataStreamFactory(streamFactoryList);
_window_factories = new() {
new VolSurfaceWindowFactory(this, bus, user.Value),
new AnalyticsExpirationParametersWindowFactory(this, bus),
new SlideReportWindowFactory(this, bus, reports_demuxer.subscribe),
new ComboReportWindowFactory(this, bus, reports_demuxer.subscribe),
new StreamReportWindowFactory(this, bus, persist, streamFactory, streamReportsSrc),
new PNLWindowFactory(
this, bus, settings_hub, orders_model, position_model, sec_meta_store),
new DayFillsWindowFactory(
@@ -72,6 +91,7 @@ namespace mbts.spark {
reports_src.Subscribe(_on_reports),
nullable_reports_src.Subscribe(reports_demuxer),
reports_demuxer,
streamReportsSrc.OnDispatcher().Subscribe(onStreamReports),
vm.launch_exp_params_view_cmd.subscribe_executed(_launch_exp_params_view),
vm.launch_pnl_cmd.subscribe_executed(_launch_pnl),
vm.launch_day_fills_cmd.subscribe_executed(_launch_day_fills),
@@ -86,7 +106,12 @@ namespace mbts.spark {
// combo
vm.combo_report_launcher_vm.launch_cmd.subscribe_executed(_launch_combo_report),
vm.combo_report_launcher_vm.create_cmd.subscribe_executed(_create_combo_report),
vm.combo_report_launcher_vm.delete_cmd.subscribe_executed(_delete_combo_report));
vm.combo_report_launcher_vm.delete_cmd.subscribe_executed(_delete_combo_report),
// stream
vm.StreamReportLauncher.launch_cmd.subscribe_executed(launchStreamReport),
vm.StreamReportLauncher.create_cmd.subscribe_executed(createStreamReport),
vm.StreamReportLauncher.delete_cmd.subscribe_executed(r => deleteStreamReport(r).ignore()),
streamReportsSrc.Connect());
}
public enum WindowType { Main, Heatmap }
@@ -111,8 +136,8 @@ namespace mbts.spark {
var settings = VolSurfaceSettings.Default(string.Empty);
var vm = new VolSurfaceSettingsEditorVM(
_bus, settings, v => _bus.post(SparkTags.VolSurfaceCreateTag, v)) {
can_edit_name = true
};
can_edit_name = true
};
var window = new VolSurfaceSettingsEditor {
DataContext = vm,
WindowStartupLocation = WindowStartupLocation.CenterScreen
@@ -237,6 +262,29 @@ namespace mbts.spark {
void _launch_combo_report(int id) =>
_bus.post(SparkTags.ShowComboReportTag, ComboReportSettings.Default(id));
void createStreamReport(string _) {
var vm = new StreamReportConfigurationVM(true);
var win = new StreamReportConfigurationDialog() {
DataContext = vm
};
WindowUtilities.connect_vm(win, vm);
vm.CommitCmd.executed += Commit;
win.move_to_mouse(-100, -100);
win.Show();
async void Commit(StreamReport report) {
await persist.set(StreamReport.PersistTopic, report.Name.ToString(), report);
WindowUtilities.force_close(win);
_bus.post(SparkTags.ShowStreamReportTag, report);
}
}
async Task deleteStreamReport(string name) =>
await persist.clear(StreamReport.PersistTopic, name);
void launchStreamReport(string name) =>
_bus.post(SparkTags.ShowStreamReportTag, new() { Name = name });
void _on_reports(IReadOnlyDictionary<int, ReportImmutable> reports) {
vm.slide_report_launcher_vm.items.Clear();
vm.combo_report_launcher_vm.items.Clear();
@@ -251,5 +299,10 @@ namespace mbts.spark {
}
}
}
void onStreamReports(IReadOnlyDictionary<string, StreamReport> streamReports) {
vm.StreamReportLauncher.items.SetItems(
streamReports.Values.Select(r => new KeyValueItemVM<string, string>(r.Name, r.Name)));
}
}
}
@@ -12,6 +12,7 @@ namespace mbts.spark {
public KeyValueLauncherVM<int, string> vol_surface_launcher_vm { get; } = new() { type_name = "Vol Surface" };
public KeyValueLauncherVM<int, string> slide_report_launcher_vm { get; } = new() { type_name = "Slide Report" };
public KeyValueLauncherVM<int, string> combo_report_launcher_vm { get; } = new() { type_name = "Combo Report" };
public KeyValueLauncherVM<string, string> StreamReportLauncher { get; } = new() { type_name = "Stream Report" };
// pnl
public EventCommand launch_pnl_cmd { get; } = new();
@@ -105,6 +105,8 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button
@@ -194,5 +196,23 @@
</Grid>
</ContentControl>
<ToggleButton
Grid.Row="9"
c:RadioButtonGroupManager.Value="stream_reports"
c:RadioButtonGroupManager.Manager="{StaticResource WindowTypeRadioButtonGroupManager}"
Margin="0,6,0,0"
Content="Stream"
IsChecked="{Binding Path='(u:ExpandCollapseAnimator.IsExpanded)', ElementName=StreamReportContent, Mode=TwoWay}"
Style="{StaticResource MenuToggleButton}"
/>
<ContentControl Grid.Row="10" Height="0">
<ContentControl
x:Name="StreamReportContent"
Content="{Binding stream_report_launcher_vm}"
ContentTemplate="{StaticResource ReportLauncherTemplate}"
/>
</ContentControl>
</Grid>
</UserControl>
@@ -0,0 +1,15 @@
#nullable enable
namespace Spark.Analytics;
using ProtoBuf;
[ProtoContract]
public class StreamReport {
public const string PersistTopic = "stream_view";
[ProtoMember(1)]
public string? Name { get; set; }
[ProtoMember(2)]
public string? Query { get; set; }
}
@@ -0,0 +1,63 @@
<Window
x:Class="Spark.Analytics.StreamReportConfigurationDialog"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
SizeToContent="WidthAndHeight"
Title="Stream Report"
Style="{StaticResource BTSDialog}"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/CursorsEx.xaml"/>
<ResourceDictionary Source="/view/Resources/DataTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<AdornerDecorator>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="16" />
<RowDefinition Height="Auto" />
<RowDefinition Height="16" />
<RowDefinition Height="*" />
<RowDefinition Height="16" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="16" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="16" />
</Grid.ColumnDefinitions>
<TextBox
Grid.Row="1"
Grid.Column="1"
ToolTipService.ShowOnDisabled="True"
u:TextBoxBehavior.TextPrompt="Name"
HorizontalAlignment="Stretch"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding CanEditName}"
ToolTip="Name" />
<TextBox
Grid.Row="3"
Grid.Column="1"
u:TextBoxBehavior.TextPrompt="Query"
HorizontalAlignment="Stretch"
Text="{Binding Query, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap"
AcceptsReturn="True"
MinWidth="240"
MinLines="3"
ToolTip="Query" />
<c:DialogSkirtOKCancel
Grid.Row="5"
Grid.ColumnSpan="3"
OKCommand="{Binding CommitCmd}"
OKCommandParameter="{Binding Result}" />
</Grid>
</AdornerDecorator>
</Window>
@@ -0,0 +1,12 @@
#nullable enable
namespace Spark.Analytics;
using System.Windows;
/// <summary>
/// Interaction logic for StreamReportConfigurationDialog.xaml
/// </summary>
partial class StreamReportConfigurationDialog : Window {
public StreamReportConfigurationDialog() =>
InitializeComponent();
}
@@ -0,0 +1,44 @@
#nullable enable
namespace Spark.Analytics;
using mbts.ui;
using mbts.ui.shell;
class StreamReportConfigurationVM : DisposableViewModelBase {
readonly Property<string?> name;
readonly Property<string?> query;
readonly DelegateProperty<StreamReport?> result;
public StreamReportConfigurationVM(bool canEditName) {
CanEditName = canEditName;
name = backing<string?>(nameof(Name));
query = backing<string?>(nameof(Query));
result = backing<StreamReport?>(
nameof(Result),
() => new() {
Name = Name,
Query = Query
});
CommitCmd = new EventCommand<StreamReport?>(IsValid);
query.Changed += (o, n) => {
result.refresh();
CommitCmd.RaiseCanExecuteChanged();
};
static bool IsValid(StreamReport? r) =>
r is not null && !string.IsNullOrEmpty(r.Query);
}
public string? Name {
get => name.Value;
set => name.set(value);
}
public bool CanEditName { get; }
public string? Query {
get => query.Value;
set => query.set(value);
}
public StreamReport? Result => result.Value;
public IEventCommand<StreamReport?> CommitCmd { get; }
}
Whitespace-only changes.
@@ -0,0 +1,35 @@
#nullable enable
namespace Spark.Analytics;
using BCG;
using mbts.ui.controls;
using mbts.ui.shell;
using System;
class StreamReportRowVM : DisposableViewModelBase, DIYGrid.IRowVM {
readonly IBlueRow row;
public StreamReportRowVM(IBlueRow row) {
this.row = row;
}
public event Action? Invalidated;
public IBlueRow Row => row;
public object? this[string columnName] => row[columnName];
public object? this[int columnIndex] => row[columnIndex];
event Action? DIYGrid.IRowVM.invalidated {
add => Invalidated += value;
remove => Invalidated -= value;
}
void RaiseInvalidated() =>
Invalidated?.Invoke();
void DIYGrid.IRowVM.raise_invalidated() =>
RaiseInvalidated();
}
@@ -0,0 +1,11 @@
namespace Spark.Analytics;
using ProtoBuf;
[ProtoContract]
class StreamReportSettings {
public const string PersistTopic = "stream_view";
[ProtoMember(1)]
public int Id { get; set; }
}
@@ -0,0 +1,135 @@
#nullable enable
namespace Spark.Analytics;
using BCG;
using bts;
using bts.collections;
using Bts.DataStreamCore;
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utility;
using Spark.Core.Disposables;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
class StreamReportVM : DisposableViewModelBase {
readonly List<(IDataGridColumnFilter Filter, string Template)> columnFilters = new();
readonly Property<StreamReportRowVM?> currentRow;
public StreamReportVM(StreamReport report, IObservable<IDataPacket> source, Func<StreamReport, Task> commitAsync) {
Name = report.Name ?? string.Empty;
Query = report.Query ?? string.Empty;
currentRow = backing<StreamReportRowVM?>(nameof(CurrentRow));
LaunchSettingsEditorCmd = new DialogCommand(CreateSettingsDialog);
_dispose = source.OnDispatcher().Subscribe(dp => {
if (Columns.Count == 0) {
columnFilters.SetItems(dp.Schema.columnInfo.Select(columnFilterFactory));
Columns.AddRange(dp.Schema.columnInfo.Select(columnFactory));
}
foreach (IBlueRow br in dp.deletedRows) {
var id = br.Id();
if (!Rows.RemoveFirst(r => r.Row.Id() == id)) {
Log.assert(false, "Failed to remove deleted row");
}
}
foreach (IBlueRow br in dp.addedRows) {
Rows.Add(new(br));
}
});
Window CreateSettingsDialog() {
var vm = new StreamReportConfigurationVM(false) {
Name = Name,
Query = Query
};
var win = new StreamReportConfigurationDialog() {
DataContext = vm
};
WindowUtilities.connect_vm(win, vm);
vm.CommitCmd.executed += Commit;
win.move_to_mouse(-100, -100);
return win;
async void Commit(StreamReport? report) {
if (report is null) {
return;
}
await commitAsync(report);
WindowUtilities.force_close(win);
}
}
}
public string Name { get; }
public string Query { get; }
public ObservableCollection<DIYGrid.ColumnBase> Columns { get; } = new();
public ObservableCollection<StreamReportRowVM> Rows { get; } = new();
public StreamReportRowVM? CurrentRow {
get => currentRow.Value;
set => currentRow.set(value);
}
public IDialogCommand LaunchSettingsEditorCmd { get; }
(IDataGridColumnFilter Filter, string Template) getColumnFilter(ColumnInfo columnInfo) {
if (columnInfo.colNo < 0 || columnInfo.colNo >= columnFilters.Count) {
throw new IndexOutOfRangeException();
}
return columnFilters[columnInfo.colNo];
}
(IDataGridColumnFilter Filter, string Template) columnFilterFactory(ColumnInfo columnInfo) {
var type = columnInfo.colType;
var name = columnInfo.colName;
var idx = columnInfo.colNo;
if (type == typeof(double) || type == typeof(float)) {
return (new DoubleMinMax<StreamReportRowVM>(r => r.Row.GetFloat64(idx) ?? double.NaN, name), DataGridFilterKnownTemplates.DoubleMinMax);
}
if (type == typeof(int)) {
return (new IntMinMax<StreamReportRowVM>(r => r.Row.GetInt32(idx) ?? 0, name), DataGridFilterKnownTemplates.IntMinMax);
}
if (type == typeof(uint)) {
return (new UIntMinMax<StreamReportRowVM>(r => (uint)(r.Row.GetInt64(idx) ?? 0), name), DataGridFilterKnownTemplates.UIntMinMax);
}
if (type == typeof(long)) {
return (new Int64MinMax<StreamReportRowVM>(r => r.Row.GetInt64(idx) ?? 0, name), DataGridFilterKnownTemplates.UIntMinMax);
}
if (type == typeof(string)) {
return (new RegexFilterVM<StreamReportRowVM>(r => r.Row[idx]?.ToString(), name), DataGridFilterKnownTemplates.Regex);
}
if (type == typeof(DateTime)) {
return (new TimeFilterVM<StreamReportRowVM>(r => r.Row.get_datetime(idx), name), DataGridFilterKnownTemplates.TimeFilter);
}
throw new NotImplementedException($"Filter not implemented for column type {type} (name: '{name}')");
}
DIYGrid.ColumnBase columnFactory(ColumnInfo columnInfo) {
var type = columnInfo.colType;
var name = columnInfo.colName;
var idx = columnInfo.colNo;
var (filter, filterTemplate) = getColumnFilter(columnInfo);
var rv = new DIYGrid.RenderTextColumn<StreamReportRowVM>(
r => r[columnInfo.colNo]?.ToString(), filter, filterTemplate) {
id = columnInfo.colName,
Header = columnInfo.colName,
Width = 80,
is_visible = true
};
var gs = GridSettings.Default;
rv.set_fallback_font_params(
new System.Windows.Media.FontFamily(gs.font_family), gs.font_size, gs.font_color.rgb_color(), gs.font_weight, gs.background);
return rv;
}
}
@@ -0,0 +1,55 @@
<UserControl
x:Class="Spark.Analytics.StreamReportView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bv="clr-namespace:bts.view"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:anal="clr-namespace:Spark.Analytics"
u:WindowStyle.UnsafeWindow="{Binding Path='(u:WindowStyle.UnsafeWindow)', RelativeSource={RelativeSource AncestorType=bv:SparkWindowView}}"
FocusManager.IsFocusScope="True"
Background="{u:BTSBrush UI.common_background}"
>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/FilterTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<AdornerDecorator>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<c:DIYGrid
x:Name="grid"
Grid.Row="0"
Columns="{Binding Columns}"
CurrentRow="{Binding CurrentRow}"
Rows="{Binding Rows}"
SyncColumnSortDirectionWithSortDescriptions="False"
>
<c:DIYGrid.RowTemplate>
<DataTemplate>
<anal:StreamReportRowView />
</DataTemplate>
</c:DIYGrid.RowTemplate>
</c:DIYGrid>
<StatusBar Grid.Row="1" DockPanel.Dock="Bottom">
<StatusBarItem HorizontalAlignment="Right">
<TextBlock>
<Run Text="{Binding Rows.Count, Mode=OneWay}" />
<Run Text=" | Rows "/>
<Run Text="{Binding Columns.Count, Mode=OneWay}" />
<Run Text=" | Columns"/>
</TextBlock>
</StatusBarItem>
</StatusBar>
</Grid>
</AdornerDecorator>
</UserControl>
@@ -0,0 +1,13 @@
namespace Spark.Analytics;
using mbts.ui.controls;
using System.Windows.Controls;
partial class StreamReportView : UserControl {
public StreamReportView() {
InitializeComponent();
}
}
class StreamReportRowView : DIYGrid.HighPerformanceRow<StreamReportRowVM> { }
@@ -0,0 +1,72 @@
#nullable enable
namespace Spark.Analytics;
using BCG;
using bts;
using bts.api;
using bts.spark;
using Bts.DataStream;
using Bts.DataStreamCore;
using Bts.DataStreamExpressions;
using mbts.persist;
using mbts.ui;
using Spark.Core.Disposables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
class StreamReportWindow : SparkWindow<StreamReport>, ISharedWindow {
public const string WINDOW_TYPE_NAME = "StreamReport";
readonly IDataStreamFactory streamFactory;
readonly StreamReport report;
readonly IUserPersist persist;
StreamReportVM? vm;
StreamReportView? view;
List<SparkCommand>? commands;
public StreamReportWindow(StreamReportWindowFactory factory, IBus bus, IDataStreamFactory streamFactory, StreamReport report, IUserPersist persist)
: base(WINDOW_TYPE_NAME, bus, factory) {
this.streamFactory = streamFactory;
this.report = report;
this.persist = persist;
Title = report.Name;
}
public override string window_type => WINDOW_TYPE_NAME;
public override UIElement? Content => view;
public override StreamReport SaveState => report;
public string thread_id => WINDOW_TYPE_NAME;
public override IEnumerable<SparkCommand> Commands =>
commands ?? Enumerable.Empty<SparkCommand>();
public void thread_init() {
if (report?.Query is null) {
Log.Ui.error("Unable to create report view because query is null");
return;
}
var exp = DataStreamExpressionsInterpreter.Evaluate(report.Query);
var stream = exp.getView(new Dictionary<string, StatementExpression>(0), streamFactory)?.AsObservable()
?? new LiteralStream("InvalidStream", "id:1,error:'Invalid query'").AsObservable();
vm = new(report, stream, r => persist.set(StreamReport.PersistTopic, r.Name ?? string.Empty, r));
commands = new() {
new SparkCommandCommand("Settings", Icons.Gear, vm.LaunchSettingsEditorCmd),
};
view = new() {
DataContext = vm
};
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
Disposable.dispose(ref vm);
commands?.OfType<IDisposable>().DisposeAll();
commands?.Clear();
}
}
@@ -0,0 +1,69 @@
#nullable enable
namespace Spark.Analytics;
using bts.api;
using bts.shell;
using Bts.DataStreamCore;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using Microsoft.Extensions.Logging;
using Spark.Core.Disposables;
using Spark.Core.Reactive;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
class StreamReportWindowFactory : ShellWindowFactory<StreamReport> {
readonly IBus bus;
readonly IUserPersist persist;
readonly IObservable<IReadOnlyDictionary<string, StreamReport>> streamReportsSrc;
readonly IDataStreamFactory streamFactory;
bool isInitialized;
public StreamReportWindowFactory(
IShellModule module, IBus bus, IUserPersist persist, IDataStreamFactory streamFactory, IObservable<IReadOnlyDictionary<string, StreamReport>> streamReportsSrc)
: base(module, StreamReportWindow.WINDOW_TYPE_NAME) {
this.bus = bus;
this.persist = persist;
this.streamFactory = streamFactory;
var streamReportsReplay = streamReportsSrc.Replay(1);
this.streamReportsSrc = streamReportsReplay;
_dispose = Disposable.Create(
bus.subscribe(SparkTags.ShowStreamReportTag).OnDispatcher().Subscribe(Show),
streamReportsReplay.Connect());
}
public override Task<IShellWindow> load(StreamReport state) =>
createAsync(state);
public async void Show(StreamReport state) =>
bus.post(SparkTags.ShowWindow, await createAsync(state));
async Task<IShellWindow> createAsync(StreamReport report) {
if (!isInitialized) {
isInitialized = true;
}
report.Query ??= (await streamReportsSrc.SelectKey(report.Name ?? string.Empty).FirstOrDefaultAsync())?.Query;
return new StreamReportWindow(this, bus, streamFactory, report, persist);
}
class LoggerFacade<T> : ILogger, ILogger<T> {
public IDisposable? BeginScope<TState>(TState state) where TState : notnull {
return Disposable.empty;
}
public bool IsEnabled(LogLevel logLevel) {
return false;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { }
}
}
+3
View File
@@ -137,6 +137,9 @@ namespace mbts.spark {
public static ITag<ComboReportSettings> ShowComboReportTag { get; } =
_mk_tag<ComboReportSettings>();
public static ITag<Spark.Analytics.StreamReport> ShowStreamReportTag { get; } =
_mk_tag<Spark.Analytics.StreamReport>();
public static ITag<ReconcileReportSettings> show_reconcile_report { get; } =
_mk_tag<ReconcileReportSettings>();
@@ -59,6 +59,7 @@
AlgoType = "AlgoTypeTemplate",
DoubleMinMax = "DoubleMinMaxTemplate",
IntMinMax = "IntMinMaxTemplate",
Int64MinMax = "Int64MinMaxTemplate",
UIntMinMax = "UIntMinMaxTemplate",
UShortMinMax = "UShortMinMaxTemplate",
ULongMinMax = "ULongMinMaxTemplate",
@@ -0,0 +1,69 @@
namespace mbts.spark.filters;
using bts.utils;
using ProtoBuf;
using System;
class Int64MinMax<TRow> : ComparableMinMax<TRow, long, Int64MinMaxState> {
public Int64MinMax(Func<TRow, long> get_row_val, string prop_name)
: base(get_row_val, prop_name) { }
}
[ProtoContract]
class Int64Status : INullableStructProto<long>, IEquatable<Int64Status> {
[ProtoMember(1)]
bool _active;
[ProtoMember(2)]
long _value;
public bool active => _active;
public long? value {
get => _active ? new long?(_value) : new long?();
set { if (_active = value.HasValue) _value = value.Value; }
}
public bool Equals(Int64Status other) =>
other != null &&
_active == other._active &&
_value == other._value;
public override bool Equals(object obj) =>
Equals(obj as Int64Status);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
_active.GetHashCode(),
_value.GetHashCode());
}
[ProtoContract]
class Int64MinMaxState : IMinMaxState<long>, IEquatable<Int64MinMaxState> {
[ProtoMember(1)]
readonly Int64Status _minimum;
[ProtoMember(2)]
readonly Int64Status _maximum;
public Int64MinMaxState() {
_minimum = new Int64Status();
_maximum = new Int64Status();
}
public INullableStructProto<long> minimum => _minimum;
public INullableStructProto<long> maximum => _maximum;
public bool Equals(Int64MinMaxState other) =>
other != null &&
_minimum.safe_equals(other._minimum) &&
_maximum.safe_equals(other._maximum);
public override bool Equals(object obj) =>
Equals(obj as Int64MinMaxState);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
_minimum?.GetHashCode() ?? 0,
_maximum?.GetHashCode() ?? 0);
}
@@ -13,6 +13,7 @@
<ResourceDictionary Source="/view/Resources/ComboBoxes.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DoubleMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/IntMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/Int64MinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/UIntMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/UShortMinMaxFilterControl.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/ULongMinMaxFilterControl.xaml"/>
@@ -56,6 +57,23 @@
/>
</usp:FilterContentControl>
</DataTemplate>
<DataTemplate x:Key="Int64MinMaxTemplate">
<usp:FilterContentControl
ApplyCommandParameter="{Binding}"
ApplyCommand="{x:Static c:DataGridFilterProperties.CommitCommand}"
ClearCommandParameter="{Binding}"
ClearCommand="{x:Static c:DataGridFilterProperties.ClearCommand}"
>
<usp:Int64MinMaxFilterControl
x:Name="Filter"
Minimum="{Binding minimum}"
Maximum="{Binding maximum}"
RequestBindingUpdateSource="{Binding}"
Width="{Binding Source={StaticResource MinMaxWidth}}"
u:Behavior.AutoFocusTargetProvider="{u:AutoFocusTarget TextBox, FocusKeyboard=True, ReleaseKeyboard=True}"
/>
</usp:FilterContentControl>
</DataTemplate>
<DataTemplate x:Key="UIntMinMaxTemplate">
<usp:FilterContentControl
ApplyCommandParameter="{Binding}"
@@ -0,0 +1,58 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:usp="clr-namespace:mbts.ui.spark">
<Style TargetType="usp:Int64MinMaxFilterControl">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="usp:Int64MinMaxFilterControl">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
VerticalAlignment="{TemplateBinding VerticalAlignment}"
>
<Grid
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="6"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="8"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Minimum</TextBlock>
<TextBlock Grid.Row="2" VerticalAlignment="Center">Maximum</TextBlock>
<c:TickUpDownNullableInt64
x:Name="PART_Minimum_Tick"
Grid.Column="2"
Focusable="False"
Value="{Binding Minimum, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
/>
<c:TickUpDownNullableInt64
x:Name="PART_Maximum_Tick"
Grid.Column="2"
Grid.Row="2"
Focusable="False"
Value="{Binding Maximum, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
@@ -0,0 +1,75 @@
using mbts.ui.controls;
using mbts.ui.extensions;
using Spark.Core.Disposables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace mbts.ui.spark {
/// <summary>
/// Interaction logic for Int64MinMaxFilterControl.xaml
/// </summary>
class Int64MinMaxFilterControl : Control {
static Int64MinMaxFilterControl() =>
DefaultStyleKeyProperty.OverrideMetadata(
typeof(Int64MinMaxFilterControl), new FrameworkPropertyMetadata(typeof(Int64MinMaxFilterControl)));
readonly BindingUpdateGroup minTextUpdate = new();
readonly BindingUpdateGroup maxTextUpdate = new();
IDisposable hooks;
public Int64MinMaxFilterControl() {
minTextUpdate.Properties.Add(TextBox.TextProperty);
maxTextUpdate.Properties.Add(TextBox.TextProperty);
BindingOperations.SetBinding(minTextUpdate, BindingUpdateGroup.SourceProperty, new Binding(nameof(RequestBindingUpdateSource)) { Source = this });
BindingOperations.SetBinding(maxTextUpdate, BindingUpdateGroup.SourceProperty, new Binding(nameof(RequestBindingUpdateSource)) { Source = this });
}
public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(nameof(Minimum), typeof(long?), typeof(Int64MinMaxFilterControl),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public long? Minimum {
get => GetValue(MinimumProperty) as long?;
set => SetValue(MinimumProperty, value);
}
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(nameof(Maximum), typeof(long?), typeof(Int64MinMaxFilterControl),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public long? Maximum {
get => GetValue(MaximumProperty) as long?;
set => SetValue(MaximumProperty, value);
}
public static readonly DependencyProperty RequestBindingUpdateSourceProperty = DependencyProperty.Register(
nameof(RequestBindingUpdateSource), typeof(IRequestBindingSourceUpdate), typeof(Int64MinMaxFilterControl));
public IRequestBindingSourceUpdate RequestBindingUpdateSource {
get => GetValue(RequestBindingUpdateSourceProperty) as IRequestBindingSourceUpdate;
set => SetValue(RequestBindingUpdateSourceProperty, value);
}
public override void OnApplyTemplate() {
Disposable.dispose(ref hooks);
var minTick = this.assert_template_child<TickUpDownNullableInt64>("PART_Minimum_Tick");
var maxTick = this.assert_template_child<TickUpDownNullableInt64>("PART_Maximum_Tick");
SetMaxTarget();
SetMaxTarget();
hooks = Disposable.Create(
minTick.SubscribeLoaded((s, e) => SetMinTarget()),
maxTick.SubscribeLoaded((s, e) => SetMaxTarget())
);
void SetMinTarget() =>
minTextUpdate.Target = minTick.descendants_of_type<TextBox>().FirstOrDefault();
void SetMaxTarget() =>
maxTextUpdate.Target = maxTick.descendants_of_type<TextBox>().FirstOrDefault();
}
}
}
@@ -3,6 +3,7 @@
using Spark.Core.Reactive;
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
@@ -215,6 +216,20 @@
this IObservable<T> source, Func<T, TResult> selector) =>
Observable.Create<TResult>(o => source.Subscribe(v => o.OnNext(selector(v))));
public static IObservable<TValue> SelectKey<TKey, TValue>(this IObservable<IReadOnlyDictionary<TKey, TValue>> source, TKey key) {
return Observable.Create<TValue>(Subscribe);
IDisposable Subscribe(IObserver<TValue> observer) {
return source.Subscribe(OnNext);
void OnNext(IReadOnlyDictionary<TKey, TValue> dict) {
if (dict.TryGetValue(key, out var val)) {
observer.OnNext(val);
}
}
}
}
/// <summary>
/// Uses each element of a source observable to create an inner observable of <typeparamref name="TResult"/>, unlike <see cref="Observable.SelectMany{TSource, TResult}(IObservable{TSource}, Func{TSource, IObservable{TResult}})"/>,
/// each inner sequence is terminated when the next one begins.