PlotViewBase.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="PlotViewBase.cs" company="OxyPlot">
  3. // Copyright (c) 2020 OxyPlot contributors
  4. // </copyright>
  5. // --------------------------------------------------------------------------------------------------------------------
  6. namespace OxyPlot.Wpf
  7. {
  8. using OxyPlot;
  9. using System;
  10. using System.Collections.ObjectModel;
  11. using System.Linq;
  12. using System.Windows;
  13. using System.Windows.Controls;
  14. using System.Windows.Controls.Primitives;
  15. using System.Windows.Input;
  16. using System.Windows.Media;
  17. using System.Windows.Threading;
  18. using System.Windows.Documents;
  19. using CursorType = OxyPlot.CursorType;
  20. /// <summary>
  21. /// Base class for WPF PlotView implementations.
  22. /// </summary>
  23. [TemplatePart(Name = PartGrid, Type = typeof(Grid))]
  24. public abstract partial class PlotViewBase : Control, IPlotView
  25. {
  26. /// <summary>
  27. /// The Grid PART constant.
  28. /// </summary>
  29. protected const string PartGrid = "PART_Grid";
  30. /// <summary>
  31. /// The grid.
  32. /// </summary>
  33. protected Grid grid;
  34. /// <summary>
  35. /// The plot presenter.
  36. /// </summary>
  37. protected FrameworkElement plotPresenter;
  38. /// <summary>
  39. /// The render context
  40. /// </summary>
  41. protected IRenderContext renderContext;
  42. /// <summary>
  43. /// The model lock.
  44. /// </summary>
  45. private readonly object modelLock = new object();
  46. /// <summary>
  47. /// The current tracker.
  48. /// </summary>
  49. private FrameworkElement currentTracker;
  50. /// <summary>
  51. /// The current tracker template.
  52. /// </summary>
  53. private ControlTemplate currentTrackerTemplate;
  54. /// <summary>
  55. /// The default plot controller.
  56. /// </summary>
  57. private IPlotController defaultController;
  58. /// <summary>
  59. /// Indicates whether the <see cref="PlotViewBase"/> was in the visual tree the last time <see cref="Render"/> was called.
  60. /// </summary>
  61. private bool isInVisualTree;
  62. /// <summary>
  63. /// The mouse down point.
  64. /// </summary>
  65. private ScreenPoint mouseDownPoint;
  66. /// <summary>
  67. /// The overlays.
  68. /// </summary>
  69. private Canvas overlays;
  70. /// <summary>
  71. /// The zoom control.
  72. /// </summary>
  73. private ContentControl zoomControl;
  74. /// <summary>
  75. /// Initializes static members of the <see cref="PlotViewBase" /> class.
  76. /// </summary>
  77. static PlotViewBase()
  78. {
  79. DefaultStyleKeyProperty.OverrideMetadata(typeof(PlotViewBase), new FrameworkPropertyMetadata(typeof(PlotViewBase)));
  80. PaddingProperty.OverrideMetadata(typeof(PlotViewBase), new FrameworkPropertyMetadata(new Thickness(8)));
  81. }
  82. /// <summary>
  83. /// Initializes a new instance of the <see cref="PlotViewBase" /> class.
  84. /// </summary>
  85. protected PlotViewBase()
  86. {
  87. this.TrackerDefinitions = new ObservableCollection<TrackerDefinition>();
  88. this.CommandBindings.Add(new CommandBinding(PlotCommands.ResetAxes, (s, e) => this.ResetAllAxes()));
  89. this.IsManipulationEnabled = true;
  90. this.LayoutUpdated += this.OnLayoutUpdated;
  91. }
  92. /// <summary>
  93. /// Gets the actual PlotView controller.
  94. /// </summary>
  95. /// <value>The actual PlotView controller.</value>
  96. public IPlotController ActualController => this.Controller ?? (this.defaultController ??= new PlotController());
  97. /// <inheritdoc/>
  98. IController IView.ActualController => this.ActualController;
  99. /// <summary>
  100. /// Gets the actual model.
  101. /// </summary>
  102. /// <value>The actual model.</value>
  103. public PlotModel ActualModel { get; private set; }
  104. /// <inheritdoc/>
  105. Model IView.ActualModel => this.ActualModel;
  106. /// <summary>
  107. /// Gets the coordinates of the client area of the view.
  108. /// </summary>
  109. public OxyRect ClientArea => new OxyRect(0, 0, this.ActualWidth, this.ActualHeight);
  110. /// <summary>
  111. /// Gets the tracker definitions.
  112. /// </summary>
  113. /// <value>The tracker definitions.</value>
  114. public ObservableCollection<TrackerDefinition> TrackerDefinitions { get; }
  115. /// <summary>
  116. /// Hides the tracker.
  117. /// </summary>
  118. public void HideTracker()
  119. {
  120. if (this.currentTracker != null)
  121. {
  122. this.overlays.Children.Remove(this.currentTracker);
  123. this.currentTracker = null;
  124. this.currentTrackerTemplate = null;
  125. }
  126. }
  127. /// <summary>
  128. /// Hides the zoom rectangle.
  129. /// </summary>
  130. public void HideZoomRectangle()
  131. {
  132. this.zoomControl.Visibility = Visibility.Collapsed;
  133. }
  134. /// <summary>
  135. /// Invalidate the PlotView (not blocking the UI thread)
  136. /// </summary>
  137. /// <param name="updateData">The update Data.</param>
  138. public void InvalidatePlot(bool updateData = true)
  139. {
  140. if (this.ActualModel == null)
  141. {
  142. return;
  143. }
  144. lock (this.ActualModel.SyncRoot)
  145. {
  146. ((IPlotModel)this.ActualModel).Update(updateData);
  147. }
  148. this.BeginInvoke(this.Render);
  149. }
  150. /// <inheritdoc/>
  151. public override void OnApplyTemplate()
  152. {
  153. base.OnApplyTemplate();
  154. this.grid = this.GetTemplateChild(PartGrid) as Grid;
  155. if (this.grid == null)
  156. {
  157. return;
  158. }
  159. this.plotPresenter = this.CreatePlotPresenter();
  160. this.grid.Children.Add(this.plotPresenter);
  161. this.plotPresenter.UpdateLayout();
  162. this.renderContext = this.CreateRenderContext();
  163. this.overlays = new Canvas();
  164. this.grid.Children.Add(this.overlays);
  165. this.zoomControl = new ContentControl();
  166. this.zoomControl.Focusable = false;
  167. this.overlays.Children.Add(this.zoomControl);
  168. // add additional grid on top of everthing else to fix issue of mouse events getting lost
  169. // it must be added last so it covers all other controls
  170. var mouseGrid = new Grid
  171. {
  172. Background = Brushes.Transparent // background must be set for hit test to work
  173. };
  174. this.grid.Children.Add(mouseGrid);
  175. }
  176. /// <summary>
  177. /// Pans all axes.
  178. /// </summary>
  179. /// <param name="delta">The delta.</param>
  180. public void PanAllAxes(Vector delta)
  181. {
  182. if (this.ActualModel != null)
  183. {
  184. this.ActualModel.PanAllAxes(delta.X, delta.Y);
  185. }
  186. this.InvalidatePlot(false);
  187. }
  188. /// <summary>
  189. /// Resets all axes.
  190. /// </summary>
  191. public void ResetAllAxes()
  192. {
  193. if (this.ActualModel != null)
  194. {
  195. this.ActualModel.ResetAllAxes();
  196. }
  197. this.InvalidatePlot(false);
  198. }
  199. /// <summary>
  200. /// Stores text on the clipboard.
  201. /// </summary>
  202. /// <param name="text">The text.</param>
  203. public void SetClipboardText(string text)
  204. {
  205. Clipboard.SetText(text);
  206. }
  207. /// <summary>
  208. /// Sets the cursor type.
  209. /// </summary>
  210. /// <param name="cursorType">The cursor type.</param>
  211. public void SetCursorType(CursorType cursorType)
  212. {
  213. this.Cursor = cursorType switch
  214. {
  215. CursorType.Pan => this.PanCursor,
  216. CursorType.ZoomRectangle => this.ZoomRectangleCursor,
  217. CursorType.ZoomHorizontal => this.ZoomHorizontalCursor,
  218. CursorType.ZoomVertical => this.ZoomVerticalCursor,
  219. _ => Cursors.Arrow,
  220. };
  221. }
  222. /// <summary>
  223. /// Shows the tracker.
  224. /// </summary>
  225. /// <param name="trackerHitResult">The tracker data.</param>
  226. public void ShowTracker(TrackerHitResult trackerHitResult)
  227. {
  228. if (trackerHitResult == null)
  229. {
  230. this.HideTracker();
  231. return;
  232. }
  233. var trackerTemplate = this.DefaultTrackerTemplate;
  234. if (trackerHitResult.Series != null && !string.IsNullOrEmpty(trackerHitResult.Series.TrackerKey))
  235. {
  236. var match = this.TrackerDefinitions.FirstOrDefault(t => t.TrackerKey == trackerHitResult.Series.TrackerKey);
  237. if (match != null)
  238. {
  239. trackerTemplate = match.TrackerTemplate;
  240. }
  241. }
  242. if (trackerTemplate == null)
  243. {
  244. this.HideTracker();
  245. return;
  246. }
  247. if (!ReferenceEquals(trackerTemplate, this.currentTrackerTemplate))
  248. {
  249. this.HideTracker();
  250. var tracker = new ContentControl { Template = trackerTemplate };
  251. this.overlays.Children.Add(tracker);
  252. this.currentTracker = tracker;
  253. this.currentTrackerTemplate = trackerTemplate;
  254. }
  255. if (this.currentTracker != null)
  256. {
  257. this.currentTracker.DataContext = trackerHitResult;
  258. }
  259. }
  260. /// <summary>
  261. /// Shows the zoom rectangle.
  262. /// </summary>
  263. /// <param name="r">The rectangle.</param>
  264. public void ShowZoomRectangle(OxyRect r)
  265. {
  266. this.zoomControl.Width = r.Width;
  267. this.zoomControl.Height = r.Height;
  268. Canvas.SetLeft(this.zoomControl, r.Left);
  269. Canvas.SetTop(this.zoomControl, r.Top);
  270. this.zoomControl.Template = this.ZoomRectangleTemplate;
  271. this.zoomControl.Visibility = Visibility.Visible;
  272. }
  273. /// <summary>
  274. /// Zooms all axes.
  275. /// </summary>
  276. /// <param name="factor">The zoom factor.</param>
  277. public void ZoomAllAxes(double factor)
  278. {
  279. if (this.ActualModel != null)
  280. {
  281. this.ActualModel.ZoomAllAxes(factor);
  282. }
  283. this.InvalidatePlot(false);
  284. }
  285. /// <summary>
  286. /// Clears the background of the plot presenter.
  287. /// </summary>
  288. protected abstract void ClearBackground();
  289. /// <summary>
  290. /// Creates the plot presenter.
  291. /// </summary>
  292. /// <returns>The plot presenter.</returns>
  293. protected abstract FrameworkElement CreatePlotPresenter();
  294. /// <summary>
  295. /// Creates the render context.
  296. /// </summary>
  297. /// <returns>The render context.</returns>
  298. protected abstract IRenderContext CreateRenderContext();
  299. /// <summary>
  300. /// Called when the model is changed.
  301. /// </summary>
  302. protected void OnModelChanged()
  303. {
  304. lock (this.modelLock)
  305. {
  306. if (this.ActualModel != null)
  307. {
  308. ((IPlotModel)this.ActualModel).AttachPlotView(null);
  309. this.ActualModel = null;
  310. }
  311. if (this.Model != null)
  312. {
  313. ((IPlotModel)this.Model).AttachPlotView(this);
  314. this.ActualModel = this.Model;
  315. }
  316. }
  317. this.InvalidatePlot();
  318. }
  319. /// <summary>
  320. /// Renders the plot model to the plot presenter.
  321. /// </summary>
  322. protected void Render()
  323. {
  324. if (this.plotPresenter == null || this.renderContext == null)
  325. {
  326. return;
  327. }
  328. this.isInVisualTree = this.IsInVisualTree();
  329. this.RenderOverride();
  330. }
  331. /// <summary>
  332. /// Renders the plot model to the plot presenter.
  333. /// </summary>
  334. protected virtual void RenderOverride()
  335. {
  336. var dpiScale = this.UpdateDpi();
  337. this.ClearBackground();
  338. if (this.ActualModel != null)
  339. {
  340. // round width and height to full device pixels
  341. var width = ((int)(this.plotPresenter.ActualWidth * dpiScale)) / dpiScale;
  342. var height = ((int)(this.plotPresenter.ActualHeight * dpiScale)) / dpiScale;
  343. lock (this.ActualModel.SyncRoot)
  344. {
  345. ((IPlotModel)this.ActualModel).Render(this.renderContext, new OxyRect(0, 0, width, height));
  346. }
  347. }
  348. }
  349. /// <summary>
  350. /// Updates the DPI scale of the render context.
  351. /// </summary>
  352. /// <returns>The DPI scale.</returns>
  353. protected virtual double UpdateDpi()
  354. {
  355. var transformMatrix = PresentationSource.FromVisual(this)?.CompositionTarget?.TransformToDevice;
  356. var scale = transformMatrix == null ? 1 : (transformMatrix.Value.M11 + transformMatrix.Value.M22) / 2;
  357. return scale;
  358. }
  359. /// <summary>
  360. /// Called when the model is changed.
  361. /// </summary>
  362. /// <param name="d">The sender.</param>
  363. /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs" /> instance containing the event data.</param>
  364. private static void ModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  365. {
  366. ((PlotViewBase)d).OnModelChanged();
  367. }
  368. /// <summary>
  369. /// Invokes the specified action on the dispatcher, if necessary.
  370. /// </summary>
  371. /// <param name="action">The action.</param>
  372. private void BeginInvoke(Action action)
  373. {
  374. if (!this.Dispatcher.CheckAccess())
  375. {
  376. this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, action);
  377. }
  378. else
  379. {
  380. action();
  381. }
  382. }
  383. /// <summary>
  384. /// Gets a value indicating whether the <see cref="PlotViewBase"/> is connected to the visual tree.
  385. /// </summary>
  386. /// <returns><c>true</c> if the PlotViewBase is connected to the visual tree; <c>false</c> otherwise.</returns>
  387. private bool IsInVisualTree()
  388. {
  389. DependencyObject dpObject = this;
  390. while ((dpObject = VisualTreeHelper.GetParent(dpObject)) != null)
  391. {
  392. if (dpObject is Window)
  393. {
  394. return true;
  395. }
  396. //Check if the parent is an AdornerDecorator like in an ElementHost
  397. if (dpObject is AdornerDecorator)
  398. {
  399. return true;
  400. }
  401. //Check if the logical parent is a popup. If so, we found the popuproot
  402. var logicalRoot = LogicalTreeHelper.GetParent(dpObject);
  403. if (logicalRoot is Popup)
  404. {
  405. return true;
  406. }
  407. }
  408. return false;
  409. }
  410. /// <summary>
  411. /// This event fires every time Layout updates the layout of the trees associated with current Dispatcher.
  412. /// </summary>
  413. /// <param name="sender">The sender.</param>
  414. /// <param name="e">The event args.</param>
  415. private void OnLayoutUpdated(object sender, EventArgs e)
  416. {
  417. // if we were not in the visual tree the last time we tried to render but are now, we have to render
  418. if (!this.isInVisualTree && this.IsInVisualTree())
  419. {
  420. this.Render();
  421. }
  422. }
  423. }
  424. }