diff --git a/.gitignore b/.gitignore index be8b11c10..96c2e9ef9 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,6 @@ src/client/spark/Properties/launchSettings.json compile_commands.json .cquery_cached_index/ src/client/sparkcmd/Properties/launchSettings.json +node_modules +paket-files +project.lock.json diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index 6272ed432..b3bd9d815 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -17,7 +17,9 @@ ], "limitSymbolsToIncludedHeaders": true, "databaseFilename": "" - } + }, + "cStandard": "c11", + "cppStandard": "c++17" }, { "name": "Windows", @@ -96,5 +98,5 @@ "cppStandard": "c++17" } ], - "version": 3 + "version": 4 } \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 7f93934db..a91924c90 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,6 +1,7 @@ { "version": "0.2.0", "configurations": [ + { "name": "(gdb) Launch", "type": "cppdbg", @@ -117,12 +118,76 @@ "/home/bts/spark/": "${workspaceRoot}" } }, + { + "name": "Admin Service Tests", + "type": "cppdbg", + "request": "launch", + "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", + "args": ["test", "[admin_service]"], + "stopAtEntry": false, + "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", + "environment": [], + "externalConsole": true, + "MIMode": "gdb", + "preLaunchTask": "", + "logging": { + "engineLogging": false + }, + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "enable pretty-printer", + "ignoreFailures": true + } + ], + "pipeTransport": { + "pipeCwd": "${workspaceRoot}", + "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", + "pipeArgs": ["bts@sparkvm"], + "debuggerPath": "/usr/bin/gdb" + }, + "sourceFileMap": { + "/home/bts/spark/": "${workspaceRoot}" + } + }, + { + "name": "Limiter Tests", + "type": "cppdbg", + "request": "launch", + "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", + "args": ["test", "[limiter]"], + "stopAtEntry": false, + "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", + "environment": [], + "externalConsole": true, + "MIMode": "gdb", + "preLaunchTask": "", + "logging": { + "engineLogging": false + }, + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "enable pretty-printer", + "ignoreFailures": true + } + ], + "pipeTransport": { + "pipeCwd": "${workspaceRoot}", + "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", + "pipeArgs": ["bts@sparkvm"], + "debuggerPath": "/usr/bin/gdb" + }, + "sourceFileMap": { + "/home/bts/spark/": "${workspaceRoot}" + } + }, { "name": "MD Tests", "type": "cppdbg", "request": "launch", "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", - "args": ["test", "-a", "LoadSessionKeys"], + "args": ["test", "[md]"], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", "environment": [], diff --git a/CMakeLists.txt b/CMakeLists.txt index 1bd7cb21b..46ab43de1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,6 +36,5 @@ else () set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} -DNDEBUG -O3") add_subdirectory(src/lib) add_subdirectory(src/server/sparkd) + add_subdirectory(src/web) endif() - - diff --git a/docker/linux b/docker/linux index bc896f18d..6037d094b 160000 --- a/docker/linux +++ b/docker/linux @@ -1 +1 @@ -Subproject commit bc896f18dc1431377fa533cb14276c14583c8bda +Subproject commit 6037d094b7ce931f526394644be5e35629cdb3a0 diff --git a/externals b/externals index 9dd9d7a5d..281bd00a2 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit 9dd9d7a5dd6d751fb58ae240eaac6d8cbb8f0b25 +Subproject commit 281bd00a2d1f33bf6613358999355671ff4a9af5 diff --git a/src/client/spark/Admin/AdminModel.cs b/src/client/spark/Admin/AdminModel.cs new file mode 100644 index 000000000..38eab3960 --- /dev/null +++ b/src/client/spark/Admin/AdminModel.cs @@ -0,0 +1,30 @@ +using bts.api; +using bts.api.admin; +using bts.api.core; +using bts.spark; +using mbts.spark.utilities; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel.Composition; +using System.Linq; +using System.Reactive.Linq; +using System.Threading.Tasks; + +namespace mbts.spark { + [Export] + class AdminModel { + readonly AdminService _service; + + [ImportingConstructor] + private AdminModel(AdminService service) { + _service = service; + + on_admin_data = _service.subscribei_admin_data().Table().Replay(1).RefCount(); + } + + public IObservable> on_admin_data { get; } + + } +} \ No newline at end of file diff --git a/src/client/spark/Daemons/OrderTicketDaemon.cs b/src/client/spark/Daemons/OrderTicketDaemon.cs index d35a34afa..5aaa169cc 100644 --- a/src/client/spark/Daemons/OrderTicketDaemon.cs +++ b/src/client/spark/Daemons/OrderTicketDaemon.cs @@ -57,7 +57,8 @@ namespace bts.shell { } void _show_modify_order(uint order_key) { - if (_orders.state.TryGetValue(order_key, out OrderRecordImmutable ori) && _md_map.TryGetValue(ori.Def.SecurityKey, out SecurityMD smd)) + if (_orders.state.TryGetValue(order_key, out OrderRecordImmutable ori) && _md_map.TryGetValue(ori.Def.SecurityKey, out SecurityMD smd) + && (ori.HasDef && ori.Def.HasCustomDef && !(ori.Def.CustomDef.HasStop || ori.Def.CustomDef.HasStopLimit))) _show_order_window(new OrderModificationDialog { DataContext = new ExistingOrderTicketVM(_model, Observable.Return(new OrderRecordTuple(ori, smd)), diff --git a/src/client/spark/Daemons/ShellServices.cs b/src/client/spark/Daemons/ShellServices.cs index bbbde12c7..3d6df5e78 100644 --- a/src/client/spark/Daemons/ShellServices.cs +++ b/src/client/spark/Daemons/ShellServices.cs @@ -11,6 +11,7 @@ using bts.support; using bts.api.orderman; using bts.api.synthetic; using bts.api.diagnostic; +using bts.api.admin; namespace Spark { @@ -34,6 +35,9 @@ namespace Spark [Export] public OrderService order_service => context.locate(); + [Export] + public AdminService admin_service => context.locate(); + [Export] public SyntheticSecurityService synthetic_security_service => context.locate(); diff --git a/src/client/spark/IMenuItemVM.cs b/src/client/spark/IMenuItemVM.cs new file mode 100644 index 000000000..a42d613fc --- /dev/null +++ b/src/client/spark/IMenuItemVM.cs @@ -0,0 +1,38 @@ +using mbts.ui.shell; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui { + interface IMenuItemVM { + string name { get; } + string group { get; } + ImageSource icon { get; } + ICommand command { get; } + object parameter { get; } + } + + class MenuItemVM : ViewModelBase, IMenuItemVM { + object _parameter; + + public MenuItemVM(string name, ICommand command, ImageSource icon = null, string group = null, object parameter = null) { + this.name = name; + this.group = group; + this.command = command; + this.icon = icon; + _parameter = parameter; + } + + public string name { get; } + public string group { get; } + public ImageSource icon { get; } + public ICommand command { get; } + public object parameter { + get => _parameter; + set { + _parameter = value; + command.TryRaiseCanExecuteChanged(); + RaisePropertyChanged(); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs index 1e394d2bf..36348abd6 100644 --- a/src/client/spark/Images/Icons.cs +++ b/src/client/spark/Images/Icons.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -42,7 +42,6 @@ namespace mbts.ui 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 Ticket { get { return load_image("Ticket.png"); } } // replaced with AddOrders @@ -98,14 +97,17 @@ namespace mbts.ui public static ImageSource Clock { get { return (DrawingImage)_resources["Clock"]; } } public static ImageSource Defrag { get { return (DrawingImage)_resources["Defrag"]; } } public static ImageSource Display { get { return (DrawingImage)_resources["Display"]; } } + public static ImageSource Export => (DrawingImage)_resources["Export"]; public static ImageSource Filter { get { return (DrawingImage)_resources["Filter"]; } } public static ImageSource FilterActive { get { return (DrawingImage)_resources["FilterActive"]; } } public static ImageSource FilterError { get { return (DrawingImage)_resources["FilterError"]; } } + public static ImageSource Import => (DrawingImage)_resources["Import"]; public static ImageSource Knight { get { return (DrawingImage)_resources["Knight"]; } } public static ImageSource Payment { get { return (DrawingImage)_resources["Payment"]; } } public static ImageSource Spawn { get { return (DrawingImage)_resources["Spawn"]; } } public static ImageSource Target { get { return (DrawingImage)_resources["Target"]; } } public static ImageSource Tetris { get { return (DrawingImage)_resources["Tetris"]; } } + public static ImageSource ViewSettings => (DrawingImage)_resources["ViewSettings"]; public static ImageSource Wrench { get { return (DrawingImage)_resources["Wrench"]; } } public static ImageSource Support => (DrawingImage)_resources["SupportIcon"]; diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml index f74fc9f57..aebe68c31 100644 --- a/src/client/spark/Images/Vector/Icons.xaml +++ b/src/client/spark/Images/Vector/Icons.xaml @@ -319,7 +319,7 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> - + @@ -608,7 +608,7 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> - + @@ -718,7 +718,7 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> - + @@ -730,6 +730,45 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/ActionMenu/ActionMenu.xaml.cs b/src/client/spark/view/Controls/ActionMenu/ActionMenu.xaml.cs new file mode 100644 index 000000000..609cfbdf6 --- /dev/null +++ b/src/client/spark/view/Controls/ActionMenu/ActionMenu.xaml.cs @@ -0,0 +1,22 @@ +using System.Collections; +using System.Linq; +using System.Windows; + +namespace mbts.ui.controls { + /// + /// Interaction logic for ActionMenu.xaml + /// + partial class ActionMenu : PopupControl { + public ActionMenu() => + InitializeComponent(); + + public static readonly DependencyProperty ItemsSourceProperty = + WPFHelper.create_dp( + nameof(ItemsSource), Enumerable.Empty()); + + public IEnumerable ItemsSource { + get => GetValue(ItemsSourceProperty) as IEnumerable; + set => SetValue(ItemsSourceProperty, value); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Badge.cs b/src/client/spark/view/Controls/Badge.cs index f69ca734c..f47e38e15 100644 --- a/src/client/spark/view/Controls/Badge.cs +++ b/src/client/spark/view/Controls/Badge.cs @@ -23,16 +23,16 @@ namespace mbts.ui.controls { DefaultStyleKeyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(typeof(Badge))); WidthProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(15.0)); HeightProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(10.0)); - FontSizeProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(9.0, FrameworkPropertyMetadataOptions.AffectsRender, update_text)); + FontSizeProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender /*| FrameworkPropertyMetadataOptions.AffectsMeasure*/, update_text)); ForegroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.White, update_text)); BackgroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender)); BorderThicknessProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new Thickness(1))); BorderBrushProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.Black)); - FontFamilyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new FontFamily("Consolas"))); - } + FontFamilyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new FontFamily("Consolas"), FrameworkPropertyMetadataOptions.AffectsRender /*| FrameworkPropertyMetadataOptions.AffectsMeasure*/, update_text)); - public Badge() { - FontSize = 9; + //TextProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, update_text)); + //TopTextProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, update_text)); + //BottomTextProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, update_text)); } public string Text { @@ -77,7 +77,7 @@ namespace mbts.ui.controls { f(b, new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, - b._face, 4.2, b.Foreground, _dpi)); + b._face, b.FontSize, b.Foreground, _dpi)); b.InvalidateVisual(); }; } @@ -102,23 +102,40 @@ namespace mbts.ui.controls { b._face = b._face ?? new Typeface(b.FontFamily, b.FontStyle, b.FontWeight, b.FontStretch); } + //protected override Size MeasureOverride(Size availableSize) { + // Double calc_height = 0.0; + // Double calc_width = 0.0; + // Size size = new Size(0, 0); + + // Size center_size = new Size(_center_text.Width, _center_text.Height); + // Size top_size = new Size(_top_text.Width, _top_text.Height); + // Size bottom_size = new Size(_bottom_text.Width, _bottom_text.Height); + + // calc_width = Math.Max(center_size.Width, top_size.Width); + // calc_width = Math.Max(calc_width, bottom_size.Width); + + // calc_height += center_size.Height; + // calc_height += top_size.Height; + // calc_height += bottom_size.Height; + + // size.Width = calc_width; + // size.Height = calc_height; + + // return size; + + //} + protected override void OnRender(DrawingContext dc) { base.OnRender(dc); double border_thickness = BorderThickness.Top; var pen = new Pen(BorderBrush, border_thickness); dc.DrawRoundedRectangle(Background, pen, new Rect(0, 0 + border_thickness, ActualWidth, ActualHeight - 2 * border_thickness), CornerRadius, CornerRadius); - if (_center_text != null) { - _center_text.SetFontSize(FontSize); + if (_center_text != null) dc.DrawText(_center_text, new Point((ActualWidth-_center_text.Width)/2, (ActualHeight-_center_text.Height)/2)); - } - if (_top_text != null) { - _top_text.SetFontSize(FontSize); - dc.DrawText(_top_text, new Point(border_thickness, 0.0)); - } - if (_bottom_text != null) { - _bottom_text.SetFontSize(FontSize); + if (_top_text != null) + dc.DrawText(_top_text, new Point(border_thickness, 0.0)); + if (_bottom_text != null) dc.DrawText(_bottom_text, new Point(border_thickness, ActualHeight - _bottom_text.Height)); - } } } } \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker.xaml b/src/client/spark/view/Controls/ColorPicker.xaml deleted file mode 100644 index 5190d1c57..000000000 --- a/src/client/spark/view/Controls/ColorPicker.xaml +++ /dev/null @@ -1,8 +0,0 @@ - - diff --git a/src/client/spark/view/Controls/ColorPicker.xaml.cs b/src/client/spark/view/Controls/ColorPicker.xaml.cs deleted file mode 100644 index d4c970b5f..000000000 --- a/src/client/spark/view/Controls/ColorPicker.xaml.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; -using mbts.ui.shell; -using System.ComponentModel; -using System; - -namespace mbts.ui.controls -{ - /// - /// Interaction logic for ColorPicker.xaml - /// - public partial class ColorPicker : ComboBox - { - public ColorPicker() { - InitializeComponent(); - Loaded += ColorPicker_Loaded; - } - - void ColorPicker_Loaded(object sender, RoutedEventArgs e) { - if (SelectedItem == null) { - _set_SelectedItem(selected_color); - } - } - - static ColorPicker() { - DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorPicker), new FrameworkPropertyMetadata(typeof(ColorPicker))); - ComboBox.SelectedItemProperty.OverrideMetadata(typeof(ColorPicker), new FrameworkPropertyMetadata(null, - (d, e) => { - var target = (ColorPicker)d; - var color_item = e.NewValue as ColorItem; - if (color_item != null && color_item.color != target.selected_color) - target.selected_color = color_item.color; - })); - } - - public static DependencyProperty selected_colorProperty = DependencyProperty.Register("selected_color", typeof(Color), typeof(ColorPicker), - new FrameworkPropertyMetadata(Colors.Black, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => { - var target = (ColorPicker)d; - var color = (Color)e.NewValue; - target._set_SelectedItem(color); - })); - - private void _set_SelectedItem(Color color) { - var color_item = SelectedItem as ColorItem; - if (color_item == null || color_item.color != color) { - var dc_match = ItemsSource.OfType().FirstOrDefault(c => c.color == color); - if (dc_match != null) - SelectedItem = dc_match; - else { - var item = ItemsSource.OfType().Single(); - item.color = color; - SelectedItem = item; - } - } - } - - public Color selected_color { - get { return (Color)GetValue(selected_colorProperty); } - set { SetValue(selected_colorProperty, value); } - } - - private IDisposable _dialog; - - public ICommand launch_color_dialog { - get { - return new DelegateCommand(() => { - Disposable.dispose(ref _dialog); - var dialog = new CustomColorPicker(); - dialog.SelectedColor = selected_color; - dialog.committed += c => selected_color = c; - var window = new Window { Style = this.TryFindResource("BTSWindow") as Style, Content = dialog, SizeToContent = SizeToContent.WidthAndHeight }; - window.move_to_mouse(-240, -400); - window.Show(); - _dialog = Disposable.Create(() => window.Close()); - }); - } - } - } -} diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorPalette.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorPalette.cs new file mode 100644 index 000000000..e8b086ea4 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorPalette.cs @@ -0,0 +1,112 @@ +using ProtoBuf; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Media; + +namespace mbts.ui.controls.color_picker { + [ProtoContract] + class ColorPalette { + [ProtoMember(1)] + public string group { get; set; } + [ProtoMember(2)] + public List colors { get; set; } + [ProtoMember(3)] + public bool can_user_edit { get; set; } + + #region Presets + public static IEnumerable all_presets() { + yield return market_palette(); + yield return trading_palette(); + yield return grid_palette(); + yield return application_palette(); + yield return bts_palette(); + yield return blank_palette(); + } + public static ColorPalette market_palette() => + new ColorPalette { + group = "Market", + colors = new List() { + new NamedColor(BTSColors.MarketData.bid, "Bid"), + new NamedColor(BTSColors.MarketData.ask, "Ask"), + new NamedColor(BTSColors.MarketData.trade_alert, "Trade Alert"), + new NamedColor(BTSColors.MarketData.settlement_background, "Settlement"), + new NamedColor(BTSColors.MarketData.atm_background, "ATM"), + new NamedColor(BTSColors.Position.default_background, "Position") + } + }; + + public static ColorPalette trading_palette() => + new ColorPalette { + group = "Trading", + colors = new List() { + new NamedColor(BTSColors.MarketData.bid, "Buy"), + new NamedColor(BTSColors.MarketData.ask, "Ask"), + new NamedColor(BTSColors.Orders.sent, "Order Sent"), + new NamedColor(BTSColors.Orders.filled, "Order Filled"), + new NamedColor(BTSColors.Orders.filled_dark, "Order Filled (Dark)"), + new NamedColor(BTSColors.Orders.price_background, "Price"), + new NamedColor(BTSColors.Orders.size_background, "Size"), + } + }; + + public static ColorPalette grid_palette() => + new ColorPalette { + group = "Grid", + colors = new List() { + new NamedColor(Colors.MediumSlateBlue, "Grid Selection"), + new NamedColor(BTSColors.header, "Header Background"), + new NamedColor(BTSColors.header_text, "Header Foreground"), + new NamedColor(Colors.PaleGreen, "Filter Active"), + new NamedColor(Colors.Red, "Filter Error") + } + }; + + public static ColorPalette application_palette () => + new ColorPalette { + group = "Application", + colors = new List { + new NamedColor(BTSColors.accent_dark, "Shell Accent Dark"), + new NamedColor(BTSColors.accent_light, "Shell Accent Light"), + new NamedColor(BTSColors.success, "Success"), + new NamedColor(BTSColors.warning, "Warning"), + new NamedColor(BTSColors.danger, "Danger"), + new NamedColor(BTSColors.logo, "Logo"), + new NamedColor(BTSColors.brand_lightest, "Brand Lightest"), + new NamedColor(BTSColors.brand_lighter, "Brand Lighter"), + new NamedColor(BTSColors.brand_light, "Brand Light"), + new NamedColor(BTSColors.brand_medium, "Brand Medium"), + new NamedColor(BTSColors.brand_dark, "Brand Dark"), + new NamedColor(BTSColors.brand_darker, "Brand Darker"), + new NamedColor(BTSColors.brand_darkest, "Brand Darkest"), + } + }; + + public static ColorPalette bts_palette() => + new ColorPalette { + group = "BTS", + colors = new List { + new NamedColor(BTSColors.red_orange, "Red Orange"), + new NamedColor(BTSColors.blue, "Blue"), + new NamedColor(BTSColors.yellow, "Yellow"), + new NamedColor(BTSColors.green, "Green"), + new NamedColor(BTSColors.orange, "Orange"), + new NamedColor(BTSColors.pale_blue, "Pale Blue"), + new NamedColor(BTSColors.red, "Red"), + new NamedColor(BTSColors.pale_green, "Pale Green"), + new NamedColor(BTSColors.purple, "Purple"), + new NamedColor(BTSColors.teal, "Teal"), + new NamedColor(BTSColors.olive, "Olive") + } + }; + + public static ColorPalette blank_palette() => + new ColorPalette { + group = "Custom", + can_user_edit = true, + colors = new List( + Enumerable.Range(1, 30) + .Select(i => new NamedColor(Colors.White, $"Custom{i}"))) + }; + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorPaletteVM.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorPaletteVM.cs new file mode 100644 index 000000000..40d07e7fb --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorPaletteVM.cs @@ -0,0 +1,39 @@ +using mbts.ui.shell; +using System.Collections.ObjectModel; +using System.Linq; + +namespace mbts.ui.controls.color_picker { + class ColorPaletteVM : ViewModelBase { + readonly Property _group; + readonly Property _selected_named_color; + + public ColorPaletteVM(ColorPalette palette) + : this(palette.group, new ObservableCollection(palette.colors.Select(nc => new NamedColorVM(nc, palette.can_user_edit))), palette.can_user_edit) { } + + public ColorPaletteVM(string group, ObservableCollection named_colors, bool can_user_edit) { + _group = backing(nameof(this.group), group); + _selected_named_color = backing(nameof(selected_named_color)); + this.named_colors = named_colors; + this.can_user_edit = can_user_edit; + } + + public string group { get => _group.Value; set => _group.Value = value; } + public bool can_user_edit { get; set; } + public ObservableCollection named_colors { get; } + public NamedColorVM selected_named_color { + get => _selected_named_color.Value; + set => _selected_named_color.Value = value; + } + + public void try_select(NamedColorVM nc) { + if (selected_named_color == nc) + return; + if (nc != null && named_colors.Contains(nc)) + selected_named_color = nc; + else selected_named_color = null; + } + + public ColorPalette to_palette() => + new ColorPalette { colors = named_colors.Select(nc => new NamedColor(nc.color, nc.name)).ToList(), group = group }; + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorPickerVM.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorPickerVM.cs new file mode 100644 index 000000000..a6ede091c --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorPickerVM.cs @@ -0,0 +1,200 @@ +using mbts.collections; +using mbts.ui.shell; +using mbts.ui.utility; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui.controls.color_picker { + partial class ColorPickerVM : DisposableViewModelBase { + const int _n_hue_grad_stops = 7; + static readonly double _hue_grad_increment, _hue_grad_stop_unit; + readonly GradientStopCollection _hue_gradient_collection; + readonly Property _color, _max_saturation; + readonly DelegateProperty _saturation_tool_tip, _hue_tool_tip; + readonly DelegateProperty _alpha, _red, _green, _blue; + readonly Property _hue, _saturation, _light; + readonly SetMap _named_color_map = new SetMap(); + readonly ObservableAggregateCollection _all_colors = new ObservableAggregateCollection(); + NamedColorVM _selected_named_color; + + static ColorPickerVM() { + _hue_grad_increment = 360.0 / (_n_hue_grad_stops - 1); + _hue_grad_stop_unit = 1.0 / (_n_hue_grad_stops - 1); + } + + public ColorPickerVM() { + _hue_gradient_collection = + new GradientStopCollection( + Enumerable.Range(0, _n_hue_grad_stops).Select(i => { + var c = ColorUtils.from_ahsb(255, i * _hue_grad_increment, 1, 0.5); + return new GradientStop(c, i * _hue_grad_stop_unit); + })); + hue_gradient_brush = new LinearGradientBrush(_hue_gradient_collection); + // basic color props + _color = backing(nameof(result), Colors.White); + _color.Changed += (o, n) => _set_hue_gradient_brush(); + _alpha = backing(nameof(alpha), () => result.A, nameof(result)); + _red = backing(nameof(red), () => result.R, nameof(result)); + _green = backing(nameof(green), () => result.G, nameof(result)); + _blue = backing(nameof(blue), () => result.B, nameof(result)); + _hue = backing(nameof(hue), () => result.hue(), nameof(result)); + _saturation = backing(nameof(saturation), () => result.saturation(), nameof(result)); + _light = backing(nameof(light), () => result.brightness(), nameof(result)); + // + _hue_tool_tip = backing(nameof(hue_tool_tip), () => (result.R == result.G && result.G == result.B) ? + "(H)ue not applicable when R, G, and B are all the same (shades of gray)." : null, nameof(result)); + _saturation_tool_tip = backing(nameof(saturation_tool_tip), () => (light == 0 || light == 1) ? + "(S)aturation not Applicable when (L)ightness is 0 or 1 (black or white)." : null, nameof(result)); + _max_saturation = backing(nameof(max_saturation), () => ColorUtils.from_ahsb(alpha, hue, 1, light), nameof(result)); + // palettes/named colors + all_colors_view = CollectionViewSource.GetDefaultView(_all_colors); + //all_colors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(NamedColorVM.group))); + palettes.CollectionChanged += on_palettes_collection_changed; + // export/import palette cmds + const string msg_title = "Color Picker", palette_type_name = "Palette"; + (string name, string[] extensions) palette_extensions_filter = ("palette files", new[] { "palette" }); + var export_palette_cmd = FileDialogCommand.export_proto( + vm => vm.to_palette(), + vm => vm != null, + vm => vm.group, + msg_title, + on_exported: (vm, file) => vm.group = file, + filter_items: palette_extensions_filter); + var import_palette_cmd = FileDialogCommand.import_proto( + p => palettes.Add(new ColorPaletteVM(p)), null, palette_type_name, msg_title, filter_items: palette_extensions_filter); + // + action_menu_items = new ReadOnlyObservableCollection( + new ObservableAppendCollection( + new ObservableAutoWrapper( + new ObservableFilterCollection( + palettes, + vm => vm.can_user_edit), + vm => new ExportMenuItemVM(vm, export_palette_cmd)), + new MenuItemVM("Import Palette...", import_palette_cmd, Icons.Import))); + _dispose = Disposable.Create(export_palette_cmd, import_palette_cmd); + // + void on_palettes_collection_changed(object sender, NotifyCollectionChangedEventArgs e) { + switch (e.Action) { + case NotifyCollectionChangedAction.Add: on_palettes_added(e.NewItems); break; + case NotifyCollectionChangedAction.Remove: on_palettes_removed(e.OldItems); break; + case NotifyCollectionChangedAction.Reset: + // the stale PropertyChanged callbacks should not be an issue, just clear all_colors and treat this like an 'Add' change + _all_colors.clear_collections(); + on_palettes_added(palettes); + break; + } + } + void on_palettes_added(IList items) { + foreach (ColorPaletteVM p in items) { + p.PropertyChanged += on_palette_property_changed; + _all_colors.add_collection(p.named_colors); + p.try_select(selected_named_color); + } + } + void on_palettes_removed(IList items) { + foreach (ColorPaletteVM p in items) { + p.PropertyChanged -= on_palette_property_changed; + _all_colors.remove_collection(p.named_colors); + } + } + void on_palette_property_changed(object sender, PropertyChangedEventArgs e) { + if (e.PropertyName == nameof(ColorPaletteVM.selected_named_color)) { + var vm = (ColorPaletteVM)sender; + if (vm.selected_named_color != null) + selected_named_color = vm.selected_named_color; + } + } + } + + public string saturation_tool_tip => _saturation_tool_tip.Value; + public string hue_tool_tip => _hue_tool_tip.Value; + public byte alpha { get => _alpha.Value; set { result = Color.FromArgb(value, result.R, result.G, result.B); } } + public byte red { get => _red.Value; set { result = Color.FromArgb(result.A, value, result.G, result.B); } } + public byte green { get => _green.Value; set { result = Color.FromArgb(result.A, result.R, value, result.B); } } + public byte blue { get => _blue.Value; set { result = Color.FromArgb(result.A, result.R, result.G, value); } } + public double hue { + get => _hue.Value; + set { + _ensure_light_allows_saturation(); + _ensure_saturation_allows_hue(); + result = ColorUtils.from_ahsb(alpha, value, saturation, light); + } + } + public double saturation { + get => _saturation.Value; + set { + _ensure_light_allows_saturation(); + result = ColorUtils.from_ahsb(alpha, hue, value, light); + } + } + public double light { get => _light.Value; set { result = ColorUtils.from_ahsb(alpha, hue, saturation, value); } } + public Color result { + get => _color.Value; + set { + _color.Value = value; + if (_named_color_map.try_lookup(value, out ISet ncs)) { + _selected_named_color = ncs.First(); + RaisePropertyChanged(nameof(selected_named_color)); + } + } + } + public LinearGradientBrush hue_gradient_brush { get; } + public Color max_saturation => _max_saturation.Value; + public ObservableCollection palettes { get; } = new ObservableCollection(); + public ReadOnlyObservableCollection action_menu_items { get; } + public ICollectionView all_colors_view { get; } + + public NamedColorVM selected_named_color { + get => _selected_named_color; + set { + _selected_named_color = value; + foreach (var p in palettes) + p.try_select(value); + if (value != null) + _color.Value = value.color; + RaisePropertyChanged(); + } + } + + void _set_hue_gradient_brush() { + for (int i = 0; i < _n_hue_grad_stops; i++) + _hue_gradient_collection[i].Color = ColorUtils.from_ahsb(alpha, i * _hue_grad_increment, saturation, light); + } + + void _ensure_light_allows_saturation() { + if (light < .1) _light.Value = .1; + else if (light > .9) _light.Value = .9; + } + + void _ensure_saturation_allows_hue() { + if (saturation < .1) _saturation.Value = .1; + } + + class ExportMenuItemVM : ViewModelBase, IMenuItemVM { + readonly DelegateProperty _name; + + public ExportMenuItemVM(ColorPaletteVM palette, ICommand export_cmd) { + _name = backing(nameof(name), () => $"Export '{palette.group}' Palette..."); + command = export_cmd; + parameter = palette; + palette.PropertyChanged += (s, e) => { + if (e.PropertyName == nameof(ColorPaletteVM.group)) + _name.refresh(); + }; + } + + public string name => _name.Value; + public ImageSource icon { get; } = Icons.Export; + public ICommand command { get; } + public object parameter { get; } + public string group => "Export"; + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs new file mode 100644 index 000000000..b20e85b58 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs @@ -0,0 +1,43 @@ +using ProtoBuf; +using System; +using System.Windows.Media; + +namespace mbts.ui.controls.color_picker { + public class ColorSwatchItem { + public Color Color { get; set; } + public string HexString { get; set; } + } + + [ProtoContract] + class NamedColor : IEquatable { + [ProtoMember(1)] + public string name { get; set; } + + [ProtoMember(2)] + uint _color_id; + + public NamedColor() { } + public NamedColor(Color color, string name) { + this.color = color; + this.name = name; + } + + Color? _color; + public Color color { + get => (_color ?? (_color = _color_id.rgb_color())).Value; + set { + _color = value; + _color_id = new BTSColor(value).ToUint(); + } + } + + public bool Equals(NamedColor other) => + other != null && other.color == color && other.name == name; + + public override bool Equals(object obj) => + Equals(obj as NamedColor); + + public override int GetHashCode() => + (int)_color_id; + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorUtils.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorUtils.cs new file mode 100644 index 000000000..b62f86cbb --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorUtils.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; +using Color = System.Windows.Media.Color; + +namespace mbts.ui.controls.color_picker { + public static class ColorUtils { + [DllImport("shlwapi.dll")] + public static extern int ColorHLSToRGB(int H, int L, int S); + + public static Color ColorFromHSL(int H, int S, int L) { + int colorInt = ColorHLSToRGB(H, L, S); + byte[] bytes = BitConverter.GetBytes(colorInt); + return Color.FromArgb(255, bytes[0], bytes[1], bytes[2]); + } + + + public static string ToHexString(this Color c) => + "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); + + public static Color ColorFromHexString(string hex) => + Color.FromRgb( + Convert.ToByte(hex.Substring(1, 2), 16), + Convert.ToByte(hex.Substring(3, 2), 16), + Convert.ToByte(hex.Substring(5, 2), 16)); + + #region Hue, Saturation, Brightness + // https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Color.cs,2f0cba80c49c6b4e + public static double hue(this Color c) { + if (c.R == c.G && c.G == c.B) + return 0; // 0 makes as good an UNDEFINED value as any + + float r = (float)c.R / 255.0f; + float g = (float)c.G / 255.0f; + float b = (float)c.B / 255.0f; + + float max, min; + float delta; + float hue = 0.0f; + + max = r; min = r; + + if (g > max) max = g; + if (b > max) max = b; + + if (g < min) min = g; + if (b < min) min = b; + + delta = max - min; + + if (r == max) { + hue = (g - b) / delta; + } else if (g == max) { + hue = 2 + (b - r) / delta; + } else if (b == max) { + hue = 4 + (r - g) / delta; + } + hue *= 60; + + if (hue < 0.0f) { + hue += 360.0f; + } + return hue; + } + + public static double brightness(this Color color) { + float r = (float)color.R / 255.0f; + float g = (float)color.G / 255.0f; + float b = (float)color.B / 255.0f; + + float max, min; + + max = r; min = r; + + if (g > max) max = g; + if (b > max) max = b; + + if (g < min) min = g; + if (b < min) min = b; + + return (max + min) / 2; + } + + public static double saturation(this Color color) { + float r = (float)color.R / 255.0f; + float g = (float)color.G / 255.0f; + float b = (float)color.B / 255.0f; + + float max, min; + float l, s = 0; + + max = r; min = r; + + if (g > max) max = g; + if (b > max) max = b; + + if (g < min) min = g; + if (b < min) min = b; + + // if max == min, then there is no color and + // the saturation is zero. + // + if (max != min) { + l = (max + min) / 2; + + if (l <= .5) { + s = (max - min) / (max + min); + } else { + s = (max - min) / (2 - max - min); + } + } + return s; + } + #endregion + + public static bool is_gray(this Color color) => + color.R == color.G && color.G == color.B; + + public static bool is_black_or_white(this Color color) => + color.R == 0 ? + color.G == 0 && color.B == 0 : + color.R == 255 && color.G == 255 && color.B == 255; + + public static Color from_ahsb(byte alpha, double hue, double saturation, double brightness) { + if (0 > hue || 360 < hue) throw new ArgumentOutOfRangeException("hue", hue, "Value must be within a range of 0 - 360."); + else if (0 > saturation || 1 < saturation) throw new ArgumentOutOfRangeException("saturation", saturation, "Value must be within a range of 0 - 1."); + else if (0 > brightness || 1 < brightness) throw new ArgumentOutOfRangeException("brightness", brightness, "Value must be within a range of 0 - 1."); + else if (0 == saturation) return Color.FromArgb(alpha, Convert.ToByte(brightness * 255), Convert.ToByte(brightness * 255), Convert.ToByte(brightness * 255)); + else { + double max, mid, min; + int i_sextant; + byte i_max, i_mid, i_min; + if (0.5 < brightness) { + max = brightness - (brightness * saturation) + saturation; + min = brightness + (brightness * saturation) - saturation; + } else { + max = brightness + (brightness * saturation); + min = brightness - (brightness * saturation); + } + i_sextant = (int)Math.Floor(hue / 60f); + if (300f <= hue) + hue -= 360f; + hue /= 60f; + hue -= 2.0 * Math.Floor(((i_sextant + 1.0) % 6.0) / 2.0); + if (0 == i_sextant % 2) + mid = hue * (max - min) + min; + else mid = min - hue * (max - min); + i_max = Convert.ToByte(max * 255); + i_mid = Convert.ToByte(mid * 255); + i_min = Convert.ToByte(min * 255); + + switch (i_sextant) { + case 1: return Color.FromArgb(alpha, i_mid, i_max, i_min); + case 2: return Color.FromArgb(alpha, i_min, i_max, i_mid); + case 3: return Color.FromArgb(alpha, i_min, i_mid, i_max); + case 4: return Color.FromArgb(alpha, i_mid, i_min, i_max); + case 5: return Color.FromArgb(alpha, i_max, i_min, i_mid); + default: return Color.FromArgb(alpha, i_max, i_mid, i_min); + } + } + } + + public static Color adjust_color(Color from, Color to, double percent_towards) { + if (percent_towards < 0 || percent_towards > 1) + throw new ArgumentOutOfRangeException(nameof(percent_towards)); + double rdiff = (to.R - from.R) * percent_towards; + double gdiff = (to.G - from.G) * percent_towards; + double bdiff = (to.B - from.B) * percent_towards; + return Color.FromRgb((byte)(from.R + rdiff), (byte)(from.G + gdiff), (byte)(from.B + bdiff)); + } + + // https://stackoverflow.com/questions/5091455/web-color-list-in-c-sharp-application + public static List GetWebColors() { + Type colors = typeof(System.Drawing.Color); + PropertyInfo[] colorInfo = colors.GetProperties(BindingFlags.Public | + BindingFlags.Static); + List list = new List(); + foreach (PropertyInfo info in colorInfo) { + var c = System.Drawing.Color.FromName(info.Name); + list.Add(Color.FromArgb(c.A, c.R, c.G, c.B)); + } + return list; + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/Code/NamedColorVM.cs b/src/client/spark/view/Controls/ColorPicker/Code/NamedColorVM.cs new file mode 100644 index 000000000..9a9696c22 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/Code/NamedColorVM.cs @@ -0,0 +1,41 @@ +using mbts.ui.shell; +using System; +using System.Windows.Media; + +namespace mbts.ui.controls.color_picker { + class NamedColorVM : ViewModelBase { + readonly NamedColor _named_color; + + public NamedColorVM(NamedColor named_color, bool can_user_edit) { + _named_color = named_color; + this.can_user_edit = can_user_edit; + } + + public Color color => _named_color.color; + public string name { + get => _named_color.name; + set { + if (!can_user_edit) + throw new InvalidOperationException($"Cannot change name of color '{name}.'"); + _named_color.name = value; + RaisePropertyChanged(); + } + } + public string group { get; set; } + public bool can_user_edit { get; } + public byte red => color.R; + public byte green => color.G; + public byte blue => color.B; + public double hue => color.hue(); + public double saturation => color.saturation(); + public double light => color.brightness(); + + public void assign_color(Color color) { + _named_color.color = color; + RaisePropertyChanged(nameof(color)); + } + + public NamedColor to_named_color() => + new NamedColor(color, name); + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml b/src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml new file mode 100644 index 000000000..2059977d7 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml @@ -0,0 +1,319 @@ + + + + + + + + #00FF00 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml.cs b/src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml.cs new file mode 100644 index 000000000..c469d2492 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml.cs @@ -0,0 +1,236 @@ +using mbts.spark.utilities; +using mbts.ui.extensions; +using mbts.ui.utility; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace mbts.ui.controls.color_picker { + /// + /// Interaction logic for ColorPickerControl.xaml + /// + partial class ColorPickerControl : Control { + const string _max_saturation_color_key = "MaxSaturationColor"; + readonly PropertyUpdateGate _saturation_border_gate = new PropertyUpdateGate(); + readonly ColorPickerVM _color_vm = new ColorPickerVM(); + + DataGrid _named_colors_grid; + Border _saturation_border; + Image _sample_image; + TabItem _named_colors_tab, _hue_sat_tab; + IDisposable _template_hooks; + + public ColorPickerControl() { + InitializeComponent(); + DataContext = _color_vm; + CommandManager.AddExecutedHandler(this, executed_handler); + CommandManager.AddCanExecuteHandler(this, can_execute_handler); + + void executed_handler(object sender, ExecutedRoutedEventArgs e) { + // hack to commit value, then release focus when 'Enter' is pressed + if (e.OriginalSource is TextBox tb && e.Command == EditingCommands.EnterParagraphBreak) { + bool commit_grid_edit = _named_colors_grid.IsKeyboardFocusWithin; + tb.GetBindingExpression(TextBox.TextProperty)?.UpdateSource(); + tb.ReleaseMouseCapture(); + Keyboard.ClearFocus(); + e.Handled = true; + if (commit_grid_edit) + _named_colors_grid.CommitEdit(); + } else if (e.Parameter is NamedColorVM vm) { + if (e.Command == ColorPickerSwatch.AssignColorCommand) + vm.assign_color(_color_vm.result); + else if (e.Command == ColorPickerSwatch.NameColorCommand) { + _named_colors_tab.IsSelected = true; + _color_vm.selected_named_color = vm; + _named_colors_grid.ScrollIntoView(vm); + _named_colors_grid.CurrentCell = new DataGridCellInfo(vm, _named_colors_grid.Columns[0]); + } + } + } + + void can_execute_handler(object sender, CanExecuteRoutedEventArgs e) => + e.CanExecute = true; + } + + #region SelectedColor + public static readonly DependencyProperty SelectedColorProperty = + WPFHelper.create_dp(nameof(SelectedColor), (cp, val) => cp._color_vm.result = val); + + public Color SelectedColor { get => (Color)GetValue(SelectedColorProperty); set => SetValue(SelectedColorProperty, value); } + + public static readonly DependencyProperty PalettesProperty = + WPFHelper.create_dp, ColorPickerControl>( + nameof(Palettes), + (cp, oldval, newval) => { + if (oldval != null) { + oldval.CollectionChanged -= cp._on_palettes_collection_changed; + cp._on_palettes_collection_changed(new Collection(), new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldval)); + } + if (newval != null) { + cp._on_palettes_collection_changed(newval, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + newval.CollectionChanged += cp._on_palettes_collection_changed; + } + }); + + public ObservableCollection Palettes { + get => GetValue(PalettesProperty) as ObservableCollection; + set => SetValue(PalettesProperty, value); + } + + // just let color_vm have it's own ObservableCollection that will never change. + // this is easier than trying to either + // a) change the collection during it's lifetime, or + // b) destroy and recreate color_vm without breaking TabControl bindings, and ICollectionView source dependencies + void _on_palettes_collection_changed(object sender, NotifyCollectionChangedEventArgs e) { + switch (e.Action) { + case NotifyCollectionChangedAction.Add: _color_vm.palettes.InsertRange(e.NewStartingIndex, e.NewItems); break; + case NotifyCollectionChangedAction.Remove: _color_vm.palettes.RemoveRange(e.OldStartingIndex, e.OldItems.Count); break; + case NotifyCollectionChangedAction.Move: _color_vm.palettes.Move(e.OldStartingIndex, e.NewStartingIndex); break; + case NotifyCollectionChangedAction.Replace: + _color_vm.palettes.RemoveRange(e.OldStartingIndex, e.OldItems.Count); + _color_vm.palettes.InsertRange(e.NewStartingIndex, e.NewItems); + break; + case NotifyCollectionChangedAction.Reset: + _color_vm.palettes.Clear(); + if (sender is IEnumerable items) + _color_vm.palettes.AddRange(items); + break; + } + } + #endregion + + public override void OnApplyTemplate() { + Disposable.dispose(ref _template_hooks); + _named_colors_grid = this.assert_template_child("_named_colors_grid"); + _named_colors_tab = this.assert_template_child("_named_colors_tab"); + _hue_sat_tab = this.assert_template_child("_hue_sat_tab"); + _saturation_border = this.assert_template_child("_saturation_border"); + _sample_image = this.assert_template_child("_sample_image"); + // TabItems do not inherit DataContext properly from its visual parent, which breaks certain bindings + _named_colors_grid.SetBinding(DataGrid.ItemsSourceProperty, new Binding(nameof(ColorPickerVM.all_colors_view)) { Source = _color_vm }); + _named_colors_grid.SetBinding(DataGrid.SelectedItemProperty, new Binding(nameof(ColorPickerVM.selected_named_color)) { Source = _color_vm }); + _color_vm.PropertyChanged += color_vm_property_changed; + _color_vm.result = SelectedColor; + IDisposable mouse_move_hook = null; + _saturation_border.MouseDown += saturation_border_mouse_down; + _saturation_border.MouseUp += saturation_border_mouse_up; + + _template_hooks = Disposable.Create(() => { + _named_colors_grid.clear_bindings(DataGrid.ItemsSourceProperty, DataGrid.SelectedItemProperty); + _color_vm.PropertyChanged -= color_vm_property_changed; + _saturation_border.MouseDown -= saturation_border_mouse_down; + _saturation_border.MouseUp -= saturation_border_mouse_up; + Disposable.dispose(ref mouse_move_hook); + }); + + void color_vm_property_changed(object sender, PropertyChangedEventArgs e) { + switch (e.PropertyName) { + case nameof(ColorPickerVM.max_saturation): _update_saturation_img(); break; + case nameof(ColorPickerVM.result): SelectedColor = _color_vm.result; break; + } + } + + void saturation_border_mouse_down(object sender, MouseButtonEventArgs e) { + set_result_from_saturation_click(e.GetPosition(_saturation_border)); + Disposable.dispose(ref mouse_move_hook); + mouse_move_hook = _saturation_border.SubscribeMouseMove(saturation_border_mouse_move); + } + + void saturation_border_mouse_up(object sender, MouseButtonEventArgs e) => + Disposable.dispose(ref mouse_move_hook); + + void saturation_border_mouse_move(object sender, MouseEventArgs e) => + set_result_from_saturation_click(e.GetPosition(this)); + + void set_result_from_saturation_click(Point pt) { + var tr = (Color)Resources[_max_saturation_color_key]; + // do not turn to gray, or else hue context will be lost (i.e 0 or 1) + double left = 1 - MathUtils.within_range(0.01, 0.99, pt.X / _saturation_border.ActualWidth); + double down = MathUtils.within_range(0.01, 0.99, (pt.Y / _saturation_border.ActualHeight)); + var left_adj = ColorUtils.adjust_color(tr, Colors.White, left); + var result = ColorUtils.adjust_color(left_adj, Colors.Black, down); + using (_saturation_border_gate.update()) + _color_vm.result = result; + } + } + + void _tab_control_selection_changed(object sender, SelectionChangedEventArgs e) { + if (_hue_sat_tab.IsSelected) + _update_saturation_img(); + } + + void _update_saturation_img() => + _saturation_border_gate.try_update(() => + Resources[_max_saturation_color_key] = _color_vm.max_saturation); + + void _sample_image_click(BitmapSource img, Point pos) { + // https://social.msdn.microsoft.com/Forums/vstudio/en-US/82a5731e-e201-4aaf-8d4b-062b138338fe/getting-pixel-information-from-a-bitmapimage?forum=wpf + int stride = (int)img.Width * 4; + int size = (int)img.Height * stride; + byte[] pixels = new byte[(int)size]; + img.CopyPixels(pixels, stride, 0); + // Get pixel + var x = (int)pos.X; + var y = (int)pos.Y; + int index = y * stride + 4 * x; + byte red = pixels[index]; + byte green = pixels[index + 1]; + byte blue = pixels[index + 2]; + byte alpha = pixels[index + 3]; + var color = Color.FromArgb(alpha, blue, green, red); + _color_vm.result = color; + } + + void _sample_image_mouse_down(object sender, MouseButtonEventArgs e) { + Mouse.Capture(this); + MouseMove += _color_picker_control_mouse_move; + MouseUp += _color_picker_control_MouseUp; + } + + void _color_picker_control_mouse_move(object sender, MouseEventArgs e) { + var pos = e.GetPosition(_sample_image); + var img = _sample_image.Source as BitmapSource; + if (pos.X > 0 && pos.Y > 0 && pos.X < img.PixelWidth && pos.Y < img.PixelHeight) + _sample_image_click(img, pos); + } + + void _color_picker_control_MouseUp(object sender, MouseButtonEventArgs e) { + Mouse.Capture(null); + MouseMove -= _color_picker_control_mouse_move; + MouseUp -= _color_picker_control_MouseUp; + } + } + + class PaletteTabHeaderTemplateConverter : IMultiValueConverter { + public DataTemplate NormalTemplate { get; set; } + public DataTemplate EditableTemplate { get; set; } + + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { + if (ObjectHelper.try_convert_args(values, out ColorPaletteVM vm, out bool is_selected)) { + if (vm.can_user_edit && is_selected) + return EditableTemplate; + } + return NormalTemplate; + } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException(); + } + + class NamedColorCellEditingTemplateSelector : DataTemplateSelector { + public DataTemplate EditableTemplate { get; set; } + public DataTemplate ReadOnlyTemplate { get; set; } + + public override DataTemplate SelectTemplate(object item, DependencyObject container) => + item is NamedColorVM vm && vm.can_user_edit ? EditableTemplate : ReadOnlyTemplate; + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml b/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml new file mode 100644 index 000000000..e01ad5ef0 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml @@ -0,0 +1,26 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs b/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs new file mode 100644 index 000000000..2ca7bd734 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs @@ -0,0 +1,33 @@ +using mbts.ui.controls.color_picker; +using System.Collections.ObjectModel; +using System.Windows; +using System.Windows.Media; + +namespace mbts.ui.controls { + /// + /// Interaction logic for ColorPickerPopup.xaml + /// + partial class ColorPickerPopup : PopupControl { + public ColorPickerPopup() => + InitializeComponent(); + + public static readonly DependencyProperty SelectedColorProperty = + WPFHelper.create_dp( + nameof(SelectedColor), + FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, + Colors.Black); + + public Color SelectedColor { + get => (Color)GetValue(SelectedColorProperty); + set => SetValue(SelectedColorProperty, value); + } + + public static readonly DependencyProperty PalettesProperty = + WPFHelper.create_dp, ColorPickerPopup>(nameof(Palettes)); + + public ObservableCollection Palettes { + get => GetValue(PalettesProperty) as ObservableCollection; + set => SetValue(PalettesProperty, value); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml b/src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml new file mode 100644 index 000000000..592860148 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml.cs b/src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml.cs new file mode 100644 index 000000000..e0badf823 --- /dev/null +++ b/src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml.cs @@ -0,0 +1,47 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; + +namespace mbts.ui.controls.color_picker { + /// + /// Interaction logic for ColorPickerSwatch.xaml + /// + partial class ColorPickerSwatch : ListBox { + public ColorPickerSwatch() => + InitializeComponent(); + + public static readonly RoutedCommand + AssignColorCommand = new RoutedCommand(), + NameColorCommand = new RoutedCommand(); + + protected override DependencyObject GetContainerForItemOverride() { + var lbi = new ListBoxItem(); + // + var assign_color_mb = new MouseBinding(AssignColorCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.Control)); + BindingOperations.SetBinding(assign_color_mb, InputBinding.CommandParameterProperty, new Binding("DataContext") { Source = lbi }); + BindingOperations.SetBinding(assign_color_mb, InputBinding.CommandTargetProperty, + new Binding() { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ColorPickerControl), 1) }); + // + var name_color_mb = new MouseBinding(NameColorCommand, new MouseGesture(MouseAction.LeftClick, ModifierKeys.Alt)); + BindingOperations.SetBinding(name_color_mb, InputBinding.CommandParameterProperty, new Binding("DataContext") { Source = lbi }); + BindingOperations.SetBinding(name_color_mb, InputBinding.CommandTargetProperty, + new Binding() { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ColorPickerControl), 1) }); + // + lbi.InputBindings.Add(assign_color_mb); + lbi.InputBindings.Add(name_color_mb); + return lbi; + } + } + + class NamedColorItemToolTipConverter : IMultiValueConverter { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) => + ObjectHelper.try_convert_args(values, out string name, out bool can_user_edit) ? + $"{name} (Alt + Click for info{(can_user_edit ? ", Ctrl + Click to assign" : string.Empty)})" : + string.Empty; + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/CustomColorPicker.xaml b/src/client/spark/view/Controls/CustomColorPicker.xaml deleted file mode 100644 index 114631f83..000000000 --- a/src/client/spark/view/Controls/CustomColorPicker.xaml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +