Application.cs 64 KB

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