UI - Added reusable device visualizer

Settings - Show device LED images in settings
Editor - Improved performance on big surfaces
This commit is contained in:
SpoinkyNL committed 2020-04-15 12:27:58 +02:00
1 parent 7c53533113
commit 46aef81600
31 files changed
+407 -402

No files matched your search

@@ -0,0 +1,135 @@
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:converters="clr-namespace:Artemis.UI.Shared.Converters" x:Class="Artemis.UI.Shared.Controls.ColorPicker"
mc:Ignorable="d"
d:DesignHeight="101.848" d:DesignWidth="242.956">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.ColorPicker.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
</ResourceDictionary.MergedDictionaries>
<converters:ColorToStringConverter x:Key="ColorToStringConverter" />
<converters:ColorToSolidColorConverter x:Key="ColorToSolidColorConverter" />
<VisualBrush x:Key="Checkerboard" TileMode="Tile" Stretch="Uniform" ViewportUnits="Absolute" Viewport="0,0,10,10">
<VisualBrush.Visual>
<Grid Width="10" Height="10">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Fill="Gray" />
<Rectangle Grid.Row="0" Grid.Column="1" Fill="White" />
<Rectangle Grid.Row="1" Grid.Column="0" Fill="White" />
<Rectangle Grid.Row="1" Grid.Column="1" Fill="Gray" />
</Grid>
</VisualBrush.Visual>
</VisualBrush>
<ControlTemplate x:Key="MaterialDesignOpacitySlider" TargetType="{x:Type Slider}">
<Border
x:Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="1" Height="8" CornerRadius="4" Background="{StaticResource Checkerboard}">
<Border Height="8" CornerRadius="4">
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
<GradientStop Offset="0" Color="Transparent" />
<GradientStop Offset="1.0"
Color="{Binding Color, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Converter={StaticResource ColorToSolidColorConverter}}" />
</LinearGradientBrush>
</Border.Background>
</Border>
</Border>
<Track
x:Name="PART_Track"
Grid.Row="1"
OpacityMask="{x:Null}">
<Track.DecreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.DecreaseLarge}" Style="{StaticResource MaterialDesignHorizontalColorSliderTrackRepeatButton}" />
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.IncreaseLarge}" Style="{StaticResource MaterialDesignHorizontalColorSliderTrackRepeatButton}" />
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb x:Name="Thumb" Width="20" Height="20" VerticalAlignment="Center" Focusable="False" OverridesDefaultStyle="True"
Template="{StaticResource MaterialDesignColorSliderThumb}">
<Thumb.Foreground>
<SolidColorBrush
Color="{Binding Color, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Mode=OneWay, Converter={StaticResource ColorToSolidColorConverter}}" />
</Thumb.Foreground>
</Thumb>
</Track.Thumb>
</Track>
</Grid>
</Border>
</ControlTemplate>
</ResourceDictionary>
</UserControl.Resources>
<Grid HorizontalAlignment="Stretch">
<!-- Style="{StaticResource MaterialDesignFloatingHintTextBox}" -->
<!-- Padding="0 0 10 0" -->
<TextBox x:Name="ColorCodeTextBox"
materialDesign:TextFieldAssist.TextBoxViewMargin="1 0 1 0"
Text="{Binding Color, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Converter={StaticResource ColorToStringConverter}}"
MinWidth="95"
MaxLength="9"
Margin="0"
HorizontalAlignment="Stretch" />
<Border Width="15"
Height="15"
CornerRadius="15"
Margin="0,0,0,2"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Background="{StaticResource Checkerboard}">
<Ellipse Stroke="{DynamicResource NormalBorderBrush}" Cursor="Hand" MouseUp="UIElement_OnMouseUp">
<Ellipse.Fill>
<SolidColorBrush Color="{Binding Color, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Mode=OneWay}" />
</Ellipse.Fill>
</Ellipse>
</Border>
<Popup AllowsTransparency="True"
Placement="Bottom"
CustomPopupPlacementCallback="{x:Static materialDesign:CustomPopupPlacementCallbackHelper.LargePopupCallback}"
PlacementTarget="{Binding ElementName=PART_TextBox}"
StaysOpen="False"
PopupAnimation="Fade"
IsOpen="{Binding PopupOpen, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
<materialDesign:Card Width="200" Height="200" Margin="30" materialDesign:ShadowAssist.ShadowDepth="Depth4">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="160" />
<RowDefinition />
</Grid.RowDefinitions>
<materialDesign:ColorPicker Grid.Row="0" Color="{Binding Color, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
<Slider Grid.Row="1" Margin="8"
IsMoveToPointEnabled="True"
Orientation="Horizontal"
Style="{StaticResource MaterialDesignColorSlider}"
Template="{StaticResource MaterialDesignOpacitySlider}"
Value="{Binding ColorOpacity, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
Maximum="255" />
</Grid>
</materialDesign:Card>
</Popup>
</Grid>
</UserControl>
@@ -0,0 +1,117 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace Artemis.UI.Shared.Controls
{
/// <summary>
/// Interaction logic for ColorPicker.xaml
/// </summary>
public partial class ColorPicker : UserControl, INotifyPropertyChanged
{
public static readonly DependencyProperty ColorProperty = DependencyProperty.Register(nameof(Color), typeof(Color), typeof(ColorPicker),
new FrameworkPropertyMetadata(default(Color), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ColorPropertyChangedCallback));
public static readonly DependencyProperty PopupOpenProperty = DependencyProperty.Register(nameof(PopupOpen), typeof(bool), typeof(ColorPicker),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, PopupOpenPropertyChangedCallback));
internal static readonly DependencyProperty ColorOpacityProperty = DependencyProperty.Register(nameof(ColorOpacity), typeof(byte), typeof(ColorPicker),
new FrameworkPropertyMetadata((byte) 255, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ColorOpacityPropertyChangedCallback));
public static readonly RoutedEvent ColorChangedEvent =
EventManager.RegisterRoutedEvent(
nameof(Color),
RoutingStrategy.Bubble,
typeof(RoutedPropertyChangedEventHandler<Color>),
typeof(ColorPicker));
public static readonly RoutedEvent PopupOpenChangedEvent =
EventManager.RegisterRoutedEvent(
nameof(PopupOpen),
RoutingStrategy.Bubble,
typeof(RoutedPropertyChangedEventHandler<bool>),
typeof(ColorPicker));
private bool _inCallback;
public ColorPicker()
{
InitializeComponent();
}
public Color Color
{
get => (Color) GetValue(ColorProperty);
set => SetValue(ColorProperty, value);
}
public bool PopupOpen
{
get => (bool) GetValue(PopupOpenProperty);
set => SetValue(PopupOpenProperty, value);
}
internal byte ColorOpacity
{
get => (byte) GetValue(ColorOpacityProperty);
set => SetValue(ColorOpacityProperty, value);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private static void ColorPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
colorPicker._inCallback = true;
colorPicker.SetCurrentValue(ColorOpacityProperty, ((Color) e.NewValue).A);
colorPicker.OnPropertyChanged(nameof(Color));
colorPicker._inCallback = false;
}
private static void PopupOpenPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
colorPicker._inCallback = true;
colorPicker.OnPropertyChanged(nameof(PopupOpen));
colorPicker._inCallback = false;
}
private static void ColorOpacityPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorPicker = (ColorPicker) d;
if (colorPicker._inCallback)
return;
colorPicker._inCallback = true;
var color = colorPicker.Color;
if (e.NewValue is byte opacity)
color = Color.FromArgb(opacity, color.R, color.G, color.B);
colorPicker.SetCurrentValue(ColorProperty, color);
colorPicker.OnPropertyChanged(nameof(ColorOpacity));
colorPicker._inCallback = false;
}
private void UIElement_OnMouseUp(object sender, MouseButtonEventArgs e)
{
PopupOpen = !PopupOpen;
}
}
}
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Artemis.Core.Models.Surface;
using RGB.NET.Core;
using Stylet;
namespace Artemis.UI.Shared.Controls
{
public class DeviceVisualizer : FrameworkElement
{
public static readonly DependencyProperty DeviceProperty = DependencyProperty.Register(nameof(Device), typeof(ArtemisDevice), typeof(DeviceVisualizer),
new FrameworkPropertyMetadata(default(ArtemisDevice), FrameworkPropertyMetadataOptions.AffectsRender, DevicePropertyChangedCallback));
public static readonly DependencyProperty ShowColorsProperty = DependencyProperty.Register(nameof(ShowColors), typeof(bool), typeof(DeviceVisualizer),
new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.AffectsRender));
private BitmapImage _deviceImage;
private List<DeviceVisualizerLed> _deviceVisualizerLeds;
private DrawingGroup _backingStore;
private static void DevicePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var deviceVisualizer = (DeviceVisualizer) d;
deviceVisualizer.Dispatcher.Invoke(() =>
{
deviceVisualizer.SubscribeToSurfaceUpdate((ArtemisDevice) e.OldValue, (ArtemisDevice) e.NewValue);
deviceVisualizer.Initialize();
});
}
public ArtemisDevice Device
{
get => (ArtemisDevice) GetValue(DeviceProperty);
set => SetValue(DeviceProperty, value);
}
public bool ShowColors
{
get => (bool) GetValue(ShowColorsProperty);
set => SetValue(ShowColorsProperty, value);
}
public DeviceVisualizer()
{
_backingStore = new DrawingGroup();
_deviceVisualizerLeds = new List<DeviceVisualizerLed>();
}
private void Initialize()
{
_deviceImage = null;
_deviceVisualizerLeds.Clear();
if (Device == null)
return;
// Load the device main image
if (Device.RgbDevice?.DeviceInfo?.Image?.AbsolutePath != null && File.Exists(Device.RgbDevice.DeviceInfo.Image.AbsolutePath))
_deviceImage = new BitmapImage(Device.RgbDevice.DeviceInfo.Image);
// Create all the LEDs
foreach (var artemisLed in Device.Leds)
{
_deviceVisualizerLeds.Add(new DeviceVisualizerLed(artemisLed));
}
}
private void SubscribeToSurfaceUpdate(ArtemisDevice oldValue, ArtemisDevice newValue)
{
if (oldValue != null)
oldValue.Surface.RgbSurface.Updated -= RgbSurfaceOnUpdated;
if (newValue != null)
newValue.Surface.RgbSurface.Updated += RgbSurfaceOnUpdated;
}
private void RgbSurfaceOnUpdated(UpdatedEventArgs args)
{
Dispatcher.Invoke(() =>
{
if (ShowColors)
{
Render();
}
});
}
private void Render()
{
var drawingContext = _backingStore.Open();
foreach (var deviceVisualizerLed in _deviceVisualizerLeds)
deviceVisualizerLed.Render(drawingContext, true);
drawingContext.Close();
}
protected override void OnRender(DrawingContext drawingContext)
{
if (Device == null)
return;
// Determine the scale required to fit the desired size of the control
var scale = Math.Min(DesiredSize.Width / Device.RgbDevice.Size.Width, DesiredSize.Height / Device.RgbDevice.Size.Height);
var scaledRect = new Rect(0, 0, Device.RgbDevice.Size.Width * scale, Device.RgbDevice.Size.Height * scale);
// Center and scale the visualization in the desired bounding box
if (DesiredSize.Width > 0 && DesiredSize.Height > 0)
{
drawingContext.PushTransform(new TranslateTransform(DesiredSize.Width / 2 - scaledRect.Width / 2, DesiredSize.Height / 2 - scaledRect.Height / 2));
drawingContext.PushTransform(new ScaleTransform(scale, scale));
}
// Render device and LED images
if (_deviceImage != null)
drawingContext.DrawImage(_deviceImage, new Rect(0, 0, Device.RgbDevice.Size.Width, Device.RgbDevice.Size.Height));
foreach (var deviceVisualizerLed in _deviceVisualizerLeds)
deviceVisualizerLed.Render(drawingContext, false);
drawingContext.DrawDrawing(_backingStore);
}
}
}
@@ -0,0 +1,135 @@
using System;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Artemis.Core.Models.Surface;
using RGB.NET.Core;
using Color = System.Windows.Media.Color;
namespace Artemis.UI.Shared.Controls
{
internal class DeviceVisualizerLed
{
public DeviceVisualizerLed(ArtemisLed led)
{
Led = led;
if (Led.RgbLed.Image != null && File.Exists(Led.RgbLed.Image.AbsolutePath))
LedImage = new BitmapImage(Led.RgbLed.Image);
CreateLedGeometry();
}
public ArtemisLed Led { get; }
public BitmapImage LedImage { get; set; }
public Geometry DisplayGeometry { get; private set; }
internal void Render(DrawingContext drawingContext, bool renderGeometry)
{
if (!renderGeometry)
RenderImage(drawingContext);
else
RenderGeometry(drawingContext);
}
private void CreateLedGeometry()
{
switch (Led.RgbLed.Shape)
{
case Shape.Custom:
if (Led.RgbLed.Device.DeviceInfo.DeviceType == RGBDeviceType.Keyboard || Led.RgbLed.Device.DeviceInfo.DeviceType == RGBDeviceType.Keypad)
CreateCustomGeometry(2.0);
else
CreateCustomGeometry(1.0);
break;
case Shape.Rectangle:
if (Led.RgbLed.Device.DeviceInfo.DeviceType == RGBDeviceType.Keyboard || Led.RgbLed.Device.DeviceInfo.DeviceType == RGBDeviceType.Keypad)
CreateKeyCapGeometry();
else
CreateRectangleGeometry();
break;
case Shape.Circle:
CreateCircleGeometry();
break;
default:
throw new ArgumentOutOfRangeException();
}
// Stroke geometry is the display geometry excluding the inner geometry
DisplayGeometry.Transform = new TranslateTransform(Led.RgbLed.LedRectangle.Location.X, Led.RgbLed.LedRectangle.Location.Y);
// Try to gain some performance
DisplayGeometry = DisplayGeometry.GetFlattenedPathGeometry();
DisplayGeometry.Freeze();
}
private void CreateRectangleGeometry()
{
DisplayGeometry = new RectangleGeometry(new Rect(0.5, 0.5, Led.RgbLed.Size.Width - 1, Led.RgbLed.Size.Height - 1));
}
private void CreateCircleGeometry()
{
DisplayGeometry = new EllipseGeometry(new Rect(0.5, 0.5, Led.RgbLed.Size.Width - 1, Led.RgbLed.Size.Height - 1));
}
private void CreateKeyCapGeometry()
{
DisplayGeometry = new RectangleGeometry(new Rect(1, 1, Led.RgbLed.Size.Width - 2, Led.RgbLed.Size.Height - 2), 1.6, 1.6);
}
private void CreateCustomGeometry(double deflateAmount)
{
try
{
DisplayGeometry = Geometry.Combine(
Geometry.Empty,
Geometry.Parse(Led.RgbLed.ShapeData),
GeometryCombineMode.Union,
new TransformGroup
{
Children = new TransformCollection
{
new ScaleTransform(Led.RgbLed.Size.Width - deflateAmount, Led.RgbLed.Size.Height - deflateAmount),
new TranslateTransform(deflateAmount / 2, deflateAmount / 2)
}
}
);
}
catch (Exception)
{
CreateRectangleGeometry();
}
}
private void RenderGeometry(DrawingContext drawingContext)
{
if (DisplayGeometry == null)
return;
var r = Led.RgbLed.Color.GetR();
var g = Led.RgbLed.Color.GetG();
var b = Led.RgbLed.Color.GetB();
var fillBrush = new SolidColorBrush(Color.FromArgb(100, r,g,b));
fillBrush.Freeze();
var penBrush = new SolidColorBrush(Color.FromArgb(255, r, g, b));
penBrush.Freeze();
drawingContext.DrawGeometry(fillBrush, new Pen(penBrush, 1), DisplayGeometry);
}
private void RenderImage(DrawingContext drawingContext)
{
if (LedImage == null)
return;
var ledRect = new Rect(
Led.RgbLed.LedRectangle.Location.X,
Led.RgbLed.LedRectangle.Location.Y,
Led.RgbLed.LedRectangle.Size.Width,
Led.RgbLed.LedRectangle.Size.Height
);
drawingContext.DrawImage(LedImage, ledRect);
}
}
}
@@ -0,0 +1,45 @@
<UserControl x:Class="Artemis.UI.Shared.Controls.DraggableFloat"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<StackPanel>
<!-- Drag handle -->
<Border x:Name="DragHandle" BorderThickness="0,0,0,1" Height="19">
<Border.BorderBrush>
<VisualBrush>
<VisualBrush.Visual>
<Rectangle StrokeDashArray="2 2" Stroke="{DynamicResource SecondaryAccentBrush}" StrokeThickness="1"
Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualHeight}" />
</VisualBrush.Visual>
</VisualBrush>
</Border.BorderBrush>
<TextBlock Width="60"
Height="17"
Padding="1 0"
Margin="0 4 0 0"
Text="{Binding Value, StringFormat=N3, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
Cursor="/Resources/Cursors/aero_drag_ew.cur"
Foreground="{DynamicResource SecondaryAccentBrush}"
MouseDown="InputMouseDown"
MouseUp="InputMouseUp"
MouseMove="InputMouseMove"
RequestBringIntoView="Input_OnRequestBringIntoView"/>
</Border>
<!-- Input -->
<TextBox x:Name="Input"
Width="60"
Height="20"
materialDesign:ValidationAssist.UsePopup="True"
HorizontalAlignment="Left"
Text="{Binding Value, StringFormat=N3, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
LostFocus="InputLostFocus"
KeyDown="InputKeyDown"
RequestBringIntoView="Input_OnRequestBringIntoView" />
</StackPanel>
</UserControl>
@@ -0,0 +1,161 @@
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Artemis.UI.Shared.Controls
{
/// <summary>
/// Interaction logic for DraggableFloat.xaml
/// </summary>
public partial class DraggableFloat : UserControl, INotifyPropertyChanged
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(float), typeof(DraggableFloat),
new FrameworkPropertyMetadata(default(float), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, FloatPropertyChangedCallback));
public static readonly DependencyProperty StepSizeProperty = DependencyProperty.Register(nameof(StepSize), typeof(float), typeof(DraggableFloat));
public static readonly RoutedEvent ValueChangedEvent =
EventManager.RegisterRoutedEvent(
nameof(Value),
RoutingStrategy.Bubble,
typeof(RoutedPropertyChangedEventHandler<float>),
typeof(DraggableFloat));
public event EventHandler DragStarted;
public event EventHandler DragEnded;
private bool _inCallback;
private Point _mouseDragStartPoint;
private float _startValue;
private bool _calledDragStarted;
public DraggableFloat()
{
InitializeComponent();
}
public float Value
{
get => (float) GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
public float StepSize
{
get => (float) GetValue(StepSizeProperty);
set => SetValue(StepSizeProperty, value);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private static void FloatPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var draggableFloat = (DraggableFloat) d;
if (draggableFloat._inCallback)
return;
draggableFloat._inCallback = true;
draggableFloat.OnPropertyChanged(nameof(Value));
draggableFloat._inCallback = false;
}
private void InputMouseDown(object sender, MouseButtonEventArgs e)
{
_startValue = Value;
((IInputElement) sender).CaptureMouse();
_mouseDragStartPoint = e.GetPosition((IInputElement) sender);
}
private void InputMouseUp(object sender, MouseButtonEventArgs e)
{
var position = e.GetPosition((IInputElement) sender);
if (position == _mouseDragStartPoint)
DisplayInput();
else
{
OnDragEnded();
_calledDragStarted = false;
}
((IInputElement) sender).ReleaseMouseCapture();
}
private void InputMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed)
return;
if (!_calledDragStarted)
{
OnDragStarted();
_calledDragStarted = true;
}
// Use decimals for everything to avoid floating point errors
var startValue = new decimal(_startValue);
var startX = new decimal(_mouseDragStartPoint.X);
var x = new decimal(e.GetPosition((IInputElement) sender).X);
var stepSize = new decimal(StepSize);
Value = (float) UltimateRoundingFunction(startValue + stepSize * (x - startX), stepSize, 0.5m);
}
private void InputLostFocus(object sender, RoutedEventArgs e)
{
DisplayDragHandle();
}
private void InputKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
DisplayDragHandle();
else if (e.Key == Key.Escape)
{
Input.Text = _startValue.ToString();
DisplayDragHandle();
}
}
private void DisplayInput()
{
DragHandle.Visibility = Visibility.Collapsed;
Input.Visibility = Visibility.Visible;
Input.Focus();
Input.SelectAll();
}
private void DisplayDragHandle()
{
Input.Visibility = Visibility.Collapsed;
DragHandle.Visibility = Visibility.Visible;
}
private void Input_OnRequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
e.Handled = true;
}
private static decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
{
return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
}
protected virtual void OnDragStarted()
{
DragStarted?.Invoke(this, EventArgs.Empty);
}
protected virtual void OnDragEnded()
{
DragEnded?.Invoke(this, EventArgs.Empty);
}
}
}
@@ -0,0 +1,50 @@
<UserControl x:Class="Artemis.UI.Shared.Controls.GradientPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:converters="clr-namespace:Artemis.UI.Shared.Converters"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.ColorPicker.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
</ResourceDictionary.MergedDictionaries>
<converters:ColorGradientToGradientStopsConverter x:Key="ColorGradientToGradientStopsConverter" />
<VisualBrush x:Key="Checkerboard" TileMode="Tile" Stretch="Uniform" ViewportUnits="Absolute" Viewport="0,0,10,10">
<VisualBrush.Visual>
<Grid Width="10" Height="10">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Fill="Gray" />
<Rectangle Grid.Row="0" Grid.Column="1" Fill="White" />
<Rectangle Grid.Row="1" Grid.Column="0" Fill="White" />
<Rectangle Grid.Row="1" Grid.Column="1" Fill="Gray" />
</Grid>
</VisualBrush.Visual>
</VisualBrush>
</ResourceDictionary>
</UserControl.Resources>
<Border Height="15"
CornerRadius="5"
Margin="0,0,0,2"
HorizontalAlignment="Stretch"
Background="{StaticResource Checkerboard}">
<Ellipse Stroke="{DynamicResource NormalBorderBrush}" Cursor="Hand" MouseUp="UIElement_OnMouseUp">
<Ellipse.Fill>
<LinearGradientBrush
GradientStops="{Binding ColorGradient.Stops, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Converter={StaticResource ColorGradientToGradientStopsConverter}}" />
</Ellipse.Fill>
</Ellipse>
</Border>
</UserControl>
@@ -0,0 +1,83 @@
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Artemis.Core.Models.Profile;
using Artemis.UI.Shared.Annotations;
using Artemis.UI.Shared.Services.Interfaces;
namespace Artemis.UI.Shared.Controls
{
/// <summary>
/// Interaction logic for GradientPicker.xaml
/// </summary>
public partial class GradientPicker : UserControl, INotifyPropertyChanged
{
private static IGradientPickerService _gradientPickerService;
private bool _inCallback;
public GradientPicker()
{
InitializeComponent();
}
/// <summary>
/// Used by the gradient picker to load saved gradients, do not touch or it'll just throw an exception
/// </summary>
public static IGradientPickerService GradientPickerService
{
private get => _gradientPickerService;
set
{
if (_gradientPickerService != null)
throw new AccessViolationException("This is not for you to touch");
_gradientPickerService = value;
}
}
/// <summary>
/// Gets or sets the currently selected color gradient
/// </summary>
public ColorGradient ColorGradient
{
get => (ColorGradient) GetValue(ColorGradientProperty);
set => SetValue(ColorGradientProperty, value);
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private static void ColorGradientPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var gradientPicker = (GradientPicker) d;
if (gradientPicker._inCallback)
return;
gradientPicker._inCallback = true;
gradientPicker.OnPropertyChanged(nameof(ColorGradient));
gradientPicker._inCallback = false;
}
private void UIElement_OnMouseUp(object sender, MouseButtonEventArgs e)
{
GradientPickerService.ShowGradientPicker(ColorGradient);
}
#region Static WPF fields
public static readonly DependencyProperty ColorGradientProperty = DependencyProperty.Register(nameof(ColorGradient), typeof(ColorGradient), typeof(GradientPicker),
new FrameworkPropertyMetadata(default(ColorGradient), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ColorGradientPropertyChangedCallback));
public static readonly RoutedEvent ColorGradientChangedEvent =
EventManager.RegisterRoutedEvent(nameof(ColorGradient), RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<ColorGradient>), typeof(GradientPicker));
#endregion
}
}