ColorPicker.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. namespace Terminal.Gui.Views;
  2. /// <summary>
  3. /// Color Picker supporting RGB, HSL, and HSV color models. Supports choosing colors with
  4. /// sliders and color names from the <see cref="IColorNameResolver"/>.
  5. /// </summary>
  6. public partial class ColorPicker : View, IDesignable
  7. {
  8. /// <summary>
  9. /// Creates a new instance of <see cref="ColorPicker"/>. Use
  10. /// <see cref="Style"/> to change color model. Use <see cref="SelectedColor"/>
  11. /// to change initial <see cref="Color"/>.
  12. /// </summary>
  13. public ColorPicker ()
  14. {
  15. CanFocus = true;
  16. TabStop = TabBehavior.TabStop;
  17. Height = Dim.Auto ();
  18. Width = Dim.Auto (minimumContentDim: 32);
  19. ApplyStyleChanges ();
  20. }
  21. private readonly Dictionary<IColorBar, TextField> _textFields = new ();
  22. private readonly ColorModelStrategy _strategy = new ();
  23. private TextField? _tfHex;
  24. private Label? _lbHex;
  25. private TextField? _tfName;
  26. private Label? _lbName;
  27. private Color _selectedColor = Color.Black;
  28. // TODO: Add interface
  29. private readonly IColorNameResolver _colorNameResolver = new StandardColorsNameResolver ();
  30. private List<IColorBar> _bars = [];
  31. /// <summary>
  32. /// Rebuild the user interface to reflect the new state of <see cref="Style"/>.
  33. /// </summary>
  34. public void ApplyStyleChanges ()
  35. {
  36. Color oldValue = _selectedColor;
  37. DisposeOldViews ();
  38. var y = 0;
  39. const int TEXT_FIELD_WIDTH = 4;
  40. foreach (ColorBar bar in _strategy.CreateBars (Style.ColorModel))
  41. {
  42. bar.Y = y;
  43. bar.Width = Dim.Fill (Style.ShowTextFields ? TEXT_FIELD_WIDTH : 0);
  44. TextField? tfValue = null;
  45. if (Style.ShowTextFields)
  46. {
  47. tfValue = new TextField
  48. {
  49. X = Pos.AnchorEnd (TEXT_FIELD_WIDTH),
  50. Y = y,
  51. Width = TEXT_FIELD_WIDTH
  52. };
  53. tfValue.HasFocusChanged += UpdateSingleBarValueFromTextField;
  54. tfValue.Accepting += (s, _) => UpdateSingleBarValueFromTextField (s);
  55. _textFields.Add (bar, tfValue);
  56. }
  57. y++;
  58. bar.ValueChanged += RebuildColorFromBar;
  59. _bars.Add (bar);
  60. Add (bar);
  61. if (tfValue is { })
  62. {
  63. Add (tfValue);
  64. }
  65. }
  66. if (Style.ShowColorName)
  67. {
  68. CreateNameField ();
  69. }
  70. CreateTextField ();
  71. SelectedColor = oldValue;
  72. SetNeedsLayout ();
  73. }
  74. /// <summary>
  75. /// Fired when color is changed.
  76. /// </summary>
  77. public event EventHandler<ResultEventArgs<Color>>? ColorChanged;
  78. /// <inheritdoc/>
  79. protected override bool OnDrawingContent (DrawContext? context)
  80. {
  81. Attribute normal = GetAttributeForRole (VisualRole.Normal);
  82. SetAttribute (new (SelectedColor, normal.Background, Enabled ? TextStyle.None : TextStyle.Faint));
  83. int y = _bars.Count + (Style.ShowColorName ? 1 : 0);
  84. AddRune (13, y, (Rune)'■');
  85. return true;
  86. }
  87. /// <summary>
  88. /// The color selected in the picker
  89. /// </summary>
  90. public Color SelectedColor
  91. {
  92. get => _selectedColor;
  93. set => SetSelectedColor (value, true);
  94. }
  95. /// <summary>
  96. /// Style settings for the color picker. After making changes ensure you call
  97. /// <see cref="ApplyStyleChanges"/>.
  98. /// </summary>
  99. public ColorPickerStyle Style { get; set; } = new ();
  100. private void CreateNameField ()
  101. {
  102. _lbName = new ()
  103. {
  104. Text = "Name:",
  105. X = 0,
  106. Y = 3
  107. };
  108. _tfName = new ()
  109. {
  110. Y = 3,
  111. X = 6,
  112. Width = 20 // width of "LightGoldenRodYellow" - the longest w3c color name
  113. };
  114. Add (_lbName);
  115. Add (_tfName);
  116. var auto = new AppendAutocomplete (_tfName);
  117. auto.SuggestionGenerator = new SingleWordSuggestionGenerator
  118. {
  119. AllSuggestions = _colorNameResolver.GetColorNames ().ToList ()
  120. };
  121. _tfName.Autocomplete = auto;
  122. _tfName.HasFocusChanged += UpdateValueFromName;
  123. _tfName.Accepting += (s, _) => UpdateValueFromName ();
  124. }
  125. private void CreateTextField ()
  126. {
  127. int y = _bars.Count;
  128. if (Style.ShowColorName)
  129. {
  130. y++;
  131. }
  132. _lbHex = new ()
  133. {
  134. Text = "Hex:",
  135. X = 0,
  136. Y = y
  137. };
  138. _tfHex = new ()
  139. {
  140. Y = y,
  141. X = 4,
  142. Width = 8,
  143. };
  144. Add (_lbHex);
  145. Add (_tfHex);
  146. _tfHex.HasFocusChanged += UpdateValueFromTextField;
  147. _tfHex.Accepting += (_, _) => UpdateValueFromTextField ();
  148. }
  149. private void DisposeOldViews ()
  150. {
  151. foreach (ColorBar bar in _bars.Cast<ColorBar> ())
  152. {
  153. bar.ValueChanged -= RebuildColorFromBar;
  154. if (_textFields.TryGetValue (bar, out TextField? tf))
  155. {
  156. Remove (tf);
  157. tf.Dispose ();
  158. }
  159. Remove (bar);
  160. bar.Dispose ();
  161. }
  162. _bars = new ();
  163. _textFields.Clear ();
  164. if (_lbHex != null)
  165. {
  166. Remove (_lbHex);
  167. _lbHex.Dispose ();
  168. _lbHex = null;
  169. }
  170. if (_tfHex != null)
  171. {
  172. Remove (_tfHex);
  173. _tfHex.Dispose ();
  174. _tfHex = null;
  175. }
  176. if (_lbName != null)
  177. {
  178. Remove (_lbName);
  179. _lbName.Dispose ();
  180. _lbName = null;
  181. }
  182. if (_tfName != null)
  183. {
  184. Remove (_tfName);
  185. _tfName.Dispose ();
  186. _tfName = null;
  187. }
  188. }
  189. private void RebuildColorFromBar (object? sender, EventArgs<int> e)
  190. {
  191. SetSelectedColor (_strategy.GetColorFromBars (_bars, Style.ColorModel), false);
  192. }
  193. private void SetSelectedColor (Color value, bool syncBars)
  194. {
  195. if (_selectedColor != value)
  196. {
  197. Color old = _selectedColor;
  198. _selectedColor = value;
  199. ColorChanged?.Invoke (this, new (value));
  200. }
  201. SyncSubViewValues (syncBars);
  202. }
  203. private void SyncSubViewValues (bool syncBars)
  204. {
  205. if (syncBars)
  206. {
  207. _strategy.SetBarsToColor (_bars, _selectedColor, Style.ColorModel);
  208. }
  209. foreach (KeyValuePair<IColorBar, TextField> kvp in _textFields)
  210. {
  211. kvp.Value.Text = kvp.Key.Value.ToString ();
  212. }
  213. var colorHex = _selectedColor.ToString ($"#{SelectedColor.R:X2}{SelectedColor.G:X2}{SelectedColor.B:X2}");
  214. if (_tfName != null)
  215. {
  216. _tfName.Text = _colorNameResolver.TryNameColor (_selectedColor, out string? name) ? name : string.Empty;
  217. }
  218. if (_tfHex != null)
  219. {
  220. _tfHex.Text = colorHex;
  221. }
  222. SetNeedsLayout ();
  223. }
  224. private void UpdateSingleBarValueFromTextField (object? sender, HasFocusEventArgs e)
  225. {
  226. // if the new value of Focused is true then it is an enter event so ignore
  227. if (e.NewValue)
  228. {
  229. return;
  230. }
  231. // it is a leave event so update
  232. UpdateSingleBarValueFromTextField (sender);
  233. }
  234. private void UpdateSingleBarValueFromTextField (object? sender)
  235. {
  236. foreach (KeyValuePair<IColorBar, TextField> kvp in _textFields)
  237. {
  238. if (kvp.Value != sender)
  239. {
  240. continue;
  241. }
  242. if (int.TryParse (kvp.Value.Text, out int v))
  243. {
  244. kvp.Key.Value = v;
  245. }
  246. }
  247. }
  248. private void UpdateValueFromName (object? sender, HasFocusEventArgs e)
  249. {
  250. // if the new value of Focused is true then it is an enter event so ignore
  251. if (e.NewValue)
  252. {
  253. return;
  254. }
  255. // it is a leave event so update
  256. UpdateValueFromName ();
  257. }
  258. private void UpdateValueFromName ()
  259. {
  260. if (_tfName == null)
  261. {
  262. return;
  263. }
  264. if (_colorNameResolver.TryParseColor (_tfName.Text, out Color newColor))
  265. {
  266. SelectedColor = newColor;
  267. }
  268. else
  269. {
  270. // value is invalid, revert the value in the text field back to current state
  271. SyncSubViewValues (false);
  272. }
  273. }
  274. private void UpdateValueFromTextField (object? sender, HasFocusEventArgs e)
  275. {
  276. // if the new value of Focused is true then it is an enter event so ignore
  277. if (e.NewValue)
  278. {
  279. return;
  280. }
  281. // it is a leave event so update
  282. UpdateValueFromTextField ();
  283. }
  284. private void UpdateValueFromTextField ()
  285. {
  286. if (_tfHex == null)
  287. {
  288. return;
  289. }
  290. if (Color.TryParse (_tfHex.Text, out Color? newColor))
  291. {
  292. SelectedColor = newColor.Value;
  293. }
  294. else
  295. {
  296. // value is invalid, revert the value in the text field back to current state
  297. SyncSubViewValues (false);
  298. }
  299. }
  300. /// <inheritdoc/>
  301. public bool EnableForDesign ()
  302. {
  303. SelectedColor = Color.BrightRed;
  304. return true;
  305. }
  306. /// <inheritdoc />
  307. protected override void Dispose (bool disposing)
  308. {
  309. DisposeOldViews ();
  310. base.Dispose (disposing);
  311. }
  312. }