using System; using Amphora; namespace Prism.Glass { /// /// Ties a color picker to the selected stop of a gradient. The picker shows the stop and editing it recolors the /// stop. /// public class StopColorLink { private readonly GradientModel gradient; private readonly ColorPickerModel picker; // The stop color the picker was last put on, so an edit that leaves the color alone leaves the picker alone. private StopColor shown; private bool pushing; private bool showing; /// /// Raised with why, when the gradient refuses a color edited in the picker. The picker is put back first. /// public event Action OnRefused; /// /// Links a picker to a gradient, and puts the picker on the selected stop. /// public StopColorLink(GradientModel gradient, ColorPickerModel picker) { this.gradient = gradient ?? throw new ArgumentNullException(nameof(gradient)); this.picker = picker ?? throw new ArgumentNullException(nameof(picker)); Show(); picker.Changed += Push; gradient.Changed += _ => Follow(); gradient.SelectionChanged += _ => Follow(); } private void Show() { shown = gradient.GetColor(gradient.SelectedIndex); showing = true; picker.Restart(shown.ToHsv()); showing = false; } // A hue the stop can't hold, such as a gray's in Oklab, is lost if the picker takes the stop's word for it. private void Follow() { if (!pushing && gradient.GetColor(gradient.SelectedIndex) != shown) { Show(); } } private void Push(Hsv color) { if (showing) { return; } pushing = true; Status set = gradient.SetStopColor(gradient.SelectedIndex, StopColor.FromHsv(color)); shown = gradient.GetColor(gradient.SelectedIndex); pushing = false; // The picker is put back on the stop first, so a listener sees it as it is left. if (!set.IsOk) { Show(); OnRefused?.Invoke(set); } } } }