Application.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Reactive.Concurrency;
  5. using System.Threading;
  6. using Avalonia.Controls;
  7. using Avalonia.Controls.Templates;
  8. using Avalonia.Input;
  9. using Avalonia.Input.Platform;
  10. using Avalonia.Input.Raw;
  11. using Avalonia.Layout;
  12. using Avalonia.Platform;
  13. using Avalonia.Styling;
  14. using Avalonia.Threading;
  15. namespace Avalonia
  16. {
  17. /// <summary>
  18. /// Encapsulates a Avalonia application.
  19. /// </summary>
  20. /// <remarks>
  21. /// The <see cref="Application"/> class encapsulates Avalonia application-specific
  22. /// functionality, including:
  23. /// - A global set of <see cref="DataTemplates"/>.
  24. /// - A global set of <see cref="Styles"/>.
  25. /// - A <see cref="FocusManager"/>.
  26. /// - An <see cref="InputManager"/>.
  27. /// - Registers services needed by the rest of Avalonia in the <see cref="RegisterServices"/>
  28. /// method.
  29. /// - Tracks the lifetime of the application.
  30. /// </remarks>
  31. public class Application : IApplicationLifecycle, IGlobalDataTemplates, IGlobalStyles, IStyleRoot, IResourceNode
  32. {
  33. /// <summary>
  34. /// The application-global data templates.
  35. /// </summary>
  36. private DataTemplates _dataTemplates;
  37. private readonly Lazy<IClipboard> _clipboard =
  38. new Lazy<IClipboard>(() => (IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)));
  39. private readonly Styler _styler = new Styler();
  40. private Styles _styles;
  41. private IResourceDictionary _resources;
  42. private CancellationTokenSource _mainLoopCancellationTokenSource;
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="Application"/> class.
  45. /// </summary>
  46. public Application()
  47. {
  48. Windows = new WindowCollection(this);
  49. OnExit += OnExiting;
  50. }
  51. /// <inheritdoc/>
  52. public event EventHandler<ResourcesChangedEventArgs> ResourcesChanged;
  53. /// <summary>
  54. /// Gets the current instance of the <see cref="Application"/> class.
  55. /// </summary>
  56. /// <value>
  57. /// The current instance of the <see cref="Application"/> class.
  58. /// </value>
  59. public static Application Current
  60. {
  61. get { return AvaloniaLocator.Current.GetService<Application>(); }
  62. }
  63. /// <summary>
  64. /// Gets or sets the application's global data templates.
  65. /// </summary>
  66. /// <value>
  67. /// The application's global data templates.
  68. /// </value>
  69. public DataTemplates DataTemplates => _dataTemplates ?? (_dataTemplates = new DataTemplates());
  70. /// <summary>
  71. /// Gets the application's focus manager.
  72. /// </summary>
  73. /// <value>
  74. /// The application's focus manager.
  75. /// </value>
  76. public IFocusManager FocusManager
  77. {
  78. get;
  79. private set;
  80. }
  81. /// <summary>
  82. /// Gets the application's input manager.
  83. /// </summary>
  84. /// <value>
  85. /// The application's input manager.
  86. /// </value>
  87. public InputManager InputManager
  88. {
  89. get;
  90. private set;
  91. }
  92. /// <summary>
  93. /// Gets the application clipboard.
  94. /// </summary>
  95. public IClipboard Clipboard => _clipboard.Value;
  96. /// <summary>
  97. /// Gets the application's global resource dictionary.
  98. /// </summary>
  99. public IResourceDictionary Resources
  100. {
  101. get => _resources ?? (Resources = new ResourceDictionary());
  102. set
  103. {
  104. Contract.Requires<ArgumentNullException>(value != null);
  105. var hadResources = false;
  106. if (_resources != null)
  107. {
  108. hadResources = _resources.Count > 0;
  109. _resources.ResourcesChanged -= ResourcesChanged;
  110. }
  111. _resources = value;
  112. _resources.ResourcesChanged += ResourcesChanged;
  113. if (hadResources || _resources.Count > 0)
  114. {
  115. ResourcesChanged?.Invoke(this, new ResourcesChangedEventArgs());
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// Gets the application's global styles.
  121. /// </summary>
  122. /// <value>
  123. /// The application's global styles.
  124. /// </value>
  125. /// <remarks>
  126. /// Global styles apply to all windows in the application.
  127. /// </remarks>
  128. public Styles Styles => _styles ?? (_styles = new Styles());
  129. /// <inheritdoc/>
  130. bool IDataTemplateHost.IsDataTemplatesInitialized => _dataTemplates != null;
  131. /// <summary>
  132. /// Gets the styling parent of the application, which is null.
  133. /// </summary>
  134. IStyleHost IStyleHost.StylingParent => null;
  135. /// <inheritdoc/>
  136. bool IStyleHost.IsStylesInitialized => _styles != null;
  137. /// <inheritdoc/>
  138. bool IResourceProvider.HasResources => _resources?.Count > 0;
  139. /// <inheritdoc/>
  140. IResourceNode IResourceNode.ResourceParent => null;
  141. /// <summary>
  142. /// Gets or sets the <see cref="ExitMode"/>. This property indicates whether the application exits explicitly or implicitly.
  143. /// If <see cref="ExitMode"/> is set to OnExplicitExit the application is only closes if Exit is called.
  144. /// The default is OnLastWindowClose
  145. /// </summary>
  146. /// <value>
  147. /// The shutdown mode.
  148. /// </value>
  149. public ExitMode ExitMode { get; set; }
  150. /// <summary>
  151. /// Gets or sets the main window of the application.
  152. /// </summary>
  153. /// <value>
  154. /// The main window.
  155. /// </value>
  156. public Window MainWindow { get; set; }
  157. /// <summary>
  158. /// Gets the open windows of the application.
  159. /// </summary>
  160. /// <value>
  161. /// The windows.
  162. /// </value>
  163. public WindowCollection Windows { get; }
  164. /// <summary>
  165. /// Gets or sets a value indicating whether this instance is existing.
  166. /// </summary>
  167. /// <value>
  168. /// <c>true</c> if this instance is existing; otherwise, <c>false</c>.
  169. /// </value>
  170. internal bool IsExiting { get; set; }
  171. /// <summary>
  172. /// Initializes the application by loading XAML etc.
  173. /// </summary>
  174. public virtual void Initialize()
  175. {
  176. }
  177. /// <summary>
  178. /// Runs the application's main loop until the <see cref="ICloseable"/> is closed.
  179. /// </summary>
  180. /// <param name="closable">The closable to track</param>
  181. public void Run(ICloseable closable)
  182. {
  183. if (_mainLoopCancellationTokenSource != null)
  184. {
  185. throw new Exception("Run should only called once");
  186. }
  187. closable.Closed += (s, e) => Exit();
  188. _mainLoopCancellationTokenSource = new CancellationTokenSource();
  189. Dispatcher.UIThread.MainLoop(_mainLoopCancellationTokenSource.Token);
  190. // Make sure we call OnExit in case an error happened and Exit() wasn't called explicitly
  191. if (!IsExiting)
  192. {
  193. OnExit?.Invoke(this, EventArgs.Empty);
  194. }
  195. }
  196. /// <summary>
  197. /// Runs the application's main loop until some condition occurs that is specified by ExitMode.
  198. /// </summary>
  199. /// <param name="mainWindow">The main window</param>
  200. public void Run(Window mainWindow)
  201. {
  202. if (_mainLoopCancellationTokenSource != null)
  203. {
  204. throw new Exception("Run should only called once");
  205. }
  206. _mainLoopCancellationTokenSource = new CancellationTokenSource();
  207. if (MainWindow == null)
  208. {
  209. if (mainWindow == null)
  210. {
  211. throw new ArgumentNullException(nameof(mainWindow));
  212. }
  213. if (!mainWindow.IsVisible)
  214. {
  215. mainWindow.Show();
  216. }
  217. MainWindow = mainWindow;
  218. }
  219. Dispatcher.UIThread.MainLoop(_mainLoopCancellationTokenSource.Token);
  220. // Make sure we call OnExit in case an error happened and Exit() wasn't called explicitly
  221. if (!IsExiting)
  222. {
  223. OnExit?.Invoke(this, EventArgs.Empty);
  224. }
  225. }
  226. /// <summary>
  227. /// Runs the application's main loop until the <see cref="CancellationToken"/> is canceled.
  228. /// </summary>
  229. /// <param name="token">The token to track</param>
  230. public void Run(CancellationToken token)
  231. {
  232. Dispatcher.UIThread.MainLoop(token);
  233. // Make sure we call OnExit in case an error happened and Exit() wasn't called explicitly
  234. if (!IsExiting)
  235. {
  236. OnExit?.Invoke(this, EventArgs.Empty);
  237. }
  238. }
  239. /// <summary>
  240. /// Exits the application
  241. /// </summary>
  242. public void Exit()
  243. {
  244. IsExiting = true;
  245. Windows.Clear();
  246. OnExit?.Invoke(this, EventArgs.Empty);
  247. _mainLoopCancellationTokenSource?.Cancel();
  248. }
  249. /// <inheritdoc/>
  250. bool IResourceProvider.TryGetResource(string key, out object value)
  251. {
  252. value = null;
  253. return (_resources?.TryGetResource(key, out value) ?? false) ||
  254. Styles.TryGetResource(key, out value);
  255. }
  256. /// <summary>
  257. /// Sent when the application is exiting.
  258. /// </summary>
  259. public event EventHandler OnExit;
  260. /// <summary>
  261. /// Called when the application is exiting.
  262. /// </summary>
  263. /// <param name="sender"></param>
  264. /// <param name="e"></param>
  265. protected virtual void OnExiting(object sender, EventArgs e)
  266. {
  267. }
  268. /// <summary>
  269. /// Register's the services needed by Avalonia.
  270. /// </summary>
  271. public virtual void RegisterServices()
  272. {
  273. AvaloniaSynchronizationContext.InstallIfNeeded();
  274. FocusManager = new FocusManager();
  275. InputManager = new InputManager();
  276. AvaloniaLocator.CurrentMutable
  277. .Bind<IAccessKeyHandler>().ToTransient<AccessKeyHandler>()
  278. .Bind<IGlobalDataTemplates>().ToConstant(this)
  279. .Bind<IGlobalStyles>().ToConstant(this)
  280. .Bind<IFocusManager>().ToConstant(FocusManager)
  281. .Bind<IInputManager>().ToConstant(InputManager)
  282. .Bind<IKeyboardNavigationHandler>().ToTransient<KeyboardNavigationHandler>()
  283. .Bind<IStyler>().ToConstant(_styler)
  284. .Bind<IApplicationLifecycle>().ToConstant(this)
  285. .Bind<IScheduler>().ToConstant(AvaloniaScheduler.Instance)
  286. .Bind<IDragDropDevice>().ToConstant(DragDropDevice.Instance)
  287. .Bind<IPlatformDragSource>().ToTransient<InProcessDragSource>();
  288. }
  289. }
  290. }