Control.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using Avalonia.Automation.Peers;
  5. using Avalonia.Controls.Documents;
  6. using Avalonia.Controls.Primitives;
  7. using Avalonia.Controls.Templates;
  8. using Avalonia.Input;
  9. using Avalonia.Input.Platform;
  10. using Avalonia.Interactivity;
  11. using Avalonia.LogicalTree;
  12. using Avalonia.Media;
  13. using Avalonia.Rendering;
  14. using Avalonia.Styling;
  15. using Avalonia.Threading;
  16. using Avalonia.VisualTree;
  17. namespace Avalonia.Controls
  18. {
  19. /// <summary>
  20. /// Base class for Avalonia controls.
  21. /// </summary>
  22. /// <remarks>
  23. /// The control class extends <see cref="InputElement"/> and adds the following features:
  24. ///
  25. /// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control.
  26. /// - <see cref="ContextRequestedEvent"/> and other context menu related members.
  27. /// </remarks>
  28. public class Control : InputElement, IControl, INamed, IVisualBrushInitialize, ISetterValue
  29. {
  30. /// <summary>
  31. /// Defines the <see cref="FocusAdorner"/> property.
  32. /// </summary>
  33. public static readonly StyledProperty<ITemplate<IControl>?> FocusAdornerProperty =
  34. AvaloniaProperty.Register<Control, ITemplate<IControl>?>(nameof(FocusAdorner));
  35. /// <summary>
  36. /// Defines the <see cref="Tag"/> property.
  37. /// </summary>
  38. public static readonly StyledProperty<object?> TagProperty =
  39. AvaloniaProperty.Register<Control, object?>(nameof(Tag));
  40. /// <summary>
  41. /// Defines the <see cref="ContextMenu"/> property.
  42. /// </summary>
  43. public static readonly StyledProperty<ContextMenu?> ContextMenuProperty =
  44. AvaloniaProperty.Register<Control, ContextMenu?>(nameof(ContextMenu));
  45. /// <summary>
  46. /// Defines the <see cref="ContextFlyout"/> property
  47. /// </summary>
  48. public static readonly StyledProperty<FlyoutBase?> ContextFlyoutProperty =
  49. AvaloniaProperty.Register<Control, FlyoutBase?>(nameof(ContextFlyout));
  50. /// <summary>
  51. /// Event raised when an element wishes to be scrolled into view.
  52. /// </summary>
  53. public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent =
  54. RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>(
  55. "RequestBringIntoView",
  56. RoutingStrategies.Bubble);
  57. /// <summary>
  58. /// Provides event data for the <see cref="ContextRequested"/> event.
  59. /// </summary>
  60. public static readonly RoutedEvent<ContextRequestedEventArgs> ContextRequestedEvent =
  61. RoutedEvent.Register<Control, ContextRequestedEventArgs>(
  62. nameof(ContextRequested),
  63. RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
  64. /// <summary>
  65. /// Defines the <see cref="Loaded"/> event.
  66. /// </summary>
  67. public static readonly RoutedEvent<RoutedEventArgs> LoadedEvent =
  68. RoutedEvent.Register<Control, RoutedEventArgs>(
  69. nameof(Loaded),
  70. RoutingStrategies.Direct);
  71. /// <summary>
  72. /// Defines the <see cref="Unloaded"/> event.
  73. /// </summary>
  74. public static readonly RoutedEvent<RoutedEventArgs> UnloadedEvent =
  75. RoutedEvent.Register<Control, RoutedEventArgs>(
  76. nameof(Unloaded),
  77. RoutingStrategies.Direct);
  78. /// <summary>
  79. /// Defines the <see cref="FlowDirection"/> property.
  80. /// </summary>
  81. public static readonly AttachedProperty<FlowDirection> FlowDirectionProperty =
  82. AvaloniaProperty.RegisterAttached<Control, Control, FlowDirection>(
  83. nameof(FlowDirection),
  84. inherits: true);
  85. // Note the following:
  86. // _loadedQueue :
  87. // Is the queue where any control will be added to indicate that its loaded
  88. // event should be scheduled and called later.
  89. // _loadedProcessingQueue :
  90. // Contains a copied snapshot of the _loadedQueue at the time when processing
  91. // starts and individual events are being fired. This was needed to avoid
  92. // exceptions if new controls were added in the Loaded event itself.
  93. private static bool _isLoadedProcessing = false;
  94. private static readonly HashSet<Control> _loadedQueue = new HashSet<Control>();
  95. private static readonly HashSet<Control> _loadedProcessingQueue = new HashSet<Control>();
  96. private bool _isLoaded = false;
  97. private DataTemplates? _dataTemplates;
  98. private IControl? _focusAdorner;
  99. private AutomationPeer? _automationPeer;
  100. /// <summary>
  101. /// Gets or sets the control's focus adorner.
  102. /// </summary>
  103. public ITemplate<IControl>? FocusAdorner
  104. {
  105. get => GetValue(FocusAdornerProperty);
  106. set => SetValue(FocusAdornerProperty, value);
  107. }
  108. /// <summary>
  109. /// Gets or sets the data templates for the control.
  110. /// </summary>
  111. /// <remarks>
  112. /// Each control may define data templates which are applied to the control itself and its
  113. /// children.
  114. /// </remarks>
  115. public DataTemplates DataTemplates => _dataTemplates ??= new DataTemplates();
  116. /// <summary>
  117. /// Gets or sets a context menu to the control.
  118. /// </summary>
  119. public ContextMenu? ContextMenu
  120. {
  121. get => GetValue(ContextMenuProperty);
  122. set => SetValue(ContextMenuProperty, value);
  123. }
  124. /// <summary>
  125. /// Gets or sets a context flyout to the control
  126. /// </summary>
  127. public FlyoutBase? ContextFlyout
  128. {
  129. get => GetValue(ContextFlyoutProperty);
  130. set => SetValue(ContextFlyoutProperty, value);
  131. }
  132. /// <summary>
  133. /// Gets a value indicating whether the control is fully constructed in the visual tree
  134. /// and both layout and render are complete.
  135. /// </summary>
  136. /// <remarks>
  137. /// This is set to true while raising the <see cref="Loaded"/> event.
  138. /// </remarks>
  139. public bool IsLoaded => _isLoaded;
  140. /// <summary>
  141. /// Gets or sets a user-defined object attached to the control.
  142. /// </summary>
  143. public object? Tag
  144. {
  145. get => GetValue(TagProperty);
  146. set => SetValue(TagProperty, value);
  147. }
  148. /// <summary>
  149. /// Gets or sets the text flow direction.
  150. /// </summary>
  151. public FlowDirection FlowDirection
  152. {
  153. get => GetValue(FlowDirectionProperty);
  154. set => SetValue(FlowDirectionProperty, value);
  155. }
  156. /// <summary>
  157. /// Occurs when the user has completed a context input gesture, such as a right-click.
  158. /// </summary>
  159. public event EventHandler<ContextRequestedEventArgs>? ContextRequested
  160. {
  161. add => AddHandler(ContextRequestedEvent, value);
  162. remove => RemoveHandler(ContextRequestedEvent, value);
  163. }
  164. /// <summary>
  165. /// Occurs when the control has been fully constructed in the visual tree and both
  166. /// layout and render are complete.
  167. /// </summary>
  168. /// <remarks>
  169. /// This event is guaranteed to occur after the control template is applied and references
  170. /// to objects created after the template is applied are available. This makes it different
  171. /// from OnAttachedToVisualTree which doesn't have these references. This event occurs at the
  172. /// latest possible time in the control creation life-cycle.
  173. /// </remarks>
  174. public event EventHandler<RoutedEventArgs>? Loaded
  175. {
  176. add => AddHandler(LoadedEvent, value);
  177. remove => RemoveHandler(LoadedEvent, value);
  178. }
  179. /// <summary>
  180. /// Occurs when the control is removed from the visual tree.
  181. /// </summary>
  182. /// <remarks>
  183. /// This is API symmetrical with <see cref="Loaded"/> and exists for compatibility with other
  184. /// XAML frameworks; however, it behaves the same as OnDetachedFromVisualTree.
  185. /// </remarks>
  186. public event EventHandler<RoutedEventArgs>? Unloaded
  187. {
  188. add => AddHandler(UnloadedEvent, value);
  189. remove => RemoveHandler(UnloadedEvent, value);
  190. }
  191. public new IControl? Parent => (IControl?)base.Parent;
  192. /// <summary>
  193. /// Gets the value of the attached <see cref="FlowDirectionProperty"/> on a control.
  194. /// </summary>
  195. /// <param name="control">The control.</param>
  196. /// <returns>The flow direction.</returns>
  197. public static FlowDirection GetFlowDirection(Control control)
  198. {
  199. return control.GetValue(FlowDirectionProperty);
  200. }
  201. /// <summary>
  202. /// Sets the value of the attached <see cref="FlowDirectionProperty"/> on a control.
  203. /// </summary>
  204. /// <param name="control">The control.</param>
  205. /// <param name="value">The property value to set.</param>
  206. public static void SetFlowDirection(Control control, FlowDirection value)
  207. {
  208. control.SetValue(FlowDirectionProperty, value);
  209. }
  210. /// <inheritdoc/>
  211. bool IDataTemplateHost.IsDataTemplatesInitialized => _dataTemplates != null;
  212. /// <summary>
  213. /// Gets a value indicating whether control bypass FlowDirecton policies.
  214. /// </summary>
  215. /// <remarks>
  216. /// Related to FlowDirection system and returns false as default, so if
  217. /// <see cref="FlowDirection"/> is RTL then control will get a mirror presentation.
  218. /// For controls that want to avoid this behavior, override this property and return true.
  219. /// </remarks>
  220. protected virtual bool BypassFlowDirectionPolicies => false;
  221. /// <inheritdoc/>
  222. void ISetterValue.Initialize(ISetter setter)
  223. {
  224. if (setter is Setter s && s.Property == ContextFlyoutProperty)
  225. {
  226. return; // Allow ContextFlyout to not need wrapping in <Template>
  227. }
  228. throw new InvalidOperationException(
  229. "Cannot use a control as a Setter value. Wrap the control in a <Template>.");
  230. }
  231. /// <inheritdoc/>
  232. void IVisualBrushInitialize.EnsureInitialized()
  233. {
  234. if (VisualRoot == null)
  235. {
  236. if (!IsInitialized)
  237. {
  238. foreach (var i in this.GetSelfAndVisualDescendants())
  239. {
  240. var c = i as IControl;
  241. if (c?.IsInitialized == false && c is ISupportInitialize init)
  242. {
  243. init.BeginInit();
  244. init.EndInit();
  245. }
  246. }
  247. }
  248. if (!IsArrangeValid)
  249. {
  250. Measure(Size.Infinity);
  251. Arrange(new Rect(DesiredSize));
  252. }
  253. }
  254. }
  255. /// <summary>
  256. /// Gets the element that receives the focus adorner.
  257. /// </summary>
  258. /// <returns>The control that receives the focus adorner.</returns>
  259. protected virtual IControl? GetTemplateFocusTarget() => this;
  260. private static Action loadedProcessingAction = () =>
  261. {
  262. // Copy the loaded queue for processing
  263. // There was a possibility of the "Collection was modified; enumeration operation may not execute."
  264. // exception when only a single hash set was used. This could happen when new controls are added
  265. // within the Loaded callback/event itself. To fix this, two hash sets are used and while one is
  266. // being processed the other accepts adding new controls to process next.
  267. _loadedProcessingQueue.Clear();
  268. foreach (Control control in _loadedQueue)
  269. {
  270. _loadedProcessingQueue.Add(control);
  271. }
  272. _loadedQueue.Clear();
  273. foreach (Control control in _loadedProcessingQueue)
  274. {
  275. control.OnLoadedCore();
  276. }
  277. _loadedProcessingQueue.Clear();
  278. _isLoadedProcessing = false;
  279. // Restart if any controls were added to the queue while processing
  280. if (_loadedQueue.Count > 0)
  281. {
  282. _isLoadedProcessing = true;
  283. Dispatcher.UIThread.Post(loadedProcessingAction!, DispatcherPriority.Loaded);
  284. }
  285. };
  286. /// <summary>
  287. /// Schedules <see cref="OnLoadedCore"/> to be called for this control.
  288. /// For performance, it will be queued with other controls.
  289. /// </summary>
  290. internal void ScheduleOnLoadedCore()
  291. {
  292. if (_isLoaded == false)
  293. {
  294. bool isAdded = _loadedQueue.Add(this);
  295. if (isAdded &&
  296. _isLoadedProcessing == false)
  297. {
  298. _isLoadedProcessing = true;
  299. Dispatcher.UIThread.Post(loadedProcessingAction!, DispatcherPriority.Loaded);
  300. }
  301. }
  302. }
  303. /// <summary>
  304. /// Invoked as the first step of marking the control as loaded and raising the
  305. /// <see cref="Loaded"/> event.
  306. /// </summary>
  307. internal void OnLoadedCore()
  308. {
  309. if (_isLoaded == false &&
  310. ((ILogical)this).IsAttachedToLogicalTree)
  311. {
  312. _isLoaded = true;
  313. OnLoaded();
  314. }
  315. }
  316. /// <summary>
  317. /// Invoked as the first step of marking the control as unloaded and raising the
  318. /// <see cref="Unloaded"/> event.
  319. /// </summary>
  320. internal void OnUnloadedCore()
  321. {
  322. if (_isLoaded)
  323. {
  324. // Remove from the loaded event queue here as a failsafe in case the control
  325. // is detached before the dispatcher runs the Loaded jobs.
  326. _loadedQueue.Remove(this);
  327. _isLoaded = false;
  328. OnUnloaded();
  329. }
  330. }
  331. /// <summary>
  332. /// Invoked just before the <see cref="Loaded"/> event.
  333. /// </summary>
  334. protected virtual void OnLoaded()
  335. {
  336. var eventArgs = new RoutedEventArgs(LoadedEvent);
  337. eventArgs.Source = null;
  338. RaiseEvent(eventArgs);
  339. }
  340. /// <summary>
  341. /// Invoked just before the <see cref="Unloaded"/> event.
  342. /// </summary>
  343. protected virtual void OnUnloaded()
  344. {
  345. var eventArgs = new RoutedEventArgs(UnloadedEvent);
  346. eventArgs.Source = null;
  347. RaiseEvent(eventArgs);
  348. }
  349. /// <inheritdoc/>
  350. protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
  351. {
  352. base.OnAttachedToVisualTreeCore(e);
  353. InitializeIfNeeded();
  354. ScheduleOnLoadedCore();
  355. }
  356. /// <inheritdoc/>
  357. protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
  358. {
  359. base.OnDetachedFromVisualTreeCore(e);
  360. OnUnloadedCore();
  361. }
  362. /// <inheritdoc/>
  363. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  364. {
  365. base.OnAttachedToVisualTree(e);
  366. InvalidateMirrorTransform();
  367. }
  368. /// <inheritdoc/>
  369. protected override void OnGotFocus(GotFocusEventArgs e)
  370. {
  371. base.OnGotFocus(e);
  372. if (IsFocused &&
  373. (e.NavigationMethod == NavigationMethod.Tab ||
  374. e.NavigationMethod == NavigationMethod.Directional))
  375. {
  376. var adornerLayer = AdornerLayer.GetAdornerLayer(this);
  377. if (adornerLayer != null)
  378. {
  379. if (_focusAdorner == null)
  380. {
  381. var template = GetValue(FocusAdornerProperty);
  382. if (template != null)
  383. {
  384. _focusAdorner = template.Build();
  385. }
  386. }
  387. if (_focusAdorner != null && GetTemplateFocusTarget() is Visual target)
  388. {
  389. AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target);
  390. adornerLayer.Children.Add(_focusAdorner);
  391. }
  392. }
  393. }
  394. }
  395. /// <inheritdoc/>
  396. protected override void OnLostFocus(RoutedEventArgs e)
  397. {
  398. base.OnLostFocus(e);
  399. if (_focusAdorner?.Parent != null)
  400. {
  401. var adornerLayer = (IPanel)_focusAdorner.Parent;
  402. adornerLayer.Children.Remove(_focusAdorner);
  403. _focusAdorner = null;
  404. }
  405. }
  406. protected virtual AutomationPeer OnCreateAutomationPeer()
  407. {
  408. return new NoneAutomationPeer(this);
  409. }
  410. internal AutomationPeer GetOrCreateAutomationPeer()
  411. {
  412. VerifyAccess();
  413. if (_automationPeer is object)
  414. {
  415. return _automationPeer;
  416. }
  417. _automationPeer = OnCreateAutomationPeer();
  418. return _automationPeer;
  419. }
  420. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  421. {
  422. base.OnPointerReleased(e);
  423. if (e.Source == this
  424. && !e.Handled
  425. && e.InitialPressMouseButton == MouseButton.Right)
  426. {
  427. var args = new ContextRequestedEventArgs(e);
  428. RaiseEvent(args);
  429. e.Handled = args.Handled;
  430. }
  431. }
  432. protected override void OnKeyUp(KeyEventArgs e)
  433. {
  434. base.OnKeyUp(e);
  435. if (e.Source == this
  436. && !e.Handled)
  437. {
  438. var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>()?.OpenContextMenu;
  439. if (keymap is null)
  440. {
  441. return;
  442. }
  443. var matches = false;
  444. for (var index = 0; index < keymap.Count; index++)
  445. {
  446. var key = keymap[index];
  447. matches |= key.Matches(e);
  448. if (matches)
  449. {
  450. break;
  451. }
  452. }
  453. if (matches)
  454. {
  455. var args = new ContextRequestedEventArgs();
  456. RaiseEvent(args);
  457. e.Handled = args.Handled;
  458. }
  459. }
  460. }
  461. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  462. {
  463. base.OnPropertyChanged(change);
  464. if (change.Property == FlowDirectionProperty)
  465. {
  466. InvalidateMirrorTransform();
  467. foreach (var visual in VisualChildren)
  468. {
  469. if (visual is Control child)
  470. {
  471. child.InvalidateMirrorTransform();
  472. }
  473. }
  474. }
  475. }
  476. /// <summary>
  477. /// Computes the <see cref="IVisual.HasMirrorTransform"/> value according to the
  478. /// <see cref="FlowDirection"/> and <see cref="BypassFlowDirectionPolicies"/>
  479. /// </summary>
  480. public virtual void InvalidateMirrorTransform()
  481. {
  482. var flowDirection = this.FlowDirection;
  483. var parentFlowDirection = FlowDirection.LeftToRight;
  484. bool bypassFlowDirectionPolicies = BypassFlowDirectionPolicies;
  485. bool parentBypassFlowDirectionPolicies = false;
  486. var parent = ((IVisual)this).VisualParent as Control;
  487. if (parent != null)
  488. {
  489. parentFlowDirection = parent.FlowDirection;
  490. parentBypassFlowDirectionPolicies = parent.BypassFlowDirectionPolicies;
  491. }
  492. bool thisShouldBeMirrored = flowDirection == FlowDirection.RightToLeft && !bypassFlowDirectionPolicies;
  493. bool parentShouldBeMirrored = parentFlowDirection == FlowDirection.RightToLeft && !parentBypassFlowDirectionPolicies;
  494. bool shouldApplyMirrorTransform = thisShouldBeMirrored != parentShouldBeMirrored;
  495. HasMirrorTransform = shouldApplyMirrorTransform;
  496. }
  497. }
  498. }