Application.cs 61 KB

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