Application.cs 64 KB

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