Application.cs 11 KB

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