LineDrawing.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. Width = Application.Force16Colors ? 35 : Dim.Auto (DimAutoStyle.Auto, Dim.Percent (80), Dim.Percent (90)),
  119. Height = 10
  120. };
  121. var btnOk = new Button
  122. {
  123. X = Pos.Center () - 5,
  124. Y = Application.Force16Colors ? 6 : 4,
  125. Text = "Ok",
  126. Width = Dim.Auto (),
  127. IsDefault = true
  128. };
  129. btnOk.Accepting += (s, e) =>
  130. {
  131. accept = true;
  132. e.Cancel = true;
  133. Application.RequestStop ();
  134. };
  135. var btnCancel = new Button
  136. {
  137. X = Pos.Center () + 5,
  138. Y = 4,
  139. Text = "Cancel",
  140. Width = Dim.Auto ()
  141. };
  142. btnCancel.Accepting += (s, e) =>
  143. {
  144. e.Cancel = true;
  145. Application.RequestStop ();
  146. };
  147. d.Add (btnOk);
  148. d.Add (btnCancel);
  149. d.AddButton (btnOk);
  150. d.AddButton (btnCancel);
  151. View cp;
  152. if (Application.Force16Colors)
  153. {
  154. cp = new ColorPicker16
  155. {
  156. SelectedColor = current.GetClosestNamedColor16 (),
  157. Width = Dim.Fill ()
  158. };
  159. }
  160. else
  161. {
  162. cp = new ColorPicker
  163. {
  164. SelectedColor = current,
  165. Width = Dim.Fill (),
  166. Style = new () { ShowColorName = true, ShowTextFields = true }
  167. };
  168. ((ColorPicker)cp).ApplyStyleChanges ();
  169. }
  170. d.Add (cp);
  171. Application.Run (d);
  172. d.Dispose ();
  173. newColor = Application.Force16Colors ? ((ColorPicker16)cp).SelectedColor : ((ColorPicker)cp).SelectedColor;
  174. return accept;
  175. }
  176. }
  177. public class ToolsView : Window
  178. {
  179. private Button _addLayerBtn;
  180. private readonly AttributeView _colors;
  181. private RadioGroup _stylePicker;
  182. public Attribute CurrentColor
  183. {
  184. get => _colors.Value;
  185. set => _colors.Value = value;
  186. }
  187. public ToolsView ()
  188. {
  189. BorderStyle = LineStyle.Dotted;
  190. Border.Thickness = new (1, 2, 1, 1);
  191. Initialized += ToolsView_Initialized;
  192. _colors = new ();
  193. }
  194. public event Action AddLayer;
  195. public override void BeginInit ()
  196. {
  197. base.BeginInit ();
  198. _colors.ValueChanged += (s, e) => ColorChanged?.Invoke (this, e);
  199. _stylePicker = new()
  200. {
  201. X = 0, Y = Pos.Bottom (_colors), RadioLabels = Enum.GetNames (typeof (LineStyle)).ToArray ()
  202. };
  203. _stylePicker.SelectedItemChanged += (s, a) => { SetStyle?.Invoke ((LineStyle)a.SelectedItem); };
  204. _stylePicker.SelectedItem = 1;
  205. _addLayerBtn = new() { Text = "New Layer", X = Pos.Center (), Y = Pos.Bottom (_stylePicker) };
  206. _addLayerBtn.Accepting += (s, a) => AddLayer?.Invoke ();
  207. Add (_colors, _stylePicker, _addLayerBtn);
  208. }
  209. public event EventHandler<Attribute> ColorChanged;
  210. public event Action<LineStyle> SetStyle;
  211. private void ToolsView_Initialized (object sender, EventArgs e)
  212. {
  213. LayoutSubviews ();
  214. Width = Math.Max (_colors.Frame.Width, _stylePicker.Frame.Width) + GetAdornmentsThickness ().Horizontal;
  215. Height = _colors.Frame.Height + _stylePicker.Frame.Height + _addLayerBtn.Frame.Height + GetAdornmentsThickness ().Vertical;
  216. SuperView.LayoutSubviews ();
  217. }
  218. }
  219. public class DrawingArea : View
  220. {
  221. public readonly List<LineCanvas> Layers = new ();
  222. private readonly Stack<StraightLine> _undoHistory = new ();
  223. public Attribute CurrentAttribute { get; set; }
  224. public LineCanvas CurrentLayer { get; set; }
  225. public ITool CurrentTool { get; set; } = new DrawLineTool ();
  226. public DrawingArea () { AddLayer (); }
  227. public override void OnDrawContentComplete (Rectangle viewport)
  228. {
  229. base.OnDrawContentComplete (viewport);
  230. foreach (LineCanvas canvas in Layers)
  231. {
  232. foreach (KeyValuePair<Point, Cell?> c in canvas.GetCellMap ())
  233. {
  234. if (c.Value is { })
  235. {
  236. Driver.SetAttribute (c.Value.Value.Attribute ?? ColorScheme.Normal);
  237. // TODO: #2616 - Support combining sequences that don't normalize
  238. AddRune (c.Key.X, c.Key.Y, c.Value.Value.Rune);
  239. }
  240. }
  241. }
  242. }
  243. //// BUGBUG: Why is this not handled by a key binding???
  244. public override bool OnKeyDown (Key e)
  245. {
  246. // BUGBUG: These should be implemented with key bindings
  247. if (e.KeyCode == (KeyCode.Z | KeyCode.CtrlMask))
  248. {
  249. StraightLine pop = CurrentLayer.RemoveLastLine ();
  250. if (pop != null)
  251. {
  252. _undoHistory.Push (pop);
  253. SetNeedsDisplay ();
  254. return true;
  255. }
  256. }
  257. if (e.KeyCode == (KeyCode.Y | KeyCode.CtrlMask))
  258. {
  259. if (_undoHistory.Any ())
  260. {
  261. StraightLine pop = _undoHistory.Pop ();
  262. CurrentLayer.AddLine (pop);
  263. SetNeedsDisplay ();
  264. return true;
  265. }
  266. }
  267. return false;
  268. }
  269. protected override bool OnMouseEvent (MouseEvent mouseEvent)
  270. {
  271. CurrentTool.OnMouseEvent (this, mouseEvent);
  272. return base.OnMouseEvent (mouseEvent);
  273. }
  274. internal void AddLayer ()
  275. {
  276. CurrentLayer = new ();
  277. Layers.Add (CurrentLayer);
  278. }
  279. internal void SetAttribute (Attribute a) { CurrentAttribute = a; }
  280. public void ClearUndo () { _undoHistory.Clear (); }
  281. }
  282. public class AttributeView : View
  283. {
  284. public event EventHandler<Attribute> ValueChanged;
  285. private Attribute _value;
  286. public Attribute Value
  287. {
  288. get => _value;
  289. set
  290. {
  291. _value = value;
  292. ValueChanged?.Invoke (this, value);
  293. }
  294. }
  295. private static readonly HashSet<(int, int)> ForegroundPoints = new()
  296. {
  297. (0, 0), (1, 0), (2, 0),
  298. (0, 1), (1, 1), (2, 1)
  299. };
  300. private static readonly HashSet<(int, int)> BackgroundPoints = new()
  301. {
  302. (3, 1),
  303. (1, 2), (2, 2), (3, 2)
  304. };
  305. public AttributeView ()
  306. {
  307. Width = 4;
  308. Height = 3;
  309. }
  310. /// <inheritdoc/>
  311. public override void OnDrawContent (Rectangle viewport)
  312. {
  313. base.OnDrawContent (viewport);
  314. Color fg = Value.Foreground;
  315. Color bg = Value.Background;
  316. bool isTransparentFg = fg == GetNormalColor ().Background;
  317. bool isTransparentBg = bg == GetNormalColor ().Background;
  318. Driver.SetAttribute (new (fg, isTransparentFg ? Color.Gray : fg));
  319. // Square of foreground color
  320. foreach ((int, int) point in ForegroundPoints)
  321. {
  322. // Make pattern like this when it is same color as background of control
  323. /*▓▒
  324. ▒▓*/
  325. Rune rune;
  326. if (isTransparentFg)
  327. {
  328. rune = (Rune)(point.Item1 % 2 == point.Item2 % 2 ? '▓' : '▒');
  329. }
  330. else
  331. {
  332. rune = (Rune)'█';
  333. }
  334. AddRune (point.Item1, point.Item2, rune);
  335. }
  336. Driver.SetAttribute (new (bg, isTransparentBg ? Color.Gray : bg));
  337. // Square of background color
  338. foreach ((int, int) point in BackgroundPoints)
  339. {
  340. // Make pattern like this when it is same color as background of control
  341. /*▓▒
  342. ▒▓*/
  343. Rune rune;
  344. if (isTransparentBg)
  345. {
  346. rune = (Rune)(point.Item1 % 2 == point.Item2 % 2 ? '▓' : '▒');
  347. }
  348. else
  349. {
  350. rune = (Rune)'█';
  351. }
  352. AddRune (point.Item1, point.Item2, rune);
  353. }
  354. }
  355. /// <inheritdoc/>
  356. protected override bool OnMouseEvent (MouseEvent mouseEvent)
  357. {
  358. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked))
  359. {
  360. if (IsForegroundPoint (mouseEvent.Position.X, mouseEvent.Position.Y))
  361. {
  362. ClickedInForeground ();
  363. }
  364. else if (IsBackgroundPoint (mouseEvent.Position.X, mouseEvent.Position.Y))
  365. {
  366. ClickedInBackground ();
  367. }
  368. }
  369. return base.OnMouseEvent (mouseEvent);
  370. }
  371. private bool IsForegroundPoint (int x, int y) { return ForegroundPoints.Contains ((x, y)); }
  372. private bool IsBackgroundPoint (int x, int y) { return BackgroundPoints.Contains ((x, y)); }
  373. private void ClickedInBackground ()
  374. {
  375. if (LineDrawing.PromptForColor ("Background", Value.Background, out Color newColor))
  376. {
  377. Value = new (Value.Foreground, newColor);
  378. SetNeedsDisplay ();
  379. }
  380. }
  381. private void ClickedInForeground ()
  382. {
  383. if (LineDrawing.PromptForColor ("Foreground", Value.Foreground, out Color newColor))
  384. {
  385. Value = new (newColor, Value.Background);
  386. SetNeedsDisplay ();
  387. }
  388. }
  389. }