123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636 |
- using System;
- using Avalonia.Controls.Presenters;
- using Avalonia.Controls.Templates;
- using Avalonia.Controls.UnitTests.Utils;
- using Avalonia.Data;
- using Avalonia.Input;
- using Avalonia.Interactivity;
- using Avalonia.Layout;
- using Avalonia.Media;
- using Avalonia.Platform;
- using Avalonia.Rendering;
- using Avalonia.Threading;
- using Avalonia.UnitTests;
- using Moq;
- using Xunit;
- using MouseButton = Avalonia.Input.MouseButton;
- namespace Avalonia.Controls.UnitTests
- {
- public class ButtonTests : ScopedTestBase
- {
- private MouseTestHelper _helper = new MouseTestHelper();
- [Fact]
- public void Button_Is_Disabled_When_Command_Is_Disabled()
- {
- var command = new TestCommand(false);
- var target = new Button
- {
- Command = command,
- };
- var root = new TestRoot { Child = target };
- Assert.False(target.IsEffectivelyEnabled);
- command.IsEnabled = true;
- Assert.True(target.IsEffectivelyEnabled);
- command.IsEnabled = false;
- Assert.False(target.IsEffectivelyEnabled);
- }
- [Fact]
- public void Button_Is_Disabled_When_Command_Is_Enabled_But_IsEnabled_Is_False()
- {
- var command = new TestCommand(true);
- var target = new Button
- {
- IsEnabled = false,
- Command = command,
- };
- var root = new TestRoot { Child = target };
- Assert.False(((IInputElement)target).IsEffectivelyEnabled);
- }
- [Fact]
- public void Button_Is_Disabled_When_Bound_Command_Doesnt_Exist()
- {
- var target = new Button
- {
- [!Button.CommandProperty] = new Binding("Command"),
- };
- Assert.True(target.IsEnabled);
- Assert.False(target.IsEffectivelyEnabled);
- }
- [Fact]
- public void Button_Is_Disabled_When_Bound_Command_Is_Removed()
- {
- var viewModel = new
- {
- Command = new TestCommand(true),
- };
- var target = new Button
- {
- DataContext = viewModel,
- [!Button.CommandProperty] = new Binding("Command"),
- };
- Assert.True(target.IsEnabled);
- Assert.True(target.IsEffectivelyEnabled);
- target.DataContext = null;
- Assert.True(target.IsEnabled);
- Assert.False(target.IsEffectivelyEnabled);
- }
- [Fact]
- public void Button_Is_Enabled_When_Bound_Command_Is_Added()
- {
- var viewModel = new
- {
- Command = new TestCommand(true),
- };
- var target = new Button
- {
- DataContext = new object(),
- [!Button.CommandProperty] = new Binding("Command"),
- };
- var root = new TestRoot { Child = target };
- Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
- Assert.True(target.IsEnabled);
- Assert.False(target.IsEffectivelyEnabled);
- target.DataContext = viewModel;
- Assert.True(target.IsEnabled);
- Assert.True(target.IsEffectivelyEnabled);
- }
- [Fact]
- public void Button_Is_Disabled_When_Disabled_Bound_Command_Is_Added()
- {
- var viewModel = new
- {
- Command = new TestCommand(false),
- };
- var target = new Button
- {
- DataContext = new object(),
- [!Button.CommandProperty] = new Binding("Command"),
- };
- Assert.True(target.IsEnabled);
- Assert.False(target.IsEffectivelyEnabled);
- target.DataContext = viewModel;
- Assert.True(target.IsEnabled);
- Assert.False(target.IsEffectivelyEnabled);
- }
- [Fact]
- public void Button_Raises_Click()
- {
- var renderer = new Mock<IHitTester>();
- var pt = new Point(50, 50);
- renderer.Setup(r => r.HitTest(It.IsAny<Point>(), It.IsAny<Visual>(), It.IsAny<Func<Visual, bool>>()))
- .Returns<Point, Visual, Func<Visual, bool>>((p, r, f) =>
- r.Bounds.Contains(p) ? new Visual[] { r } : new Visual[0]);
- using var _ = UnitTestApplication.Start(TestServices.StyledWindow);
- var root = new Window() { HitTesterOverride = renderer.Object };
- var target = new Button()
- {
- Width = 100,
- Height = 100,
- VerticalAlignment = VerticalAlignment.Top,
- HorizontalAlignment = HorizontalAlignment.Left
- };
- root.Content = target;
- root.Show();
- bool clicked = false;
- target.Click += (s, e) => clicked = true;
- RaisePointerEntered(target);
- RaisePointerMove(target, pt);
- RaisePointerPressed(target, 1, MouseButton.Left, pt);
- Assert.Equal(_helper.Captured, target);
- RaisePointerReleased(target, MouseButton.Left, pt);
- Assert.Equal(_helper.Captured, null);
- Assert.True(clicked);
- }
- [Fact]
- public void Button_Does_Not_Raise_Click_When_PointerReleased_Outside()
- {
- var root = new TestRoot();
- var target = new Button()
- {
- Width = 100,
- Height = 100
- };
- root.Child = target;
- bool clicked = false;
- target.Click += (s, e) => clicked = true;
- RaisePointerEntered(target);
- RaisePointerMove(target, new Point(50, 50));
- RaisePointerPressed(target, 1, MouseButton.Left, new Point(50, 50));
- RaisePointerExited(target);
- Assert.Equal(_helper.Captured, target);
- RaisePointerReleased(target, MouseButton.Left, new Point(200, 50));
- Assert.Equal(_helper.Captured, null);
- Assert.False(clicked);
- }
- [Fact]
- public void Button_With_RenderTransform_Raises_Click()
- {
- var renderer = new Mock<IHitTester>();
- var pt = new Point(150, 50);
- renderer.Setup(r => r.HitTest(It.IsAny<Point>(), It.IsAny<Visual>(), It.IsAny<Func<Visual, bool>>()))
- .Returns<Point, Visual, Func<Visual, bool>>((p, r, f) =>
- r.Bounds.Contains(p.Transform(r.RenderTransform.Value.Invert())) ?
- new Visual[] { r } : new Visual[0]);
- using var _ = UnitTestApplication.Start(TestServices.StyledWindow);
- var root = new Window() { HitTesterOverride = renderer.Object };
- var target = new Button()
- {
- Width = 100,
- Height = 100,
- VerticalAlignment = VerticalAlignment.Top,
- HorizontalAlignment = HorizontalAlignment.Left,
- RenderTransform = new TranslateTransform { X = 100, Y = 0 }
- };
- root.Content = target;
- root.Show();
- //actual bounds of button should be 100,0,100,100 x -> translated 100 pixels
- //so mouse with x=150 coordinates should trigger click
- //button shouldn't count on bounds to calculate pointer is in the over or not, but
- //on avalonia event system, as renderer hit test will properly calculate whether to send
- //mouse over events to button based on rendered bounds
- //note: button also may have not rectangular shape and only renderer hit testing is reliable
- bool clicked = false;
- target.Click += (s, e) => clicked = true;
- RaisePointerEntered(target);
- RaisePointerMove(target, pt);
- RaisePointerPressed(target, 1, MouseButton.Left, pt);
- Assert.Equal(_helper.Captured, target);
- RaisePointerReleased(target, MouseButton.Left, pt);
- Assert.Equal(_helper.Captured, null);
- Assert.True(clicked);
- }
- [Fact]
- public void Button_Does_Not_Subscribe_To_Command_CanExecuteChanged_Until_Added_To_Logical_Tree()
- {
- var command = new TestCommand(true);
- var target = new Button
- {
- Command = command,
- };
- Assert.Equal(0, command.SubscriptionCount);
- }
- [Fact]
- public void Button_Subscribes_To_Command_CanExecuteChanged_When_Added_To_Logical_Tree()
- {
- var command = new TestCommand(true);
- var target = new Button { Command = command };
- var root = new TestRoot { Child = target };
- Assert.Equal(1, command.SubscriptionCount);
- }
- [Fact]
- public void Button_Unsubscribes_From_Command_CanExecuteChanged_When_Removed_From_Logical_Tree()
- {
- var command = new TestCommand(true);
- var target = new Button { Command = command };
- var root = new TestRoot { Child = target };
- root.Child = null;
- Assert.Equal(0, command.SubscriptionCount);
- }
- [Fact]
- public void Button_Invokes_CanExecute_When_CommandParameter_Changed()
- {
- var target = new Button();
- var raised = 0;
- target.Click += (s, e) => ++raised;
-
- target.RaiseEvent(new AccessKeyEventArgs("b", false));
-
- Assert.Equal(1, raised);
- }
- [Fact]
- public void Raises_Click_When_AccessKey_Raised()
- {
- var raised = 0;
- var ah = new AccessKeyHandler();
- var kd = new KeyboardDevice();
- using var app = UnitTestApplication.Start(TestServices.StyledWindow
- .With(
- accessKeyHandler: ah,
- keyboardDevice: () => kd)
- );
- var impl = CreateMockTopLevelImpl();
- var command = new TestCommand(p => p is bool value && value, _ => raised++);
- Button target;
- var root = new TestTopLevel(impl.Object)
- {
- Template = CreateTemplate(),
- Content = target = new Button
- {
- Content = "_A",
- Command = command,
- Template = new FuncControlTemplate<Button>((parent, scope) =>
- {
- return new ContentPresenter
- {
- Name = "PART_ContentPresenter",
- [~ContentPresenter.ContentProperty] = new TemplateBinding(Button.ContentProperty),
- [~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(Button.ContentProperty),
- RecognizesAccessKey = true,
- }.RegisterInNameScope(scope);
- })
- },
- };
- root.ApplyTemplate();
- root.Presenter.UpdateChild();
- target.ApplyTemplate();
- target.Presenter.UpdateChild();
- kd.SetFocusedElement(target, NavigationMethod.Unspecified, KeyModifiers.None);
- Dispatcher.UIThread.RunJobs(DispatcherPriority.Loaded);
- var accessKey = Key.A;
- target.CommandParameter = true;
- RaiseAccessKey(root, accessKey);
- Assert.Equal(1, raised);
- target.CommandParameter = false;
- RaiseAccessKey(root, accessKey);
- Assert.Equal(1, raised);
-
- static FuncControlTemplate<TestTopLevel> CreateTemplate()
- {
- return new FuncControlTemplate<TestTopLevel>((x, scope) =>
- new ContentPresenter
- {
- Name = "PART_ContentPresenter",
- [~ContentPresenter.ContentProperty] = new TemplateBinding(ContentControl.ContentProperty),
- [~ContentPresenter.ContentTemplateProperty] = new TemplateBinding(ContentControl.ContentTemplateProperty)
- }.RegisterInNameScope(scope));
- }
- static Mock<ITopLevelImpl> CreateMockTopLevelImpl(bool setupProperties = false)
- {
- var topLevel = new Mock<ITopLevelImpl>();
- if (setupProperties)
- topLevel.SetupAllProperties();
- topLevel.Setup(x => x.RenderScaling).Returns(1);
- topLevel.Setup(x => x.Compositor).Returns(RendererMocks.CreateDummyCompositor());
- return topLevel;
- }
- static void RaiseAccessKey(IInputElement target, Key accessKey)
- {
- KeyDown(target, Key.LeftAlt);
- KeyDown(target, accessKey, KeyModifiers.Alt);
- KeyUp(target, accessKey, KeyModifiers.Alt);
- KeyUp(target, Key.LeftAlt);
- }
- static void KeyDown(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None)
- {
- target.RaiseEvent(new KeyEventArgs
- {
- RoutedEvent = InputElement.KeyDownEvent,
- Key = key,
- KeyModifiers = modifiers,
- });
- }
- static void KeyUp(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None)
- {
- target.RaiseEvent(new KeyEventArgs
- {
- RoutedEvent = InputElement.KeyUpEvent,
- Key = key,
- KeyModifiers = modifiers,
- });
- }
- }
- [Fact]
- public void Button_Invokes_Doesnt_Execute_When_Button_Disabled()
- {
- var target = new Button();
- var raised = 0;
- target.IsEnabled = false;
- target.Click += (s, e) => ++raised;
- target.RaiseEvent(new AccessKeyEventArgs("b", false));
- Assert.Equal(0, raised);
- }
- [Fact]
- public void Button_IsDefault_Works()
- {
- using (UnitTestApplication.Start(TestServices.StyledWindow))
- {
- var raised = 0;
- var target = new Button();
- var window = new Window { Content = target };
- window.Show();
- target.Click += (s, e) => ++raised;
- target.IsDefault = false;
- window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
- Assert.Equal(0, raised);
- target.IsDefault = true;
- window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
- Assert.Equal(1, raised);
- target.IsDefault = false;
- window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
- Assert.Equal(1, raised);
- target.IsDefault = true;
- window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
- Assert.Equal(2, raised);
- window.Content = null;
- // To check if handler was raised on the button, when it's detached, we need to pass it as a source manually.
- window.RaiseEvent(CreateKeyDownEvent(Key.Enter, target));
- Assert.Equal(2, raised);
- }
- }
-
- [Fact]
- public void Button_IsDefault_Should_Not_Work_When_Button_Is_Not_Effectively_Visible()
- {
- using (UnitTestApplication.Start(TestServices.StyledWindow))
- {
- var raised = 0;
- var panel = new Panel();
- var target = new Button();
- panel.Children.Add(target);
- var window = new Window { Content = panel };
- window.Show();
- target.Click += (s, e) => ++raised;
-
- target.IsDefault = true;
- panel.IsVisible = false;
- window.RaiseEvent(CreateKeyDownEvent(Key.Enter));
- Assert.Equal(0, raised);
- }
- }
- [Fact]
- public void Button_IsCancel_Works()
- {
- using (UnitTestApplication.Start(TestServices.StyledWindow))
- {
- var raised = 0;
- var target = new Button();
- var window = new Window { Content = target };
- window.Show();
- target.Click += (s, e) => ++raised;
- target.IsCancel = false;
- window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
- Assert.Equal(0, raised);
- target.IsCancel = true;
- window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
- Assert.Equal(1, raised);
- target.IsCancel = false;
- window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
- Assert.Equal(1, raised);
- target.IsCancel = true;
- window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
- Assert.Equal(2, raised);
- window.Content = null;
- window.RaiseEvent(CreateKeyDownEvent(Key.Escape, target));
- Assert.Equal(2, raised);
- }
- }
-
- [Fact]
- public void Button_IsCancel_Should_Not_Work_When_Button_Is_Not_Effectively_Visible()
- {
- using (UnitTestApplication.Start(TestServices.StyledWindow))
- {
- var raised = 0;
- var panel = new Panel();
- var target = new Button();
- panel.Children.Add(target);
- var window = new Window { Content = panel };
- window.Show();
- target.Click += (s, e) => ++raised;
-
- target.IsCancel = true;
- panel.IsVisible = false;
- window.RaiseEvent(CreateKeyDownEvent(Key.Escape));
- Assert.Equal(0, raised);
- }
- }
- [Fact]
- public void Button_CommandParameter_Does_Not_Change_While_Execution()
- {
- var target = new Button();
- object lastParamenter = "A";
- var generator = new Random();
- var onlyOnce = false;
- var command = new TestCommand(parameter =>
- {
- if (!onlyOnce)
- {
- onlyOnce = true;
- target.CommandParameter = generator.Next();
- }
- lastParamenter = parameter;
- return true;
- },
- parameter =>
- {
- Assert.Equal(lastParamenter, parameter);
- });
- target.CommandParameter = lastParamenter;
- target.Command = command;
- var root = new TestRoot { Child = target };
- (target as IClickableControl).RaiseClick();
- }
- [Fact]
- void Should_Not_Fire_Click_Event_On_Space_Key_When_It_Is_Not_Focus()
- {
- using (UnitTestApplication.Start(TestServices.StyledWindow))
- {
- var raised = 0;
- var target = new TextBox();
- var button = new Button()
- {
- Content = target,
- };
- var window = new Window { Content = button };
- window.Show();
- button.Click += (s, e) => ++raised;
- target.Focus();
- target.RaiseEvent(CreateKeyDownEvent(Key.Space));
- target.RaiseEvent(CreateKeyUpEvent(Key.Space));
- Assert.Equal(0, raised);
- }
- }
- private KeyEventArgs CreateKeyDownEvent(Key key, Interactive source = null)
- {
- return new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = key, Source = source };
- }
- private KeyEventArgs CreateKeyUpEvent(Key key, Interactive source = null)
- {
- return new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = key, Source = source };
- }
- private void RaisePointerPressed(Button button, int clickCount, MouseButton mouseButton, Point position)
- {
- _helper.Down(button, mouseButton, position, clickCount: clickCount);
- }
- private void RaisePointerReleased(Button button, MouseButton mouseButton, Point pt)
- {
- _helper.Up(button, mouseButton, pt);
- }
- private void RaisePointerEntered(Button button)
- {
- _helper.Enter(button);
- }
- private void RaisePointerExited(Button button)
- {
- _helper.Leave(button);
- }
- private void RaisePointerMove(Button button, Point pos)
- {
- _helper.Move(button, pos);
- }
- private class TestTopLevel : TopLevel
- {
- private readonly ILayoutManager _layoutManager;
- public bool IsClosed { get; private set; }
- public TestTopLevel(ITopLevelImpl impl, ILayoutManager layoutManager = null)
- : base(impl)
- {
- _layoutManager = layoutManager ?? new LayoutManager(this);
- }
- private protected override ILayoutManager CreateLayoutManager() => _layoutManager;
- }
- }
- }
|