ControlTests.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Reactive.Disposables;
  6. using System.Threading.Tasks;
  7. using Avalonia.Collections;
  8. using Avalonia.Controls;
  9. using Avalonia.Controls.Presenters;
  10. using Avalonia.Controls.Primitives;
  11. using Avalonia.Controls.Shapes;
  12. using Avalonia.Controls.Templates;
  13. using Avalonia.Data;
  14. using Avalonia.Diagnostics;
  15. using Avalonia.Input;
  16. using Avalonia.Media;
  17. using Avalonia.Platform;
  18. using Avalonia.Rendering;
  19. using Avalonia.Rendering.Composition;
  20. using Avalonia.Styling;
  21. using Avalonia.Threading;
  22. using Avalonia.UnitTests;
  23. using Avalonia.VisualTree;
  24. using JetBrains.dotMemoryUnit;
  25. using Moq;
  26. using Xunit;
  27. using Xunit.Abstractions;
  28. namespace Avalonia.LeakTests
  29. {
  30. [DotMemoryUnit(FailIfRunWithoutSupport = false)]
  31. public class ControlTests
  32. {
  33. // Need to have the collection as field, so GC will not free it
  34. private readonly ObservableCollection<string> _observableCollection = new();
  35. public ControlTests(ITestOutputHelper atr)
  36. {
  37. DotMemoryUnitTestOutput.SetOutputMethod(atr.WriteLine);
  38. }
  39. [Fact]
  40. public void DataGrid_Is_Freed()
  41. {
  42. using (Start())
  43. {
  44. // When attached to INotifyCollectionChanged, DataGrid will subscribe to it's events, potentially causing leak
  45. Func<Window> run = () =>
  46. {
  47. var window = new Window
  48. {
  49. Content = new DataGrid
  50. {
  51. ItemsSource = _observableCollection
  52. }
  53. };
  54. window.Show();
  55. // Do a layout and make sure that DataGrid gets added to visual tree.
  56. window.LayoutManager.ExecuteInitialLayoutPass();
  57. Assert.IsType<DataGrid>(window.Presenter.Child);
  58. // Clear the content and ensure the DataGrid is removed.
  59. window.Content = null;
  60. window.LayoutManager.ExecuteLayoutPass();
  61. Assert.Null(window.Presenter.Child);
  62. return window;
  63. };
  64. var result = run();
  65. // Process all Loaded events to free control reference(s)
  66. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  67. dotMemory.Check(memory =>
  68. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<DataGrid>()).ObjectsCount));
  69. }
  70. }
  71. [Fact]
  72. public void Canvas_Is_Freed()
  73. {
  74. using (Start())
  75. {
  76. Func<Window> run = () =>
  77. {
  78. var window = new Window
  79. {
  80. Content = new Canvas()
  81. };
  82. window.Show();
  83. // Do a layout and make sure that Canvas gets added to visual tree.
  84. window.LayoutManager.ExecuteInitialLayoutPass();
  85. Assert.IsType<Canvas>(window.Presenter.Child);
  86. // Clear the content and ensure the Canvas is removed.
  87. window.Content = null;
  88. window.LayoutManager.ExecuteLayoutPass();
  89. Assert.Null(window.Presenter.Child);
  90. return window;
  91. };
  92. var result = run();
  93. // Process all Loaded events to free control reference(s)
  94. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  95. dotMemory.Check(memory =>
  96. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount));
  97. }
  98. }
  99. [Fact]
  100. public void Named_Canvas_Is_Freed()
  101. {
  102. using (Start())
  103. {
  104. Func<Window> run = () =>
  105. {
  106. var scope = new NameScope();
  107. var window = new Window
  108. {
  109. Content = new Canvas
  110. {
  111. Name = "foo"
  112. }.RegisterInNameScope(scope)
  113. };
  114. NameScope.SetNameScope(window, scope);
  115. window.Show();
  116. // Do a layout and make sure that Canvas gets added to visual tree.
  117. window.LayoutManager.ExecuteInitialLayoutPass();
  118. Assert.IsType<Canvas>(window.Find<Canvas>("foo"));
  119. Assert.IsType<Canvas>(window.Presenter.Child);
  120. // Clear the content and ensure the Canvas is removed.
  121. window.Content = null;
  122. NameScope.SetNameScope(window, null);
  123. window.LayoutManager.ExecuteLayoutPass();
  124. Assert.Null(window.Presenter.Child);
  125. return window;
  126. };
  127. var result = run();
  128. // Process all Loaded events to free control reference(s)
  129. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  130. dotMemory.Check(memory =>
  131. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount));
  132. }
  133. }
  134. [Fact]
  135. public void ScrollViewer_With_Content_Is_Freed()
  136. {
  137. using (Start())
  138. {
  139. Func<Window> run = () =>
  140. {
  141. var window = new Window
  142. {
  143. Content = new ScrollViewer
  144. {
  145. Content = new Canvas()
  146. }
  147. };
  148. window.Show();
  149. // Do a layout and make sure that ScrollViewer gets added to visual tree and its
  150. // template applied.
  151. window.LayoutManager.ExecuteInitialLayoutPass();
  152. Assert.IsType<ScrollViewer>(window.Presenter.Child);
  153. Assert.IsType<Canvas>(((ScrollViewer)window.Presenter.Child).Presenter.Child);
  154. // Clear the content and ensure the ScrollViewer is removed.
  155. window.Content = null;
  156. window.LayoutManager.ExecuteLayoutPass();
  157. Assert.Null(window.Presenter.Child);
  158. return window;
  159. };
  160. var result = run();
  161. // Process all Loaded events to free control reference(s)
  162. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  163. dotMemory.Check(memory =>
  164. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount));
  165. dotMemory.Check(memory =>
  166. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount));
  167. }
  168. }
  169. [Fact]
  170. public void TextBox_Is_Freed()
  171. {
  172. using (Start())
  173. {
  174. Func<Window> run = () =>
  175. {
  176. var window = new Window
  177. {
  178. Content = new TextBox()
  179. };
  180. window.Show();
  181. // Do a layout and make sure that TextBox gets added to visual tree and its
  182. // template applied.
  183. window.LayoutManager.ExecuteInitialLayoutPass();
  184. Assert.IsType<TextBox>(window.Presenter.Child);
  185. Assert.NotEmpty(window.Presenter.Child.GetVisualChildren());
  186. // Clear the content and ensure the TextBox is removed.
  187. window.Content = null;
  188. window.LayoutManager.ExecuteLayoutPass();
  189. Assert.Null(window.Presenter.Child);
  190. return window;
  191. };
  192. var result = run();
  193. // Process all Loaded events to free control reference(s)
  194. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  195. dotMemory.Check(memory =>
  196. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount));
  197. }
  198. }
  199. [Fact]
  200. public void TextBox_With_Xaml_Binding_Is_Freed()
  201. {
  202. using (Start())
  203. {
  204. Func<Window> run = () =>
  205. {
  206. var window = new Window
  207. {
  208. DataContext = new Node { Name = "foo" },
  209. Content = new TextBox()
  210. };
  211. var binding = new Avalonia.Data.Binding
  212. {
  213. Path = "Name"
  214. };
  215. var textBox = (TextBox)window.Content;
  216. textBox.Bind(TextBox.TextProperty, binding);
  217. window.Show();
  218. // Do a layout and make sure that TextBox gets added to visual tree and its
  219. // Text property set.
  220. window.LayoutManager.ExecuteInitialLayoutPass();
  221. Assert.IsType<TextBox>(window.Presenter.Child);
  222. Assert.Equal("foo", ((TextBox)window.Presenter.Child).Text);
  223. // Clear the content and DataContext and ensure the TextBox is removed.
  224. window.Content = null;
  225. window.DataContext = null;
  226. window.LayoutManager.ExecuteLayoutPass();
  227. Assert.Null(window.Presenter.Child);
  228. return window;
  229. };
  230. var result = run();
  231. // Process all Loaded events to free control reference(s)
  232. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  233. dotMemory.Check(memory =>
  234. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount));
  235. dotMemory.Check(memory =>
  236. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Node>()).ObjectsCount));
  237. }
  238. }
  239. [Fact]
  240. public void TextBox_Class_Listeners_Are_Freed()
  241. {
  242. using (Start())
  243. {
  244. TextBox textBox;
  245. var window = new Window
  246. {
  247. Content = textBox = new TextBox()
  248. };
  249. window.Show();
  250. // Do a layout and make sure that TextBox gets added to visual tree and its
  251. // template applied.
  252. window.LayoutManager.ExecuteInitialLayoutPass();
  253. Assert.Same(textBox, window.Presenter.Child);
  254. // Get the border from the TextBox template.
  255. var border = textBox.GetTemplateChildren().FirstOrDefault(x => x.Name == "border");
  256. // The TextBox should have subscriptions to its Classes collection from the
  257. // default theme.
  258. Assert.NotEqual(0, textBox.Classes.ListenerCount);
  259. // Clear the content and ensure the TextBox is removed.
  260. window.Content = null;
  261. window.LayoutManager.ExecuteLayoutPass();
  262. Assert.Null(window.Presenter.Child);
  263. // Check that the TextBox has no subscriptions to its Classes collection.
  264. Assert.Null(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers());
  265. }
  266. }
  267. [Fact]
  268. public void TreeView_Is_Freed()
  269. {
  270. using (Start())
  271. {
  272. Func<Window> run = () =>
  273. {
  274. var nodes = new[]
  275. {
  276. new Node
  277. {
  278. Children = new[] { new Node() },
  279. }
  280. };
  281. TreeView target;
  282. var window = new Window
  283. {
  284. Content = target = new TreeView
  285. {
  286. DataTemplates =
  287. {
  288. new FuncTreeDataTemplate<Node>(
  289. (x, _) => new TextBlock { Text = x.Name },
  290. x => x.Children)
  291. },
  292. ItemsSource = nodes
  293. }
  294. };
  295. window.Show();
  296. // Do a layout and make sure that TreeViewItems get realized.
  297. window.LayoutManager.ExecuteInitialLayoutPass();
  298. Assert.Single(target.GetRealizedContainers());
  299. // Clear the content and ensure the TreeView is removed.
  300. window.Content = null;
  301. window.LayoutManager.ExecuteLayoutPass();
  302. Assert.Null(window.Presenter.Child);
  303. return window;
  304. };
  305. var result = run();
  306. // Process all Loaded events to free control reference(s)
  307. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  308. dotMemory.Check(memory =>
  309. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TreeView>()).ObjectsCount));
  310. }
  311. }
  312. [Fact]
  313. public void Slider_Is_Freed()
  314. {
  315. using (Start())
  316. {
  317. Func<Window> run = () =>
  318. {
  319. var window = new Window
  320. {
  321. Content = new Slider()
  322. };
  323. window.Show();
  324. // Do a layout and make sure that Slider gets added to visual tree.
  325. window.LayoutManager.ExecuteInitialLayoutPass();
  326. Assert.IsType<Slider>(window.Presenter.Child);
  327. // Clear the content and ensure the Slider is removed.
  328. window.Content = null;
  329. window.LayoutManager.ExecuteLayoutPass();
  330. Assert.Null(window.Presenter.Child);
  331. return window;
  332. };
  333. var result = run();
  334. // Process all Loaded events to free control reference(s)
  335. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  336. dotMemory.Check(memory =>
  337. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Slider>()).ObjectsCount));
  338. }
  339. }
  340. [Fact]
  341. public void TabItem_Is_Freed()
  342. {
  343. using (Start())
  344. {
  345. Func<Window> run = () =>
  346. {
  347. var window = new Window
  348. {
  349. Content = new TabControl
  350. {
  351. ItemsSource = new[] { new TabItem() }
  352. }
  353. };
  354. window.Show();
  355. // Do a layout and make sure that TabControl and TabItem gets added to visual tree.
  356. window.LayoutManager.ExecuteInitialLayoutPass();
  357. var tabControl = Assert.IsType<TabControl>(window.Presenter.Child);
  358. Assert.IsType<TabItem>(tabControl.Presenter.Panel.Children[0]);
  359. // Clear the items and ensure the TabItem is removed.
  360. tabControl.ItemsSource = null;
  361. window.LayoutManager.ExecuteLayoutPass();
  362. Assert.Empty(tabControl.Presenter.Panel.Children);
  363. return window;
  364. };
  365. var result = run();
  366. // Process all Loaded events to free control reference(s)
  367. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  368. dotMemory.Check(memory =>
  369. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TabItem>()).ObjectsCount));
  370. }
  371. }
  372. [Fact]
  373. public void RendererIsDisposed()
  374. {
  375. using (Start())
  376. {
  377. var impl = new Mock<IWindowImpl>();
  378. impl.Setup(r => r.TryGetFeature(It.IsAny<Type>())).Returns(null);
  379. impl.SetupGet(x => x.RenderScaling).Returns(1);
  380. impl.SetupProperty(x => x.Closed);
  381. impl.Setup(x => x.Compositor).Returns(RendererMocks.CreateDummyCompositor());
  382. impl.Setup(x => x.Dispose()).Callback(() => impl.Object.Closed());
  383. AvaloniaLocator.CurrentMutable.Bind<IWindowingPlatform>()
  384. .ToConstant(new MockWindowingPlatform(() => impl.Object));
  385. var window = new Window()
  386. {
  387. Content = new Button()
  388. };
  389. window.Show();
  390. window.Close();
  391. Assert.True(((CompositingRenderer)window.Renderer).IsDisposed);
  392. }
  393. }
  394. [Fact]
  395. public void Control_With_Style_RenderTransform_Is_Freed()
  396. {
  397. // # Issue #3545
  398. using (Start())
  399. {
  400. Func<Window> run = () =>
  401. {
  402. var window = new Window
  403. {
  404. Styles =
  405. {
  406. new Style(x => x.OfType<Canvas>())
  407. {
  408. Setters =
  409. {
  410. new Setter
  411. {
  412. Property = Visual.RenderTransformProperty,
  413. Value = new RotateTransform(45),
  414. }
  415. }
  416. }
  417. },
  418. Content = new Canvas()
  419. };
  420. window.Show();
  421. // Do a layout and make sure that Canvas gets added to visual tree with
  422. // its render transform.
  423. window.LayoutManager.ExecuteInitialLayoutPass();
  424. var canvas = Assert.IsType<Canvas>(window.Presenter.Child);
  425. Assert.IsType<RotateTransform>(canvas.RenderTransform);
  426. // Clear the content and ensure the Canvas is removed.
  427. window.Content = null;
  428. window.LayoutManager.ExecuteLayoutPass();
  429. Assert.Null(window.Presenter.Child);
  430. return window;
  431. };
  432. var result = run();
  433. // Process all Loaded events to free control reference(s)
  434. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  435. dotMemory.Check(memory =>
  436. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount));
  437. }
  438. }
  439. [Fact]
  440. public void Attached_ContextMenu_Is_Freed()
  441. {
  442. using (Start())
  443. {
  444. void AttachShowAndDetachContextMenu(Control control)
  445. {
  446. var contextMenu = new ContextMenu
  447. {
  448. Items =
  449. {
  450. new MenuItem { Header = "Foo" },
  451. new MenuItem { Header = "Foo" },
  452. }
  453. };
  454. control.ContextMenu = contextMenu;
  455. contextMenu.Open(control);
  456. contextMenu.Close();
  457. control.ContextMenu = null;
  458. }
  459. var window = new Window { Focusable = true };
  460. window.Show();
  461. Assert.Same(window, window.FocusManager.GetFocusedElement());
  462. // Context menu in resources means the baseline may not be 0.
  463. var initialMenuCount = 0;
  464. var initialMenuItemCount = 0;
  465. dotMemory.Check(memory =>
  466. {
  467. initialMenuCount = memory.GetObjects(where => where.Type.Is<ContextMenu>()).ObjectsCount;
  468. initialMenuItemCount = memory.GetObjects(where => where.Type.Is<MenuItem>()).ObjectsCount;
  469. });
  470. AttachShowAndDetachContextMenu(window);
  471. // Process all Loaded events to free control reference(s)
  472. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  473. Mock.Get(window.PlatformImpl).Invocations.Clear();
  474. dotMemory.Check(memory =>
  475. Assert.Equal(initialMenuCount, memory.GetObjects(where => where.Type.Is<ContextMenu>()).ObjectsCount));
  476. dotMemory.Check(memory =>
  477. Assert.Equal(initialMenuItemCount, memory.GetObjects(where => where.Type.Is<MenuItem>()).ObjectsCount));
  478. }
  479. }
  480. [Fact]
  481. public void Attached_Control_From_ContextMenu_Is_Freed()
  482. {
  483. using (Start())
  484. {
  485. var contextMenu = new ContextMenu();
  486. Func<Window> run = () =>
  487. {
  488. var window = new Window
  489. {
  490. Content = new TextBlock
  491. {
  492. ContextMenu = contextMenu
  493. }
  494. };
  495. window.Show();
  496. // Do a layout and make sure that TextBlock gets added to visual tree.
  497. window.LayoutManager.ExecuteInitialLayoutPass();
  498. Assert.IsType<TextBlock>(window.Presenter.Child);
  499. // Clear the content and ensure the TextBlock is removed.
  500. window.Content = null;
  501. window.LayoutManager.ExecuteLayoutPass();
  502. Assert.Null(window.Presenter.Child);
  503. return window;
  504. };
  505. var result = run();
  506. // Process all Loaded events to free control reference(s)
  507. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  508. dotMemory.Check(memory =>
  509. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBlock>()).ObjectsCount));
  510. }
  511. }
  512. [Fact]
  513. public void Standalone_ContextMenu_Is_Freed()
  514. {
  515. using (Start())
  516. {
  517. void BuildAndShowContextMenu(Control control)
  518. {
  519. var contextMenu = new ContextMenu
  520. {
  521. Items =
  522. {
  523. new MenuItem { Header = "Foo" },
  524. new MenuItem { Header = "Foo" },
  525. }
  526. };
  527. contextMenu.Open(control);
  528. contextMenu.Close();
  529. }
  530. var window = new Window { Focusable = true };
  531. window.Show();
  532. Assert.Same(window, window.FocusManager.GetFocusedElement());
  533. // Context menu in resources means the baseline may not be 0.
  534. var initialMenuCount = 0;
  535. var initialMenuItemCount = 0;
  536. dotMemory.Check(memory =>
  537. {
  538. initialMenuCount = memory.GetObjects(where => where.Type.Is<ContextMenu>()).ObjectsCount;
  539. initialMenuItemCount = memory.GetObjects(where => where.Type.Is<MenuItem>()).ObjectsCount;
  540. });
  541. BuildAndShowContextMenu(window);
  542. BuildAndShowContextMenu(window);
  543. // Process all Loaded events to free control reference(s)
  544. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  545. Mock.Get(window.PlatformImpl).Invocations.Clear();
  546. dotMemory.Check(memory =>
  547. Assert.Equal(initialMenuCount, memory.GetObjects(where => where.Type.Is<ContextMenu>()).ObjectsCount));
  548. dotMemory.Check(memory =>
  549. Assert.Equal(initialMenuItemCount, memory.GetObjects(where => where.Type.Is<MenuItem>()).ObjectsCount));
  550. }
  551. }
  552. [Fact]
  553. public void Path_Is_Freed()
  554. {
  555. using (Start())
  556. {
  557. var geometry = new EllipseGeometry { Rect = new Rect(0, 0, 10, 10) };
  558. Func<Window> run = () =>
  559. {
  560. var window = new Window
  561. {
  562. Content = new Path
  563. {
  564. Data = geometry
  565. }
  566. };
  567. window.Show();
  568. window.LayoutManager.ExecuteInitialLayoutPass();
  569. Assert.IsType<Path>(window.Presenter.Child);
  570. window.Content = null;
  571. window.LayoutManager.ExecuteLayoutPass();
  572. Assert.Null(window.Presenter.Child);
  573. return window;
  574. };
  575. var result = run();
  576. // Process all Loaded events to free control reference(s)
  577. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  578. dotMemory.Check(memory =>
  579. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Path>()).ObjectsCount));
  580. // We are keeping geometry alive to simulate a resource that outlives the control.
  581. GC.KeepAlive(geometry);
  582. }
  583. }
  584. [Fact]
  585. public void ItemsRepeater_Is_Freed()
  586. {
  587. using (Start())
  588. {
  589. Func<Window> run = () =>
  590. {
  591. var window = new Window
  592. {
  593. Content = new ItemsRepeater(),
  594. };
  595. window.Show();
  596. window.LayoutManager.ExecuteInitialLayoutPass();
  597. Assert.IsType<ItemsRepeater>(window.Presenter.Child);
  598. window.Content = null;
  599. window.LayoutManager.ExecuteLayoutPass();
  600. Assert.Null(window.Presenter.Child);
  601. return window;
  602. };
  603. var result = run();
  604. // Process all Loaded events to free control reference(s)
  605. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  606. dotMemory.Check(memory =>
  607. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<ItemsRepeater>()).ObjectsCount));
  608. }
  609. }
  610. [Fact]
  611. public void ElementName_Binding_In_DataTemplate_Is_Freed()
  612. {
  613. using (Start())
  614. {
  615. // Height of ListBoxItem content + padding.
  616. const double ListBoxItemHeight = 12;
  617. const double TextBoxHeight = 25;
  618. var items = new ObservableCollection<int>(Enumerable.Range(0, 10));
  619. NameScope ns;
  620. TextBox tb;
  621. ListBox lb;
  622. var window = new Window
  623. {
  624. [NameScope.NameScopeProperty] = ns = new NameScope(),
  625. Width = 100,
  626. Height = (items.Count * ListBoxItemHeight) + TextBoxHeight,
  627. Content = new DockPanel
  628. {
  629. Children =
  630. {
  631. (tb = new TextBox
  632. {
  633. Name = "tb",
  634. Text = "foo",
  635. Height = TextBoxHeight,
  636. [DockPanel.DockProperty] = Dock.Top,
  637. }),
  638. (lb = new ListBox
  639. {
  640. ItemsSource = items,
  641. ItemTemplate = new FuncDataTemplate<int>((_, _) =>
  642. new Canvas
  643. {
  644. Width = 10,
  645. Height = 10,
  646. [!Control.TagProperty] = new Binding
  647. {
  648. ElementName = "tb",
  649. Path = "Text",
  650. NameScope = new WeakReference<INameScope>(ns),
  651. }
  652. }),
  653. Padding = new Thickness(0),
  654. }),
  655. }
  656. }
  657. };
  658. tb.RegisterInNameScope(ns);
  659. window.Show();
  660. window.LayoutManager.ExecuteInitialLayoutPass();
  661. void AssertInitialItemState()
  662. {
  663. var item0 = (ListBoxItem)lb.GetRealizedContainers().First();
  664. var canvas0 = (Canvas)item0.Presenter.Child;
  665. Assert.Equal("foo", canvas0.Tag);
  666. }
  667. Assert.Equal(10, lb.GetRealizedContainers().Count());
  668. AssertInitialItemState();
  669. items.Clear();
  670. window.LayoutManager.ExecuteLayoutPass();
  671. Assert.Empty(lb.GetRealizedContainers());
  672. // Process all Loaded events to free control reference(s)
  673. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  674. dotMemory.Check(memory =>
  675. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount));
  676. }
  677. }
  678. [Fact]
  679. public void HotKeyManager_Should_Release_Reference_When_Control_Detached()
  680. {
  681. using (Start())
  682. {
  683. Func<Window> run = () =>
  684. {
  685. var gesture1 = new KeyGesture(Key.A, KeyModifiers.Control);
  686. var tl = new Window
  687. {
  688. Content = new ItemsRepeater(),
  689. };
  690. tl.Show();
  691. var button = new Button();
  692. tl.Content = button;
  693. tl.Template = CreateWindowTemplate();
  694. tl.ApplyTemplate();
  695. tl.Presenter.ApplyTemplate();
  696. HotKeyManager.SetHotKey(button, gesture1);
  697. // Detach the button from the logical tree, so there is no reference to it
  698. tl.Content = null;
  699. tl.ApplyTemplate();
  700. return tl;
  701. };
  702. var result = run();
  703. // Process all Loaded events to free control reference(s)
  704. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  705. dotMemory.Check(memory =>
  706. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Button>()).ObjectsCount));
  707. }
  708. }
  709. [Fact]
  710. public void HotKeyManager_Should_Release_Reference_When_Control_In_Item_Template_Detached()
  711. {
  712. using (Start())
  713. {
  714. Func<Window> run = () =>
  715. {
  716. var gesture1 = new KeyGesture(Key.A, KeyModifiers.Control);
  717. var tl = new Window { SizeToContent = SizeToContent.WidthAndHeight, IsVisible = true };
  718. var lm = tl.LayoutManager;
  719. tl.Show();
  720. var keyGestures = new AvaloniaList<KeyGesture> { gesture1 };
  721. var listBox = new ListBox
  722. {
  723. Width = 100,
  724. Height = 100,
  725. // Create a button with binding to the KeyGesture in the template and add it to references list
  726. ItemTemplate = new FuncDataTemplate(typeof(KeyGesture), (o, scope) =>
  727. {
  728. var keyGesture = o as KeyGesture;
  729. return new Button
  730. {
  731. DataContext = keyGesture,
  732. [!Button.HotKeyProperty] = new Binding("")
  733. };
  734. })
  735. };
  736. // Add the listbox and render it
  737. tl.Content = listBox;
  738. lm.ExecuteInitialLayoutPass();
  739. listBox.ItemsSource = keyGestures;
  740. lm.ExecuteLayoutPass();
  741. // Let the button detach when clearing the source items
  742. keyGestures.Clear();
  743. lm.ExecuteLayoutPass();
  744. // Add it again to double check,and render
  745. keyGestures.Add(gesture1);
  746. lm.ExecuteLayoutPass();
  747. keyGestures.Clear();
  748. lm.ExecuteLayoutPass();
  749. return tl;
  750. };
  751. var result = run();
  752. // Process all Loaded events to free control reference(s)
  753. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  754. dotMemory.Check(memory =>
  755. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Button>()).ObjectsCount));
  756. }
  757. }
  758. [Fact]
  759. public void ToolTip_Is_Freed()
  760. {
  761. using (Start())
  762. {
  763. Func<Window> run = () =>
  764. {
  765. var window = new Window();
  766. var source = new Button
  767. {
  768. Template = new FuncControlTemplate<Button>((parent, _) =>
  769. new Decorator
  770. {
  771. [ToolTip.TipProperty] = new TextBlock
  772. {
  773. [~TextBlock.TextProperty] = new TemplateBinding(ContentControl.ContentProperty)
  774. }
  775. }),
  776. };
  777. window.Content = source;
  778. window.Show();
  779. var templateChild = (Decorator)source.GetVisualChildren().Single();
  780. ToolTip.SetIsOpen(templateChild, true);
  781. ToolTip.SetIsOpen(templateChild, false);
  782. // Detach the button from the logical tree, so there is no reference to it
  783. window.Content = null;
  784. // Mock keep reference on a Popup via InvocationsCollection. So let's clear it before.
  785. Mock.Get(window.PlatformImpl).Invocations.Clear();
  786. return window;
  787. };
  788. var result = run();
  789. // Process all Loaded events to free control reference(s)
  790. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  791. dotMemory.Check(memory =>
  792. {
  793. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBlock>()).ObjectsCount);
  794. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<ToolTip>()).ObjectsCount);
  795. });
  796. }
  797. }
  798. [Fact]
  799. public void Flyout_Is_Freed()
  800. {
  801. using (Start())
  802. {
  803. Func<Window> run = () =>
  804. {
  805. var window = new Window();
  806. var source = new Button
  807. {
  808. Template = new FuncControlTemplate<Button>((parent, _) =>
  809. new Button
  810. {
  811. Flyout = new Flyout
  812. {
  813. Content = new TextBlock
  814. {
  815. [~TextBlock.TextProperty] = new TemplateBinding(ContentControl.ContentProperty)
  816. }
  817. }
  818. }),
  819. };
  820. window.Content = source;
  821. window.Show();
  822. var templateChild = (Button)source.GetVisualChildren().Single();
  823. templateChild.Flyout!.ShowAt(templateChild);
  824. templateChild.Flyout!.Hide();
  825. // Detach the button from the logical tree, so there is no reference to it
  826. window.Content = null;
  827. // Mock keep reference on a Popup via InvocationsCollection. So let's clear it before.
  828. Mock.Get(window.PlatformImpl).Invocations.Clear();
  829. return window;
  830. };
  831. var result = run();
  832. // Process all Loaded events to free control reference(s)
  833. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  834. dotMemory.Check(memory =>
  835. {
  836. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBlock>()).ObjectsCount);
  837. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Flyout>()).ObjectsCount);
  838. Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Popup>()).ObjectsCount);
  839. });
  840. }
  841. }
  842. private FuncControlTemplate CreateWindowTemplate()
  843. {
  844. return new FuncControlTemplate<Window>((parent, scope) =>
  845. {
  846. return new ContentPresenter
  847. {
  848. Name = "PART_ContentPresenter",
  849. [~ContentPresenter.ContentProperty] = parent[~ContentControl.ContentProperty],
  850. }.RegisterInNameScope(scope);
  851. });
  852. }
  853. private IDisposable Start()
  854. {
  855. static void Cleanup()
  856. {
  857. // KeyboardDevice holds a reference to the focused item.
  858. KeyboardDevice.Instance.SetFocusedElement(null, NavigationMethod.Unspecified, KeyModifiers.None);
  859. // Empty the dispatcher queue.
  860. Dispatcher.UIThread.RunJobs();
  861. }
  862. return new CompositeDisposable
  863. {
  864. Disposable.Create(Cleanup),
  865. UnitTestApplication.Start(TestServices.StyledWindow.With(
  866. focusManager: new FocusManager(),
  867. keyboardDevice: () => new KeyboardDevice(),
  868. inputManager: new InputManager()))
  869. };
  870. }
  871. private class Node
  872. {
  873. public string Name { get; set; }
  874. public IEnumerable<Node> Children { get; set; }
  875. }
  876. }
  877. }