Application.cs 49 KB

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