ButtonTests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. using System;
  2. using Avalonia.Controls.Presenters;
  3. using Avalonia.Controls.Templates;
  4. using Avalonia.Controls.UnitTests.Utils;
  5. using Avalonia.Data;
  6. using Avalonia.Input;
  7. using Avalonia.Interactivity;
  8. using Avalonia.Layout;
  9. using Avalonia.Media;
  10. using Avalonia.Platform;
  11. using Avalonia.Rendering;
  12. using Avalonia.Threading;
  13. using Avalonia.UnitTests;
  14. using Moq;
  15. using Xunit;
  16. using MouseButton = Avalonia.Input.MouseButton;
  17. namespace Avalonia.Controls.UnitTests
  18. {
  19. public class ButtonTests : ScopedTestBase
  20. {
  21. private MouseTestHelper _helper = new MouseTestHelper();
  22. [Fact]
  23. public void Button_Is_Disabled_When_Command_Is_Disabled()
  24. {
  25. var command = new TestCommand(false);
  26. var target = new Button
  27. {
  28. Command = command,
  29. };
  30. var root = new TestRoot { Child = target };
  31. Assert.False(target.IsEffectivelyEnabled);
  32. command.IsEnabled = true;
  33. Assert.True(target.IsEffectivelyEnabled);
  34. command.IsEnabled = false;
  35. Assert.False(target.IsEffectivelyEnabled);
  36. }
  37. [Fact]
  38. public void Button_Is_Disabled_When_Command_Is_Enabled_But_IsEnabled_Is_False()
  39. {
  40. var command = new TestCommand(true);
  41. var target = new Button
  42. {
  43. IsEnabled = false,
  44. Command = command,
  45. };
  46. var root = new TestRoot { Child = target };
  47. Assert.False(((IInputElement)target).IsEffectivelyEnabled);
  48. }
  49. [Fact]
  50. public void Button_Is_Disabled_When_Bound_Command_Doesnt_Exist()
  51. {
  52. var target = new Button
  53. {
  54. [!Button.CommandProperty] = new Binding("Command"),
  55. };
  56. Assert.True(target.IsEnabled);
  57. Assert.False(target.IsEffectivelyEnabled);
  58. }
  59. [Fact]
  60. public void Button_Is_Disabled_When_Bound_Command_Is_Removed()
  61. {
  62. var viewModel = new
  63. {
  64. Command = new TestCommand(true),
  65. };
  66. var target = new Button
  67. {
  68. DataContext = viewModel,
  69. [!Button.CommandProperty] = new Binding("Command"),
  70. };
  71. Assert.True(target.IsEnabled);
  72. Assert.True(target.IsEffectivelyEnabled);
  73. target.DataContext = null;
  74. Assert.True(target.IsEnabled);
  75. Assert.False(target.IsEffectivelyEnabled);
  76. }
  77. [Fact]
  78. public void Button_Is_Enabled_When_Bound_Command_Is_Added()
  79. {
  80. var viewModel = new
  81. {
  82. Command = new TestCommand(true),
  83. };
  84. var target = new Button
  85. {
  86. DataContext = new object(),
  87. [!Button.CommandProperty] = new Binding("Command"),
  88. };
  89. var root = new TestRoot { Child = target };
  90. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  91. Assert.True(target.IsEnabled);
  92. Assert.False(target.IsEffectivelyEnabled);
  93. target.DataContext = viewModel;
  94. Assert.True(target.IsEnabled);
  95. Assert.True(target.IsEffectivelyEnabled);
  96. }
  97. [Fact]
  98. public void Button_Is_Disabled_When_Disabled_Bound_Command_Is_Added()
  99. {
  100. var viewModel = new
  101. {
  102. Command = new TestCommand(false),
  103. };
  104. var target = new Button
  105. {
  106. DataContext = new object(),
  107. [!Button.CommandProperty] = new Binding("Command"),
  108. };
  109. Assert.True(target.IsEnabled);
  110. Assert.False(target.IsEffectivelyEnabled);
  111. target.DataContext = viewModel;
  112. Assert.True(target.IsEnabled);
  113. Assert.False(target.IsEffectivelyEnabled);
  114. }
  115. [Fact]
  116. public void Button_Raises_Click()
  117. {
  118. var renderer = new Mock<IHitTester>();
  119. var pt = new Point(50, 50);
  120. renderer.Setup(r => r.HitTest(It.IsAny<Point>(), It.IsAny<Visual>(), It.IsAny<Func<Visual, bool>>()))
  121. .Returns<Point, Visual, Func<Visual, bool>>((p, r, f) =>
  122. r.Bounds.Contains(p) ? new Visual[] { r } : new Visual[0]);
  123. using var _ = UnitTestApplication.Start(TestServices.StyledWindow);
  124. var root = new Window() { HitTesterOverride = renderer.Object };
  125. var target = new Button()
  126. {
  127. Width = 100,
  128. Height = 100,
  129. VerticalAlignment = VerticalAlignment.Top,
  130. HorizontalAlignment = HorizontalAlignment.Left
  131. };
  132. root.Content = target;
  133. root.Show();
  134. bool clicked = false;
  135. target.Click += (s, e) => clicked = true;
  136. RaisePointerEntered(target);
  137. RaisePointerMove(target, pt);
  138. RaisePointerPressed(target, 1, MouseButton.Left, pt);
  139. Assert.Equal(_helper.Captured, target);
  140. RaisePointerReleased(target, MouseButton.Left, pt);
  141. Assert.Equal(_helper.Captured, null);
  142. Assert.True(clicked);
  143. }
  144. [Fact]
  145. public void Button_Does_Not_Raise_Click_When_PointerReleased_Outside()
  146. {
  147. var root = new TestRoot();
  148. var target = new Button()
  149. {
  150. Width = 100,
  151. Height = 100
  152. };
  153. root.Child = target;
  154. bool clicked = false;
  155. target.Click += (s, e) => clicked = true;
  156. RaisePointerEntered(target);
  157. RaisePointerMove(target, new Point(50, 50));
  158. RaisePointerPressed(target, 1, MouseButton.Left, new Point(50, 50));
  159. RaisePointerExited(target);
  160. Assert.Equal(_helper.Captured, target);
  161. RaisePointerReleased(target, MouseButton.Left, new Point(200, 50));
  162. Assert.Equal(_helper.Captured, null);
  163. Assert.False(clicked);
  164. }
  165. [Fact]
  166. public void Button_With_RenderTransform_Raises_Click()
  167. {
  168. var renderer = new Mock<IHitTester>();
  169. var pt = new Point(150, 50);
  170. renderer.Setup(r => r.HitTest(It.IsAny<Point>(), It.IsAny<Visual>(), It.IsAny<Func<Visual, bool>>()))
  171. .Returns<Point, Visual, Func<Visual, bool>>((p, r, f) =>
  172. r.Bounds.Contains(p.Transform(r.RenderTransform.Value.Invert())) ?
  173. new Visual[] { r } : new Visual[0]);
  174. using var _ = UnitTestApplication.Start(TestServices.StyledWindow);
  175. var root = new Window() { HitTesterOverride = renderer.Object };
  176. var target = new Button()
  177. {
  178. Width = 100,
  179. Height = 100,
  180. VerticalAlignment = VerticalAlignment.Top,
  181. HorizontalAlignment = HorizontalAlignment.Left,
  182. RenderTransform = new TranslateTransform { X = 100, Y = 0 }
  183. };
  184. root.Content = target;
  185. root.Show();
  186. //actual bounds of button should be 100,0,100,100 x -> translated 100 pixels
  187. //so mouse with x=150 coordinates should trigger click
  188. //button shouldn't count on bounds to calculate pointer is in the over or not, but
  189. //on avalonia event system, as renderer hit test will properly calculate whether to send
  190. //mouse over events to button based on rendered bounds
  191. //note: button also may have not rectangular shape and only renderer hit testing is reliable
  192. bool clicked = false;
  193. target.Click += (s, e) => clicked = true;
  194. RaisePointerEntered(target);
  195. RaisePointerMove(target, pt);
  196. RaisePointerPressed(target, 1, MouseButton.Left, pt);
  197. Assert.Equal(_helper.Captured, target);
  198. RaisePointerReleased(target, MouseButton.Left, pt);
  199. Assert.Equal(_helper.Captured, null);
  200. Assert.True(clicked);
  201. }
  202. [Fact]
  203. public void Button_Does_Not_Subscribe_To_Command_CanExecuteChanged_Until_Added_To_Logical_Tree()
  204. {
  205. var command = new TestCommand(true);
  206. var target = new Button
  207. {
  208. Command = command,
  209. };
  210. Assert.Equal(0, command.SubscriptionCount);
  211. }
  212. [Fact]
  213. public void Button_Subscribes_To_Command_CanExecuteChanged_When_Added_To_Logical_Tree()
  214. {
  215. var command = new TestCommand(true);
  216. var target = new Button { Command = command };
  217. var root = new TestRoot { Child = target };
  218. Assert.Equal(1, command.SubscriptionCount);
  219. }
  220. [Fact]
  221. public void Button_Unsubscribes_From_Command_CanExecuteChanged_When_Removed_From_Logical_Tree()
  222. {
  223. var command = new TestCommand(true);
  224. var target = new Button { Command = command };
  225. var root = new TestRoot { Child = target };
  226. root.Child = null;
  227. Assert.Equal(0, command.SubscriptionCount);
  228. }
  229. [Fact]
  230. public void Button_Invokes_CanExecute_When_CommandParameter_Changed()
  231. {
  232. var target = new Button();
  233. var raised = 0;
  234. target.Click += (s, e) => ++raised;
  235. target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent));
  236. Assert.Equal(1, raised);
  237. }
  238. [Fact]
  239. public void Raises_Click_When_AccessKey_Raised()
  240. {
  241. var raised = 0;
  242. var ah = new AccessKeyHandler();
  243. using var app = UnitTestApplication.Start(TestServices.StyledWindow.With(accessKeyHandler: ah));
  244. var impl = CreateMockTopLevelImpl();
  245. var command = new TestCommand(p => p is bool value && value, _ => raised++);
  246. Button target;
  247. var root = new TestTopLevel(impl.Object)
  248. {
  249. Template = CreateTemplate(),
  250. Content = target = new Button
  251. {
  252. Content = "_A",
  253. Command = command,
  254. Template = new FuncControlTemplate<Button>((parent, scope) =>
  255. {
  256. return new ContentPresenter
  257. {
  258. Name = "PART_ContentPresenter",
  259. [~ContentPresenter.ContentProperty] = new TemplateBinding(Button.ContentProperty),
  260. [~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(Button.ContentProperty),
  261. RecognizesAccessKey = true,
  262. }.RegisterInNameScope(scope);
  263. })
  264. },
  265. };
  266. root.ApplyTemplate();
  267. root.Presenter.UpdateChild();
  268. target.ApplyTemplate();
  269. target.Presenter.UpdateChild();
  270. Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
  271. var accessKey = Key.A;
  272. target.CommandParameter = true;
  273. RaiseAccessKey(root, accessKey);
  274. Assert.Equal(1, raised);
  275. target.CommandParameter = false;
  276. RaiseAccessKey(root, accessKey);
  277. Assert.Equal(1, raised);
  278. static FuncControlTemplate<TestTopLevel> CreateTemplate()
  279. {
  280. return new FuncControlTemplate<TestTopLevel>((x, scope) =>
  281. new ContentPresenter
  282. {
  283. Name = "PART_ContentPresenter",
  284. [~ContentPresenter.ContentProperty] = new TemplateBinding(ContentControl.ContentProperty),
  285. [~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(ContentControl.ContentTemplateProperty)
  286. }.RegisterInNameScope(scope));
  287. }
  288. static Mock<ITopLevelImpl> CreateMockTopLevelImpl(bool setupProperties = false)
  289. {
  290. var topLevel = new Mock<ITopLevelImpl>();
  291. if (setupProperties)
  292. topLevel.SetupAllProperties();
  293. topLevel.Setup(x => x.RenderScaling).Returns(1);
  294. topLevel.Setup(x => x.Compositor).Returns(RendererMocks.CreateDummyCompositor());
  295. return topLevel;
  296. }
  297. static void RaiseAccessKey(IInputElement target, Key accessKey)
  298. {
  299. KeyDown(target, Key.LeftAlt);
  300. KeyDown(target, accessKey, KeyModifiers.Alt);
  301. KeyUp(target, accessKey, KeyModifiers.Alt);
  302. KeyUp(target, Key.LeftAlt);
  303. }
  304. static void KeyDown(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None)
  305. {
  306. target.RaiseEvent(new KeyEventArgs
  307. {
  308. RoutedEvent = InputElement.KeyDownEvent,
  309. Key = key,
  310. KeyModifiers = modifiers,
  311. });
  312. }
  313. static void KeyUp(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None)
  314. {
  315. target.RaiseEvent(new KeyEventArgs
  316. {
  317. RoutedEvent = InputElement.KeyUpEvent,
  318. Key = key,
  319. KeyModifiers = modifiers,
  320. });
  321. }
  322. }
  323. [Fact]
  324. public void Button_Invokes_Doesnt_Execute_When_Button_Disabled()
  325. {
  326. var target = new Button();
  327. var raised = 0;
  328. target.IsEnabled = false;
  329. target.Click += (s, e) => ++raised;
  330. target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent));
  331. Assert.Equal(0, raised);
  332. }
  333. [Fact]
  334. public void Button_IsDefault_Works()
  335. {
  336. using (UnitTestApplication.Start(TestServices.StyledWindow))
  337. {
  338. var raised = 0;
  339. var target = new Button();
  340. var window = new Window { Content = target };
  341. window.Show();
  342. target.Click += (s, e) => ++raised;
  343. target.IsDefault = false;
  344. window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
  345. Assert.Equal(0, raised);
  346. target.IsDefault = true;
  347. window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
  348. Assert.Equal(1, raised);
  349. target.IsDefault = false;
  350. window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
  351. Assert.Equal(1, raised);
  352. target.IsDefault = true;
  353. window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
  354. Assert.Equal(2, raised);
  355. window.Content = null;
  356. // To check if handler was raised on the button, when it's detached, we need to pass it as a source manually.
  357. window.RaiseEvent(CreateKeyDownEvent(Key.Enter, target));
  358. Assert.Equal(2, raised);
  359. }
  360. }
  361. [Fact]
  362. public void Button_IsCancel_Works()
  363. {
  364. using (UnitTestApplication.Start(TestServices.StyledWindow))
  365. {
  366. var raised = 0;
  367. var target = new Button();
  368. var window = new Window { Content = target };
  369. window.Show();
  370. target.Click += (s, e) => ++raised;
  371. target.IsCancel = false;
  372. window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
  373. Assert.Equal(0, raised);
  374. target.IsCancel = true;
  375. window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
  376. Assert.Equal(1, raised);
  377. target.IsCancel = false;
  378. window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
  379. Assert.Equal(1, raised);
  380. target.IsCancel = true;
  381. window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
  382. Assert.Equal(2, raised);
  383. window.Content = null;
  384. window.RaiseEvent(CreateKeyDownEvent(Key.Escape, target));
  385. Assert.Equal(2, raised);
  386. }
  387. }
  388. [Fact]
  389. public void Button_CommandParameter_Does_Not_Change_While_Execution()
  390. {
  391. var target = new Button();
  392. object lastParamenter = "A";
  393. var generator = new Random();
  394. var onlyOnce = false;
  395. var command = new TestCommand(parameter =>
  396. {
  397. if (!onlyOnce)
  398. {
  399. onlyOnce = true;
  400. target.CommandParameter = generator.Next();
  401. }
  402. lastParamenter = parameter;
  403. return true;
  404. },
  405. parameter =>
  406. {
  407. Assert.Equal(lastParamenter, parameter);
  408. });
  409. target.CommandParameter = lastParamenter;
  410. target.Command = command;
  411. var root = new TestRoot { Child = target };
  412. (target as IClickableControl).RaiseClick();
  413. }
  414. [Fact]
  415. void Should_Not_Fire_Click_Event_On_Space_Key_When_It_Is_Not_Focus()
  416. {
  417. using (UnitTestApplication.Start(TestServices.StyledWindow))
  418. {
  419. var raised = 0;
  420. var target = new TextBox();
  421. var button = new Button()
  422. {
  423. Content = target,
  424. };
  425. var window = new Window { Content = button };
  426. window.Show();
  427. button.Click += (s, e) => ++raised;
  428. target.Focus();
  429. target.RaiseEvent(CreateKeyDownEvent(Key.Space));
  430. target.RaiseEvent(CreateKeyUpEvent(Key.Space));
  431. Assert.Equal(0, raised);
  432. }
  433. }
  434. private KeyEventArgs CreateKeyDownEvent(Key key, Interactive source = null)
  435. {
  436. return new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = key, Source = source };
  437. }
  438. private KeyEventArgs CreateKeyUpEvent(Key key, Interactive source = null)
  439. {
  440. return new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = key, Source = source };
  441. }
  442. private void RaisePointerPressed(Button button, int clickCount, MouseButton mouseButton, Point position)
  443. {
  444. _helper.Down(button, mouseButton, position, clickCount: clickCount);
  445. }
  446. private void RaisePointerReleased(Button button, MouseButton mouseButton, Point pt)
  447. {
  448. _helper.Up(button, mouseButton, pt);
  449. }
  450. private void RaisePointerEntered(Button button)
  451. {
  452. _helper.Enter(button);
  453. }
  454. private void RaisePointerExited(Button button)
  455. {
  456. _helper.Leave(button);
  457. }
  458. private void RaisePointerMove(Button button, Point pos)
  459. {
  460. _helper.Move(button, pos);
  461. }
  462. private class TestTopLevel : TopLevel
  463. {
  464. private readonly ILayoutManager _layoutManager;
  465. public bool IsClosed { get; private set; }
  466. public TestTopLevel(ITopLevelImpl impl, ILayoutManager layoutManager = null)
  467. : base(impl)
  468. {
  469. _layoutManager = layoutManager ?? new LayoutManager(this);
  470. }
  471. private protected override ILayoutManager CreateLayoutManager() => _layoutManager;
  472. }
  473. }
  474. }