LineDrawing.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Terminal.Gui;
  6. namespace UICatalog.Scenarios;
  7. public interface ITool
  8. {
  9. void OnMouseEvent (DrawingArea area, MouseEvent mouseEvent);
  10. }
  11. internal class DrawLineTool : ITool
  12. {
  13. private StraightLine _currentLine;
  14. public LineStyle LineStyle { get; set; } = LineStyle.Single;
  15. /// <inheritdoc/>
  16. public void OnMouseEvent (DrawingArea area, MouseEvent mouseEvent)
  17. {
  18. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed))
  19. {
  20. if (_currentLine == null)
  21. {
  22. // Mouse pressed down
  23. _currentLine = new (
  24. mouseEvent.Position,
  25. 0,
  26. Orientation.Vertical,
  27. LineStyle,
  28. area.CurrentAttribute
  29. );
  30. area.CurrentLayer.AddLine (_currentLine);
  31. }
  32. else
  33. {
  34. // Mouse dragged
  35. Point start = _currentLine.Start;
  36. Point end = mouseEvent.Position;
  37. var orientation = Orientation.Vertical;
  38. int length = end.Y - start.Y;
  39. // if line is wider than it is tall switch to horizontal
  40. if (Math.Abs (start.X - end.X) > Math.Abs (start.Y - end.Y))
  41. {
  42. orientation = Orientation.Horizontal;
  43. length = end.X - start.X;
  44. }
  45. if (length > 0)
  46. {
  47. length++;
  48. }
  49. else
  50. {
  51. length--;
  52. }
  53. _currentLine.Length = length;
  54. _currentLine.Orientation = orientation;
  55. area.CurrentLayer.ClearCache ();
  56. area.SetNeedsDisplay ();
  57. }
  58. }
  59. else
  60. {
  61. // Mouse released
  62. if (_currentLine != null)
  63. {
  64. if (_currentLine.Length == 0)
  65. {
  66. _currentLine.Length = 1;
  67. }
  68. if (_currentLine.Style == LineStyle.None)
  69. {
  70. // Treat none as eraser
  71. int idx = area.Layers.IndexOf (area.CurrentLayer);
  72. area.Layers.Remove (area.CurrentLayer);
  73. area.CurrentLayer = new (
  74. area.CurrentLayer.Lines.Exclude (
  75. _currentLine.Start,
  76. _currentLine.Length,
  77. _currentLine.Orientation
  78. )
  79. );
  80. area.Layers.Insert (idx, area.CurrentLayer);
  81. }
  82. _currentLine = null;
  83. area.ClearUndo ();
  84. area.SetNeedsDisplay ();
  85. }
  86. }
  87. }
  88. }
  89. [ScenarioMetadata ("Line Drawing", "Demonstrates LineCanvas.")]
  90. [ScenarioCategory ("Controls")]
  91. [ScenarioCategory ("Drawing")]
  92. public class LineDrawing : Scenario
  93. {
  94. public override void Main ()
  95. {
  96. Application.Init ();
  97. var win = new Window { Title = GetQuitKeyAndName () };
  98. var canvas = new DrawingArea { X = 0, Y = 0, Width = Dim.Fill (), Height = Dim.Fill () };
  99. var tools = new ToolsView { Title = "Tools", X = Pos.Right (canvas) - 20, Y = 2 };
  100. tools.ColorChanged += (s, e) => canvas.SetAttribute (e);
  101. tools.SetStyle += b => canvas.CurrentTool = new DrawLineTool { LineStyle = b };
  102. tools.AddLayer += () => canvas.AddLayer ();
  103. win.Add (canvas);
  104. win.Add (tools);
  105. tools.CurrentColor = canvas.GetNormalColor ();
  106. canvas.CurrentAttribute = tools.CurrentColor;
  107. win.KeyDown += (s, e) => { e.Handled = canvas.OnKeyDown (e); };
  108. Application.Run (win);
  109. win.Dispose ();
  110. Application.Shutdown ();
  111. }
  112. public static bool PromptForColor (string title, Color current, out Color newColor)
  113. {
  114. var accept = false;
  115. var d = new Dialog
  116. {
  117. Title = title,
  118. Height = 7
  119. };
  120. var btnOk = new Button
  121. {
  122. X = Pos.Center () - 5,
  123. Y = 4,
  124. Text = "Ok",
  125. Width = Dim.Auto (),
  126. IsDefault = true
  127. };
  128. btnOk.Accepted += (s, e) =>
  129. {
  130. accept = true;
  131. e.Handled = true;
  132. Application.RequestStop ();
  133. };
  134. var btnCancel = new Button
  135. {
  136. X = Pos.Center () + 5,
  137. Y = 4,
  138. Text = "Cancel",
  139. Width = Dim.Auto ()
  140. };
  141. btnCancel.Accepted += (s, e) =>
  142. {
  143. e.Handled = true;
  144. Application.RequestStop ();
  145. };
  146. d.Add (btnOk);
  147. d.Add (btnCancel);
  148. /* Does not work
  149. d.AddButton (btnOk);
  150. d.AddButton (btnCancel);
  151. */
  152. var cp = new ColorPicker
  153. {
  154. SelectedColor = current,
  155. Width = Dim.Fill ()
  156. };
  157. d.Add (cp);
  158. Application.Run (d);
  159. d.Dispose ();
  160. newColor = cp.SelectedColor;
  161. return accept;
  162. }
  163. }
  164. public class ToolsView : Window
  165. {
  166. private Button _addLayerBtn;
  167. private readonly AttributeView _colors;
  168. private RadioGroup _stylePicker;
  169. public Attribute CurrentColor
  170. {
  171. get => _colors.Value;
  172. set => _colors.Value = value;
  173. }
  174. public ToolsView ()
  175. {
  176. BorderStyle = LineStyle.Dotted;
  177. Border.Thickness = new (1, 2, 1, 1);
  178. Initialized += ToolsView_Initialized;
  179. _colors = new ();
  180. }
  181. public event Action AddLayer;
  182. public override void BeginInit ()
  183. {
  184. base.BeginInit ();
  185. _colors.ValueChanged += (s, e) => ColorChanged?.Invoke (this, e);
  186. _stylePicker = new()
  187. {
  188. X = 0, Y = Pos.Bottom (_colors), RadioLabels = Enum.GetNames (typeof (LineStyle)).ToArray ()
  189. };
  190. _stylePicker.SelectedItemChanged += (s, a) => { SetStyle?.Invoke ((LineStyle)a.SelectedItem); };
  191. _stylePicker.SelectedItem = 1;
  192. _addLayerBtn = new() { Text = "New Layer", X = Pos.Center (), Y = Pos.Bottom (_stylePicker) };
  193. _addLayerBtn.Accepted += (s, a) => AddLayer?.Invoke ();
  194. Add (_colors, _stylePicker, _addLayerBtn);
  195. }
  196. public event EventHandler<Attribute> ColorChanged;
  197. public event Action<LineStyle> SetStyle;
  198. private void ToolsView_Initialized (object sender, EventArgs e)
  199. {
  200. LayoutSubviews ();
  201. Width = Math.Max (_colors.Frame.Width, _stylePicker.Frame.Width) + GetAdornmentsThickness ().Horizontal;
  202. Height = _colors.Frame.Height + _stylePicker.Frame.Height + _addLayerBtn.Frame.Height + GetAdornmentsThickness ().Vertical;
  203. SuperView.LayoutSubviews ();
  204. }
  205. }
  206. public class DrawingArea : View
  207. {
  208. public readonly List<LineCanvas> Layers = new ();
  209. private readonly Stack<StraightLine> _undoHistory = new ();
  210. public Attribute CurrentAttribute { get; set; }
  211. public LineCanvas CurrentLayer { get; set; }
  212. public ITool CurrentTool { get; set; } = new DrawLineTool ();
  213. public DrawingArea () { AddLayer (); }
  214. public override void OnDrawContentComplete (Rectangle viewport)
  215. {
  216. base.OnDrawContentComplete (viewport);
  217. foreach (LineCanvas canvas in Layers)
  218. {
  219. foreach (KeyValuePair<Point, Cell?> c in canvas.GetCellMap ())
  220. {
  221. if (c.Value is { })
  222. {
  223. Driver.SetAttribute (c.Value.Value.Attribute ?? ColorScheme.Normal);
  224. // TODO: #2616 - Support combining sequences that don't normalize
  225. AddRune (c.Key.X, c.Key.Y, c.Value.Value.Rune);
  226. }
  227. }
  228. }
  229. }
  230. //// BUGBUG: Why is this not handled by a key binding???
  231. public override bool OnKeyDown (Key e)
  232. {
  233. // BUGBUG: These should be implemented with key bindings
  234. if (e.KeyCode == (KeyCode.Z | KeyCode.CtrlMask))
  235. {
  236. StraightLine pop = CurrentLayer.RemoveLastLine ();
  237. if (pop != null)
  238. {
  239. _undoHistory.Push (pop);
  240. SetNeedsDisplay ();
  241. return true;
  242. }
  243. }
  244. if (e.KeyCode == (KeyCode.Y | KeyCode.CtrlMask))
  245. {
  246. if (_undoHistory.Any ())
  247. {
  248. StraightLine pop = _undoHistory.Pop ();
  249. CurrentLayer.AddLine (pop);
  250. SetNeedsDisplay ();
  251. return true;
  252. }
  253. }
  254. return false;
  255. }
  256. protected override bool OnMouseEvent (MouseEvent mouseEvent)
  257. {
  258. CurrentTool.OnMouseEvent (this, mouseEvent);
  259. return base.OnMouseEvent (mouseEvent);
  260. }
  261. internal void AddLayer ()
  262. {
  263. CurrentLayer = new ();
  264. Layers.Add (CurrentLayer);
  265. }
  266. internal void SetAttribute (Attribute a) { CurrentAttribute = a; }
  267. public void ClearUndo () { _undoHistory.Clear (); }
  268. }
  269. public class AttributeView : View
  270. {
  271. public event EventHandler<Attribute> ValueChanged;
  272. private Attribute _value;
  273. public Attribute Value
  274. {
  275. get => _value;
  276. set
  277. {
  278. _value = value;
  279. ValueChanged?.Invoke (this, value);
  280. }
  281. }
  282. private static readonly HashSet<(int, int)> ForegroundPoints = new()
  283. {
  284. (0, 0), (1, 0), (2, 0),
  285. (0, 1), (1, 1), (2, 1)
  286. };
  287. private static readonly HashSet<(int, int)> BackgroundPoints = new()
  288. {
  289. (3, 1),
  290. (1, 2), (2, 2), (3, 2)
  291. };
  292. public AttributeView ()
  293. {
  294. Width = 4;
  295. Height = 3;
  296. }
  297. /// <inheritdoc/>
  298. public override void OnDrawContent (Rectangle viewport)
  299. {
  300. base.OnDrawContent (viewport);
  301. Color fg = Value.Foreground;
  302. Color bg = Value.Background;
  303. bool isTransparentFg = fg == GetNormalColor ().Background;
  304. bool isTransparentBg = bg == GetNormalColor ().Background;
  305. Driver.SetAttribute (new (fg, isTransparentFg ? Color.Gray : fg));
  306. // Square of foreground color
  307. foreach ((int, int) point in ForegroundPoints)
  308. {
  309. // Make pattern like this when it is same color as background of control
  310. /*▓▒
  311. ▒▓*/
  312. Rune rune;
  313. if (isTransparentFg)
  314. {
  315. rune = (Rune)(point.Item1 % 2 == point.Item2 % 2 ? '▓' : '▒');
  316. }
  317. else
  318. {
  319. rune = (Rune)'█';
  320. }
  321. AddRune (point.Item1, point.Item2, rune);
  322. }
  323. Driver.SetAttribute (new (bg, isTransparentBg ? Color.Gray : bg));
  324. // Square of background color
  325. foreach ((int, int) point in BackgroundPoints)
  326. {
  327. // Make pattern like this when it is same color as background of control
  328. /*▓▒
  329. ▒▓*/
  330. Rune rune;
  331. if (isTransparentBg)
  332. {
  333. rune = (Rune)(point.Item1 % 2 == point.Item2 % 2 ? '▓' : '▒');
  334. }
  335. else
  336. {
  337. rune = (Rune)'█';
  338. }
  339. AddRune (point.Item1, point.Item2, rune);
  340. }
  341. }
  342. /// <inheritdoc/>
  343. protected override bool OnMouseEvent (MouseEvent mouseEvent)
  344. {
  345. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked))
  346. {
  347. if (IsForegroundPoint (mouseEvent.Position.X, mouseEvent.Position.Y))
  348. {
  349. ClickedInForeground ();
  350. }
  351. else if (IsBackgroundPoint (mouseEvent.Position.X, mouseEvent.Position.Y))
  352. {
  353. ClickedInBackground ();
  354. }
  355. }
  356. return base.OnMouseEvent (mouseEvent);
  357. }
  358. private bool IsForegroundPoint (int x, int y) { return ForegroundPoints.Contains ((x, y)); }
  359. private bool IsBackgroundPoint (int x, int y) { return BackgroundPoints.Contains ((x, y)); }
  360. private void ClickedInBackground ()
  361. {
  362. if (LineDrawing.PromptForColor ("Background", Value.Background, out Color newColor))
  363. {
  364. Value = new (Value.Foreground, newColor);
  365. SetNeedsDisplay ();
  366. }
  367. }
  368. private void ClickedInForeground ()
  369. {
  370. if (LineDrawing.PromptForColor ("Foreground", Value.Foreground, out Color newColor))
  371. {
  372. Value = new (newColor, Value.Background);
  373. SetNeedsDisplay ();
  374. }
  375. }
  376. }