Application.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Linq;
  5. using System.Globalization;
  6. using System.Reflection;
  7. using System.IO;
  8. using System.Text.Json.Serialization;
  9. namespace Terminal.Gui {
  10. /// <summary>
  11. /// A static, singleton class representing the application. This class is the entry point for the application.
  12. /// </summary>
  13. /// <example>
  14. /// <code>
  15. /// // A simple Terminal.Gui app that creates a window with a frame and title with
  16. /// // 5 rows/columns of padding.
  17. /// Application.Init();
  18. /// var win = new Window ($"Example App ({Application.QuitKey} to quit)") {
  19. /// X = 5,
  20. /// Y = 5,
  21. /// Width = Dim.Fill (5),
  22. /// Height = Dim.Fill (5)
  23. /// };
  24. /// Application.Top.Add(win);
  25. /// Application.Run();
  26. /// Application.Shutdown();
  27. /// </code>
  28. /// </example>
  29. /// <remarks>
  30. /// <para>
  31. /// Creates a instance of <see cref="Terminal.Gui.MainLoop"/> to process input events, handle timers and
  32. /// other sources of data. It is accessible via the <see cref="MainLoop"/> property.
  33. /// </para>
  34. /// <para>
  35. /// The <see cref="Iteration"/> event is invoked on each iteration of the <see cref="Terminal.Gui.MainLoop"/>.
  36. /// </para>
  37. /// <para>
  38. /// When invoked it sets the <see cref="SynchronizationContext"/> to one that is tied
  39. /// to the <see cref="MainLoop"/>, allowing user code to use async/await.
  40. /// </para>
  41. /// </remarks>
  42. public static partial class Application {
  43. /// <summary>
  44. /// The current <see cref="ConsoleDriver"/> in use.
  45. /// </summary>
  46. public static ConsoleDriver Driver;
  47. /// <summary>
  48. /// If <see langword="true"/>, forces the use of the System.Console-based (see <see cref="NetDriver"/>) driver. The default is <see langword="false"/>.
  49. /// </summary>
  50. public static bool UseSystemConsole { get; set; } = false;
  51. // For Unit testing - ignores UseSystemConsole
  52. internal static bool _forceFakeConsole;
  53. private static List<CultureInfo> _cachedSupportedCultures;
  54. /// <summary>
  55. /// Gets all cultures supported by the application without the invariant language.
  56. /// </summary>
  57. public static List<CultureInfo> SupportedCultures => _cachedSupportedCultures;
  58. private static List<CultureInfo> GetSupportedCultures ()
  59. {
  60. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  61. // Get the assembly
  62. Assembly assembly = Assembly.GetExecutingAssembly ();
  63. //Find the location of the assembly
  64. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  65. // Find the resource file name of the assembly
  66. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  67. // Return all culture for which satellite folder found with culture code.
  68. return culture.Where (cultureInfo =>
  69. assemblyLocation != null &&
  70. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  71. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  72. ).ToList ();
  73. }
  74. #region Initialization (Init/Shutdown)
  75. /// <summary>
  76. /// Initializes a new instance of <see cref="Terminal.Gui"/> Application.
  77. /// </summary>
  78. /// <para>
  79. /// Call this method once per instance (or after <see cref="Shutdown"/> has been called).
  80. /// </para>
  81. /// <para>
  82. /// This function loads the right <see cref="ConsoleDriver"/> for the platform,
  83. /// Creates a <see cref="Toplevel"/>. and assigns it to <see cref="Top"/>
  84. /// </para>
  85. /// <para>
  86. /// <see cref="Shutdown"/> must be called when the application is closing (typically after <see cref="Run(Func{Exception, bool})"/> has
  87. /// returned) to ensure resources are cleaned up and terminal settings restored.
  88. /// </para>
  89. /// <para>
  90. /// The <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver, IMainLoopDriver)"/> function
  91. /// combines <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> and <see cref="Run(Toplevel, Func{Exception, bool})"/>
  92. /// into a single call. An applciation cam use <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver, IMainLoopDriver)"/>
  93. /// without explicitly calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  94. /// </para>
  95. /// <param name="driver">
  96. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  97. /// platform will be used (see <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, and <see cref="NetDriver"/>).</param>
  98. /// <param name="mainLoopDriver">
  99. /// Specifies the <see cref="MainLoop"/> to use.
  100. /// Must not be <see langword="null"/> if <paramref name="driver"/> is not <see langword="null"/>.
  101. /// </param>
  102. public static void Init (ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) => InternalInit (() => Toplevel.Create (), driver, mainLoopDriver);
  103. internal static bool _initialized = false;
  104. internal static int _mainThreadId = -1;
  105. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  106. //
  107. // Called from:
  108. //
  109. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  110. // Run<T>() - When the user wants to use a custom Toplevel. calledViaRunT will be true, enabling Run<T>() to be called without calling Init first.
  111. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  112. //
  113. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  114. internal static void InternalInit (Func<Toplevel> topLevelFactory, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null, bool calledViaRunT = false)
  115. {
  116. if (_initialized && driver == null) {
  117. return;
  118. }
  119. if (_initialized) {
  120. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  121. }
  122. if (!calledViaRunT) {
  123. // Reset all class variables (Application is a singleton).
  124. ResetState ();
  125. }
  126. // For UnitTests
  127. if (driver != null) {
  128. Driver = driver;
  129. }
  130. // Start the process of configuration management.
  131. // Note that we end up calling LoadConfigurationFromAllSources
  132. // multiple times. We need to do this because some settings are only
  133. // valid after a Driver is loaded. In this cases we need just
  134. // `Settings` so we can determine which driver to use.
  135. ConfigurationManager.Load (true);
  136. ConfigurationManager.Apply ();
  137. if (Driver == null) {
  138. var p = Environment.OSVersion.Platform;
  139. if (_forceFakeConsole) {
  140. // For Unit Testing only
  141. Driver = new FakeDriver ();
  142. } else if (UseSystemConsole) {
  143. Driver = new NetDriver ();
  144. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  145. Driver = new WindowsDriver ();
  146. } else {
  147. Driver = new CursesDriver ();
  148. }
  149. if (Driver == null) {
  150. throw new InvalidOperationException ("Init could not determine the ConsoleDriver to use.");
  151. }
  152. }
  153. if (mainLoopDriver == null) {
  154. // TODO: Move this logic into ConsoleDriver
  155. if (Driver is FakeDriver) {
  156. mainLoopDriver = new FakeMainLoop (Driver);
  157. } else if (Driver is NetDriver) {
  158. mainLoopDriver = new NetMainLoop (Driver);
  159. } else if (Driver is WindowsDriver) {
  160. mainLoopDriver = new WindowsMainLoop (Driver);
  161. } else if (Driver is CursesDriver) {
  162. mainLoopDriver = new UnixMainLoop (Driver);
  163. }
  164. if (mainLoopDriver == null) {
  165. throw new InvalidOperationException ("Init could not determine the MainLoopDriver to use.");
  166. }
  167. }
  168. MainLoop = new MainLoop (mainLoopDriver);
  169. try {
  170. Driver.Init (OnTerminalResized);
  171. } catch (InvalidOperationException ex) {
  172. // This is a case where the driver is unable to initialize the console.
  173. // This can happen if the console is already in use by another process or
  174. // if running in unit tests.
  175. // In this case, we want to throw a more specific exception.
  176. throw new InvalidOperationException ("Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.", ex);
  177. }
  178. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  179. Top = topLevelFactory ();
  180. Current = Top;
  181. _cachedSupportedCultures = GetSupportedCultures ();
  182. _mainThreadId = Thread.CurrentThread.ManagedThreadId;
  183. _initialized = true;
  184. }
  185. /// <summary>
  186. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  187. /// </summary>
  188. /// <remarks>
  189. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  190. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  191. /// </remarks>
  192. public static void Shutdown ()
  193. {
  194. ResetState ();
  195. ConfigurationManager.PrintJsonErrors ();
  196. }
  197. // Encapsulate all setting of initial state for Application; Having
  198. // this in a function like this ensures we don't make mistakes in
  199. // guaranteeing that the state of this singleton is deterministic when Init
  200. // starts running and after Shutdown returns.
  201. static void ResetState ()
  202. {
  203. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  204. // Init created. Apps that do any threading will need to code defensively for this.
  205. // e.g. see Issue #537
  206. foreach (var t in _toplevels) {
  207. t.Running = false;
  208. t.Dispose ();
  209. }
  210. _toplevels.Clear ();
  211. Current = null;
  212. Top?.Dispose ();
  213. Top = null;
  214. // BUGBUG: OverlappedTop is not cleared here, but it should be?
  215. MainLoop?.Stop ();
  216. MainLoop = null;
  217. Driver?.End ();
  218. Driver = null;
  219. Iteration = null;
  220. RootMouseEvent = null;
  221. RootKeyEvent = null;
  222. TerminalResized = null;
  223. _mainThreadId = -1;
  224. NotifyNewRunState = null;
  225. NotifyStopRunState = null;
  226. _initialized = false;
  227. _mouseGrabView = null;
  228. _lastMouseOwnerView = null;
  229. // Reset synchronization context to allow the user to run async/await,
  230. // as the main loop has been ended, the synchronization context from
  231. // gui.cs does no longer process any callbacks. See #1084 for more details:
  232. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  233. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  234. }
  235. #endregion Initialization (Init/Shutdown)
  236. #region Run (Begin, Run, End)
  237. /// <summary>
  238. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is created in
  239. /// <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  240. /// </summary>
  241. /// <remarks>
  242. /// If <see cref="ExitRunLoopAfterFirstIteration"/> is <see langword="true"/> callers to
  243. /// <see cref="Begin(Toplevel)"/> must also subscribe to <see cref="NotifyStopRunState"/>
  244. /// and manually dispose of the <see cref="RunState"/> token when the application is done.
  245. /// </remarks>
  246. public static event EventHandler<RunStateEventArgs> NotifyNewRunState;
  247. /// <summary>
  248. /// Notify that a existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).
  249. /// </summary>
  250. /// <remarks>
  251. /// If <see cref="ExitRunLoopAfterFirstIteration"/> is <see langword="true"/> callers to
  252. /// <see cref="Begin(Toplevel)"/> must also subscribe to <see cref="NotifyStopRunState"/>
  253. /// and manually dispose of the <see cref="RunState"/> token when the application is done.
  254. /// </remarks>
  255. public static event EventHandler<ToplevelEventArgs> NotifyStopRunState;
  256. /// <summary>
  257. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  258. /// </summary>
  259. /// <returns>The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  260. /// <param name="Toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  261. /// <remarks>
  262. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus,
  263. /// it adds this to the list of <see cref="Toplevel"/>s, sets up the <see cref="MainLoop"/> to process the
  264. /// event, lays out the Subviews, focuses the first element, and draws the
  265. /// <see cref="Toplevel"/> in the screen. This is usually followed by executing
  266. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  267. /// undo these changes.
  268. /// </remarks>
  269. public static RunState Begin (Toplevel Toplevel)
  270. {
  271. if (Toplevel == null) {
  272. throw new ArgumentNullException (nameof (Toplevel));
  273. } else if (Toplevel.IsOverlappedContainer && OverlappedTop != Toplevel && OverlappedTop != null) {
  274. throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
  275. }
  276. // Ensure the mouse is ungrabed.
  277. _mouseGrabView = null;
  278. var rs = new RunState (Toplevel);
  279. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  280. if (!Toplevel.IsInitialized) {
  281. Toplevel.BeginInit ();
  282. Toplevel.EndInit ();
  283. }
  284. lock (_toplevels) {
  285. // If Top was already initialized with Init, and Begin has never been called
  286. // Top was not added to the Toplevels Stack. It will thus never get disposed.
  287. // Clean it up here:
  288. if (Top != null && Toplevel != Top && !_toplevels.Contains (Top)) {
  289. Top.Dispose ();
  290. Top = null;
  291. } else if (Top != null && Toplevel != Top && _toplevels.Contains (Top)) {
  292. Top.OnLeave (Toplevel);
  293. }
  294. if (string.IsNullOrEmpty (Toplevel.Id)) {
  295. var count = 1;
  296. var id = (_toplevels.Count + count).ToString ();
  297. while (_toplevels.Count > 0 && _toplevels.FirstOrDefault (x => x.Id == id) != null) {
  298. count++;
  299. id = (_toplevels.Count + count).ToString ();
  300. }
  301. Toplevel.Id = (_toplevels.Count + count).ToString ();
  302. _toplevels.Push (Toplevel);
  303. } else {
  304. var dup = _toplevels.FirstOrDefault (x => x.Id == Toplevel.Id);
  305. if (dup == null) {
  306. _toplevels.Push (Toplevel);
  307. }
  308. }
  309. if (_toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  310. throw new ArgumentException ("There are duplicates Toplevels Id's");
  311. }
  312. }
  313. if (Top == null || Toplevel.IsOverlappedContainer) {
  314. Top = Toplevel;
  315. }
  316. var refreshDriver = true;
  317. if (OverlappedTop == null || Toplevel.IsOverlappedContainer || (Current?.Modal == false && Toplevel.Modal)
  318. || (Current?.Modal == false && !Toplevel.Modal) || (Current?.Modal == true && Toplevel.Modal)) {
  319. if (Toplevel.Visible) {
  320. Current = Toplevel;
  321. SetCurrentOverlappedAsTop ();
  322. } else {
  323. refreshDriver = false;
  324. }
  325. } else if ((OverlappedTop != null && Toplevel != OverlappedTop && Current?.Modal == true && !_toplevels.Peek ().Modal)
  326. || (OverlappedTop != null && Toplevel != OverlappedTop && Current?.Running == false)) {
  327. refreshDriver = false;
  328. MoveCurrent (Toplevel);
  329. } else {
  330. refreshDriver = false;
  331. MoveCurrent (Current);
  332. }
  333. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  334. if (Toplevel.LayoutStyle == LayoutStyle.Computed) {
  335. Toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  336. }
  337. Toplevel.LayoutSubviews ();
  338. Toplevel.PositionToplevels ();
  339. Toplevel.FocusFirst ();
  340. if (refreshDriver) {
  341. OverlappedTop?.OnChildLoaded (Toplevel);
  342. Toplevel.OnLoaded ();
  343. Toplevel.SetNeedsDisplay ();
  344. Toplevel.Draw ();
  345. Toplevel.PositionCursor ();
  346. Driver.Refresh ();
  347. }
  348. NotifyNewRunState?.Invoke (Toplevel, new RunStateEventArgs (rs));
  349. return rs;
  350. }
  351. /// <summary>
  352. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  353. /// </summary>
  354. /// <remarks>
  355. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  356. /// </remarks>
  357. public static void Run (Func<Exception, bool> errorHandler = null)
  358. {
  359. Run (Top, errorHandler);
  360. }
  361. /// <summary>
  362. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  363. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  364. /// <para>
  365. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialize the application.
  366. /// </para>
  367. /// <para>
  368. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  369. /// returned) to ensure resources are cleaned up and terminal settings restored.
  370. /// </para>
  371. /// </summary>
  372. /// <remarks>
  373. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  374. /// </remarks>
  375. /// <param name="errorHandler"></param>
  376. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  377. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  378. /// Must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  379. /// </param>
  380. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  381. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  382. {
  383. if (_initialized) {
  384. if (Driver != null) {
  385. // Init() has been called and we have a driver, so just run the app.
  386. var top = new T ();
  387. var type = top.GetType ().BaseType;
  388. while (type != typeof (Toplevel) && type != typeof (object)) {
  389. type = type.BaseType;
  390. }
  391. if (type != typeof (Toplevel)) {
  392. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  393. }
  394. Run (top, errorHandler);
  395. } else {
  396. // This codepath should be impossible because Init(null, null) will select the platform default driver
  397. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  398. }
  399. } else {
  400. // Init() has NOT been called.
  401. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  402. Run (Top, errorHandler);
  403. }
  404. }
  405. /// <summary>
  406. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  407. /// </summary>
  408. /// <remarks>
  409. /// <para>
  410. /// This method is used to start processing events
  411. /// for the main application, but it is also used to
  412. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  413. /// </para>
  414. /// <para>
  415. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  416. /// </para>
  417. /// <para>
  418. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  419. /// and then calling <see cref="End(RunState)"/>.
  420. /// </para>
  421. /// <para>
  422. /// Alternatively, to have a program control the main loop and
  423. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  424. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  425. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  426. /// then return control immediately.
  427. /// </para>
  428. /// <para>
  429. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  430. /// Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  431. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  432. /// this method will exit.
  433. /// </para>
  434. /// </remarks>
  435. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  436. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  437. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  438. {
  439. var resume = true;
  440. while (resume) {
  441. #if !DEBUG
  442. try {
  443. #endif
  444. resume = false;
  445. var runToken = Begin (view);
  446. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  447. // by using NotifyStopRunState event.
  448. RunLoop (runToken);
  449. if (!ExitRunLoopAfterFirstIteration) {
  450. End (runToken);
  451. }
  452. #if !DEBUG
  453. }
  454. catch (Exception error)
  455. {
  456. if (errorHandler == null)
  457. {
  458. throw;
  459. }
  460. resume = errorHandler(error);
  461. }
  462. #endif
  463. }
  464. }
  465. /// <summary>
  466. /// Triggers a refresh of the entire display.
  467. /// </summary>
  468. public static void Refresh ()
  469. {
  470. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  471. Driver.ClearContents ();
  472. View last = null;
  473. foreach (var v in _toplevels.Reverse ()) {
  474. if (v.Visible) {
  475. v.SetNeedsDisplay ();
  476. v.SetSubViewNeedsDisplay ();
  477. v.Draw ();
  478. }
  479. last = v;
  480. }
  481. last?.PositionCursor ();
  482. Driver.Refresh ();
  483. }
  484. /// <summary>
  485. /// This event is raised on each iteration of the <see cref="MainLoop"/>.
  486. /// </summary>
  487. /// <remarks>
  488. /// See also <see cref="Timeout"/>
  489. /// </remarks>
  490. public static Action Iteration;
  491. /// <summary>
  492. /// The <see cref="MainLoop"/> driver for the application
  493. /// </summary>
  494. /// <value>The main loop.</value>
  495. public static MainLoop MainLoop { get; private set; }
  496. /// <summary>
  497. /// Set to true to cause the RunLoop method to exit after the first iterations.
  498. /// Set to false (the default) to cause the RunLoop to continue running until Application.RequestStop() is called.
  499. /// </summary>
  500. public static bool ExitRunLoopAfterFirstIteration { get; set; } = false;
  501. //
  502. // provides the sync context set while executing code in Terminal.Gui, to let
  503. // users use async/await on their code
  504. //
  505. class MainLoopSyncContext : SynchronizationContext {
  506. readonly MainLoop mainLoop;
  507. public MainLoopSyncContext (MainLoop mainLoop)
  508. {
  509. this.mainLoop = mainLoop;
  510. }
  511. public override SynchronizationContext CreateCopy ()
  512. {
  513. return new MainLoopSyncContext (MainLoop);
  514. }
  515. public override void Post (SendOrPostCallback d, object state)
  516. {
  517. mainLoop.AddIdle (() => {
  518. d (state);
  519. return false;
  520. });
  521. //mainLoop.Driver.Wakeup ();
  522. }
  523. public override void Send (SendOrPostCallback d, object state)
  524. {
  525. if (Thread.CurrentThread.ManagedThreadId == _mainThreadId) {
  526. d (state);
  527. } else {
  528. var wasExecuted = false;
  529. mainLoop.Invoke (() => {
  530. d (state);
  531. wasExecuted = true;
  532. });
  533. while (!wasExecuted) {
  534. Thread.Sleep (15);
  535. }
  536. }
  537. }
  538. }
  539. /// <summary>
  540. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  541. /// </summary>
  542. /// <remarks>
  543. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  544. /// </remarks>
  545. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  546. /// <param name="wait">By default this is <see langword="true"/> which will execute the loop waiting for events,
  547. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  548. public static void RunLoop (RunState state, bool wait = true)
  549. {
  550. if (state == null)
  551. throw new ArgumentNullException (nameof (state));
  552. if (state.Toplevel == null)
  553. throw new ObjectDisposedException ("state");
  554. bool firstIteration = true;
  555. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  556. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  557. return;
  558. }
  559. RunMainLoopIteration (ref state, wait, ref firstIteration);
  560. }
  561. }
  562. /// <summary>
  563. /// Run one iteration of the <see cref="MainLoop"/>.
  564. /// </summary>
  565. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  566. /// <param name="wait">If <see langword="true"/> will execute the <see cref="MainLoop"/> waiting for events. If <see langword="true"/>
  567. /// will return after a single iteration.</param>
  568. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  569. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  570. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  571. {
  572. if (MainLoop.EventsPending (wait)) {
  573. // Notify Toplevel it's ready
  574. if (firstIteration) {
  575. state.Toplevel.OnReady ();
  576. }
  577. MainLoop.RunIteration ();
  578. Iteration?.Invoke ();
  579. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  580. if (state.Toplevel != Current) {
  581. OverlappedTop?.OnDeactivate (state.Toplevel);
  582. state.Toplevel = Current;
  583. OverlappedTop?.OnActivate (state.Toplevel);
  584. Top.SetSubViewNeedsDisplay ();
  585. Refresh ();
  586. } else if (Current.SuperView == null && Current?.Modal == true) {
  587. Refresh ();
  588. }
  589. if (Driver.EnsureCursorVisibility ()) {
  590. state.Toplevel.SetNeedsDisplay ();
  591. }
  592. } else if (!wait) {
  593. return;
  594. }
  595. firstIteration = false;
  596. if (state.Toplevel != Top &&
  597. (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded)) {
  598. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  599. Top.Clear ();
  600. Top.Draw ();
  601. foreach (var top in _toplevels.Reverse ()) {
  602. if (top != Top && top != state.Toplevel) {
  603. top.SetNeedsDisplay ();
  604. top.SetSubViewNeedsDisplay ();
  605. top.Clear ();
  606. top.Draw ();
  607. }
  608. }
  609. }
  610. if (_toplevels.Count == 1 && state.Toplevel == Top
  611. && (Driver.Cols != state.Toplevel.Frame.Width || Driver.Rows != state.Toplevel.Frame.Height)
  612. && (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded)) {
  613. state.Toplevel.Clear ();
  614. }
  615. if (state.Toplevel.NeedsDisplay ||
  616. state.Toplevel.SubViewNeedsDisplay ||
  617. state.Toplevel.LayoutNeeded ||
  618. OverlappedChildNeedsDisplay ()) {
  619. state.Toplevel.Clear ();
  620. state.Toplevel.Draw ();
  621. state.Toplevel.PositionCursor ();
  622. Driver.Refresh ();
  623. } else {
  624. Driver.UpdateCursor ();
  625. }
  626. if (state.Toplevel != Top &&
  627. !state.Toplevel.Modal &&
  628. (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded)) {
  629. Top.Draw ();
  630. }
  631. }
  632. /// <summary>
  633. /// Wakes up the <see cref="MainLoop"/> that might be waiting on input; must be thread safe.
  634. /// </summary>
  635. public static void DoEvents ()
  636. {
  637. MainLoop.MainLoopDriver.Wakeup ();
  638. }
  639. /// <summary>
  640. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  641. /// </summary>
  642. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  643. /// <remarks>
  644. /// <para>
  645. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  646. /// </para>
  647. /// <para>
  648. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property
  649. /// on the currently running <see cref="Toplevel"/> to false.
  650. /// </para>
  651. /// </remarks>
  652. public static void RequestStop (Toplevel top = null)
  653. {
  654. if (OverlappedTop == null || top == null || (OverlappedTop == null && top != null)) {
  655. top = Current;
  656. }
  657. if (OverlappedTop != null && top.IsOverlappedContainer && top?.Running == true
  658. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  659. OverlappedTop.RequestStop ();
  660. } else if (OverlappedTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  661. && top.Modal && top.Running) {
  662. var ev = new ToplevelClosingEventArgs (Current);
  663. Current.OnClosing (ev);
  664. if (ev.Cancel) {
  665. return;
  666. }
  667. ev = new ToplevelClosingEventArgs (top);
  668. top.OnClosing (ev);
  669. if (ev.Cancel) {
  670. return;
  671. }
  672. Current.Running = false;
  673. OnNotifyStopRunState (Current);
  674. top.Running = false;
  675. OnNotifyStopRunState (top);
  676. } else if ((OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  677. && Current?.Running == true && !top.Running)
  678. || (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  679. && Current?.Running == false && !top.Running && _toplevels.ToArray () [1].Running)) {
  680. MoveCurrent (top);
  681. } else if (OverlappedTop != null && Current != top && Current?.Running == true && !top.Running
  682. && Current?.Modal == true && top.Modal) {
  683. // The Current and the top are both modal so needed to set the Current.Running to false too.
  684. Current.Running = false;
  685. OnNotifyStopRunState (Current);
  686. } else if (OverlappedTop != null && Current == top && OverlappedTop?.Running == true && Current?.Running == true && top.Running
  687. && Current?.Modal == true && top.Modal) {
  688. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  689. // both are the same, so needed to set the Current.Running to false too.
  690. Current.Running = false;
  691. OnNotifyStopRunState (Current);
  692. } else {
  693. Toplevel currentTop;
  694. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  695. currentTop = Current;
  696. } else {
  697. currentTop = top;
  698. }
  699. if (!currentTop.Running) {
  700. return;
  701. }
  702. var ev = new ToplevelClosingEventArgs (currentTop);
  703. currentTop.OnClosing (ev);
  704. if (ev.Cancel) {
  705. return;
  706. }
  707. currentTop.Running = false;
  708. OnNotifyStopRunState (currentTop);
  709. }
  710. }
  711. static void OnNotifyStopRunState (Toplevel top)
  712. {
  713. if (ExitRunLoopAfterFirstIteration) {
  714. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  715. }
  716. }
  717. /// <summary>
  718. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  719. /// </summary>
  720. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  721. public static void End (RunState runState)
  722. {
  723. if (runState == null)
  724. throw new ArgumentNullException (nameof (runState));
  725. if (OverlappedTop != null) {
  726. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  727. } else {
  728. runState.Toplevel.OnUnloaded ();
  729. }
  730. // End the RunState.Toplevel
  731. // First, take it off the Toplevel Stack
  732. if (_toplevels.Count > 0) {
  733. if (_toplevels.Peek () != runState.Toplevel) {
  734. // If there the top of the stack is not the RunState.Toplevel then
  735. // this call to End is not balanced with the call to Begin that started the RunState
  736. throw new ArgumentException ("End must be balanced with calls to Begin");
  737. }
  738. _toplevels.Pop ();
  739. }
  740. // Notify that it is closing
  741. runState.Toplevel?.OnClosed (runState.Toplevel);
  742. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  743. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  744. if (OverlappedTop != null && !(runState.Toplevel).Modal && runState.Toplevel != OverlappedTop) {
  745. OverlappedTop.OnChildClosed (runState.Toplevel);
  746. }
  747. // Set Current and Top to the next TopLevel on the stack
  748. if (_toplevels.Count == 0) {
  749. Current = null;
  750. } else {
  751. Current = _toplevels.Peek ();
  752. if (_toplevels.Count == 1 && Current == OverlappedTop) {
  753. OverlappedTop.OnAllChildClosed ();
  754. } else {
  755. SetCurrentOverlappedAsTop ();
  756. runState.Toplevel.OnLeave (Current);
  757. Current.OnEnter (runState.Toplevel);
  758. }
  759. Refresh ();
  760. }
  761. runState.Toplevel?.Dispose ();
  762. runState.Toplevel = null;
  763. runState.Dispose ();
  764. }
  765. #endregion Run (Begin, Run, End)
  766. #region Toplevel handling
  767. static readonly Stack<Toplevel> _toplevels = new Stack<Toplevel> ();
  768. /// <summary>
  769. /// The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)
  770. /// </summary>
  771. /// <value>The top.</value>
  772. public static Toplevel Top { get; private set; }
  773. /// <summary>
  774. /// The current <see cref="Toplevel"/> object. This is updated when <see cref="Application.Run(Func{Exception, bool})"/>
  775. /// enters and leaves to point to the current <see cref="Toplevel"/> .
  776. /// </summary>
  777. /// <value>The current.</value>
  778. public static Toplevel Current { get; private set; }
  779. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  780. {
  781. if (!Toplevel.Running || (Toplevel == Current && Toplevel.Visible) || OverlappedTop == null || _toplevels.Peek ().Modal) {
  782. return;
  783. }
  784. foreach (var top in _toplevels.Reverse ()) {
  785. if (top.Modal && top != Current) {
  786. MoveCurrent (top);
  787. return;
  788. }
  789. }
  790. if (!Toplevel.Visible && Toplevel == Current) {
  791. OverlappedMoveNext ();
  792. }
  793. }
  794. static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  795. {
  796. var startFrame = start.Frame;
  797. if (!startFrame.Contains (x, y)) {
  798. resx = 0;
  799. resy = 0;
  800. return null;
  801. }
  802. if (_toplevels != null) {
  803. int count = _toplevels.Count;
  804. if (count > 0) {
  805. var rx = x - startFrame.X;
  806. var ry = y - startFrame.Y;
  807. foreach (var t in _toplevels) {
  808. if (t != Current) {
  809. if (t != start && t.Visible && t.Frame.Contains (rx, ry)) {
  810. start = t;
  811. break;
  812. }
  813. }
  814. }
  815. }
  816. }
  817. resx = x - startFrame.X;
  818. resy = y - startFrame.Y;
  819. return start;
  820. }
  821. static View FindTopFromView (View view)
  822. {
  823. View top = view?.SuperView != null && view?.SuperView != Top
  824. ? view.SuperView : view;
  825. while (top?.SuperView != null && top?.SuperView != Top) {
  826. top = top.SuperView;
  827. }
  828. return top;
  829. }
  830. // Only return true if the Current has changed.
  831. static bool MoveCurrent (Toplevel top)
  832. {
  833. // The Current is modal and the top is not modal Toplevel then
  834. // the Current must be moved above the first not modal Toplevel.
  835. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == true && !_toplevels.Peek ().Modal) {
  836. lock (_toplevels) {
  837. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  838. }
  839. var index = 0;
  840. var savedToplevels = _toplevels.ToArray ();
  841. foreach (var t in savedToplevels) {
  842. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  843. lock (_toplevels) {
  844. _toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  845. }
  846. }
  847. index++;
  848. }
  849. return false;
  850. }
  851. // The Current and the top are both not running Toplevel then
  852. // the top must be moved above the first not running Toplevel.
  853. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Running == false && !top.Running) {
  854. lock (_toplevels) {
  855. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  856. }
  857. var index = 0;
  858. foreach (var t in _toplevels.ToArray ()) {
  859. if (!t.Running && t != Current && index > 0) {
  860. lock (_toplevels) {
  861. _toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  862. }
  863. }
  864. index++;
  865. }
  866. return false;
  867. }
  868. if ((OverlappedTop != null && top?.Modal == true && _toplevels.Peek () != top)
  869. || (OverlappedTop != null && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  870. || (OverlappedTop != null && Current?.Modal == false && top != Current)
  871. || (OverlappedTop != null && Current?.Modal == true && top == OverlappedTop)) {
  872. lock (_toplevels) {
  873. _toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  874. Current = top;
  875. }
  876. }
  877. return true;
  878. }
  879. /// <summary>
  880. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  881. /// </summary>
  882. public static Action<ResizedEventArgs> TerminalResized;
  883. static void OnTerminalResized ()
  884. {
  885. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  886. TerminalResized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  887. foreach (var t in _toplevels) {
  888. t.SetRelativeLayout (full);
  889. t.LayoutSubviews ();
  890. t.PositionToplevels ();
  891. t.OnTerminalResized (new SizeChangedEventArgs (full.Size));
  892. }
  893. Refresh ();
  894. }
  895. #endregion Toplevel handling
  896. #region Mouse handling
  897. /// <summary>
  898. /// Disable or enable the mouse. The mouse is enabled by default.
  899. /// </summary>
  900. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  901. public static bool IsMouseDisabled { get; set; }
  902. /// <summary>
  903. /// The current <see cref="View"/> object that wants continuous mouse button pressed events.
  904. /// </summary>
  905. public static View WantContinuousButtonPressedView { get; private set; }
  906. static View _mouseGrabView;
  907. /// <summary>
  908. /// The view that grabbed the mouse, to where mouse events will be routed to.
  909. /// </summary>
  910. public static View MouseGrabView => _mouseGrabView;
  911. /// <summary>
  912. /// Invoked when a view wants to grab the mouse; can be canceled.
  913. /// </summary>
  914. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  915. /// <summary>
  916. /// Invoked when a view wants ungrab the mouse; can be canceled.
  917. /// </summary>
  918. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  919. /// <summary>
  920. /// Invoked after a view has grabbed the mouse.
  921. /// </summary>
  922. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  923. /// <summary>
  924. /// Invoked after a view has ungrabbed the mouse.
  925. /// </summary>
  926. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  927. /// <summary>
  928. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/> is called.
  929. /// </summary>
  930. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  931. public static void GrabMouse (View view)
  932. {
  933. if (view == null)
  934. return;
  935. if (!OnGrabbingMouse (view)) {
  936. OnGrabbedMouse (view);
  937. _mouseGrabView = view;
  938. //Driver.UncookMouse ();
  939. }
  940. }
  941. /// <summary>
  942. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  943. /// </summary>
  944. public static void UngrabMouse ()
  945. {
  946. if (_mouseGrabView == null)
  947. return;
  948. if (!OnUnGrabbingMouse (_mouseGrabView)) {
  949. OnUnGrabbedMouse (_mouseGrabView);
  950. _mouseGrabView = null;
  951. //Driver.CookMouse ();
  952. }
  953. }
  954. static bool OnGrabbingMouse (View view)
  955. {
  956. if (view == null)
  957. return false;
  958. var evArgs = new GrabMouseEventArgs (view);
  959. GrabbingMouse?.Invoke (view, evArgs);
  960. return evArgs.Cancel;
  961. }
  962. static bool OnUnGrabbingMouse (View view)
  963. {
  964. if (view == null)
  965. return false;
  966. var evArgs = new GrabMouseEventArgs (view);
  967. UnGrabbingMouse?.Invoke (view, evArgs);
  968. return evArgs.Cancel;
  969. }
  970. static void OnGrabbedMouse (View view)
  971. {
  972. if (view == null)
  973. return;
  974. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  975. }
  976. static void OnUnGrabbedMouse (View view)
  977. {
  978. if (view == null)
  979. return;
  980. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  981. }
  982. /// <summary>
  983. /// Merely a debugging aid to see the raw mouse events
  984. /// </summary>
  985. public static Action<MouseEvent> RootMouseEvent;
  986. static View _lastMouseOwnerView;
  987. static void ProcessMouseEvent (MouseEvent me)
  988. {
  989. static bool OutsideBounds (Point p, Rect r) => p.X < 0 || p.X > r.Right || p.Y < 0 || p.Y > r.Bottom;
  990. if (IsMouseDisabled) {
  991. return;
  992. }
  993. var view = View.FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  994. if (view != null && view.WantContinuousButtonPressed) {
  995. WantContinuousButtonPressedView = view;
  996. } else {
  997. WantContinuousButtonPressedView = null;
  998. }
  999. if (view != null) {
  1000. me.View = view;
  1001. }
  1002. RootMouseEvent?.Invoke (me);
  1003. if (me.Handled) {
  1004. return;
  1005. }
  1006. if (_mouseGrabView != null) {
  1007. var newxy = _mouseGrabView.ScreenToView (me.X, me.Y);
  1008. var nme = new MouseEvent () {
  1009. X = newxy.X,
  1010. Y = newxy.Y,
  1011. Flags = me.Flags,
  1012. OfX = me.X - newxy.X,
  1013. OfY = me.Y - newxy.Y,
  1014. View = view
  1015. };
  1016. if (OutsideBounds (new Point (nme.X, nme.Y), _mouseGrabView.Bounds)) {
  1017. _lastMouseOwnerView?.OnMouseLeave (me);
  1018. }
  1019. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1020. if (_mouseGrabView?.OnMouseEvent (nme) == true) {
  1021. return;
  1022. }
  1023. }
  1024. if ((view == null || view == OverlappedTop) && !Current.Modal && OverlappedTop != null
  1025. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1026. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  1027. view = View.FindDeepestView (top, me.X, me.Y, out rx, out ry);
  1028. if (view != null && view != OverlappedTop && top != Current) {
  1029. MoveCurrent ((Toplevel)top);
  1030. }
  1031. }
  1032. if (view != null) {
  1033. var nme = new MouseEvent () {
  1034. X = rx,
  1035. Y = ry,
  1036. Flags = me.Flags,
  1037. OfX = 0,
  1038. OfY = 0,
  1039. View = view
  1040. };
  1041. if (_lastMouseOwnerView == null) {
  1042. _lastMouseOwnerView = view;
  1043. view.OnMouseEnter (nme);
  1044. } else if (_lastMouseOwnerView != view) {
  1045. _lastMouseOwnerView.OnMouseLeave (nme);
  1046. view.OnMouseEnter (nme);
  1047. _lastMouseOwnerView = view;
  1048. }
  1049. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1050. return;
  1051. if (view.WantContinuousButtonPressed)
  1052. WantContinuousButtonPressedView = view;
  1053. else
  1054. WantContinuousButtonPressedView = null;
  1055. // Should we bubbled up the event, if it is not handled?
  1056. view.OnMouseEvent (nme);
  1057. BringOverlappedTopToFront ();
  1058. }
  1059. }
  1060. #endregion Mouse handling
  1061. #region Keyboard handling
  1062. static Key _alternateForwardKey = Key.PageDown | Key.CtrlMask;
  1063. /// <summary>
  1064. /// Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.
  1065. /// </summary>
  1066. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1067. public static Key AlternateForwardKey {
  1068. get => _alternateForwardKey;
  1069. set {
  1070. if (_alternateForwardKey != value) {
  1071. var oldKey = _alternateForwardKey;
  1072. _alternateForwardKey = value;
  1073. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1074. }
  1075. }
  1076. }
  1077. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1078. {
  1079. foreach (var top in _toplevels.ToArray ()) {
  1080. top.OnAlternateForwardKeyChanged (e);
  1081. }
  1082. }
  1083. static Key _alternateBackwardKey = Key.PageUp | Key.CtrlMask;
  1084. /// <summary>
  1085. /// Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.
  1086. /// </summary>
  1087. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1088. public static Key AlternateBackwardKey {
  1089. get => _alternateBackwardKey;
  1090. set {
  1091. if (_alternateBackwardKey != value) {
  1092. var oldKey = _alternateBackwardKey;
  1093. _alternateBackwardKey = value;
  1094. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1095. }
  1096. }
  1097. }
  1098. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1099. {
  1100. foreach (var top in _toplevels.ToArray ()) {
  1101. top.OnAlternateBackwardKeyChanged (oldKey);
  1102. }
  1103. }
  1104. static Key _quitKey = Key.Q | Key.CtrlMask;
  1105. /// <summary>
  1106. /// Gets or sets the key to quit the application.
  1107. /// </summary>
  1108. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1109. public static Key QuitKey {
  1110. get => _quitKey;
  1111. set {
  1112. if (_quitKey != value) {
  1113. var oldKey = _quitKey;
  1114. _quitKey = value;
  1115. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1116. }
  1117. }
  1118. }
  1119. static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1120. {
  1121. // Duplicate the list so if it changes during enumeration we're safe
  1122. foreach (var top in _toplevels.ToArray ()) {
  1123. top.OnQuitKeyChanged (e);
  1124. }
  1125. }
  1126. static void ProcessKeyEvent (KeyEvent ke)
  1127. {
  1128. if (RootKeyEvent?.Invoke (ke) ?? false) {
  1129. return;
  1130. }
  1131. var chain = _toplevels.ToList ();
  1132. foreach (var topLevel in chain) {
  1133. if (topLevel.ProcessHotKey (ke))
  1134. return;
  1135. if (topLevel.Modal)
  1136. break;
  1137. }
  1138. foreach (var topLevel in chain) {
  1139. if (topLevel.ProcessKey (ke))
  1140. return;
  1141. if (topLevel.Modal)
  1142. break;
  1143. }
  1144. foreach (var topLevel in chain) {
  1145. // Process the key normally
  1146. if (topLevel.ProcessColdKey (ke))
  1147. return;
  1148. if (topLevel.Modal)
  1149. break;
  1150. }
  1151. }
  1152. static void ProcessKeyDownEvent (KeyEvent ke)
  1153. {
  1154. var chain = _toplevels.ToList ();
  1155. foreach (var topLevel in chain) {
  1156. if (topLevel.OnKeyDown (ke))
  1157. return;
  1158. if (topLevel.Modal)
  1159. break;
  1160. }
  1161. }
  1162. static void ProcessKeyUpEvent (KeyEvent ke)
  1163. {
  1164. var chain = _toplevels.ToList ();
  1165. foreach (var topLevel in chain) {
  1166. if (topLevel.OnKeyUp (ke))
  1167. return;
  1168. if (topLevel.Modal)
  1169. break;
  1170. }
  1171. }
  1172. /// <summary>
  1173. /// <para>
  1174. /// Called for new KeyPress events before any processing is performed or
  1175. /// views evaluate. Use for global key handling and/or debugging.
  1176. /// </para>
  1177. /// <para>Return true to suppress the KeyPress event</para>
  1178. /// </summary>
  1179. public static Func<KeyEvent, bool> RootKeyEvent;
  1180. #endregion Keyboard handling
  1181. }
  1182. }