From 8a4e90e1be84cedb91adc176f2b064bc2f3624f9 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 2 Jan 2022 14:21:29 -0500 Subject: [PATCH] refactor: Clean up BTSColor * Rename argb props to be lower case * Make some member fns static extensions * Remove Serializable attribute * Use a single uint prop (rather than 4 byte props) for protobuf serialization --- .../MarketView/MarketViewWindowFactory.cs | 8 +- .../Trading/Ladder/VM/LadderOrderVM.cs | 21 +- .../Trading/Ladder/VM/LadderSettingsVM.cs | 2 +- .../spark/core/FontsAndColors/BTSColor.cs | 350 +++---- .../core/FontsAndColors/BTSColorExtension.cs | 2 +- .../core/FontsAndColors/BTSColorExtensions.cs | 69 ++ .../ColorPicker/Code/ColorSwatchItem.cs | 2 +- .../view/Converters/BTSColorConverter.cs | 18 +- .../spark/view/Extensions/WPFExtensions.cs | 895 +++++++++--------- src/client/spark_core/utils/BitHelper.cs | 28 +- 10 files changed, 701 insertions(+), 694 deletions(-) create mode 100644 src/client/spark/core/FontsAndColors/BTSColorExtensions.cs diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs index f87b00520..d42a0aaad 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs @@ -83,10 +83,10 @@ namespace bts.shell { var ask_col_index = columns.FindIndex(x => x.id == col_id(Columns.Ask)); if (bid_col_index > -1 && ask_col_index > -1) { if (!columns[bid_col_index].background_color_override.HasValue) { - columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint())); + columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.value)); } if (!columns[ask_col_index].background_color_override.HasValue) { - columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint())); + columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.value)); } } // and enable background color upgrade @@ -253,11 +253,11 @@ namespace bts.shell { bool applied = false; if (bid_col_index > -1 && ask_col_index > -1) { if (!columns[bid_col_index].background_color_override.HasValue) { - columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint())); + columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.value)); applied = true; } if (!columns[ask_col_index].background_color_override.HasValue) { - columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint())); + columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.value)); applied = true; } } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs index 3e88bdb88..a9f24ed07 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs @@ -94,19 +94,14 @@ namespace mbts.spark { } public void update() { - // update brushes - Color color; - switch (side) { - case Side.Buy: color = BTSColors.MarketData.bid_alt; break; - case Side.Sell: color = BTSColors.MarketData.ask_alt; break; - case Side.Undefined: - default: - color = BTSColors.MarketData.bid_ask_alt_blend; break; - } - var darker = BTSColor.darken2(color.R, color.G, color.B, 0.75); - Color dark = new Color() { A = 255, R = darker.r, G = darker.g, B = darker.b }; - var buy_sell_background_fill_color = new SolidColorBrush(color); - buy_sell_background_fill_color.Freeze(); + var color = side switch { + Side.Buy => BTSColors.MarketData.bid_alt, + Side.Sell => BTSColors.MarketData.ask_alt, + _ => BTSColors.MarketData.bid_ask_alt_blend, + }; + var (r, g, b) = color.darken2(0.75); + var dark = Color.FromRgb(r, g, b); + var buy_sell_background_fill_color = color.to_brush().frozen(); background = buy_sell_background_fill_color; hoverbackground = mkbrush(dark, _darkbg, 0); diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index e86517914..859388626 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -726,7 +726,7 @@ namespace mbts.spark { public LadderMarketBreakLine get_settings() => new LadderMarketBreakLine { - color = new BTSColor(color).ToUint(), + color = new BTSColor(color).value, show = show, refresh_mode = refresh_mode }; diff --git a/src/client/spark/core/FontsAndColors/BTSColor.cs b/src/client/spark/core/FontsAndColors/BTSColor.cs index 699a5cbdf..b1b670e5a 100644 --- a/src/client/spark/core/FontsAndColors/BTSColor.cs +++ b/src/client/spark/core/FontsAndColors/BTSColor.cs @@ -1,259 +1,179 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +namespace mbts.ui { + using bts.utils; -namespace mbts.ui { - [Serializable] - [ProtoBuf.ProtoContract(Name = "SerializableColorWrapper")] - public class BTSColor { - public BTSColor() { - A = 255; - B = 128; - R = 128; - G = 128; - } + using ProtoBuf; - public BTSColor(byte gray) { - A = 255; - B = gray; - R = gray; - G = gray; - } + using System; - public BTSColor(byte r, byte g, byte b) { - A = 255; - R = r; - G = g; - B = b; - } + [ProtoContract] + public class BTSColor : IEquatable { + public BTSColor() : this(255, 128, 128, 128) { } + + public BTSColor(byte gray) : this(255, gray, gray, gray) { } + + public BTSColor(byte r, byte g, byte b) : this(255, r, g, b) { } public BTSColor(byte a, byte r, byte g, byte b) { - A = a; - R = r; - G = g; - B = b; + this.a = a; + this.r = r; + this.g = g; + this.b = b; } public BTSColor(System.Windows.Media.Color color) { - A = color.A; - R = color.R; - G = color.G; - B = color.B; + a = color.A; + r = color.R; + g = color.G; + b = color.B; } public BTSColor(System.Drawing.Color color) { - A = color.A; - R = color.R; - G = color.G; - B = color.B; + a = color.A; + r = color.R; + g = color.G; + b = color.B; } public BTSColor(byte alpha, BTSColor color) { - A = alpha; - R = color.R; - G = color.G; - B = color.B; + a = alpha; + r = color.r; + g = color.g; + b = color.b; } - public BTSColor(uint source) { - var arr = BitConverter.GetBytes(source); - - A = (byte)(arr[3] != 0 ? arr[3] : 0xff); - R = arr[2]; - G = arr[1]; - B = arr[0]; - } - - public override bool Equals(object obj) { - if (obj != null) { - if (obj is BTSColor) - return ((BTSColor)obj).A == A && ((BTSColor)obj).B == B && ((BTSColor)obj).R == R && ((BTSColor)obj).G == G; - if (obj is System.Windows.Media.Color) - return ((System.Windows.Media.Color)obj).A == A && ((System.Windows.Media.Color)obj).B == B && ((System.Windows.Media.Color)obj).R == R && ((System.Windows.Media.Color)obj).G == G; - else if (obj is System.Drawing.Color) - return ((System.Drawing.Color)obj).A == A && ((System.Drawing.Color)obj).B == B && ((System.Drawing.Color)obj).R == R && ((System.Drawing.Color)obj).G == G; - } - return false; - } - - public override int GetHashCode() { - return (int)ToUint(); - } - - public uint ToUint() { - return ((uint)A << 24) | ((uint)R << 16) | ((uint)G << 8) | (uint)B; - } + public BTSColor(uint value) => + this.value = value; public enum LightenMethod { Absolute, Relative } - // return a new BTSColor that has been lightened by the specified amount - public BTSColor lighten(int value, LightenMethod method = LightenMethod.Relative) { - var hsl = to_hsl(); + public byte a { + get => (byte)(value >> 24); + set => this.value = BitHelper.set_byte(this.value, value, 24); + } - double _l = hsl.Item3; + public byte r { + get => (byte)(value >> 16); + set => this.value = BitHelper.set_byte(this.value, value, 16); + } - if (method == LightenMethod.Relative) { - _l += _l * value / 100; - } else { - _l += value / 100; + public byte g { + get => (byte)(value >> 8); + set => this.value = BitHelper.set_byte(this.value, value, 8); + } + + public byte b { + get => (byte)value; + set => this.value = BitHelper.set_byte(this.value, value, 0); + } + + [ProtoMember(1)] + public uint value { get; set; } + + public static double hue(double h, double s, double l) { + double m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; + double m1 = l * 2 - m2; + + switch (h) { + case < 0: + h += 1; + break; + case > 1: + h -= 1; + break; } - var rgb = to_rgb(hsl.Item1, hsl.Item2, _l); - - byte _r = (byte)rgb.Item1; - byte _g = (byte)rgb.Item2; - byte _b = (byte)rgb.Item3; - - return new BTSColor(_r, _g, _b); + if (h * 6 < 1) { + return m1 + (m2 - m1) * h * 6; + } + if (h * 2 < 1) { + return m2; + } + if (h * 3 < 2) { + return m1 + (m2 - m1) * (2 / 3 - h) * 6; + } + return m1; } - // Lighten by a negative number - public BTSColor darken(int value, LightenMethod method = LightenMethod.Relative) { - return lighten(value * -1); + // convert an HSL color into RGB + public static (double r, double g, double b) to_rgb(double h, double s, double l) { + h = h % 360 / 360; + s = Math.Min(1, Math.Max(0, s / 100)); + l = Math.Min(1, Math.Max(0, l / 100)); + + return ( + hue(h + 1 / 3, s, l) * 255, + hue(h, s, l) * 255, + hue(h - 1 / 3, s, l) * 255); } - public static (byte r, byte g, byte b) darken2(byte r, byte g, byte b, double darker = 0.75) { - return ((byte)(r * darker), (byte)(g * darker), (byte)(b * darker)); + public void Deconstruct(out byte a, out byte r, out byte g, out byte b) { + a = this.a; + r = this.r; + g = this.g; + b = this.b; } + public static implicit operator System.Drawing.Color(BTSColor x) => + x is null ? + System.Drawing.Color.Gray : + System.Drawing.Color.FromArgb(x.a, x.r, x.g, x.b); - #region Properties + public static implicit operator BTSColor(System.Drawing.Color x) => + new(x); - [ProtoBuf.ProtoMember(2), DefaultValue((byte)255)] - public byte A { get; private set; } + public static implicit operator System.Windows.Media.Color(BTSColor x) => + x is null ? + System.Windows.Media.Colors.Gray : + System.Windows.Media.Color.FromArgb(x.a, x.r, x.g, x.b); - [ProtoBuf.ProtoMember(6), DefaultValue((byte)128)] - public byte R { get; private set; } + public static implicit operator BTSColor(System.Windows.Media.Color x) => + new(x); - [ProtoBuf.ProtoMember(8), DefaultValue((byte)128)] - public byte G { get; private set; } - - [ProtoBuf.ProtoMember(4), DefaultValue((byte)128)] - public byte B { get; private set; } - - #endregion - - public static implicit operator System.Drawing.Color(BTSColor x) { - if (x != null) - return System.Drawing.Color.FromArgb(x.A, x.R, x.G, x.B); - return System.Drawing.Color.Gray; - } - - public static implicit operator BTSColor(System.Drawing.Color x) { - return new BTSColor(x); - } - - public static implicit operator System.Windows.Media.Color(BTSColor x) { - if (x != null) - return System.Windows.Media.Color.FromArgb(x.A, x.R, x.G, x.B); - return System.Windows.Media.Colors.Gray; - } - - public static implicit operator BTSColor(System.Windows.Media.Color x) { - return new BTSColor(x); - } - - static public implicit operator System.Windows.Media.Brush(BTSColor x) { - var v = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(x.A, x.R, x.G, x.B)); + public static implicit operator System.Windows.Media.Brush(BTSColor x) { + var v = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(x.a, x.r, x.g, x.b)); v.Freeze(); return v; } - static public implicit operator BTSColor(System.Windows.Media.SolidColorBrush x) { - return new BTSColor(x.Color); + public static implicit operator BTSColor(System.Windows.Media.SolidColorBrush x) => + new(x.Color); + + public static implicit operator BTSColor(byte x) => + new(x); + + public static implicit operator uint(BTSColor x) => + x.value; + + public static implicit operator BTSColor(uint x) => + new(x); + + public static implicit operator BTSColor(SettingsColor x) => + new((byte)x.A, (byte)x.R, (byte)x.G, (byte)x.B); + + public static implicit operator SettingsColor(BTSColor x) => + new() { A = x.a, R = x.r, G = x.g, B = x.b }; + + public BTSColor clone() => + new(a, r, g, b); + + public bool Equals(BTSColor other) => + other != null && value == other.value; + + public override bool Equals(object obj) { + if (obj is BTSColor bts_color) + return Equals(bts_color); + if (obj is System.Windows.Media.Color media_color) + return Equals(new BTSColor(media_color)); + if (obj is System.Drawing.Color drawing_color) + return Equals(new BTSColor(drawing_color)); + return false; } - public static implicit operator BTSColor(byte x) { - return new BTSColor(x); - } - - public static implicit operator uint(BTSColor x) { - return x.ToUint(); - } - - public static implicit operator BTSColor(uint x) { - return new BTSColor(x); - } - - public static implicit operator BTSColor(SettingsColor x) { - return new BTSColor((byte)x.A, (byte)x.R, (byte)x.G, (byte)x.B); - } - - public static implicit operator SettingsColor(BTSColor x) { - return new SettingsColor() { A = x.A, R = x.R, G = x.G, B = x.B }; - } - - #region Private Functions - - // convert the current color into HSL - private Tuple to_hsl() { - double rr = (double)R / (double)byte.MaxValue; - double gg = (double)G / (double)byte.MaxValue; - double bb = (double)B / (double)byte.MaxValue; - - var max = Math.Max(Math.Max(rr, gg), bb); - var min = Math.Min(Math.Min(rr, gg), bb); - double h = 0; - double s = 0; - double l = (max + min) / 2; - double d = max - min; - if (min != max) { - s = l > 0.5 ? - d / (2 - max - min) : - d / (max + min); - if (max == rr) h = (gg - bb) / d + (gg < bb ? 6 : 0); - if (max == gg) h = (bb - rr) / d + 2; - if (max == bb) h = (rr - gg) / d + 4; - h /= 6; - h = h * 360; - - s = s * 100; - l = l * 100; - } - - return Tuple.Create(h, s, l); - - } - - // convert an HSL color into RGB - private Tuple to_rgb(double h, double s, double l) { - h = (h % 360) / 360; - s = Math.Min(1, Math.Max(0, s / 100)); - l = Math.Min(1, Math.Max(0, l / 100)); - - double r = hue(h + 1 / 3, s, l) * 255; - double g = hue(h, s, l) * 255; - double b = hue(h - 1 / 3, s, l) * 255; - - return Tuple.Create(r, g, b); - } - - private double hue(double h, double s, double l) { - double m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; - double m1 = l * 2 - m2; - - h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); - - if (h * 6 < 1) { - return m1 + (m2 - m1) * h * 6; - } else if (h * 2 < 1) { - return m2; - } else if (h * 3 < 2) { - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - } else { - return m1; - } - } - #endregion - - + public override int GetHashCode() => + // Must return a const bc argb props are mutable + 0; } - } diff --git a/src/client/spark/core/FontsAndColors/BTSColorExtension.cs b/src/client/spark/core/FontsAndColors/BTSColorExtension.cs index 52a43966c..247683785 100644 --- a/src/client/spark/core/FontsAndColors/BTSColorExtension.cs +++ b/src/client/spark/core/FontsAndColors/BTSColorExtension.cs @@ -86,7 +86,7 @@ namespace mbts.ui { } if (Alpha != 0) { - out_color = new BTSColor((Byte)Alpha, out_color.R, out_color.G, out_color.B); + out_color = new BTSColor((Byte)Alpha, out_color.r, out_color.g, out_color.b); } // if the property type is a Color then return a Color diff --git a/src/client/spark/core/FontsAndColors/BTSColorExtensions.cs b/src/client/spark/core/FontsAndColors/BTSColorExtensions.cs new file mode 100644 index 000000000..5d788f7c3 --- /dev/null +++ b/src/client/spark/core/FontsAndColors/BTSColorExtensions.cs @@ -0,0 +1,69 @@ + +namespace mbts.ui { + using System; + + static class BTSColorExtensions { + public static System.Windows.Media.SolidColorBrush to_brush(this BTSColor color) => + new(color); + + public static System.Windows.Media.Color to_media_color(this BTSColor color) => + System.Windows.Media.Color.FromArgb(color.a, color.r, color.g, color.b); + + // return a new BTSColor that has been lightened by the specified amount + public static BTSColor lighten(this BTSColor color, int value, BTSColor.LightenMethod method = BTSColor.LightenMethod.Relative) { + var (h, s, l) = color.to_hsl(); + + if (method == BTSColor.LightenMethod.Relative) { + l += l * value / 100; + } else { + l += value / 100; + } + + var (r, g, b) = BTSColor.to_rgb(h, s, l); + return new((byte)r, (byte)g, (byte)b); + } + + // Lighten by a negative number + public static BTSColor darken(this BTSColor color, int value, BTSColor.LightenMethod method = BTSColor.LightenMethod.Relative) => + color.lighten(value * -1); + + public static (byte r, byte g, byte b) darken2(this BTSColor color, double darker = 0.75) => + ((byte)(color.r * darker), (byte)(color.g * darker), (byte)(color.b * darker)); + + // convert the current color into HSL + public static (double h, double s, double l) to_hsl(this BTSColor color) { + double rr = color.r / (double)byte.MaxValue; + double gg = color.g / (double)byte.MaxValue; + double bb = color.b / (double)byte.MaxValue; + + var max = Math.Max(Math.Max(rr, gg), bb); + var min = Math.Min(Math.Min(rr, gg), bb); + double h = 0; + double s = 0; + double l = (max + min) / 2; + double d = max - min; + + if (min == max) { + return (h, s, l); + } + + s = l > 0.5 ? + d / (2 - max - min) : + d / (max + min); + if (max == rr) { + h = (gg - bb) / d + (gg < bb ? 6 : 0); + } + if (max == gg) { + h = (bb - rr) / d + 2; + } + if (max == bb) { + h = (rr - gg) / d + 4; + } + h *= 60; + s *= 100; + l *= 100; + + return (h, s, l); + } + } +} diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs index db38f7750..99712d599 100644 --- a/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs @@ -28,7 +28,7 @@ namespace mbts.ui.controls.color_picker { get => (_color ?? (_color = _color_id.rgb_color())).Value; set { _color = value; - _color_id = new BTSColor(value).ToUint(); + _color_id = new BTSColor(value).value; } } diff --git a/src/client/spark/view/Converters/BTSColorConverter.cs b/src/client/spark/view/Converters/BTSColorConverter.cs index d5e5db271..199ef5ff4 100644 --- a/src/client/spark/view/Converters/BTSColorConverter.cs +++ b/src/client/spark/view/Converters/BTSColorConverter.cs @@ -1,18 +1,18 @@ using System; +using System.Globalization; using System.Windows.Data; using System.Windows.Media; namespace mbts.ui.converters { public class BTSColorConverter : IValueConverter { - public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value is Color) return value; - BTSColor c = value as BTSColor ?? new BTSColor(); - return Color.FromArgb(c.A, c.R, c.G, c.B); - } + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => + value is Color color ? + color : + (value as BTSColor ?? new BTSColor()).as_media_color(); - public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value is Color) return new BTSColor((Color)value); - return value as BTSColor ?? new BTSColor(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => + value is Color color ? + new BTSColor(color.A, color.R, color.G, color.B) : + value as BTSColor ?? new BTSColor(); } } diff --git a/src/client/spark/view/Extensions/WPFExtensions.cs b/src/client/spark/view/Extensions/WPFExtensions.cs index 2746a6c21..fdbab44ed 100644 --- a/src/client/spark/view/Extensions/WPFExtensions.cs +++ b/src/client/spark/view/Extensions/WPFExtensions.cs @@ -1,449 +1,446 @@ -using bts; -using bts.collections; -using bts.utils; - -using mbts.ui.utility; -using mbts.utils; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Linq; -using System.Reactive.Linq; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; - -namespace mbts.ui { - static class WPFExtensions { - 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); - } - - public static T get_template_child(this Control control, string name) { - object obj = get_template_child(control, name); - return ConvertUtils.try_convert(obj); - } - - public static bool try_get_template_child(this Control control, string name, out object result) { - if (control == null) throw new ArgumentNullException(nameof(control)); - var t = control.Template; - if (t != null) { - result = control.Template.FindName(name, control); - return result != null; - } - result = null; - return false; - } - - public static bool try_get_template_child(this Control control, string name, out T result) { - if (try_get_template_child(control, name, out object obj)) - return ConvertUtils.try_convert(obj, out result); - result = default; - return false; - } - - public static object assert_template_child(this Control control, string name) { - if (!try_get_template_child(control, name, out object result)) - throw new InvalidOperationException($"Template must have a child named '{name}'"); - return result; - } - - public static T assert_template_child(this Control control, string name) { - if (!try_get_template_child(control, name, out T result)) - throw new InvalidOperationException($"Template must have a {typeof(T)} child named '{name}'"); - return result; - } - - public static IEnumerable visual_children(this FrameworkElement v) { - var count = VisualTreeHelper.GetChildrenCount(v); - for (var x = 0; x < count; x++) { - yield return VisualTreeHelper.GetChild(v, x); - } - } - - // TODO: replace this method with 'argb_color' - // - before that, need to verify that no settings/colors become 'invisible' as a result. - public static Color rgb_color(this UInt32 color) { - var bytes = BitConverter.GetBytes(color); - return Color.FromRgb(bytes[2], bytes[1], bytes[0]); - } - - public static Color argb_color(this uint color) { - var bytes = BitConverter.GetBytes(color); - return Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]); - } - - /// - /// Creates a blended color, whose a, r, g, b channels are the average of two colors. - /// - public static Color blend_with(this Color color, Color other) => - Color.FromArgb( - (byte)(((ushort)color.A + (ushort)other.A) / 2), - (byte)(((ushort)color.R + (ushort)other.R) / 2), - (byte)(((ushort)color.G + (ushort)other.G) / 2), - (byte)(((ushort)color.B + (ushort)other.B) / 2)); - - public static SolidColorBrush to_brush(this BTSColor color) => - new SolidColorBrush(color); - - public static Brush rgb_brush(this uint color) { - var brush = new SolidColorBrush(rgb_color(color)); - brush.Freeze(); - return brush; - } - - public static Brush argb_brush(this uint color) { - var brush = new SolidColorBrush(argb_color(color)); - brush.Freeze(); - return brush; - } - - public static SolidColorBrush rgb_solid_brush(this uint color) => - new SolidColorBrush(rgb_color(color)); - - public static UInt32 rgb_color(this Color color) { - return (uint)color.A << 24 | (uint)color.R << 16 | (uint)color.G << 8 | (uint)color.B; - } - - public static Brush to_brush(this Color color) => - new SolidColorBrush(color); - - public static SolidColorBrush to_solid_brush(this Color color) => - new SolidColorBrush(color); - - public static Brush frozen(this Brush brush) { - brush.Freeze(); - return brush; - } - - public static SolidColorBrush frozen(this SolidColorBrush brush) { - brush.Freeze(); - return brush; - } - - public static Color with(this Color color, byte alpha) => - Color.FromArgb(alpha, color.R, color.G, color.B); - - public static SolidColorBrush with(this SolidColorBrush brush, double opacity) { - brush.Opacity = opacity; - return brush; - } - - public static Pen frozen(this Pen pen) { - pen.Freeze(); - return pen; - } - - public static ImageSource frozen(this ImageSource image_source) { - image_source.Freeze(); - return image_source; - } - - public static Point within_bounds(this Point point, double x_min = 0, double y_min = 0, double x_max = double.PositiveInfinity, double y_max = double.PositiveInfinity) => - new Point(MathUtils.within_range(x_min, x_max, point.X), MathUtils.within_range(y_min, y_max, point.Y)); - - // Perform a breadth first traversal of all children returning any that match the predicate. - // Matching children are *not* further traversed - public static IEnumerable visual_children_where(this FrameworkElement v, Func match) { - var children = visual_children(v).OfType().ToList(); - while (children.Count() > 0) { - var next = new List(); - foreach (var c in children) { - if (match(c)) { - yield return c; - } else { - next.AddRange(visual_children(c).OfType()); - } - } - children = next; - } - } - - public static IEnumerable descendants_of_type(this FrameworkElement v) { - return v.visual_children_where(fe => fe is T).Cast(); - } - - public static bool try_find_descendent_of_type(this FrameworkElement element, out T result) where T : DependencyObject => - element.descendants_of_type().TryGetFirst(out result); - - public static bool try_find_ancestor_of_type(this FrameworkElement element, out T result) where T : DependencyObject { - result = find_ancestor_of_type(element); - return result != null; - } - - public static bool try_find_ancestor_of_type(this FrameworkContentElement element, out T result) where T : DependencyObject { - result = find_ancestor_of_type(element); - return result != null; - } - - public static T find_ancestor_of_type(this FrameworkElement element) where T : DependencyObject { - return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); - T impl(DependencyObject d) { - if (d is T direct_match) - return direct_match; - if (d is FrameworkElement el) { - if (el.find_ancestor_of_type() is T rv) - return rv; - } else if (d is FrameworkContentElement cel) { - if (cel.find_ancestor_of_type() is T rv) - return rv; - } - return null; - } - IEnumerable candidates() { - yield return element.Parent; - yield return element.TemplatedParent; - yield return VisualTreeHelper.GetParent(element); - } - } - - public static T find_ancestor_of_type(this FrameworkContentElement element) where T : DependencyObject { - return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); - T impl(DependencyObject d) { - if (d is T direct_match) - return direct_match; - if (d is FrameworkElement el) { - if (el.find_ancestor_of_type() is T rv) - return rv; - } else if (d is FrameworkContentElement cel) { - if (cel.find_ancestor_of_type() is T rv) - return rv; - } - return null; - } - IEnumerable candidates() { - yield return element.Parent; - yield return element.TemplatedParent; - yield return VisualTreeHelper.GetParent(element); - } - } - - public static void clear_bindings(this DependencyObject d_obj, params DependencyProperty[] d_props) { - foreach (var dp in d_props) - BindingOperations.ClearBinding(d_obj, dp); - } - - public static IDisposable attach_binding(this DependencyObject target, DependencyProperty target_property, string path, FrameworkElement source_view, IValueConverter converter = null) { - object source_vm = source_view.DataContext; - try_reset_binding(); - source_view.DataContextChanged += on_data_context_changed; - return Disposable.Create(() => { - try { - source_view.DataContextChanged -= on_data_context_changed; - } catch (Exception ex) { - Log.Ui.warn($"Error detaching from {nameof(source_view)}.{nameof(FrameworkElement.DataContextChanged)} event: {ex}."); - } - }); - void on_data_context_changed(object sender, DependencyPropertyChangedEventArgs e) { - source_vm = e.NewValue; - try_reset_binding(); - } - void try_reset_binding() { - if (source_vm != null) - target.reset_binding(target_property, new Binding(path) { Source = source_vm, Converter = converter }); - } - } - - public static void reset_binding(this DependencyObject target, DependencyProperty target_property, BindingBase binding) { - BindingOperations.ClearBinding(target, target_property); - BindingOperations.SetBinding(target, target_property, binding); - } - - public static void TryRaiseCanExecuteChanged(this ICommand command) { - if (command == null) return; - else if (command is IRaiseCanExecuteChangedCommand temp) - temp.RaiseCanExecuteChanged(); - else - throw new NotImplementedException("This ICommand does not implement IRaiseCanExecuteChanged"); - } - - public static Task ExecuteAsync(this ICommand command, object parameter) { - ExceptionAssert.Argument.NotNull(command, nameof(command)); - if (command is IAsyncCommand acmd) - return acmd.Execute(parameter); - else - return Task.Run(() => command.Execute(parameter)); - } - - public static void TryExecuteIfCan(this ICommand command, object parameter) { - if (command != null) - ExecuteIfCan(command, parameter); - } - - public static void ExecuteIfCan(this ICommand command, object parameter) { - ExceptionAssert.Argument.NotNull(command, nameof(command)); - if (command.CanExecute(parameter)) - command.Execute(parameter); - } - - public static IDisposable ObserveProperty(this DependencyObject instance, DependencyProperty property, EventHandler callback) { - var descriptor = DependencyPropertyDescriptor.FromProperty(property, instance.GetType()); - if (descriptor != null) { - descriptor.AddValueChanged(instance, callback); - return Disposable.Create(() => descriptor.RemoveValueChanged(instance, callback)); - } - throw new ArgumentException("Could not find property descriptor given type"); - } - - public static IObservable Observe(this DependencyObject instance, DependencyProperty property) { - Log.assert(typeof(T) == instance.GetType()); - return Observable.Create(observer => { - return instance.ObserveProperty(property, (o, e) => { - observer.OnNext((T)instance.GetValue(property)); - }); - }); - } - - public static void CommitAny(this IEditableCollectionView collection) { - if (collection.IsEditingItem) { - collection.CommitEdit(); - } else if (collection.IsAddingNew) { - collection.CommitNew(); - } - } - - public static void CancelAny(this IEditableCollectionView collection) { - if (collection.IsEditingItem) { - if (collection.CanCancelEdit) - collection.CancelEdit(); - } else if (collection.IsAddingNew) { - collection.CancelNew(); - } - } - - public static void ClearMouseBindings(this UIElement element, MouseAction action) => - ClearMouseBindings(element, action, ModifierKeys.None); - - public static void ClearMouseBindings(this UIElement element, MouseAction action, ModifierKeys modifiers) { - for (int i = 0; i < element.InputBindings.Count; i++) { - var mb = element.InputBindings[i] as MouseBinding; - if (mb != null) { - var g = mb.Gesture as MouseGesture; - if (g != null && g.MouseAction == action && g.Modifiers == modifiers) - element.InputBindings.RemoveAt(i); - } - } - } - - public static void ClearKeyBindings(this UIElement element, Key key) => - ClearKeyBindings(element, key, ModifierKeys.None); - - public static void ClearKeyBindings(this UIElement element, Key key, ModifierKeys modifiers) { - for (int i = 0; i < element.InputBindings.Count; i++) { - if (element.InputBindings[i] is KeyBinding kb && kb.Key == key && kb.Modifiers == modifiers) - element.InputBindings.RemoveAt(i--); - } - } - - public static void ClearCommandBindings(this UIElement element, RoutedCommand cmd) { - for (int i = 0; i < element.CommandBindings.Count; i++) { - if (element.CommandBindings[i].Command == cmd) - element.CommandBindings.RemoveAt(i--); - } - } - - public static void EnsureIsVisible(this Window window) { - if (!window.IsVisible) window.Show(); - if (window.WindowState == WindowState.Minimized) { - window.WindowState = WindowState.Normal; - } - window.ensure_onscreen(); - window.Activate(); - } - - public static Size MeasureText(this Typeface font, double size, string text) { -#pragma warning disable CS0618 // Type or member is obsolete - var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, font, size, Brushes.Black); -#pragma warning restore CS0618 // Type or member is obsolete - return new Size(ft.Width, ft.Height); - } - - public static void SetSortingCriteria(this ICollectionView collection_view, IEnumerable sorting_criteria) { - collection_view.SortDescriptions.Clear(); - if (sorting_criteria != null) - foreach (var sc in sorting_criteria) - collection_view.SortDescriptions.Add(new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)); - } - - /// - /// Converts .SortDescriptions into a List<>. - /// - public static List get_sorting_criteria(this ICollectionView collection_view, ObservableCollection columns) => - collection_view.SortDescriptions - .Select(sd => new SortingCriteria(columns.FirstOrDefault(c => c.sort_member_path == sd.PropertyName)?.id, sd.Direction == ListSortDirection.Ascending)) - .Where(sc => sc.col_name != null) - .ToList(); - - public static IEnumerable get_sorting_criteria(this ICollectionView collection_view, IEnumerable columns) => - get_sorting_criteria(collection_view.SortDescriptions, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); - - public static IEnumerable get_sorting_criteria(IEnumerable sort_descriptions, IEnumerable<(string id, string path)> columns) => - from sd in sort_descriptions - join col in columns - on sd.PropertyName equals col.path - select new SortingCriteria(col.id, sd.Direction == ListSortDirection.Ascending); - - public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable columns) => - get_sort_descriptions(sorting_criterion, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); - - public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable<(string id, string path)> columns) => - from sc in sorting_criterion - join col in columns - on sc.col_name equals col.id - select new SortDescription(col.path, sc.direction()); - - /// - /// Converts each into a and assigns the result to .SortDescriptions. - /// - public static void set_sort_descriptions(this ICollectionView collection_view, IEnumerable sorting_criterion, ObservableCollection columns) { - using (collection_view.DeferRefresh()) { - collection_view.SortDescriptions.SetItems(sorting_criterion.empty_if_null() - .Select(sc => new SortDescription( - columns.FirstOrDefault(c => string.Equals(c.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase))?.sort_member_path, - sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)) - .Where(sd => !string.IsNullOrEmpty(sd.PropertyName))); - } - } - - public static IObservable> subscribe_sorting_criterion(this ICollectionView collection_view, Func sort_member_to_id) => - Observable.Create>(o => { - INotifyCollectionChanged notification_src = collection_view.SortDescriptions; - IList sort_descriptions = collection_view.SortDescriptions; - var sorting_criterion = sort_descriptions.Select(to_criteria).ToList(); - notification_src.CollectionChanged += on_sort_descriptions_changed; - o.OnNext(sorting_criterion); - return Disposable.Create(dispose); - // local methods - void on_sort_descriptions_changed(object sender, NotifyCollectionChangedEventArgs e) { - CollectionHelper.reflect_change(sorting_criterion, collection_view.SortDescriptions, to_criteria, null, e); - o.OnNext(sorting_criterion); - } - SortingCriteria to_criteria(SortDescription sd) => new SortingCriteria(sort_member_to_id(sd.PropertyName), sd.Direction == ListSortDirection.Ascending); - void dispose() => notification_src.CollectionChanged -= on_sort_descriptions_changed; - }); - - public static IEnumerable FlatItems(this CollectionViewGroup group) { - foreach (var item in group.Items) { - if (item is CollectionViewGroup nested) { - foreach (var ni in FlatItems(nested)) - yield return ni; - } else { - yield return item; - } - } - } - - public static Rect Expanded(this Rect rect, double uniform_dimension) { - // since Rect is a struct, we are mutating a copy of the caller's actual rect - rect.Inflate(new Size(uniform_dimension, uniform_dimension)); - return rect; - } - } -} +using bts; +using bts.collections; +using bts.utils; + +using mbts.ui.utility; +using mbts.utils; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui { + static class WPFExtensions { + 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); + } + + public static T get_template_child(this Control control, string name) { + object obj = get_template_child(control, name); + return ConvertUtils.try_convert(obj); + } + + public static bool try_get_template_child(this Control control, string name, out object result) { + if (control == null) throw new ArgumentNullException(nameof(control)); + var t = control.Template; + if (t != null) { + result = control.Template.FindName(name, control); + return result != null; + } + result = null; + return false; + } + + public static bool try_get_template_child(this Control control, string name, out T result) { + if (try_get_template_child(control, name, out object obj)) + return ConvertUtils.try_convert(obj, out result); + result = default; + return false; + } + + public static object assert_template_child(this Control control, string name) { + if (!try_get_template_child(control, name, out object result)) + throw new InvalidOperationException($"Template must have a child named '{name}'"); + return result; + } + + public static T assert_template_child(this Control control, string name) { + if (!try_get_template_child(control, name, out T result)) + throw new InvalidOperationException($"Template must have a {typeof(T)} child named '{name}'"); + return result; + } + + public static IEnumerable visual_children(this FrameworkElement v) { + var count = VisualTreeHelper.GetChildrenCount(v); + for (var x = 0; x < count; x++) { + yield return VisualTreeHelper.GetChild(v, x); + } + } + + // TODO: replace this method with 'argb_color' + // - before that, need to verify that no settings/colors become 'invisible' as a result. + public static Color rgb_color(this UInt32 color) { + var bytes = BitConverter.GetBytes(color); + return Color.FromRgb(bytes[2], bytes[1], bytes[0]); + } + + public static Color argb_color(this uint color) { + var bytes = BitConverter.GetBytes(color); + return Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]); + } + + /// + /// Creates a blended color, whose a, r, g, b channels are the average of two colors. + /// + public static Color blend_with(this Color color, Color other) => + Color.FromArgb( + (byte)(((ushort)color.A + (ushort)other.A) / 2), + (byte)(((ushort)color.R + (ushort)other.R) / 2), + (byte)(((ushort)color.G + (ushort)other.G) / 2), + (byte)(((ushort)color.B + (ushort)other.B) / 2)); + + public static Brush rgb_brush(this uint color) { + var brush = new SolidColorBrush(rgb_color(color)); + brush.Freeze(); + return brush; + } + + public static Brush argb_brush(this uint color) { + var brush = new SolidColorBrush(argb_color(color)); + brush.Freeze(); + return brush; + } + + public static SolidColorBrush rgb_solid_brush(this uint color) => + new SolidColorBrush(rgb_color(color)); + + public static UInt32 rgb_color(this Color color) { + return (uint)color.A << 24 | (uint)color.R << 16 | (uint)color.G << 8 | (uint)color.B; + } + + public static Brush to_brush(this Color color) => + new SolidColorBrush(color); + + public static SolidColorBrush to_solid_brush(this Color color) => + new SolidColorBrush(color); + + public static Brush frozen(this Brush brush) { + brush.Freeze(); + return brush; + } + + public static SolidColorBrush frozen(this SolidColorBrush brush) { + brush.Freeze(); + return brush; + } + + public static Color with(this Color color, byte alpha) => + Color.FromArgb(alpha, color.R, color.G, color.B); + + public static SolidColorBrush with(this SolidColorBrush brush, double opacity) { + brush.Opacity = opacity; + return brush; + } + + public static Pen frozen(this Pen pen) { + pen.Freeze(); + return pen; + } + + public static ImageSource frozen(this ImageSource image_source) { + image_source.Freeze(); + return image_source; + } + + public static Point within_bounds(this Point point, double x_min = 0, double y_min = 0, double x_max = double.PositiveInfinity, double y_max = double.PositiveInfinity) => + new Point(MathUtils.within_range(x_min, x_max, point.X), MathUtils.within_range(y_min, y_max, point.Y)); + + // Perform a breadth first traversal of all children returning any that match the predicate. + // Matching children are *not* further traversed + public static IEnumerable visual_children_where(this FrameworkElement v, Func match) { + var children = visual_children(v).OfType().ToList(); + while (children.Count() > 0) { + var next = new List(); + foreach (var c in children) { + if (match(c)) { + yield return c; + } else { + next.AddRange(visual_children(c).OfType()); + } + } + children = next; + } + } + + public static IEnumerable descendants_of_type(this FrameworkElement v) { + return v.visual_children_where(fe => fe is T).Cast(); + } + + public static bool try_find_descendent_of_type(this FrameworkElement element, out T result) where T : DependencyObject => + element.descendants_of_type().TryGetFirst(out result); + + public static bool try_find_ancestor_of_type(this FrameworkElement element, out T result) where T : DependencyObject { + result = find_ancestor_of_type(element); + return result != null; + } + + public static bool try_find_ancestor_of_type(this FrameworkContentElement element, out T result) where T : DependencyObject { + result = find_ancestor_of_type(element); + return result != null; + } + + public static T find_ancestor_of_type(this FrameworkElement element) where T : DependencyObject { + return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); + T impl(DependencyObject d) { + if (d is T direct_match) + return direct_match; + if (d is FrameworkElement el) { + if (el.find_ancestor_of_type() is T rv) + return rv; + } else if (d is FrameworkContentElement cel) { + if (cel.find_ancestor_of_type() is T rv) + return rv; + } + return null; + } + IEnumerable candidates() { + yield return element.Parent; + yield return element.TemplatedParent; + yield return VisualTreeHelper.GetParent(element); + } + } + + public static T find_ancestor_of_type(this FrameworkContentElement element) where T : DependencyObject { + return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); + T impl(DependencyObject d) { + if (d is T direct_match) + return direct_match; + if (d is FrameworkElement el) { + if (el.find_ancestor_of_type() is T rv) + return rv; + } else if (d is FrameworkContentElement cel) { + if (cel.find_ancestor_of_type() is T rv) + return rv; + } + return null; + } + IEnumerable candidates() { + yield return element.Parent; + yield return element.TemplatedParent; + yield return VisualTreeHelper.GetParent(element); + } + } + + public static void clear_bindings(this DependencyObject d_obj, params DependencyProperty[] d_props) { + foreach (var dp in d_props) + BindingOperations.ClearBinding(d_obj, dp); + } + + public static IDisposable attach_binding(this DependencyObject target, DependencyProperty target_property, string path, FrameworkElement source_view, IValueConverter converter = null) { + object source_vm = source_view.DataContext; + try_reset_binding(); + source_view.DataContextChanged += on_data_context_changed; + return Disposable.Create(() => { + try { + source_view.DataContextChanged -= on_data_context_changed; + } catch (Exception ex) { + Log.Ui.warn($"Error detaching from {nameof(source_view)}.{nameof(FrameworkElement.DataContextChanged)} event: {ex}."); + } + }); + void on_data_context_changed(object sender, DependencyPropertyChangedEventArgs e) { + source_vm = e.NewValue; + try_reset_binding(); + } + void try_reset_binding() { + if (source_vm != null) + target.reset_binding(target_property, new Binding(path) { Source = source_vm, Converter = converter }); + } + } + + public static void reset_binding(this DependencyObject target, DependencyProperty target_property, BindingBase binding) { + BindingOperations.ClearBinding(target, target_property); + BindingOperations.SetBinding(target, target_property, binding); + } + + public static void TryRaiseCanExecuteChanged(this ICommand command) { + if (command == null) return; + else if (command is IRaiseCanExecuteChangedCommand temp) + temp.RaiseCanExecuteChanged(); + else + throw new NotImplementedException("This ICommand does not implement IRaiseCanExecuteChanged"); + } + + public static Task ExecuteAsync(this ICommand command, object parameter) { + ExceptionAssert.Argument.NotNull(command, nameof(command)); + if (command is IAsyncCommand acmd) + return acmd.Execute(parameter); + else + return Task.Run(() => command.Execute(parameter)); + } + + public static void TryExecuteIfCan(this ICommand command, object parameter) { + if (command != null) + ExecuteIfCan(command, parameter); + } + + public static void ExecuteIfCan(this ICommand command, object parameter) { + ExceptionAssert.Argument.NotNull(command, nameof(command)); + if (command.CanExecute(parameter)) + command.Execute(parameter); + } + + public static IDisposable ObserveProperty(this DependencyObject instance, DependencyProperty property, EventHandler callback) { + var descriptor = DependencyPropertyDescriptor.FromProperty(property, instance.GetType()); + if (descriptor != null) { + descriptor.AddValueChanged(instance, callback); + return Disposable.Create(() => descriptor.RemoveValueChanged(instance, callback)); + } + throw new ArgumentException("Could not find property descriptor given type"); + } + + public static IObservable Observe(this DependencyObject instance, DependencyProperty property) { + Log.assert(typeof(T) == instance.GetType()); + return Observable.Create(observer => { + return instance.ObserveProperty(property, (o, e) => { + observer.OnNext((T)instance.GetValue(property)); + }); + }); + } + + public static void CommitAny(this IEditableCollectionView collection) { + if (collection.IsEditingItem) { + collection.CommitEdit(); + } else if (collection.IsAddingNew) { + collection.CommitNew(); + } + } + + public static void CancelAny(this IEditableCollectionView collection) { + if (collection.IsEditingItem) { + if (collection.CanCancelEdit) + collection.CancelEdit(); + } else if (collection.IsAddingNew) { + collection.CancelNew(); + } + } + + public static void ClearMouseBindings(this UIElement element, MouseAction action) => + ClearMouseBindings(element, action, ModifierKeys.None); + + public static void ClearMouseBindings(this UIElement element, MouseAction action, ModifierKeys modifiers) { + for (int i = 0; i < element.InputBindings.Count; i++) { + var mb = element.InputBindings[i] as MouseBinding; + if (mb != null) { + var g = mb.Gesture as MouseGesture; + if (g != null && g.MouseAction == action && g.Modifiers == modifiers) + element.InputBindings.RemoveAt(i); + } + } + } + + public static void ClearKeyBindings(this UIElement element, Key key) => + ClearKeyBindings(element, key, ModifierKeys.None); + + public static void ClearKeyBindings(this UIElement element, Key key, ModifierKeys modifiers) { + for (int i = 0; i < element.InputBindings.Count; i++) { + if (element.InputBindings[i] is KeyBinding kb && kb.Key == key && kb.Modifiers == modifiers) + element.InputBindings.RemoveAt(i--); + } + } + + public static void ClearCommandBindings(this UIElement element, RoutedCommand cmd) { + for (int i = 0; i < element.CommandBindings.Count; i++) { + if (element.CommandBindings[i].Command == cmd) + element.CommandBindings.RemoveAt(i--); + } + } + + public static void EnsureIsVisible(this Window window) { + if (!window.IsVisible) window.Show(); + if (window.WindowState == WindowState.Minimized) { + window.WindowState = WindowState.Normal; + } + window.ensure_onscreen(); + window.Activate(); + } + + public static Size MeasureText(this Typeface font, double size, string text) { +#pragma warning disable CS0618 // Type or member is obsolete + var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, font, size, Brushes.Black); +#pragma warning restore CS0618 // Type or member is obsolete + return new Size(ft.Width, ft.Height); + } + + public static void SetSortingCriteria(this ICollectionView collection_view, IEnumerable sorting_criteria) { + collection_view.SortDescriptions.Clear(); + if (sorting_criteria != null) + foreach (var sc in sorting_criteria) + collection_view.SortDescriptions.Add(new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)); + } + + /// + /// Converts .SortDescriptions into a List<>. + /// + public static List get_sorting_criteria(this ICollectionView collection_view, ObservableCollection columns) => + collection_view.SortDescriptions + .Select(sd => new SortingCriteria(columns.FirstOrDefault(c => c.sort_member_path == sd.PropertyName)?.id, sd.Direction == ListSortDirection.Ascending)) + .Where(sc => sc.col_name != null) + .ToList(); + + public static IEnumerable get_sorting_criteria(this ICollectionView collection_view, IEnumerable columns) => + get_sorting_criteria(collection_view.SortDescriptions, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); + + public static IEnumerable get_sorting_criteria(IEnumerable sort_descriptions, IEnumerable<(string id, string path)> columns) => + from sd in sort_descriptions + join col in columns + on sd.PropertyName equals col.path + select new SortingCriteria(col.id, sd.Direction == ListSortDirection.Ascending); + + public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable columns) => + get_sort_descriptions(sorting_criterion, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); + + public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable<(string id, string path)> columns) => + from sc in sorting_criterion + join col in columns + on sc.col_name equals col.id + select new SortDescription(col.path, sc.direction()); + + /// + /// Converts each into a and assigns the result to .SortDescriptions. + /// + public static void set_sort_descriptions(this ICollectionView collection_view, IEnumerable sorting_criterion, ObservableCollection columns) { + using (collection_view.DeferRefresh()) { + collection_view.SortDescriptions.SetItems(sorting_criterion.empty_if_null() + .Select(sc => new SortDescription( + columns.FirstOrDefault(c => string.Equals(c.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase))?.sort_member_path, + sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)) + .Where(sd => !string.IsNullOrEmpty(sd.PropertyName))); + } + } + + public static IObservable> subscribe_sorting_criterion(this ICollectionView collection_view, Func sort_member_to_id) => + Observable.Create>(o => { + INotifyCollectionChanged notification_src = collection_view.SortDescriptions; + IList sort_descriptions = collection_view.SortDescriptions; + var sorting_criterion = sort_descriptions.Select(to_criteria).ToList(); + notification_src.CollectionChanged += on_sort_descriptions_changed; + o.OnNext(sorting_criterion); + return Disposable.Create(dispose); + // local methods + void on_sort_descriptions_changed(object sender, NotifyCollectionChangedEventArgs e) { + CollectionHelper.reflect_change(sorting_criterion, collection_view.SortDescriptions, to_criteria, null, e); + o.OnNext(sorting_criterion); + } + SortingCriteria to_criteria(SortDescription sd) => new SortingCriteria(sort_member_to_id(sd.PropertyName), sd.Direction == ListSortDirection.Ascending); + void dispose() => notification_src.CollectionChanged -= on_sort_descriptions_changed; + }); + + public static IEnumerable FlatItems(this CollectionViewGroup group) { + foreach (var item in group.Items) { + if (item is CollectionViewGroup nested) { + foreach (var ni in FlatItems(nested)) + yield return ni; + } else { + yield return item; + } + } + } + + public static Rect Expanded(this Rect rect, double uniform_dimension) { + // since Rect is a struct, we are mutating a copy of the caller's actual rect + rect.Inflate(new Size(uniform_dimension, uniform_dimension)); + return rect; + } + } +} diff --git a/src/client/spark_core/utils/BitHelper.cs b/src/client/spark_core/utils/BitHelper.cs index f669a3baa..d27157f55 100644 --- a/src/client/spark_core/utils/BitHelper.cs +++ b/src/client/spark_core/utils/BitHelper.cs @@ -1,6 +1,8 @@ namespace bts.utils { public static class BitHelper { + public static byte loaded_byte => _ByteBits.all; public static int loaded_int32 => _Int32Bits.all; + public static uint loaded_uint32 => _UInt32Bits.all; public static bool remove_flags(ref int target, int flags) { if ((target & flags) == flags) { @@ -9,6 +11,17 @@ } else return false; } + static class _ByteBits { + public static readonly byte all; + + static _ByteBits() { + all = 1 << 7; + all |= (byte)(all >> 1); + all |= (byte)(all >> 2); + all |= (byte)(all >> 4); + } + } + static class _Int32Bits { public static readonly int all; @@ -21,5 +34,18 @@ all |= (all >> 16); } } + + static class _UInt32Bits { + public static readonly uint all; + + static _UInt32Bits() { + all = 1u << 31; + all |= all >> 1; + all |= all >> 2; + all |= all >> 4; + all |= all >> 8; + all |= all >> 16; + } + } } -} \ No newline at end of file +}