Application.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  1. using System.Diagnostics;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using System.Text.Json.Serialization;
  5. namespace Terminal.Gui;
  6. /// <summary>A static, singleton class representing the application. This class is the entry point for the application.</summary>
  7. /// <example>
  8. /// <code>
  9. /// // A simple Terminal.Gui app that creates a window with a frame and title with
  10. /// // 5 rows/columns of padding.
  11. /// Application.Init();
  12. /// var win = new Window ($"Example App ({Application.QuitKey} to quit)") {
  13. /// X = 5,
  14. /// Y = 5,
  15. /// Width = Dim.Fill (5),
  16. /// Height = Dim.Fill (5)
  17. /// };
  18. /// Application.Top.Add(win);
  19. /// Application.Run();
  20. /// Application.Shutdown();
  21. /// </code>
  22. /// </example>
  23. /// <remarks>TODO: Flush this out.</remarks>
  24. public static partial class Application
  25. {
  26. // For Unit testing - ignores UseSystemConsole
  27. internal static bool _forceFakeConsole;
  28. /// <summary>Gets the <see cref="ConsoleDriver"/> that has been selected. See also <see cref="ForceDriver"/>.</summary>
  29. public static ConsoleDriver Driver { get; internal set; }
  30. /// <summary>
  31. /// Gets or sets whether <see cref="Application.Driver"/> will be forced to output only the 16 colors defined in
  32. /// <see cref="ColorName"/>. The default is <see langword="false"/>, meaning 24-bit (TrueColor) colors will be output
  33. /// as long as the selected <see cref="ConsoleDriver"/> supports TrueColor.
  34. /// </summary>
  35. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  36. public static bool Force16Colors { get; set; }
  37. /// <summary>
  38. /// Forces the use of the specified driver (one of "fake", "ansi", "curses", "net", or "windows"). If not
  39. /// specified, the driver is selected based on the platform.
  40. /// </summary>
  41. /// <remarks>
  42. /// Note, <see cref="Application.Init(ConsoleDriver, string)"/> will override this configuration setting if called
  43. /// with either `driver` or `driverName` specified.
  44. /// </remarks>
  45. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  46. public static string ForceDriver { get; set; } = string.Empty;
  47. /// <summary>Gets all cultures supported by the application without the invariant language.</summary>
  48. public static List<CultureInfo> SupportedCultures { get; private set; }
  49. internal static List<CultureInfo> GetSupportedCultures ()
  50. {
  51. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  52. // Get the assembly
  53. var assembly = Assembly.GetExecutingAssembly ();
  54. //Find the location of the assembly
  55. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  56. // Find the resource file name of the assembly
  57. var resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  58. // Return all culture for which satellite folder found with culture code.
  59. return culture.Where (
  60. cultureInfo =>
  61. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  62. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  63. )
  64. .ToList ();
  65. }
  66. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  67. // Encapsulate all setting of initial state for Application; Having
  68. // this in a function like this ensures we don't make mistakes in
  69. // guaranteeing that the state of this singleton is deterministic when Init
  70. // starts running and after Shutdown returns.
  71. internal static void ResetState ()
  72. {
  73. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  74. // Init created. Apps that do any threading will need to code defensively for this.
  75. // e.g. see Issue #537
  76. foreach (Toplevel t in _topLevels)
  77. {
  78. t.Running = false;
  79. #if DEBUG_IDISPOSABLE
  80. // Don't dispose the tolevels. It's up to caller dispose them
  81. Debug.Assert (t.WasDisposed);
  82. #endif
  83. }
  84. _topLevels.Clear ();
  85. Current = null;
  86. #if DEBUG_IDISPOSABLE
  87. // Don't dispose the Top. It's up to caller dispose it
  88. if (Top is { })
  89. {
  90. Debug.Assert (Top.WasDisposed);
  91. // If End wasn't called _latestClosedRunStateToplevel may be null
  92. if (_latestClosedRunStateToplevel is { })
  93. {
  94. Debug.Assert (_latestClosedRunStateToplevel.WasDisposed);
  95. Debug.Assert (_latestClosedRunStateToplevel == Top);
  96. }
  97. }
  98. #endif
  99. Top = null;
  100. _latestClosedRunStateToplevel = null;
  101. // MainLoop stuff
  102. MainLoop?.Dispose ();
  103. MainLoop = null;
  104. _mainThreadId = -1;
  105. Iteration = null;
  106. EndAfterFirstIteration = false;
  107. // Driver stuff
  108. if (Driver is { })
  109. {
  110. Driver.SizeChanged -= Driver_SizeChanged;
  111. Driver.KeyDown -= Driver_KeyDown;
  112. Driver.KeyUp -= Driver_KeyUp;
  113. Driver.MouseEvent -= Driver_MouseEvent;
  114. Driver?.End ();
  115. Driver = null;
  116. }
  117. // Don't reset ForceDriver; it needs to be set before Init is called.
  118. //ForceDriver = string.Empty;
  119. Force16Colors = false;
  120. _forceFakeConsole = false;
  121. // Run State stuff
  122. NotifyNewRunState = null;
  123. NotifyStopRunState = null;
  124. MouseGrabView = null;
  125. _initialized = false;
  126. // Mouse
  127. _mouseEnteredView = null;
  128. WantContinuousButtonPressedView = null;
  129. MouseEvent = null;
  130. GrabbedMouse = null;
  131. UnGrabbingMouse = null;
  132. GrabbedMouse = null;
  133. UnGrabbedMouse = null;
  134. // Keyboard
  135. AlternateBackwardKey = Key.Empty;
  136. AlternateForwardKey = Key.Empty;
  137. QuitKey = Key.Empty;
  138. KeyDown = null;
  139. KeyUp = null;
  140. SizeChanging = null;
  141. Colors.Reset ();
  142. // Reset synchronization context to allow the user to run async/await,
  143. // as the main loop has been ended, the synchronization context from
  144. // gui.cs does no longer process any callbacks. See #1084 for more details:
  145. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  146. SynchronizationContext.SetSynchronizationContext (null);
  147. }
  148. #region Initialization (Init/Shutdown)
  149. /// <summary>Initializes a new instance of <see cref="Terminal.Gui"/> Application.</summary>
  150. /// <para>Call this method once per instance (or after <see cref="Shutdown"/> has been called).</para>
  151. /// <para>
  152. /// This function loads the right <see cref="ConsoleDriver"/> for the platform, Creates a <see cref="Toplevel"/>. and
  153. /// assigns it to <see cref="Top"/>
  154. /// </para>
  155. /// <para>
  156. /// <see cref="Shutdown"/> must be called when the application is closing (typically after
  157. /// <see cref="Run(Func{Exception, bool}, ConsoleDriver)"/> has returned) to ensure resources are cleaned up and terminal settings
  158. /// restored.
  159. /// </para>
  160. /// <para>
  161. /// The <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver)"/> function combines
  162. /// <see cref="Init(ConsoleDriver, string)"/> and <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> into a single
  163. /// call. An application cam use <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver)"/> without explicitly calling
  164. /// <see cref="Init(ConsoleDriver, string)"/>.
  165. /// </para>
  166. /// <param name="driver">
  167. /// The <see cref="ConsoleDriver"/> to use. If neither <paramref name="driver"/> or
  168. /// <paramref name="driverName"/> are specified the default driver for the platform will be used.
  169. /// </param>
  170. /// <param name="driverName">
  171. /// The short name (e.g. "net", "windows", "ansi", "fake", or "curses") of the
  172. /// <see cref="ConsoleDriver"/> to use. If neither <paramref name="driver"/> or <paramref name="driverName"/> are
  173. /// specified the default driver for the platform will be used.
  174. /// </param>
  175. public static void Init (ConsoleDriver driver = null, string driverName = null) { InternalInit (driver, driverName); }
  176. internal static bool _initialized;
  177. internal static int _mainThreadId = -1;
  178. // INTERNAL function for initializing an app with a Toplevel factory object, driver, and mainloop.
  179. //
  180. // Called from:
  181. //
  182. // Init() - When the user wants to use the default Toplevel. calledViaRunT will be false, causing all state to be reset.
  183. // 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.
  184. // Unit Tests - To initialize the app with a custom Toplevel, using the FakeDriver. calledViaRunT will be false, causing all state to be reset.
  185. //
  186. // calledViaRunT: If false (default) all state will be reset. If true the state will not be reset.
  187. internal static void InternalInit (
  188. ConsoleDriver driver = null,
  189. string driverName = null,
  190. bool calledViaRunT = false
  191. )
  192. {
  193. if (_initialized && driver is null)
  194. {
  195. return;
  196. }
  197. if (_initialized)
  198. {
  199. throw new InvalidOperationException ("Init has already been called and must be bracketed by Shutdown.");
  200. }
  201. if (!calledViaRunT)
  202. {
  203. // Reset all class variables (Application is a singleton).
  204. ResetState ();
  205. }
  206. // For UnitTests
  207. if (driver is { })
  208. {
  209. Driver = driver;
  210. }
  211. // Start the process of configuration management.
  212. // Note that we end up calling LoadConfigurationFromAllSources
  213. // multiple times. We need to do this because some settings are only
  214. // valid after a Driver is loaded. In this cases we need just
  215. // `Settings` so we can determine which driver to use.
  216. Load (true);
  217. Apply ();
  218. // Ignore Configuration for ForceDriver if driverName is specified
  219. if (!string.IsNullOrEmpty (driverName))
  220. {
  221. ForceDriver = driverName;
  222. }
  223. if (Driver is null)
  224. {
  225. PlatformID p = Environment.OSVersion.Platform;
  226. if (string.IsNullOrEmpty (ForceDriver))
  227. {
  228. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  229. {
  230. Driver = new WindowsDriver ();
  231. }
  232. else
  233. {
  234. Driver = new CursesDriver ();
  235. }
  236. }
  237. else
  238. {
  239. List<Type> drivers = GetDriverTypes ();
  240. Type driverType = drivers.FirstOrDefault (t => t.Name.Equals (ForceDriver, StringComparison.InvariantCultureIgnoreCase));
  241. if (driverType is { })
  242. {
  243. Driver = (ConsoleDriver)Activator.CreateInstance (driverType);
  244. }
  245. else
  246. {
  247. throw new ArgumentException (
  248. $"Invalid driver name: {ForceDriver}. Valid names are {string.Join (", ", drivers.Select (t => t.Name))}"
  249. );
  250. }
  251. }
  252. }
  253. try
  254. {
  255. MainLoop = Driver.Init ();
  256. }
  257. catch (InvalidOperationException ex)
  258. {
  259. // This is a case where the driver is unable to initialize the console.
  260. // This can happen if the console is already in use by another process or
  261. // if running in unit tests.
  262. // In this case, we want to throw a more specific exception.
  263. throw new InvalidOperationException (
  264. "Unable to initialize the console. This can happen if the console is already in use by another process or in unit tests.",
  265. ex
  266. );
  267. }
  268. Driver.SizeChanged += (s, args) => OnSizeChanging (args);
  269. Driver.KeyDown += (s, args) => OnKeyDown (args);
  270. Driver.KeyUp += (s, args) => OnKeyUp (args);
  271. Driver.MouseEvent += (s, args) => OnMouseEvent (args);
  272. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  273. SupportedCultures = GetSupportedCultures ();
  274. _mainThreadId = Thread.CurrentThread.ManagedThreadId;
  275. _initialized = true;
  276. }
  277. private static void Driver_SizeChanged (object sender, SizeChangedEventArgs e) { OnSizeChanging (e); }
  278. private static void Driver_KeyDown (object sender, Key e) { OnKeyDown (e); }
  279. private static void Driver_KeyUp (object sender, Key e) { OnKeyUp (e); }
  280. private static void Driver_MouseEvent (object sender, MouseEventEventArgs e) { OnMouseEvent (e); }
  281. /// <summary>Gets of list of <see cref="ConsoleDriver"/> types that are available.</summary>
  282. /// <returns></returns>
  283. public static List<Type> GetDriverTypes ()
  284. {
  285. // use reflection to get the list of drivers
  286. List<Type> driverTypes = new ();
  287. foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ())
  288. {
  289. foreach (Type type in asm.GetTypes ())
  290. {
  291. if (type.IsSubclassOf (typeof (ConsoleDriver)) && !type.IsAbstract)
  292. {
  293. driverTypes.Add (type);
  294. }
  295. }
  296. }
  297. return driverTypes;
  298. }
  299. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  300. /// <remarks>
  301. /// Shutdown must be called for every call to <see cref="Init"/> or
  302. /// <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to ensure all resources are cleaned up (Disposed)
  303. /// and terminal settings are restored.
  304. /// </remarks>
  305. public static void Shutdown ()
  306. {
  307. ResetState ();
  308. PrintJsonErrors ();
  309. }
  310. #endregion Initialization (Init/Shutdown)
  311. #region Run (Begin, Run, End, Stop)
  312. /// <summary>
  313. /// Notify that a new <see cref="RunState"/> was created (<see cref="Begin(Toplevel)"/> was called). The token is
  314. /// created in <see cref="Begin(Toplevel)"/> and this event will be fired before that function exits.
  315. /// </summary>
  316. /// <remarks>
  317. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  318. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  319. /// when the application is done.
  320. /// </remarks>
  321. public static event EventHandler<RunStateEventArgs> NotifyNewRunState;
  322. /// <summary>Notify that a existent <see cref="RunState"/> is stopping (<see cref="End(RunState)"/> was called).</summary>
  323. /// <remarks>
  324. /// If <see cref="EndAfterFirstIteration"/> is <see langword="true"/> callers to <see cref="Begin(Toplevel)"/>
  325. /// must also subscribe to <see cref="NotifyStopRunState"/> and manually dispose of the <see cref="RunState"/> token
  326. /// when the application is done.
  327. /// </remarks>
  328. public static event EventHandler<ToplevelEventArgs> NotifyStopRunState;
  329. /// <summary>Building block API: Prepares the provided <see cref="Toplevel"/> for execution.</summary>
  330. /// <returns>
  331. /// The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon
  332. /// completion.
  333. /// </returns>
  334. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  335. /// <remarks>
  336. /// This method prepares the provided <see cref="Toplevel"/> for running with the focus, it adds this to the list
  337. /// of <see cref="Toplevel"/>s, lays out the Subviews, focuses the first element, and draws the <see cref="Toplevel"/>
  338. /// in the screen. This is usually followed by executing the <see cref="RunLoop"/> method, and then the
  339. /// <see cref="End(RunState)"/> method upon termination which will undo these changes.
  340. /// </remarks>
  341. public static RunState Begin (Toplevel toplevel)
  342. {
  343. if (toplevel is null)
  344. {
  345. throw new ArgumentNullException (nameof (toplevel));
  346. }
  347. #if DEBUG_IDISPOSABLE
  348. Debug.Assert (!toplevel.WasDisposed);
  349. if (_latestClosedRunStateToplevel is { } && _latestClosedRunStateToplevel != toplevel)
  350. {
  351. Debug.Assert (_latestClosedRunStateToplevel.WasDisposed);
  352. }
  353. #endif
  354. if (toplevel.IsOverlappedContainer && OverlappedTop != toplevel && OverlappedTop is { })
  355. {
  356. throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
  357. }
  358. // Ensure the mouse is ungrabed.
  359. MouseGrabView = null;
  360. var rs = new RunState (toplevel);
  361. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  362. if (!toplevel.IsInitialized)
  363. {
  364. toplevel.BeginInit ();
  365. toplevel.EndInit ();
  366. }
  367. #if DEBUG_IDISPOSABLE
  368. if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
  369. {
  370. // This assertion confirm if the Top was already disposed
  371. Debug.Assert (Top.WasDisposed);
  372. Debug.Assert (Top == _latestClosedRunStateToplevel);
  373. }
  374. #endif
  375. lock (_topLevels)
  376. {
  377. if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
  378. {
  379. // If Top was already disposed and isn't on the Toplevels Stack,
  380. // clean it up here if is the same as _latestClosedRunStateToplevel
  381. if (Top == _latestClosedRunStateToplevel)
  382. {
  383. Top = null;
  384. }
  385. else
  386. {
  387. // Probably this will never hit
  388. throw new ObjectDisposedException (Top.GetType ().FullName);
  389. }
  390. }
  391. else if (OverlappedTop is { } && toplevel != Top && _topLevels.Contains (Top))
  392. {
  393. Top.OnLeave (toplevel);
  394. }
  395. // BUGBUG: We should not depend on `Id` internally.
  396. // BUGBUG: It is super unclear what this code does anyway.
  397. if (string.IsNullOrEmpty (toplevel.Id))
  398. {
  399. var count = 1;
  400. var id = (_topLevels.Count + count).ToString ();
  401. while (_topLevels.Count > 0 && _topLevels.FirstOrDefault (x => x.Id == id) is { })
  402. {
  403. count++;
  404. id = (_topLevels.Count + count).ToString ();
  405. }
  406. toplevel.Id = (_topLevels.Count + count).ToString ();
  407. _topLevels.Push (toplevel);
  408. }
  409. else
  410. {
  411. Toplevel dup = _topLevels.FirstOrDefault (x => x.Id == toplevel.Id);
  412. if (dup is null)
  413. {
  414. _topLevels.Push (toplevel);
  415. }
  416. }
  417. if (_topLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
  418. {
  419. throw new ArgumentException ("There are duplicates Toplevels Id's");
  420. }
  421. }
  422. if (Top is null || toplevel.IsOverlappedContainer)
  423. {
  424. Top = toplevel;
  425. }
  426. var refreshDriver = true;
  427. if (OverlappedTop is null
  428. || toplevel.IsOverlappedContainer
  429. || (Current?.Modal == false && toplevel.Modal)
  430. || (Current?.Modal == false && !toplevel.Modal)
  431. || (Current?.Modal == true && toplevel.Modal))
  432. {
  433. if (toplevel.Visible)
  434. {
  435. Current?.OnDeactivate (toplevel);
  436. var previousCurrent = Current;
  437. Current = toplevel;
  438. Current.OnActivate (previousCurrent);
  439. SetCurrentOverlappedAsTop ();
  440. }
  441. else
  442. {
  443. refreshDriver = false;
  444. }
  445. }
  446. else if ((OverlappedTop != null
  447. && toplevel != OverlappedTop
  448. && Current?.Modal == true
  449. && !_topLevels.Peek ().Modal)
  450. || (OverlappedTop is { } && toplevel != OverlappedTop && Current?.Running == false))
  451. {
  452. refreshDriver = false;
  453. MoveCurrent (toplevel);
  454. }
  455. else
  456. {
  457. refreshDriver = false;
  458. MoveCurrent (Current);
  459. }
  460. //if (Toplevel.LayoutStyle == LayoutStyle.Computed) {
  461. toplevel.SetRelativeLayout (Driver.Bounds);
  462. //}
  463. // BUGBUG: This call is likley not needed.
  464. toplevel.LayoutSubviews ();
  465. toplevel.PositionToplevels ();
  466. toplevel.FocusFirst ();
  467. if (refreshDriver)
  468. {
  469. OverlappedTop?.OnChildLoaded (toplevel);
  470. toplevel.OnLoaded ();
  471. toplevel.SetNeedsDisplay ();
  472. toplevel.Draw ();
  473. toplevel.PositionCursor ();
  474. Driver.Refresh ();
  475. }
  476. NotifyNewRunState?.Invoke (toplevel, new RunStateEventArgs (rs));
  477. return rs;
  478. }
  479. /// <summary>
  480. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> with the value of
  481. /// <see cref="Top"/>.
  482. /// </summary>
  483. /// <remarks>See <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> for more details.</remarks>
  484. public static void Run (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null) { Run<Toplevel> (errorHandler, driver);}
  485. /// <summary>
  486. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> with a new instance of the
  487. /// specified <see cref="Toplevel"/>-derived class.
  488. /// <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
  489. /// <para>
  490. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
  491. /// ensure resources are cleaned up and terminal settings restored.
  492. /// </para>
  493. /// </summary>
  494. /// <remarks>See <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> for more details.</remarks>
  495. /// <param name="errorHandler"></param>
  496. /// <param name="driver">
  497. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  498. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  499. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  500. /// </param>
  501. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  502. where T : Toplevel, new()
  503. {
  504. var top = new T () as Toplevel;
  505. EnsureValidInitialization (top, driver);
  506. RunApp (top, errorHandler);
  507. }
  508. /// <summary>Runs the main loop on the given <see cref="Toplevel"/> container.</summary>
  509. /// <remarks>
  510. /// <para>
  511. /// This method is used to start processing events for the main application, but it is also used to run other
  512. /// modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  513. /// </para>
  514. /// <para>
  515. /// To make a <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> stop execution, call
  516. /// <see cref="Application.RequestStop"/>.
  517. /// </para>
  518. /// <para>
  519. /// Calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> is equivalent to calling
  520. /// <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState)"/>, and then calling
  521. /// <see cref="End(RunState)"/>.
  522. /// </para>
  523. /// <para>
  524. /// Alternatively, to have a program control the main loop and process events manually, call
  525. /// <see cref="Begin(Toplevel)"/> to set things up manually and then repeatedly call
  526. /// <see cref="RunLoop(RunState)"/> with the wait parameter set to false. By doing this the
  527. /// <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
  528. /// return control immediately.
  529. /// </para>
  530. /// <para>
  531. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
  532. /// rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  533. /// returns <see langword="true"/> the <see cref="RunLoop(RunState)"/> will resume; otherwise this method will
  534. /// exit.
  535. /// </para>
  536. /// </remarks>
  537. /// <param name="view">The <see cref="Toplevel"/> to run as a modal.</param>
  538. /// <param name="errorHandler">
  539. /// RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true,
  540. /// rethrows when null).
  541. /// </param>
  542. /// <param name="driver">
  543. /// The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
  544. /// be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
  545. /// <see langword="null"/> if <see cref="Init"/> has already been called.
  546. /// </param>
  547. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
  548. {
  549. EnsureValidInitialization (view, driver);
  550. RunApp (view, errorHandler);
  551. }
  552. private static void RunApp (Toplevel view, Func<Exception, bool> errorHandler = null)
  553. {
  554. var resume = true;
  555. while (resume)
  556. {
  557. #if !DEBUG
  558. try
  559. {
  560. #endif
  561. resume = false;
  562. RunState runState = Begin (view);
  563. // If EndAfterFirstIteration is true then the user must dispose of the runToken
  564. // by using NotifyStopRunState event.
  565. RunLoop (runState);
  566. if (!EndAfterFirstIteration)
  567. {
  568. End (runState);
  569. }
  570. #if !DEBUG
  571. }
  572. catch (Exception error)
  573. {
  574. if (errorHandler is null)
  575. {
  576. throw;
  577. }
  578. resume = errorHandler (error);
  579. }
  580. #endif
  581. }
  582. }
  583. private static void EnsureValidInitialization (Toplevel top, ConsoleDriver driver)
  584. {
  585. if (top is null)
  586. {
  587. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  588. }
  589. if (_initialized)
  590. {
  591. if (Driver is null)
  592. {
  593. // Ensure disposing the toplevel before throwing
  594. top.Dispose ();
  595. // This code path should be impossible because Init(null, null) will select the platform default driver
  596. throw new InvalidOperationException (
  597. "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
  598. );
  599. }
  600. }
  601. else
  602. {
  603. // Init() has NOT been called.
  604. InternalInit (driver, null, true);
  605. }
  606. }
  607. /// <summary>Adds a timeout to the application.</summary>
  608. /// <remarks>
  609. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  610. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  611. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  612. /// </remarks>
  613. public static object AddTimeout (TimeSpan time, Func<bool> callback) { return MainLoop?.AddTimeout (time, callback); }
  614. /// <summary>Removes a previously scheduled timeout</summary>
  615. /// <remarks>The token parameter is the value returned by <see cref="AddTimeout"/>.</remarks>
  616. /// Returns
  617. /// <c>true</c>
  618. /// if the timeout is successfully removed; otherwise,
  619. /// <c>false</c>
  620. /// .
  621. /// This method also returns
  622. /// <c>false</c>
  623. /// if the timeout is not found.
  624. public static bool RemoveTimeout (object token) { return MainLoop?.RemoveTimeout (token) ?? false; }
  625. /// <summary>Runs <paramref name="action"/> on the thread that is processing events</summary>
  626. /// <param name="action">the action to be invoked on the main processing thread.</param>
  627. public static void Invoke (Action action)
  628. {
  629. MainLoop?.AddIdle (
  630. () =>
  631. {
  632. action ();
  633. return false;
  634. }
  635. );
  636. }
  637. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  638. // is ProgressBarStyles and it's not clear it needs to.
  639. /// <summary>Wakes up the running application that might be waiting on input.</summary>
  640. public static void Wakeup () { MainLoop?.Wakeup (); }
  641. /// <summary>Triggers a refresh of the entire display.</summary>
  642. public static void Refresh ()
  643. {
  644. // TODO: Figure out how to remove this call to ClearContents. Refresh should just repaint damaged areas, not clear
  645. Driver.ClearContents ();
  646. View last = null;
  647. foreach (Toplevel v in _topLevels.Reverse ())
  648. {
  649. if (v.Visible)
  650. {
  651. v.SetNeedsDisplay ();
  652. v.SetSubViewNeedsDisplay ();
  653. v.Draw ();
  654. }
  655. last = v;
  656. }
  657. last?.PositionCursor ();
  658. Driver.Refresh ();
  659. }
  660. /// <summary>This event is raised on each iteration of the main loop.</summary>
  661. /// <remarks>See also <see cref="Timeout"/></remarks>
  662. public static event EventHandler<IterationEventArgs> Iteration;
  663. /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
  664. /// <value>The main loop.</value>
  665. internal static MainLoop MainLoop { get; private set; }
  666. /// <summary>
  667. /// Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
  668. /// cause the application to continue running until Application.RequestStop () is called.
  669. /// </summary>
  670. public static bool EndAfterFirstIteration { get; set; }
  671. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  672. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  673. public static void RunLoop (RunState state)
  674. {
  675. if (state is null)
  676. {
  677. throw new ArgumentNullException (nameof (state));
  678. }
  679. if (state.Toplevel is null)
  680. {
  681. throw new ObjectDisposedException ("state");
  682. }
  683. var firstIteration = true;
  684. for (state.Toplevel.Running = true; state.Toplevel.Running;)
  685. {
  686. MainLoop.Running = true;
  687. if (EndAfterFirstIteration && !firstIteration)
  688. {
  689. return;
  690. }
  691. RunIteration (ref state, ref firstIteration);
  692. }
  693. MainLoop.Running = false;
  694. // Run one last iteration to consume any outstanding input events from Driver
  695. // This is important for remaining OnKeyUp events.
  696. RunIteration (ref state, ref firstIteration);
  697. }
  698. /// <summary>Run one application iteration.</summary>
  699. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  700. /// <param name="firstIteration">
  701. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  702. /// will be set to <see langword="false"/> if at least one iteration happened.
  703. /// </param>
  704. public static void RunIteration (ref RunState state, ref bool firstIteration)
  705. {
  706. if (MainLoop.Running && MainLoop.EventsPending ())
  707. {
  708. // Notify Toplevel it's ready
  709. if (firstIteration)
  710. {
  711. state.Toplevel.OnReady ();
  712. }
  713. MainLoop.RunIteration ();
  714. Iteration?.Invoke (null, new IterationEventArgs ());
  715. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  716. if (state.Toplevel != Current)
  717. {
  718. OverlappedTop?.OnDeactivate (state.Toplevel);
  719. state.Toplevel = Current;
  720. OverlappedTop?.OnActivate (state.Toplevel);
  721. Top.SetSubViewNeedsDisplay ();
  722. Refresh ();
  723. }
  724. }
  725. firstIteration = false;
  726. if (state.Toplevel != Top && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  727. {
  728. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  729. Top.Draw ();
  730. foreach (Toplevel top in _topLevels.Reverse ())
  731. {
  732. if (top != Top && top != state.Toplevel)
  733. {
  734. top.SetNeedsDisplay ();
  735. top.SetSubViewNeedsDisplay ();
  736. top.Draw ();
  737. }
  738. }
  739. }
  740. if (_topLevels.Count == 1
  741. && state.Toplevel == Top
  742. && (Driver.Cols != state.Toplevel.Frame.Width
  743. || Driver.Rows != state.Toplevel.Frame.Height)
  744. && (state.Toplevel.NeedsDisplay
  745. || state.Toplevel.SubViewNeedsDisplay
  746. || state.Toplevel.LayoutNeeded))
  747. {
  748. Driver.ClearContents ();
  749. }
  750. if (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || OverlappedChildNeedsDisplay ())
  751. {
  752. state.Toplevel.Draw ();
  753. state.Toplevel.PositionCursor ();
  754. Driver.Refresh ();
  755. }
  756. else
  757. {
  758. Driver.UpdateCursor ();
  759. }
  760. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  761. {
  762. Top.Draw ();
  763. }
  764. }
  765. /// <summary>Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.</summary>
  766. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  767. /// <remarks>
  768. /// <para>This will cause <see cref="Application.Run(Func{Exception, bool}, ConsoleDriver)"/> to return.</para>
  769. /// <para>
  770. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  771. /// property on the currently running <see cref="Toplevel"/> to false.
  772. /// </para>
  773. /// </remarks>
  774. public static void RequestStop (Toplevel top = null)
  775. {
  776. if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { }))
  777. {
  778. top = Current;
  779. }
  780. if (OverlappedTop != null
  781. && top.IsOverlappedContainer
  782. && top?.Running == true
  783. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false)))
  784. {
  785. OverlappedTop.RequestStop ();
  786. }
  787. else if (OverlappedTop != null
  788. && top != Current
  789. && Current?.Running == true
  790. && Current?.Modal == true
  791. && top.Modal
  792. && top.Running)
  793. {
  794. var ev = new ToplevelClosingEventArgs (Current);
  795. Current.OnClosing (ev);
  796. if (ev.Cancel)
  797. {
  798. return;
  799. }
  800. ev = new ToplevelClosingEventArgs (top);
  801. top.OnClosing (ev);
  802. if (ev.Cancel)
  803. {
  804. return;
  805. }
  806. Current.Running = false;
  807. OnNotifyStopRunState (Current);
  808. top.Running = false;
  809. OnNotifyStopRunState (top);
  810. }
  811. else if ((OverlappedTop != null
  812. && top != OverlappedTop
  813. && top != Current
  814. && Current?.Modal == false
  815. && Current?.Running == true
  816. && !top.Running)
  817. || (OverlappedTop != null
  818. && top != OverlappedTop
  819. && top != Current
  820. && Current?.Modal == false
  821. && Current?.Running == false
  822. && !top.Running
  823. && _topLevels.ToArray () [1].Running))
  824. {
  825. MoveCurrent (top);
  826. }
  827. else if (OverlappedTop != null
  828. && Current != top
  829. && Current?.Running == true
  830. && !top.Running
  831. && Current?.Modal == true
  832. && top.Modal)
  833. {
  834. // The Current and the top are both modal so needed to set the Current.Running to false too.
  835. Current.Running = false;
  836. OnNotifyStopRunState (Current);
  837. }
  838. else if (OverlappedTop != null
  839. && Current == top
  840. && OverlappedTop?.Running == true
  841. && Current?.Running == true
  842. && top.Running
  843. && Current?.Modal == true
  844. && top.Modal)
  845. {
  846. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  847. // both are the same, so needed to set the Current.Running to false too.
  848. Current.Running = false;
  849. OnNotifyStopRunState (Current);
  850. }
  851. else
  852. {
  853. Toplevel currentTop;
  854. if (top == Current || (Current?.Modal == true && !top.Modal))
  855. {
  856. currentTop = Current;
  857. }
  858. else
  859. {
  860. currentTop = top;
  861. }
  862. if (!currentTop.Running)
  863. {
  864. return;
  865. }
  866. var ev = new ToplevelClosingEventArgs (currentTop);
  867. currentTop.OnClosing (ev);
  868. if (ev.Cancel)
  869. {
  870. return;
  871. }
  872. currentTop.Running = false;
  873. OnNotifyStopRunState (currentTop);
  874. }
  875. }
  876. private static void OnNotifyStopRunState (Toplevel top)
  877. {
  878. if (EndAfterFirstIteration)
  879. {
  880. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  881. }
  882. }
  883. private static Toplevel _latestClosedRunStateToplevel;
  884. /// <summary>
  885. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  886. /// <see cref="Begin(Toplevel)"/> .
  887. /// </summary>
  888. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  889. public static void End (RunState runState)
  890. {
  891. if (runState is null)
  892. {
  893. throw new ArgumentNullException (nameof (runState));
  894. }
  895. if (OverlappedTop is { })
  896. {
  897. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  898. }
  899. else
  900. {
  901. runState.Toplevel.OnUnloaded ();
  902. }
  903. // End the RunState.Toplevel
  904. // First, take it off the Toplevel Stack
  905. if (_topLevels.Count > 0)
  906. {
  907. if (_topLevels.Peek () != runState.Toplevel)
  908. {
  909. // If there the top of the stack is not the RunState.Toplevel then
  910. // this call to End is not balanced with the call to Begin that started the RunState
  911. throw new ArgumentException ("End must be balanced with calls to Begin");
  912. }
  913. _topLevels.Pop ();
  914. }
  915. // Notify that it is closing
  916. runState.Toplevel?.OnClosed (runState.Toplevel);
  917. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  918. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  919. if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop)
  920. {
  921. OverlappedTop.OnChildClosed (runState.Toplevel);
  922. }
  923. // Set Current and Top to the next TopLevel on the stack
  924. if (_topLevels.Count == 0)
  925. {
  926. Current = null;
  927. }
  928. else
  929. {
  930. Current = _topLevels.Peek ();
  931. if (_topLevels.Count == 1 && Current == OverlappedTop)
  932. {
  933. OverlappedTop.OnAllChildClosed ();
  934. }
  935. else
  936. {
  937. SetCurrentOverlappedAsTop ();
  938. runState.Toplevel.OnLeave (Current);
  939. Current.OnEnter (runState.Toplevel);
  940. }
  941. Refresh ();
  942. }
  943. // Don't dispose runState.Toplevel. It's up to caller dispose it
  944. // If it's not the same as the current in the RunIteration,
  945. // it will be fixed later in the next RunIteration.
  946. if (OverlappedTop is { } && !_topLevels.Contains (OverlappedTop))
  947. {
  948. _latestClosedRunStateToplevel = OverlappedTop;
  949. }
  950. else
  951. {
  952. _latestClosedRunStateToplevel = runState.Toplevel;
  953. }
  954. runState.Toplevel = null;
  955. runState.Dispose ();
  956. }
  957. #endregion Run (Begin, Run, End)
  958. #region Toplevel handling
  959. /// <summary>Holds the stack of TopLevel views.</summary>
  960. // BUGBUG: Techncally, this is not the full lst of TopLevels. THere be dragons hwre. E.g. see how Toplevel.Id is used. What
  961. // about TopLevels that are just a SubView of another View?
  962. internal static readonly Stack<Toplevel> _topLevels = new ();
  963. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  964. /// <value>The top.</value>
  965. public static Toplevel Top { get; private set; }
  966. /// <summary>
  967. /// The current <see cref="Toplevel"/> object. This is updated when
  968. /// <see cref="Application.Run(Func{Exception, bool}, ConsoleDriver)"/> enters and leaves to point to the current
  969. /// <see cref="Toplevel"/> .
  970. /// </summary>
  971. /// <value>The current.</value>
  972. public static Toplevel Current { get; private set; }
  973. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  974. {
  975. if (!Toplevel.Running
  976. || (Toplevel == Current && Toplevel.Visible)
  977. || OverlappedTop == null
  978. || _topLevels.Peek ().Modal)
  979. {
  980. return;
  981. }
  982. foreach (Toplevel top in _topLevels.Reverse ())
  983. {
  984. if (top.Modal && top != Current)
  985. {
  986. MoveCurrent (top);
  987. return;
  988. }
  989. }
  990. if (!Toplevel.Visible && Toplevel == Current)
  991. {
  992. OverlappedMoveNext ();
  993. }
  994. }
  995. #nullable enable
  996. private static Toplevel? FindDeepestTop (Toplevel start, int x, int y)
  997. {
  998. if (!start.Frame.Contains (x, y))
  999. {
  1000. return null;
  1001. }
  1002. if (_topLevels is { Count: > 0 })
  1003. {
  1004. int rx = x - start.Frame.X;
  1005. int ry = y - start.Frame.Y;
  1006. foreach (Toplevel t in _topLevels)
  1007. {
  1008. if (t != Current)
  1009. {
  1010. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  1011. {
  1012. start = t;
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. }
  1018. return start;
  1019. }
  1020. #nullable restore
  1021. private static View FindTopFromView (View view)
  1022. {
  1023. View top = view?.SuperView is { } && view?.SuperView != Top
  1024. ? view.SuperView
  1025. : view;
  1026. while (top?.SuperView is { } && top?.SuperView != Top)
  1027. {
  1028. top = top.SuperView;
  1029. }
  1030. return top;
  1031. }
  1032. #nullable enable
  1033. // Only return true if the Current has changed.
  1034. private static bool MoveCurrent (Toplevel? top)
  1035. {
  1036. // The Current is modal and the top is not modal Toplevel then
  1037. // the Current must be moved above the first not modal Toplevel.
  1038. if (OverlappedTop is { }
  1039. && top != OverlappedTop
  1040. && top != Current
  1041. && Current?.Modal == true
  1042. && !_topLevels.Peek ().Modal)
  1043. {
  1044. lock (_topLevels)
  1045. {
  1046. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1047. }
  1048. var index = 0;
  1049. Toplevel [] savedToplevels = _topLevels.ToArray ();
  1050. foreach (Toplevel t in savedToplevels)
  1051. {
  1052. if (!t.Modal && t != Current && t != top && t != savedToplevels [index])
  1053. {
  1054. lock (_topLevels)
  1055. {
  1056. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  1057. }
  1058. }
  1059. index++;
  1060. }
  1061. return false;
  1062. }
  1063. // The Current and the top are both not running Toplevel then
  1064. // the top must be moved above the first not running Toplevel.
  1065. if (OverlappedTop is { }
  1066. && top != OverlappedTop
  1067. && top != Current
  1068. && Current?.Running == false
  1069. && top?.Running == false)
  1070. {
  1071. lock (_topLevels)
  1072. {
  1073. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1074. }
  1075. var index = 0;
  1076. foreach (Toplevel t in _topLevels.ToArray ())
  1077. {
  1078. if (!t.Running && t != Current && index > 0)
  1079. {
  1080. lock (_topLevels)
  1081. {
  1082. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  1083. }
  1084. }
  1085. index++;
  1086. }
  1087. return false;
  1088. }
  1089. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  1090. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  1091. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  1092. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  1093. {
  1094. lock (_topLevels)
  1095. {
  1096. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1097. Current = top;
  1098. }
  1099. }
  1100. return true;
  1101. }
  1102. #nullable restore
  1103. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  1104. /// <remarks>
  1105. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  1106. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  1107. /// </remarks>
  1108. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  1109. /// <summary>
  1110. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  1111. /// <see cref="SizeChanging"/> event.
  1112. /// </summary>
  1113. /// <param name="args">The new size.</param>
  1114. /// <returns><see lanword="true"/>if the size was changed.</returns>
  1115. public static bool OnSizeChanging (SizeChangedEventArgs args)
  1116. {
  1117. SizeChanging?.Invoke (null, args);
  1118. if (args.Cancel)
  1119. {
  1120. return false;
  1121. }
  1122. foreach (Toplevel t in _topLevels)
  1123. {
  1124. t.SetRelativeLayout (Rectangle.Empty with { Size = args.Size });
  1125. t.LayoutSubviews ();
  1126. t.PositionToplevels ();
  1127. t.OnSizeChanging (new SizeChangedEventArgs (args.Size));
  1128. }
  1129. Refresh ();
  1130. return true;
  1131. }
  1132. #endregion Toplevel handling
  1133. #region Mouse handling
  1134. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  1135. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1136. public static bool IsMouseDisabled { get; set; }
  1137. /// <summary>The current <see cref="View"/> object that wants continuous mouse button pressed events.</summary>
  1138. public static View WantContinuousButtonPressedView { get; private set; }
  1139. /// <summary>
  1140. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  1141. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  1142. /// </summary>
  1143. public static View MouseGrabView { get; private set; }
  1144. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  1145. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  1146. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  1147. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  1148. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  1149. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  1150. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  1151. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  1152. /// <summary>
  1153. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  1154. /// is called.
  1155. /// </summary>
  1156. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  1157. public static void GrabMouse (View view)
  1158. {
  1159. if (view is null)
  1160. {
  1161. return;
  1162. }
  1163. if (!OnGrabbingMouse (view))
  1164. {
  1165. OnGrabbedMouse (view);
  1166. MouseGrabView = view;
  1167. }
  1168. }
  1169. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  1170. public static void UngrabMouse ()
  1171. {
  1172. if (MouseGrabView is null)
  1173. {
  1174. return;
  1175. }
  1176. if (!OnUnGrabbingMouse (MouseGrabView))
  1177. {
  1178. var view = MouseGrabView;
  1179. MouseGrabView = null;
  1180. OnUnGrabbedMouse (view);
  1181. }
  1182. }
  1183. private static bool OnGrabbingMouse (View view)
  1184. {
  1185. if (view is null)
  1186. {
  1187. return false;
  1188. }
  1189. var evArgs = new GrabMouseEventArgs (view);
  1190. GrabbingMouse?.Invoke (view, evArgs);
  1191. return evArgs.Cancel;
  1192. }
  1193. private static bool OnUnGrabbingMouse (View view)
  1194. {
  1195. if (view is null)
  1196. {
  1197. return false;
  1198. }
  1199. var evArgs = new GrabMouseEventArgs (view);
  1200. UnGrabbingMouse?.Invoke (view, evArgs);
  1201. return evArgs.Cancel;
  1202. }
  1203. private static void OnGrabbedMouse (View view)
  1204. {
  1205. if (view is null)
  1206. {
  1207. return;
  1208. }
  1209. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1210. }
  1211. private static void OnUnGrabbedMouse (View view)
  1212. {
  1213. if (view is null)
  1214. {
  1215. return;
  1216. }
  1217. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1218. }
  1219. #nullable enable
  1220. // Used by OnMouseEvent to track the last view that was clicked on.
  1221. internal static View? _mouseEnteredView;
  1222. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  1223. /// <remarks>
  1224. /// <para>
  1225. /// Use this event to receive mouse events in screen coordinates. Use <see cref="MouseEvent"/> to
  1226. /// receive mouse events relative to a <see cref="View"/>'s bounds.
  1227. /// </para>
  1228. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  1229. /// </remarks>
  1230. public static event EventHandler<MouseEventEventArgs> MouseEvent;
  1231. /// <summary>Called when a mouse event occurs. Raises the <see cref="MouseEvent"/> event.</summary>
  1232. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  1233. /// <param name="a">The mouse event with coordinates relative to the screen.</param>
  1234. internal static void OnMouseEvent (MouseEventEventArgs a)
  1235. {
  1236. if (IsMouseDisabled)
  1237. {
  1238. return;
  1239. }
  1240. // TODO: In PR #3273, FindDeepestView will return adornments. Update logic below to fix adornment mouse handling
  1241. var view = View.FindDeepestView (Current, a.MouseEvent.X, a.MouseEvent.Y);
  1242. if (view is { WantContinuousButtonPressed: true })
  1243. {
  1244. WantContinuousButtonPressedView = view;
  1245. }
  1246. else
  1247. {
  1248. WantContinuousButtonPressedView = null;
  1249. }
  1250. if (view is { })
  1251. {
  1252. a.MouseEvent.View = view;
  1253. }
  1254. MouseEvent?.Invoke (null, new MouseEventEventArgs (a.MouseEvent));
  1255. if (a.MouseEvent.Handled)
  1256. {
  1257. return;
  1258. }
  1259. if (MouseGrabView is { })
  1260. {
  1261. // If the mouse is grabbed, send the event to the view that grabbed it.
  1262. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  1263. Point frameLoc = MouseGrabView.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
  1264. var viewRelativeMouseEvent = new MouseEvent
  1265. {
  1266. X = frameLoc.X,
  1267. Y = frameLoc.Y,
  1268. Flags = a.MouseEvent.Flags,
  1269. ScreenPosition = new (a.MouseEvent.X, a.MouseEvent.Y),
  1270. View = view
  1271. };
  1272. if (MouseGrabView.Bounds.Contains (viewRelativeMouseEvent.X, viewRelativeMouseEvent.Y) is false)
  1273. {
  1274. // The mouse has moved outside the bounds of the view that
  1275. // grabbed the mouse, so we tell the view that last got
  1276. // OnMouseEnter the mouse is leaving
  1277. // BUGBUG: That sentence makes no sense. Either I'm missing something or this logic is flawed.
  1278. _mouseEnteredView?.OnMouseLeave (a.MouseEvent);
  1279. }
  1280. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1281. if (MouseGrabView?.OnMouseEvent (viewRelativeMouseEvent) == true)
  1282. {
  1283. return;
  1284. }
  1285. }
  1286. if (view is not Adornment)
  1287. {
  1288. if ((view is null || view == OverlappedTop)
  1289. && Current is { Modal: false }
  1290. && OverlappedTop != null
  1291. && a.MouseEvent.Flags != MouseFlags.ReportMousePosition
  1292. && a.MouseEvent.Flags != 0)
  1293. {
  1294. // This occurs when there are multiple overlapped "tops"
  1295. // E.g. "Mdi" - in the Background Worker Scenario
  1296. View? top = FindDeepestTop (Top, a.MouseEvent.X, a.MouseEvent.Y);
  1297. view = View.FindDeepestView (top, a.MouseEvent.X, a.MouseEvent.Y);
  1298. if (view is { } && view != OverlappedTop && top != Current)
  1299. {
  1300. MoveCurrent ((Toplevel)top);
  1301. }
  1302. }
  1303. }
  1304. if (view is null)
  1305. {
  1306. return;
  1307. }
  1308. MouseEvent? me = null;
  1309. if (view is Adornment adornment)
  1310. {
  1311. var frameLoc = adornment.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
  1312. me = new MouseEvent
  1313. {
  1314. X = frameLoc.X,
  1315. Y = frameLoc.Y,
  1316. Flags = a.MouseEvent.Flags,
  1317. ScreenPosition = new (a.MouseEvent.X, a.MouseEvent.Y),
  1318. View = view
  1319. };
  1320. }
  1321. else if (view.BoundsToScreen (view.Bounds).Contains (a.MouseEvent.X, a.MouseEvent.Y))
  1322. {
  1323. Point boundsPoint = view.ScreenToBounds (a.MouseEvent.X, a.MouseEvent.Y);
  1324. me = new MouseEvent
  1325. {
  1326. X = boundsPoint.X,
  1327. Y = boundsPoint.Y,
  1328. Flags = a.MouseEvent.Flags,
  1329. ScreenPosition = new (a.MouseEvent.X, a.MouseEvent.Y),
  1330. View = view
  1331. };
  1332. }
  1333. if (me is null)
  1334. {
  1335. return;
  1336. }
  1337. if (_mouseEnteredView is null)
  1338. {
  1339. _mouseEnteredView = view;
  1340. view.OnMouseEnter (me);
  1341. }
  1342. else if (_mouseEnteredView != view)
  1343. {
  1344. _mouseEnteredView.OnMouseLeave (me);
  1345. view.OnMouseEnter (me);
  1346. _mouseEnteredView = view;
  1347. }
  1348. if (!view.WantMousePositionReports && a.MouseEvent.Flags == MouseFlags.ReportMousePosition)
  1349. {
  1350. return;
  1351. }
  1352. WantContinuousButtonPressedView = view.WantContinuousButtonPressed ? view : null;
  1353. //Debug.WriteLine ($"OnMouseEvent: ({a.MouseEvent.X},{a.MouseEvent.Y}) - {a.MouseEvent.Flags}");
  1354. if (view.OnMouseEvent (me))
  1355. {
  1356. // Should we bubble up the event, if it is not handled?
  1357. //return;
  1358. }
  1359. BringOverlappedTopToFront ();
  1360. }
  1361. #nullable restore
  1362. #endregion Mouse handling
  1363. #region Keyboard handling
  1364. private static Key _alternateForwardKey = Key.Empty; // Defined in config.json
  1365. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  1366. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1367. [JsonConverter (typeof (KeyJsonConverter))]
  1368. public static Key AlternateForwardKey
  1369. {
  1370. get => _alternateForwardKey;
  1371. set
  1372. {
  1373. if (_alternateForwardKey != value)
  1374. {
  1375. Key oldKey = _alternateForwardKey;
  1376. _alternateForwardKey = value;
  1377. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1378. }
  1379. }
  1380. }
  1381. private static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1382. {
  1383. foreach (Toplevel top in _topLevels.ToArray ())
  1384. {
  1385. top.OnAlternateForwardKeyChanged (e);
  1386. }
  1387. }
  1388. private static Key _alternateBackwardKey = Key.Empty; // Defined in config.json
  1389. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  1390. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1391. [JsonConverter (typeof (KeyJsonConverter))]
  1392. public static Key AlternateBackwardKey
  1393. {
  1394. get => _alternateBackwardKey;
  1395. set
  1396. {
  1397. if (_alternateBackwardKey != value)
  1398. {
  1399. Key oldKey = _alternateBackwardKey;
  1400. _alternateBackwardKey = value;
  1401. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1402. }
  1403. }
  1404. }
  1405. private static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1406. {
  1407. foreach (Toplevel top in _topLevels.ToArray ())
  1408. {
  1409. top.OnAlternateBackwardKeyChanged (oldKey);
  1410. }
  1411. }
  1412. private static Key _quitKey = Key.Empty; // Defined in config.json
  1413. /// <summary>Gets or sets the key to quit the application.</summary>
  1414. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1415. [JsonConverter (typeof (KeyJsonConverter))]
  1416. public static Key QuitKey
  1417. {
  1418. get => _quitKey;
  1419. set
  1420. {
  1421. if (_quitKey != value)
  1422. {
  1423. Key oldKey = _quitKey;
  1424. _quitKey = value;
  1425. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1426. }
  1427. }
  1428. }
  1429. private static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1430. {
  1431. // Duplicate the list so if it changes during enumeration we're safe
  1432. foreach (Toplevel top in _topLevels.ToArray ())
  1433. {
  1434. top.OnQuitKeyChanged (e);
  1435. }
  1436. }
  1437. /// <summary>
  1438. /// Event fired when the user presses a key. Fired by <see cref="OnKeyDown"/>.
  1439. /// <para>
  1440. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1441. /// additional processing.
  1442. /// </para>
  1443. /// </summary>
  1444. /// <remarks>
  1445. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1446. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1447. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  1448. /// </remarks>
  1449. public static event EventHandler<Key> KeyDown;
  1450. /// <summary>
  1451. /// Called by the <see cref="ConsoleDriver"/> when the user presses a key. Fires the <see cref="KeyDown"/> event
  1452. /// then calls <see cref="View.NewKeyDownEvent"/> on all top level views. Called after <see cref="OnKeyDown"/> and
  1453. /// before <see cref="OnKeyUp"/>.
  1454. /// </summary>
  1455. /// <remarks>Can be used to simulate key press events.</remarks>
  1456. /// <param name="keyEvent"></param>
  1457. /// <returns><see langword="true"/> if the key was handled.</returns>
  1458. public static bool OnKeyDown (Key keyEvent)
  1459. {
  1460. if (!_initialized)
  1461. {
  1462. return true;
  1463. }
  1464. KeyDown?.Invoke (null, keyEvent);
  1465. if (keyEvent.Handled)
  1466. {
  1467. return true;
  1468. }
  1469. foreach (Toplevel topLevel in _topLevels.ToList ())
  1470. {
  1471. if (topLevel.NewKeyDownEvent (keyEvent))
  1472. {
  1473. return true;
  1474. }
  1475. if (topLevel.Modal)
  1476. {
  1477. break;
  1478. }
  1479. }
  1480. // Invoke any Global KeyBindings
  1481. foreach (Toplevel topLevel in _topLevels.ToList ())
  1482. {
  1483. foreach (View view in topLevel.Subviews.Where (
  1484. v => v.KeyBindings.TryGet (
  1485. keyEvent,
  1486. KeyBindingScope.Application,
  1487. out KeyBinding _
  1488. )
  1489. ))
  1490. {
  1491. if (view.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.Application, out KeyBinding _))
  1492. {
  1493. bool? handled = view.OnInvokingKeyBindings (keyEvent);
  1494. if (handled is { } && (bool)handled)
  1495. {
  1496. return true;
  1497. }
  1498. }
  1499. }
  1500. }
  1501. return false;
  1502. }
  1503. /// <summary>
  1504. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  1505. /// <para>
  1506. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1507. /// additional processing.
  1508. /// </para>
  1509. /// </summary>
  1510. /// <remarks>
  1511. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1512. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1513. /// <para>Fired after <see cref="KeyDown"/>.</para>
  1514. /// </remarks>
  1515. public static event EventHandler<Key> KeyUp;
  1516. /// <summary>
  1517. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  1518. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  1519. /// </summary>
  1520. /// <remarks>Can be used to simulate key press events.</remarks>
  1521. /// <param name="a"></param>
  1522. /// <returns><see langword="true"/> if the key was handled.</returns>
  1523. public static bool OnKeyUp (Key a)
  1524. {
  1525. if (!_initialized)
  1526. {
  1527. return true;
  1528. }
  1529. KeyUp?.Invoke (null, a);
  1530. if (a.Handled)
  1531. {
  1532. return true;
  1533. }
  1534. foreach (Toplevel topLevel in _topLevels.ToList ())
  1535. {
  1536. if (topLevel.NewKeyUpEvent (a))
  1537. {
  1538. return true;
  1539. }
  1540. if (topLevel.Modal)
  1541. {
  1542. break;
  1543. }
  1544. }
  1545. return false;
  1546. }
  1547. #endregion Keyboard handling
  1548. }