PlotBase.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="PlotBase.cs" company="OxyPlot">
  3. // Copyright (c) 2014 OxyPlot contributors
  4. // </copyright>
  5. // <summary>
  6. // Represents a control that displays a <see cref="PlotModel" />.
  7. // </summary>
  8. // --------------------------------------------------------------------------------------------------------------------
  9. using Avalonia.Reactive;
  10. namespace OxyPlot.Avalonia
  11. {
  12. using global::Avalonia;
  13. using global::Avalonia.Controls;
  14. using global::Avalonia.Controls.Presenters;
  15. using global::Avalonia.Controls.Primitives;
  16. using global::Avalonia.Input;
  17. using global::Avalonia.Threading;
  18. using global::Avalonia.VisualTree;
  19. using System;
  20. using System.Collections.ObjectModel;
  21. using System.Diagnostics;
  22. using System.Linq;
  23. using System.Threading;
  24. /// <summary>
  25. /// Represents a control that displays a <see cref="PlotModel" />.
  26. /// </summary>
  27. public abstract partial class PlotBase : TemplatedControl, IPlotView
  28. {
  29. /// <summary>
  30. /// The Grid PART constant.
  31. /// </summary>
  32. protected const string PartPanel = "PART_Panel";
  33. /// <summary>
  34. /// The tracker definitions.
  35. /// </summary>
  36. private readonly ObservableCollection<TrackerDefinition> trackerDefinitions;
  37. /// <summary>
  38. /// The render context
  39. /// </summary>
  40. private CanvasRenderContext renderContext;
  41. /// <summary>
  42. /// The canvas.
  43. /// </summary>
  44. private Canvas canvas;
  45. /// <summary>
  46. /// The current tracker.
  47. /// </summary>
  48. private Control currentTracker;
  49. /// <summary>
  50. /// The grid.
  51. /// </summary>
  52. private Panel panel;
  53. /// <summary>
  54. /// Invalidation flag (0: no update, 1: update, 2: update date).
  55. /// </summary>
  56. private int isUpdateRequired;
  57. /// <summary>
  58. /// Invalidation flag (0: no update, 1: update visual elements).
  59. /// </summary>
  60. private int isPlotInvalidated;
  61. /// <summary>
  62. /// The mouse down point.
  63. /// </summary>
  64. private ScreenPoint mouseDownPoint;
  65. /// <summary>
  66. /// The overlays.
  67. /// </summary>
  68. private Canvas overlays;
  69. /// <summary>
  70. /// The zoom control.
  71. /// </summary>
  72. private ContentControl zoomControl;
  73. /// <summary>
  74. /// The is visible to user cache.
  75. /// </summary>
  76. private bool isVisibleToUserCache;
  77. /// <summary>
  78. /// The cached parent.
  79. /// </summary>
  80. private Control containerCache;
  81. /// <summary>
  82. /// Initializes a new instance of the <see cref="PlotBase" /> class.
  83. /// </summary>
  84. protected PlotBase()
  85. {
  86. DisconnectCanvasWhileUpdating = true;
  87. trackerDefinitions = new ObservableCollection<TrackerDefinition>();
  88. this.GetObservable(BoundsProperty).Subscribe(new AnonymousObserver<Rect>(OnSizeChanged));
  89. }
  90. /// <summary>
  91. /// Gets or sets a value indicating whether to disconnect the canvas while updating.
  92. /// </summary>
  93. /// <value><c>true</c> if canvas should be disconnected while updating; otherwise, <c>false</c>.</value>
  94. public bool DisconnectCanvasWhileUpdating { get; set; }
  95. /// <summary>
  96. /// Gets the actual model in the view.
  97. /// </summary>
  98. /// <value>
  99. /// The actual model.
  100. /// </value>
  101. Model IView.ActualModel
  102. {
  103. get
  104. {
  105. return ActualModel;
  106. }
  107. }
  108. /// <summary>
  109. /// Gets the actual model.
  110. /// </summary>
  111. /// <value>The actual model.</value>
  112. public abstract PlotModel ActualModel { get; }
  113. /// <summary>
  114. /// Gets the actual controller.
  115. /// </summary>
  116. /// <value>
  117. /// The actual <see cref="IController" />.
  118. /// </value>
  119. IController IView.ActualController
  120. {
  121. get
  122. {
  123. return ActualController;
  124. }
  125. }
  126. /// <summary>
  127. /// Gets the actual PlotView controller.
  128. /// </summary>
  129. /// <value>The actual PlotView controller.</value>
  130. public abstract IPlotController ActualController { get; }
  131. /// <summary>
  132. /// Gets the coordinates of the client area of the view.
  133. /// </summary>
  134. public OxyRect ClientArea
  135. {
  136. get
  137. {
  138. return new OxyRect(0, 0, Bounds.Width, Bounds.Height);
  139. }
  140. }
  141. /// <summary>
  142. /// Gets the tracker definitions.
  143. /// </summary>
  144. /// <value>The tracker definitions.</value>
  145. public ObservableCollection<TrackerDefinition> TrackerDefinitions
  146. {
  147. get
  148. {
  149. return trackerDefinitions;
  150. }
  151. }
  152. /// <summary>
  153. /// Hides the tracker.
  154. /// </summary>
  155. public void HideTracker()
  156. {
  157. if (currentTracker != null)
  158. {
  159. overlays.Children.Remove(currentTracker);
  160. currentTracker = null;
  161. }
  162. }
  163. /// <summary>
  164. /// Hides the zoom rectangle.
  165. /// </summary>
  166. public void HideZoomRectangle()
  167. {
  168. zoomControl.IsVisible = false;
  169. }
  170. /// <summary>
  171. /// Pans all axes.
  172. /// </summary>
  173. /// <param name="delta">The delta.</param>
  174. public void PanAllAxes(Vector delta)
  175. {
  176. ActualModel?.PanAllAxes(delta.X, delta.Y);
  177. InvalidatePlot(false);
  178. }
  179. /// <summary>
  180. /// Zooms all axes.
  181. /// </summary>
  182. /// <param name="factor">The zoom factor.</param>
  183. public void ZoomAllAxes(double factor)
  184. {
  185. ActualModel?.ZoomAllAxes(factor);
  186. InvalidatePlot(false);
  187. }
  188. /// <summary>
  189. /// Resets all axes.
  190. /// </summary>
  191. public void ResetAllAxes()
  192. {
  193. ActualModel?.ResetAllAxes();
  194. InvalidatePlot(false);
  195. }
  196. /// <summary>
  197. /// Invalidate the PlotView (not blocking the UI thread)
  198. /// </summary>
  199. /// <param name="updateData">The update Data.</param>
  200. public void InvalidatePlot(bool updateData = true)
  201. {
  202. // perform update on UI thread
  203. var updateState = updateData ? 2 : 1;
  204. int currentState = isUpdateRequired;
  205. while (currentState < updateState)
  206. {
  207. if (Interlocked.CompareExchange(ref isUpdateRequired, updateState, currentState) == currentState)
  208. {
  209. BeginInvoke(() => UpdateModel(updateData));
  210. break;
  211. }
  212. else
  213. {
  214. currentState = isUpdateRequired;
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// When overridden in a derived class, is invoked whenever application code or internal processes (such as a rebuilding layout pass)
  220. /// call <see cref="M:System.Windows.Controls.Control.ApplyTemplate" /> . In simplest terms, this means the method is called
  221. /// just before a UI element displays in an application. For more information, see Remarks.
  222. /// </summary>
  223. /// <param name="e">Event data for applying the template.</param>
  224. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  225. {
  226. base.OnApplyTemplate(e);
  227. panel = e.NameScope.Find(PartPanel) as Panel;
  228. if (panel == null)
  229. {
  230. return;
  231. }
  232. canvas = new Canvas();
  233. panel.Children.Add(canvas);
  234. renderContext = new CanvasRenderContext(canvas);
  235. overlays = new Canvas { Name = "Overlays" };
  236. panel.Children.Add(overlays);
  237. zoomControl = new ContentControl();
  238. overlays.Children.Add(zoomControl);
  239. }
  240. /// <summary>
  241. /// Sets the cursor type.
  242. /// </summary>
  243. /// <param name="cursorType">The cursor type.</param>
  244. public void SetCursorType(CursorType cursorType)
  245. {
  246. switch (cursorType)
  247. {
  248. case CursorType.Pan:
  249. Cursor = PanCursor;
  250. break;
  251. case CursorType.ZoomRectangle:
  252. Cursor = ZoomRectangleCursor;
  253. break;
  254. case CursorType.ZoomHorizontal:
  255. Cursor = ZoomHorizontalCursor;
  256. break;
  257. case CursorType.ZoomVertical:
  258. Cursor = ZoomVerticalCursor;
  259. break;
  260. default:
  261. Cursor = Cursor.Default;
  262. break;
  263. }
  264. }
  265. /// <summary>
  266. /// Shows the tracker.
  267. /// </summary>
  268. /// <param name="trackerHitResult">The tracker data.</param>
  269. public void ShowTracker(TrackerHitResult trackerHitResult)
  270. {
  271. if (trackerHitResult == null)
  272. {
  273. HideTracker();
  274. return;
  275. }
  276. var trackerTemplate = DefaultTrackerTemplate;
  277. if (trackerHitResult.Series != null && !string.IsNullOrEmpty(trackerHitResult.Series.TrackerKey))
  278. {
  279. var match = TrackerDefinitions.FirstOrDefault(t => t.TrackerKey == trackerHitResult.Series.TrackerKey);
  280. if (match != null)
  281. {
  282. trackerTemplate = match.TrackerTemplate;
  283. }
  284. }
  285. if (trackerTemplate == null)
  286. {
  287. HideTracker();
  288. return;
  289. }
  290. var tracker = trackerTemplate.Build(new ContentControl());
  291. // ReSharper disable once RedundantNameQualifier
  292. if (!object.ReferenceEquals(tracker, currentTracker))
  293. {
  294. HideTracker();
  295. overlays.Children.Add(tracker.Result);
  296. currentTracker = tracker.Result;
  297. }
  298. if (currentTracker != null)
  299. {
  300. currentTracker.DataContext = trackerHitResult;
  301. }
  302. }
  303. /// <summary>
  304. /// Shows the zoom rectangle.
  305. /// </summary>
  306. /// <param name="r">The rectangle.</param>
  307. public void ShowZoomRectangle(OxyRect r)
  308. {
  309. zoomControl.Width = r.Width;
  310. zoomControl.Height = r.Height;
  311. Canvas.SetLeft(zoomControl, r.Left);
  312. Canvas.SetTop(zoomControl, r.Top);
  313. zoomControl.Template = ZoomRectangleTemplate;
  314. zoomControl.IsVisible = true;
  315. }
  316. /// <summary>
  317. /// Stores text on the clipboard.
  318. /// </summary>
  319. /// <param name="text">The text.</param>
  320. public async void SetClipboardText(string text)
  321. {
  322. if (TopLevel.GetTopLevel(this) is { Clipboard: { } clipboard })
  323. {
  324. await clipboard.SetTextAsync(text).ConfigureAwait(true);
  325. }
  326. }
  327. /// <summary>
  328. /// Provides the behavior for the Arrange pass of Silverlight layout. Classes can override this method to define their own Arrange pass behavior.
  329. /// </summary>
  330. /// <param name="finalSize">The final area within the parent that this object should use to arrange itself and its children.</param>
  331. /// <returns>The actual size that is used after the element is arranged in layout.</returns>
  332. protected override Size ArrangeOverride(Size finalSize)
  333. {
  334. var actualSize = base.ArrangeOverride(finalSize);
  335. if (actualSize.Width > 0 && actualSize.Height > 0)
  336. {
  337. if (Interlocked.CompareExchange(ref isPlotInvalidated, 0, 1) == 1)
  338. {
  339. UpdateVisuals();
  340. }
  341. }
  342. return actualSize;
  343. }
  344. /// <summary>
  345. /// Updates the model.
  346. /// </summary>
  347. /// <param name="updateData">The update Data.</param>
  348. protected void UpdateModel(bool updateData = true)
  349. {
  350. if (Width <= 0 || Height <= 0 || ActualModel == null)
  351. {
  352. isUpdateRequired = 0;
  353. return;
  354. }
  355. lock (this.ActualModel.SyncRoot)
  356. {
  357. var updateState = (Interlocked.Exchange(ref isUpdateRequired, 0));
  358. if (updateState > 0)
  359. {
  360. ((IPlotModel)ActualModel).Update(updateState == 2 || updateData);
  361. }
  362. }
  363. if (Interlocked.CompareExchange(ref isPlotInvalidated, 1, 0) == 0)
  364. {
  365. // Invalidate the arrange state for the element.
  366. // After the invalidation, the element will have its layout updated,
  367. // which will occur asynchronously unless subsequently forced by UpdateLayout.
  368. BeginInvoke(InvalidateArrange);
  369. }
  370. }
  371. /// <summary>
  372. /// Determines whether the plot is currently visible to the user.
  373. /// </summary>
  374. /// <returns><c>true</c> if the plot is currently visible to the user; otherwise, <c>false</c>.</returns>
  375. protected bool IsVisibleToUser()
  376. {
  377. return IsUserVisible(this);
  378. }
  379. /// <summary>
  380. /// Determines whether the specified element is currently visible to the user.
  381. /// </summary>
  382. /// <param name="element">The element.</param>
  383. /// <returns><c>true</c> if the specified element is currently visible to the user; otherwise, <c>false</c>.</returns>
  384. private static bool IsUserVisible(Control element)
  385. {
  386. return element.IsEffectivelyVisible;
  387. }
  388. /// <summary>
  389. /// Called when the size of the control is changed.
  390. /// </summary>
  391. /// <param name="sender">The sender.</param>
  392. /// <param name="size">The new size</param>
  393. private void OnSizeChanged(Rect size)
  394. {
  395. if (size.Height > 0 && size.Width > 0)
  396. {
  397. InvalidatePlot(false);
  398. }
  399. }
  400. /// <summary>
  401. /// Gets the relevant parent.
  402. /// </summary>
  403. /// <typeparam name="T">Type of the relevant parent</typeparam>
  404. /// <param name="obj">The object.</param>
  405. /// <returns>The relevant parent.</returns>
  406. private Control GetRelevantParent<T>(Visual obj)
  407. where T : Control
  408. {
  409. var container = obj.GetVisualParent();
  410. if (container is ContentPresenter contentPresenter)
  411. {
  412. container = GetRelevantParent<T>(contentPresenter);
  413. }
  414. if (container is Panel panel)
  415. {
  416. container = GetRelevantParent<ScrollViewer>(panel);
  417. }
  418. if (!(container is T) && (container != null))
  419. {
  420. container = GetRelevantParent<T>(container);
  421. }
  422. return (Control)container;
  423. }
  424. /// <summary>
  425. /// Updates the visuals.
  426. /// </summary>
  427. private void UpdateVisuals()
  428. {
  429. if (canvas == null || renderContext == null)
  430. {
  431. return;
  432. }
  433. if (!IsVisibleToUser())
  434. {
  435. return;
  436. }
  437. // Clear the canvas
  438. canvas.Children.Clear();
  439. if (ActualModel?.Background.IsVisible() == true)
  440. {
  441. canvas.Background = ActualModel.Background.ToBrush();
  442. }
  443. else
  444. {
  445. canvas.Background = null;
  446. }
  447. if (ActualModel != null)
  448. {
  449. lock (this.ActualModel.SyncRoot)
  450. {
  451. var updateState = (Interlocked.Exchange(ref isUpdateRequired, 0));
  452. if (updateState > 0)
  453. {
  454. ((IPlotModel)ActualModel).Update(updateState == 2);
  455. }
  456. if (DisconnectCanvasWhileUpdating)
  457. {
  458. // TODO: profile... not sure if this makes any difference
  459. var idx = panel.Children.IndexOf(canvas);
  460. if (idx != -1)
  461. {
  462. panel.Children.RemoveAt(idx);
  463. }
  464. ((IPlotModel)ActualModel).Render(renderContext, new OxyRect(0, 0, canvas.Bounds.Width, canvas.Bounds.Height));
  465. // reinsert the canvas again
  466. if (idx != -1)
  467. {
  468. panel.Children.Insert(idx, canvas);
  469. }
  470. }
  471. else
  472. {
  473. ((IPlotModel)ActualModel).Render(renderContext, new OxyRect(0, 0, canvas.Bounds.Width, canvas.Bounds.Height));
  474. }
  475. }
  476. }
  477. }
  478. /// <summary>
  479. /// Invokes the specified action on the dispatcher, if necessary.
  480. /// </summary>
  481. /// <param name="action">The action.</param>
  482. private static void BeginInvoke(Action action)
  483. {
  484. if (Dispatcher.UIThread.CheckAccess())
  485. {
  486. action?.Invoke();
  487. }
  488. else
  489. {
  490. Dispatcher.UIThread.InvokeAsync(action, DispatcherPriority.Loaded);
  491. }
  492. }
  493. }
  494. }