Application.cs 44 KB

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