TopLevel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using System;
  2. using System.Reactive.Linq;
  3. using Avalonia.Controls.Primitives;
  4. using Avalonia.Input;
  5. using Avalonia.Input.Raw;
  6. using Avalonia.Layout;
  7. using Avalonia.Logging;
  8. using Avalonia.LogicalTree;
  9. using Avalonia.Media;
  10. using Avalonia.Platform;
  11. using Avalonia.Rendering;
  12. using Avalonia.Styling;
  13. using Avalonia.Utilities;
  14. using Avalonia.VisualTree;
  15. using JetBrains.Annotations;
  16. namespace Avalonia.Controls
  17. {
  18. /// <summary>
  19. /// Base class for top-level widgets.
  20. /// </summary>
  21. /// <remarks>
  22. /// This class acts as a base for top level widget.
  23. /// It handles scheduling layout, styling and rendering as well as
  24. /// tracking the widget's <see cref="ClientSize"/>.
  25. /// </remarks>
  26. public abstract class TopLevel : ContentControl,
  27. IInputRoot,
  28. ILayoutRoot,
  29. IRenderRoot,
  30. ICloseable,
  31. IStyleHost,
  32. ILogicalRoot,
  33. IWeakSubscriber<ResourcesChangedEventArgs>
  34. {
  35. /// <summary>
  36. /// Defines the <see cref="ClientSize"/> property.
  37. /// </summary>
  38. public static readonly DirectProperty<TopLevel, Size> ClientSizeProperty =
  39. AvaloniaProperty.RegisterDirect<TopLevel, Size>(nameof(ClientSize), o => o.ClientSize);
  40. /// <summary>
  41. /// Defines the <see cref="IInputRoot.PointerOverElement"/> property.
  42. /// </summary>
  43. public static readonly StyledProperty<IInputElement> PointerOverElementProperty =
  44. AvaloniaProperty.Register<TopLevel, IInputElement>(nameof(IInputRoot.PointerOverElement));
  45. /// <summary>
  46. /// Defines the <see cref="TransparencyLevelHint"/> property.
  47. /// </summary>
  48. public static readonly StyledProperty<WindowTransparencyLevel> TransparencyLevelHintProperty =
  49. AvaloniaProperty.Register<TopLevel, WindowTransparencyLevel>(nameof(TransparencyLevelHint), WindowTransparencyLevel.None);
  50. /// <summary>
  51. /// Defines the <see cref="ActualTransparencyLevel"/> property.
  52. /// </summary>
  53. public static readonly DirectProperty<TopLevel, WindowTransparencyLevel> ActualTransparencyLevelProperty =
  54. AvaloniaProperty.RegisterDirect<TopLevel, WindowTransparencyLevel>(nameof(ActualTransparencyLevel),
  55. o => o.ActualTransparencyLevel,
  56. unsetValue: WindowTransparencyLevel.None);
  57. /// <summary>
  58. /// Defines the <see cref="TransparencyBackgroundFallbackProperty"/> property.
  59. /// </summary>
  60. public static readonly StyledProperty<IBrush> TransparencyBackgroundFallbackProperty =
  61. AvaloniaProperty.Register<TopLevel, IBrush>(nameof(TransparencyBackgroundFallback), Brushes.White);
  62. private readonly IInputManager _inputManager;
  63. private readonly IAccessKeyHandler _accessKeyHandler;
  64. private readonly IKeyboardNavigationHandler _keyboardNavigationHandler;
  65. private readonly IPlatformRenderInterface _renderInterface;
  66. private readonly IGlobalStyles _globalStyles;
  67. private Size _clientSize;
  68. private WindowTransparencyLevel _actualTransparencyLevel;
  69. private ILayoutManager _layoutManager;
  70. private Border _transparencyFallbackBorder;
  71. /// <summary>
  72. /// Initializes static members of the <see cref="TopLevel"/> class.
  73. /// </summary>
  74. static TopLevel()
  75. {
  76. AffectsMeasure<TopLevel>(ClientSizeProperty);
  77. TransparencyLevelHintProperty.Changed.AddClassHandler<TopLevel>(
  78. (tl, e) =>
  79. {
  80. if (tl.PlatformImpl != null)
  81. {
  82. tl.PlatformImpl.SetTransparencyLevelHint((WindowTransparencyLevel)e.NewValue);
  83. tl.HandleTransparencyLevelChanged(tl.PlatformImpl.TransparencyLevel);
  84. }
  85. });
  86. }
  87. /// <summary>
  88. /// Initializes a new instance of the <see cref="TopLevel"/> class.
  89. /// </summary>
  90. /// <param name="impl">The platform-specific window implementation.</param>
  91. public TopLevel(ITopLevelImpl impl)
  92. : this(impl, AvaloniaLocator.Current)
  93. {
  94. }
  95. /// <summary>
  96. /// Initializes a new instance of the <see cref="TopLevel"/> class.
  97. /// </summary>
  98. /// <param name="impl">The platform-specific window implementation.</param>
  99. /// <param name="dependencyResolver">
  100. /// The dependency resolver to use. If null the default dependency resolver will be used.
  101. /// </param>
  102. public TopLevel(ITopLevelImpl impl, IAvaloniaDependencyResolver dependencyResolver)
  103. {
  104. if (impl == null)
  105. {
  106. throw new InvalidOperationException(
  107. "Could not create window implementation: maybe no windowing subsystem was initialized?");
  108. }
  109. PlatformImpl = impl;
  110. _actualTransparencyLevel = PlatformImpl.TransparencyLevel;
  111. dependencyResolver = dependencyResolver ?? AvaloniaLocator.Current;
  112. var styler = TryGetService<IStyler>(dependencyResolver);
  113. _accessKeyHandler = TryGetService<IAccessKeyHandler>(dependencyResolver);
  114. _inputManager = TryGetService<IInputManager>(dependencyResolver);
  115. _keyboardNavigationHandler = TryGetService<IKeyboardNavigationHandler>(dependencyResolver);
  116. _renderInterface = TryGetService<IPlatformRenderInterface>(dependencyResolver);
  117. _globalStyles = TryGetService<IGlobalStyles>(dependencyResolver);
  118. Renderer = impl.CreateRenderer(this);
  119. if (Renderer != null)
  120. {
  121. Renderer.SceneInvalidated += SceneInvalidated;
  122. }
  123. impl.SetInputRoot(this);
  124. impl.Closed = HandleClosed;
  125. impl.Input = HandleInput;
  126. impl.Paint = HandlePaint;
  127. impl.Resized = HandleResized;
  128. impl.ScalingChanged = HandleScalingChanged;
  129. impl.TransparencyLevelChanged = HandleTransparencyLevelChanged;
  130. _keyboardNavigationHandler?.SetOwner(this);
  131. _accessKeyHandler?.SetOwner(this);
  132. if (_globalStyles is object)
  133. {
  134. _globalStyles.GlobalStylesAdded += ((IStyleHost)this).StylesAdded;
  135. _globalStyles.GlobalStylesRemoved += ((IStyleHost)this).StylesRemoved;
  136. }
  137. styler?.ApplyStyles(this);
  138. ClientSize = impl.ClientSize;
  139. this.GetObservable(PointerOverElementProperty)
  140. .Select(
  141. x => (x as InputElement)?.GetObservable(CursorProperty) ?? Observable.Empty<Cursor>())
  142. .Switch().Subscribe(cursor => PlatformImpl?.SetCursor(cursor?.PlatformCursor));
  143. if (((IStyleHost)this).StylingParent is IResourceHost applicationResources)
  144. {
  145. WeakSubscriptionManager.Subscribe(
  146. applicationResources,
  147. nameof(IResourceHost.ResourcesChanged),
  148. this);
  149. }
  150. impl.LostFocus += PlatformImpl_LostFocus;
  151. }
  152. /// <summary>
  153. /// Fired when the window is opened.
  154. /// </summary>
  155. public event EventHandler Opened;
  156. /// <summary>
  157. /// Fired when the window is closed.
  158. /// </summary>
  159. public event EventHandler Closed;
  160. /// <summary>
  161. /// Gets or sets the client size of the window.
  162. /// </summary>
  163. public Size ClientSize
  164. {
  165. get { return _clientSize; }
  166. protected set { SetAndRaise(ClientSizeProperty, ref _clientSize, value); }
  167. }
  168. /// <summary>
  169. /// Gets or sets the <see cref="WindowTransparencyLevel"/> that the TopLevel should use when possible.
  170. /// </summary>
  171. public WindowTransparencyLevel TransparencyLevelHint
  172. {
  173. get { return GetValue(TransparencyLevelHintProperty); }
  174. set { SetValue(TransparencyLevelHintProperty, value); }
  175. }
  176. /// <summary>
  177. /// Gets the acheived <see cref="WindowTransparencyLevel"/> that the platform was able to provide.
  178. /// </summary>
  179. public WindowTransparencyLevel ActualTransparencyLevel
  180. {
  181. get => _actualTransparencyLevel;
  182. private set => SetAndRaise(ActualTransparencyLevelProperty, ref _actualTransparencyLevel, value);
  183. }
  184. /// <summary>
  185. /// Gets or sets the <see cref="IBrush"/> that transparency will blend with when transparency is not supported.
  186. /// By default this is a solid white brush.
  187. /// </summary>
  188. public IBrush TransparencyBackgroundFallback
  189. {
  190. get => GetValue(TransparencyBackgroundFallbackProperty);
  191. set => SetValue(TransparencyBackgroundFallbackProperty, value);
  192. }
  193. public ILayoutManager LayoutManager
  194. {
  195. get
  196. {
  197. if (_layoutManager == null)
  198. _layoutManager = CreateLayoutManager();
  199. return _layoutManager;
  200. }
  201. }
  202. /// <summary>
  203. /// Gets the platform-specific window implementation.
  204. /// </summary>
  205. [CanBeNull]
  206. public ITopLevelImpl PlatformImpl { get; private set; }
  207. /// <summary>
  208. /// Gets the renderer for the window.
  209. /// </summary>
  210. public IRenderer Renderer { get; private set; }
  211. /// <summary>
  212. /// Gets the access key handler for the window.
  213. /// </summary>
  214. IAccessKeyHandler IInputRoot.AccessKeyHandler => _accessKeyHandler;
  215. /// <summary>
  216. /// Gets or sets the keyboard navigation handler for the window.
  217. /// </summary>
  218. IKeyboardNavigationHandler IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler;
  219. /// <summary>
  220. /// Gets or sets the input element that the pointer is currently over.
  221. /// </summary>
  222. IInputElement IInputRoot.PointerOverElement
  223. {
  224. get { return GetValue(PointerOverElementProperty); }
  225. set { SetValue(PointerOverElementProperty, value); }
  226. }
  227. /// <inheritdoc/>
  228. IMouseDevice IInputRoot.MouseDevice => PlatformImpl?.MouseDevice;
  229. void IWeakSubscriber<ResourcesChangedEventArgs>.OnEvent(object sender, ResourcesChangedEventArgs e)
  230. {
  231. ((ILogical)this).NotifyResourcesChanged(e);
  232. }
  233. /// <summary>
  234. /// Gets or sets a value indicating whether access keys are shown in the window.
  235. /// </summary>
  236. bool IInputRoot.ShowAccessKeys
  237. {
  238. get { return GetValue(AccessText.ShowAccessKeyProperty); }
  239. set { SetValue(AccessText.ShowAccessKeyProperty, value); }
  240. }
  241. /// <inheritdoc/>
  242. double ILayoutRoot.LayoutScaling => PlatformImpl?.Scaling ?? 1;
  243. /// <inheritdoc/>
  244. double IRenderRoot.RenderScaling => PlatformImpl?.Scaling ?? 1;
  245. IStyleHost IStyleHost.StylingParent => _globalStyles;
  246. IRenderTarget IRenderRoot.CreateRenderTarget() => CreateRenderTarget();
  247. /// <inheritdoc/>
  248. protected virtual IRenderTarget CreateRenderTarget()
  249. {
  250. if(PlatformImpl == null)
  251. throw new InvalidOperationException("Can't create render target, PlatformImpl is null (might be already disposed)");
  252. return _renderInterface.CreateRenderTarget(PlatformImpl.Surfaces);
  253. }
  254. /// <inheritdoc/>
  255. void IRenderRoot.Invalidate(Rect rect)
  256. {
  257. PlatformImpl?.Invalidate(rect);
  258. }
  259. /// <inheritdoc/>
  260. Point IRenderRoot.PointToClient(PixelPoint p)
  261. {
  262. return PlatformImpl?.PointToClient(p) ?? default;
  263. }
  264. /// <inheritdoc/>
  265. PixelPoint IRenderRoot.PointToScreen(Point p)
  266. {
  267. return PlatformImpl?.PointToScreen(p) ?? default;
  268. }
  269. /// <summary>
  270. /// Creates the layout manager for this <see cref="TopLevel" />.
  271. /// </summary>
  272. protected virtual ILayoutManager CreateLayoutManager() => new LayoutManager(this);
  273. /// <summary>
  274. /// Handles a paint notification from <see cref="ITopLevelImpl.Resized"/>.
  275. /// </summary>
  276. /// <param name="rect">The dirty area.</param>
  277. protected virtual void HandlePaint(Rect rect)
  278. {
  279. Renderer?.Paint(rect);
  280. }
  281. /// <summary>
  282. /// Handles a closed notification from <see cref="ITopLevelImpl.Closed"/>.
  283. /// </summary>
  284. protected virtual void HandleClosed()
  285. {
  286. if (_globalStyles is object)
  287. {
  288. _globalStyles.GlobalStylesAdded -= ((IStyleHost)this).StylesAdded;
  289. _globalStyles.GlobalStylesRemoved -= ((IStyleHost)this).StylesRemoved;
  290. }
  291. Renderer?.Dispose();
  292. Renderer = null;
  293. var logicalArgs = new LogicalTreeAttachmentEventArgs(this, this, null);
  294. ((ILogical)this).NotifyDetachedFromLogicalTree(logicalArgs);
  295. var visualArgs = new VisualTreeAttachmentEventArgs(this, this);
  296. OnDetachedFromVisualTreeCore(visualArgs);
  297. (this as IInputRoot).MouseDevice?.TopLevelClosed(this);
  298. PlatformImpl = null;
  299. OnClosed(EventArgs.Empty);
  300. LayoutManager?.Dispose();
  301. }
  302. /// <summary>
  303. /// Handles a resize notification from <see cref="ITopLevelImpl.Resized"/>.
  304. /// </summary>
  305. /// <param name="clientSize">The new client size.</param>
  306. protected virtual void HandleResized(Size clientSize)
  307. {
  308. ClientSize = clientSize;
  309. Width = clientSize.Width;
  310. Height = clientSize.Height;
  311. LayoutManager.ExecuteLayoutPass();
  312. Renderer?.Resized(clientSize);
  313. }
  314. /// <summary>
  315. /// Handles a window scaling change notification from
  316. /// <see cref="ITopLevelImpl.ScalingChanged"/>.
  317. /// </summary>
  318. /// <param name="scaling">The window scaling.</param>
  319. protected virtual void HandleScalingChanged(double scaling)
  320. {
  321. LayoutHelper.InvalidateSelfAndChildrenMeasure(this);
  322. }
  323. private bool TransparencyLevelsMatch (WindowTransparencyLevel requested, WindowTransparencyLevel received)
  324. {
  325. if(requested == received)
  326. {
  327. return true;
  328. }
  329. else if(requested >= WindowTransparencyLevel.Blur && received >= WindowTransparencyLevel.Blur)
  330. {
  331. return true;
  332. }
  333. return false;
  334. }
  335. protected virtual void HandleTransparencyLevelChanged(WindowTransparencyLevel transparencyLevel)
  336. {
  337. if(_transparencyFallbackBorder != null)
  338. {
  339. if(transparencyLevel == WindowTransparencyLevel.None ||
  340. TransparencyLevelHint == WindowTransparencyLevel.None ||
  341. !TransparencyLevelsMatch(TransparencyLevelHint, transparencyLevel))
  342. {
  343. _transparencyFallbackBorder.Background = TransparencyBackgroundFallback;
  344. }
  345. else
  346. {
  347. _transparencyFallbackBorder.Background = null;
  348. }
  349. }
  350. ActualTransparencyLevel = transparencyLevel;
  351. }
  352. /// <inheritdoc/>
  353. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  354. {
  355. base.OnAttachedToVisualTree(e);
  356. throw new InvalidOperationException(
  357. $"Control '{GetType().Name}' is a top level control and cannot be added as a child.");
  358. }
  359. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  360. {
  361. base.OnApplyTemplate(e);
  362. _transparencyFallbackBorder = e.NameScope.Find<Border>("PART_TransparencyFallback");
  363. HandleTransparencyLevelChanged(PlatformImpl.TransparencyLevel);
  364. }
  365. /// <summary>
  366. /// Raises the <see cref="Opened"/> event.
  367. /// </summary>
  368. /// <param name="e">The event args.</param>
  369. protected virtual void OnOpened(EventArgs e) => Opened?.Invoke(this, e);
  370. /// <summary>
  371. /// Raises the <see cref="Closed"/> event.
  372. /// </summary>
  373. /// <param name="e">The event args.</param>
  374. protected virtual void OnClosed(EventArgs e) => Closed?.Invoke(this, e);
  375. /// <summary>
  376. /// Tries to get a service from an <see cref="IAvaloniaDependencyResolver"/>, logging a
  377. /// warning if not found.
  378. /// </summary>
  379. /// <typeparam name="T">The service type.</typeparam>
  380. /// <param name="resolver">The resolver.</param>
  381. /// <returns>The service.</returns>
  382. private T TryGetService<T>(IAvaloniaDependencyResolver resolver) where T : class
  383. {
  384. var result = resolver.GetService<T>();
  385. if (result == null)
  386. {
  387. Logger.TryGet(LogEventLevel.Warning, LogArea.Control)?.Log(
  388. this,
  389. "Could not create {Service} : maybe Application.RegisterServices() wasn't called?",
  390. typeof(T));
  391. }
  392. return result;
  393. }
  394. /// <summary>
  395. /// Handles input from <see cref="ITopLevelImpl.Input"/>.
  396. /// </summary>
  397. /// <param name="e">The event args.</param>
  398. private void HandleInput(RawInputEventArgs e)
  399. {
  400. _inputManager.ProcessInput(e);
  401. }
  402. private void SceneInvalidated(object sender, SceneInvalidatedEventArgs e)
  403. {
  404. (this as IInputRoot).MouseDevice.SceneInvalidated(this, e.DirtyRect);
  405. }
  406. void PlatformImpl_LostFocus()
  407. {
  408. var focused = (IVisual)FocusManager.Instance.Current;
  409. if (focused == null)
  410. return;
  411. while (focused.VisualParent != null)
  412. focused = focused.VisualParent;
  413. if (focused == this)
  414. KeyboardDevice.Instance.SetFocusedElement(null, NavigationMethod.Unspecified, KeyModifiers.None);
  415. }
  416. }
  417. }