Application.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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. Current.OnEnter (Current);
  757. }
  758. Refresh ();
  759. }
  760. runState.Toplevel?.Dispose ();
  761. runState.Toplevel = null;
  762. runState.Dispose ();
  763. }
  764. #endregion Run (Begin, Run, End)
  765. #region Toplevel handling
  766. static readonly Stack<Toplevel> _toplevels = new Stack<Toplevel> ();
  767. /// <summary>
  768. /// The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)
  769. /// </summary>
  770. /// <value>The top.</value>
  771. public static Toplevel Top { get; private set; }
  772. /// <summary>
  773. /// The current <see cref="Toplevel"/> object. This is updated when <see cref="Application.Run(Func{Exception, bool})"/>
  774. /// enters and leaves to point to the current <see cref="Toplevel"/> .
  775. /// </summary>
  776. /// <value>The current.</value>
  777. public static Toplevel Current { get; private set; }
  778. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  779. {
  780. if (!Toplevel.Running || (Toplevel == Current && Toplevel.Visible) || OverlappedTop == null || _toplevels.Peek ().Modal) {
  781. return;
  782. }
  783. foreach (var top in _toplevels.Reverse ()) {
  784. if (top.Modal && top != Current) {
  785. MoveCurrent (top);
  786. return;
  787. }
  788. }
  789. if (!Toplevel.Visible && Toplevel == Current) {
  790. OverlappedMoveNext ();
  791. }
  792. }
  793. static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  794. {
  795. var startFrame = start.Frame;
  796. if (!startFrame.Contains (x, y)) {
  797. resx = 0;
  798. resy = 0;
  799. return null;
  800. }
  801. if (_toplevels != null) {
  802. int count = _toplevels.Count;
  803. if (count > 0) {
  804. var rx = x - startFrame.X;
  805. var ry = y - startFrame.Y;
  806. foreach (var t in _toplevels) {
  807. if (t != Current) {
  808. if (t != start && t.Visible && t.Frame.Contains (rx, ry)) {
  809. start = t;
  810. break;
  811. }
  812. }
  813. }
  814. }
  815. }
  816. resx = x - startFrame.X;
  817. resy = y - startFrame.Y;
  818. return start;
  819. }
  820. static View FindTopFromView (View view)
  821. {
  822. View top = view?.SuperView != null && view?.SuperView != Top
  823. ? view.SuperView : view;
  824. while (top?.SuperView != null && top?.SuperView != Top) {
  825. top = top.SuperView;
  826. }
  827. return top;
  828. }
  829. // Only return true if the Current has changed.
  830. static bool MoveCurrent (Toplevel top)
  831. {
  832. // The Current is modal and the top is not modal Toplevel then
  833. // the Current must be moved above the first not modal Toplevel.
  834. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == true && !_toplevels.Peek ().Modal) {
  835. lock (_toplevels) {
  836. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  837. }
  838. var index = 0;
  839. var savedToplevels = _toplevels.ToArray ();
  840. foreach (var t in savedToplevels) {
  841. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  842. lock (_toplevels) {
  843. _toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  844. }
  845. }
  846. index++;
  847. }
  848. return false;
  849. }
  850. // The Current and the top are both not running Toplevel then
  851. // the top must be moved above the first not running Toplevel.
  852. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Running == false && !top.Running) {
  853. lock (_toplevels) {
  854. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  855. }
  856. var index = 0;
  857. foreach (var t in _toplevels.ToArray ()) {
  858. if (!t.Running && t != Current && index > 0) {
  859. lock (_toplevels) {
  860. _toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  861. }
  862. }
  863. index++;
  864. }
  865. return false;
  866. }
  867. if ((OverlappedTop != null && top?.Modal == true && _toplevels.Peek () != top)
  868. || (OverlappedTop != null && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  869. || (OverlappedTop != null && Current?.Modal == false && top != Current)
  870. || (OverlappedTop != null && Current?.Modal == true && top == OverlappedTop)) {
  871. lock (_toplevels) {
  872. _toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  873. Current = top;
  874. }
  875. }
  876. return true;
  877. }
  878. /// <summary>
  879. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  880. /// </summary>
  881. public static Action<ResizedEventArgs> TerminalResized;
  882. static void OnTerminalResized ()
  883. {
  884. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  885. TerminalResized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  886. foreach (var t in _toplevels) {
  887. t.SetRelativeLayout (full);
  888. t.LayoutSubviews ();
  889. t.PositionToplevels ();
  890. t.OnTerminalResized (new SizeChangedEventArgs (full.Size));
  891. }
  892. Refresh ();
  893. }
  894. #endregion Toplevel handling
  895. #region Mouse handling
  896. /// <summary>
  897. /// Disable or enable the mouse. The mouse is enabled by default.
  898. /// </summary>
  899. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  900. public static bool IsMouseDisabled { get; set; }
  901. /// <summary>
  902. /// The current <see cref="View"/> object that wants continuous mouse button pressed events.
  903. /// </summary>
  904. public static View WantContinuousButtonPressedView { get; private set; }
  905. static View _mouseGrabView;
  906. /// <summary>
  907. /// The view that grabbed the mouse, to where mouse events will be routed to.
  908. /// </summary>
  909. public static View MouseGrabView => _mouseGrabView;
  910. /// <summary>
  911. /// Invoked when a view wants to grab the mouse; can be canceled.
  912. /// </summary>
  913. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  914. /// <summary>
  915. /// Invoked when a view wants ungrab the mouse; can be canceled.
  916. /// </summary>
  917. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  918. /// <summary>
  919. /// Invoked after a view has grabbed the mouse.
  920. /// </summary>
  921. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  922. /// <summary>
  923. /// Invoked after a view has ungrabbed the mouse.
  924. /// </summary>
  925. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  926. /// <summary>
  927. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/> is called.
  928. /// </summary>
  929. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  930. public static void GrabMouse (View view)
  931. {
  932. if (view == null)
  933. return;
  934. if (!OnGrabbingMouse (view)) {
  935. OnGrabbedMouse (view);
  936. _mouseGrabView = view;
  937. //Driver.UncookMouse ();
  938. }
  939. }
  940. /// <summary>
  941. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  942. /// </summary>
  943. public static void UngrabMouse ()
  944. {
  945. if (_mouseGrabView == null)
  946. return;
  947. if (!OnUnGrabbingMouse (_mouseGrabView)) {
  948. OnUnGrabbedMouse (_mouseGrabView);
  949. _mouseGrabView = null;
  950. //Driver.CookMouse ();
  951. }
  952. }
  953. static bool OnGrabbingMouse (View view)
  954. {
  955. if (view == null)
  956. return false;
  957. var evArgs = new GrabMouseEventArgs (view);
  958. GrabbingMouse?.Invoke (view, evArgs);
  959. return evArgs.Cancel;
  960. }
  961. static bool OnUnGrabbingMouse (View view)
  962. {
  963. if (view == null)
  964. return false;
  965. var evArgs = new GrabMouseEventArgs (view);
  966. UnGrabbingMouse?.Invoke (view, evArgs);
  967. return evArgs.Cancel;
  968. }
  969. static void OnGrabbedMouse (View view)
  970. {
  971. if (view == null)
  972. return;
  973. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  974. }
  975. static void OnUnGrabbedMouse (View view)
  976. {
  977. if (view == null)
  978. return;
  979. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  980. }
  981. /// <summary>
  982. /// Merely a debugging aid to see the raw mouse events
  983. /// </summary>
  984. public static Action<MouseEvent> RootMouseEvent;
  985. static View _lastMouseOwnerView;
  986. static void ProcessMouseEvent (MouseEvent me)
  987. {
  988. static bool OutsideBounds (Point p, Rect r) => p.X < 0 || p.X > r.Right || p.Y < 0 || p.Y > r.Bottom;
  989. if (IsMouseDisabled) {
  990. return;
  991. }
  992. var view = View.FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  993. if (view != null && view.WantContinuousButtonPressed) {
  994. WantContinuousButtonPressedView = view;
  995. } else {
  996. WantContinuousButtonPressedView = null;
  997. }
  998. if (view != null) {
  999. me.View = view;
  1000. }
  1001. RootMouseEvent?.Invoke (me);
  1002. if (me.Handled) {
  1003. return;
  1004. }
  1005. if (_mouseGrabView != null) {
  1006. var newxy = _mouseGrabView.ScreenToView (me.X, me.Y);
  1007. var nme = new MouseEvent () {
  1008. X = newxy.X,
  1009. Y = newxy.Y,
  1010. Flags = me.Flags,
  1011. OfX = me.X - newxy.X,
  1012. OfY = me.Y - newxy.Y,
  1013. View = view
  1014. };
  1015. if (OutsideBounds (new Point (nme.X, nme.Y), _mouseGrabView.Bounds)) {
  1016. _lastMouseOwnerView?.OnMouseLeave (me);
  1017. }
  1018. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1019. if (_mouseGrabView?.OnMouseEvent (nme) == true) {
  1020. return;
  1021. }
  1022. }
  1023. if ((view == null || view == OverlappedTop) && !Current.Modal && OverlappedTop != null
  1024. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1025. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  1026. view = View.FindDeepestView (top, me.X, me.Y, out rx, out ry);
  1027. if (view != null && view != OverlappedTop && top != Current) {
  1028. MoveCurrent ((Toplevel)top);
  1029. }
  1030. }
  1031. if (view != null) {
  1032. var nme = new MouseEvent () {
  1033. X = rx,
  1034. Y = ry,
  1035. Flags = me.Flags,
  1036. OfX = 0,
  1037. OfY = 0,
  1038. View = view
  1039. };
  1040. if (_lastMouseOwnerView == null) {
  1041. _lastMouseOwnerView = view;
  1042. view.OnMouseEnter (nme);
  1043. } else if (_lastMouseOwnerView != view) {
  1044. _lastMouseOwnerView.OnMouseLeave (nme);
  1045. view.OnMouseEnter (nme);
  1046. _lastMouseOwnerView = view;
  1047. }
  1048. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1049. return;
  1050. if (view.WantContinuousButtonPressed)
  1051. WantContinuousButtonPressedView = view;
  1052. else
  1053. WantContinuousButtonPressedView = null;
  1054. // Should we bubbled up the event, if it is not handled?
  1055. view.OnMouseEvent (nme);
  1056. BringOverlappedTopToFront ();
  1057. }
  1058. }
  1059. #endregion Mouse handling
  1060. #region Keyboard handling
  1061. static Key _alternateForwardKey = Key.PageDown | Key.CtrlMask;
  1062. /// <summary>
  1063. /// Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.
  1064. /// </summary>
  1065. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1066. public static Key AlternateForwardKey {
  1067. get => _alternateForwardKey;
  1068. set {
  1069. if (_alternateForwardKey != value) {
  1070. var oldKey = _alternateForwardKey;
  1071. _alternateForwardKey = value;
  1072. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1073. }
  1074. }
  1075. }
  1076. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1077. {
  1078. foreach (var top in _toplevels.ToArray ()) {
  1079. top.OnAlternateForwardKeyChanged (e);
  1080. }
  1081. }
  1082. static Key _alternateBackwardKey = Key.PageUp | Key.CtrlMask;
  1083. /// <summary>
  1084. /// Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.
  1085. /// </summary>
  1086. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1087. public static Key AlternateBackwardKey {
  1088. get => _alternateBackwardKey;
  1089. set {
  1090. if (_alternateBackwardKey != value) {
  1091. var oldKey = _alternateBackwardKey;
  1092. _alternateBackwardKey = value;
  1093. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1094. }
  1095. }
  1096. }
  1097. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1098. {
  1099. foreach (var top in _toplevels.ToArray ()) {
  1100. top.OnAlternateBackwardKeyChanged (oldKey);
  1101. }
  1102. }
  1103. static Key _quitKey = Key.Q | Key.CtrlMask;
  1104. /// <summary>
  1105. /// Gets or sets the key to quit the application.
  1106. /// </summary>
  1107. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1108. public static Key QuitKey {
  1109. get => _quitKey;
  1110. set {
  1111. if (_quitKey != value) {
  1112. var oldKey = _quitKey;
  1113. _quitKey = value;
  1114. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1115. }
  1116. }
  1117. }
  1118. static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1119. {
  1120. // Duplicate the list so if it changes during enumeration we're safe
  1121. foreach (var top in _toplevels.ToArray ()) {
  1122. top.OnQuitKeyChanged (e);
  1123. }
  1124. }
  1125. static void ProcessKeyEvent (KeyEvent ke)
  1126. {
  1127. if (RootKeyEvent?.Invoke (ke) ?? false) {
  1128. return;
  1129. }
  1130. var chain = _toplevels.ToList ();
  1131. foreach (var topLevel in chain) {
  1132. if (topLevel.ProcessHotKey (ke))
  1133. return;
  1134. if (topLevel.Modal)
  1135. break;
  1136. }
  1137. foreach (var topLevel in chain) {
  1138. if (topLevel.ProcessKey (ke))
  1139. return;
  1140. if (topLevel.Modal)
  1141. break;
  1142. }
  1143. foreach (var topLevel in chain) {
  1144. // Process the key normally
  1145. if (topLevel.ProcessColdKey (ke))
  1146. return;
  1147. if (topLevel.Modal)
  1148. break;
  1149. }
  1150. }
  1151. static void ProcessKeyDownEvent (KeyEvent ke)
  1152. {
  1153. var chain = _toplevels.ToList ();
  1154. foreach (var topLevel in chain) {
  1155. if (topLevel.OnKeyDown (ke))
  1156. return;
  1157. if (topLevel.Modal)
  1158. break;
  1159. }
  1160. }
  1161. static void ProcessKeyUpEvent (KeyEvent ke)
  1162. {
  1163. var chain = _toplevels.ToList ();
  1164. foreach (var topLevel in chain) {
  1165. if (topLevel.OnKeyUp (ke))
  1166. return;
  1167. if (topLevel.Modal)
  1168. break;
  1169. }
  1170. }
  1171. /// <summary>
  1172. /// <para>
  1173. /// Called for new KeyPress events before any processing is performed or
  1174. /// views evaluate. Use for global key handling and/or debugging.
  1175. /// </para>
  1176. /// <para>Return true to suppress the KeyPress event</para>
  1177. /// </summary>
  1178. public static Func<KeyEvent, bool> RootKeyEvent;
  1179. #endregion Keyboard handling
  1180. }
  1181. }