From ab950cba919d9599c347d6dc5f20fcc8bbac96ec Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Fri, 18 May 2018 20:56:38 +0000 Subject: [PATCH] Merged from dev --- .gitignore | 3 + .vscode/c_cpp_properties.json | 6 +- .vscode/launch.json | 67 +- CMakeLists.txt | 3 +- docker/linux | 2 +- externals | 2 +- src/client/spark/Admin/AdminModel.cs | 30 + src/client/spark/Daemons/OrderTicketDaemon.cs | 3 +- src/client/spark/Daemons/ShellServices.cs | 4 + src/client/spark/IMenuItemVM.cs | 38 + src/client/spark/Images/Icons.cs | 6 +- src/client/spark/Images/Vector/Icons.xaml | 45 +- .../Modules/Market/MarketView/MarketViewVM.cs | 2 +- .../Market/MarketView/MarketViewView.xaml | 226 +- .../Market/MarketView/MarketViewView.xaml.cs | 7 +- .../Market/MarketView/MarketViewWindow.cs | 89 +- .../MarketView/MarketViewWindowFactory.cs | 8 +- .../Market/TimeAndSales/TimeAndSalesView.xaml | 3 +- .../TimeAndSales/TimeAndSalesView.xaml.cs | 9 +- .../Market/TimeAndSales/TimeAndSalesWindow.cs | 9 +- .../Spreader/ExecutionStrategyEditor.xaml | 5 +- .../Spreader/ExecutionStrategyEditor.xaml.cs | 41 +- .../Modules/Spreader/SyntheticDataHelper.cs | 4 + .../Modules/Spreader/SyntheticEditorView.xaml | 1 + .../Spreader/SyntheticManagementView.xaml.cs | 4 +- .../VM/ParameterRows/Leg/HedgeRatioModel.cs | 9 + ...teMarketVolumeBasedCrossCrossTicksModel.cs | 39 + ...ositeMarketVolumeBasedCrossEnabledModel.cs | 36 + ...iteMarketVolumeBasedCrossThresholdModel.cs | 41 + .../PostHedgePriceBasedCrossEnabledModel.cs | 0 ...ostHedgePriceBasedCrossMarketTicksModel.cs | 0 .../PostHedgePriceBasedCrossTicksModel.cs | 0 .../PostHedgeTimeBasedCrossEnabledModel.cs | 0 ...PostHedgeTimeBasedCrossMarketTicksModel.cs | 0 .../PostHedgeTimeBasedCrossTimeModel.cs | 0 .../PreHedgePaylessEnabledModel.cs | 0 .../PreHedgePaylessThresholdModel.cs | 0 .../PreHedgePaylessTicksModel.cs | 0 .../{ => Payup}/PreHedgePayupEnabledModel.cs | 0 .../PreHedgePayupThresholdModel.cs | 0 .../{ => Payup}/PreHedgePayupTicksModel.cs | 0 .../QuoteInsideMarketThrottleEnabled.cs | 0 .../QuoteInsideMarketThrottleMinMove.cs | 0 .../QuoteInsideMarketThrottleTicksModel.cs | 0 .../QuoteThrottleEnabledModel.cs | 0 .../QuoteThrottleInsideTicksModel.cs | 0 .../QuoteThrottleOutsideTicksModel.cs | 0 .../Spreader/VM/ParameterRows/RowModel.cs | 6 + .../Modules/Spreader/VM/SyntheticEditorVM.cs | 14 +- .../ActivityLog/ActivityLogCategories.cs | 2 +- .../spark/Modules/Trading/Fills/FillsVM.cs | 6 +- .../Modules/Trading/Fills/FillsView.xaml.cs | 7 +- .../Modules/Trading/Fills/FillsWindow.cs | 35 +- .../Trading/Fills/FillsWindowFactory.cs | 2 +- .../Modules/Trading/LadderWindowFactory.cs | 34 +- .../Modules/Trading/TradingShellModule.cs | 12 +- .../spark/Orders/OrderActivitySummarizer.cs | 6 +- src/client/spark/Orders/OrderIconFactory.cs | 4 +- .../spark/Orders/OrderPropertiesEditorVM.cs | 191 +- .../Orders/OrderTypeVMs/IcebergOrderVM.cs | 2 +- src/client/spark/Themes/generic.xaml | 1 + .../BeholderCollection.cs | 0 .../ObservableAggregateCollection.cs | 80 + .../ObservableAppendCollection.cs | 0 .../ObservableAutoWrapper.cs | 0 .../ObservableCollectionEx.cs | 0 .../ObservableDistinctCollection.cs | 0 .../ObservableEditableCollection.cs | 0 .../ObservableFilterCollection.cs | 0 .../ObservableSortedCollection.cs | 0 .../ObservantDictionary.cs | 0 .../core/{Utility => Collections}/SetMap.cs | 0 .../{Utility => Commands}/AsyncCommand.cs | 0 .../{Utility => Commands}/DelegateCommand.cs | 0 .../DelegateCommandParamObserver.cs | 0 .../ObservantAsyncCommand.cs | 0 .../{Utility => Commands}/ObservantCommand.cs | 0 .../{Utility => Commands}/TupleCommand.cs | 0 .../ExceptionAssert.cs | 0 .../spark/core/FontsAndColors/BTSColors.cs | 22 +- .../{Utility => FontsAndColors}/FontParams.cs | 0 .../GenericCollectionExtensions.cs | 35 + .../core/GlobalExtensions/GlobalExtensions.cs | 16 +- .../core/GlobalExtensions/ObjectHelper.cs | 11 + .../IInitializable.cs | 0 .../UserSettings/UserSettings.cs | 30 + .../UserSettings/UserSettingsHub.cs | 46 + .../WindowSettings/IWindowSettingsManager.cs | 66 + .../AnonymousEqualityComparer.cs | 0 src/client/spark/core/Utility/CompareUtils.cs | 18 + .../CustomModelAttributes.cs | 0 .../core/{utils => Utility}/MiscUtils.cs | 0 .../{utils => Utility}/ObservableDemuxer.cs | 0 .../{utils => Utility}/ReverseComparer.cs | 0 .../{utils => Utility}/SingleValuePump.cs | 0 .../TableUpdateTransform.cs | 0 .../spark/core/Utility/ThreadSafeCounter.cs | 22 + .../spark/core/Utility/ViewModelBase.cs | 235 +- src/client/spark/core/utils/CompareUtils.cs | 40 - .../view/Controls/ActionMenu/ActionMenu.xaml | 71 + .../Controls/ActionMenu/ActionMenu.xaml.cs | 22 + src/client/spark/view/Controls/Badge.cs | 49 +- .../spark/view/Controls/ColorPicker.xaml | 8 - .../spark/view/Controls/ColorPicker.xaml.cs | 85 - .../Controls/ColorPicker/Code/ColorPalette.cs | 112 + .../ColorPicker/Code/ColorPaletteVM.cs | 39 + .../ColorPicker/Code/ColorPickerVM.cs | 200 + .../ColorPicker/Code/ColorSwatchItem.cs | 43 + .../Controls/ColorPicker/Code/ColorUtils.cs | 186 + .../Controls/ColorPicker/Code/NamedColorVM.cs | 41 + .../ColorPicker/ColorPickerControl.xaml | 319 + .../ColorPicker/ColorPickerControl.xaml.cs | 236 + .../ColorPicker/ColorPickerPopup.xaml | 26 + .../ColorPicker/ColorPickerPopup.xaml.cs | 33 + .../ColorPicker/ColorPickerSwatch.xaml | 44 + .../ColorPicker/ColorPickerSwatch.xaml.cs | 47 + .../view/Controls/CustomColorPicker.xaml | 70 - .../view/Controls/CustomColorPicker.xaml.cs | 70 - .../Filters/DataGridFilterHelper.cs | 36 +- .../Filters/DataGridFilterProperties.cs | 34 +- .../DataGridEx/Filters/VM/TimeFilterVM.cs | 13 +- .../Filters/Views/FilterContentControl.xaml | 18 +- .../Views/FilterContentControl.xaml.cs | 20 +- .../Filters/Views/FilterTemplates.xaml | 63 +- .../Filters/Views/TimeFilterControl.xaml | 12 +- .../Filters/Views/TimeFilterControl.xaml.cs | 17 +- .../Controls/DialogSkirts/DialogSkirt.xaml | 71 + .../Controls/DialogSkirts/DialogSkirt.xaml.cs | 107 + .../view/Controls/FontPicker/FontPicker.xaml | 88 + .../Controls/FontPicker/FontPicker.xaml.cs | 100 + .../Controls/GradientCustomColorPicker.xaml | 61 - .../GradientCustomColorPicker.xaml.cs | 71 - .../view/Controls/Popup/PopupControl.xaml.cs | 17 +- .../view/Converters/ColorToBrushConverter.cs | 27 + .../spark/view/Converters/NotConverter.cs | 26 +- .../Extensions/Command/FileDialogCommand.cs | 160 +- .../view/Extensions/HighDpiExtensions.cs | 37 +- .../Extensions/TextElement/TextBoxBehavior.cs | 24 + .../spark/view/Extensions/WPFExtensions.cs | 21 +- .../view/Resources/ColorPickerPalette.png | Bin 0 -> 60205 bytes .../spark/view/Resources/ComboBoxes.xaml | 52 - .../spark/view/Resources/Converters.xaml | 1 + src/client/spark/view/Resources/DataGrid.xaml | 20 + .../spark/view/Resources/WindowStyle.xaml | 2 +- src/client/spark/view/Shell/Launcher.xaml | 2 +- src/client/spark/view/Spark/Core/TickUtils.cs | 9 - .../spark/view/Spark/Ladder/LadderGridHost.cs | 217 +- .../spark/view/Spark/Ladder/LadderOrderVM.cs | 97 +- .../view/Spark/Ladder/LadderOrdersHost.cs | 37 +- .../spark/view/Spark/Ladder/LadderSettings.cs | 149 +- .../Spark/Ladder/LadderSettingsDialog.xaml | 129 + .../Spark/Ladder/LadderSettingsDialog.xaml.cs | 13 + .../view/Spark/Ladder/LadderSettingsVM.cs | 197 + .../view/Spark/Ladder/LadderSettingsView.xaml | 251 + .../Spark/Ladder/LadderSettingsView.xaml.cs | 13 + .../view/Spark/Ladder/LadderTactileAdorner.cs | 6 +- .../spark/view/Spark/Ladder/LadderVM.cs | 81 +- .../spark/view/Spark/Ladder/LadderView.xaml | 89 +- .../spark/view/Spark/Ladder/LaderRender.cs | 47 +- .../spark/view/Spark/PAndL/PAndLModel.cs | 5 +- src/client/spark/view/Spark/PAndL/PAndLVM.cs | 4 +- .../spark/view/Spark/PAndL/PAndLView.xaml.cs | 1 - .../spark/view/Spark/PAndL/PnLCalculator.cs | 21 + src/client/spark/view/Spark/PAndL/PnLData.cs | 8 +- .../Spark/Shell/OrderBook/OrderBookRowVM.cs | 4 +- .../view/Spark/Shell/OrderBook/OrderBookVM.cs | 302 +- .../Spark/Shell/OrderBook/OrderBookView.xaml | 7 +- .../Shell/OrderBook/OrderBookView.xaml.cs | 10 +- .../spark/view/Spark/Utilities/MathUtils.cs | 10 + .../view/Spark/Utilities/OrderDataHelper.cs | 82 +- .../Spark/Utilities/WindowSettingsDialogVM.cs | 100 + .../spark/view/Spark/Utilities/WorkLoop.cs | 75 +- src/client/spark/view/Utility/Command.cs | 27 - src/client/spark/view/Utility/CursorHelper.cs | 11 +- src/client/spark/view/Utility/GlyphContext.cs | 29 +- .../Utility/IRequestClearFocus.cs | 0 .../Utility/IRequestViewClose.cs | 0 .../spark/view/Utility/InlineUserProperty.cs | 2 +- .../spark/view/Utility/KeyedStyleSelector.cs | 36 + .../view/Utility/KeyedTemplateSelector.cs | 36 + .../spark/view/Utility/PropertyUpdateGate.cs | 26 + src/client/spark/view/Utility/TextUtils.cs | 32 +- src/client/spark/view/Utility/WPFHelper.cs | 18 +- src/client/spark_api/api/ClientChannel.cs | 40 +- src/client/spark_api/api/Result.cs | 1 + .../spark_core/utils/AnonymousDisposable.cs | 1 + src/client/spark_sdk/samples/OrderSample.cs | 36 +- src/client/spark_sdk/samples/SDKMain.cs | 9 +- src/client/sparkcmd/Program.cs | 18 +- src/lib/CMakeDeps.cmake | 2 +- src/lib/api/apicore.proto | 7 + src/lib/api/apigateway.proto | 43 + src/lib/api/public/ApiUtils.h | 11 + src/lib/api/public/Result.h | 2 + src/lib/api/public/ServiceContext.h | 2 + src/lib/api/service_compiler/plugin.py | 89 +- .../templates/c#/immutable.pb.cs | 10 +- .../service_compiler/templates/fs/fable.fs | 91 + src/lib/api/service_compiler/templates/js/ts | 58 + .../api/service_helpers/AdminServiceUtils.cpp | 94 + .../api/service_helpers/AdminServiceUtils.h | 841 ++ src/lib/api/services/AccountService.proto | 56 - src/lib/api/services/AdminService.proto | 201 +- src/lib/api/services/OrderService.proto | 18 +- src/lib/api/services/UserService.proto | 16 +- src/lib/config/defaults/jetfix.conf | 483 +- src/lib/config/protos/MarketData.proto | 6 +- src/lib/config/protos/UI.proto | 7 + src/lib/config/protos/jetfix.proto | 3 - src/lib/md/Diag/ShmDumper.cpp | 8 +- src/lib/md/MDConsumerHandle.cpp | 26 +- src/lib/md/MDConsumerHandle.h | 16 +- src/lib/md/MDProducerHandle.cpp | 68 +- src/lib/md/MDProducerHandle.h | 20 +- src/lib/md/Shm/MDStructure.h | 16 +- src/lib/md/relay/RelayClient.cpp | 12 +- src/lib/md/test/md2_tests.cpp | 3 +- .../md/test/synthetic_book_merge_tests.cpp | 18 +- src/lib/sparkproto/SparkProtos.proto | 17 +- src/lib/utils/Dispatcher.cpp | 2 + src/lib/utils/Dispatcher.h | 7 + src/lib/utils/TimeStamp.h | 2 +- src/server/sparkd/CMakeDeps.cmake | 2 +- src/server/sparkd/CMakeLists.txt | 3 +- src/server/sparkd/cmds/AutoCert.cpp | 1388 ++- src/server/sparkd/cmds/Benchmark.cpp | 2 +- src/server/sparkd/cmds/QuickTest.cpp | 34 +- src/server/sparkd/cmds/Run.cpp | 77 +- src/server/sparkd/cmds/Span.cpp | 24 + src/server/sparkd/cmds/Span.h | 20 + .../exchange_sim/ExchangeSimApplication.cpp | 42 +- src/server/sparkd/http/ApiGateway.cpp | 141 + src/server/sparkd/http/ApiGateway.h | 25 + src/server/sparkd/http/WebServer.cpp | 263 + src/server/sparkd/http/WebServer.h | 16 + src/server/sparkd/main.cpp | 2 + .../md/platforms/mdp3_onixs/MDP3Listener.cpp | 18 +- .../md/platforms/mdp3_onixs/MDP3Listener.h | 5 +- .../mercury/synopsis/ISynopsisBuilder.h | 1 + .../sparkd/orderman/actors/AsyncFactory.cpp | 30 +- .../sparkd/orderman/actors/AsyncFactory.h | 2 +- .../orderman/actors/ExecutionGateway.cpp | 17 +- .../sparkd/orderman/actors/FillStore.cpp | 84 +- src/server/sparkd/orderman/actors/FillStore.h | 1 + .../sparkd/orderman/actors/OrderStore.cpp | 7 +- .../sparkd/orderman/actors/OrderStore.h | 2 +- .../sparkd/orderman/actors/ServiceBridge.cpp | 297 +- .../sparkd/orderman/actors/ServiceBridge.h | 14 +- .../actors/order_manager/OrderManager.cpp | 200 +- .../actors/order_manager/OrderManager.h | 8 +- .../actors/order_manager/OrderServices.h | 170 +- .../order_manager/OrderServicesData.cpp | 24 + .../actors/order_manager/OrderServicesData.h | 85 +- .../sparkd/orderman/doc/order_man_notes.org | 13 + .../orderman/events/ActivateOrderEvent.h | 2 +- .../sparkd/orderman/events/BookUpdateEvent.h | 16 +- .../sparkd/orderman/events/CancelOrderEvent.h | 1 - .../sparkd/orderman/events/CrackOrderEvent.h | 1 - .../events/CreateFIXBufferReplyEvent.h | 23 +- .../events/CreateFIXBufferRequestEvent.h | 1 - .../orderman/events/CreateOrderReplyEvent.h | 1 - .../orderman/events/CreateOrderRequestEvent.h | 1 - .../events/GatewayStatusChangeEvent.h | 6 +- .../orderman/events/NewAdminDataEvent.h | 24 + .../orderman/events/OrderManagerReadyEvent.h | 1 - .../sparkd/orderman/events/StoredFillEvent.h | 9 +- .../sparkd/orderman/events/StoredOrderEvent.h | 1 - .../sparkd/orderman/events/UpdateOrderEvent.h | 1 - .../sparkd/orderman/limiter/LimitStore.cpp | 77 + .../sparkd/orderman/limiter/LimitStore.h | 186 + .../sparkd/orderman/limiter/Limiter.cpp | 103 + src/server/sparkd/orderman/limiter/Limiter.h | 55 + .../sparkd/orderman/limiter/LimiterUtils.h | 73 + .../orderman/limiter/ProductLimitNode.cpp | 18 + .../orderman/limiter/ProductLimitNode.h | 70 + .../orderman/limiter/ProductLimitTree.cpp | 19 + .../orderman/limiter/ProductLimitTree.h | 36 + .../orderman/limiter/SecurityClipTree.h | 55 + .../orderman/limiter/SecurityLimitNode.cpp | 24 + .../orderman/limiter/SecurityLimitNode.h | 100 + .../orderman/limiter/SecurityLimitTree.cpp | 21 + .../orderman/limiter/SecurityLimitTree.h | 84 + .../orderman/limiter/tests/limit_tests.cpp | 334 + .../orderman/order_factory/OrderFactory.cpp | 17 +- .../orderman/order_factory/OrderFactory.h | 4 +- .../orderman/order_router/OrderRouter.cpp | 66 + .../orderman/order_router/OrderRouter.h | 57 + .../orderman/orderman_utils/orderman_common.h | 3 + .../sparkd/orderman/orders/IcebergOrder.cpp | 2 +- .../sparkd/orderman/orders/IcebergOrder.h | 2 +- .../sparkd/orderman/orders/NativeOrder.cpp | 418 +- .../sparkd/orderman/orders/NativeOrder.h | 4 +- src/server/sparkd/orderman/orders/Order.h | 2 +- .../orders/PreActivationOrderServices.h | 13 +- .../sparkd/orderman/orders/TimeBoxOrder.cpp | 2 +- .../sparkd/orderman/orders/TimeBoxOrder.h | 2 +- .../orders/spreader_orders/SpreaderOrder.cpp | 2 +- .../orders/spreader_orders/SpreaderOrder.h | 4 +- .../spreader/SpreaderBookkeepingData.h | 2 +- .../spreader_orders/spreader/SpreaderUtils.h | 42 +- .../HedgerWorkingStateWorker.cpp | 5 +- .../orderman/server/OrderServiceServer.cpp | 46 +- .../sparkd/position/MarginServiceCore.cpp | 1 - .../sparkd/position/tests/PositionTests.cpp | 2 - .../sparkd/risk_limits/AccountRiskLimiter.cpp | 139 - .../sparkd/risk_limits/AccountRiskLimiter.h | 67 - .../sparkd/risk_limits/IRiskLimitObserver.cpp | 9 - .../sparkd/risk_limits/IRiskLimitObserver.h | 17 - .../risk_limits/OperatorRiskLimiter.cpp | 96 - .../sparkd/risk_limits/OperatorRiskLimiter.h | 44 - .../sparkd/risk_limits/RiskLimitManager.cpp | 143 - .../sparkd/risk_limits/RiskLimitManager.h | 54 - .../sparkd/risk_limits/RiskLimitState.h | 16 - src/server/sparkd/risk_limits/RiskLimiter.cpp | 142 - src/server/sparkd/risk_limits/RiskLimiter.h | 38 - src/server/sparkd/risk_limits/SymbolKey.cpp | 14 - src/server/sparkd/risk_limits/SymbolKey.h | 14 - .../risk_limits/tests/RiskLimitsTests.cpp | 414 - src/server/sparkd/securities/ISecurityDB.h | 2 +- src/server/sparkd/securities/MapSecurityDB.h | 2 +- .../sparkd/user/AccountServiceServer.cpp | 212 - src/server/sparkd/user/AccountServiceServer.h | 35 - src/server/sparkd/user/AdminServiceServer.cpp | 296 + src/server/sparkd/user/AdminServiceServer.h | 79 + src/server/sparkd/user/UserServiceServer.cpp | 277 +- src/server/sparkd/user/UserServiceServer.h | 7 - .../sparkd/user/tests/UserAndAccountTests.cpp | 275 - .../sparkd/user/tests/admin_service_tests.cpp | 162 + src/web/CMakeDeps.cmake | 1 + src/web/CMakeLists.txt | 41 + src/web/api/__tests__/ServiceContext.test.ts | 25 + src/web/api/build.sh | 67 + src/web/api/jest.config.js | 23 + src/web/api/package-lock.json | 6645 ++++++++++++++ src/web/api/package.json | 34 + src/web/api/quiet_build.sh | 12 + src/web/api/src/DynamicService.ts | 81 + src/web/api/src/ServiceContext.ts | 175 + src/web/api/src/bts_assert.ts | 13 + src/web/api/tsconfig.json | 30 + src/web/api/tsconfig.release.json | 11 + src/web/ui/.paket/Paket.Restore.targets | 276 + src/web/ui/.paket/paket.exe | Bin 0 -> 8404776 bytes src/web/ui/.paket/paket.exe.config | 24 + src/web/ui/.paket/paket.targets | 71 + src/web/ui/.vscode/tasks.json | 42 + src/web/ui/NuGet.Config | 10 + src/web/ui/package-lock.json | 8022 +++++++++++++++++ src/web/ui/package.json | 40 + src/web/ui/paket-files/paket.restore.cached | 701 ++ src/web/ui/paket.dependencies | 13 + src/web/ui/paket.lock | 701 ++ src/web/ui/public/font-awesome.min.css | 4 + .../ui/public/fonts/fontawesome-webfont.woff2 | Bin 0 -> 71896 bytes src/web/ui/public/img/favicon.ico | Bin 0 -> 1150 bytes src/web/ui/public/index.html | 17 + src/web/ui/sass/main.sass | 31 + src/web/ui/src/Access.fs | 97 + src/web/ui/src/Accounts/ClipLimits.fs | 51 + src/web/ui/src/Accounts/ProductLimits.fs | 73 + src/web/ui/src/Accounts/SecurityLimits.fs | 63 + src/web/ui/src/Accounts/State.fs | 140 + src/web/ui/src/Accounts/Types.fs | 63 + src/web/ui/src/Accounts/View.fs | 204 + src/web/ui/src/App.fs | 126 + src/web/ui/src/Cmd.fs | 7 + src/web/ui/src/Controls/Button.fs | 57 + src/web/ui/src/Controls/DataGrid.fs | 51 + src/web/ui/src/Controls/Fields.fs | 195 + src/web/ui/src/Controls/ReactGrid.fs | 92 + src/web/ui/src/Controls/Table.fs | 39 + src/web/ui/src/Controls/nbsp.fs | 7 + src/web/ui/src/Global.fs | 32 + src/web/ui/src/Imports.fs | 11 + src/web/ui/src/Lens.fs | 18 + src/web/ui/src/Login/Login.fs | 91 + src/web/ui/src/Navbar/View.fs | 7 + src/web/ui/src/State.fs | 39 + src/web/ui/src/Types.fs | 25 + src/web/ui/src/Users/State.fs | 235 + src/web/ui/src/Users/Types.fs | 53 + src/web/ui/src/Users/View.fs | 245 + src/web/ui/src/Util/EnumUtils.fs | 52 + src/web/ui/src/Util/JSMap.fs | 67 + src/web/ui/src/paket.references | 7 + src/web/ui/src/ui.fsproj | 51 + src/web/ui/webpack.config.js | 80 + src/webui.sln | 16 + testing/cycle_info.txt | 13 +- .../spreader_common_setup_1.txt} | 0 .../spreader_common_setup_2.txt} | 0 testing/manual/admin/clip_limits.txt | 24 + testing/manual/admin/order_router.txt | 38 + .../manual/admin/product_position_limits.txt | 26 + .../manual/admin/security_position_limits.txt | 35 + .../manual/admin/spread_position_limits.txt | 29 + .../manual/admin/user_account_activation.txt | 19 + .../manual/admin/users_accounts_basics.txt | 20 + testing/manual/{misc => forms}/fills.txt | 0 .../manual/{misc => forms}/market_view.txt | 0 .../manual/{misc/P&L.txt => forms2/PAndL.txt} | 7 +- .../{misc => forms2}/time_and_sales.txt | 0 testing/manual/{misc => ladder}/ladder.txt | 0 testing/manual/ladder/ui_performance.txt | 16 + testing/manual/misc/workspaces.txt | 2 +- .../manual/{misc => orders}/order_book.txt | 0 testing/manual/{misc => orders}/ticket.txt | 0 testing/manual/settings/UserSettingsTest.txt | 84 + .../hedge_ratio.txt | 0 .../quoting_throttle.txt | 0 .../simple_sanity.txt | 0 .../post_hedge_ticks_away_cross.txt | 0 .../post_hedge_time_based_cross.txt | 0 .../pre_hedge_pay_less.txt | 0 .../pre_hedge_payup.txt | 0 testing/post_to_jira.sh | 4 +- tools/Protobuf.cmake | 4 +- tools/audit_uploader/audit_uploader.py | 128 + tools/audit_uploader/example_job_file.txt | 19 + tools/docker_update.sh | 8 + tools/replicator/build_win.sh | 2 +- tools/replicator/replicate_to_linux_vm.py | 3 + tools/replicator/replicate_to_windows_vm.py | 1 + tools/spark_vm_shell.sh | 5 +- 424 files changed, 31620 insertions(+), 4908 deletions(-) create mode 100644 src/client/spark/Admin/AdminModel.cs create mode 100644 src/client/spark/IMenuItemVM.cs create mode 100644 src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/OppositeMarketVolumeBasedCross/PostHedgeOppositeMarketVolumeBasedCrossCrossTicksModel.cs create mode 100644 src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/OppositeMarketVolumeBasedCross/PostHedgeOppositeMarketVolumeBasedCrossEnabledModel.cs create mode 100644 src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/OppositeMarketVolumeBasedCross/PostHedgeOppositeMarketVolumeBasedCrossThresholdModel.cs rename src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/{ => PriceBasedCross}/PostHedgePriceBasedCrossEnabledModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/{ => PriceBasedCross}/PostHedgePriceBasedCrossMarketTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/{ => PriceBasedCross}/PostHedgePriceBasedCrossTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/{ => TimeBasedCross}/PostHedgeTimeBasedCrossEnabledModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/{ => TimeBasedCross}/PostHedgeTimeBasedCrossMarketTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PostHedge/{ => TimeBasedCross}/PostHedgeTimeBasedCrossTimeModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PreHedge/{ => Payless}/PreHedgePaylessEnabledModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PreHedge/{ => Payless}/PreHedgePaylessThresholdModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PreHedge/{ => Payless}/PreHedgePaylessTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PreHedge/{ => Payup}/PreHedgePayupEnabledModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PreHedge/{ => Payup}/PreHedgePayupThresholdModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/PreHedge/{ => Payup}/PreHedgePayupTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/Quote/{ => InsideMarketThrottle}/QuoteInsideMarketThrottleEnabled.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/Quote/{ => InsideMarketThrottle}/QuoteInsideMarketThrottleMinMove.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/Quote/{ => InsideMarketThrottle}/QuoteInsideMarketThrottleTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/Quote/{ => Throttle}/QuoteThrottleEnabledModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/Quote/{ => Throttle}/QuoteThrottleInsideTicksModel.cs (100%) rename src/client/spark/Modules/Spreader/VM/ParameterRows/Quote/{ => Throttle}/QuoteThrottleOutsideTicksModel.cs (100%) rename src/client/spark/core/{Utility => Collections}/BeholderCollection.cs (100%) create mode 100644 src/client/spark/core/Collections/ObservableAggregateCollection.cs rename src/client/spark/core/{Utility => Collections}/ObservableAppendCollection.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservableAutoWrapper.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservableCollectionEx.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservableDistinctCollection.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservableEditableCollection.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservableFilterCollection.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservableSortedCollection.cs (100%) rename src/client/spark/core/{Utility => Collections}/ObservantDictionary.cs (100%) rename src/client/spark/core/{Utility => Collections}/SetMap.cs (100%) rename src/client/spark/core/{Utility => Commands}/AsyncCommand.cs (100%) rename src/client/spark/core/{Utility => Commands}/DelegateCommand.cs (100%) rename src/client/spark/core/{Utility => Commands}/DelegateCommandParamObserver.cs (100%) rename src/client/spark/core/{Utility => Commands}/ObservantAsyncCommand.cs (100%) rename src/client/spark/core/{Utility => Commands}/ObservantCommand.cs (100%) rename src/client/spark/core/{Utility => Commands}/TupleCommand.cs (100%) rename src/client/spark/core/{Utility => Exceptions}/ExceptionAssert.cs (100%) rename src/client/spark/core/{Utility => FontsAndColors}/FontParams.cs (100%) rename src/client/spark/core/{utils => ShellInterface}/IInitializable.cs (100%) create mode 100644 src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs create mode 100644 src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs create mode 100644 src/client/spark/core/ShellInterface/UserSettings/WindowSettings/IWindowSettingsManager.cs rename src/client/spark/core/{utils => Utility}/AnonymousEqualityComparer.cs (100%) create mode 100644 src/client/spark/core/Utility/CompareUtils.cs rename src/client/spark/core/{utils => Utility}/CustomModelAttributes.cs (100%) rename src/client/spark/core/{utils => Utility}/MiscUtils.cs (100%) rename src/client/spark/core/{utils => Utility}/ObservableDemuxer.cs (100%) rename src/client/spark/core/{utils => Utility}/ReverseComparer.cs (100%) rename src/client/spark/core/{utils => Utility}/SingleValuePump.cs (100%) rename src/client/spark/core/{utils => Utility}/TableUpdateTransform.cs (100%) create mode 100644 src/client/spark/core/Utility/ThreadSafeCounter.cs delete mode 100644 src/client/spark/core/utils/CompareUtils.cs create mode 100644 src/client/spark/view/Controls/ActionMenu/ActionMenu.xaml create mode 100644 src/client/spark/view/Controls/ActionMenu/ActionMenu.xaml.cs delete mode 100644 src/client/spark/view/Controls/ColorPicker.xaml delete mode 100644 src/client/spark/view/Controls/ColorPicker.xaml.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/Code/ColorPalette.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/Code/ColorPaletteVM.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/Code/ColorPickerVM.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/Code/ColorUtils.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/Code/NamedColorVM.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml create mode 100644 src/client/spark/view/Controls/ColorPicker/ColorPickerControl.xaml.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml create mode 100644 src/client/spark/view/Controls/ColorPicker/ColorPickerPopup.xaml.cs create mode 100644 src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml create mode 100644 src/client/spark/view/Controls/ColorPicker/ColorPickerSwatch.xaml.cs delete mode 100644 src/client/spark/view/Controls/CustomColorPicker.xaml delete mode 100644 src/client/spark/view/Controls/CustomColorPicker.xaml.cs create mode 100644 src/client/spark/view/Controls/DialogSkirts/DialogSkirt.xaml create mode 100644 src/client/spark/view/Controls/DialogSkirts/DialogSkirt.xaml.cs create mode 100644 src/client/spark/view/Controls/FontPicker/FontPicker.xaml create mode 100644 src/client/spark/view/Controls/FontPicker/FontPicker.xaml.cs delete mode 100644 src/client/spark/view/Controls/GradientCustomColorPicker.xaml delete mode 100644 src/client/spark/view/Controls/GradientCustomColorPicker.xaml.cs create mode 100644 src/client/spark/view/Converters/ColorToBrushConverter.cs create mode 100644 src/client/spark/view/Resources/ColorPickerPalette.png create mode 100644 src/client/spark/view/Spark/Ladder/LadderSettingsDialog.xaml create mode 100644 src/client/spark/view/Spark/Ladder/LadderSettingsDialog.xaml.cs create mode 100644 src/client/spark/view/Spark/Ladder/LadderSettingsVM.cs create mode 100644 src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml create mode 100644 src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml.cs create mode 100644 src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs delete mode 100644 src/client/spark/view/Utility/Command.cs rename src/client/spark/{core => view}/Utility/IRequestClearFocus.cs (100%) rename src/client/spark/{core => view}/Utility/IRequestViewClose.cs (100%) create mode 100644 src/client/spark/view/Utility/KeyedStyleSelector.cs create mode 100644 src/client/spark/view/Utility/KeyedTemplateSelector.cs create mode 100644 src/client/spark/view/Utility/PropertyUpdateGate.cs create mode 100644 src/lib/api/apigateway.proto create mode 100644 src/lib/api/service_compiler/templates/fs/fable.fs create mode 100644 src/lib/api/service_compiler/templates/js/ts create mode 100644 src/lib/api/service_helpers/AdminServiceUtils.cpp create mode 100644 src/lib/api/service_helpers/AdminServiceUtils.h delete mode 100644 src/lib/api/services/AccountService.proto create mode 100644 src/server/sparkd/cmds/Span.cpp create mode 100644 src/server/sparkd/cmds/Span.h create mode 100644 src/server/sparkd/http/ApiGateway.cpp create mode 100644 src/server/sparkd/http/ApiGateway.h create mode 100644 src/server/sparkd/http/WebServer.cpp create mode 100644 src/server/sparkd/http/WebServer.h create mode 100644 src/server/sparkd/orderman/actors/order_manager/OrderServicesData.cpp create mode 100644 src/server/sparkd/orderman/events/NewAdminDataEvent.h create mode 100644 src/server/sparkd/orderman/limiter/LimitStore.cpp create mode 100644 src/server/sparkd/orderman/limiter/LimitStore.h create mode 100644 src/server/sparkd/orderman/limiter/Limiter.cpp create mode 100644 src/server/sparkd/orderman/limiter/Limiter.h create mode 100644 src/server/sparkd/orderman/limiter/LimiterUtils.h create mode 100644 src/server/sparkd/orderman/limiter/ProductLimitNode.cpp create mode 100644 src/server/sparkd/orderman/limiter/ProductLimitNode.h create mode 100644 src/server/sparkd/orderman/limiter/ProductLimitTree.cpp create mode 100644 src/server/sparkd/orderman/limiter/ProductLimitTree.h create mode 100644 src/server/sparkd/orderman/limiter/SecurityClipTree.h create mode 100644 src/server/sparkd/orderman/limiter/SecurityLimitNode.cpp create mode 100644 src/server/sparkd/orderman/limiter/SecurityLimitNode.h create mode 100644 src/server/sparkd/orderman/limiter/SecurityLimitTree.cpp create mode 100644 src/server/sparkd/orderman/limiter/SecurityLimitTree.h create mode 100644 src/server/sparkd/orderman/limiter/tests/limit_tests.cpp create mode 100644 src/server/sparkd/orderman/order_router/OrderRouter.cpp create mode 100644 src/server/sparkd/orderman/order_router/OrderRouter.h delete mode 100644 src/server/sparkd/risk_limits/AccountRiskLimiter.cpp delete mode 100644 src/server/sparkd/risk_limits/AccountRiskLimiter.h delete mode 100644 src/server/sparkd/risk_limits/IRiskLimitObserver.cpp delete mode 100644 src/server/sparkd/risk_limits/IRiskLimitObserver.h delete mode 100644 src/server/sparkd/risk_limits/OperatorRiskLimiter.cpp delete mode 100644 src/server/sparkd/risk_limits/OperatorRiskLimiter.h delete mode 100644 src/server/sparkd/risk_limits/RiskLimitManager.cpp delete mode 100644 src/server/sparkd/risk_limits/RiskLimitManager.h delete mode 100644 src/server/sparkd/risk_limits/RiskLimitState.h delete mode 100644 src/server/sparkd/risk_limits/RiskLimiter.cpp delete mode 100644 src/server/sparkd/risk_limits/RiskLimiter.h delete mode 100644 src/server/sparkd/risk_limits/SymbolKey.cpp delete mode 100644 src/server/sparkd/risk_limits/SymbolKey.h delete mode 100644 src/server/sparkd/risk_limits/tests/RiskLimitsTests.cpp delete mode 100644 src/server/sparkd/user/AccountServiceServer.cpp delete mode 100644 src/server/sparkd/user/AccountServiceServer.h create mode 100644 src/server/sparkd/user/AdminServiceServer.cpp create mode 100644 src/server/sparkd/user/AdminServiceServer.h delete mode 100644 src/server/sparkd/user/tests/UserAndAccountTests.cpp create mode 100644 src/server/sparkd/user/tests/admin_service_tests.cpp create mode 100644 src/web/CMakeDeps.cmake create mode 100644 src/web/CMakeLists.txt create mode 100644 src/web/api/__tests__/ServiceContext.test.ts create mode 100755 src/web/api/build.sh create mode 100644 src/web/api/jest.config.js create mode 100644 src/web/api/package-lock.json create mode 100644 src/web/api/package.json create mode 100644 src/web/api/quiet_build.sh create mode 100644 src/web/api/src/DynamicService.ts create mode 100644 src/web/api/src/ServiceContext.ts create mode 100644 src/web/api/src/bts_assert.ts create mode 100644 src/web/api/tsconfig.json create mode 100644 src/web/api/tsconfig.release.json create mode 100644 src/web/ui/.paket/Paket.Restore.targets create mode 100644 src/web/ui/.paket/paket.exe create mode 100644 src/web/ui/.paket/paket.exe.config create mode 100644 src/web/ui/.paket/paket.targets create mode 100644 src/web/ui/.vscode/tasks.json create mode 100644 src/web/ui/NuGet.Config create mode 100644 src/web/ui/package-lock.json create mode 100644 src/web/ui/package.json create mode 100644 src/web/ui/paket-files/paket.restore.cached create mode 100644 src/web/ui/paket.dependencies create mode 100644 src/web/ui/paket.lock create mode 100644 src/web/ui/public/font-awesome.min.css create mode 100644 src/web/ui/public/fonts/fontawesome-webfont.woff2 create mode 100644 src/web/ui/public/img/favicon.ico create mode 100644 src/web/ui/public/index.html create mode 100644 src/web/ui/sass/main.sass create mode 100644 src/web/ui/src/Access.fs create mode 100644 src/web/ui/src/Accounts/ClipLimits.fs create mode 100644 src/web/ui/src/Accounts/ProductLimits.fs create mode 100644 src/web/ui/src/Accounts/SecurityLimits.fs create mode 100644 src/web/ui/src/Accounts/State.fs create mode 100644 src/web/ui/src/Accounts/Types.fs create mode 100644 src/web/ui/src/Accounts/View.fs create mode 100644 src/web/ui/src/App.fs create mode 100644 src/web/ui/src/Cmd.fs create mode 100644 src/web/ui/src/Controls/Button.fs create mode 100644 src/web/ui/src/Controls/DataGrid.fs create mode 100644 src/web/ui/src/Controls/Fields.fs create mode 100644 src/web/ui/src/Controls/ReactGrid.fs create mode 100644 src/web/ui/src/Controls/Table.fs create mode 100644 src/web/ui/src/Controls/nbsp.fs create mode 100644 src/web/ui/src/Global.fs create mode 100644 src/web/ui/src/Imports.fs create mode 100644 src/web/ui/src/Lens.fs create mode 100644 src/web/ui/src/Login/Login.fs create mode 100644 src/web/ui/src/Navbar/View.fs create mode 100644 src/web/ui/src/State.fs create mode 100644 src/web/ui/src/Types.fs create mode 100644 src/web/ui/src/Users/State.fs create mode 100644 src/web/ui/src/Users/Types.fs create mode 100644 src/web/ui/src/Users/View.fs create mode 100644 src/web/ui/src/Util/EnumUtils.fs create mode 100644 src/web/ui/src/Util/JSMap.fs create mode 100644 src/web/ui/src/paket.references create mode 100644 src/web/ui/src/ui.fsproj create mode 100644 src/web/ui/webpack.config.js create mode 100644 src/webui.sln rename testing/{manual/spreader/common_setup_1.txt => docs/spreader_common_setup_1.txt} (100%) rename testing/{manual/spreader/common_setup_2.txt => docs/spreader_common_setup_2.txt} (100%) create mode 100644 testing/manual/admin/clip_limits.txt create mode 100644 testing/manual/admin/order_router.txt create mode 100644 testing/manual/admin/product_position_limits.txt create mode 100644 testing/manual/admin/security_position_limits.txt create mode 100644 testing/manual/admin/spread_position_limits.txt create mode 100644 testing/manual/admin/user_account_activation.txt create mode 100644 testing/manual/admin/users_accounts_basics.txt rename testing/manual/{misc => forms}/fills.txt (100%) rename testing/manual/{misc => forms}/market_view.txt (100%) rename testing/manual/{misc/P&L.txt => forms2/PAndL.txt} (88%) rename testing/manual/{misc => forms2}/time_and_sales.txt (100%) rename testing/manual/{misc => ladder}/ladder.txt (100%) create mode 100644 testing/manual/ladder/ui_performance.txt rename testing/manual/{misc => orders}/order_book.txt (100%) rename testing/manual/{misc => orders}/ticket.txt (100%) create mode 100644 testing/manual/settings/UserSettingsTest.txt rename testing/manual/{spreader => spreader_misc}/hedge_ratio.txt (100%) rename testing/manual/{spreader => spreader_misc}/quoting_throttle.txt (100%) rename testing/manual/{spreader => spreader_misc}/simple_sanity.txt (100%) rename testing/manual/{spreader => spreader_post_hedge}/post_hedge_ticks_away_cross.txt (100%) rename testing/manual/{spreader => spreader_post_hedge}/post_hedge_time_based_cross.txt (100%) rename testing/manual/{spreader => spreader_pre_hedge}/pre_hedge_pay_less.txt (100%) rename testing/manual/{spreader => spreader_pre_hedge}/pre_hedge_payup.txt (100%) create mode 100644 tools/audit_uploader/audit_uploader.py create mode 100644 tools/audit_uploader/example_job_file.txt create mode 100644 tools/docker_update.sh 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 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +