Application.cs 61 KB

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