View.Drawing.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. using System.ComponentModel;
  2. using System.Diagnostics;
  3. namespace Terminal.Gui.ViewBase;
  4. public partial class View // Drawing APIs
  5. {
  6. /// <summary>
  7. /// Draws a set of peer views (views that share the same SuperView).
  8. /// </summary>
  9. /// <param name="views">The peer views to draw.</param>
  10. /// <param name="force">If <see langword="true"/>, <see cref="View.SetNeedsDraw()"/> will be called on each view to force it to be drawn.</param>
  11. internal static void Draw (IEnumerable<View> views, bool force)
  12. {
  13. // **Snapshot once** — every recursion level gets its own frozen array
  14. View [] viewsArray = views.Snapshot ();
  15. // The draw context is used to track the region drawn by each view.
  16. DrawContext context = new DrawContext ();
  17. foreach (View view in viewsArray)
  18. {
  19. if (force)
  20. {
  21. view.SetNeedsDraw ();
  22. }
  23. view.Draw (context);
  24. }
  25. // Draw the margins last to ensure they are drawn on top of the content.
  26. Margin.DrawMargins (viewsArray);
  27. // DrawMargins may have caused some views have NeedsDraw/NeedsSubViewDraw set; clear them all.
  28. foreach (View view in viewsArray)
  29. {
  30. view.ClearNeedsDraw ();
  31. }
  32. // After all peer views have been drawn and cleared, we can now clear the SuperView's SubViewNeedsDraw flag.
  33. // ClearNeedsDraw() does not clear SuperView.SubViewNeedsDraw (by design, to avoid premature clearing
  34. // when peer subviews still need drawing), so we must do it here after ALL peers are processed.
  35. // We only clear the flag if ALL the SuperView's SubViews no longer need drawing.
  36. View? lastSuperView = null;
  37. foreach (View view in viewsArray)
  38. {
  39. if (view is not Adornment && view.SuperView is { } && view.SuperView != lastSuperView)
  40. {
  41. // Check if ANY subview of this SuperView still needs drawing
  42. bool anySubViewNeedsDrawing = view.SuperView.InternalSubViews.Any (v => v.NeedsDraw || v.SubViewNeedsDraw);
  43. if (!anySubViewNeedsDrawing)
  44. {
  45. view.SuperView.SubViewNeedsDraw = false;
  46. }
  47. lastSuperView = view.SuperView;
  48. }
  49. }
  50. }
  51. /// <summary>
  52. /// Draws the view if it needs to be drawn.
  53. /// </summary>
  54. /// <remarks>
  55. /// <para>
  56. /// The view will only be drawn if it is visible, and has any of <see cref="NeedsDraw"/>,
  57. /// <see cref="SubViewNeedsDraw"/>,
  58. /// or <see cref="NeedsLayout"/> set.
  59. /// </para>
  60. /// <para>
  61. /// See the View Drawing Deep Dive for more information: <see href="https://gui-cs.github.io/Terminal.Gui/docs/drawing.html"/>.
  62. /// </para>
  63. /// </remarks>
  64. public void Draw (DrawContext? context = null)
  65. {
  66. if (!CanBeVisible (this))
  67. {
  68. return;
  69. }
  70. Region? originalClip = GetClip ();
  71. // TODO: This can be further optimized by checking NeedsDraw below and only
  72. // TODO: clearing, drawing text, drawing content, etc. if it is true.
  73. if (NeedsDraw || SubViewNeedsDraw)
  74. {
  75. // ------------------------------------
  76. // Draw the Border and Padding Adornments.
  77. // Note: Margin with a Shadow is special-cased and drawn in a separate pass to support
  78. // transparent shadows.
  79. DoDrawAdornments (originalClip);
  80. SetClip (originalClip);
  81. // ------------------------------------
  82. // Clear the Viewport
  83. // By default, we clip to the viewport preventing drawing outside the viewport
  84. // We also clip to the content, but if a developer wants to draw outside the viewport, they can do
  85. // so via settings. SetClip honors the ViewportSettings.DisableVisibleContentClipping flag.
  86. // Get our Viewport in screen coordinates
  87. originalClip = AddViewportToClip ();
  88. // If no context ...
  89. context ??= new ();
  90. SetAttributeForRole (Enabled ? VisualRole.Normal : VisualRole.Disabled);
  91. DoClearViewport (context);
  92. // ------------------------------------
  93. // Draw the SubViews first (order matters: SubViews, Text, Content)
  94. if (SubViewNeedsDraw)
  95. {
  96. DoDrawSubViews (context);
  97. }
  98. // ------------------------------------
  99. // Draw the text
  100. SetAttributeForRole (Enabled ? VisualRole.Normal : VisualRole.Disabled);
  101. DoDrawText (context);
  102. // ------------------------------------
  103. // Draw the content
  104. DoDrawContent (context);
  105. // ------------------------------------
  106. // Draw the line canvas
  107. // Restore the clip before rendering the line canvas and adornment subviews
  108. // because they may draw outside the viewport.
  109. SetClip (originalClip);
  110. originalClip = AddFrameToClip ();
  111. DoRenderLineCanvas (context);
  112. // ------------------------------------
  113. // Re-draw the Border and Padding Adornment SubViews
  114. // HACK: This is a hack to ensure that the Border and Padding Adornment SubViews are drawn after the line canvas.
  115. DoDrawAdornmentsSubViews ();
  116. // ------------------------------------
  117. // Advance the diagnostics draw indicator
  118. Border?.AdvanceDrawIndicator ();
  119. ClearNeedsDraw ();
  120. if (this is not Adornment && SuperView is not Adornment)
  121. {
  122. // Parent
  123. Debug.Assert (Margin!.Parent == this);
  124. Debug.Assert (Border!.Parent == this);
  125. Debug.Assert (Padding!.Parent == this);
  126. // SubViewNeedsDraw is set to false by ClearNeedsDraw.
  127. Debug.Assert (SubViewNeedsDraw == false);
  128. Debug.Assert (Margin!.SubViewNeedsDraw == false);
  129. Debug.Assert (Border!.SubViewNeedsDraw == false);
  130. Debug.Assert (Padding!.SubViewNeedsDraw == false);
  131. // NeedsDraw is set to false by ClearNeedsDraw.
  132. Debug.Assert (NeedsDraw == false);
  133. Debug.Assert (Margin!.NeedsDraw == false);
  134. Debug.Assert (Border!.NeedsDraw == false);
  135. Debug.Assert (Padding!.NeedsDraw == false);
  136. }
  137. }
  138. // ------------------------------------
  139. // This causes the Margin to be drawn in a second pass if it has a ShadowStyle
  140. Margin?.CacheClip ();
  141. // ------------------------------------
  142. // Reset the clip to what it was when we started
  143. SetClip (originalClip);
  144. // ------------------------------------
  145. // We're done drawing - The Clip is reset to what it was before we started
  146. // But the context contains the region that was drawn by this view
  147. DoDrawComplete (context);
  148. // When DoDrawComplete returns, Driver.Clip has been updated to exclude this view's area.
  149. // The next view drawn (earlier in Z-order, typically a peer view or the SuperView) will see
  150. // a clip with "holes" where this view (and any SubViews drawn before it) are located.
  151. }
  152. #region DrawAdornments
  153. private void DoDrawAdornmentsSubViews ()
  154. {
  155. // NOTE: We do not support SubViews of Margin
  156. if (Border?.SubViews is { } && Border.Thickness != Thickness.Empty && Border.NeedsDraw)
  157. {
  158. // PERFORMANCE: Get the check for DrawIndicator out of this somehow.
  159. foreach (View subview in Border.SubViews.Where (v => v.Visible || v.Id == "DrawIndicator"))
  160. {
  161. if (subview.Id != "DrawIndicator")
  162. {
  163. subview.SetNeedsDraw ();
  164. }
  165. LineCanvas.Exclude (new (subview.FrameToScreen ()));
  166. }
  167. Region? saved = Border?.AddFrameToClip ();
  168. Border?.DoDrawSubViews ();
  169. SetClip (saved);
  170. }
  171. if (Padding?.SubViews is { } && Padding.Thickness != Thickness.Empty && Padding.NeedsDraw)
  172. {
  173. foreach (View subview in Padding.SubViews)
  174. {
  175. subview.SetNeedsDraw ();
  176. }
  177. Region? saved = Padding?.AddFrameToClip ();
  178. Padding?.DoDrawSubViews ();
  179. SetClip (saved);
  180. }
  181. }
  182. internal void DoDrawAdornments (Region? originalClip)
  183. {
  184. if (this is Adornment)
  185. {
  186. AddFrameToClip ();
  187. }
  188. else
  189. {
  190. // Set the clip to be just the thicknesses of the adornments
  191. // TODO: Put this union logic in a method on View?
  192. Region? clipAdornments = Margin!.Thickness.AsRegion (Margin!.FrameToScreen ());
  193. clipAdornments.Combine (Border!.Thickness.AsRegion (Border!.FrameToScreen ()), RegionOp.Union);
  194. clipAdornments.Combine (Padding!.Thickness.AsRegion (Padding!.FrameToScreen ()), RegionOp.Union);
  195. clipAdornments.Combine (originalClip, RegionOp.Intersect);
  196. SetClip (clipAdornments);
  197. }
  198. if (Margin?.NeedsLayout == true)
  199. {
  200. Margin.NeedsLayout = false;
  201. Margin?.Thickness.Draw (Driver, FrameToScreen ());
  202. Margin?.Parent?.SetSubViewNeedsDrawDownHierarchy ();
  203. }
  204. if (SubViewNeedsDraw)
  205. {
  206. // A SubView may add to the LineCanvas. This ensures any Adornment LineCanvas updates happen.
  207. Border?.SetNeedsDraw ();
  208. Padding?.SetNeedsDraw ();
  209. Margin?.SetNeedsDraw ();
  210. }
  211. if (OnDrawingAdornments ())
  212. {
  213. return;
  214. }
  215. // TODO: add event.
  216. DrawAdornments ();
  217. }
  218. /// <summary>
  219. /// Causes <see cref="Margin"/>, <see cref="Border"/>, and <see cref="Padding"/> to be drawn.
  220. /// </summary>
  221. /// <remarks>
  222. /// <para>
  223. /// <see cref="Margin"/> is drawn in a separate pass if <see cref="ShadowStyle"/> is set.
  224. /// </para>
  225. /// </remarks>
  226. public void DrawAdornments ()
  227. {
  228. // We do not attempt to draw Margin. It is drawn in a separate pass.
  229. // Each of these renders lines to this View's LineCanvas
  230. // Those lines will be finally rendered in OnRenderLineCanvas
  231. if (Border is { } && Border.Thickness != Thickness.Empty)
  232. {
  233. Border?.Draw ();
  234. }
  235. if (Padding is { } && Padding.Thickness != Thickness.Empty)
  236. {
  237. Padding?.Draw ();
  238. }
  239. if (Margin is { } && Margin.Thickness != Thickness.Empty/* && Margin.ShadowStyle == ShadowStyle.None*/)
  240. {
  241. //Margin?.Draw ();
  242. }
  243. }
  244. private void ClearFrame ()
  245. {
  246. if (Driver is null)
  247. {
  248. return;
  249. }
  250. // Get screen-relative coords
  251. Rectangle toClear = FrameToScreen ();
  252. Attribute prev = SetAttribute (GetAttributeForRole (VisualRole.Normal));
  253. Driver.FillRect (toClear);
  254. SetAttribute (prev);
  255. SetNeedsDraw ();
  256. }
  257. /// <summary>
  258. /// Called when the View's Adornments are to be drawn. Prepares <see cref="View.LineCanvas"/>. If
  259. /// <see cref="SuperViewRendersLineCanvas"/> is true, only the
  260. /// <see cref="LineCanvas"/> of this view's SubViews will be rendered. If <see cref="SuperViewRendersLineCanvas"/> is
  261. /// false (the default), this method will cause the <see cref="LineCanvas"/> be prepared to be rendered.
  262. /// </summary>
  263. /// <returns><see langword="true"/> to stop further drawing of the Adornments.</returns>
  264. protected virtual bool OnDrawingAdornments () { return false; }
  265. #endregion DrawAdornments
  266. #region ClearViewport
  267. internal void DoClearViewport (DrawContext? context = null)
  268. {
  269. if (!NeedsDraw || ViewportSettings.HasFlag (ViewportSettingsFlags.Transparent) || OnClearingViewport ())
  270. {
  271. return;
  272. }
  273. var dev = new DrawEventArgs (Viewport, Rectangle.Empty, context);
  274. ClearingViewport?.Invoke (this, dev);
  275. if (dev.Cancel)
  276. {
  277. // BUGBUG: We should add the Viewport to context.DrawRegion here?
  278. SetNeedsDraw ();
  279. return;
  280. }
  281. if (!ViewportSettings.HasFlag (ViewportSettingsFlags.Transparent))
  282. {
  283. ClearViewport (context);
  284. OnClearedViewport ();
  285. ClearedViewport?.Invoke (this, new (Viewport, Viewport, null));
  286. }
  287. }
  288. /// <summary>
  289. /// Called when the <see cref="Viewport"/> is to be cleared.
  290. /// </summary>
  291. /// <returns><see langword="true"/> to stop further clearing.</returns>
  292. protected virtual bool OnClearingViewport () { return false; }
  293. /// <summary>Event invoked when the <see cref="Viewport"/> is to be cleared.</summary>
  294. /// <remarks>
  295. /// <para>Will be invoked before any subviews added with <see cref="Add(View)"/> have been drawn.</para>
  296. /// <para>
  297. /// Rect provides the view-relative rectangle describing the currently visible viewport into the
  298. /// <see cref="View"/> .
  299. /// </para>
  300. /// </remarks>
  301. public event EventHandler<DrawEventArgs>? ClearingViewport;
  302. /// <summary>
  303. /// Called when the <see cref="Viewport"/> has been cleared
  304. /// </summary>
  305. protected virtual void OnClearedViewport () { }
  306. /// <summary>Event invoked when the <see cref="Viewport"/> has been cleared.</summary>
  307. public event EventHandler<DrawEventArgs>? ClearedViewport;
  308. /// <summary>Clears <see cref="Viewport"/> with the normal background.</summary>
  309. /// <remarks>
  310. /// <para>
  311. /// If <see cref="ViewportSettings"/> has <see cref="ViewBase.ViewportSettingsFlags.ClearContentOnly"/> only
  312. /// the portion of the content
  313. /// area that is visible within the <see cref="View.Viewport"/> will be cleared. This is useful for views that have
  314. /// a
  315. /// content area larger than the Viewport (e.g. when <see cref="ViewportSettingsFlags.AllowNegativeLocation"/> is
  316. /// enabled) and want
  317. /// the area outside the content to be visually distinct.
  318. /// </para>
  319. /// </remarks>
  320. public void ClearViewport (DrawContext? context = null)
  321. {
  322. if (Driver is null)
  323. {
  324. return;
  325. }
  326. // Get screen-relative coords
  327. Rectangle toClear = ViewportToScreen (Viewport with { Location = new (0, 0) });
  328. if (ViewportSettings.HasFlag (ViewportSettingsFlags.ClearContentOnly))
  329. {
  330. Rectangle visibleContent = ViewportToScreen (new Rectangle (new (-Viewport.X, -Viewport.Y), GetContentSize ()));
  331. toClear = Rectangle.Intersect (toClear, visibleContent);
  332. }
  333. Driver.FillRect (toClear);
  334. // context.AddDrawnRectangle (toClear);
  335. SetNeedsDraw ();
  336. }
  337. #endregion ClearViewport
  338. #region DrawText
  339. private void DoDrawText (DrawContext? context = null)
  340. {
  341. if (!NeedsDraw)
  342. {
  343. return;
  344. }
  345. if (!string.IsNullOrEmpty (TextFormatter.Text))
  346. {
  347. TextFormatter.NeedsFormat = true;
  348. }
  349. if (OnDrawingText (context))
  350. {
  351. return;
  352. }
  353. // TODO: Get rid of this vf in lieu of the one above
  354. if (OnDrawingText ())
  355. {
  356. return;
  357. }
  358. var dev = new DrawEventArgs (Viewport, Rectangle.Empty, context);
  359. DrawingText?.Invoke (this, dev);
  360. if (dev.Cancel)
  361. {
  362. return;
  363. }
  364. DrawText (context);
  365. OnDrewText ();
  366. DrewText?.Invoke (this, EventArgs.Empty);
  367. }
  368. /// <summary>
  369. /// Called when the <see cref="Text"/> of the View is to be drawn.
  370. /// </summary>
  371. /// <param name="context">The draw context to report drawn areas to.</param>
  372. /// <returns><see langword="true"/> to stop further drawing of <see cref="Text"/>.</returns>
  373. protected virtual bool OnDrawingText (DrawContext? context) { return false; }
  374. /// <summary>
  375. /// Called when the <see cref="Text"/> of the View is to be drawn.
  376. /// </summary>
  377. /// <returns><see langword="true"/> to stop further drawing of <see cref="Text"/>.</returns>
  378. protected virtual bool OnDrawingText () { return false; }
  379. /// <summary>Raised when the <see cref="Text"/> of the View is to be drawn.</summary>
  380. /// <returns>
  381. /// Set <see cref="CancelEventArgs.Cancel"/> to <see langword="true"/> to stop further drawing of
  382. /// <see cref="Text"/>.
  383. /// </returns>
  384. public event EventHandler<DrawEventArgs>? DrawingText;
  385. /// <summary>
  386. /// Draws the <see cref="Text"/> of the View using the <see cref="TextFormatter"/>.
  387. /// </summary>
  388. /// <param name="context">The draw context to report drawn areas to.</param>
  389. public void DrawText (DrawContext? context = null)
  390. {
  391. var drawRect = new Rectangle (ContentToScreen (Point.Empty), GetContentSize ());
  392. // Use GetDrawRegion to get precise drawn areas
  393. Region textRegion = TextFormatter.GetDrawRegion (drawRect);
  394. // Report the drawn area to the context
  395. context?.AddDrawnRegion (textRegion);
  396. if (Driver is { })
  397. {
  398. TextFormatter.Draw (
  399. Driver,
  400. drawRect,
  401. HasFocus ? GetAttributeForRole (VisualRole.Focus) : GetAttributeForRole (VisualRole.Normal),
  402. HasFocus ? GetAttributeForRole (VisualRole.HotFocus) : GetAttributeForRole (VisualRole.HotNormal),
  403. Rectangle.Empty);
  404. }
  405. // We assume that the text has been drawn over the entire area; ensure that the SubViews are redrawn.
  406. SetSubViewNeedsDrawDownHierarchy ();
  407. }
  408. /// <summary>
  409. /// Called when the <see cref="Text"/> of the View has been drawn.
  410. /// </summary>
  411. protected virtual void OnDrewText () { }
  412. /// <summary>Raised when the <see cref="Text"/> of the View has been drawn.</summary>
  413. public event EventHandler? DrewText;
  414. #endregion DrawText
  415. #region DrawContent
  416. private void DoDrawContent (DrawContext? context = null)
  417. {
  418. if (!NeedsDraw || OnDrawingContent (context))
  419. {
  420. return;
  421. }
  422. var dev = new DrawEventArgs (Viewport, Rectangle.Empty, context);
  423. DrawingContent?.Invoke (this, dev);
  424. if (dev.Cancel)
  425. {
  426. return;
  427. }
  428. // No default drawing; let event handlers or overrides handle it
  429. }
  430. /// <summary>
  431. /// Called when the View's content is to be drawn. The default implementation does nothing.
  432. /// </summary>
  433. /// <param name="context">The draw context to report drawn areas to.</param>
  434. /// <returns><see langword="true"/> to stop further drawing content.</returns>
  435. /// <remarks>
  436. /// <para>
  437. /// Override this method to draw custom content for your View.
  438. /// </para>
  439. /// <para>
  440. /// <b>Transparency Support:</b> If your View has <see cref="ViewportSettings"/> with <see cref="ViewportSettingsFlags.Transparent"/>
  441. /// set, you should report the exact regions you draw to via the <paramref name="context"/> parameter. This allows
  442. /// the transparency system to exclude only the drawn areas from the clip region, letting views beneath show through
  443. /// in the areas you didn't draw.
  444. /// </para>
  445. /// <para>
  446. /// Use <see cref="DrawContext.AddDrawnRectangle"/> for simple rectangular areas, or <see cref="DrawContext.AddDrawnRegion"/>
  447. /// for complex, non-rectangular shapes. All coordinates passed to these methods must be in <b>screen-relative coordinates</b>.
  448. /// Use <see cref="View.ViewportToScreen(in Rectangle)"/> or <see cref="View.ContentToScreen(in Point)"/> to convert from
  449. /// viewport-relative or content-relative coordinates.
  450. /// </para>
  451. /// <para>
  452. /// Example of drawing custom content with transparency support:
  453. /// </para>
  454. /// <code>
  455. /// protected override bool OnDrawingContent (DrawContext? context)
  456. /// {
  457. /// base.OnDrawingContent (context);
  458. ///
  459. /// // Draw content in viewport-relative coordinates
  460. /// Rectangle rect1 = new Rectangle (5, 5, 10, 3);
  461. /// Rectangle rect2 = new Rectangle (8, 8, 4, 7);
  462. /// FillRect (rect1, Glyphs.BlackCircle);
  463. /// FillRect (rect2, Glyphs.BlackCircle);
  464. ///
  465. /// // Report drawn region in screen-relative coordinates for transparency
  466. /// if (ViewportSettings.HasFlag (ViewportSettingsFlags.Transparent))
  467. /// {
  468. /// Region drawnRegion = new Region (ViewportToScreen (rect1));
  469. /// drawnRegion.Union (ViewportToScreen (rect2));
  470. /// context?.AddDrawnRegion (drawnRegion);
  471. /// }
  472. ///
  473. /// return true;
  474. /// }
  475. /// </code>
  476. /// </remarks>
  477. protected virtual bool OnDrawingContent (DrawContext? context) { return false; }
  478. /// <summary>Raised when the View's content is to be drawn.</summary>
  479. /// <remarks>
  480. /// <para>
  481. /// Subscribe to this event to draw custom content for the View. Use the drawing methods available on <see cref="View"/>
  482. /// such as <see cref="View.AddRune(int, int, Rune)"/>, <see cref="View.AddStr(string)"/>, and <see cref="View.FillRect(Rectangle, Rune)"/>.
  483. /// </para>
  484. /// <para>
  485. /// The event is invoked after <see cref="ClearingViewport"/> and <see cref="Text"/> have been drawn, but after <see cref="SubViews"/> have been drawn.
  486. /// </para>
  487. /// <para>
  488. /// <b>Transparency Support:</b> If the View has <see cref="ViewportSettings"/> with <see cref="ViewportSettingsFlags.Transparent"/>
  489. /// set, use the <see cref="DrawEventArgs.DrawContext"/> to report which areas were actually drawn. This enables proper transparency
  490. /// by excluding only the drawn areas from the clip region. See <see cref="DrawContext"/> for details on reporting drawn regions.
  491. /// </para>
  492. /// <para>
  493. /// The <see cref="DrawEventArgs.NewViewport"/> property provides the view-relative rectangle describing the currently visible viewport into the View.
  494. /// </para>
  495. /// </remarks>
  496. public event EventHandler<DrawEventArgs>? DrawingContent;
  497. #endregion DrawContent
  498. #region DrawSubViews
  499. private void DoDrawSubViews (DrawContext? context = null)
  500. {
  501. if (!NeedsDraw || OnDrawingSubViews (context))
  502. {
  503. return;
  504. }
  505. // TODO: Get rid of this vf in lieu of the one above
  506. if (OnDrawingSubViews ())
  507. {
  508. return;
  509. }
  510. var dev = new DrawEventArgs (Viewport, Rectangle.Empty, context);
  511. DrawingSubViews?.Invoke (this, dev);
  512. if (dev.Cancel)
  513. {
  514. return;
  515. }
  516. if (!SubViewNeedsDraw)
  517. {
  518. return;
  519. }
  520. DrawSubViews (context);
  521. }
  522. /// <summary>
  523. /// Called when the <see cref="SubViews"/> are to be drawn.
  524. /// </summary>
  525. /// <param name="context">The draw context to report drawn areas to, or null if not tracking.</param>
  526. /// <returns><see langword="true"/> to stop further drawing of <see cref="SubViews"/>.</returns>
  527. protected virtual bool OnDrawingSubViews (DrawContext? context) { return false; }
  528. /// <summary>
  529. /// Called when the <see cref="SubViews"/> are to be drawn.
  530. /// </summary>
  531. /// <returns><see langword="true"/> to stop further drawing of <see cref="SubViews"/>.</returns>
  532. protected virtual bool OnDrawingSubViews () { return false; }
  533. /// <summary>Raised when the <see cref="SubViews"/> are to be drawn.</summary>
  534. /// <remarks>
  535. /// </remarks>
  536. /// <returns>
  537. /// Set <see cref="CancelEventArgs.Cancel"/> to <see langword="true"/> to stop further drawing of
  538. /// <see cref="SubViews"/>.
  539. /// </returns>
  540. public event EventHandler<DrawEventArgs>? DrawingSubViews;
  541. /// <summary>
  542. /// Draws the <see cref="SubViews"/>.
  543. /// </summary>
  544. /// <param name="context">The draw context to report drawn areas to, or null if not tracking.</param>
  545. public void DrawSubViews (DrawContext? context = null)
  546. {
  547. if (InternalSubViews.Count == 0)
  548. {
  549. return;
  550. }
  551. // Draw the SubViews in reverse Z-order to leverage clipping.
  552. // SubViews earlier in the collection are drawn last (on top).
  553. foreach (View view in InternalSubViews.Snapshot ().Where (v => v.Visible).Reverse ())
  554. {
  555. // TODO: HACK - This forcing of SetNeedsDraw with SuperViewRendersLineCanvas enables auto line join to work, but is brute force.
  556. if (view.SuperViewRendersLineCanvas || view.ViewportSettings.HasFlag (ViewportSettingsFlags.Transparent))
  557. {
  558. //view.SetNeedsDraw ();
  559. }
  560. view.Draw (context);
  561. if (view.SuperViewRendersLineCanvas)
  562. {
  563. LineCanvas.Merge (view.LineCanvas);
  564. view.LineCanvas.Clear ();
  565. }
  566. }
  567. }
  568. #endregion DrawSubViews
  569. #region DrawLineCanvas
  570. private void DoRenderLineCanvas (DrawContext? context)
  571. {
  572. // TODO: Add context to OnRenderingLineCanvas
  573. if (!NeedsDraw || OnRenderingLineCanvas ())
  574. {
  575. return;
  576. }
  577. // TODO: Add event
  578. RenderLineCanvas (context);
  579. }
  580. /// <summary>
  581. /// Called when the <see cref="View.LineCanvas"/> is to be rendered. See <see cref="RenderLineCanvas"/>.
  582. /// </summary>
  583. /// <returns><see langword="true"/> to stop further drawing of <see cref="LineCanvas"/>.</returns>
  584. protected virtual bool OnRenderingLineCanvas () { return false; }
  585. /// <summary>The canvas that any line drawing that is to be shared by SubViews of this view should add lines to.</summary>
  586. /// <remarks><see cref="Border"/> adds border lines to this LineCanvas.</remarks>
  587. public LineCanvas LineCanvas { get; } = new ();
  588. /// <summary>
  589. /// Gets or sets whether this View will use its SuperView's <see cref="LineCanvas"/> for rendering any
  590. /// lines. If <see langword="true"/> the rendering of any borders drawn by this view will be done by its
  591. /// SuperView. If <see langword="false"/> (the default) this View's <see cref="OnDrawingAdornments"/> method will
  592. /// be called to render the borders.
  593. /// </summary>
  594. public virtual bool SuperViewRendersLineCanvas { get; set; } = false;
  595. /// <summary>
  596. /// Causes the contents of <see cref="LineCanvas"/> to be drawn.
  597. /// If <see cref="SuperViewRendersLineCanvas"/> is true, only the
  598. /// <see cref="LineCanvas"/> of this view's SubViews will be rendered. If <see cref="SuperViewRendersLineCanvas"/> is
  599. /// false (the default), this method will cause the <see cref="LineCanvas"/> to be rendered.
  600. /// </summary>
  601. /// <param name="context"></param>
  602. public void RenderLineCanvas (DrawContext? context)
  603. {
  604. if (Driver is null)
  605. {
  606. return;
  607. }
  608. if (!SuperViewRendersLineCanvas && LineCanvas.Bounds != Rectangle.Empty)
  609. {
  610. foreach (KeyValuePair<Point, Cell?> p in LineCanvas.GetCellMap ())
  611. {
  612. // Get the entire map
  613. if (p.Value is { })
  614. {
  615. SetAttribute (p.Value.Value.Attribute ?? GetAttributeForRole (VisualRole.Normal));
  616. Driver.Move (p.Key.X, p.Key.Y);
  617. // TODO: #2616 - Support combining sequences that don't normalize
  618. AddStr (p.Value.Value.Grapheme);
  619. // Add each drawn cell to the context
  620. //context?.AddDrawnRectangle (new Rectangle (p.Key, new (1, 1)) );
  621. }
  622. }
  623. LineCanvas.Clear ();
  624. }
  625. }
  626. #endregion DrawLineCanvas
  627. #region DrawComplete
  628. /// <summary>
  629. /// Called at the end of <see cref="Draw(DrawContext)"/> to finalize drawing and update the clip region.
  630. /// </summary>
  631. /// <param name="context">
  632. /// The <see cref="DrawContext"/> tracking what regions were drawn by this view and its subviews.
  633. /// May be <see langword="null"/> if not tracking drawn regions.
  634. /// </param>
  635. private void DoDrawComplete (DrawContext? context)
  636. {
  637. // Phase 1: Notify that drawing is complete
  638. // Raise virtual method first, then event. This allows subclasses to override behavior
  639. // before subscribers see the event.
  640. OnDrawComplete (context);
  641. DrawComplete?.Invoke (this, new (Viewport, Viewport, context));
  642. // Phase 2: Update Driver.Clip to exclude this view's drawn area
  643. // This prevents views "behind" this one (earlier in draw order/Z-order) from drawing over it.
  644. // Adornments (Margin, Border, Padding) are handled by their Adornment.Parent view and don't exclude themselves.
  645. if (this is not Adornment)
  646. {
  647. if (ViewportSettings.HasFlag (ViewportSettingsFlags.Transparent))
  648. {
  649. // Transparent View Path:
  650. // Only exclude the regions that were actually drawn, allowing views beneath
  651. // to show through in areas where nothing was drawn.
  652. // The context.DrawnRegion may include areas outside the Viewport (e.g., if content
  653. // was drawn with ViewportSettingsFlags.AllowContentOutsideViewport). We need to clip
  654. // it to the Viewport bounds to prevent excluding areas that aren't visible.
  655. context!.ClipDrawnRegion (ViewportToScreen (Viewport));
  656. // Exclude the actually-drawn region from Driver.Clip
  657. ExcludeFromClip (context.GetDrawnRegion ());
  658. // Border and Padding are always opaque (they draw lines/fills), so exclude them too
  659. ExcludeFromClip (Border?.Thickness.AsRegion (Border.FrameToScreen ()));
  660. ExcludeFromClip (Padding?.Thickness.AsRegion (Padding.FrameToScreen ()));
  661. }
  662. else
  663. {
  664. // Opaque View Path (default):
  665. // Exclude the entire view area from Driver.Clip. This is the typical case where
  666. // the view is considered fully opaque.
  667. // Start with the Frame in screen coordinates
  668. Rectangle borderFrame = FrameToScreen ();
  669. // If there's a Border, use its frame instead (includes the border thickness)
  670. if (Border is { })
  671. {
  672. borderFrame = Border.FrameToScreen ();
  673. }
  674. // Exclude this view's entire area (Border inward, but not Margin) from the clip.
  675. // This prevents any view drawn after this one from drawing in this area.
  676. ExcludeFromClip (borderFrame);
  677. // Update the DrawContext to track that we drew this entire rectangle.
  678. // This allows our SuperView (if any) to know what area we occupied,
  679. // which is important for transparency calculations at higher levels.
  680. context?.AddDrawnRectangle (borderFrame);
  681. }
  682. }
  683. // When this method returns, Driver.Clip has been updated to exclude this view's area.
  684. // The next view drawn (earlier in Z-order, typically a peer view or the SuperView) will see
  685. // a clip with "holes" where this view (and any SubViews drawn before it) are located.
  686. }
  687. /// <summary>
  688. /// Called when the View has completed drawing and is about to update the clip region.
  689. /// </summary>
  690. /// <param name="context">
  691. /// The <see cref="DrawContext"/> containing the regions that were drawn by this view and its subviews.
  692. /// May be <see langword="null"/> if not tracking drawn regions.
  693. /// </param>
  694. /// <remarks>
  695. /// <para>
  696. /// This method is called at the very end of <see cref="Draw(DrawContext)"/>, after all drawing
  697. /// (adornments, content, text, subviews, line canvas) has completed but before the view's area
  698. /// is excluded from <see cref="IDriver.Clip"/>.
  699. /// </para>
  700. /// <para>
  701. /// Use this method to:
  702. /// </para>
  703. /// <list type="bullet">
  704. /// <item>
  705. /// <description>Perform any final drawing operations that need to happen after SubViews are drawn</description>
  706. /// </item>
  707. /// <item>
  708. /// <description>Inspect what was drawn via the <paramref name="context"/> parameter</description>
  709. /// </item>
  710. /// <item>
  711. /// <description>Add additional regions to the <paramref name="context"/> if needed</description>
  712. /// </item>
  713. /// </list>
  714. /// <para>
  715. /// <b>Important:</b> At this point, <see cref="IDriver.Clip"/> has been restored to the state
  716. /// it was in when <see cref="Draw(DrawContext)"/> began. After this method returns, the view's
  717. /// area will be excluded from the clip (see <see cref="DoDrawComplete"/> for details).
  718. /// </para>
  719. /// <para>
  720. /// <b>Transparency Support:</b> If <see cref="ViewportSettings"/> includes
  721. /// <see cref="ViewportSettingsFlags.Transparent"/>, the <paramref name="context"/> parameter
  722. /// contains the actual regions that were drawn. You can inspect this to see what areas
  723. /// will be excluded from the clip, and optionally add more regions if needed.
  724. /// </para>
  725. /// </remarks>
  726. /// <seealso cref="DrawComplete"/>
  727. /// <seealso cref="Draw(DrawContext)"/>
  728. /// <seealso cref="DoDrawComplete"/>
  729. protected virtual void OnDrawComplete (DrawContext? context) { }
  730. /// <summary>Raised when the View has completed drawing and is about to update the clip region.</summary>
  731. /// <remarks>
  732. /// <para>
  733. /// This event is raised at the very end of <see cref="Draw(DrawContext)"/>, after all drawing
  734. /// operations have completed but before the view's area is excluded from <see cref="IDriver.Clip"/>.
  735. /// </para>
  736. /// <para>
  737. /// The <see cref="DrawEventArgs.DrawContext"/> property provides information about what regions
  738. /// were drawn by this view and its subviews. This is particularly useful for views with
  739. /// <see cref="ViewportSettingsFlags.Transparent"/> enabled, as it shows exactly which areas
  740. /// will be excluded from the clip.
  741. /// </para>
  742. /// <para>
  743. /// Use this event to:
  744. /// </para>
  745. /// <list type="bullet">
  746. /// <item>
  747. /// <description>Perform any final drawing operations</description>
  748. /// </item>
  749. /// <item>
  750. /// <description>Inspect what was drawn</description>
  751. /// </item>
  752. /// <item>
  753. /// <description>Track drawing statistics or metrics</description>
  754. /// </item>
  755. /// </list>
  756. /// <para>
  757. /// <b>Note:</b> This event fires <i>after</i> <see cref="OnDrawComplete(DrawContext)"/>. If you need
  758. /// to override the behavior, prefer overriding the virtual method in a subclass rather than
  759. /// subscribing to this event.
  760. /// </para>
  761. /// </remarks>
  762. /// <seealso cref="OnDrawComplete(DrawContext)"/>
  763. /// <seealso cref="Draw(DrawContext)"/>
  764. public event EventHandler<DrawEventArgs>? DrawComplete;
  765. #endregion DrawComplete
  766. }