Application.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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?.Dispose ();
  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)"/>,
  419. /// followed by <see cref="RunLoop(RunState)"/>, 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)"/> with the wait parameter set to false. By doing this
  425. /// the <see cref="RunLoop(RunState)"/> 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 exceptions 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)"/> will resume; otherwise
  432. /// this method will exit.
  433. /// </para>
  434. /// </remarks>
  435. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</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. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  543. public static void RunLoop (RunState state)
  544. {
  545. if (state == null)
  546. throw new ArgumentNullException (nameof (state));
  547. if (state.Toplevel == null)
  548. throw new ObjectDisposedException ("state");
  549. bool firstIteration = true;
  550. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  551. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  552. return;
  553. }
  554. RunMainLoopIteration (ref state, ref firstIteration);
  555. }
  556. }
  557. /// <summary>
  558. /// Run one iteration of the <see cref="MainLoop"/>.
  559. /// </summary>
  560. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  561. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  562. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  563. public static void RunMainLoopIteration (ref RunState state, ref bool firstIteration)
  564. {
  565. if (MainLoop.EventsPending ()) {
  566. // Notify Toplevel it's ready
  567. if (firstIteration) {
  568. state.Toplevel.OnReady ();
  569. }
  570. MainLoop.RunIteration ();
  571. Iteration?.Invoke ();
  572. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  573. if (state.Toplevel != Current) {
  574. OverlappedTop?.OnDeactivate (state.Toplevel);
  575. state.Toplevel = Current;
  576. OverlappedTop?.OnActivate (state.Toplevel);
  577. Top.SetSubViewNeedsDisplay ();
  578. Refresh ();
  579. } else if (Current.SuperView == null && Current?.Modal == true) {
  580. Refresh ();
  581. }
  582. if (Driver.EnsureCursorVisibility ()) {
  583. state.Toplevel.SetNeedsDisplay ();
  584. }
  585. }
  586. firstIteration = false;
  587. if (state.Toplevel != Top &&
  588. (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded)) {
  589. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  590. Top.Clear ();
  591. Top.Draw ();
  592. foreach (var top in _toplevels.Reverse ()) {
  593. if (top != Top && top != state.Toplevel) {
  594. top.SetNeedsDisplay ();
  595. top.SetSubViewNeedsDisplay ();
  596. top.Clear ();
  597. top.Draw ();
  598. }
  599. }
  600. }
  601. if (_toplevels.Count == 1 && state.Toplevel == Top
  602. && (Driver.Cols != state.Toplevel.Frame.Width || Driver.Rows != state.Toplevel.Frame.Height)
  603. && (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded)) {
  604. state.Toplevel.Clear ();
  605. }
  606. if (state.Toplevel.NeedsDisplay ||
  607. state.Toplevel.SubViewNeedsDisplay ||
  608. state.Toplevel.LayoutNeeded ||
  609. OverlappedChildNeedsDisplay ()) {
  610. state.Toplevel.Clear ();
  611. state.Toplevel.Draw ();
  612. state.Toplevel.PositionCursor ();
  613. Driver.Refresh ();
  614. } else {
  615. Driver.UpdateCursor ();
  616. }
  617. if (state.Toplevel != Top &&
  618. !state.Toplevel.Modal &&
  619. (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded)) {
  620. Top.Draw ();
  621. }
  622. }
  623. ///// <summary>
  624. ///// Wakes up the <see cref="MainLoop"/> that might be waiting on input; must be thread safe.
  625. ///// </summary>
  626. //public static void DoEvents ()
  627. //{
  628. // MainLoop.MainLoopDriver.Wakeup ();
  629. //}
  630. /// <summary>
  631. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  632. /// </summary>
  633. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  634. /// <remarks>
  635. /// <para>
  636. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  637. /// </para>
  638. /// <para>
  639. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property
  640. /// on the currently running <see cref="Toplevel"/> to false.
  641. /// </para>
  642. /// </remarks>
  643. public static void RequestStop (Toplevel top = null)
  644. {
  645. if (OverlappedTop == null || top == null || (OverlappedTop == null && top != null)) {
  646. top = Current;
  647. }
  648. if (OverlappedTop != null && top.IsOverlappedContainer && top?.Running == true
  649. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  650. OverlappedTop.RequestStop ();
  651. } else if (OverlappedTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  652. && top.Modal && top.Running) {
  653. var ev = new ToplevelClosingEventArgs (Current);
  654. Current.OnClosing (ev);
  655. if (ev.Cancel) {
  656. return;
  657. }
  658. ev = new ToplevelClosingEventArgs (top);
  659. top.OnClosing (ev);
  660. if (ev.Cancel) {
  661. return;
  662. }
  663. Current.Running = false;
  664. OnNotifyStopRunState (Current);
  665. top.Running = false;
  666. OnNotifyStopRunState (top);
  667. } else if ((OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  668. && Current?.Running == true && !top.Running)
  669. || (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == false
  670. && Current?.Running == false && !top.Running && _toplevels.ToArray () [1].Running)) {
  671. MoveCurrent (top);
  672. } else if (OverlappedTop != null && Current != top && Current?.Running == true && !top.Running
  673. && Current?.Modal == true && top.Modal) {
  674. // The Current and the top are both modal so needed to set the Current.Running to false too.
  675. Current.Running = false;
  676. OnNotifyStopRunState (Current);
  677. } else if (OverlappedTop != null && Current == top && OverlappedTop?.Running == true && Current?.Running == true && top.Running
  678. && Current?.Modal == true && top.Modal) {
  679. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  680. // both are the same, so needed to set the Current.Running to false too.
  681. Current.Running = false;
  682. OnNotifyStopRunState (Current);
  683. } else {
  684. Toplevel currentTop;
  685. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  686. currentTop = Current;
  687. } else {
  688. currentTop = top;
  689. }
  690. if (!currentTop.Running) {
  691. return;
  692. }
  693. var ev = new ToplevelClosingEventArgs (currentTop);
  694. currentTop.OnClosing (ev);
  695. if (ev.Cancel) {
  696. return;
  697. }
  698. currentTop.Running = false;
  699. OnNotifyStopRunState (currentTop);
  700. }
  701. }
  702. static void OnNotifyStopRunState (Toplevel top)
  703. {
  704. if (ExitRunLoopAfterFirstIteration) {
  705. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  706. }
  707. }
  708. /// <summary>
  709. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  710. /// </summary>
  711. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  712. public static void End (RunState runState)
  713. {
  714. if (runState == null)
  715. throw new ArgumentNullException (nameof (runState));
  716. if (OverlappedTop != null) {
  717. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  718. } else {
  719. runState.Toplevel.OnUnloaded ();
  720. }
  721. // End the RunState.Toplevel
  722. // First, take it off the Toplevel Stack
  723. if (_toplevels.Count > 0) {
  724. if (_toplevels.Peek () != runState.Toplevel) {
  725. // If there the top of the stack is not the RunState.Toplevel then
  726. // this call to End is not balanced with the call to Begin that started the RunState
  727. throw new ArgumentException ("End must be balanced with calls to Begin");
  728. }
  729. _toplevels.Pop ();
  730. }
  731. // Notify that it is closing
  732. runState.Toplevel?.OnClosed (runState.Toplevel);
  733. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  734. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  735. if (OverlappedTop != null && !(runState.Toplevel).Modal && runState.Toplevel != OverlappedTop) {
  736. OverlappedTop.OnChildClosed (runState.Toplevel);
  737. }
  738. // Set Current and Top to the next TopLevel on the stack
  739. if (_toplevels.Count == 0) {
  740. Current = null;
  741. } else {
  742. Current = _toplevels.Peek ();
  743. if (_toplevels.Count == 1 && Current == OverlappedTop) {
  744. OverlappedTop.OnAllChildClosed ();
  745. } else {
  746. SetCurrentOverlappedAsTop ();
  747. runState.Toplevel.OnLeave (Current);
  748. Current.OnEnter (runState.Toplevel);
  749. }
  750. Refresh ();
  751. }
  752. runState.Toplevel?.Dispose ();
  753. runState.Toplevel = null;
  754. runState.Dispose ();
  755. }
  756. #endregion Run (Begin, Run, End)
  757. #region Toplevel handling
  758. static readonly Stack<Toplevel> _toplevels = new Stack<Toplevel> ();
  759. /// <summary>
  760. /// The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)
  761. /// </summary>
  762. /// <value>The top.</value>
  763. public static Toplevel Top { get; private set; }
  764. /// <summary>
  765. /// The current <see cref="Toplevel"/> object. This is updated when <see cref="Application.Run(Func{Exception, bool})"/>
  766. /// enters and leaves to point to the current <see cref="Toplevel"/> .
  767. /// </summary>
  768. /// <value>The current.</value>
  769. public static Toplevel Current { get; private set; }
  770. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  771. {
  772. if (!Toplevel.Running || (Toplevel == Current && Toplevel.Visible) || OverlappedTop == null || _toplevels.Peek ().Modal) {
  773. return;
  774. }
  775. foreach (var top in _toplevels.Reverse ()) {
  776. if (top.Modal && top != Current) {
  777. MoveCurrent (top);
  778. return;
  779. }
  780. }
  781. if (!Toplevel.Visible && Toplevel == Current) {
  782. OverlappedMoveNext ();
  783. }
  784. }
  785. static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  786. {
  787. var startFrame = start.Frame;
  788. if (!startFrame.Contains (x, y)) {
  789. resx = 0;
  790. resy = 0;
  791. return null;
  792. }
  793. if (_toplevels != null) {
  794. int count = _toplevels.Count;
  795. if (count > 0) {
  796. var rx = x - startFrame.X;
  797. var ry = y - startFrame.Y;
  798. foreach (var t in _toplevels) {
  799. if (t != Current) {
  800. if (t != start && t.Visible && t.Frame.Contains (rx, ry)) {
  801. start = t;
  802. break;
  803. }
  804. }
  805. }
  806. }
  807. }
  808. resx = x - startFrame.X;
  809. resy = y - startFrame.Y;
  810. return start;
  811. }
  812. static View FindTopFromView (View view)
  813. {
  814. View top = view?.SuperView != null && view?.SuperView != Top
  815. ? view.SuperView : view;
  816. while (top?.SuperView != null && top?.SuperView != Top) {
  817. top = top.SuperView;
  818. }
  819. return top;
  820. }
  821. // Only return true if the Current has changed.
  822. static bool MoveCurrent (Toplevel top)
  823. {
  824. // The Current is modal and the top is not modal Toplevel then
  825. // the Current must be moved above the first not modal Toplevel.
  826. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Modal == true && !_toplevels.Peek ().Modal) {
  827. lock (_toplevels) {
  828. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  829. }
  830. var index = 0;
  831. var savedToplevels = _toplevels.ToArray ();
  832. foreach (var t in savedToplevels) {
  833. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  834. lock (_toplevels) {
  835. _toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  836. }
  837. }
  838. index++;
  839. }
  840. return false;
  841. }
  842. // The Current and the top are both not running Toplevel then
  843. // the top must be moved above the first not running Toplevel.
  844. if (OverlappedTop != null && top != OverlappedTop && top != Current && Current?.Running == false && !top.Running) {
  845. lock (_toplevels) {
  846. _toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  847. }
  848. var index = 0;
  849. foreach (var t in _toplevels.ToArray ()) {
  850. if (!t.Running && t != Current && index > 0) {
  851. lock (_toplevels) {
  852. _toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  853. }
  854. }
  855. index++;
  856. }
  857. return false;
  858. }
  859. if ((OverlappedTop != null && top?.Modal == true && _toplevels.Peek () != top)
  860. || (OverlappedTop != null && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  861. || (OverlappedTop != null && Current?.Modal == false && top != Current)
  862. || (OverlappedTop != null && Current?.Modal == true && top == OverlappedTop)) {
  863. lock (_toplevels) {
  864. _toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  865. Current = top;
  866. }
  867. }
  868. return true;
  869. }
  870. /// <summary>
  871. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  872. /// </summary>
  873. public static Action<ResizedEventArgs> TerminalResized;
  874. static void OnTerminalResized ()
  875. {
  876. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  877. TerminalResized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  878. foreach (var t in _toplevels) {
  879. t.SetRelativeLayout (full);
  880. t.LayoutSubviews ();
  881. t.PositionToplevels ();
  882. t.OnTerminalResized (new SizeChangedEventArgs (full.Size));
  883. }
  884. Refresh ();
  885. }
  886. #endregion Toplevel handling
  887. #region Mouse handling
  888. /// <summary>
  889. /// Disable or enable the mouse. The mouse is enabled by default.
  890. /// </summary>
  891. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  892. public static bool IsMouseDisabled { get; set; }
  893. /// <summary>
  894. /// The current <see cref="View"/> object that wants continuous mouse button pressed events.
  895. /// </summary>
  896. public static View WantContinuousButtonPressedView { get; private set; }
  897. static View _mouseGrabView;
  898. /// <summary>
  899. /// The view that grabbed the mouse, to where mouse events will be routed to.
  900. /// </summary>
  901. public static View MouseGrabView => _mouseGrabView;
  902. /// <summary>
  903. /// Invoked when a view wants to grab the mouse; can be canceled.
  904. /// </summary>
  905. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  906. /// <summary>
  907. /// Invoked when a view wants ungrab the mouse; can be canceled.
  908. /// </summary>
  909. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  910. /// <summary>
  911. /// Invoked after a view has grabbed the mouse.
  912. /// </summary>
  913. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  914. /// <summary>
  915. /// Invoked after a view has ungrabbed the mouse.
  916. /// </summary>
  917. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  918. /// <summary>
  919. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/> is called.
  920. /// </summary>
  921. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  922. public static void GrabMouse (View view)
  923. {
  924. if (view == null)
  925. return;
  926. if (!OnGrabbingMouse (view)) {
  927. OnGrabbedMouse (view);
  928. _mouseGrabView = view;
  929. //Driver.UncookMouse ();
  930. }
  931. }
  932. /// <summary>
  933. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  934. /// </summary>
  935. public static void UngrabMouse ()
  936. {
  937. if (_mouseGrabView == null)
  938. return;
  939. if (!OnUnGrabbingMouse (_mouseGrabView)) {
  940. OnUnGrabbedMouse (_mouseGrabView);
  941. _mouseGrabView = null;
  942. //Driver.CookMouse ();
  943. }
  944. }
  945. static bool OnGrabbingMouse (View view)
  946. {
  947. if (view == null)
  948. return false;
  949. var evArgs = new GrabMouseEventArgs (view);
  950. GrabbingMouse?.Invoke (view, evArgs);
  951. return evArgs.Cancel;
  952. }
  953. static bool OnUnGrabbingMouse (View view)
  954. {
  955. if (view == null)
  956. return false;
  957. var evArgs = new GrabMouseEventArgs (view);
  958. UnGrabbingMouse?.Invoke (view, evArgs);
  959. return evArgs.Cancel;
  960. }
  961. static void OnGrabbedMouse (View view)
  962. {
  963. if (view == null)
  964. return;
  965. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  966. }
  967. static void OnUnGrabbedMouse (View view)
  968. {
  969. if (view == null)
  970. return;
  971. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  972. }
  973. /// <summary>
  974. /// Merely a debugging aid to see the raw mouse events
  975. /// </summary>
  976. public static Action<MouseEvent> RootMouseEvent;
  977. static View _lastMouseOwnerView;
  978. static void ProcessMouseEvent (MouseEvent me)
  979. {
  980. static bool OutsideBounds (Point p, Rect r) => p.X < 0 || p.X > r.Right || p.Y < 0 || p.Y > r.Bottom;
  981. if (IsMouseDisabled) {
  982. return;
  983. }
  984. var view = View.FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  985. if (view != null && view.WantContinuousButtonPressed) {
  986. WantContinuousButtonPressedView = view;
  987. } else {
  988. WantContinuousButtonPressedView = null;
  989. }
  990. if (view != null) {
  991. me.View = view;
  992. }
  993. RootMouseEvent?.Invoke (me);
  994. if (me.Handled) {
  995. return;
  996. }
  997. if (_mouseGrabView != null) {
  998. var newxy = _mouseGrabView.ScreenToView (me.X, me.Y);
  999. var nme = new MouseEvent () {
  1000. X = newxy.X,
  1001. Y = newxy.Y,
  1002. Flags = me.Flags,
  1003. OfX = me.X - newxy.X,
  1004. OfY = me.Y - newxy.Y,
  1005. View = view
  1006. };
  1007. if (OutsideBounds (new Point (nme.X, nme.Y), _mouseGrabView.Bounds)) {
  1008. _lastMouseOwnerView?.OnMouseLeave (me);
  1009. }
  1010. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1011. if (_mouseGrabView?.OnMouseEvent (nme) == true) {
  1012. return;
  1013. }
  1014. }
  1015. if ((view == null || view == OverlappedTop) && !Current.Modal && OverlappedTop != null
  1016. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  1017. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  1018. view = View.FindDeepestView (top, me.X, me.Y, out rx, out ry);
  1019. if (view != null && view != OverlappedTop && top != Current) {
  1020. MoveCurrent ((Toplevel)top);
  1021. }
  1022. }
  1023. if (view != null) {
  1024. var nme = new MouseEvent () {
  1025. X = rx,
  1026. Y = ry,
  1027. Flags = me.Flags,
  1028. OfX = 0,
  1029. OfY = 0,
  1030. View = view
  1031. };
  1032. if (_lastMouseOwnerView == null) {
  1033. _lastMouseOwnerView = view;
  1034. view.OnMouseEnter (nme);
  1035. } else if (_lastMouseOwnerView != view) {
  1036. _lastMouseOwnerView.OnMouseLeave (nme);
  1037. view.OnMouseEnter (nme);
  1038. _lastMouseOwnerView = view;
  1039. }
  1040. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1041. return;
  1042. if (view.WantContinuousButtonPressed)
  1043. WantContinuousButtonPressedView = view;
  1044. else
  1045. WantContinuousButtonPressedView = null;
  1046. // Should we bubbled up the event, if it is not handled?
  1047. view.OnMouseEvent (nme);
  1048. BringOverlappedTopToFront ();
  1049. }
  1050. }
  1051. #endregion Mouse handling
  1052. #region Keyboard handling
  1053. static Key _alternateForwardKey = Key.PageDown | Key.CtrlMask;
  1054. /// <summary>
  1055. /// Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.
  1056. /// </summary>
  1057. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1058. public static Key AlternateForwardKey {
  1059. get => _alternateForwardKey;
  1060. set {
  1061. if (_alternateForwardKey != value) {
  1062. var oldKey = _alternateForwardKey;
  1063. _alternateForwardKey = value;
  1064. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1065. }
  1066. }
  1067. }
  1068. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1069. {
  1070. foreach (var top in _toplevels.ToArray ()) {
  1071. top.OnAlternateForwardKeyChanged (e);
  1072. }
  1073. }
  1074. static Key _alternateBackwardKey = Key.PageUp | Key.CtrlMask;
  1075. /// <summary>
  1076. /// Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.
  1077. /// </summary>
  1078. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1079. public static Key AlternateBackwardKey {
  1080. get => _alternateBackwardKey;
  1081. set {
  1082. if (_alternateBackwardKey != value) {
  1083. var oldKey = _alternateBackwardKey;
  1084. _alternateBackwardKey = value;
  1085. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1086. }
  1087. }
  1088. }
  1089. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1090. {
  1091. foreach (var top in _toplevels.ToArray ()) {
  1092. top.OnAlternateBackwardKeyChanged (oldKey);
  1093. }
  1094. }
  1095. static Key _quitKey = Key.Q | Key.CtrlMask;
  1096. /// <summary>
  1097. /// Gets or sets the key to quit the application.
  1098. /// </summary>
  1099. [SerializableConfigurationProperty (Scope = typeof (SettingsScope)), JsonConverter (typeof (KeyJsonConverter))]
  1100. public static Key QuitKey {
  1101. get => _quitKey;
  1102. set {
  1103. if (_quitKey != value) {
  1104. var oldKey = _quitKey;
  1105. _quitKey = value;
  1106. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1107. }
  1108. }
  1109. }
  1110. static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1111. {
  1112. // Duplicate the list so if it changes during enumeration we're safe
  1113. foreach (var top in _toplevels.ToArray ()) {
  1114. top.OnQuitKeyChanged (e);
  1115. }
  1116. }
  1117. static void ProcessKeyEvent (KeyEvent ke)
  1118. {
  1119. if (RootKeyEvent?.Invoke (ke) ?? false) {
  1120. return;
  1121. }
  1122. var chain = _toplevels.ToList ();
  1123. foreach (var topLevel in chain) {
  1124. if (topLevel.ProcessHotKey (ke))
  1125. return;
  1126. if (topLevel.Modal)
  1127. break;
  1128. }
  1129. foreach (var topLevel in chain) {
  1130. if (topLevel.ProcessKey (ke))
  1131. return;
  1132. if (topLevel.Modal)
  1133. break;
  1134. }
  1135. foreach (var topLevel in chain) {
  1136. // Process the key normally
  1137. if (topLevel.ProcessColdKey (ke))
  1138. return;
  1139. if (topLevel.Modal)
  1140. break;
  1141. }
  1142. }
  1143. static void ProcessKeyDownEvent (KeyEvent ke)
  1144. {
  1145. var chain = _toplevels.ToList ();
  1146. foreach (var topLevel in chain) {
  1147. if (topLevel.OnKeyDown (ke))
  1148. return;
  1149. if (topLevel.Modal)
  1150. break;
  1151. }
  1152. }
  1153. static void ProcessKeyUpEvent (KeyEvent ke)
  1154. {
  1155. var chain = _toplevels.ToList ();
  1156. foreach (var topLevel in chain) {
  1157. if (topLevel.OnKeyUp (ke))
  1158. return;
  1159. if (topLevel.Modal)
  1160. break;
  1161. }
  1162. }
  1163. /// <summary>
  1164. /// <para>
  1165. /// Called for new KeyPress events before any processing is performed or
  1166. /// views evaluate. Use for global key handling and/or debugging.
  1167. /// </para>
  1168. /// <para>Return true to suppress the KeyPress event</para>
  1169. /// </summary>
  1170. public static Func<KeyEvent, bool> RootKeyEvent;
  1171. #endregion Keyboard handling
  1172. }
  1173. }