diff --git a/spark.proj b/spark.proj index c1aca656f..786ccd4bf 100644 --- a/spark.proj +++ b/spark.proj @@ -1,11 +1,14 @@ net462 + MakeFileProj + Makefile + - + diff --git a/src/client/spark/uicore/BTSApplicationBootstrapper.cs b/src/client/spark/uicore/BTSApplicationBootstrapper.cs new file mode 100644 index 000000000..45228bdae --- /dev/null +++ b/src/client/spark/uicore/BTSApplicationBootstrapper.cs @@ -0,0 +1,47 @@ +using System; +using System.Windows; +using System.Collections.Generic; +using mbts.ui.native; +using bts.log; +using System.Windows.Threading; + +namespace mbts.ui +{ + public abstract class BTSApplicationBootstrapper : IDisposable + { + private ShellModel _model; + + static BTSApplicationBootstrapper() { + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + Dispatcher.CurrentDispatcher.UnhandledException += CurrentDispatcher_HandleClipboardError; + } + + public static void CurrentDispatcher_HandleClipboardError(object sender, DispatcherUnhandledExceptionEventArgs e) { + // Dont' allow clipboard failure to bring down the shell + var com_exeption = e.Exception as System.Runtime.InteropServices.COMException; + if (com_exeption != null && com_exeption.ErrorCode == -2147221040) { + e.Handled = true; + } + } + + static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { + Logger.log(Level.Error, Subsystem.ui, "Unhandled Exception: " + e.ExceptionObject.ToString()); + if (e.IsTerminating) { + Logger.system_is_crashing("Unhandled exception", e.ExceptionObject); + } + } + + // Should create and show the shell + public abstract void CreateShell(ShellModel model); + + public void Run() { + _model = new ShellModel(); + _model.Initialize(); + CreateShell(_model); + } + + public void Dispose() { + _model.Dispose(); + } + } +} diff --git a/src/client/spark/uicore/BTSColor.cs b/src/client/spark/uicore/BTSColor.cs new file mode 100644 index 000000000..213169ed1 --- /dev/null +++ b/src/client/spark/uicore/BTSColor.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Reflection; +using System.ComponentModel; + +namespace mbts.ui +{ + [Serializable] + [ProtoBuf.ProtoContract(Name = "SerializableColorWrapper")] + public class BTSColor + { + public BTSColor() + { + A = 255; + B = 128; + R = 128; + G = 128; + } + + public BTSColor(byte gray) + { + A = 255; + B = gray; + R = gray; + G = gray; + } + + public BTSColor(byte r, byte g, byte b) + { + A = 255; + R = r; + G = g; + B = b; + } + + public BTSColor(byte a, byte r, byte g, byte b) + { + A = a; + R = r; + G = g; + B = b; + } + + public BTSColor(System.Windows.Media.Color color) + { + 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; + } + + public BTSColor(byte alpha, BTSColor color) + { + 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 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(); + + double _l = hsl.Item3; + + if (method == LightenMethod.Relative) + { + _l += _l * value / 100; + } + else + { + _l += value / 100; + } + + 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); + } + + // Lighten by a negative number + public BTSColor darken(int value, LightenMethod method = LightenMethod.Relative) + { + return lighten(value * -1); + } + + 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)); + } + + + #region Properties + + [ProtoBuf.ProtoMember(2), DefaultValue((byte)255)] + public byte A { get; private set; } + + [ProtoBuf.ProtoMember(6), DefaultValue((byte)128)] + public byte R { get; private set; } + + [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) + { + return new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(x.A, x.R, x.G, x.B)); + } + + static public implicit operator BTSColor(System.Windows.Media.SolidColorBrush x) + { + return new BTSColor(x.Color); + } + + 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 + + + } + +} diff --git a/src/client/spark/uicore/BTSColorExtension.cs b/src/client/spark/uicore/BTSColorExtension.cs new file mode 100644 index 000000000..c035e8ed7 --- /dev/null +++ b/src/client/spark/uicore/BTSColorExtension.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Markup; +using System.Windows.Media; +using System.Reflection; + +namespace mbts.ui +{ + [MarkupExtensionReturnType(typeof(object))] + public class BTSColorExtension : MarkupExtension + { + + public BTSColorExtension() { } + + public BTSColorExtension(string name) + { + Name = name; + } + + // The color_dictionary needs to be populated once + static BTSColorExtension() + { + // get all the colors in the nested types + foreach(Type t in typeof(BTSColors).GetNestedTypes(BindingFlags.Public | BindingFlags.Static)) { + foreach(PropertyInfo p in t.GetProperties(BindingFlags.Public | BindingFlags.Static)) { + if(p.PropertyType == typeof(BTSColor)) + color_dictionary.Add("{0}.{1}".fmt(t.Name, p.Name), (BTSColor)p.GetValue(null)); + else if (p.PropertyType == typeof(Color)) + color_dictionary.Add("{0}.{1}".fmt(t.Name, p.Name), (Color)p.GetValue(null)); + } + } + foreach(PropertyInfo p in typeof(BTSColors).GetProperties(BindingFlags.Public | BindingFlags.Static)) { + if(p.PropertyType == typeof(BTSColor)) + color_dictionary.Add(p.Name, (BTSColor)p.GetValue(null)); + else if (p.PropertyType == typeof(Color)) + color_dictionary.Add(p.Name, (Color)p.GetValue(null)); + } + } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + if (serviceProvider == null) { return null; } + + // get the target of the extension from the IServiceProvider interface + IProvideValueTarget _ipvt = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); + + // Get the Name of the attribute + String property_name = ""; + + Type property_type = null; + + //if property is not part of the VisualTree (Style defined in Resources, or ControlTemplate Triggers etc.) + if (_ipvt.TargetProperty == null) + property_type = typeof(Color); + + else if(_ipvt.TargetProperty is DependencyProperty) + { + DependencyProperty target_property = _ipvt.TargetProperty as DependencyProperty; + property_name = target_property.Name; + property_type = target_property.PropertyType; + } + else + { // else it must be PropertyInfo + PropertyInfo target_property = _ipvt.TargetProperty as PropertyInfo; + property_name = target_property.Name; + } + + + // if the color name exists in the dictionary then return the color/brush + BTSColor out_color = null; + + if (color_dictionary.TryGetValue(Name, out out_color)) + { + if (Lighten != 0) + { + out_color = out_color.lighten(Lighten); + } + + if (Darken != 0) + { + out_color = out_color.darken(Darken); + } + + if (Alpha != 0) + { + 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 + // else return a brush + if (property_type != null && property_type == typeof(Color)) + { + return (Color)out_color; + } + else + { + return (Brush)out_color; + } + } + else + { // if the color is not in the dictionary then throw an exception + Logger.assert_d(false, "The color '{0}' could not be found".fmt(Name)); + throw new ColorNotFoundException(); + } + + } + + // Create dictionary of colors + public static readonly Dictionary color_dictionary = new Dictionary(); + + [ConstructorArgument("name")] + public string Name { get; set; } + + public int Lighten { get; set; } + public int Darken { get; set; } + public int Alpha { get; set; } + + } +} diff --git a/src/client/spark/uicore/BTSColors.cs b/src/client/spark/uicore/BTSColors.cs new file mode 100644 index 000000000..b9b9b9f2a --- /dev/null +++ b/src/client/spark/uicore/BTSColors.cs @@ -0,0 +1,455 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Media; + + +namespace mbts.ui +{ + // Usage + // xmlns:mbts="clr-namespace:mbts.ui;assembly=bts_uicore" + // Value = "{mbts:BTSColor X.y}" + public static class BTSColors + { + static BTSColors() { + _header_brush = new SolidColorBrush(header); + _header_text_brush = new SolidColorBrush(header_text); + _header_alternate_brush = new SolidColorBrush(header_alternate); + foreach (var brush in new Brush[] { _header_brush, _header_text_brush, _header_alternate_brush }) brush.Freeze(); + } + + private static Brush _header_brush, _header_text_brush, _header_alternate_brush; + + [DisplayInfo(name = "Default Header")] + public static BTSColor header { get { return BTSCoreColors.base_blue; } } + public static Brush header_brush { get { return _header_brush; } } + public static BTSColor header_text { get { return BTSCoreColors.white; } } + public static Brush header_text_brush { get { return _header_text_brush; } } + public static BTSColor header_alternate { get { return BTSCoreColors.blue_grey; } } + public static BTSColor disabled_text { get { return BTSCoreColors.gray_light; } } + + public static BTSColor pinkalicious { get { return new BTSColor(0xff, 0x33, 0x99); } } + + // Grid column colors + + public static class Security + { + [DisplayInfo(name = "Security")] + public static BTSColor default_background { get { return BTSCoreColors.blue_dark; } } + public static BTSColor default_text { get { return BTSCoreColors.white; } } + + public static BTSColor default_future_background { get { return BTSCoreColors.green_dark_light; } } + public static BTSColor default_future_text { get { return BTSCoreColors.white; } } + + public static BTSColor visible_strike_range_background { get { return BTSCoreColors.blue_bright; } } + } + + public static class Greeks + { + // Base Colors + [DisplayInfo(name = "Greeks")] + public static BTSColor default_background { get { return BTSCoreColors.blue_bright_light; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + [DisplayInfo(name = "Theo")] + public static BTSColor live_theo { get { return BTSCoreColors.unrelated_green_for_theos_and_deltas_and_nothing_else; } } + [DisplayInfo(name = "Delta")] + public static BTSColor delta { get { return live_theo; } } + + // Alerts + [DisplayInfo(name = "Cross Buy Alert")] + public static BTSColor cross_buy { get { return BTSCoreColors.blue_light_alternate; } } + [DisplayInfo(name = "Proximity Buy Alert")] + public static BTSColor proximity_buy { get { return BTSCoreColors.blue_light_alternate_light; } } + [DisplayInfo(name = "Cross Sell Alert")] + public static BTSColor cross_sell { get { return BTSCoreColors.red_light; } } + [DisplayInfo(name = "Proximity Sell Alert")] + public static BTSColor proximity_sell { get { return BTSCoreColors.red_lighter; } } + + } + + public static class MarketData + { + static MarketData() { + _bid_brush.Freeze(); + _ask_brush.Freeze(); + } + private static readonly Brush _bid_brush = new SolidColorBrush(_bid); + private static readonly Brush _ask_brush = new SolidColorBrush(_ask); + // Base Colors + [DisplayInfo(name = "Market Data")] + public static BTSColor default_background { get { return BTSCoreColors.blue_light_lighter; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + private static readonly BTSColor _bid = new BTSColor(44, 75, 244), _ask = new BTSColor(244, 66, 66); + public static BTSColor bid { get { return _bid; } } + public static BTSColor ask { get { return _ask; } } + public static BTSColor last { get { return BTSCoreColors.black; } } + public static Brush bid_brush => _bid_brush; + public static Brush ask_brush => _ask_brush; + + [DisplayInfo(name = "Settlement")] + public static BTSColor settlement_background { get { return Grid.default_column_background; } } + [DisplayInfo(name = "Driver")] + public static BTSColor driver_background { get { return BTSCoreColors.blue_light_lighter; } } + + [DisplayInfo(name = "ATM")] + public static BTSColor atm_background { get { return BTSCoreColors.gray_dark; } } + + // Alerts + [DisplayInfo(name = "Trade Alert")] + public static BTSColor trade_alert { get { return BTSCoreColors.red_pale_dark; } } + [DisplayInfo(name = "Trade price over Theo Alert")] + public static BTSColor trade_price_over_theo { get { return BTSCoreColors.red_pale_dark; } } + [DisplayInfo(name = "Trade price under Theo Alert")] + public static BTSColor trade_price_under_theo { get { return BTSCoreColors.blue_bright_dark; } } + + } + + public static class Tasking + { + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + [DisplayInfo(name = "Task On")] + public static BTSColor eye_on { get { return BTSCoreColors.green_p_light; } } + public static BTSColor eye_cross { get { return BTSCoreColors.orange_light; } } + } + + public static class Position + { + // Base Colors + [DisplayInfo(name = "Position")] + public static BTSColor default_background { get { return BTSCoreColors.blue_light_dark; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + } + + public static class RiskReport + { + // Base Colors + [DisplayInfo(name = "Risk Report")] + public static BTSColor default_background { get { return BTSCoreColors.blue_light_dark; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + [DisplayInfo(name = "Risk PnL")] + public static BTSColor pnl_background { get { return Grid.default_column_background; } } + + // Alerts + public static BTSColor pnl_loss_text { get { return BTSCoreColors.red; } } + public static BTSColor pnl_profit_text { get { return text_default; } } + } + + public static class Orders + { + // Base Colors + [DisplayInfo(name = "Orders")] + public static BTSColor default_background { get { return BTSCoreColors.blue_light_lighter; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + [DisplayInfo(name = "Price")] + public static BTSColor price_background { get { return BTSCoreColors.blue_light_dark; } } + [DisplayInfo(name = "Size")] + public static BTSColor size_background { get { return BTSCoreColors.blue_light_dark; } } + + // Alerts + public static BTSColor working_status_summary { get { return BTSCoreColors.green; } } + public static BTSColor working_cancel { get { return BTSCoreColors.red; } } + public static BTSColor working_cancel_text { get { return BTSCoreColors.white; } } + + public static BTSColor filled { get { return BTSCoreColors.green_light_light_saturated; } } + + [DisplayInfo(name = "Order Buy Text")] + public static BTSColor order_buy_text { get { return BTSCoreColors.black; } } + [DisplayInfo(name = "Order Sell Text")] + public static BTSColor order_sell_text { get { return BTSCoreColors.black; } } + + [DisplayInfo(name = "Order Buy Background")] + public static BTSColor order_buy_background { get { return BTSCoreColors.red_light_dark_saturated; } } + [DisplayInfo(name = "Order Sell Background")] + public static BTSColor order_sell_background { get { return BTSCoreColors.blue_light_dark_saturated; } } + + public static BTSColor straddle_theovsmarket_negative { get { return BTSCoreColors.red_light; } } + public static BTSColor straddle_theovsmarket_positive { get { return BTSCoreColors.green_light; } } + } + + public static class AW2 { + public static BTSColor collapsed { get { return BTSCoreColors.blue_light_dark; } } + } + + public static class Quoter + { + // Base Colors + [DisplayInfo(name = "Quoter")] + public static BTSColor default_background { get { return BTSCoreColors.blue_grey_lighter; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + [DisplayInfo(name = "Quoter Set Background")] + public static BTSColor set_background { get { return BTSCoreColors.blue_grey_light; } } + + public static BTSColor ask_text { get { return BTSCoreColors.red_dark; } } + public static BTSColor bid_text { get { return BTSCoreColors.blue; } } + + // Alerts + [DisplayInfo(name = "Quoting Security On")] + public static BTSColor quoting_security_on { get { return BTSCoreColors.yellow_lighter; } } + [DisplayInfo(name = "Quoting Security Streaming")] + public static BTSColor quoting_security_streaming { get { return BTSCoreColors.green_bright; } } + [DisplayInfo(name = "Quoting Security On BBO")] + public static BTSColor quoting_security_on_bbo { get { return BTSCoreColors.green_bright_dark; } } + + } + + public static class Quoteset + { + // Base Colors + [DisplayInfo(name = "Quoteset")] + public static BTSColor default_background { get { return BTSCoreColors.gray_dc; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + + public static BTSColor ask_text { get { return BTSCoreColors.red_dark; } } + public static BTSColor bid_text { get { return BTSCoreColors.blue; } } + + [DisplayInfo(name = "Quoteset Price")] + public static BTSColor mid_price_background { get { return new BTSColor(0xff, 0xda, 0xb9); } } //ffdab9 - "PeachPuff" + [DisplayInfo(name = "Quoteset Mid Straddle")] + public static BTSColor mid_straddle_background { get { return mid_price_background; } } + + // Alerts + [DisplayInfo(name = "Quoteset Override")] + public static BTSColor quoteset_override { get { return BTSCoreColors.gray_8c; } } + [DisplayInfo(name = "Quoteset Input Override")] + public static BTSColor quoteset_input_override { get { return BTSCoreColors.blue_grey_light; } } + + } + + public static class Presave + { + [DisplayInfo(name = "Presave")] + public static BTSColor default_background { get { return BTSCoreColors.yellow_light; } } + public static BTSColor default_text { get { return BTSCoreColors.black; } } + } + + public static class Grid + { + // grid defaults + [DisplayInfo(name = "Grid Line")] + public static BTSColor grid_line_dark { get { return BTSCoreColors.black; } } + public static BTSColor grid_line { get { return BTSCoreColors.gray; } } + public static BTSColor grid_line_light { get { return BTSCoreColors.gray_light; } } + public static BTSColor grid_line_lighter { get { return BTSCoreColors.gray_lighter; } } + public static BTSColor grid_line_lightest { get { return BTSCoreColors.gray_lightest; } } + public static BTSColor grid_line_lightest_light { get { return BTSCoreColors.gray_lightest_light; } } + public static BTSColor grid_selection_background_overlay { get { return BTSCoreColors.gray; } } + public static BTSColor grid_selection_background { get { return BTSCoreColors.gray_lighter; } } + public static BTSColor grid_selection_border { get { return BTSCoreColors.blue_bright; } } + + public static BTSColor grid_vertical_group_separator { get { return grid_line_dark; } } + + public static BTSColor expiration_seperator { get { return grid_line_dark; } } + + [DisplayInfo(name = "Grid Default Background")] + public static BTSColor default_column_background { get { return BTSCoreColors.blue_light; } } + public static BTSColor light_column_background { get { return BTSCoreColors.white; } } + + // input grid + public static BTSColor input_grid_line { get { return BTSCoreColors.black; } } + public static BTSColor input_cell_background { get { return BTSCoreColors.white; } } + public static BTSColor input_grid_line_focused { get { return BTSCoreColors.blue_bright; } } + public static BTSColor input_cell_background_focused { get { return BTSCoreColors.gray_lightest_light; } } + public static BTSColor wacky_strike_atm_color { get { return new BTSColor(0x82, 0x93, 0xaf); } } + public static BTSColor alternate_row_background { get { return BTSCoreColors.blue_light_lighter; } } + + public static BTSColor grid_cell_change_flash { get { return new BTSColor(0xff, 0xff, 0x11); } } // Not useable from ColorAnimation? - see VolSurfaceView.xaml + } + + public static class Graph + { + public static BTSColor grid_line { get { return new BTSColor(64, 0, 0, 0); } } + } + + public static class UI + { + [DisplayInfo(name = "Shell Background")] + public static BTSColor default_background { get { return new BTSColor(0xf6, 0xf6, 0xf6); } } + [DisplayInfo(name = "Shell Text")] + public static BTSColor default_text { get { return new BTSColor(34); } } + public static BTSColor alternate_text { get { return BTSCoreColors.white; } } + + public static BTSColor input_background { get { return new BTSColor(0xff); } } + public static BTSColor input_text { get { return default_text; } } + + public static BTSColor freeze { get { return gray; } } + + [DisplayInfo(name = "Shell Accent Dark")] + public static BTSColor accent_dark { get { return logo; } } + [DisplayInfo(name = "Shell Accent Light")] + public static BTSColor accent_light { get { return new BTSColor(0x8f, 0xa9, 0xbe); } } + + public static BTSColor form_border { get { return new BTSColor(80, 80, 90); } } + + [DisplayInfo(name = "Shell Dialog Skirt")] + public static BTSColor dialog_skirt { get { return new BTSColor(0xe1, 0xe7, 0xeb); } } + + [DisplayInfo(name = "BTS Success")] + public static BTSColor success { get { return new BTSColor(67, 172, 106); } } + [DisplayInfo(name = "BTS Danger")] + public static BTSColor danger { get { return new BTSColor(240, 65, 36); } } + [DisplayInfo(name = "BTS Warning")] + public static BTSColor warning { get { return new BTSColor(191, 102, 0); } } + public static BTSColor warning_dark { get { return new BTSColor(114, 61, 0); } } + public static BTSColor warning_light { get { return new BTSColor(Colors.LightYellow); } } + + + public static BTSColor brand_lightest { get { return new BTSColor(230, 243, 249); } } + public static BTSColor brand_lighter { get { return new BTSColor(191, 225, 239); } } + [DisplayInfo(name = "BTS Brand Light")] + public static BTSColor brand_light { get { return new BTSColor(128, 195, 224); } } + [DisplayInfo(name = "BTS Brand Info")] + public static BTSColor brand_info { get { return new BTSColor(25, 187, 255); } } + public static BTSColor brand_medium { get { return new BTSColor(60, 165, 207); } } + [DisplayInfo(name = "BTS Brand Primary")] + public static BTSColor brand_primary { get { return new BTSColor(0, 134, 191); } } + [DisplayInfo(name = "BTS Brand Dark")] + public static BTSColor brand_dark { get { return new BTSColor(0, 101, 143); } } + public static BTSColor brand_darker { get { return new BTSColor(0, 67, 96); } } + public static BTSColor brand_darkest { get { return new BTSColor(0, 13, 19); } } + + public static BTSColor black { get { return BTSCoreColors.black; } } + public static BTSColor white { get { return BTSCoreColors.white; } } + + [DisplayInfo(name = "Darkest Gray")] + public static BTSColor gray_darkest { get { return BTSCoreColors.gray_darkest; } } + [DisplayInfo(name = "Darker Gray")] + public static BTSColor gray_darker { get { return BTSCoreColors.gray_darker; } } + [DisplayInfo(name = "Dark Gray")] + public static BTSColor gray_dark { get { return BTSCoreColors.gray_dark; } } + [DisplayInfo(name = "Gray")] + public static BTSColor gray { get { return BTSCoreColors.gray; } } + [DisplayInfo(name = "Light Gray")] + public static BTSColor gray_light { get { return BTSCoreColors.gray_light; } } + [DisplayInfo(name = "Lighter Gray")] + public static BTSColor gray_lighter { get { return BTSCoreColors.gray_lighter; } } + [DisplayInfo(name = "Lightest Gray")] + public static BTSColor gray_lightest { get { return BTSCoreColors.gray_lightest; } } + } + + public static class VolSurfaceGraph + { + [DisplayInfo(name = "Vol Surface Curve")] + public static BTSColor main_curve { get { return BTSCoreColors.black; } } + [DisplayInfo(name = "Vol Surface Wing")] + public static BTSColor wing { get { return BTSCoreColors.gray; } } + [DisplayInfo(name = "Vol Surface Put Special")] + public static BTSColor put_special { get { return BTSCoreColors.blue; } } + [DisplayInfo(name = "Vol Surface ATM")] + public static BTSColor main_curve_atm { get { return BTSCoreColors.green; } } + [DisplayInfo(name = "Vol Surface Call Special")] + public static BTSColor call_special { get { return BTSCoreColors.red; } } + [DisplayInfo(name = "Vol Surface Put Implied Vol")] + public static BTSColor implied_put { get { return BTSCoreColors.blue_bright_light; } } + [DisplayInfo(name = "Vol Surface ATM Implied Vol")] + public static BTSColor implied_atm { get { return BTSCoreColors.black; } } + [DisplayInfo(name = "Vol Surface Call Implied Vol")] + public static BTSColor implied_call { get { return BTSCoreColors.red_light; } } + [DisplayInfo(name = "Vol Path")] + public static BTSColor vol_path { get { return BTSCoreColors.cyan_green_dark; } } + } + + public static class Heatmap + { + //public static BTSColor negative_diff { get { return Colors.CornflowerBlue; } } + //public static BTSColor no_diff { get { return Colors.White; } } + //public static BTSColor positive_diff { get { return Colors.MediumVioletRed; } } + + public static BTSColor negative_diff { get { return Color.FromRgb(155, 0, 16); } } + public static BTSColor no_diff { get { return Colors.White; } } + public static BTSColor positive_diff { get { return Color.FromRgb(0, 90, 50); } } + } + + // Style Guide Colors + public static Color brand_lightest { get { return UI.brand_lightest; } } + public static Brush brand_lightest_brush { get { return new SolidColorBrush(brand_lightest); } } + public static Color brand_lighter { get { return UI.brand_lighter; } } + public static Brush brand_lighter_brush { get { return new SolidColorBrush(brand_lighter); } } + public static Color brand_light { get { return UI.brand_light; } } + public static Brush brand_light_brush { get { return new SolidColorBrush(brand_light); } } + public static Color brand_info { get { return UI.brand_info; } } + public static Brush brand_info_brush { get { return new SolidColorBrush(brand_info); } } + public static Color brand_medium { get { return UI.brand_medium; } } + public static Brush brand_medium_brush { get { return new SolidColorBrush(brand_medium); } } + public static Color brand_primary { get { return UI.brand_primary; } } + public static Brush brand_primary_brush { get { return new SolidColorBrush(brand_primary); } } + public static Color brand_dark { get { return UI.brand_dark; } } + public static Brush brand_dark_brush { get { return new SolidColorBrush(brand_dark); } } + public static Color brand_darker { get { return UI.brand_darker; } } + public static Brush brand_darker_brush { get { return new SolidColorBrush(brand_darker); } } + public static Color brand_darkest { get { return UI.brand_darkest; } } + public static Brush brand_darkest_brush { get { return new SolidColorBrush(brand_darkest); } } + + public static Color success { get { return UI.success; } } + public static Brush success_brush { get { return new SolidColorBrush(success); } } + public static Color danger { get { return UI.danger; } } + public static Brush danger_brush { get { return new SolidColorBrush(danger); } } + public static Color warning { get { return UI.warning; } } + public static Brush warning_brush { get { return new BTSColor(191, 102, 0); } } + public static Color warning_dark { get { return UI.warning_dark; } } + public static Brush warning_dark_brush { get { return new SolidColorBrush(warning_dark); } } + public static Color warning_light { get { return UI.warning_light; } } + public static Brush warning_light_brush { get { return new SolidColorBrush(warning_light); } } + + public static Color text_default { get { return UI.default_text; } } + public static Brush text_default_brush { get { return new SolidColorBrush(text_default); } } + public static Color text_alternate { get { return UI.alternate_text; } } + public static Brush text_alternate_brush { get { return new SolidColorBrush(text_alternate); } } + public static Color text_alternate_dark { get { return (Color)BTSCoreColors.black; } } + public static Brush text_alternate_dark_brush { get { return new SolidColorBrush(text_alternate_dark); } } + + // Logo Colors + public static Color logo { get { return Color.FromRgb(0x00, 0x86, 0xbf); } } + public static Brush logo_brush { get { return new SolidColorBrush(logo); } } + public static Color logo_brown { get { return Color.FromRgb(56, 52, 49); } } + public static Brush logo_brown_brush { get { return new SolidColorBrush(logo_brown); } } + public static Color logo_gray { get { return Color.FromRgb(179, 179, 179); } } + public static Brush logo_gray_brush { get { return new SolidColorBrush(logo_gray); } } + + public static Color common_background { get { return UI.default_background; } } + public static Brush common_background_brush { get { return new SolidColorBrush(common_background); } } + + public static Color accent1 { get { return UI.accent_light; } } + public static Brush accent1_brush { get { return new SolidColorBrush(accent1); } } + + public static Color accent_dark { get { return UI.accent_dark; } } + public static Brush accent_dark_brush { get { return new SolidColorBrush(accent_dark); } } + public static Color accent_light { get { return UI.accent_light; } } + public static Brush accent_light_brush { get { return new SolidColorBrush(accent_light); } } + public static Brush accent_light_background_brush { get { Brush rv = accent_light_brush; rv.Opacity = 0.2; return rv; } } + + public static Brush form_border_brush { get { return new SolidColorBrush(UI.form_border); } } + + public static Color dialog_skirt { get { return UI.dialog_skirt; } } + public static Brush dialog_skirt_brush { get { return new SolidColorBrush(dialog_skirt); } } + + // Main form display colors + #region Main Form Colors + public static Color red_orange { get { return Color.FromRgb(0xde, 0x34, 0x29); } } + public static Color blue { get { return Color.FromRgb(0x16, 0x7e, 0xd3); } } + public static Brush blue_brush { get { return new SolidColorBrush(blue); } } + public static Color yellow { get { return Color.FromRgb(0xfd, 0xcb, 0x4a); } } + public static Brush yellow_brush { get { return new SolidColorBrush(yellow); } } + public static Color green { get { return Color.FromRgb(0x43, 0xa2, 0x3c); } } + public static Color orange { get { return Color.FromRgb(0xfc, 0x8b, 0x00); } } + public static Color pale_blue { get { return Color.FromRgb(0x2f, 0xb5, 0xe4); } } + public static Brush pale_blue_brush { get { return new SolidColorBrush(pale_blue); } } + public static Color red { get { return Color.FromRgb(0xc4, 0x12, 0x12); } } + public static Color pale_green { get { return Color.FromRgb(0x37, 0x7d, 0x35); } } + public static Color purple { get { return Color.FromRgb(0x81, 0x5f, 0x91); } } + public static Color teal { get { return Color.FromRgb(0x6d, 0xdb, 0xff); } } //"Win8" teal + public static Color olive { get { return Color.FromRgb(0x80, 0x80, 0x00); } } + + private static Color[] _colors = new Color[] { blue, red_orange, green, yellow, pale_blue, orange, red, pale_green, purple, olive }; + public static Color[] module_colors { get { return _colors; } } + #endregion + + } +} diff --git a/src/client/spark/uicore/BTSCoreColors.cs b/src/client/spark/uicore/BTSCoreColors.cs new file mode 100644 index 000000000..9258755d4 --- /dev/null +++ b/src/client/spark/uicore/BTSCoreColors.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace mbts.ui +{ + public static class BTSCoreColors + { + // Gray + public static BTSColor black = 0x00;// 000000 + public static BTSColor white = 0xff; // ffffff + + + public static BTSColor gray_8c = 0x8c; // 8c8c8c + public static BTSColor gray_dc = 0xdc; // dcdcdc + + public static BTSColor gray_darkest = 0x21; // 212121 + public static BTSColor gray_darker = 0x40;// 404040 + public static BTSColor gray_dark = 0x5e;// 5e5e5e + public static BTSColor gray = 0x80; // 808080 (replaces system Gray) + public static BTSColor gray_light = 0xa1; // a1a1a1 + public static BTSColor gray_lighter = 0xbf; // bfbfbf + public static BTSColor gray_lightest = 0xde; // dedede + public static BTSColor gray_lightest_light = 0xf5; // f5f5f5 (Replaces System Light Smoke) + + // Blue + public static BTSColor blue = new BTSColor(0x00, 0x00, 0xff); // 0000ff + + public static BTSColor base_blue = new BTSColor(0x41, 0x69, 0xaa); // 4169AA + + public static BTSColor blue_light_dark = new BTSColor(0x9a, 0xb1, 0xd6); //9ab1d6 + public static BTSColor blue_light_dark_saturated = new BTSColor(0x72, 0x98, 0xd6); //7298d6 + public static BTSColor blue_light = new BTSColor(0xc2, 0xd6, 0xf6); //c2d6f6 + public static BTSColor blue_light_light = new BTSColor(0xd4, 0xe1, 0xf6); //d4e1f6 + public static BTSColor blue_light_lighter = new BTSColor(0xe6, 0xef, 0xff); //e6efff + + public static BTSColor blue_light_alternate = new BTSColor(0xa6, 0xba, 0xff); //a6baff + public static BTSColor blue_light_alternate_light = new BTSColor(0xd9, 0xd9, 0xff); //d9d9ff + + public static BTSColor blue_pale_light = new BTSColor(0xf2, 0xf7, 0xff); //f2f7ff + + public static BTSColor blue_dark = new BTSColor(0x1a, 0x34, 0x5d); //1A345D + public static BTSColor blue_dark_light = new BTSColor(0x2e, 0x5b, 0xa3); //2e5ba3 + public static BTSColor blue_dark_lighter_pale = new BTSColor(0x63, 0x8a, 0xc7); //638ac7 + + public static BTSColor blue_bright_darkest = new BTSColor(0x29, 0x59, 0xa6); //2959a6 + public static BTSColor blue_bright_darker = new BTSColor(0x39, 0x6c, 0xbf); //396cbf + public static BTSColor blue_bright_dark = new BTSColor(0x55, 0x85, 0xd4); //5585d4 + public static BTSColor blue_bright = new BTSColor(0x5e, 0x98, 0xf6); //5E98F6 + public static BTSColor blue_bright_light_dark = new BTSColor(0x8f, 0xaf, 0xff); //8fbaff + public static BTSColor blue_bright_light = new BTSColor(0xa6, 0xc8, 0xff); //a6c8ff + public static BTSColor blue_bright_lighter = new BTSColor(0xd6, 0xe6, 0xff); //d6e6ff + public static BTSColor blue_bright_lightest = new BTSColor(0xeb, 0xf3, 0xff); //ebf3ff + + public static BTSColor blue_grey_dark = new BTSColor(0x3b, 0x46, 0x57); //3b4657 + public static BTSColor blue_grey = new BTSColor(0x7e, 0x9a, 0xb8); //7E94B8 + public static BTSColor blue_grey_light = new BTSColor(0xba, 0xbf, 0xc7); //babfc7 + public static BTSColor blue_grey_lighter = new BTSColor(0xd1, 0xd7, 0xe0); //d1d7e0 + public static BTSColor blue_grey_lightest = new BTSColor(0xde, 0xde, 0xe8); //dedee8 + + + + // Cyan + public static BTSColor cyan_green_darker = new BTSColor(0x0a, 0x79, 0x66); //0A7966 + public static BTSColor cyan_green_dark = new BTSColor(0x1b, 0x96, 0x81); //1B9681 + public static BTSColor cyan_green = new BTSColor(0x34, 0xa3, 0x90); //34A390 + public static BTSColor cyan_green_light = new BTSColor(0x57, 0xbe, 0xad); //57BEAD + public static BTSColor cyan_green_lighter = new BTSColor(0x88, 0xd9, 0xcb); //88D9CB + public static BTSColor cyan_green_lightest = new BTSColor(0xac, 0xe8, 0xde); //ace8de + + // Green + public static BTSColor unrelated_green_for_theos_and_deltas_and_nothing_else = new BTSColor(0xd1, 0xff, 0xd1); // d1ffd1 + + public static BTSColor green_mid = new BTSColor(0x70, 0xa3, 0x52); //70a352 + + public static BTSColor green_light_dark = new BTSColor(0x88, 0xa3, 0x53); //88a352 + public static BTSColor green_light_saturated = new BTSColor(0xb8, 0xff, 0x2e); //b8ff2e + public static BTSColor green_light = new BTSColor(0xd4, 0xff, 0x80); //d4ff80 + public static BTSColor green_light_light_saturated = new BTSColor(0xd7, 0xff, 0x8a); //d7ff8a + public static BTSColor green_light_light = new BTSColor(0xeb, 0xff, 0xc4); //ebffc4 + + public static BTSColor green_dark = new BTSColor(0x61, 0x77, 0x22); //617722 + + public static BTSColor green_pale_dark = new BTSColor(0xac, 0xcf, 0x68); //accf68 + + public static BTSColor green_bright_darker = new BTSColor(0x51, 0x87, 0x00); //518700 + public static BTSColor green_bright_dark = new BTSColor(0x60, 0xa1, 0x00); //60a100 + public static BTSColor green_bright = new BTSColor(0x7c, 0xcf, 0x00); //7ccf00 + public static BTSColor green_bright_light = new BTSColor(0xdf, 0xf2, 0xc2); //dff2c2 + + public static BTSColor green = new BTSColor(0x00, 0xc0, 0x00); //00c000 + public static BTSColor green_p_light = new BTSColor(0x99, 0xee, 0x90); //99ee90 + + public static BTSColor green_dark_light = new BTSColor(0x25, 0x5d, 0x25); //255d25 + + //Red + public static BTSColor red_lighter = new BTSColor(0xff, 0xd9, 0xd9); //ffd9d9 + public static BTSColor red_light = new BTSColor(0xff, 0xa6, 0xa6); //ffa6a6 + public static BTSColor red = new BTSColor(0xff, 0x00, 0x00); // ff0000 + public static BTSColor red_dark = new BTSColor(0xc0, 0x00, 0x00); // c00000 + + public static BTSColor red_pale_dark = new BTSColor(0xe6, 0x68, 0x55); //e66855 + public static BTSColor red_pale = new BTSColor(0xff, 0xbf, 0xb5); // ffbfb5 + + public static BTSColor red_light_dark = new BTSColor(0xd6, 0x9a, 0x9a); //d69a9a + public static BTSColor red_light_dark_saturated = new BTSColor(0xd6, 0x7e, 0x7e); //d67e7e + + // Yellow + public static BTSColor yellow_bright = new BTSColor(0xee, 0xff, 0x00); //eeff00 + + public static BTSColor yellow_lightest_lightest = new BTSColor(0xff, 0xfc, 0xf2); //fffcf2 + public static BTSColor yellow_lightest = new BTSColor(0xff, 0xec, 0xa0); //FFECA0 + public static BTSColor yellow_lighter = new BTSColor(0xff, 0xe2, 0x74); //FFE474 + public static BTSColor yellow_light = new BTSColor(0xff, 0xdd, 0x52); //FFDD52 + public static BTSColor yellow = new BTSColor(0xed, 0xc7, 0x2a); //EDC72A + + // Orange + public static BTSColor orange_yellow = new BTSColor(0xff, 0xbc, 0x46); //FFBC46 + + public static BTSColor orange_lightest = new BTSColor(0xff, 0xac, 0x74); //FFAC74 + public static BTSColor orange_light = new BTSColor(0xff, 0x98, 0x52); //FF9852 + public static BTSColor orange = new BTSColor(0xed, 0x79, 0x2a); //ED792A + public static BTSColor orange_dark = new BTSColor(0xc0, 0x56, 0x0f); //C0560F + } +} diff --git a/src/client/spark/uicore/BTSFont.cs b/src/client/spark/uicore/BTSFont.cs new file mode 100644 index 000000000..aa3bff744 --- /dev/null +++ b/src/client/spark/uicore/BTSFont.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace mbts.ui +{ + partial class SettingsFont + { + public double size_in_points => Size / 96 * 72; + + public BTSFontWeight weight => Bold ? System.Windows.FontWeights.Bold : System.Windows.FontWeights.Regular; + + public BTSFontStyle style + { + get => new BTSFontStyle() { italic = this.Italic, bold = this.Bold, strikeout = this.Strikeout, oblique = this.Oblique, underline = this.Underline }; + private set + { + Italic = value.italic; + Bold = value.bold; + Oblique = value.oblique; + Underline = value.underline; + Strikeout = value.strikeout; + } + } + + public static explicit operator System.Windows.Media.FontFamily(SettingsFont bts_font) => new System.Windows.Media.FontFamily(bts_font.Family); + + public static explicit operator System.Drawing.FontFamily(SettingsFont bts_font) => new System.Drawing.FontFamily(bts_font.Family); + + + public static explicit operator System.Drawing.Font(SettingsFont bts_font) + { + return new System.Drawing.Font(bts_font.Family, bts_font.Size, + (bts_font.Bold ? System.Drawing.FontStyle.Bold : System.Drawing.FontStyle.Regular) | + (bts_font.Italic ? System.Drawing.FontStyle.Italic : System.Drawing.FontStyle.Regular) | + (bts_font.Underline ? System.Drawing.FontStyle.Underline: System.Drawing.FontStyle.Regular) | + (bts_font.Strikeout ? System.Drawing.FontStyle.Strikeout : System.Drawing.FontStyle.Regular) + ); + } + + public static explicit operator SettingsFont(System.Windows.Media.FontFamily media_font_family) => new SettingsFont{ Family = media_font_family.FamilyNames.Values.ElementAt(0) }; + + public static explicit operator SettingsFont(System.Drawing.FontFamily font_family) => new SettingsFont { Family = font_family.Name }; + + public static explicit operator SettingsFont(System.Drawing.Font drawing_font) + { + return new SettingsFont + { + Family = drawing_font.Name, + Size = drawing_font.Size, + Bold = drawing_font.Bold, + Italic = drawing_font.Italic, + Strikeout = drawing_font.Strikeout, + Underline = drawing_font.Underline + }; + } + + } + +} diff --git a/src/client/spark/uicore/BTSFontFamily.cs b/src/client/spark/uicore/BTSFontFamily.cs new file mode 100644 index 000000000..7aca6d436 --- /dev/null +++ b/src/client/spark/uicore/BTSFontFamily.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace mbts.ui +{ + [ProtoBuf.ProtoContract()] + [Serializable] + public class BTSFontFamily + { + [ProtoBuf.ProtoMember(1)] + public string name { get; set; } + + public override string ToString() { return name; } + + public static implicit operator System.Windows.Media.FontFamily(BTSFontFamily bts_font_family) { + object obj = new System.Windows.Media.FontFamilyConverter().ConvertFromString(bts_font_family.name); + return obj as System.Windows.Media.FontFamily; + } + + public static implicit operator System.Drawing.FontFamily(BTSFontFamily bts_font_family) { + return bts_font_family != null ? new System.Drawing.FontFamily(bts_font_family.name) : null; + } + + public static implicit operator BTSFontFamily(System.Windows.Media.FontFamily swm_font_family) { + return swm_font_family != null ? new BTSFontFamily { name = swm_font_family.FamilyNames.Values.ElementAt(0) } : null; + } + } +} diff --git a/src/client/spark/uicore/BTSFontStyle.cs b/src/client/spark/uicore/BTSFontStyle.cs new file mode 100644 index 000000000..e6570ebc5 --- /dev/null +++ b/src/client/spark/uicore/BTSFontStyle.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + public class BTSFontStyle + { + public bool bold { get; set; } + public bool italic { get; set; } + public bool oblique { get; set; } + public bool underline { get; set; } + public bool strikeout { get; set; } + + + public static explicit operator System.Drawing.FontStyle(BTSFontStyle bts_font_style) + { + return (bts_font_style.bold ? System.Drawing.FontStyle.Bold : System.Drawing.FontStyle.Regular) | + ((bts_font_style.italic | bts_font_style.oblique) ? System.Drawing.FontStyle.Italic : System.Drawing.FontStyle.Regular) | + (bts_font_style.underline ? System.Drawing.FontStyle.Underline : System.Drawing.FontStyle.Regular) | + (bts_font_style.strikeout ? System.Drawing.FontStyle.Strikeout : System.Drawing.FontStyle.Regular); + + } + + public static explicit operator System.Windows.FontStyle(BTSFontStyle bts_font_style) + { + if (bts_font_style.italic) + return System.Windows.FontStyles.Italic; + else if (bts_font_style.oblique) + return System.Windows.FontStyles.Oblique; + else + return System.Windows.FontStyles.Normal; + + } + + public static explicit operator BTSFontStyle (System.Windows.FontStyle font_style) + { + if(font_style == System.Windows.FontStyles.Italic) + return new BTSFontStyle() { italic = true }; + else if (font_style == System.Windows.FontStyles.Oblique) + return new BTSFontStyle() { oblique = true }; + else + return new BTSFontStyle() ; + + } + + public static explicit operator BTSFontStyle(System.Drawing.FontStyle font_style) + { + var ret = new BTSFontStyle(); + + ret.bold = font_style.HasFlag(System.Drawing.FontStyle.Bold); + ret.italic = font_style.HasFlag(System.Drawing.FontStyle.Italic); + ret.underline = font_style.HasFlag(System.Drawing.FontStyle.Underline); + ret.strikeout = font_style.HasFlag(System.Drawing.FontStyle.Strikeout); + + return ret; + + + } + + } +} diff --git a/src/client/spark/uicore/BTSFontWeight.cs b/src/client/spark/uicore/BTSFontWeight.cs new file mode 100644 index 000000000..211602620 --- /dev/null +++ b/src/client/spark/uicore/BTSFontWeight.cs @@ -0,0 +1,28 @@ +using System; + +namespace mbts.ui +{ + [ProtoBuf.ProtoContract()] + [Serializable] + public class BTSFontWeight + { + [ProtoBuf.ProtoMember(1)] + public int weight { get; set; } + + public static implicit operator System.Windows.FontWeight(BTSFontWeight bts_font_weight) { + return bts_font_weight != null ? System.Windows.FontWeight.FromOpenTypeWeight(bts_font_weight.weight) : System.Windows.FontWeights.Regular; + } + + public static implicit operator System.Drawing.FontStyle(BTSFontWeight bts_font_weight) { + return bts_font_weight != null && bts_font_weight.weight == System.Windows.FontWeights.Bold.ToOpenTypeWeight() ? System.Drawing.FontStyle.Bold : System.Drawing.FontStyle.Regular; + } + + public static implicit operator BTSFontWeight(System.Windows.FontWeight sw_font_weight) { + return new BTSFontWeight { weight = sw_font_weight.ToOpenTypeWeight() }; + } + + public static implicit operator BTSFontWeight(System.Drawing.FontStyle sd_font_style) { + return new BTSFontWeight { weight = sd_font_style == System.Drawing.FontStyle.Bold ? System.Windows.FontWeights.Bold.ToOpenTypeWeight() : System.Windows.FontWeights.Regular.ToOpenTypeWeight() }; + } + } +} diff --git a/src/client/spark/uicore/Exceptions/ColorNotFoundException.cs b/src/client/spark/uicore/Exceptions/ColorNotFoundException.cs new file mode 100644 index 000000000..0bd41974d --- /dev/null +++ b/src/client/spark/uicore/Exceptions/ColorNotFoundException.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + class ColorNotFoundException : Exception + { + public ColorNotFoundException() : base("The color is not defined in BTSColors") { } + public ColorNotFoundException(String message) : base(message) { } + public ColorNotFoundException(String message, Exception inner) : base(message, inner) { } + } +} diff --git a/src/client/spark/uicore/Exceptions/DebugException.cs b/src/client/spark/uicore/Exceptions/DebugException.cs new file mode 100644 index 000000000..55d46b62c --- /dev/null +++ b/src/client/spark/uicore/Exceptions/DebugException.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + public class DebugException : Exception + { + public DebugException() { } + public DebugException(string message) : base(message) { } + public DebugException(string message, Exception inner) : base(message, inner) { } + } +} diff --git a/src/client/spark/uicore/Images/Cursors/Grab.cur b/src/client/spark/uicore/Images/Cursors/Grab.cur new file mode 100644 index 000000000..fba3ddc80 Binary files /dev/null and b/src/client/spark/uicore/Images/Cursors/Grab.cur differ diff --git a/src/client/spark/uicore/Images/Cursors/Grabbing.cur b/src/client/spark/uicore/Images/Cursors/Grabbing.cur new file mode 100644 index 000000000..41aaa62a5 Binary files /dev/null and b/src/client/spark/uicore/Images/Cursors/Grabbing.cur differ diff --git a/src/client/spark/uicore/Images/Icons.cs b/src/client/spark/uicore/Images/Icons.cs new file mode 100644 index 000000000..b57c72997 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace mbts.ui +{ + public class Icons + { + static readonly string base_uri = "pack://application:,,,/bts_uicore;component/Images/Icons/"; + private static ResourceDictionary _resources = (ResourceDictionary)Application.LoadComponent(new Uri("/bts_uicore;component/Images/Vector/Icons.xaml", UriKind.RelativeOrAbsolute)); + + private static Uri uri(string filename) { + return new Uri(base_uri + filename); + } + + [Obsolete("Please only add new vector icons using icons.xaml")] + private static ImageSource load_image(string filename) { + return new BitmapImage(uri(filename)); + } + +#pragma warning disable CS0618 // Type or member is obsolete + public static ImageSource Logo { get { return load_image("logo.ico"); } } + public static ImageSource Admin { get { return (DrawingImage)_resources["Admin"]; } } + public static ImageSource Analytics { get { return (DrawingImage)_resources["Analytics"]; } } + public static ImageSource Orders { get { return (DrawingImage)_resources["Orders"]; } } + public static ImageSource Sheets { get { return (DrawingImage)_resources["Sheets"]; } } + public static ImageSource Trades { get { return (DrawingImage)_resources["Trades"]; } } + public static ImageSource Depth { get { return (DrawingImage)_resources["Depth"]; } } + public static ImageSource SheetsRed { get { return load_image("SheetsRed.png"); } } + public static ImageSource SheetsGreen { get { return load_image("SheetsGreen.png"); } } + public static ImageSource Spreads { get { return (DrawingImage)_resources["Spreads"]; } } + public static ImageSource BlueSpreads { get { return load_image("BlueSpread.ico"); } } + public static ImageSource MMTN { get { return load_image("mmtn.ico"); } } + public static ImageSource Reports { get { return (DrawingImage)_resources["Reports"]; } } + public static ImageSource Risk { get { return (DrawingImage)_resources["Risk"]; } } + public static ImageSource Eye { get { return (DrawingImage)_resources["Eye"]; } } + public static ImageSource Coins { get { return (DrawingImage)_resources["Coins"]; } } + + + public static ImageSource Loading { get { return load_image("loading.ico"); } } + public static ImageSource DataCopy { get { return load_image("DataCopy.ico"); } } + public static ImageSource Import { get { return load_image("Import.ico"); } } + public static ImageSource Refresh { get { return load_image("Refresh.png"); } } + public static ImageSource FavoriteWindow { get { return load_image("FavoriteWindow.png"); } } + public static ImageSource RubberStamp { get { return load_image("RubberStamp.png"); } } + public static ImageSource Ticket { get { return load_image("Ticket.png"); } } + public static ImageSource Date { get { return load_image("Date.png"); } } + public static ImageSource RFQArrows { get { return load_image("RFQArrows.png"); } } + + public static ImageSource Cube3d { get { return (DrawingImage)_resources["Cube"]; /*return load_image("Cube-Molecule.png");*/ } } + public static ImageSource Algo { get { return Cube3d; } } + public static ImageSource Quote { get { return Math; } } + public static ImageSource Math { get { return (DrawingImage)_resources["Surface"]; } } + public static ImageSource Abacus { get { return load_image("Abacus.png"); } } + + public static ImageSource Add_New { get { return load_image("Add-New.png"); } } + public static ImageSource Delete { get { return load_image("Delete.png"); } } + public static ImageSource Up_Arrow { get { return load_image("Arrowhead-Up.png"); } } + public static ImageSource Down_Arrow { get { return load_image("Arrowhead-Down.png"); } } + public static ImageSource Zoom_In { get { return load_image("Zoom-In.png"); } } + public static ImageSource Zoom_Out { get { return load_image("Zoom-Out.png"); } } + public static ImageSource InsertionArrow { get { return load_image("InsertionArrow.png"); } } +#pragma warning restore CS0618 + + // Vector icons + public static ImageSource Favorites { get { return Favorites_Gold; } } + public static ImageSource Favorites_Gold { get { return (DrawingImage)_resources["FavoritesGold"]; } } + public static ImageSource Favorites_White { get { return (DrawingImage)_resources["FavoritesWhite"]; } } + public static ImageSource Window { get { return (DrawingImage)_resources["Window"]; } } + public static ImageSource ActiveWindow { get { return (DrawingImage)_resources["ActiveWindow"]; } } + public static ImageSource Trash { get { return (DrawingImage)_resources["Trash"]; } } + public static ImageSource Crucible { get { return (DrawingImage)_resources["Crucible"]; } } + + public static ImageSource Accounting { get { return (DrawingImage)_resources["Accounting"]; } } + public static ImageSource CancelOrders { get { return (DrawingImage)_resources["CancelOrders"]; } } + public static ImageSource Clock { get { return (DrawingImage)_resources["Clock"]; } } + public static ImageSource Display { get { return (DrawingImage)_resources["Display"]; } } + public static ImageSource Payment { get { return (DrawingImage)_resources["Payment"]; } } + public static ImageSource Target { get { return (DrawingImage)_resources["Target"]; } } + public static ImageSource Wrench { get { return (DrawingImage)_resources["Wrench"]; } } + } +} \ No newline at end of file diff --git a/src/client/spark/uicore/Images/Icons/Abacus.png b/src/client/spark/uicore/Images/Icons/Abacus.png new file mode 100644 index 000000000..da05e09c4 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Abacus.png differ diff --git a/src/client/spark/uicore/Images/Icons/Add-New.png b/src/client/spark/uicore/Images/Icons/Add-New.png new file mode 100644 index 000000000..eae797d44 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Add-New.png differ diff --git a/src/client/spark/uicore/Images/Icons/Admin.ico b/src/client/spark/uicore/Images/Icons/Admin.ico new file mode 100644 index 000000000..5ee2378d0 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Admin.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Admin.png b/src/client/spark/uicore/Images/Icons/Admin.png new file mode 100644 index 000000000..3368d48bb Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Admin.png differ diff --git a/src/client/spark/uicore/Images/Icons/Admin.svg b/src/client/spark/uicore/Images/Icons/Admin.svg new file mode 100644 index 000000000..e3240f5cf --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Admin.svg @@ -0,0 +1,92 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/Analytics.ico b/src/client/spark/uicore/Images/Icons/Analytics.ico new file mode 100644 index 000000000..7c7e71e28 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Analytics.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Analytics.png b/src/client/spark/uicore/Images/Icons/Analytics.png new file mode 100644 index 000000000..7611d45f6 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Analytics.png differ diff --git a/src/client/spark/uicore/Images/Icons/Analytics.svg b/src/client/spark/uicore/Images/Icons/Analytics.svg new file mode 100644 index 000000000..b5ecfe94f --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Analytics.svg @@ -0,0 +1,96 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/Arrow-Diagonal-Up-Right.png b/src/client/spark/uicore/Images/Icons/Arrow-Diagonal-Up-Right.png new file mode 100644 index 000000000..962a1e073 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Arrow-Diagonal-Up-Right.png differ diff --git a/src/client/spark/uicore/Images/Icons/Arrowhead-Down.png b/src/client/spark/uicore/Images/Icons/Arrowhead-Down.png new file mode 100644 index 000000000..940755ba4 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Arrowhead-Down.png differ diff --git a/src/client/spark/uicore/Images/Icons/Arrowhead-Up.png b/src/client/spark/uicore/Images/Icons/Arrowhead-Up.png new file mode 100644 index 000000000..9e7cbe3b3 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Arrowhead-Up.png differ diff --git a/src/client/spark/uicore/Images/Icons/BTS.png b/src/client/spark/uicore/Images/Icons/BTS.png new file mode 100644 index 000000000..c063eee7c Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/BTS.png differ diff --git a/src/client/spark/uicore/Images/Icons/BlueSpread.ico b/src/client/spark/uicore/Images/Icons/BlueSpread.ico new file mode 100644 index 000000000..11c81ad66 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/BlueSpread.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Book-Settings.png b/src/client/spark/uicore/Images/Icons/Book-Settings.png new file mode 100644 index 000000000..9922f2159 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Book-Settings.png differ diff --git a/src/client/spark/uicore/Images/Icons/Cube-Molecule.png b/src/client/spark/uicore/Images/Icons/Cube-Molecule.png new file mode 100644 index 000000000..dd0356eba Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Cube-Molecule.png differ diff --git a/src/client/spark/uicore/Images/Icons/DataCopy.ico b/src/client/spark/uicore/Images/Icons/DataCopy.ico new file mode 100644 index 000000000..3b6762539 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/DataCopy.ico differ diff --git a/src/client/spark/uicore/Images/Icons/DataCopy.svg b/src/client/spark/uicore/Images/Icons/DataCopy.svg new file mode 100644 index 000000000..ed16314a8 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/DataCopy.svg @@ -0,0 +1,96 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/Date.png b/src/client/spark/uicore/Images/Icons/Date.png new file mode 100644 index 000000000..d3af08bd7 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Date.png differ diff --git a/src/client/spark/uicore/Images/Icons/Delete.png b/src/client/spark/uicore/Images/Icons/Delete.png new file mode 100644 index 000000000..f3913c77c Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Delete.png differ diff --git a/src/client/spark/uicore/Images/Icons/Depth.ico b/src/client/spark/uicore/Images/Icons/Depth.ico new file mode 100644 index 000000000..648c98cd0 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Depth.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Depth.png b/src/client/spark/uicore/Images/Icons/Depth.png new file mode 100644 index 000000000..2420b4c76 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Depth.png differ diff --git a/src/client/spark/uicore/Images/Icons/Depth.svg b/src/client/spark/uicore/Images/Icons/Depth.svg new file mode 100644 index 000000000..2eaebc87b --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Depth.svg @@ -0,0 +1,96 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/FavoriteWindow.png b/src/client/spark/uicore/Images/Icons/FavoriteWindow.png new file mode 100644 index 000000000..bc27e4549 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/FavoriteWindow.png differ diff --git a/src/client/spark/uicore/Images/Icons/Import.ico b/src/client/spark/uicore/Images/Icons/Import.ico new file mode 100644 index 000000000..9f444d43a Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Import.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Import.svg b/src/client/spark/uicore/Images/Icons/Import.svg new file mode 100644 index 000000000..4d0532efb --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Import.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/InsertionArrow.png b/src/client/spark/uicore/Images/Icons/InsertionArrow.png new file mode 100644 index 000000000..88555ece3 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/InsertionArrow.png differ diff --git a/src/client/spark/uicore/Images/Icons/Mathematics.png b/src/client/spark/uicore/Images/Icons/Mathematics.png new file mode 100644 index 000000000..49a4638fa Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Mathematics.png differ diff --git a/src/client/spark/uicore/Images/Icons/Orders.ico b/src/client/spark/uicore/Images/Icons/Orders.ico new file mode 100644 index 000000000..5848d398e Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Orders.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Orders.png b/src/client/spark/uicore/Images/Icons/Orders.png new file mode 100644 index 000000000..34df98777 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Orders.png differ diff --git a/src/client/spark/uicore/Images/Icons/Orders.svg b/src/client/spark/uicore/Images/Icons/Orders.svg new file mode 100644 index 000000000..0ff926269 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Orders.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/Quotation-Marks.png b/src/client/spark/uicore/Images/Icons/Quotation-Marks.png new file mode 100644 index 000000000..167d11a87 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Quotation-Marks.png differ diff --git a/src/client/spark/uicore/Images/Icons/RFQArrows.png b/src/client/spark/uicore/Images/Icons/RFQArrows.png new file mode 100644 index 000000000..8b2cd3a4a Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/RFQArrows.png differ diff --git a/src/client/spark/uicore/Images/Icons/Refresh.ico b/src/client/spark/uicore/Images/Icons/Refresh.ico new file mode 100644 index 000000000..bdb829f3f Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Refresh.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Refresh.svg b/src/client/spark/uicore/Images/Icons/Refresh.svg new file mode 100644 index 000000000..583979eee --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Refresh.svg @@ -0,0 +1,96 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/RubberStamp.png b/src/client/spark/uicore/Images/Icons/RubberStamp.png new file mode 100644 index 000000000..81f8288cb Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/RubberStamp.png differ diff --git a/src/client/spark/uicore/Images/Icons/Sheets.ico b/src/client/spark/uicore/Images/Icons/Sheets.ico new file mode 100644 index 000000000..27df72ff7 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Sheets.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Sheets.png b/src/client/spark/uicore/Images/Icons/Sheets.png new file mode 100644 index 000000000..b32aa462c Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Sheets.png differ diff --git a/src/client/spark/uicore/Images/Icons/Sheets.svg b/src/client/spark/uicore/Images/Icons/Sheets.svg new file mode 100644 index 000000000..196ed186c --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Sheets.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/SheetsGreen.png b/src/client/spark/uicore/Images/Icons/SheetsGreen.png new file mode 100644 index 000000000..ec975503b Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/SheetsGreen.png differ diff --git a/src/client/spark/uicore/Images/Icons/SheetsRed.png b/src/client/spark/uicore/Images/Icons/SheetsRed.png new file mode 100644 index 000000000..8c20c6e09 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/SheetsRed.png differ diff --git a/src/client/spark/uicore/Images/Icons/Spread.ico b/src/client/spark/uicore/Images/Icons/Spread.ico new file mode 100644 index 000000000..2e3c3bd55 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Spread.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Ticket.png b/src/client/spark/uicore/Images/Icons/Ticket.png new file mode 100644 index 000000000..edd34a659 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Ticket.png differ diff --git a/src/client/spark/uicore/Images/Icons/Trades.ico b/src/client/spark/uicore/Images/Icons/Trades.ico new file mode 100644 index 000000000..2e08bc65f Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Trades.ico differ diff --git a/src/client/spark/uicore/Images/Icons/Trades.png b/src/client/spark/uicore/Images/Icons/Trades.png new file mode 100644 index 000000000..57c2e656d Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Trades.png differ diff --git a/src/client/spark/uicore/Images/Icons/Trades.svg b/src/client/spark/uicore/Images/Icons/Trades.svg new file mode 100644 index 000000000..8c36d8442 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/Trades.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/Window.png b/src/client/spark/uicore/Images/Icons/Window.png new file mode 100644 index 000000000..b5b2ea304 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Window.png differ diff --git a/src/client/spark/uicore/Images/Icons/Zoom-In.png b/src/client/spark/uicore/Images/Icons/Zoom-In.png new file mode 100644 index 000000000..b58f04958 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Zoom-In.png differ diff --git a/src/client/spark/uicore/Images/Icons/Zoom-Out.png b/src/client/spark/uicore/Images/Icons/Zoom-Out.png new file mode 100644 index 000000000..f8a4f4cd5 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/Zoom-Out.png differ diff --git a/src/client/spark/uicore/Images/Icons/eye.ico b/src/client/spark/uicore/Images/Icons/eye.ico new file mode 100644 index 000000000..8248e2e57 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/eye.ico differ diff --git a/src/client/spark/uicore/Images/Icons/eye.png b/src/client/spark/uicore/Images/Icons/eye.png new file mode 100644 index 000000000..867b4d36e Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/eye.png differ diff --git a/src/client/spark/uicore/Images/Icons/eye.svg b/src/client/spark/uicore/Images/Icons/eye.svg new file mode 100644 index 000000000..4ee9e51a3 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/eye.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/logo.ico b/src/client/spark/uicore/Images/Icons/logo.ico new file mode 100644 index 000000000..dd7444fe3 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/logo.ico differ diff --git a/src/client/spark/uicore/Images/Icons/mmtn.ico b/src/client/spark/uicore/Images/Icons/mmtn.ico new file mode 100644 index 000000000..4b20b43d8 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/mmtn.ico differ diff --git a/src/client/spark/uicore/Images/Icons/refresh.png b/src/client/spark/uicore/Images/Icons/refresh.png new file mode 100644 index 000000000..dc673d690 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/refresh.png differ diff --git a/src/client/spark/uicore/Images/Icons/reports.ico b/src/client/spark/uicore/Images/Icons/reports.ico new file mode 100644 index 000000000..6cc5dab3e Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/reports.ico differ diff --git a/src/client/spark/uicore/Images/Icons/reports.png b/src/client/spark/uicore/Images/Icons/reports.png new file mode 100644 index 000000000..5bb0e2982 Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/reports.png differ diff --git a/src/client/spark/uicore/Images/Icons/reports.svg b/src/client/spark/uicore/Images/Icons/reports.svg new file mode 100644 index 000000000..59ea51771 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/reports.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/risk.ico b/src/client/spark/uicore/Images/Icons/risk.ico new file mode 100644 index 000000000..2acb090fa Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/risk.ico differ diff --git a/src/client/spark/uicore/Images/Icons/risk.png b/src/client/spark/uicore/Images/Icons/risk.png new file mode 100644 index 000000000..a8b00b4df Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/risk.png differ diff --git a/src/client/spark/uicore/Images/Icons/risk.svg b/src/client/spark/uicore/Images/Icons/risk.svg new file mode 100644 index 000000000..e24d457f4 --- /dev/null +++ b/src/client/spark/uicore/Images/Icons/risk.svg @@ -0,0 +1,100 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Images/Icons/spread.png b/src/client/spark/uicore/Images/Icons/spread.png new file mode 100644 index 000000000..0cd5f7d4c Binary files /dev/null and b/src/client/spark/uicore/Images/Icons/spread.png differ diff --git a/src/client/spark/uicore/Images/Vector/Icons.xaml b/src/client/spark/uicore/Images/Vector/Icons.xaml new file mode 100644 index 000000000..8c35ce15a --- /dev/null +++ b/src/client/spark/uicore/Images/Vector/Icons.xaml @@ -0,0 +1,386 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/uicore/NativeMethods/BTSNativeMethods.cs b/src/client/spark/uicore/NativeMethods/BTSNativeMethods.cs new file mode 100644 index 000000000..4d0a1bd9a --- /dev/null +++ b/src/client/spark/uicore/NativeMethods/BTSNativeMethods.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; + +namespace mbts.ui.native +{ + public static class BTSUINativeMethods + { + [DllImport("bts_nview")] + public static extern void enable_limits(); + + [DllImport("bts_nview", CharSet = CharSet.Unicode)] + public static extern void set_window_app_id(IntPtr hwnd, string stack_id); + } +} diff --git a/src/client/spark/uicore/NativeMethods/HT.cs b/src/client/spark/uicore/NativeMethods/HT.cs new file mode 100644 index 000000000..32df388de --- /dev/null +++ b/src/client/spark/uicore/NativeMethods/HT.cs @@ -0,0 +1,36 @@ + +namespace mbts.ui.native +{ + public enum HT : int + { + ERROR = (-2), + TRANSPARENT = (-1), + NOWHERE = 0, + CLIENT = 1, + CAPTION = 2, + SYSMENU = 3, + GROWBOX = 4, + SIZE = GROWBOX, + MENU = 5, + HSCROLL = 6, + VSCROLL = 7, + MINBUTTON = 8, + MAXBUTTON = 9, + LEFT = 10, + RIGHT = 11, + TOP = 12, + TOPLEFT = 13, + TOPRIGHT = 14, + BOTTOM = 15, + BOTTOMLEFT = 16, + BOTTOMRIGHT = 17, + BORDER = 18, + REDUCE = MINBUTTON, + ZOOM = MAXBUTTON, +// SIZEFIRST = LEFT, +// SIZELAST = BOTTOMRIGHT, + OBJECT = 19, + CLOSE = 20, + HELP = 21, + } +} diff --git a/src/client/spark/uicore/NativeMethods/NativeMethods.cs b/src/client/spark/uicore/NativeMethods/NativeMethods.cs new file mode 100644 index 000000000..c16afab84 --- /dev/null +++ b/src/client/spark/uicore/NativeMethods/NativeMethods.cs @@ -0,0 +1,599 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Runtime.InteropServices; +using System.Windows; + +namespace mbts.ui.native +{ + public static class NativeMethods + { + [DllImport("user32.dll")] + public static extern bool PostThreadMessage(int threadid, uint msg, IntPtr wparam, IntPtr lparam); + + [DllImport("user32.dll")] + public static extern bool GetMessage(ref MSG msg, IntPtr hwnd, uint filter_mind, uint filter_max); + + [DllImport("user32.dll")] + public static extern bool DispatchMessage(ref MSG msg); + + [DllImport("user32.dll")] + public static extern bool TranslateMessage(ref MSG msg); + + #region Windows Message Loop Stuff + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, WM Msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32")] + public static extern IntPtr SendNotifyMessage(IntPtr hwnd, WM msg, Int64 wparam, Int64 lparam); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr PostMessage(IntPtr hWnd, WM Msg, IntPtr wParam, IntPtr lParam); + + [DllImport("kernel32.dll")] + public static extern bool AllocConsole(); + + public delegate IntPtr WndProcDelegate(IntPtr hwnd, uint msg, IntPtr wparam, IntPtr lparam); + + [DllImport("user32.dll")] + public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, GWL nIndex, WndProcDelegate dwNewLong); + + [DllImport("user32.dll")] + public static extern IntPtr SetWindowLongPtr(IntPtr hwnd, GWL index, WS_EX style); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll")] + public static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + + public delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr SetWindowsHookEx(HookType hookType, IntPtr lpfn, IntPtr hMod, uint dwThreadId); + + [DllImport("user32.dll", SetLastError = true)] + public static extern bool UnhookWindowsHookEx(IntPtr hhook); + + [DllImport("user32.dll", SetLastError = true)] + public static extern IntPtr CallNextHookEx(IntPtr hhk, int code, IntPtr wparam, IntPtr lparam); + + [StructLayout(LayoutKind.Sequential)] + public struct WINDOWPOS + { + public IntPtr hwnd; + public IntPtr hwndInsertAfter; + public int x; + public int y; + public int cx; + public int cy; + public int flags; + + public override string ToString() { + return "{0},{1} {2},{3}".fmt(x, y, cx, cy); + } + } + + [DllImport("kernel32.dll")] + public static extern uint GetCurrentThreadId(); + + #endregion + + #region Window Flashing API Stuff + + private const UInt32 FLASHW_STOP = 0; //Stop flashing. The system restores the window to its original state. + private const UInt32 FLASHW_CAPTION = 1; //Flash the window caption. + private const UInt32 FLASHW_TRAY = 2; //Flash the taskbar button. + private const UInt32 FLASHW_ALL = 3; //Flash both the window caption and taskbar button. + private const UInt32 FLASHW_TIMER = 4; //Flash continuously, until the FLASHW_STOP flag is set. + private const UInt32 FLASHW_TIMERNOFG = 12; //Flash continuously until the window comes to the foreground. + + [StructLayout(LayoutKind.Sequential)] + private struct FLASHWINFO + { + public UInt32 cbSize; //The size of the structure in bytes. + public IntPtr hwnd; //A Handle to the Window to be Flashed. The window can be either opened or minimized. + public UInt32 dwFlags; //The Flash Status. + public UInt32 uCount; // number of times to flash the window + public UInt32 dwTimeout; //The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate. + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool FlashWindowEx(ref FLASHWINFO pwfi); + + public static void FlashWindow(IntPtr hwnd, uint count = UInt32.MaxValue) + { + FLASHWINFO fwi = new FLASHWINFO() + { + hwnd = hwnd, + dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG, + uCount = count, + dwTimeout = 0, + }; + + fwi.cbSize = (uint)Marshal.SizeOf(fwi); + bool ret = FlashWindowEx(ref fwi); + Console.WriteLine(ret); + } + + #endregion + + public static System.Windows.Point GetCursorPos() { + Win32Point pt; + GetCursorPos(out pt); + return new System.Windows.Point(pt.x, pt.y); + } + + [DllImport("user32.dll")] + public static extern bool GetCursorPos(out Win32Point pt); + + [DllImport("user32.dll")] + public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwnd_insert_after, int x, int y, int cx, int cy, SWP flags); + + [DllImport("user32.dll")] + public static extern bool GetWindowRect(IntPtr hwnd, out Win32Rect lpRect); + + [DllImport("user32")] + public static extern bool GetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT lpwndpl); + + public static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff); + public static readonly WM WM_SHOWME = RegisterWindowMessage("SHOW_ME"); + public static readonly WM WM_SHELL_TERMINATE = RegisterWindowMessage("SHELL_TERMINATE"); + public static readonly WM WM_URL = RegisterWindowMessage("BTS_URL"); + + [DllImport("user32.dll")] + public static extern WM RegisterWindowMessage(string name); + + [DllImport("user32")] + public static extern IntPtr DefWindowProc(IntPtr hWnd, int uMsg, IntPtr wParam, IntPtr lParam); + + [DllImport("dwmapi", PreserveSig = true)] + public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Win32Rect margins); + + #region Bitmap / Device context related + + [DllImport("user32")] + public static extern IntPtr GetDC(IntPtr hwnd); + [DllImport("user32")] + public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc); + + [DllImport("gdi32")] + public static extern IntPtr CreateBitmap(int width, int height, uint planes, uint bits_per_pixel, IntPtr bits); + + [DllImport("gdi32")] + public static extern bool DeleteObject(IntPtr hObject); + + [DllImport("gdi32")] + public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); + + [DllImport("gdi32")] + public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); + + [DllImport("gdi32")] + public static extern IntPtr CreateCompatibleDC(IntPtr hdc); + + [DllImport("gdi32")] + public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop = 0x00CC0020/*SRCCOPY*/); + + [DllImport("gdi32")] + public static extern int SetStretchBltMode(IntPtr hdc, int mode); + + [DllImport("gdi32")] + public static extern bool StretchBlt(IntPtr hdc_dest, int x_dest, int y_dest, int width_dest, int height_dest, IntPtr hdc_src, int x_src, int y_src, int width_src, int height_src, int dwRop = 0x00CC0020/*SRCCOPY*/); + + #endregion + + #region Monitor/Workarea related + + public const int MONITOR_DEFAULTONPRIMARY = 1; + public const int MONITOR_DEFAULTONNEAREST = 2; + + [DllImport("user32")] + public static extern IntPtr MonitorFromWindow(IntPtr hwnd, int flags); + + [DllImport("user32")] + public static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi); + + [DllImport("user32", EntryPoint = "SystemParametersInfo", SetLastError=true)] + private static extern bool SetWorkArea_SystemParametersInfo(SPI action, uint zero, Win32Rect param, uint winini); + + public static void SetWorkArea(Rect workarea) { + var dpi_ratio = config.Configuration.get().dpi_ratio; + workarea = new Rect(workarea.Left * dpi_ratio, workarea.Top * dpi_ratio, (workarea.Right - workarea.Left) * dpi_ratio, (workarea.Bottom - workarea.Top) * dpi_ratio); + //const uint SPIF_SENDWININICHANGE = 2; + const uint SPIF_UPDATEINIFILE = 1; + + Win32Rect rect = new Win32Rect(workarea); + // Sending SPIF_SENDWININICHANGE causes this to block until all top level windows have acknowledged the settings change + // Since we want to do that during shutdown this could cause a long delay. + bool result = SetWorkArea_SystemParametersInfo(SPI.SETWORKAREA, 1, rect, SPIF_UPDATEINIFILE); + if (!result) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Failed to set work area. {0} - {1}".fmt(Marshal.GetLastWin32Error(), new System.ComponentModel.Win32Exception().Message)); + } + SendNotifyMessage(HWND_BROADCAST, WM.SETTINGCHANGE, (Int64)SPI.SETWORKAREA, 0); + } + + // Get the work area for monitor where the specified window is currently. + // The work area is the area of the window not covered by the task bar or a docked shell + public static Rect GetWorkArea(IntPtr window) { + var dpi_ratio = config.Configuration.get().dpi_ratio; + IntPtr monitor = MonitorFromWindow(window, MONITOR_DEFAULTONNEAREST); + MONITORINFO info = new MONITORINFO(); + info.cbSize = Marshal.SizeOf(info); + GetMonitorInfo(monitor, ref info); + return new Rect(info.rcWork.Left/dpi_ratio, info.rcWork.Top/dpi_ratio, (info.rcWork.Right - info.rcWork.Left)/dpi_ratio, (info.rcWork.Bottom - info.rcWork.Top)/dpi_ratio); + } + + #endregion + + [DllImport("user32")] + public static extern IntPtr GetForegroundWindow(); + + [DllImport("user32")] + public static extern bool IsWindow(IntPtr handle); + + } + + + public enum GWL + { + WNDPROC = -4, + EXSTYLE = -20, + } + + public enum WS_EX + { + TRANSPARENT = 0x20 + } + + [Flags] + public enum SWP : uint + { + SWP_NOSIZE = 1, + SWP_NOMOVE = 2, + SWP_FRAMECHANGED = 0x20 + } + + public enum SPI : uint + { + GETBEEP = 0x0001, + SETBEEP = 0x0002, + GETMOUSE = 0x0003, + SETMOUSE = 0x0004, + GETBORDER = 0x0005, + SETBORDER = 0x0006, + GETKEYBOARDSPEED = 0x000A, + SETKEYBOARDSPEED = 0x000B, + LANGDRIVER = 0x000C, + ICONHORIZONTALSPACING = 0x000D, + GETSCREENSAVETIMEOUT = 0x000E, + SETSCREENSAVETIMEOUT = 0x000F, + GETSCREENSAVEACTIVE = 0x0010, + SETSCREENSAVEACTIVE = 0x0011, + GETGRIDGRANULARITY = 0x0012, + SETGRIDGRANULARITY = 0x0013, + SETDESKWALLPAPER = 0x0014, + SETDESKPATTERN = 0x0015, + GETKEYBOARDDELAY = 0x0016, + SETKEYBOARDDELAY = 0x0017, + ICONVERTICALSPACING = 0x0018, + GETICONTITLEWRAP = 0x0019, + SETICONTITLEWRAP = 0x001A, + GETMENUDROPALIGNMENT = 0x001B, + SETMENUDROPALIGNMENT = 0x001C, + SETDOUBLECLKWIDTH = 0x001D, + SETDOUBLECLKHEIGHT = 0x001E, + GETICONTITLELOGFONT = 0x001F, + SETDOUBLECLICKTIME = 0x0020, + SETMOUSEBUTTONSWAP = 0x0021, + SETICONTITLELOGFONT = 0x0022, + GETFASTTASKSWITCH = 0x0023, + SETFASTTASKSWITCH = 0x0024, + SETDRAGFULLWINDOWS = 0x0025, + GETDRAGFULLWINDOWS = 0x0026, + GETNONCLIENTMETRICS = 0x0029, + SETNONCLIENTMETRICS = 0x002A, + GETMINIMIZEDMETRICS = 0x002B, + SETMINIMIZEDMETRICS = 0x002C, + GETICONMETRICS = 0x002D, + SETICONMETRICS = 0x002E, + SETWORKAREA = 0x002F, + GETWORKAREA = 0x0030, + SETPENWINDOWS = 0x0031, + GETHIGHCONTRAST = 0x0042, + SETHIGHCONTRAST = 0x0043, + GETKEYBOARDPREF = 0x0044, + SETKEYBOARDPREF = 0x0045, + GETSCREENREADER = 0x0046, + SETSCREENREADER = 0x0047, + GETANIMATION = 0x0048, + SETANIMATION = 0x0049, + GETFONTSMOOTHING = 0x004A, + SETFONTSMOOTHING = 0x004B, + SETDRAGWIDTH = 0x004C, + SETDRAGHEIGHT = 0x004D, + SETHANDHELD = 0x004E, + GETLOWPOWERTIMEOUT = 0x004F, + GETPOWEROFFTIMEOUT = 0x0050, + SETLOWPOWERTIMEOUT = 0x0051, + SETPOWEROFFTIMEOUT = 0x0052, + GETLOWPOWERACTIVE = 0x0053, + GETPOWEROFFACTIVE = 0x0054, + SETLOWPOWERACTIVE = 0x0055, + SETPOWEROFFACTIVE = 0x0056, + SETCURSORS = 0x0057, + SETICONS = 0x0058, + GETDEFAULTINPUTLANG = 0x0059, + SETDEFAULTINPUTLANG = 0x005A, + SETLANGTOGGLE = 0x005B, + GETWINDOWSEXTENSION = 0x005C, + SETMOUSETRAILS = 0x005D, + GETMOUSETRAILS = 0x005E, + SETSCREENSAVERRUNNING = 0x0061, + SCREENSAVERRUNNING = SETSCREENSAVERRUNNING, + GETFILTERKEYS = 0x0032, + SETFILTERKEYS = 0x0033, + GETTOGGLEKEYS = 0x0034, + SETTOGGLEKEYS = 0x0035, + GETMOUSEKEYS = 0x0036, + SETMOUSEKEYS = 0x0037, + GETSHOWSOUNDS = 0x0038, + SETSHOWSOUNDS = 0x0039, + GETSTICKYKEYS = 0x003A, + SETSTICKYKEYS = 0x003B, + GETACCESSTIMEOUT = 0x003C, + SETACCESSTIMEOUT = 0x003D, + GETSERIALKEYS = 0x003E, + SETSERIALKEYS = 0x003F, + GETSOUNDSENTRY = 0x0040, + SETSOUNDSENTRY = 0x0041, + GETSNAPTODEFBUTTON = 0x005F, + SETSNAPTODEFBUTTON = 0x0060, + GETMOUSEHOVERWIDTH = 0x0062, + SETMOUSEHOVERWIDTH = 0x0063, + GETMOUSEHOVERHEIGHT = 0x0064, + SETMOUSEHOVERHEIGHT = 0x0065, + GETMOUSEHOVERTIME = 0x0066, + SETMOUSEHOVERTIME = 0x0067, + GETWHEELSCROLLLINES = 0x0068, + SETWHEELSCROLLLINES = 0x0069, + GETMENUSHOWDELAY = 0x006A, + SETMENUSHOWDELAY = 0x006B, + GETWHEELSCROLLCHARS = 0x006C, + SETWHEELSCROLLCHARS = 0x006D, + GETSHOWIMEUI = 0x006E, + SETSHOWIMEUI = 0x006F, + GETMOUSESPEED = 0x0070, + SETMOUSESPEED = 0x0071, + GETSCREENSAVERRUNNING = 0x0072, + GETDESKWALLPAPER = 0x0073, + GETAUDIODESCRIPTION = 0x0074, + SETAUDIODESCRIPTION = 0x0075, + GETSCREENSAVESECURE = 0x0076, + SETSCREENSAVESECURE = 0x0077, + GETHUNGAPPTIMEOUT = 0x0078, + SETHUNGAPPTIMEOUT = 0x0079, + GETWAITTOKILLTIMEOUT = 0x007A, + SETWAITTOKILLTIMEOUT = 0x007B, + GETWAITTOKILLSERVICETIMEOUT = 0x007C, + SETWAITTOKILLSERVICETIMEOUT = 0x007D, + GETMOUSEDOCKTHRESHOLD = 0x007E, + SETMOUSEDOCKTHRESHOLD = 0x007F, + GETPENDOCKTHRESHOLD = 0x0080, + SETPENDOCKTHRESHOLD = 0x0081, + GETWINARRANGING = 0x0082, + SETWINARRANGING = 0x0083, + GETMOUSEDRAGOUTTHRESHOLD = 0x0084, + SETMOUSEDRAGOUTTHRESHOLD = 0x0085, + GETPENDRAGOUTTHRESHOLD = 0x0086, + SETPENDRAGOUTTHRESHOLD = 0x0087, + GETMOUSESIDEMOVETHRESHOLD = 0x0088, + SETMOUSESIDEMOVETHRESHOLD = 0x0089, + GETPENSIDEMOVETHRESHOLD = 0x008A, + SETPENSIDEMOVETHRESHOLD = 0x008B, + GETDRAGFROMMAXIMIZE = 0x008C, + SETDRAGFROMMAXIMIZE = 0x008D, + GETSNAPSIZING = 0x008E, + SETSNAPSIZING = 0x008F, + GETDOCKMOVING = 0x0090, + SETDOCKMOVING = 0x0091, + GETACTIVEWINDOWTRACKING = 0x1000, + SETACTIVEWINDOWTRACKING = 0x1001, + GETMENUANIMATION = 0x1002, + SETMENUANIMATION = 0x1003, + GETCOMBOBOXANIMATION = 0x1004, + SETCOMBOBOXANIMATION = 0x1005, + GETLISTBOXSMOOTHSCROLLING = 0x1006, + SETLISTBOXSMOOTHSCROLLING = 0x1007, + GETGRADIENTCAPTIONS = 0x1008, + SETGRADIENTCAPTIONS = 0x1009, + GETKEYBOARDCUES = 0x100A, + SETKEYBOARDCUES = 0x100B, + GETMENUUNDERLINES = GETKEYBOARDCUES, + SETMENUUNDERLINES = SETKEYBOARDCUES, + GETACTIVEWNDTRKZORDER = 0x100C, + SETACTIVEWNDTRKZORDER = 0x100D, + GETHOTTRACKING = 0x100E, + SETHOTTRACKING = 0x100F, + GETMENUFADE = 0x1012, + SETMENUFADE = 0x1013, + GETSELECTIONFADE = 0x1014, + SETSELECTIONFADE = 0x1015, + GETTOOLTIPANIMATION = 0x1016, + SETTOOLTIPANIMATION = 0x1017, + GETTOOLTIPFADE = 0x1018, + SETTOOLTIPFADE = 0x1019, + GETCURSORSHADOW = 0x101A, + SETCURSORSHADOW = 0x101B, + GETMOUSESONAR = 0x101C, + SETMOUSESONAR = 0x101D, + GETMOUSECLICKLOCK = 0x101E, + SETMOUSECLICKLOCK = 0x101F, + GETMOUSEVANISH = 0x1020, + SETMOUSEVANISH = 0x1021, + GETFLATMENU = 0x1022, + SETFLATMENU = 0x1023, + GETDROPSHADOW = 0x1024, + SETDROPSHADOW = 0x1025, + GETBLOCKSENDINPUTRESETS = 0x1026, + SETBLOCKSENDINPUTRESETS = 0x1027, + GETUIEFFECTS = 0x103E, + SETUIEFFECTS = 0x103F, + GETDISABLEOVERLAPPEDCONTENT = 0x1040, + SETDISABLEOVERLAPPEDCONTENT = 0x1041, + GETCLIENTAREAANIMATION = 0x1042, + SETCLIENTAREAANIMATION = 0x1043, + GETCLEARTYPE = 0x1048, + SETCLEARTYPE = 0x1049, + GETSPEECHRECOGNITION = 0x104A, + SETSPEECHRECOGNITION = 0x104B, + GETFOREGROUNDLOCKTIMEOUT = 0x2000, + SETFOREGROUNDLOCKTIMEOUT = 0x2001, + GETACTIVEWNDTRKTIMEOUT = 0x2002, + SETACTIVEWNDTRKTIMEOUT = 0x2003, + GETFOREGROUNDFLASHCOUNT = 0x2004, + SETFOREGROUNDFLASHCOUNT = 0x2005, + GETCARETWIDTH = 0x2006, + SETCARETWIDTH = 0x2007, + GETMOUSECLICKLOCKTIME = 0x2008, + SETMOUSECLICKLOCKTIME = 0x2009, + GETFONTSMOOTHINGTYPE = 0x200A, + SETFONTSMOOTHINGTYPE = 0x200B, + GETFONTSMOOTHINGCONTRAST = 0x200C, + SETFONTSMOOTHINGCONTRAST = 0x200D, + GETFOCUSBORDERWIDTH = 0x200E, + SETFOCUSBORDERWIDTH = 0x200F, + GETFOCUSBORDERHEIGHT = 0x2010, + SETFOCUSBORDERHEIGHT = 0x2011, + GETFONTSMOOTHINGORIENTATION = 0x2012, + SETFONTSMOOTHINGORIENTATION = 0x2013, + GETMINIMUMHITRADIUS = 0x2014, + SETMINIMUMHITRADIUS = 0x2015, + GETMESSAGEDURATION = 0x2016, + SETMESSAGEDURATION = 0x2017, + } + + #region supporting structures + [StructLayout(LayoutKind.Sequential)] + public struct CWPSTRUCT + { + public IntPtr lparam; + public IntPtr wparam; + public WM message; + public IntPtr hwnd; + } + + [StructLayout(LayoutKind.Sequential)] + public struct DEBUGHOOKINFO + { + public uint idThread; + public uint idThreadInstaller; + public IntPtr lParam; + public IntPtr wParam; + public int code; + }; + + [StructLayout(LayoutKind.Sequential)] + public struct MSG + { + public IntPtr hwnd; + public WM msg; + public IntPtr wparam; + public IntPtr lparam; + public uint time; + } + + public enum HookType + { + WH_GETMESSAGE = 3, + WH_CALLWNDPROC = 4, + WH_CALLWNDPROCRET = 12, + WH_DEBUG = 9, + WH_MOUSE = 7, + WH_SHELL = 10, + } + + public enum SysCommand + { + SC_CLOSE = 0xf060, + SC_MINIMIZE = 0XF020, + SC_MAXIMIZE = 0xF030, + SC_RESTORE = 0xF120, + } + + [StructLayout(LayoutKind.Sequential)] + public struct Win32Point + { + public override string ToString() { + return x + "," + y; + } + public Int32 x; + public Int32 y; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Win32Rect + { + public int Left; + public int Top; + public int Right; + public int Bottom; + public Win32Rect(Rect r) { + Left = (int)r.Left; + Top = (int)r.Top; + Right = ((int)(r.Left + r.Width)); + Bottom = ((int)(r.Top + r.Height)); + } + public int Width { + get { return Right - Left; } + set { Right = Left + value; } + } + public int Height { + get { return Bottom - Top; } + set { Bottom = Top = value; } + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct WINDOWPLACEMENT + { + public int Length; + public int Flags; + public int showCmd; + public Win32Point MinPosition; + public Win32Point MaxPosition; + public Win32Rect NormalPosition; + public static WINDOWPLACEMENT Default { + get { + var result = new WINDOWPLACEMENT(); + result.Length = Marshal.SizeOf(result); + return result; + } + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct MINMAXINFO + { + public Win32Point ptReserved; + public Win32Point ptMaxSize; + public Win32Point ptMaxPosition; + public Win32Point ptMinTrackSize; + public Win32Point ptMaxTrackSize; + } + + [StructLayout(LayoutKind.Sequential)] + public struct MONITORINFO + { + public int cbSize; + public Win32Rect rcMonitor; + public Win32Rect rcWork; + public uint dwFlags; + + } + + #endregion +} diff --git a/src/client/spark/uicore/NativeMethods/WM.cs b/src/client/spark/uicore/NativeMethods/WM.cs new file mode 100644 index 000000000..94ba6feff --- /dev/null +++ b/src/client/spark/uicore/NativeMethods/WM.cs @@ -0,0 +1,216 @@ + +namespace mbts.ui.native +{ + public enum WM : uint + { + ACTIVATE = 0x0006, + ACTIVATEAPP = 0x001C, + AFXFIRST = 0x0360, + AFXLAST = 0x037F, + APP = 0x8000, + ASKCBFORMATNAME = 0x030C, + CANCELJOURNAL = 0x004B, + CANCELMODE = 0x001F, + CAPTURECHANGED = 0x0215, + CHANGECBCHAIN = 0x030D, + CHANGEUISTATE = 0x0127, + CHAR = 0x0102, + CHARTOITEM = 0x002F, + CHILDACTIVATE = 0x0022, + CLEAR = 0x0303, + CLOSE = 0x0010, + COMMAND = 0x0111, + COMPACTING = 0x0041, + COMPAREITEM = 0x0039, + CONTEXTMENU = 0x007B, + COPY = 0x0301, + COPYDATA = 0x004A, + CREATE = 0x0001, + CTLCOLORBTN = 0x0135, + CTLCOLORDLG = 0x0136, + CTLCOLOREDIT = 0x0133, + CTLCOLORLISTBOX = 0x0134, + CTLCOLORMSGBOX = 0x0132, + CTLCOLORSCROLLBAR = 0x0137, + CTLCOLORSTATIC = 0x0138, + CUT = 0x0300, + DEADCHAR = 0x0103, + DELETEITEM = 0x002D, + DESTROY = 0x0002, + DESTROYCLIPBOARD = 0x0307, + DEVICECHANGE = 0x0219, + DEVMODECHANGE = 0x001B, + DISPLAYCHANGE = 0x007E, + DRAWCLIPBOARD = 0x0308, + DRAWITEM = 0x002B, + DROPFILES = 0x0233, + ENABLE = 0x000A, + ENDSESSION = 0x0016, + ENTERIDLE = 0x0121, + ENTERMENULOOP = 0x0211, + ENTERSIZEMOVE = 0x0231, + ERASEBKGND = 0x0014, + EXITMENULOOP = 0x0212, + EXITSIZEMOVE = 0x0232, + FONTCHANGE = 0x001D, + GETDLGCODE = 0x0087, + GETFONT = 0x0031, + GETHOTKEY = 0x0033, + GETICON = 0x007F, + GETMINMAXINFO = 0x0024, + GETOBJECT = 0x003D, + GETTEXT = 0x000D, + GETTEXTLENGTH = 0x000E, + HANDHELDFIRST = 0x0358, + HANDHELDLAST = 0x035F, + HELP = 0x0053, + HOTKEY = 0x0312, + HSCROLL = 0x0114, + HSCROLLCLIPBOARD = 0x030E, + ICONERASEBKGND = 0x0027, + IME_CHAR = 0x0286, + IME_COMPOSITION = 0x010F, + IME_COMPOSITIONFULL = 0x0284, + IME_CONTROL = 0x0283, + IME_ENDCOMPOSITION = 0x010E, + IME_KEYDOWN = 0x0290, + IME_KEYLAST = 0x010F, + IME_KEYUP = 0x0291, + IME_NOTIFY = 0x0282, + IME_REQUEST = 0x0288, + IME_SELECT = 0x0285, + IME_SETCONTEXT = 0x0281, + IME_STARTCOMPOSITION = 0x010D, + INITDIALOG = 0x0110, + INITMENU = 0x0116, + INITMENUPOPUP = 0x0117, + INPUTLANGCHANGE = 0x0051, + INPUTLANGCHANGEREQUEST = 0x0050, + KEYDOWN = 0x0100, + KEYFIRST = 0x0100, + KEYLAST = 0x0108, + KEYUP = 0x0101, + KILLFOCUS = 0x0008, + LBUTTONDBLCLK = 0x0203, + LBUTTONDOWN = 0x0201, + LBUTTONUP = 0x0202, + MBUTTONDBLCLK = 0x0209, + MBUTTONDOWN = 0x0207, + MBUTTONUP = 0x0208, + MDIACTIVATE = 0x0222, + MDICASCADE = 0x0227, + MDICREATE = 0x0220, + MDIDESTROY = 0x0221, + MDIGETACTIVE = 0x0229, + MDIICONARRANGE = 0x0228, + MDIMAXIMIZE = 0x0225, + MDINEXT = 0x0224, + MDIREFRESHMENU = 0x0234, + MDIRESTORE = 0x0223, + MDISETMENU = 0x0230, + MDITILE = 0x0226, + MEASUREITEM = 0x002C, + MENUCHAR = 0x0120, + MENUCOMMAND = 0x0126, + MENUDRAG = 0x0123, + MENUGETOBJECT = 0x0124, + MENURBUTTONUP = 0x0122, + MENUSELECT = 0x011F, + MOUSEACTIVATE = 0x0021, + MOUSEFIRST = 0x0200, + MOUSEHOVER = 0x02A1, + MOUSELAST = 0x020D, + MOUSELEAVE = 0x02A3, + MOUSEMOVE = 0x0200, + MOUSEWHEEL = 0x020A, + MOUSEHWHEEL = 0x020E, + MOVE = 0x0003, + MOVING = 0x0216, + NCACTIVATE = 0x0086, + NCCALCSIZE = 0x0083, + NCCREATE = 0x0081, + NCDESTROY = 0x0082, + NCHITTEST = 0x0084, + NCLBUTTONDBLCLK = 0x00A3, + NCLBUTTONDOWN = 0x00A1, + NCLBUTTONUP = 0x00A2, + NCMBUTTONDBLCLK = 0x00A9, + NCMBUTTONDOWN = 0x00A7, + NCMBUTTONUP = 0x00A8, + NCMOUSEMOVE = 0x00A0, + NCPAINT = 0x0085, + NCRBUTTONDBLCLK = 0x00A6, + NCRBUTTONDOWN = 0x00A4, + NCRBUTTONUP = 0x00A5, + NCUAHDRAWCAPTION = 0x00AE, + NCUAHDRAWFRAME = 0x00AF, + NEXTDLGCTL = 0x0028, + NEXTMENU = 0x0213, + NOTIFY = 0x004E, + NOTIFYFORMAT = 0x0055, + NULL = 0x0000, + PAINT = 0x000F, + PAINTCLIPBOARD = 0x0309, + PAINTICON = 0x0026, + PALETTECHANGED = 0x0311, + PALETTEISCHANGING = 0x0310, + PARENTNOTIFY = 0x0210, + PASTE = 0x0302, + PENWINFIRST = 0x0380, + PENWINLAST = 0x038F, + POWER = 0x0048, + POWERBROADCAST = 0x0218, + PRINT = 0x0317, + PRINTCLIENT = 0x0318, + QUERYDRAGICON = 0x0037, + QUERYENDSESSION = 0x0011, + QUERYNEWPALETTE = 0x030F, + QUERYOPEN = 0x0013, + QUEUESYNC = 0x0023, + QUIT = 0x0012, + RBUTTONDBLCLK = 0x0206, + RBUTTONDOWN = 0x0204, + RBUTTONUP = 0x0205, + RENDERALLFORMATS = 0x0306, + RENDERFORMAT = 0x0305, + SETCURSOR = 0x0020, + SETFOCUS = 0x0007, + SETFONT = 0x0030, + SETHOTKEY = 0x0032, + SETICON = 0x0080, + SETREDRAW = 0x000B, + SETTEXT = 0x000C, + SETTINGCHANGE = 0x001A, + SHOWWINDOW = 0x0018, + SIZE = 0x0005, + SIZECLIPBOARD = 0x030B, + SIZING = 0x0214, + SPOOLERSTATUS = 0x002A, + STYLECHANGED = 0x007D, + STYLECHANGING = 0x007C, + SYNCPAINT = 0x0088, + SYSCHAR = 0x0106, + SYSCOLORCHANGE = 0x0015, + SYSCOMMAND = 0x0112, + SYSDEADCHAR = 0x0107, + SYSKEYDOWN = 0x0104, + SYSKEYUP = 0x0105, + TCARD = 0x0052, + TIMECHANGE = 0x001E, + TIMER = 0x0113, + UNDO = 0x0304, + UNINITMENUPOPUP = 0x0125, + USER = 0x0400, + USERCHANGED = 0x0054, + VKEYTOITEM = 0x002E, + VSCROLL = 0x0115, + VSCROLLCLIPBOARD = 0x030A, + WINDOWPOSCHANGED = 0x0047, + WINDOWPOSCHANGING = 0x0046, + WININICHANGE = 0x001A, + XBUTTONDBLCLK = 0x020D, + XBUTTONDOWN = 0x020B, + XBUTTONUP = 0x020C, + THEMECHANGED = 0x031A, + } +} diff --git a/src/client/spark/uicore/Settings/ISavedWindowFactory.cs b/src/client/spark/uicore/Settings/ISavedWindowFactory.cs new file mode 100644 index 000000000..d2538e31d --- /dev/null +++ b/src/client/spark/uicore/Settings/ISavedWindowFactory.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.ui.shell; + +namespace mbts.ui.settings +{ + public interface ISavedWindowFactory + { + Task restore(WindowState window); + } + + [Export(typeof(ISavedWindowFactory))] + public class WindowFactory : ISavedWindowFactory + { + IEnumerable _modules; + IShellWindowMigrationRule[] _compat; + + [ImportingConstructor] + public WindowFactory(ObservableCollection modules, [ImportMany]IShellWindowMigrationRule[] migration) { + _modules = modules; + _compat = migration; + } + + public Task restore(WindowState window) { + bool changed; + int count = 0; + do { + count++; + changed = apply_compatability_migrations(ref window); + } while (count < 100 && changed); + + if (count == 100) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.Persist, "Error: Window state migration still changing after 100 iterations. Please check IShellWindowMigrationRule logic."); + } + + return restore(window.owner, window.app_data, window.position); + } + + /// When we apply the migration changes to a window we stop as soon as one "matches" and updates the state + /// Since it's possible that we have multiple levels of migration we run this function until the data stops changing (or 100 iterations) + /// ex: If change the data format twice from A to B to C then we would write 2 IShellWindowMigration instances. + /// Starting in state A one of the _compat tests changes to state B. Now we need to re-run + /// the migrations because state B will match a different rule and be converted to state C. + private bool apply_compatability_migrations(ref WindowState window) { + foreach (var test in _compat) { + try { + if (test.apply(ref window)) { + return true; + } + } + catch(Exception e) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.Persist, "Exception running compat rule {0}.\n{1}".fmt(test.GetType().Name, e.ToString())); + } + } + return false; + } + + private async Task restore(string owner_name, byte[] state, WindowPosition windowPosition) { + IShellModule owner = _modules.SingleOrDefault(m => m.key() == owner_name); + if (owner == null) { + Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Could not locate module '{0}'".fmt(owner_name)); + return null; + } + + try { + Task task = owner.create(new MemoryStream(state)); + if (task != null) { + IShellWindow window = await task; + if (window != null) { + window.set_start_position(windowPosition); + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Restoring window {0} - {1}".fmt(owner_name, window.Title)); + } + return window; + } + } + catch (Exception e) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, + "Failure to re-create window for module {0}. Error: {1}".fmt(owner_name, e.Message)); + } + return null; + } + + //private static async Task await_with_timeout(Task task) { + // if (task.IsCompleted) { + // return task.Result; + // } + // else { + // if (await Task.WhenAny(task, Task.Delay(4096)) == task) { + // return task.Result; + // } + // else { + // Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Timed out waiting to load saved window"); + // } + // } + // return default(T); + //} + } +} diff --git a/src/client/spark/uicore/Settings/ISettingsCollector.cs b/src/client/spark/uicore/Settings/ISettingsCollector.cs new file mode 100644 index 000000000..5cb48f12d --- /dev/null +++ b/src/client/spark/uicore/Settings/ISettingsCollector.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.log; +using mbts.ui.shell; + +namespace mbts.ui.settings +{ + public interface ISettingsCollector + { + // Get the save state for every open window + IEnumerable get_window_state(); + WindowState get_window_state(IShellWindow window); + IEnumerable get_module_state(); + WindowPosition get_launcher_state(); + } + + [Export(typeof(ISettingsCollector))] + class SettingsCollector : ISettingsCollector + { + IEnumerable _modules; + IWindowsInterop _interop; + IWindowManager _wm; + ILauncher _launcher; + + [ImportingConstructor] + public SettingsCollector(ObservableCollection modules, IWindowManager wm, IWindowsInterop interop, ILauncher launcher) { + _modules = modules; + _wm = wm; + _interop = interop; + _launcher = launcher; + } + + public IEnumerable get_window_state() { + foreach (var window in _wm.Windows.ToArray()) { + // Check that the window is still open since we might be iterating asyncronously + if (_wm.Windows.Contains(window)) { + var state = get_window_state(window); + if (state != null) { + yield return state; + } + } + } + } + + public IEnumerable get_module_state() { + //Note: I'm assuming that the list of modules is stable and I don't have to protect against it changing here + foreach (var module in _modules) { + string name = module.key(); + MemoryStream out_stream = new MemoryStream(); + module.get_state(out_stream); + yield return new ModuleState() { + name = module.key(), + app_data = out_stream.ToArray(), + }; + } + } + + public WindowPosition get_launcher_state() { + return _launcher.get_position(); + } + + public WindowState get_window_state(IShellWindow window) { + try { + if (window == null || window.Owner == null) return null; + MemoryStream out_stream = new MemoryStream(); + window.GetState(out_stream); + var state = new WindowState() { + owner = window.Owner.key(), + app_data = out_stream.ToArray(), + position = _interop.GetPosition(window), + title = window.Title + }; + return state; + } + catch (Exception e) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message)); + } + return null; + } + } + +} diff --git a/src/client/spark/uicore/Settings/Tests/SettingsTests.cs b/src/client/spark/uicore/Settings/Tests/SettingsTests.cs new file mode 100644 index 000000000..a1afe412b --- /dev/null +++ b/src/client/spark/uicore/Settings/Tests/SettingsTests.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.ObjectModel; +using System.Threading.Tasks; +using mbts.ui.settings; +using NUnit.Framework; + +namespace mbts.ui.tests +{ + [TestFixture] + class SettingsTests + { + [Test] + public void TestRestoreWindowFromSaved() { + //ObservableCollection modules = new ObservableCollection(); + //modules.Add(new TestShellModule() { + // create_method = stream => { + // ShellSerializationHeader header = ProtoBuf.Serializer.DeserializeWithLengthPrefix(stream, ProtoBuf.PrefixStyle.Fixed32); + // return null; + // } + //}); + //WindowFactory factory = new WindowFactory(modules, new IShellWindowMigrationRule[0]); + //TestPersist tp = new TestPersist(); + + //Task test = Task.Run(() => { + + + + //}); + //test.Wait(); + } + + [Test] + public void TestMigrationRulesMigrate() { + // Test renaming an IShellModule - windows still re-created + } + + } + + + + +} diff --git a/src/client/spark/uicore/Settings/Tests/TestPersist.cs b/src/client/spark/uicore/Settings/Tests/TestPersist.cs new file mode 100644 index 000000000..55921e891 --- /dev/null +++ b/src/client/spark/uicore/Settings/Tests/TestPersist.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.persist; + +namespace mbts.ui.tests +{ + // Stub persistance store for shell unit tests + public class TestPersist : IPersist, IUserPersist + { + public Dictionary> Values = new Dictionary>(); + + public Task set(string ns, string key, T value) { + TaskCompletionSource source = new TaskCompletionSource(); + try { + Values[ns][key] = value; + source.TrySetResult(null); + } + catch (Exception e) { + source.TrySetException(e); + } + + return source.Task; + } + + public Task clear(string ns, string key) { + TaskCompletionSource source = new TaskCompletionSource(); + try { + Values[ns].Remove(key); + source.TrySetResult(null); + } + catch (Exception e) { + source.TrySetException(e); + } + return source.Task; + } + + public Task get(string ns, string key) { + TaskCompletionSource source = new TaskCompletionSource(); + try { + T result = (T)Values[ns][key]; + source.TrySetResult(result); + } + catch (Exception e) { + source.TrySetException(e); + } + return source.Task; + } + + public async Task>> get_history(string ns, string key) { + var res = await get(ns, key); + return new Tuple[] { Tuple.Create(res, DateTime.Today) }; + } + + public Task>> query(string ns, string pattern) { + throw new NotImplementedException(); + } + + public IDisposable subscribe(string ns, string pattern, Action>> callback) { + throw new NotImplementedException(); + } + + public void Dispose() { } + } +} diff --git a/src/client/spark/uicore/Settings/Tests/TestShellModule.cs b/src/client/spark/uicore/Settings/Tests/TestShellModule.cs new file mode 100644 index 000000000..93e1f679b --- /dev/null +++ b/src/client/spark/uicore/Settings/Tests/TestShellModule.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui.tests +{ + class TestShellModule : IShellModule + { + public System.Windows.Media.ImageSource icon {get { return Icons.ActiveWindow; } } + public string name { get; set; } + public int priority { get; set; } + + public IShellWindow launch_ui { get { throw new NotImplementedException(); } } + public void load_state(System.IO.Stream state = null) {} + public void get_state(System.IO.Stream save_here) { throw new NotImplementedException(); } + public void start() { } + + public Func create_method { get; set; } + public Task create(Stream load_stream) { + TaskCompletionSource ts = new TaskCompletionSource(); + ts.SetResult(create_method(load_stream)); + return ts.Task; + } + public void Dispose() { } + } +} diff --git a/src/client/spark/uicore/Settings/UISettings.proto b/src/client/spark/uicore/Settings/UISettings.proto new file mode 100644 index 000000000..83edbc73f --- /dev/null +++ b/src/client/spark/uicore/Settings/UISettings.proto @@ -0,0 +1,127 @@ +syntax="proto3"; +package mbts.ui; +option csharp_namespace="mbts.ui"; +//import "core/bts_sys/api/services/MarketDataService.proto"; +import "google/protobuf/descriptor.proto"; + + +// +// Custom Options +// +extend google.protobuf.MessageOptions { + string header = 10000; +} +message Validation { + string pattern = 1; + uint32 max_length = 2; + int64 min_value = 3; + int64 max_value = 4; +} +extend google.protobuf.FieldOptions { + string name = 20000; + string comment = 20001; + Validation validation = 30000; +} + +// +// Special settings objects +// +message SettingsFont { + string family = 1; + float size = 2 [(validation).min_value = 4, (validation).max_value=20]; + bool bold = 3; + bool italic = 4; + bool oblique = 5; + bool underline = 6; + bool strikeout = 7; + string script = 8; +} + +message SettingsColor { + uint32 A = 1; + uint32 R = 2; + uint32 G = 3; + uint32 B = 4; +} + +message CalculatorButtons { + string buttons = 1 [(validation).pattern = "^([0-9]+[ ,;]*)*$"]; +} + +// +// Global settings container. Put your application settings in here for them to be visible in the UI +// +message ApplicationSettings { + // oneof => radio button + // color,font => custom control + GeneralSettings general = 1; + map ladder_settings = 2; +} + +// +// General settings +// + +message GeneralSettings { + double tab_width = 1; + double tab_height = 2; +} + +// +// Ladder settings +// + +message LadderSettings { + option (header) = "Ladder Settings"; + double row_height = 1; + SettingsColor grid_line_color = 2; + CalculatorButtons calculator_buttons = 3; + bool show_scroll_bar = 4; + int32 ticks_until_recenter = 5 [(validation).min_value = 3, (validation).max_value=10]; + int32 seconds_until_recenter = 6 [(validation).min_value = 10, (validation).max_value=3600]; + string initial_algo = 7; + string initial_time_in_force = 8; + uint32 default_order_size = 9; + bool animate_recenter = 10; + + LadderColumnSettings orders_column = 50; + LadderColumnSettings bid_column = 51; + LadderColumnSettings ask_column = 52; + LadderColumnSettings price_column = 53; + LadderColumnSettings last_column = 54; + +} +message LadderColumnSettings { + bool show = 1; + uint32 width = 2; + SettingsColor background = 3; + SettingsColor foreground = 4; + SettingsFont font = 5; +} + +// +// OrderBook settings +// +message OrderBookSettings { + CalculatorButtons calculator_buttons = 1; + ColumnOrder column_visibility = 100; +} +message ColumnOrder { + bool security = 100; + bool time = 101; + bool user = 102; + bool account = 103; + bool exchange = 104; + bool orders = 105; + bool side = 106; + bool status = 107; + bool price = 108; + bool quantity = 109; + bool filled= 110; + bool average_price = 111; + bool flat_order_params = 112 [(name)="Misc"]; + bool bts_order = 113 [(name)="BTS Order"]; + bool exchange_order = 114; + bool details = 115; +} + diff --git a/src/client/spark/uicore/Settings/UISettingsDefaults.cs b/src/client/spark/uicore/Settings/UISettingsDefaults.cs new file mode 100644 index 000000000..bb1db3c41 --- /dev/null +++ b/src/client/spark/uicore/Settings/UISettingsDefaults.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui { + + partial class SettingsFont { + partial void OnConstruction() { + Family = "Segoe UI"; + Size = 10; + Script = "Western"; + } + } + + partial class LadderColumnSettings { + partial void OnConstruction() { + // put default values here + Show = true; + Width = 50; + } + } + + partial class LadderSettings { + partial void OnConstruction() { + var white = BTSCoreColors.white; + var black = BTSCoreColors.black; + var grayish = BTSCoreColors.gray_lighter; + + OrdersColumn.Background = grayish; + + BidColumn.Foreground = white; + BidColumn.Background = BTSColors.MarketData.bid; + + AskColumn.Foreground = white; + AskColumn.Background = BTSColors.MarketData.ask; + + PriceColumn.Foreground = black; + PriceColumn.Background = grayish; + + LastColumn.Foreground = black; + LastColumn.Background = grayish; + + InitialAlgo = "LimitOrder"; + } + } + + partial class CalculatorButtons { + static char[] splitter = new[] { ' ', ';', ',' }; + partial void OnConstruction() { + Buttons = ""; + } + public int[] Tokens => Buttons.Split(splitter).Select(Int32.Parse).ToArray(); + } + + partial class OrderBookSettings { + partial void OnConstruction() { + CalculatorButtons = new CalculatorButtons() { Buttons = "1 1 2 3 5 9" }; + } + } + + +} diff --git a/src/client/spark/uicore/Settings/UserPersistFactory.cs b/src/client/spark/uicore/Settings/UserPersistFactory.cs new file mode 100644 index 000000000..4c2cace15 --- /dev/null +++ b/src/client/spark/uicore/Settings/UserPersistFactory.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.config; +using mbts.pubsub; +using mbts.persist; + +namespace mbts.ui.settings +{ + [Export(typeof(IUserPersistFactory))] + class UISettingsFactory : IUserPersistFactory + { + private string[] _users; + private PubsubHub _hub; + + [ImportingConstructor] + public UISettingsFactory([Import("username")] string current_user, PubsubHub hub) { + // Get the list of all UI visible users + _hub = hub; + _users = Configuration.get().users + .Where(u => u.ui_visible && u.login.login_name != current_user) + .Select(u => u.login.login_name) + .ToArray(); + } + + public IEnumerable users() { return _users; } + + public IUserPersist get_persist_for(string user) { + return new UserUISettings(user, _hub); + } + } +} diff --git a/src/client/spark/uicore/Shell/Error/ErrorShellWindow.cs b/src/client/spark/uicore/Shell/Error/ErrorShellWindow.cs new file mode 100644 index 000000000..cf61be2e4 --- /dev/null +++ b/src/client/spark/uicore/Shell/Error/ErrorShellWindow.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace mbts.ui.shell +{ + public class ErrorShellWindow : IShellWindow + { + public string Title { get; set; } + + public event Action TitleChanged = () => { }; + + public System.Windows.Media.ImageSource Icon { get; set; } + + public event Action IconChanged = () => { }; + + public IShellModule Owner { + get { return null; } + set { } + } + + public ShellWindowUI Content { get; set; } + + public ShellWindowUI GetContent() { + return Content; + } + + public void GetState(System.IO.Stream save_here) { + + } + + public void Dispose() { + + } + } +} diff --git a/src/client/spark/uicore/Shell/Favorites/FavoritesModel.cs b/src/client/spark/uicore/Shell/Favorites/FavoritesModel.cs new file mode 100644 index 000000000..84a1391fc --- /dev/null +++ b/src/client/spark/uicore/Shell/Favorites/FavoritesModel.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Input; + +namespace mbts.ui.shell +{ + public interface IFavorites + { + void add_favorite(IShellWindow window); + void remove_favorite(IShellWindow window); + bool is_favorite(IShellWindow window); + } + + [Export(typeof(IFavorites))] + public class FavoritesModel : IFavorites + { + private const string WORKSPACE_NAMESPACE = "shell_saved_windows"; + [ImportingConstructor] + public FavoritesModel() { + FavoriteWindows = new ObservableCollection(); + } + + public ObservableCollection FavoriteWindows { get; set; } + + public void add_favorite(IShellWindow window) { + throw new NotImplementedException(); + } + + public void remove_favorite(IShellWindow window) { + throw new NotImplementedException(); + } + + public bool is_favorite(IShellWindow window) { + throw new NotImplementedException(); + } + + public ICommand restore_favorite { + get { + return new DelegateCommand(name => { + throw new NotImplementedException(); + }); + } + } + } + +} diff --git a/src/client/spark/uicore/Shell/Login/LoginModel.cs b/src/client/spark/uicore/Shell/Login/LoginModel.cs new file mode 100644 index 000000000..e23e9d42e --- /dev/null +++ b/src/client/spark/uicore/Shell/Login/LoginModel.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; +using mbts.config; +using mbts.logon; +using mbts.pubsub; +using mbts.ui.native; +using mbts.utils; +using bts.co2; + +namespace mbts.ui.shell +{ + // The LoginContainer participates in the startup Import/Export dependency system + // Since the login form should not depend on *anything* it will be shown before this is created + // Once this is created it access the global LoginModel and retrieves the username + internal class LoginContainer + { + [ImportingConstructor] + public LoginContainer(PubsubHub hub, [Import("autologin", AllowDefault=true)]string auto_login) { + if (string.IsNullOrEmpty(auto_login)) { + var model = LoginModel.instance; + model.provide_hub(hub); + // await_login pumps the dispatcher but doesn't allow control to return to MEF until the username and workspace are available + model.await_login(); + UserName = model.get_username(); + Workspace = model.get_workspace(); + model.Dispose(); + } + else { + UserName = auto_login; + Environment.SetEnvironmentVariable("BTS_USER", UserName); + Workspace = string.Empty; + LoginModel.instance.Dispose(); + } + } + + [Export("username")] + public string UserName { get; private set; } + + [Export("workspace")] + public string Workspace { get; private set; } + } + + public class LoginModel : IDisposable + { + // Singleton to help bootstrap the system + private static LoginModel _instance = new LoginModel(); + public static LoginModel instance { get { return _instance; } } + private string _username; + private string _workspace; + private PreloginWorkspaceEnumerator _enum_workspace; + + Logon _logon; + DispatcherFrame _frame = new DispatcherFrame(); + + private LoginModel() { + init(); + } + + // Properties used in binding to the UI + public event Action Ready; + public string ErrorMessage { get; private set; } + public bool HasFatalError { get; set; } + public string[] UserNames { get; private set; } + + + // The final username + public string get_username() { + Logger.assert_d(!string.IsNullOrEmpty(_username)); + return _username; + } + public string get_workspace() { + return _workspace; + } + public Task> workspaces_for(string user) { + return _enum_workspace.get_workspaces(user); + } + + #region Init + // Check that the logon dependencies are valid. + // Initialization is complete when UserNames is populated + private async void init() { + // Make sure config is initialized and working + try { + Configuration.initialize(); + } + catch (ApplicationException e) { + ErrorMessage = e.Message; + HasFatalError = true; + return; + } + + // Wait for the hub to create the login doodad + var hub = await _hub_src.Task; + _enum_workspace = new PreloginWorkspaceEnumerator(hub); + _logon = new Logon(hub); + // Populate the UI + UserNames = _logon.get_all_logins(); + Array.Sort(UserNames); + if (Ready != null) { + Ready(); + } + } + + public Task preload_securities() { + return mbts.co2.Co2RelayControl.instance.preload_securities((MDRequest.Flags)0xFF); + } + #endregion + + public bool do_login(string username, string workspace, string password, out string info) { + if (UserNames.Contains(username)) { + if (_logon.logon(username, password ?? string.Empty, out info)) { + _workspace = workspace; + set_authenticated_user(username); + return true; + } +//#if DEBUG +// set_authenticated_user(username); +// return true; +//#else + return false; +//#endif + } + info = "Invalid username"; + return false; + } + + private void set_authenticated_user(string name) { + Logger.assert(!string.IsNullOrEmpty(name)); + Logger.assert(UserNames.Contains(name)); + _username = name; + Environment.SetEnvironmentVariable("BTS_USER", name); + _frame.Continue = false; + } + + public void await_login() { + if (string.IsNullOrEmpty(_username)) { + Dispatcher.PushFrame(_frame); + } + } + + + #region provide hub + public void provide_hub(PubsubHub hub) { + _hub_src.TrySetResult(hub); + } + private TaskCompletionSource _hub_src = new TaskCompletionSource(); + #endregion + + #region Dispose + public void Dispose() { + _frame.Continue = false; + UserNames = null; + _instance = null; + } + #endregion + } + +} diff --git a/src/client/spark/uicore/Shell/Login/PreloginWorkspaceEnumerator.cs b/src/client/spark/uicore/Shell/Login/PreloginWorkspaceEnumerator.cs new file mode 100644 index 000000000..bd5464012 --- /dev/null +++ b/src/client/spark/uicore/Shell/Login/PreloginWorkspaceEnumerator.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.pubsub; +using mbts.ui.settings; +using mbts.persist; + +namespace mbts.ui.shell +{ + class PreloginWorkspaceEnumerator + { + private Dictionary _cache = new Dictionary(); + private IPersist _persist; + + public PreloginWorkspaceEnumerator(PubsubHub hub) { + _persist = new UserUISettings(".*", hub); + } + + private string sort_key(string name) { + if (name.StartsWith(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)) { + // Move active workspaces to the end to the end of the list + return (char)0xff + name; + } + return name; + } + + public async Task> get_workspaces(string username) { + if (_persist != null) { + var query_result = await _persist.query(WorkspacesModel.WORKSPACE_NAMESPACE, ".*"); + foreach (var set in query_result.GroupBy(t => t.user)) { + _cache[set.Key] = set.Select(x => x.key).OrderBy(sort_key).ToArray(); + } + _persist = null; + } + + string[] result; + if (_cache.TryGetValue(username, out result)) { + return result; + } + return new string[]{}; + } + } +} diff --git a/src/client/spark/uicore/Shell/ShellMetaModule/ISettingsLauncher.cs b/src/client/spark/uicore/Shell/ShellMetaModule/ISettingsLauncher.cs new file mode 100644 index 000000000..e3317957d --- /dev/null +++ b/src/client/spark/uicore/Shell/ShellMetaModule/ISettingsLauncher.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui.shell +{ + public interface ISettingsLauncher + { + void launch_settings_editor(); + void launch_tick_settings_editor(); + } +} diff --git a/src/client/spark/uicore/Shell/ShellMetaModule/MetaShellMenuModule.cs b/src/client/spark/uicore/Shell/ShellMetaModule/MetaShellMenuModule.cs new file mode 100644 index 000000000..b72076b37 --- /dev/null +++ b/src/client/spark/uicore/Shell/ShellMetaModule/MetaShellMenuModule.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using mbts.ui.settings; +using BCG; +using System.Reflection; +using ProtoBuf; + +namespace mbts.ui.shell +{ + // + // This shell module is responsible for helping the user manage other aspects of the shell + // + // 1. Keeps a list of saved workspaces + // 2. Keeps a list of saved windows + // 3. Keeps a list of recently closed windows + // 4. Owns web browser IShellWindows + // + [Export(typeof(IShellModule))] + public class MetaShellMenuModule : IShellModule + { + MetaShellMenuViewModel _viewmodel; + IViewLocator _viewfinder; + IBrowserWindowManager _bwm; + + [ImportingConstructor] + public MetaShellMenuModule(IViewLocator view, WorkspacesModel model, [Import("workspace")]string initial_workspace, IUndoActions undo, IBrowserWindowManager ibwm) + { + _viewfinder = view; + _viewmodel = new MetaShellMenuViewModel(model, null, undo as UndoModel, ibwm); + var unused = model.init(initial_workspace); + _bwm = ibwm; + } + + #region IShellModule members + public System.Windows.Media.ImageSource icon { get { return Icons.FavoriteWindow; } } + public string name {get { return "Windows"; } } + public int priority { get { return -1024; } } + public void start() { } + public void load_state(System.IO.Stream state = null) { } + public void get_state(System.IO.Stream save_here) { } + public Task create(System.IO.Stream load_stream) { + var header = ProtoBuf.Serializer.DeserializeWithLengthPrefix(load_stream, PrefixStyle.Fixed32); + if (header != null && header.name == "Browser") { + var state = ProtoBuf.Serializer.DeserializeWithLengthPrefix(load_stream, PrefixStyle.Fixed32); + var window = _bwm.create_hidden(new Uri(state.uri, UriKind.RelativeOrAbsolute)); + return Task.FromResult(window); + } + throw new ArgumentException("load_stream"); + } + public IShellWindow launch_ui { + get { return _viewfinder.window_for(_viewmodel); } + } + #endregion + + public void Dispose() { } + } + + #region Browser window SaveState + [ProtoContract] + public class BrowserWindowState + { + [ProtoMember(10)] + public string uri; + } + #endregion +} diff --git a/src/client/spark/uicore/Shell/ShellMetaModule/MetaShellMenuViewModel.cs b/src/client/spark/uicore/Shell/ShellMetaModule/MetaShellMenuViewModel.cs new file mode 100644 index 000000000..4423372a2 --- /dev/null +++ b/src/client/spark/uicore/Shell/ShellMetaModule/MetaShellMenuViewModel.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui.shell +{ + public class MetaShellMenuViewModel : ViewModelBaseWithValidation + { + private WorkspacesModel _work_model; + private FavoritesModel _fav_model; + private UndoModel _undo_model; + + public MetaShellMenuViewModel(WorkspacesModel wmodel, FavoritesModel fmodel, UndoModel umodel, IBrowserWindowManager browser) { + _work_model = wmodel; + _fav_model = fmodel; + _undo_model = umodel; + ShowWorkspaces = true; + ShowUndo = true; + manual_command = new DelegateCommand(_ => browser.Pages.Add(new Uri("bts://m/"))); + } + + #region Workspaces + public ObservableCollection Workspaces { get { return _work_model.Workspaces; } } + public string SaveName { get; set; } + public bool IsPublicWorkspace { get; set; } + public bool ShowWorkspaces { get; set; } + + public ICommand SaveWorkspace { + get { + return new DelegateCommand(arg => { + // Check for errors in the input + if (string.IsNullOrEmpty(SaveName)) { + set_error("SaveName", "Workspace must be named"); + return; + } + if (SaveName.Contains(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)) { + set_error("SaveName", "Workspace name cannot contains '{0}'".fmt(WorkspacesModel.ACTIVE_WORKSPACE_PREFIX)); + return; + } + else { + clear_error("SaveName"); + } + // Save + _work_model.save_workspace(SaveName, ispublic: IsPublicWorkspace); + }); + } + } + + + #endregion + public ICommand launch_settings_editor { get; private set; } + + public ICommand launch_tick_settings_editor { get; private set; } + + public ICommand manual_command { get; private set; } + + + public FavoritesModel Favorites { get; private set; } + #region Favorites + #endregion + + + public ObservableCollection UndoItems { get { return _undo_model == null ? null : _undo_model.Items; } } + public bool ShowUndo { get; set; } + } +} diff --git a/src/client/spark/uicore/Shell/ShellModel.cs b/src/client/spark/uicore/Shell/ShellModel.cs new file mode 100644 index 000000000..922932b42 --- /dev/null +++ b/src/client/spark/uicore/Shell/ShellModel.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.ComponentModel.Composition.Hosting; +using System.IO; +using System.Linq; +using System.Reflection; +using mbts.config; +using bts.config; +using bts.log; + +namespace mbts.ui +{ + // Models a generic multi-window host + public class ShellModel : IDisposable + { + [ImportMany(typeof(IInitializable))] + List _initializers = new List(); + [ImportMany(typeof(IShellModule))] + IShellModule[] _rawmodules = null; + ObservableCollection _modules = new ObservableCollection(); + + [Export] + public ObservableCollection Modules => _modules; + [Export] + public ObservableCollection Windows { get; private set; } + + public ShellModel() { + Windows = new ObservableCollection(); + } + + public void Initialize() { + PerformMEFComposition(); + TidyModuleList(); + InitInitializers(); + } + + private Lazy _container = new Lazy(create_container); + [Export] + private CompositionContainer Container => _container.Value; + + private static CompositionContainer create_container() { + var component_catalog = new AggregateCatalog(); + component_catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShellModel).Assembly)); + component_catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetEntryAssembly())); + component_catalog.Catalogs.Add(new AssemblyCatalog(Assembly.Load("bts_view"))); + component_catalog.Catalogs.Add(new AssemblyCatalog(Assembly.Load("TickConversion"))); + + // Add plugin path + string plugin_path = Configuration.get().installation_specific_data_path + "/plugins/"; + if (Directory.Exists(plugin_path)) { + component_catalog.Catalogs.Add(new DirectoryCatalog(plugin_path)); + } + + // Add configures modules + foreach (string module_name in Configuration.get().modules) { + try { + if (module_name.ToLower() == "bts_shell") continue; // save us from a really irritating error message + Assembly assembly = Assembly.Load(module_name); + component_catalog.Catalogs.Add(new AssemblyCatalog(assembly)); + } + catch (FileNotFoundException) { + Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Failed to load shell plugin '" + module_name + "'. Not found."); + } + } + + return new CompositionContainer(component_catalog); + } + + public T create() where T : class { + T value = Container.GetExportedValue(); + return value; + } + + private void PerformMEFComposition() { + // Initialize MEF to populate Modules and windows + Logger.log(Level.Info, Subsystem.ui, "Beginning bts_shell module composition."); + + // Add specific instances + Container.ComposeExportedValue(this); + try { + Container.ComposeParts(this); + } + catch (ReflectionTypeLoadException rtlex) { + System.Text.StringBuilder message = new System.Text.StringBuilder(rtlex.ToString()); + foreach (var e in rtlex.LoaderExceptions) { + message.AppendLine("============================"); + message.AppendLine(e.ToString()); + } + Logger.assert(false, message.ToString()); + } + catch (CompositionException cex) { + Logger.assert(false, cex.Message); + } + } + + private void TidyModuleList() { + // Sort the modules and remove any hidden ones + var lookup = _rawmodules.ToLookup(m => IsHidden(m)); + _rawmodules = null; + foreach (var m in lookup[true]) { + m.Dispose(); + } + _modules.AddRange(lookup[false].OrderBy(m => m.priority)); + } + + private void InitInitializers() { + foreach (IInitializable i in _initializers.OrderBy(i => i.priority)) { + Logger.log(Level.Info, Subsystem.ui, "Initializing {0} prority {1}".fmt(i.GetType().ToString(), i.priority)); + i.initialize(); + } + } + + private bool IsHidden(IShellModule module) { + var props = Configuration.get(); + string name = module.GetType().Name; + foreach (var p in props.module) { + if (p.name.ToLower() == name.ToLower()) { + return !p.visible; + } + } + return false; + } + + public void Dispose() { + foreach (IShellModule module in _modules.OrderBy(m => m.priority).Reverse()) { + module.Dispose(); + } + _modules.Clear(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/uicore/Shell/Undo/UndoModel.cs b/src/client/spark/uicore/Shell/Undo/UndoModel.cs new file mode 100644 index 000000000..0bc5a5b97 --- /dev/null +++ b/src/client/spark/uicore/Shell/Undo/UndoModel.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Input; +using mbts.ui.shell; + +namespace mbts.ui +{ + [Export(typeof(IUndoActions))] + public class UndoModel : IUndoActions + { + ObservableCollection _undo = new ObservableCollection(); + public ObservableCollection Items { get { return _undo; } } + + public IDisposable push(string title, Action undo) { + if (undo == null) return Disposable.Create(() => { }); + var item = new UndoItem(this, title, undo); + _undo.Insert(0, item); + if (_undo.Count > 10) { + _undo.Remove(_undo.Last()); + } + return item; + } + + public class UndoItem : IDisposable + { + private UndoModel _owner; + private Action _undo; + internal UndoItem(UndoModel owner, string name, Action undo) { + _owner = owner; + _undo = undo; + Name = name; + } + + public string Name { get; private set; } + public ICommand Execute { + get { + return new DelegateCommand((arg) => { + try { + _undo(); + } + catch (Exception e) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Failed to undo : {0} - {1}".fmt(Name, e.ToString())); + throw; + } + finally { + this.Dispose(); + } + }); + } + } + + public void Dispose() { + if (_owner._undo.Contains(this)) { + _owner._undo.Remove(this); + } + } + } + } + +} diff --git a/src/client/spark/uicore/Shell/ViewLocator.cs b/src/client/spark/uicore/Shell/ViewLocator.cs new file mode 100644 index 000000000..3c2e1dd22 --- /dev/null +++ b/src/client/spark/uicore/Shell/ViewLocator.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// All Views reachable through the IViewLocator must +// - implement IView +// - tagged with the ViewAttribute specifying the type they want to visualize + +namespace mbts.ui.shell +{ + public interface IView { object DataContext { get; set; } } + + [MetadataAttribute] + [AttributeUsage(AttributeTargets.Class, AllowMultiple=true)] + public class ViewAttribute : ExportAttribute + { + public ViewAttribute() : base(typeof(IView)) {} + public Type Model { get; set; } + } + + public interface IViewProps + { + Type[] Model { get; } + } + + [Export(typeof(IViewLocator))] + class ViewLocator : IViewLocator + { + Dictionary> _overrides = new Dictionary>(); + + [ImportMany] + ExportFactory[] Views { get; set; } + + private object create_view(T viewmodel) { + string type_name = typeof(T).Name; + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Creating view for {0}".fmt(type_name)); + + // Check for an override + Func factory; + if (_overrides.TryGetValue(typeof(T), out factory)) { + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Found OVERRIDE view for {0}".fmt(type_name)); + var result = factory(); + set_datacontext(viewmodel, result); + return result; + } + + foreach (var view in Views) { + if (view.Metadata.Model.Contains(typeof(T))) { + var result = view.CreateExport().Value; + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Found {0} to view {1}".fmt(result.GetType(), type_name)); + result.DataContext = viewmodel; + return result; + } + } + + Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Failed to find view for {0}".fmt(type_name)); + return null; + } + + private static void set_datacontext(T viewmodel, object result) { + // Use Duck typing to set the DataContext so Views don't have to be UIElement + if (result != null) { + var property = result.GetType().GetProperty("DataContext"); + if (property != null) { + property.SetValue(result, viewmodel); + } + } + } + + public IShellWindow window_for(T viewmodel) { + return create_view(viewmodel) as IShellWindow; + } + + public object view_for(T viewmodel) { + return create_view(viewmodel); + } + + public void set_override(Func factory) { + _overrides.Add(typeof(T), factory); + } + } +} diff --git a/src/client/spark/uicore/Shell/Workspaces/Tests/WorkspaceTests.cs b/src/client/spark/uicore/Shell/Workspaces/Tests/WorkspaceTests.cs new file mode 100644 index 000000000..1340ae004 --- /dev/null +++ b/src/client/spark/uicore/Shell/Workspaces/Tests/WorkspaceTests.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using NUnit.Framework; + +namespace mbts.ui.shell.tests +{ + [TestFixture] + class WorkspaceTests + { + [Test] + public void test_favorites() { + } + + [Test] + public void test_workspaces() { + } + } +} diff --git a/src/client/spark/uicore/Shell/Workspaces/WorkspaceViewModel.cs b/src/client/spark/uicore/Shell/Workspaces/WorkspaceViewModel.cs new file mode 100644 index 000000000..0b9369947 --- /dev/null +++ b/src/client/spark/uicore/Shell/Workspaces/WorkspaceViewModel.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui.shell +{ + public class WorkspaceViewModel : ViewModelBase + { + WorkspacesModel _parent; + public WorkspaceViewModel(WorkspacesModel parent, string name, WorkspaceDefinition definition) { + _parent = parent; + Name = name; + Definition = definition; + } + + public string Name { get; private set; } + public bool IsShared { get { return Definition.is_shared; } } + public object Icon { + get { return Icons.Window; } + } + internal WorkspaceDefinition Definition { get; private set; } + + public ICommand ActivateCommand { + get { + return new DelegateCommand(param => { + var unused = _parent.load_workspace(Definition, Name); + }); + } + } + + public ICommand DeleteCommand { + get { + return new DelegateCommand(param => { + _parent.delete_workspace(Name, Definition); + }); + } + } + } +} diff --git a/src/client/spark/uicore/Shell/Workspaces/WorkspacesModel.cs b/src/client/spark/uicore/Shell/Workspaces/WorkspacesModel.cs new file mode 100644 index 000000000..878739662 --- /dev/null +++ b/src/client/spark/uicore/Shell/Workspaces/WorkspacesModel.cs @@ -0,0 +1,265 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.ComponentModel.Composition; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; +using mbts.config; +using mbts.ui.native; +using mbts.ui.settings; +using mbts.utils; +using ProtoBuf; +using mbts.persist; + +namespace mbts.ui.shell +{ + [Export] + public class WorkspacesModel : ViewModelBaseWithValidation + { + internal const string WORKSPACE_NAMESPACE = "workspace"; + internal const string ACTIVE_WORKSPACE_PREFIX = "Where I left off on "; + public static string ACTIVE_WORKSPACE_NAME { get { return ACTIVE_WORKSPACE_PREFIX + Environment.MachineName; } } + + private ISettingsCollector _settings_collector; + private ISavedWindowFactory _window_restore; + private IWindowManager _wm; + private IPersist _public; + private IPersist _private; + private ObservableCollection _modules; + private bool _closing = false; + private ILauncher _launcher; + private IUndoActions _undo; + + [ImportingConstructor] + public WorkspacesModel(ISettingsCollector settings, ISavedWindowFactory window_restore, + IWindowManager windows, ObservableCollection modules, IPersist persist, + IUserPersist user_persist, ILauncher launcher, IUndoActions undo) { + _settings_collector = settings; + _window_restore = window_restore; + _public = persist; + _private = user_persist; + _wm = windows; + _modules = modules; + _launcher = launcher; + _undo = undo; + _launcher.closing += _launcher_closing; + Workspaces = new ObservableCollection(); + } + + public async Task init(string initial_workspace) { + // Load the named workspace if it exists + // If the named workspace is ACTIVE_WORKSPACE_NAME + // check the local disk before loading from the network in case there was an error saving + var my_workspaces = await _private.query(WORKSPACE_NAMESPACE, ".*"); + my_workspaces = my_workspaces.Concat(await _public.query(WORKSPACE_NAMESPACE, ".*")); + Workspaces.AddRange(my_workspaces.Where(x => !x.key.StartsWith(ACTIVE_WORKSPACE_PREFIX)).Select(x => new WorkspaceViewModel(this, x.key, x.value))); + save_workspace_periodically(); + + var to_load = my_workspaces.SingleOrDefault(r => r.key == initial_workspace); + if (initial_workspace == ACTIVE_WORKSPACE_NAME) { + var localws = load_local_workspace(); + if (localws != null) { + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Loading workspace from disk"); + await load_workspace(localws, position_shell: true); + return; + } + } + + if (to_load != null) { + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Loading initial workspace '{0}'".fmt(to_load.key)); + // Only load the launcher position if this is a private workspace + await load_workspace(to_load.value, to_load.key, undo:false, position_shell: !to_load.value.is_shared); + } + else { + // Show launcher at default position + Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Showing launcher without loading initial workspace."); + _launcher.set_position(null); + } + } + + public async void save_workspace_periodically() { + TimeSpan interval = TimeSpan.FromSeconds(Configuration.get().save_timer); + await Task.Delay(interval); + while (!_closing) { + var workspace = await get_workspace_async(); + await _private.set(WORKSPACE_NAMESPACE, ACTIVE_WORKSPACE_NAME, workspace); + await Task.Delay(interval); + } + } + + void _launcher_closing(CancelEventArgs obj) { + _closing = true; + var workspace = get_workspace(); + var task = _private.set(WORKSPACE_NAMESPACE, ACTIVE_WORKSPACE_NAME, workspace); + _wm.Windows.Clear(); + task.Wait(TimeSpan.FromSeconds(90)); + if (!task.IsCompleted) { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Failed to save workspace during UI shutdown"); + // The server is gone! Save the state to the local disk. + save_workspace_locally(workspace); + } + } + + #region Static local save methods + + private static string local_workspace_path() { + var system = Configuration.get(); + return @"{0}/{1}/{2}".fmt(system.installation_specific_data_path, WORKSPACE_NAMESPACE, "recover_workspace"); + } + private static void save_workspace_locally(WorkspaceDefinition workspace) { + string path = local_workspace_path(); + try { + string directory = Path.GetDirectoryName(path); + Directory.CreateDirectory(directory); + using (var file = File.OpenWrite(path)) { + ProtoBuf.Serializer.SerializeWithLengthPrefix(file, workspace, PrefixStyle.Fixed32); + } + } + catch { + Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "The settings server is gone and I can't write to disk either. Shell is not having a good day."); + } + } + private static WorkspaceDefinition load_local_workspace() { + string path = local_workspace_path(); + if (File.Exists(path)) { + WorkspaceDefinition def = null; + using (var file = File.OpenRead(path)) { + def = ProtoBuf.Serializer.DeserializeWithLengthPrefix(file, PrefixStyle.Fixed32); + } + File.Delete(path); + return def; + } + return null; + } + + #endregion + + // Collection of saved workspaces + public ObservableCollection Workspaces { get; private set; } + public event Action WorkspaceLoaded; + + WorkspaceDefinition get_workspace() { + WorkspaceDefinition workspace = new WorkspaceDefinition(); + workspace.windows = _settings_collector.get_window_state().ToList(); + workspace.modules = _settings_collector.get_module_state().ToList(); + workspace.launcher_state = _settings_collector.get_launcher_state(); + return workspace; + } + + async Task get_workspace_async() { + WorkspaceDefinition workspace = new WorkspaceDefinition(); + workspace.windows = new List(); + foreach (var w in _settings_collector.get_window_state()) { + workspace.windows.Add(w); + await Task.Yield(); + } + workspace.modules = new List(); + foreach (var m in _settings_collector.get_module_state()) { + workspace.modules.Add(m); + await Task.Yield(); + } + workspace.launcher_state = _settings_collector.get_launcher_state(); + return workspace; + } + + public void save_workspace(string name, bool persist=true, bool ispublic=false) { + WorkspaceDefinition workspace = get_workspace(); + workspace.is_shared = ispublic; + if (ispublic) { name += " (shared)"; } + + // Remove the old one if a workspace by this name exists already + var old = Workspaces.SingleOrDefault(w => w.Name == name && ispublic == w.IsShared); + if (old != null) { + Workspaces.Remove(old); + } + Workspaces.Add(new WorkspaceViewModel(this, name, workspace)); + + if (persist) { + (ispublic ? _public : _private).set(WORKSPACE_NAMESPACE, name, workspace); + } + } + + public async Task load_workspace(WorkspaceDefinition def, string name="", bool undo=true, bool position_shell=false) { + Logger.assert(def != null); + + if (undo && !string.IsNullOrEmpty(name)) { + var current_workspace = await get_workspace_async(); + _undo.push("Undo Load workspace '{0}'".fmt(name), async () => { + await load_workspace(current_workspace); + }); + } + + // Close all windows + _wm.Windows.Clear(); + + if (position_shell) { + _launcher.set_position(def.launcher_state); + } + + // Load the new workspace + if (def.modules != null) { + foreach (var settings in def.modules) { + if (settings.app_data.Length > 0) { + var module = _modules.SingleOrDefault(m => m.key() == settings.name); + if (module != null) { + module.load_state(new MemoryStream(settings.app_data)); + } + } + } + } + if (def.windows != null) { + foreach (var window in def.windows) { + var new_shell_window = await _window_restore.restore(window); + if (new_shell_window != null) { + _wm.Windows.Add(new_shell_window); + } + } + } + + // Notify workspace changed + if (WorkspaceLoaded != null) { + WorkspaceLoaded(name); + } + } + + public Task delete_workspace(string name, WorkspaceDefinition def) { + var to_remove = Workspaces.SingleOrDefault(x => x.Name == name && x.IsShared == def.is_shared); + if (to_remove != null) { + Logger.assert_d(def == null || to_remove.Definition == def); + Workspaces.Remove(to_remove); + _undo.push("Restore workspace: '{0}'".fmt(name), () => { + Workspaces.Add(new WorkspaceViewModel(this, name, def)); + (def.is_shared ? _public : _private).set(WORKSPACE_NAMESPACE, name, def); + }); + } + return (def.is_shared ? _public : _private).clear(WORKSPACE_NAMESPACE, name); + } + } + + // The serialized data for the Workspace + [ProtoContract(Name = "WorkspaceDefinition")] + public class WorkspaceDefinition + { + // Converted the protobuf type ShellSettings to c# + // Avoid re-using id: 1,3,4,5,6,7 + + [ProtoMember(2, IsRequired = false)] + public List windows { get; set; } + + [ProtoMember(9, IsRequired = false)] + public List modules { get; set; } + + [ProtoMember(8, IsRequired = false)] + public WindowPosition launcher_state { get; set; } + + [ProtoMember(10, IsRequired = false)] + public bool is_shared { get; set; } + + } +} diff --git a/src/client/spark/uicore/ShellInterface/ICloseable.cs b/src/client/spark/uicore/ShellInterface/ICloseable.cs new file mode 100644 index 000000000..fafb6e806 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/ICloseable.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + public interface ICloseable + { + event EventHandler CloseRequested; + void OnClose(); + } +} diff --git a/src/client/spark/uicore/ShellInterface/ILauncher.cs b/src/client/spark/uicore/ShellInterface/ILauncher.cs new file mode 100644 index 000000000..586cb3fba --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/ILauncher.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui.shell +{ + public interface ILauncher + { + WindowPosition get_position(); + void set_position(WindowPosition pos); + void show(); + event Action closing; + event Action shown; + bool is_visible { get; } + } +} diff --git a/src/client/spark/uicore/ShellInterface/IShellModule.cs b/src/client/spark/uicore/ShellInterface/IShellModule.cs new file mode 100644 index 000000000..772dac390 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IShellModule.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; +using System.Windows.Media; +using System.Threading.Tasks; + +namespace mbts.ui +{ + public interface IShellModule : IDisposable + { + ImageSource icon { get; } + string name { get; } + + // Load priority. Higher numbers are initialized later and show up further down in the UI. + int priority { get; } + + // An interface element which will be shown to the right + // of the main IShellModule entry to ask the user for details + // about how they want to interact with the app. + // Return null to indicate no ui needed + IShellWindow launch_ui { get; } + + // Called at startup before the UI is shown + // This is an opportunity for you to kick off background services + // or connect to network resources to prepare the module. + void load_state(Stream state = null); + + // Save any running state such as launched exes here. + void get_state(Stream save_here); + + // Called when the app is shutting down to save any shell-global state. + // Individual windows will have their own GetState called. + //void GetState(Stream save_here); + + // When the user clicks on the main entry in the shell this gets called. + // If your module has a launch_ui you should probably do nothing otherwise + // create and add your main window. + void start(); + + // When restoring a saved session the data returned from + // IShellWindow::GetState is passed back to the module here. + // Most apps will chose to re-create the window from that state. + Task create(Stream load_stream); + } +} diff --git a/src/client/spark/uicore/ShellInterface/IShellWidget.cs b/src/client/spark/uicore/ShellInterface/IShellWidget.cs new file mode 100644 index 000000000..33201993f --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IShellWidget.cs @@ -0,0 +1,21 @@ +using System.Windows; + +namespace mbts.ui +{ + + // IShellWidget is a tool for adding notifications and other things to the BTS Launcher bar + public interface IShellWidget + { + // Constructed by ImportingConstructor + // + + // When the user wants to add a new widget user_configure() is called + // The Wiget system expects this to show some UI and return a serializable object. + // If the user wants to change an existing widget user_configure is called with the existing configuration passed in. + object user_configure(object existing_config); + + // A configuration object created from user_configure() is passed in describing the state of the new object + UIElement create_instance(object config); + } + +} diff --git a/src/client/spark/uicore/ShellInterface/IShellWindow.cs b/src/client/spark/uicore/ShellInterface/IShellWindow.cs new file mode 100644 index 000000000..c5cbd2f23 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IShellWindow.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; +using System.Windows.Threading; +using mbts.ui.shell; +using mbts; + +namespace mbts.ui +{ + public interface IShellWindow : IDisposable + { + // Window title + string Title { get; set; } + // Call this callback if you set the title property so the shell knows to update the display. + event Action TitleChanged; + + // Window icon + ImageSource Icon { get; } + // Call this callback if you set the icon so the shell knows to update the display. + event Action IconChanged; + + // Each IShellWindow should have an owning module so the shell knows which + // module to ask to restore the window after app restart. + IShellModule Owner { get; set; } + + // Return the UI controls which will be displayed + ShellWindowUI GetContent(); + + // This is called when the application wants to save + // the current set of windows. Write enough information to the stream + // to uniquely identify this window. This stream will be handed back to + // IShellModule.Create when the app is restarted. + void GetState(Stream save_here); + } + + public class ShellWindowUI + { + object _content; + public ShellWindowUI(HandleRef handle) { _content = handle; } + public ShellWindowUI(UIElement element) { _content = element; } + + public HandleRef HWNDContent { + get { return (HandleRef)_content; } + } + + public UIElement Content { + get { return _content as UIElement; } + } + } + + // Marker Interface for Windows which we expect to use a lot of CPU time on their render thread + // These will be automatically moved to a background thread or out of process. + // Or maybe just not shown - that way we keep the app faster. + public interface ISlowWindow : IShellWindow { + void thread_init(); + } + + //Marker for a group of windows that all want to be on the same thread (inproc AW) + public interface ISharedWindow : ISlowWindow { + string thread_id { get; } + } + public interface ITabAffineWindow : IShellWindow + { + string tab_group { get; } + } + + public interface IShellMenu + { + void opening(); + void closing(); + } + + public interface IShellThreadFactory + { + Dispatcher get_dispatcher(string id); + } + + // Store the window position until the Window is realized + public static class ShellWindowExtensions + { + private static Dictionary _pos = new Dictionary(); + public static WindowPosition start_position(this IShellWindow window) { + WindowPosition result; + lock (_pos) { + if (_pos.TryGetValue(window.GetHashCode(), out result)) { + _pos.Remove(window.GetHashCode()); + return result; + } + } + return null; + } + + public static void set_start_position(this IShellWindow window, WindowPosition pos) { + lock (_pos) { + _pos[window.GetHashCode()] = pos; + } + } + } +} diff --git a/src/client/spark/uicore/ShellInterface/IShellWindowMigrationRule.cs b/src/client/spark/uicore/ShellInterface/IShellWindowMigrationRule.cs new file mode 100644 index 000000000..a82884862 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IShellWindowMigrationRule.cs @@ -0,0 +1,10 @@ +using System; +using mbts.ui.shell; + +namespace mbts.ui +{ + public interface IShellWindowMigrationRule + { + bool apply(ref WindowState state); + } +} diff --git a/src/client/spark/uicore/ShellInterface/ITimer.cs b/src/client/spark/uicore/ShellInterface/ITimer.cs new file mode 100644 index 000000000..0d2078ef8 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/ITimer.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace mbts.ui +{ + public interface ITimer + { + event Action Tick; + } +} diff --git a/src/client/spark/uicore/ShellInterface/IUndoActions.cs b/src/client/spark/uicore/ShellInterface/IUndoActions.cs new file mode 100644 index 000000000..c5af3abff --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IUndoActions.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + // See UndoModel.cs + public interface IUndoActions + { + IDisposable push(string title, Action undo); + } +} diff --git a/src/client/spark/uicore/ShellInterface/IViewLocator.cs b/src/client/spark/uicore/ShellInterface/IViewLocator.cs new file mode 100644 index 000000000..f1c7139d4 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IViewLocator.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.ComponentModel.Composition.Hosting; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Media; +using System.Windows.Threading; + +namespace mbts.ui +{ + // Allows models to locate an appropriate view + // All Views reachable through the IViewLocator must implement IView and be tagged with the ViewAttribute specifying what they want to visualize + public interface IViewLocator + { + IShellWindow window_for(T model); + object view_for(T model); + void set_override(Func factory); + } +} diff --git a/src/client/spark/uicore/ShellInterface/IWindowManager.cs b/src/client/spark/uicore/ShellInterface/IWindowManager.cs new file mode 100644 index 000000000..904d2efae --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IWindowManager.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.ObjectModel; + +namespace mbts.ui +{ + public interface IWindowManager + { + ObservableCollection Windows { get; } + + // Bring to front of window stack and z-order + void MakeVisible(IShellWindow window); + void AlertWindow(IShellWindow window); + bool IsVisible(IShellWindow window); + } + + public interface IBrowserWindowManager + { + ObservableCollection Pages { get; } + IShellWindow create_hidden(Uri uri); + } +} diff --git a/src/client/spark/uicore/ShellInterface/IWindowsInterop.cs b/src/client/spark/uicore/ShellInterface/IWindowsInterop.cs new file mode 100644 index 000000000..de8cc6abb --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/IWindowsInterop.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using mbts.ui.shell; + +namespace mbts.ui +{ + /// + /// This interface allows the particular shell implementation to define windows specific implementations of common activities in a windowing system. + /// For example a floating window might implement AlertWindow by flashing the tasbar icon while a dock might flash the tab red. + /// + public interface IWindowsInterop + { + void MakeVisible(IShellWindow window); + void AlertWindow(IShellWindow window); + WindowPosition GetPosition(IShellWindow window); + bool IsVisible(IShellWindow window); + void PinWindow(IShellWindow window); + } +} diff --git a/src/client/spark/uicore/ShellInterface/ShellModelExtensions.cs b/src/client/spark/uicore/ShellInterface/ShellModelExtensions.cs new file mode 100644 index 000000000..8027b31ca --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/ShellModelExtensions.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui.shell +{ + public static class ShellModelExtensions + { + internal static string key(this IShellModule module) { return _module_type_key(module.GetType()); } + private static string _module_type_key(Type module_type) { return module_type.ToString(); } + public static bool is_owner(this WindowState state) where T : IShellModule { return _module_type_key(typeof(T)) == state.owner; } + } +} diff --git a/src/client/spark/uicore/ShellInterface/ShellSerializationHeader.cs b/src/client/spark/uicore/ShellInterface/ShellSerializationHeader.cs new file mode 100644 index 000000000..dbae726f7 --- /dev/null +++ b/src/client/spark/uicore/ShellInterface/ShellSerializationHeader.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ProtoBuf; + +namespace mbts.ui +{ + // A convenient type which can be used to disambiguate IShellWindow saved data + // To use this serialize it first into your save state stream + // followed by an instance specific data type + [ProtoContract] + public class ShellSerializationHeader + { + [ProtoMember(1)] + public int version { get; set; } + [ProtoMember(2)] + public string name { get; set; } + } +} diff --git a/src/client/spark/uicore/ShellSettings.proto b/src/client/spark/uicore/ShellSettings.proto new file mode 100644 index 000000000..e27510621 --- /dev/null +++ b/src/client/spark/uicore/ShellSettings.proto @@ -0,0 +1,67 @@ + +// todo: MAKE THIS INTO CODE + +syntax='proto2'; + +package mbts.ui.shell; + +enum DockState { + FLOATING = 1; + TOP = 2; + BOTTOM = 3; + LEFT = 4; + RIGHT = 5; +} + +message WindowPosition +{ + optional int32 width = 3; + optional int32 height = 4; + optional int32 left = 5; + optional int32 top = 6; + optional bool is_maximized = 7; + optional string host_id = 8; + optional int32 tab_index = 9; + + // Main window related + optional bool horizontal = 100 [default = true]; + optional bool show_text = 101 [default = true]; + optional bool always_on_top = 102 [default = false]; + optional DockState dock = 103 [default = FLOATING]; +} + +message WindowState +{ + optional string owner = 1; + optional bytes app_data = 2; + + //optional bool is_open = 3 [default = true]; + //optional bool is_favorite = 4; + //optional string title = 5; + + //optional string id = 6; + // optional bool is_loaded = 7 [default = false]; + optional WindowPosition position = 8; + + optional string title = 9; +} + +message ModuleState +{ + optional string name = 1; + optional bytes app_data = 2; +} + +message EXEShellSettings +{ + repeated string running = 1; +} + +message AdminShellSettings +{ + optional EXEShellSettings shell_settings = 1; + repeated string rec_report_providers_and_args = 2; + repeated string trade_migration_providers_and_args = 3; + optional bool trade_migration_add_missing_data_is_checked = 4 [default = true]; +} + diff --git a/src/client/spark/uicore/Utility/AsyncCommand.cs b/src/client/spark/uicore/Utility/AsyncCommand.cs new file mode 100644 index 000000000..922badb02 --- /dev/null +++ b/src/client/spark/uicore/Utility/AsyncCommand.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Input; +using System.Windows.Threading; + +namespace mbts.ui +{ + public interface IAsyncCommand : ICommand, IDisposable + { + event Action ExecutingBegin; + event Action ExecutingEnd; + } + + public class AsyncCommand : DelegateCommand, IAsyncCommand + { + public AsyncCommand(Func get_task) : this(get_task, null) { } + public AsyncCommand(Func get_task, Func can_execute) { + _get_task = get_task; + _can_execute = can_execute == null ? new Func(p => !_is_executing) : new Func(p => !_is_executing && can_execute(p)); + _execute = _execute_async; + } + + private readonly Func _get_task; + + private bool _is_executing; + private void _set_is_executing(bool is_executing) { + _is_executing = is_executing; + RaiseCanExecuteChanged(); + if (is_executing) { + if (ExecutingEnd != null) + ExecutingEnd(); + } else if (ExecutingBegin != null) + ExecutingBegin(); + } + + private IDisposable _dispose_task; + private async void _execute_async(T parameter) { + _set_is_executing(true); + var task = _get_task(parameter); + if (task != null) { + if (task.Status == TaskStatus.Created) + task.Start(); + await task; + } + _set_is_executing(false); + } + + public event Action ExecutingBegin, ExecutingEnd; + + public void Dispose() { + Disposable.dispose(ref _dispose_task); + } + } + + public class AsyncCommand : AsyncCommand + { + public AsyncCommand(Func get_task) : base(_ => get_task()) { } + public AsyncCommand(Func get_task, Func can_execute) : base(_ => get_task(), _ => can_execute()) { } + public AsyncCommand(Func get_task, Func can_execute) : base(_ => get_task(), can_execute) { } + public AsyncCommand(Func get_task) : base(get_task, null) { } + public AsyncCommand(Func get_task, Func can_execute) : base(get_task, can_execute) { } + } +} diff --git a/src/client/spark/uicore/Utility/DelegateCommand.cs b/src/client/spark/uicore/Utility/DelegateCommand.cs new file mode 100644 index 000000000..6cc6560dd --- /dev/null +++ b/src/client/spark/uicore/Utility/DelegateCommand.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows.Input; + +namespace mbts.ui +{ + public interface IRaiseCanExecuteChangedCommand : ICommand + { + void RaiseCanExecuteChanged(); + } + + public class DelegateCommand : ICommand, IRaiseCanExecuteChangedCommand + { + protected Func _can_execute; + protected Action _execute; + + protected DelegateCommand() { } + public DelegateCommand(Action execute, Func can_execute) { + _execute = execute; + _can_execute = can_execute; + } + + public DelegateCommand(Action execute) { + _execute = execute; + } + + public void RaiseCanExecuteChanged() { + if (CanExecuteChanged != null) { + CanExecuteChanged(this, null); + } + } + + T try_convert(object parameter) { + if (parameter == null) { + return default(T); + } + if (typeof(T).IsPrimitive) { + return (T)Convert.ChangeType(parameter, typeof(T)); + } + else if (typeof(T).IsAssignableFrom(parameter.GetType())) { + return (T)parameter; + } + else if (typeof(T).IsEnum && parameter is string) { + return (T)Enum.Parse(typeof(T), parameter.ToString()); + } + return default(T); + } + + public bool CanExecute(object parameter) { + if (_can_execute == null) + return true; + else + return _can_execute(try_convert(parameter)); + } + + public event EventHandler CanExecuteChanged; + + public void Execute(object parameter) { + _execute(try_convert(parameter)); + } + } + + //public class DelegateConvertCommand : ICommand, IRaiseCanExecuteChangedCommand where T : struct + //{ + // Func _can_execute; + // Action _execute; + //} + + public class DelegateCommand : DelegateCommand + { + public DelegateCommand(Action execute) : this(_ => execute()) { } + public DelegateCommand(Action execute, Func can_execute) : this(_ => execute(), _ => can_execute()) { } + public DelegateCommand(Action execute) : base(execute) { } + public DelegateCommand(Action execute, Func can_execute) : base(execute, can_execute) { } + } +} diff --git a/src/client/spark/uicore/Utility/DispatcherHelper.cs b/src/client/spark/uicore/Utility/DispatcherHelper.cs new file mode 100644 index 000000000..e3f578df4 --- /dev/null +++ b/src/client/spark/uicore/Utility/DispatcherHelper.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace System.Windows.Threading +{ + public static class DispatcherHelper + { + #region Easy Invoke + + public static void Invoke(this Dispatcher d, Action action) { + d.Invoke(action); + } + + public static void BeginInvoke(this Dispatcher d, Action action) { + d.BeginInvoke(action); + } + + public static void Invoke(this Dispatcher d, Action action, T arg1) { + d.Invoke(action, arg1); + } + + public static void Invoke(this Dispatcher d, Action action, T1 arg1, T2 arg2) { + d.Invoke(action, arg1, arg2); + } + + public static void Invoke(this Dispatcher d, Action action, T1 arg1, T2 arg2, T3 arg3) { + d.Invoke(action, arg1, arg2, arg3); + } + + public static void Invoke(this Dispatcher d, Action action, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { + d.Invoke(action, arg1, arg2, arg3, arg4); + } + + #endregion + + #region In + + public static void In(this Dispatcher d, TimeSpan time, Action action) { + DispatcherTimer dt = new DispatcherTimer(); + dt.Interval = time; + dt.Tick += new EventHandler((sender, args) => { + dt.Stop(); + action(); + }); + dt.Start(); + } + + public static void In(this Dispatcher d, TimeSpan time, Action action, T1 arg1) { + DispatcherTimer dt = new DispatcherTimer(); + dt.Interval = time; + dt.Tick += new EventHandler((sender, args) => { + dt.Stop(); + action(arg1); + }); + dt.Start(); + } + + public static void In(this Dispatcher d, TimeSpan time, Action action, T1 arg1, T2 arg2) { + DispatcherTimer dt = new DispatcherTimer(); + dt.Interval = time; + dt.Tick += new EventHandler((sender, args) => { + dt.Stop(); + action(arg1, arg2); + }); + dt.Start(); + } + + public static void In(this Dispatcher d, TimeSpan time, Action action, T1 arg1, T2 arg2, T3 arg3) { + DispatcherTimer dt = new DispatcherTimer(); + dt.Interval = time; + dt.Tick += new EventHandler((sender, args) => { + dt.Stop(); + action(arg1, arg2, arg3); + }); + dt.Start(); + } + + public static void In(this Dispatcher d, TimeSpan time, Action action, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { + DispatcherTimer dt = new DispatcherTimer(); + dt.Interval = time; + dt.Tick += new EventHandler((sender, args) => { + dt.Stop(); + action(arg1, arg2, arg3, arg4); + }); + dt.Start(); + } + + #endregion + + public static void PushFrame(this Task t) { + DispatcherFrame frame = new DispatcherFrame(); + t.ContinueWith(_ => frame.Continue = true); + Dispatcher.PushFrame(frame); + } + } +} diff --git a/src/client/spark/uicore/Utility/ExpirationFormatter.cs b/src/client/spark/uicore/Utility/ExpirationFormatter.cs new file mode 100644 index 000000000..28afb08a1 --- /dev/null +++ b/src/client/spark/uicore/Utility/ExpirationFormatter.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.security_model; + +namespace mbts.ui.utility +{ + public class ExpirationFormatter + { + private static class DateFormatter + { + private static string[] month_codes = new string[] { "F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z" }; + private static string[] month_three_letters = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + + public static string format_condensed(DateTime date, bool use_month_code, bool show_year) + { + return String.Format("{0}{1}{2}", date.Day, month_codes[date.Month - 1], show_year ? (date.Year - 2000).ToString() : String.Empty); + } + + public static string format(DateTime date, bool use_month_code, bool show_day) { + string month_text = use_month_code ? "{0}{1:00}".fmt(month_codes[date.Month - 1], date.Year - 2000) : "{0} {1:00}".fmt(month_three_letters[date.Month - 1], date.Year - 2000); + return show_day ? "{0} {1}".fmt(date.Day, month_text) : month_text; + } + + public static string format_standard(DateTime date) { return "{0} {1} {2:00}".fmt(date.Day, month_three_letters[date.Month - 1], date.Year - 2000); } + public static string format_coded(DateTime date) { return "{0} {1}{2:00}".fmt(date.Day, month_codes[date.Month - 1], date.Year - 2000); } + public static string format_coded_hide_day(DateTime date) { return "{0}{1}".fmt(month_codes[date.Month - 1], date.Year - 2000); } + + public static DateTime parse_standard(string date_text) { + string[] split = date_text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + int year = 0; + int month = Array.IndexOf(month_three_letters, split[1]) + 1; + int day = 0; + int.TryParse(split[2], out year); + int.TryParse(split[0], out day); + return new DateTime(year + 2000, month, day); + } + + public static DateTime parse_coded(string date_text) { + string[] split = date_text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + string year_text = split[1].Substring(1); + string month_text = split[1].Substring(0, 1); + string day_text = split[0]; + int month = Array.IndexOf(month_codes, month_text) + 1; + int day, year; + int.TryParse(year_text, out year); + int.TryParse(day_text, out day); + return new DateTime(year + 2000, month, day); + } + + public static DateTime parse_coded_hide_day(string date_text) { + string year_text = date_text.Substring(1); + string month_text = date_text.Substring(0, 1); + int month = Array.IndexOf(month_codes, month_text) + 1; + int year; + int.TryParse(year_text, out year); + return new DateTime(year + 2000, month, 0); + } + } + + private static IDictionary> _offset_map; + + static ExpirationFormatter() + { + try + { + _offset_map = new Dictionary>(); + _offset_map[SecurityType.type.OPTION] = new Dictionary(); + _offset_map[SecurityType.type.FUTURE] = new Dictionary(); + + bts.config.ExpirationDisplayOffset offset_list = mbts.config.Configuration.get(); + foreach (bts.config.ExpirationDisplayOffsetEntry e in offset_list.entries) + { + string security_name = e.security_name; + string security_type_text = e.security_type; + bts.security_model.SecurityType.type security_type = bts.security_model.SecurityType.type.UNSET; + Enum.TryParse(security_type_text, true, out security_type); + if (security_type == bts.security_model.SecurityType.type.OPTION || security_type == bts.security_model.SecurityType.type.FUTURE) + _offset_map[security_type][security_name] = e; + } + } + catch (Exception ex) + { + mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, String.Format("Exception message = {0}", ex.Message)); + } + } + + private static bts.config.ExpirationDisplayOffsetEntry _get_offset_entry(bts.security_model.SecurityType.type security_type, string security_name) + { + bts.config.ExpirationDisplayOffsetEntry rv = null; + IDictionary this_security_type_map = null; + if (_offset_map.TryGetValue(security_type, out this_security_type_map)) + if (this_security_type_map.TryGetValue(security_name, out rv)) + return rv; + return rv; + } + + public static DateTime convert_real_to_mapped(SecurityType.type security_type, string security_name, DateTime security_expiration) + { + bts.config.ExpirationDisplayOffsetEntry offset_entry = _get_offset_entry(security_type, security_name); + DateTime rv = security_expiration; + if (offset_entry != null) + { + if (offset_entry.addition_type == bts.config.ExpirationOffsetType.type.Month) + rv = security_expiration.AddMonths(offset_entry.addition_count); + else if (offset_entry.addition_type == bts.config.ExpirationOffsetType.type.MonthMoveToStart) + { + rv = security_expiration.AddMonths(offset_entry.addition_count); + rv = new DateTime(rv.Year, rv.Month, 1); + } + } + return rv; + } + + public static string format_expiration_standard(SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration) { + return format_expiration_standard(security_type, security_name, security_expiration, map_expiration, false); + } + + public static string format_expiration_standard(SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration, bool use_month_code) { + return format_expiration_standard(security_type, security_name, security_expiration, map_expiration, use_month_code, true); + } + + public static string format_expiration_standard(SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration, bool use_month_code, bool show_day) { + DateTime mapped_expiration = map_expiration ? convert_real_to_mapped(security_type, security_name, security_expiration) : security_expiration; + return DateFormatter.format(mapped_expiration, use_month_code, show_day); + } + + public static string format_symbol_expiration_standard (SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration) { + return format_symbol_expiration_standard(security_type, security_name, security_expiration, map_expiration, false, false, true); + } + + public static string format_symbol_expiration_standard (SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration, bool show_security_type) { + return format_symbol_expiration_standard(security_type, security_name, security_expiration, map_expiration, show_security_type, false, true); + } + + public static string format_symbol_expiration_standard(SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration, bool show_security_type, bool use_month_code) { + return format_symbol_expiration_standard(security_type, security_name, security_expiration, map_expiration, show_security_type, use_month_code, true); + } + + public static string format_symbol_expiration_standard (SecurityType.type security_type, string security_name, DateTime security_expiration, bool map_expiration, bool show_security_type, bool use_month_code, bool show_day) { + string exp_text = format_expiration_standard(security_type, security_name, security_expiration, map_expiration, use_month_code, show_day); + return !show_security_type ? String.Format("{0} {1}", security_name, exp_text) : String.Format("{0} {1} {2}", security_type.ToString().ToUpper(), security_name, exp_text); + } + + public static string format_option_expiration_condensed(string option_name, DateTime option_expiration, bool map_expiration, bool show_symbol_name, bool show_year) + { + DateTime mapped_expiration = map_expiration ? convert_real_to_mapped(SecurityType.type.OPTION, option_name, option_expiration) : option_expiration; + return String.Format("{0}{1}", show_symbol_name ? option_name : String.Empty, DateFormatter.format_condensed(mapped_expiration, true, show_year)); + } + + public static DateTime parse_standard_formatted_expiration(SecurityType.type security_type, string security_name, string security_expiration) { return DateFormatter.parse_standard(security_expiration); } + } +} diff --git a/src/client/spark/uicore/Utility/IRequestViewClose.cs b/src/client/spark/uicore/Utility/IRequestViewClose.cs new file mode 100644 index 000000000..32d55d8f9 --- /dev/null +++ b/src/client/spark/uicore/Utility/IRequestViewClose.cs @@ -0,0 +1,14 @@ +using System; + +namespace mbts.ui +{ + public interface IRequestViewClose + { + event EventHandler RequestClose; + } + + public interface ICanCloseView + { + void request_close(); + } +} diff --git a/src/client/spark/uicore/Utility/ObservableAppendCollection.cs b/src/client/spark/uicore/Utility/ObservableAppendCollection.cs new file mode 100644 index 000000000..3cdfee6bd --- /dev/null +++ b/src/client/spark/uicore/Utility/ObservableAppendCollection.cs @@ -0,0 +1,178 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui.utility +{ + + /* + * This collection does *not* handle the case where the user of the outter collection 'moves' an item into the range owned by the inner collection. + * Only use that if you're *really sure* you don't need that behavior. + */ + public class ObservableAppendCollection : ObservableCollection + { + List _prefix = new List(); + List _suffix = new List(); + ObservableCollection _inner; + bool _suspend_update = false; + + public ObservableAppendCollection(ObservableCollection inner, params T[] front_append_items) + : this(inner, front_append_items, Enumerable.Empty()) { } + + public ObservableAppendCollection(ObservableCollection inner, IEnumerable front_append_items, IEnumerable back_append_items) { + foreach (var item in front_append_items.Reverse()) + insert_front(item); + this.AddRange(inner); + inner.CollectionChanged += Inner_CollectionChanged; + _inner = inner; + foreach (var item in back_append_items) + push_back(item); + // Note: after we change we can use innser.SyncWith(this.skip/take(prefix_len())) + } + + int prefix { get { return _prefix.Count; } } + int suffix { get { return _suffix.Count; } } + + //protected override void InsertItem(int index, T item) { + // if (index <= prefix || index >= (Count - prefix)) { + // base.InsertItem(index, item); + // } + //} + protected override void MoveItem(int oldIndex, int newIndex) { + if ((oldIndex < prefix && newIndex < prefix) || + (oldIndex > Count - prefix && newIndex > Count - prefix) || + (applies_to_internal(oldIndex) && applies_to_internal(newIndex))) { + base.MoveItem(oldIndex, newIndex); + } + else { + throw new ArgumentException("Invalid move"); + } + } + public void reset_front(IEnumerable items) { + clear_front(); + //reverse to preserve order + items.Reverse().ForEach(insert_front); + } + public void reset_back(IEnumerable items) { + clear_back(); + items.ForEach(push_back); + } + public void clear_front() { + for (int i = 0; i < prefix; i++) + RemoveAt(0); + _prefix.Clear(); + } + public void clear_back() { + for (int i = 0; i < suffix; i++) + RemoveAt(Count - 1); + _suffix.Clear(); + } + public void insert_front(T item) { + _prefix.Add(item); + InsertItem(0, item); + } + public void push_back(T item) { + _suffix.Add(item); + Add(item); + } + public void clear_inner() { + _inner.Clear(); + } + + private void sync_back() { + try { + _suspend_update = true; + _inner.sync_with(this.Skip(prefix).Take(Count - prefix - suffix)); + } + finally { _suspend_update = false; } + } + + private void Inner_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { + if (_suspend_update) return; + var temp = _inner; + _inner = null; + try { + switch (e.Action) { + case NotifyCollectionChangedAction.Add: + int start = e.NewStartingIndex + prefix; + foreach (var i in e.NewItems) { + base.InsertItem(start, (T)i); + start++; + } + break; + case NotifyCollectionChangedAction.Remove: + foreach (var i in e.OldItems) { + base.RemoveAt(e.OldStartingIndex + prefix); + } + break; + case NotifyCollectionChangedAction.Reset: + while (Count > prefix + suffix) { + RemoveAt(prefix); + } + break; + case NotifyCollectionChangedAction.Move: + MoveItem(e.OldStartingIndex + prefix, e.NewStartingIndex + prefix); + break; + } + } + finally { _inner = temp; } + } + protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { + base.OnCollectionChanged(e); + if (_inner != null && (applies_to_internal(e.NewStartingIndex) || applies_to_internal(e.OldStartingIndex))) { + sync_back(); + } + } + + private bool applies_to_internal(int index) { + return index >= prefix && index <= Count - prefix; + } + } +} +namespace mbts.ui.utility.test +{ + + [TestFixture] + class TestObservableAppendCollection + { + + [Test] + public void test_append() { + ObservableCollection inner = new ObservableCollection(Enumerable.Range(100, 5)); + var outter = new ObservableAppendCollection(inner); + + Assert.That(outter.Count == inner.Count); + inner.Add(106); + Assert.That(outter.Count == inner.Count); + Assert.That(outter.SequenceEqual(inner)); + + outter.push_back(200); + Assert.That(outter.Count == inner.Count + 1); + Assert.That(inner.SequenceEqual(outter.Take(inner.Count))); + outter.insert_front(10); + Assert.That(outter.Count == inner.Count + 2); + Assert.That(outter.First() == 10); + Assert.That(outter.Last() == 200); + + inner.Add(107); + Assert.That(outter.Count == inner.Count + 2); + Assert.That(outter.First() == 10); + Assert.That(outter.Last() == 200); + Assert.That(outter.Contains(107)); + Assert.That(outter[outter.Count - 2] == 107); + outter.Remove(107); + Assert.That(!outter.Contains(107)); + Assert.That(!inner.Contains(107)); + outter.Remove(100); + Assert.That(!outter.Contains(100)); + Assert.That(!inner.Contains(100)); + + } + + } +} \ No newline at end of file diff --git a/src/client/spark/uicore/Utility/ObservableAutoWrapper.cs b/src/client/spark/uicore/Utility/ObservableAutoWrapper.cs new file mode 100644 index 000000000..e279974af --- /dev/null +++ b/src/client/spark/uicore/Utility/ObservableAutoWrapper.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Specialized; +using System.Collections.ObjectModel; +using System.Linq; +using System.Collections.Generic; +using NUnit.Framework; + +namespace mbts.ui.utility +{ + /// + /// The sole purpose of this class is to offer a less verbose alternative to + /// "new ObservableAutoWrapper(doodi, poodi)" + /// when the generic types are implicit + /// + public static class ObservableAutoWrapper + { + public static ObservableAutoWrapper Create(ObservableCollection models, Func converter) { + return new ObservableAutoWrapper(models, converter); + } + } + + public class ObservableAutoWrapper : ObservableCollection + { + private static Func _get_default_converter() { + var constructor = System.Reflection.ReflectionHelper.FindApplicableConstructor(typeof(View), typeof(Model)); + if (constructor == null) + throw new InvalidOperationException("[{0}] {1} type does not have a public constructor({0})".fmt(typeof(ObservableAutoWrapper), typeof(View), typeof(Model))); + return model => (View)constructor.Invoke(new object[] { model }); + } + + Func _converter; + ICollection _models; + + public ObservableAutoWrapper(INotifyCollectionChanged models) : this(models, _get_default_converter()) { } + + public ObservableAutoWrapper(INotifyCollectionChanged models, Func converter) { + _converter = converter; + _models = models as ICollection; + if (_models == null) { + throw new ArgumentException("models must be ICollection"); + } + models.CollectionChanged += new NotifyCollectionChangedEventHandler(model_CollectionChanged); + CopyItems(); + } + + public ObservableAutoWrapper(ObservableCollection models, Func converter) + : base() + { + _converter = converter; + _models = models; + models.CollectionChanged += new NotifyCollectionChangedEventHandler(model_CollectionChanged); + CopyItems(); + } + + public event Action ViewCreated; + public event Action ViewDestroyed; + + void model_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + switch (e.Action) + { + case NotifyCollectionChangedAction.Add: + int start = e.NewStartingIndex; + foreach (Model m in e.NewItems) + { + View v = Convert(m); + base.InsertItem(start, v); + start++; + } + break; + case NotifyCollectionChangedAction.Move: + base.Move(e.OldStartingIndex, e.NewStartingIndex); + break; + case NotifyCollectionChangedAction.Remove: + for (int x = 0; x < e.OldItems.Count; x++) + { + View v = this[e.OldStartingIndex]; + this.RemoveAt(e.OldStartingIndex); + if (ViewDestroyed != null) { + ViewDestroyed(v); + } + } + break; + case NotifyCollectionChangedAction.Replace: + start = e.NewStartingIndex; + foreach (Model m in e.NewItems) + { + var old = this[start]; + this[start] = Convert(m); + if (ViewDestroyed != null) ViewDestroyed(old); + start++; + } + break; + case NotifyCollectionChangedAction.Reset: + var old_views = this.Items.ToArray(); + this.Clear(); + foreach (View v in old_views) { + if (ViewDestroyed != null) ViewDestroyed(v); + } + CopyItems(); + break; + } + + } + + private View Convert(Model m) + { + View v = _converter(m); + if (ViewCreated != null) + { + ViewCreated(v, m); + } + return v; + } + + private void CopyItems() + { + foreach (Model m in _models) + { + this.Add(Convert(m)); + } + } + } +} + +namespace mbts.ui.utility.test +{ + + [TestFixture] + class TestObservableAutoWrapper + { + + class Model + { + public string Name { get; set; } + public override string ToString() { + return Name; + } + } + class ViewModel + { + private Model _model; + public ViewModel(Model m) { _model = m; } + public override string ToString() { + return _model.Name; + } + } + + [Test] + public void Test1() { + ObservableCollection models = new ObservableCollection(); + models.Add(new Model() { Name = "Alice" }); + Model bob; + models.Add(bob = new Model() { Name = "Bob" }); + + ObservableAutoWrapper views = new ObservableAutoWrapper(models, (m) => new ViewModel(m)); + + IsEqual(models, views); + + models.Add(new Model() { Name = "Charlotte" }); + + IsEqual(models, views); + + models.Remove(bob); + IsEqual(models, views); + + models.Insert(0, bob); + IsEqual(models, views); + + models.Move(0, 1); + IsEqual(models, views); + + models.RemoveAt(0); + IsEqual(models, views); + + models[0] = new Model() { Name = "Doug" }; + models.Insert(0, bob); + IsEqual(models, views); + + } + + static bool IsEqual(IEnumerable ms, IEnumerable vs) { + string[] a = ms.Select(i => i.ToString()).ToArray(); + string[] b = vs.Select(i => i.ToString()).ToArray(); + + Assert.AreEqual(a.Length, b.Length); + for (int x = 0; x < a.Length; x++) { + Assert.AreEqual(a[x], b[x]); + } + return true; + } + } + +} \ No newline at end of file diff --git a/src/client/spark/uicore/Utility/ObservableCollectionEx.cs b/src/client/spark/uicore/Utility/ObservableCollectionEx.cs new file mode 100644 index 000000000..e89dd1606 --- /dev/null +++ b/src/client/spark/uicore/Utility/ObservableCollectionEx.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; + +namespace mbts.collections +{ + public interface IObservableCollectionEx : IList, ICollection, IEnumerable, INotifyCollectionChanged + { + void SetItems(IEnumerable items); + } + + public interface IObservableCollectionEx : IList, ICollection, IList, ICollection, IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable, INotifyCollectionChanged + { + void SetItems(IEnumerable items); + void AddRange(IEnumerable items); + } + + public class ObservableCollectionEx : ObservableCollection, IObservableCollectionEx, IObservableCollectionEx + { + public ObservableCollectionEx() { } + + public ObservableCollectionEx(IEnumerable items) { + using (quiet_change()) foreach (var item in items) Add(item); + } + + private const string CountString = "Count"; + // This must agree with Binding.IndexerName. + private const string IndexerName = "Item[]"; + private bool _events_suspend; + + private IDisposable quiet_change() { + if (_events_suspend) throw new InvalidOperationException("Events are already suspended."); + _events_suspend = true; + return Disposable.Create(() => _events_suspend = false); + } + + private void _fire_events(NotifyCollectionChangedEventArgs e) { + base.OnPropertyChanged(new PropertyChangedEventArgs(CountString)); + base.OnPropertyChanged(new PropertyChangedEventArgs(IndexerName)); + base.OnCollectionChanged(e); + } + + protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (!_events_suspend) base.OnCollectionChanged(e); } + + public void SetItems(IEnumerable items) { + base.ClearItems(); + this.AddRange(items); + } + + public void AddRange(IEnumerable items) { + int starting_index = Count; + using (quiet_change()) foreach (var item in items) base.Add(item); + _fire_events(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, items.ToList(), starting_index)); + } + + public void SetItems(IEnumerable items) { SetItems(items.Cast()); } + } +} \ No newline at end of file diff --git a/src/client/spark/uicore/Utility/ObservableEditableCollection.cs b/src/client/spark/uicore/Utility/ObservableEditableCollection.cs new file mode 100644 index 000000000..e2682bb5b --- /dev/null +++ b/src/client/spark/uicore/Utility/ObservableEditableCollection.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Input; + +namespace mbts.ui.utility +{ + public class ObservableEditableCollection : ObservableCollection where T : new() + { + public ObservableEditableCollection(IEnumerable items) : base(items) { _init(); } + public ObservableEditableCollection(params T[] items) : base(items) { _init(); } + private void _init() { + AddItemCommand = new DelegateCommand(() => Add(new T())); + RemoveItemCommand = new DelegateCommand(item => Remove(item)); + } + + public ICommand AddItemCommand { get; private set; } + public ICommand RemoveItemCommand { get; private set; } + } +} \ No newline at end of file diff --git a/src/client/spark/uicore/Utility/ObservableFilter.cs b/src/client/spark/uicore/Utility/ObservableFilter.cs new file mode 100644 index 000000000..16e6d089a --- /dev/null +++ b/src/client/spark/uicore/Utility/ObservableFilter.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Linq; + +namespace mbts.ui.utility +{ + // Fitler over an observable collection + public class ObservableFilterCollection : ObservableCollection + { + readonly ObservableCollection _inner; + readonly Func _predicate; + + public ObservableFilterCollection(ObservableCollection inner, Func predicate) { + _predicate = predicate; + _inner = inner; + this.AddRange(inner.Where(predicate)); + inner.CollectionChanged += _inner_CollectionChanged; + } + + private void _inner_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { trigger_filter(); } + public void trigger_filter() { + // This is not the most efficient way to do this but it should work without needing more testing + // Probably won't become a bottleneck as most collections will be small + this.sync_with(_inner.Where(_predicate)); + } + + public IDisposable defer_refresh() { + _inner.CollectionChanged -= _inner_CollectionChanged; + return Disposable.Create(() => { trigger_filter(); _inner.CollectionChanged += _inner_CollectionChanged; }); + } + } +} diff --git a/src/client/spark/uicore/Utility/ObservableSortedCollection.cs b/src/client/spark/uicore/Utility/ObservableSortedCollection.cs new file mode 100644 index 000000000..8a087bacc --- /dev/null +++ b/src/client/spark/uicore/Utility/ObservableSortedCollection.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Linq; + +namespace mbts.collections +{ + public class ObservableSortedCollection : ObservableCollection + { + public ObservableSortedCollection(ObservableCollection source) : this(source, Comparer.Default) { } + + public ObservableSortedCollection(ObservableCollection source, IComparer comparer) { + _comparer = comparer; + foreach (var item in source) _insert_sorted(item); + source.CollectionChanged += source_CollectionChanged; + } + + private IComparer _comparer; + public IComparer comparer { get { return _comparer; } set { _comparer = value; sort(); } } + + protected void sort() { this.sync_with(this.OrderBy(t => t, _comparer)); } + + private void source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { + switch (e.Action) { + case NotifyCollectionChangedAction.Add: foreach (T item in e.NewItems) _insert_sorted(item); return; + case NotifyCollectionChangedAction.Remove: foreach (T item in e.OldItems) Remove(item); return; + default: + if (e.OldItems != null) foreach (T item in e.OldItems) Remove(item); + if (e.NewItems != null) foreach (T item in e.NewItems) _insert_sorted(item); + return; + } + } + + private void _insert_sorted(T item) { _insert_sorted(item, 0, Count); } + // Takes advantage of the fact that all elements are assumed to be sorted, recursively hones in on the insert index. + private void _insert_sorted(T item, int index_range_begin, int index_range_end) { + if (index_range_begin == index_range_end) { Insert(index_range_begin, item); return; } + if (index_range_end == (index_range_begin + 1)) { + if (_comparer.Compare(item, this[index_range_begin]) <= 0) Insert(index_range_begin, item); + else Insert(index_range_end, item); + return; + } + int middle_index = index_range_begin + (int)((index_range_end - index_range_begin) * 0.5); + int comp = _comparer.Compare(item, this[middle_index]); + if (comp > 0) _insert_sorted(item, middle_index + 1, index_range_end); + else if (comp < 0) { + if (_comparer.Compare(item, this[middle_index - 1]) >= 0) { Insert(middle_index, item); return; } + _insert_sorted(item, index_range_begin, middle_index - 1); + } + else { Insert(middle_index, item); return; } + } + } +} \ No newline at end of file diff --git a/src/client/spark/uicore/Utility/TupleCommand.cs b/src/client/spark/uicore/Utility/TupleCommand.cs new file mode 100644 index 000000000..f3a6279fc --- /dev/null +++ b/src/client/spark/uicore/Utility/TupleCommand.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Input; + +namespace mbts.ui +{ + internal static class TupleCommandUtility { + internal static T convert(string input) { + if (typeof(T) == typeof(bool)) { + var strval = input.Trim().ToLower(); + return (T)(object)!(strval == "0" || strval == "false"); + } + return (T)Convert.ChangeType(input, typeof(T)); + } + } + + // TupleCommand allows you to write a comma separated set of values in your CommandParameter in xaml and receive a parsed tuple in the callback + public class TupleCommand : IRaiseCanExecuteChangedCommand + { + private Func, bool> _can_execute; + private Action> _execute; + public TupleCommand(Action> exec, Func, bool> can_exec) { + _execute = exec; + _can_execute = can_exec; + } + public TupleCommand(Action> exec) : this(exec, null) {} + + public event EventHandler CanExecuteChanged; + public bool CanExecute(object parameter) { + return _can_execute(ParseParams(parameter)); + } + + private static Tuple ParseParams(object parameter) { + if (parameter == null) return null; + if (parameter is Tuple) return (Tuple)(parameter); + var split_param = parameter.ToString().Split(','); + if (split_param.Length != 2) throw new ArgumentException("Insufficient arguments in TupleCommand parameter. Expected {0},{1}".fmt(typeof(T1), typeof(T2))); + + return Tuple.Create( + TupleCommandUtility.convert(split_param[0]), + TupleCommandUtility.convert(split_param[1])); + } + + public void Execute(object parameter) { + _execute(ParseParams(parameter)); + } + + public void RaiseCanExecuteChanged() { + if (CanExecuteChanged != null) { + CanExecuteChanged(this, null); + } + } + } + + public class TupleCommand : IRaiseCanExecuteChangedCommand + { + private Func, bool> _can_execute; + private Action> _execute; + public TupleCommand(Action> exec, Func, bool> can_exec) { + _execute = exec; + _can_execute = can_exec; + } + public TupleCommand(Action> exec) : this(exec, null) { } + + public event EventHandler CanExecuteChanged; + public bool CanExecute(object parameter) { + return _can_execute(ParseParams(parameter)); + } + + private static Tuple ParseParams(object parameter) { + if (parameter == null) return null; + if (parameter is Tuple) return (Tuple)(parameter); + var split_param = parameter.ToString().Split(','); + if (split_param.Length != 3) throw new ArgumentException("Insufficient arguments in TupleCommand parameter. Expected {0},{1},{2}".fmt(typeof(T1), typeof(T2), typeof(T3))); + + return Tuple.Create( + TupleCommandUtility.convert(split_param[0]), + TupleCommandUtility.convert(split_param[1]), + TupleCommandUtility.convert(split_param[2])); + } + + public void Execute(object parameter) { + _execute(ParseParams(parameter)); + } + + public void RaiseCanExecuteChanged() { + if (CanExecuteChanged != null) { + CanExecuteChanged(this, null); + } + } + } +} diff --git a/src/client/spark/uicore/Utility/ViewModelBase.cs b/src/client/spark/uicore/Utility/ViewModelBase.cs new file mode 100644 index 000000000..61e75ac44 --- /dev/null +++ b/src/client/spark/uicore/Utility/ViewModelBase.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Reflection; +using System.Windows.Input; +using System.Linq.Expressions; + +namespace mbts.ui.shell +{ + public class ViewModelBase : INotifyPropertyChanged + { + public ViewModelBase() { + _props = new Lazy(() => { + return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); + }); + } + protected void RaisePropertyChanged([CallerMemberName]string property="") { + if (PropertyChanged != null) { + PropertyChanged(this, new PropertyChangedEventArgs(property)); + } + } + + protected void RaisePropertyChanged(params string[] properties) { + if (PropertyChanged != null) { + foreach (var prop in properties) { RaisePropertyChanged(prop); } + } + } + + protected bool Set(ref T dest, T value, [CallerMemberName]string name = "") where T : IEquatable { + if (!dest.Equals(value)) { + dest = value; + RaisePropertyChanged(name); + return true; + } + return false; + } + + public event PropertyChangedEventHandler PropertyChanged; + + private Lazy _props; + + + #region Object Diffing + private class ObjSnapshot : IDisposable + { + readonly ViewModelBase _target; + readonly Dictionary _snapshot; + readonly PropertyInfo[] _props; + + public ObjSnapshot(ViewModelBase viewModelBase, PropertyInfo[] props) { + _target = viewModelBase; + _props = props; + _snapshot = snap(); + } + + private Dictionary snap() { + // NOTE: in the future we can optimize prop.GetValue() if needed + return _props.ToDictionary(prop => prop.Name, prop => prop.GetValue(_target)); + } + + public void Dispose() { + var cur = snap(); + foreach (var key in cur.Keys) { + object oldv = _snapshot[key]; + object newv = cur[key]; + if (!Equals(oldv, newv)) { + _target.RaisePropertyChanged(key); + } + } + } + } + // Automatic (but shallow) property change notifications based on local object modifications + public IDisposable detect_property_changes() { + return new ObjSnapshot(this, _props.Value); + } + + #endregion + + #region automatic property + + // use nameof() to add compile time checks + protected Property backing(string name, T default_value = default(T)) { + return new Property(this, name, default_value); + } + + protected Property backing(Expression> member, T default_value) { + var exp = (MemberExpression)member.Body; + return new Property(this, exp.Member.Name, default_value); + } + + protected class Property : IObservable<(T oldval,T newval)> { + readonly string _propname; + readonly ViewModelBase _owner; + T _value; + + public Property(ViewModelBase owner, string name, T default_value) { + _owner = owner; + _propname = name; + _value = default_value; + } + + public delegate void PropertyChange(T oldval, T newval); + public event PropertyChange Changing; + public event PropertyChange Changed; + + public void set(T value) { + if (!value.Equals(_value)) { + Changing?.Invoke(_value, value); + var old = _value; + _value = value; + Changed?.Invoke(old, value); + _owner.RaisePropertyChanged(_propname); + } + } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) { + PropertyChange pch = (o, n) => observer.OnNext((o, n)); + Changed += pch; + return Disposable.Create(() => { + Changed -= pch; + }); + } + + public T Value { + get { return _value; } + set { set(value); } + } + } + + #endregion + } + + public abstract class DisposableViewModelBase : ViewModelBase, IDisposable + { + protected IDisposable _dispose = null; + private List _observable_properties; + + protected Property backing(string name, IObservable source, T default_value=default(T)) { + if (_observable_properties == null) _observable_properties = new List(); + var prop = new ObservablePropertySink(this, name, default_value); + _observable_properties.Add(source.Subscribe(prop)); + return prop; + } + + class ObservablePropertySink : Property, IObserver { + public ObservablePropertySink(ViewModelBase owner, string name, T default_val) : base(owner, name, default_val) { } + public void OnCompleted() { } + public void OnError(Exception error) { } + + public void OnNext(T value) { set(value); } + } + + protected void set_dispose(IDisposable disposable) { + if (_dispose != null) throw new InvalidOperationException("Cannot set disposable twice"); + _dispose = disposable; + } + protected void set_dispose(params IDisposable[] garbage) { + set_dispose(Disposable.Create(garbage)); + } + + public virtual void Dispose() { + Disposable.dispose(ref _dispose); + Disposable.dispose(_observable_properties); + } + } + + public class RequestViewCloseViewModelBase : ViewModelBase, IRequestViewClose + { + public void TryClose() { + if (RequestClose != null) + RequestClose(this, new EventArgs()); + } + + public event EventHandler RequestClose; + } + + public static class RequestViewCloseExtensions + { + public static ICommand close_command(this shell.RequestViewCloseViewModelBase rvc) { + return new DelegateCommand(rvc.TryClose); + } + } + + public class VMValueWrapper : ViewModelBase where T : IEquatable + { + public VMValueWrapper(T val) { _val = val; } + T _val; + public T value { get { return _val; } set { if (value == null || !value.Equals(_val)) { _val = value; RaisePropertyChanged(); } } } + } + + // Adds set_error and clear_error to ViewModelBase + public class ViewModelBaseWithValidation : ViewModelBase, INotifyDataErrorInfo + { + private Dictionary _errors = new Dictionary(); + + protected void set_error(string property, string error) { + _errors[property] = error; + FireErrorsChanged(property); + } + protected void clear_error(string property) { + if (_errors.ContainsKey(property)) { + _errors.Remove(property); + } + FireErrorsChanged(property); + } + + protected IDisposable validation() { + IEnumerable current = _errors.Keys.ToList(); + _errors.Clear(); + return Disposable.Create(() => { + foreach (var property in current) { + if (!_errors.ContainsKey(property)) { + FireErrorsChanged(property); + } + } + }); + } + + protected void validation_assert(bool test, string msg, params string[] properties) { + if (!test) { + foreach (var prop in properties) { + set_error(prop, msg); + } + } + } + + private void FireErrorsChanged(string property) { + if (ErrorsChanged != null) { + ErrorsChanged(this, new DataErrorsChangedEventArgs(property)); + } + } + + #region INotifyDataErrorInfo + public event EventHandler ErrorsChanged; + + public System.Collections.IEnumerable GetErrors(string propertyName) { + string error; + if (_errors.TryGetValue(propertyName, out error)) { + yield return error; + } + } + + public bool HasErrors { + get { return _errors.Count != 0; } + } + + public IEnumerable AllErrors { get { return _errors.Values; } } + #endregion + } +} diff --git a/src/client/spark/uicore/Utility/Wait.cs b/src/client/spark/uicore/Utility/Wait.cs new file mode 100644 index 000000000..1cd08f448 --- /dev/null +++ b/src/client/spark/uicore/Utility/Wait.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + public static class Wait + { + public static async Task until_true(Func test, TimeSpan? timeout=null, int poll_interval = 100) { + DateTime endTime = DateTime.MaxValue; + if (timeout.HasValue) { + endTime = DateTime.UtcNow + timeout.Value; + } + while(!test() && DateTime.UtcNow < endTime) { + await Task.Delay(poll_interval); + } + return test(); + } + } +}