using Annulus; using Azimuth; using Glass; using System; namespace Prism.Glass { /// /// A hue and saturation disc beside a value strip and an alpha strip, over a swatch of the color it started as and /// one of the color now. Every part edits the model it is given, and follows it. /// public class ColorPicker : Panel { // Kept so a color change only sets a tint. The art is wrapped when the look changes, since that allocates. private readonly TintedOverlay oldOverlay = WhiteOverlay(); private readonly TintedOverlay newOverlay = WhiteOverlay(); private TintedOverlay discOverlay = new TintedOverlay(); private TintedOverlay valueOverlay = new TintedOverlay(); private TintedOverlay alphaOverlay = new TintedOverlay(); private ColorPickerBehavior behavior; private ColorPickerMaterial pickerMaterial; // The hex text is left as it was typed while it is the one setting the color, and writing it isn't a typing. private bool changingHexText; // Setting a field from the model raises its change event, which mustn't set the model back. The round trip // would round the model's hue and saturation to whole degrees and percents. private bool refreshingFields; private readonly NumberField[] fields; private readonly Label[] fieldLabels; /// /// Gets the color being edited. /// public ColorPickerModel Model { get; } /// /// Gets the disc that picks hue and saturation. /// public PickSurface Disc { get; } = new PickSurface(); /// /// Gets the strip that picks value. /// public PickSurface ValueStrip { get; } = new PickSurface(); /// /// Gets the strip that picks alpha. /// public PickSurface AlphaStrip { get; } = new PickSurface(); public Panel AlphaBackdrop { get; } = new Panel { AbsorbsMouse = false }; public Panel DiscMarker { get; } = new Panel { AbsorbsMouse = false }; public Panel ValueMarker { get; } = new Panel { AbsorbsMouse = false }; public Panel AlphaMarker { get; } = new Panel { AbsorbsMouse = false }; /// /// Gets the swatch of the color the picker started with. /// public Panel OldSwatch { get; } = new Panel { AbsorbsMouse = false }; /// /// Gets the swatch of the color being edited. /// public Panel NewSwatch { get; } = new Panel { AbsorbsMouse = false }; /// /// Gets the box the color's hex text is typed into. /// public TextBox HexBox { get; } /// /// Gets the field for the hue in whole degrees, from 0 to 360. /// public NumberField HueField { get; } /// /// Gets the field for the saturation in whole percent. /// public NumberField SaturationField { get; } /// /// Gets the field for the value in whole percent. /// public NumberField ValueField { get; } /// /// Gets the field for the alpha in whole percent. /// public NumberField AlphaField { get; } /// /// Gets the letter before the hue field. Call after changing a label's text. /// public Label HueLabel { get; } = new Label { Text = "H" }; /// /// Gets the letter before the saturation field. /// public Label SaturationLabel { get; } = new Label { Text = "S" }; /// /// Gets the letter before the value field. /// public Label ValueLabel { get; } = new Label { Text = "V" }; /// /// Gets the letter before the alpha field. /// public Label AlphaLabel { get; } = new Label { Text = "A" }; private static NumberField MakeField(NumberFieldBehavior fieldBehavior, decimal max) { return new NumberField(fieldBehavior, new NumberField.Data { Grid = new NumberGrid { Max = max } }); } /// /// Makes a picker for the color in a model. It has no look until it is given a . /// public ColorPicker( ColorPickerModel model, ColorPickerBehavior behavior, TextBoxBehavior hexBehavior, NumberFieldBehavior fieldBehavior) { Model = model ?? throw new ArgumentNullException(nameof(model)); this.behavior = behavior ?? throw new ArgumentNullException(nameof(behavior)); // Nine is a color with its alpha, such as #RRGGBBAA. HexBox = new TextBox(hexBehavior, maxLength: 9); HueField = MakeField(fieldBehavior, 360); SaturationField = MakeField(fieldBehavior, 100); ValueField = MakeField(fieldBehavior, 100); AlphaField = MakeField(fieldBehavior, 100); fields = new[] { HueField, SaturationField, ValueField, AlphaField }; fieldLabels = new[] { HueLabel, SaturationLabel, ValueLabel, AlphaLabel }; CanvasChildren.Add(AlphaBackdrop); CanvasChildren.Add(Disc); CanvasChildren.Add(ValueStrip); CanvasChildren.Add(AlphaStrip); CanvasChildren.Add(OldSwatch); CanvasChildren.Add(NewSwatch); CanvasChildren.Add(HexBox); foreach (Label label in fieldLabels) { CanvasChildren.Add(label); } foreach (NumberField field in fields) { CanvasChildren.Add(field); } CanvasChildren.Add(DiscMarker); CanvasChildren.Add(ValueMarker); CanvasChildren.Add(AlphaMarker); Disc.OnPicked += fraction => model.PickDisc(fraction.X * 2 - 1, fraction.Y * 2 - 1); ValueStrip.OnPicked += fraction => model.PickValue(1 - fraction.Y); AlphaStrip.OnPicked += fraction => model.PickAlpha(1 - fraction.Y); model.Changed += _ => Refresh(); HexBox.OnCommitted += (_, _, _) => CommitHexText(); HexBox.OnTextChanged += (_, _) => FollowHexText(); // Written out per field so a change doesn't allocate a closure. HueField.OnValueChanged += (_, _, now) => { if (!refreshingFields) { model.PickHue((double)now / 360); } }; SaturationField.OnValueChanged += (_, _, now) => { if (!refreshingFields) { model.PickSaturation((double)now / 100); } }; ValueField.OnValueChanged += (_, _, now) => { if (!refreshingFields) { model.PickValue((double)now / 100); } }; AlphaField.OnValueChanged += (_, _, now) => { if (!refreshingFields) { model.PickAlpha((double)now / 100); } }; OldSwatch.Material = oldOverlay; NewSwatch.Material = newOverlay; ApplyBehavior(); ApplyMaterials(); Layout(); Refresh(); } /// /// Gets or sets which parts follow the color. /// public ColorPickerBehavior Behavior { get => behavior; set { behavior = value ?? throw new ArgumentNullException(nameof(value)); ApplyBehavior(); Refresh(); } } /// /// Gets or sets the look of the parts, which also sizes the picker to them. /// public ColorPickerMaterial PickerMaterial { get => pickerMaterial; set { pickerMaterial = value; ApplyMaterials(); Layout(); Refresh(); } } private static Vector SizeOf(Material material) { return material?.PreferredSize(Constraints.Unbounded) ?? Vector.Zero; } // A part with no art is hidden, since a panel with no material has nothing to draw. private static void Show(Panel part, Material material) { part.Visible = material != null; part.Material = material; } private static TintedOverlay WhiteOverlay() { return new TintedOverlay { ChildMaterial = new SolidColorMaterial { Color = Colors.White } }; } // The overlay is shown even with no art, which it then draws as nothing, so Refresh never meets a null. private static TintedOverlay ShowTinted(Panel part, Material art) { var returnMe = new TintedOverlay { ChildMaterial = art }; part.Visible = art != null; part.Material = returnMe; return returnMe; } private static Color? Followed(bool follows, Color tint) { Color? returnMe = null; if (follows) { returnMe = tint; } return returnMe; } // One line of text inside whatever the box's background adds around it. private static Scalar BoxHeight(TextBoxMaterial look) { Scalar scale = look.Scale ?? 1; Scalar lineHeight = (look.Text ?? new TextMaterialStyle()).SingleLineHeight * scale; var box = new TextBoxRenderMaterial { Background = look.Background, Scale = scale }; return box.BoundsSizeFor(new Vector(0, lineHeight)).Y; } private void ShowHexText() { string hex = Model.Hex; if (HexBox.Text != hex) { changingHexText = true; HexBox.Text = hex; changingHexText = false; } } private void SetColorFromHexText() { changingHexText = true; Model.TryParseHex(HexBox.Text); changingHexText = false; } // Text that isn't a color is put right again, and so is a color in a form the model would write differently. private void CommitHexText() { SetColorFromHexText(); ShowHexText(); } private void FollowHexText() { if (behavior.HexUpdatesWhileTyping && !changingHexText) { SetColorFromHexText(); } } private void ApplyBehavior() { foreach (NumberField field in fields) { field.RaisesValueChangedWhileScrubbing = behavior.FieldsUpdateWhileScrubbing; } } private Scalar LabelWidth(Label label) { return new TextMaterial { Text = label.Text, Style = pickerMaterial.FieldLabel } .PreferredSize(Constraints.Unbounded).X; } private void ApplyMaterials() { Material = pickerMaterial.Background; foreach (NumberField field in fields) { field.Visible = pickerMaterial.Field.HasValue; if (pickerMaterial.Field.HasValue) { field.NumberFieldMaterial = pickerMaterial.Field.Value; } } foreach (Label label in fieldLabels) { label.Visible = pickerMaterial.Field.HasValue && pickerMaterial.FieldLabel != null; if (label.Visible) { label.Style = pickerMaterial.FieldLabel; } } HexBox.Visible = pickerMaterial.HexBox.HasValue; if (pickerMaterial.HexBox.HasValue) { HexBox.TextBoxMaterial = pickerMaterial.HexBox.Value; } discOverlay = ShowTinted(Disc, pickerMaterial.Disc); valueOverlay = ShowTinted(ValueStrip, pickerMaterial.ValueStrip); alphaOverlay = ShowTinted(AlphaStrip, pickerMaterial.AlphaStrip); Show(AlphaBackdrop, pickerMaterial.AlphaBackdrop); Show(DiscMarker, pickerMaterial.DiscMarker); Show(ValueMarker, pickerMaterial.StripMarker); Show(AlphaMarker, pickerMaterial.StripMarker); } /// /// Sizes the picker to its parts and puts them in place. Setting does this too. /// public void Layout() { Scalar spacing = pickerMaterial.Spacing; Vector discSize = SizeOf(pickerMaterial.Disc); Scalar valueWidth = SizeOf(pickerMaterial.ValueStrip).X; Scalar alphaWidth = SizeOf(pickerMaterial.AlphaStrip).X; var across = new RectAggregator(new Vector(spacing, 0)); across.NewCol(discSize.X); across.NewCol(valueWidth); across.NewCol(alphaWidth); var down = new RectAggregator(new Vector(0, spacing)); down.NewRow(discSize.Y); down.NewRow(pickerMaterial.SwatchHeight); if (HexBox.Visible) { down.NewRow(BoxHeight(pickerMaterial.HexBox.Value)); } // Each field and its letter make a cell, and the four cells are as wide as the widest needs. var fieldsAcross = new RectAggregator(new Vector(spacing, 0)); Scalar cellWidth = 0; Scalar fieldsHeight = 0; if (HueField.Visible) { for (int i = 0; i < fields.Length; ++i) { var cell = new RectAggregator(new Vector(spacing, 0)); if (fieldLabels[i].Visible) { cell.NewCol(LabelWidth(fieldLabels[i])); fieldsHeight = Scalar.Max(fieldsHeight, pickerMaterial.FieldLabel.SingleLineHeight); } Vector fieldSize = fields[i].PreferredBoundsSize; cell.NewCol(fieldSize.X); cellWidth = Scalar.Max(cellWidth, cell.Rect.Width); fieldsHeight = Scalar.Max(fieldsHeight, fieldSize.Y); } fieldsAcross.NewCols(cellWidth, fields.Length); down.NewRow(fieldsHeight); } var inside = new Vector(Scalar.Max(across.Rect.Width, fieldsAcross.Rect.Width), down.Rect.Height); Vector boundsSize = inside; if (Material != null) { boundsSize = Material.BoundsSizeFor(inside); } Bounds = Bounds.WithSize(boundsSize); Rect remainder = CanvasRect; const Shortfall tooSmall = Shortfall.UseWhatIsLeft; Rect topRow = remainder.NewRow(discSize.Y, VerticalJustification.Top, spacing, tooSmall); Disc.Bounds = topRow.NewCol(discSize.X, HorizontalJustification.Left, spacing, tooSmall); ValueStrip.Bounds = topRow.NewCol(valueWidth, HorizontalJustification.Left, spacing, tooSmall); AlphaStrip.Bounds = topRow.NewCol(alphaWidth, HorizontalJustification.Left, spacing, tooSmall); AlphaBackdrop.Bounds = AlphaStrip.Bounds; Rect swatchRow = remainder.NewRow( pickerMaterial.SwatchHeight, VerticalJustification.Top, spacing, tooSmall); RectDivider swatches = swatchRow.NewCols(2, spacing); OldSwatch.Bounds = swatches[0]; NewSwatch.Bounds = swatches[1]; if (HexBox.Visible) { HexBox.Bounds = remainder.NewRow( BoxHeight(pickerMaterial.HexBox.Value), VerticalJustification.Top, spacing, tooSmall); } if (HueField.Visible) { RectDivider cells = remainder.NewCols(fields.Length, spacing); for (int i = 0; i < fields.Length; ++i) { Rect cell = cells[i]; if (fieldLabels[i].Visible) { fieldLabels[i].Bounds = cell.NewCol( LabelWidth(fieldLabels[i]), HorizontalJustification.Left, spacing, tooSmall); } fields[i].Bounds = cell; } } } private static decimal Rounded(double fraction, int scale) { return Math.Round((decimal)(fraction * scale), MidpointRounding.AwayFromZero); } // A marker across a strip sits where the fraction is, the top of the strip being 1. private Rect StripMarkerAt(Rect strip, double fraction) { Scalar height = SizeOf(pickerMaterial.StripMarker).Y; Scalar center = strip.Top + (1 - fraction) * strip.Height; // lint-ignore: carve The fraction decides where the marker sits, so it can't be carved. return Rect.FromPositionAndSize( new Vector(strip.Left, center - height / 2), new Vector(strip.Width, height)); } // The hue field may hold 360, which is the model's 0, so it is only moved when it differs by more than that. private void ShowFields(Hsv current) { refreshingFields = true; decimal degrees = Rounded(current.Hue, 360) % 360; if (HueField.Value % 360 != degrees) { HueField.Value = degrees; } SaturationField.Value = Rounded(current.Saturation, 100); ValueField.Value = Rounded(current.Value, 100); AlphaField.Value = Rounded(current.Alpha, 100); refreshingFields = false; } /// /// Puts the tints, markers and swatches where the model's color says. /// private void Refresh() { Hsv current = Model.Current; discOverlay.Tint = Followed(behavior.DiscShowsValue, Model.DiscTint); valueOverlay.Tint = Followed(behavior.ValueStripShowsHueAndSaturation, Model.ValueStripTint); alphaOverlay.Tint = Followed(behavior.AlphaStripShowsColor, Model.AlphaStripTint); oldOverlay.Tint = Model.Original; newOverlay.Tint = Model.CurrentColor; HueDisc.PointOf(current, out double x, out double y); Rect discBounds = Disc.Bounds; Vector markerSize = SizeOf(pickerMaterial.DiscMarker); Vector markerCenter = discBounds.Center + new Vector(x * discBounds.Width / 2, y * discBounds.Height / 2); DiscMarker.Bounds = Rect.FromPositionAndSize(markerCenter - markerSize / 2, markerSize); ValueMarker.Bounds = StripMarkerAt(ValueStrip.Bounds, current.Value); AlphaMarker.Bounds = StripMarkerAt(AlphaStrip.Bounds, current.Alpha); if (!changingHexText) { ShowHexText(); } ShowFields(current); } } }