Application.cs 44 KB

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