Application.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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. //
  629. // provides the sync context set while executing code in Terminal.Gui, to let
  630. // users use async/await on their code
  631. //
  632. private class MainLoopSyncContext : SynchronizationContext
  633. {
  634. public override SynchronizationContext CreateCopy () { return new MainLoopSyncContext (); }
  635. public override void Post (SendOrPostCallback d, object state)
  636. {
  637. MainLoop.AddIdle (
  638. () =>
  639. {
  640. d (state);
  641. return false;
  642. }
  643. );
  644. }
  645. //_mainLoop.Driver.Wakeup ();
  646. public override void Send (SendOrPostCallback d, object state)
  647. {
  648. if (Thread.CurrentThread.ManagedThreadId == _mainThreadId)
  649. {
  650. d (state);
  651. }
  652. else
  653. {
  654. var wasExecuted = false;
  655. Invoke (
  656. () =>
  657. {
  658. d (state);
  659. wasExecuted = true;
  660. }
  661. );
  662. while (!wasExecuted)
  663. {
  664. Thread.Sleep (15);
  665. }
  666. }
  667. }
  668. }
  669. /// <summary>Building block API: Runs the main loop for the created <see cref="Toplevel"/>.</summary>
  670. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  671. public static void RunLoop (RunState state)
  672. {
  673. if (state is null)
  674. {
  675. throw new ArgumentNullException (nameof (state));
  676. }
  677. if (state.Toplevel is null)
  678. {
  679. throw new ObjectDisposedException ("state");
  680. }
  681. var firstIteration = true;
  682. for (state.Toplevel.Running = true; state.Toplevel.Running;)
  683. {
  684. MainLoop.Running = true;
  685. if (EndAfterFirstIteration && !firstIteration)
  686. {
  687. return;
  688. }
  689. RunIteration (ref state, ref firstIteration);
  690. }
  691. MainLoop.Running = false;
  692. // Run one last iteration to consume any outstanding input events from Driver
  693. // This is important for remaining OnKeyUp events.
  694. RunIteration (ref state, ref firstIteration);
  695. }
  696. /// <summary>Run one application iteration.</summary>
  697. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  698. /// <param name="firstIteration">
  699. /// Set to <see langword="true"/> if this is the first run loop iteration. Upon return, it
  700. /// will be set to <see langword="false"/> if at least one iteration happened.
  701. /// </param>
  702. public static void RunIteration (ref RunState state, ref bool firstIteration)
  703. {
  704. if (MainLoop.Running && MainLoop.EventsPending ())
  705. {
  706. // Notify Toplevel it's ready
  707. if (firstIteration)
  708. {
  709. state.Toplevel.OnReady ();
  710. }
  711. MainLoop.RunIteration ();
  712. Iteration?.Invoke (null, new IterationEventArgs ());
  713. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  714. if (state.Toplevel != Current)
  715. {
  716. OverlappedTop?.OnDeactivate (state.Toplevel);
  717. state.Toplevel = Current;
  718. OverlappedTop?.OnActivate (state.Toplevel);
  719. Top.SetSubViewNeedsDisplay ();
  720. Refresh ();
  721. }
  722. }
  723. firstIteration = false;
  724. if (state.Toplevel != Top && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  725. {
  726. state.Toplevel.SetNeedsDisplay (state.Toplevel.Frame);
  727. Top.Draw ();
  728. foreach (Toplevel top in _topLevels.Reverse ())
  729. {
  730. if (top != Top && top != state.Toplevel)
  731. {
  732. top.SetNeedsDisplay ();
  733. top.SetSubViewNeedsDisplay ();
  734. top.Draw ();
  735. }
  736. }
  737. }
  738. if (_topLevels.Count == 1
  739. && state.Toplevel == Top
  740. && (Driver.Cols != state.Toplevel.Frame.Width
  741. || Driver.Rows != state.Toplevel.Frame.Height)
  742. && (state.Toplevel.NeedsDisplay
  743. || state.Toplevel.SubViewNeedsDisplay
  744. || state.Toplevel.LayoutNeeded))
  745. {
  746. state.Toplevel.Clear (Driver.Bounds);
  747. }
  748. if (state.Toplevel.NeedsDisplay || state.Toplevel.SubViewNeedsDisplay || state.Toplevel.LayoutNeeded || OverlappedChildNeedsDisplay ())
  749. {
  750. state.Toplevel.Draw ();
  751. state.Toplevel.PositionCursor ();
  752. Driver.Refresh ();
  753. }
  754. else
  755. {
  756. Driver.UpdateCursor ();
  757. }
  758. if (state.Toplevel != Top && !state.Toplevel.Modal && (Top.NeedsDisplay || Top.SubViewNeedsDisplay || Top.LayoutNeeded))
  759. {
  760. Top.Draw ();
  761. }
  762. }
  763. /// <summary>Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.</summary>
  764. /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
  765. /// <remarks>
  766. /// <para>This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.</para>
  767. /// <para>
  768. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
  769. /// property on the currently running <see cref="Toplevel"/> to false.
  770. /// </para>
  771. /// </remarks>
  772. public static void RequestStop (Toplevel top = null)
  773. {
  774. if (OverlappedTop is null || top is null || (OverlappedTop is null && top is { }))
  775. {
  776. top = Current;
  777. }
  778. if (OverlappedTop != null
  779. && top.IsOverlappedContainer
  780. && top?.Running == true
  781. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false)))
  782. {
  783. OverlappedTop.RequestStop ();
  784. }
  785. else if (OverlappedTop != null
  786. && top != Current
  787. && Current?.Running == true
  788. && Current?.Modal == true
  789. && top.Modal
  790. && top.Running)
  791. {
  792. var ev = new ToplevelClosingEventArgs (Current);
  793. Current.OnClosing (ev);
  794. if (ev.Cancel)
  795. {
  796. return;
  797. }
  798. ev = new ToplevelClosingEventArgs (top);
  799. top.OnClosing (ev);
  800. if (ev.Cancel)
  801. {
  802. return;
  803. }
  804. Current.Running = false;
  805. OnNotifyStopRunState (Current);
  806. top.Running = false;
  807. OnNotifyStopRunState (top);
  808. }
  809. else if ((OverlappedTop != null
  810. && top != OverlappedTop
  811. && top != Current
  812. && Current?.Modal == false
  813. && Current?.Running == true
  814. && !top.Running)
  815. || (OverlappedTop != null
  816. && top != OverlappedTop
  817. && top != Current
  818. && Current?.Modal == false
  819. && Current?.Running == false
  820. && !top.Running
  821. && _topLevels.ToArray () [1].Running))
  822. {
  823. MoveCurrent (top);
  824. }
  825. else if (OverlappedTop != null
  826. && Current != top
  827. && Current?.Running == true
  828. && !top.Running
  829. && Current?.Modal == true
  830. && top.Modal)
  831. {
  832. // The Current and the top are both modal so needed to set the Current.Running to false too.
  833. Current.Running = false;
  834. OnNotifyStopRunState (Current);
  835. }
  836. else if (OverlappedTop != null
  837. && Current == top
  838. && OverlappedTop?.Running == true
  839. && Current?.Running == true
  840. && top.Running
  841. && Current?.Modal == true
  842. && top.Modal)
  843. {
  844. // The OverlappedTop was requested to stop inside a modal Toplevel which is the Current and top,
  845. // both are the same, so needed to set the Current.Running to false too.
  846. Current.Running = false;
  847. OnNotifyStopRunState (Current);
  848. }
  849. else
  850. {
  851. Toplevel currentTop;
  852. if (top == Current || (Current?.Modal == true && !top.Modal))
  853. {
  854. currentTop = Current;
  855. }
  856. else
  857. {
  858. currentTop = top;
  859. }
  860. if (!currentTop.Running)
  861. {
  862. return;
  863. }
  864. var ev = new ToplevelClosingEventArgs (currentTop);
  865. currentTop.OnClosing (ev);
  866. if (ev.Cancel)
  867. {
  868. return;
  869. }
  870. currentTop.Running = false;
  871. OnNotifyStopRunState (currentTop);
  872. }
  873. }
  874. private static void OnNotifyStopRunState (Toplevel top)
  875. {
  876. if (EndAfterFirstIteration)
  877. {
  878. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  879. }
  880. }
  881. /// <summary>
  882. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
  883. /// <see cref="Begin(Toplevel)"/> .
  884. /// </summary>
  885. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  886. public static void End (RunState runState)
  887. {
  888. if (runState is null)
  889. {
  890. throw new ArgumentNullException (nameof (runState));
  891. }
  892. if (OverlappedTop is { })
  893. {
  894. OverlappedTop.OnChildUnloaded (runState.Toplevel);
  895. }
  896. else
  897. {
  898. runState.Toplevel.OnUnloaded ();
  899. }
  900. // End the RunState.Toplevel
  901. // First, take it off the Toplevel Stack
  902. if (_topLevels.Count > 0)
  903. {
  904. if (_topLevels.Peek () != runState.Toplevel)
  905. {
  906. // If there the top of the stack is not the RunState.Toplevel then
  907. // this call to End is not balanced with the call to Begin that started the RunState
  908. throw new ArgumentException ("End must be balanced with calls to Begin");
  909. }
  910. _topLevels.Pop ();
  911. }
  912. // Notify that it is closing
  913. runState.Toplevel?.OnClosed (runState.Toplevel);
  914. // If there is a OverlappedTop that is not the RunState.Toplevel then runstate.TopLevel
  915. // is a child of MidTop and we should notify the OverlappedTop that it is closing
  916. if (OverlappedTop is { } && !runState.Toplevel.Modal && runState.Toplevel != OverlappedTop)
  917. {
  918. OverlappedTop.OnChildClosed (runState.Toplevel);
  919. }
  920. // Set Current and Top to the next TopLevel on the stack
  921. if (_topLevels.Count == 0)
  922. {
  923. Current = null;
  924. }
  925. else
  926. {
  927. Current = _topLevels.Peek ();
  928. if (_topLevels.Count == 1 && Current == OverlappedTop)
  929. {
  930. OverlappedTop.OnAllChildClosed ();
  931. }
  932. else
  933. {
  934. SetCurrentOverlappedAsTop ();
  935. runState.Toplevel.OnLeave (Current);
  936. Current.OnEnter (runState.Toplevel);
  937. }
  938. Refresh ();
  939. }
  940. runState.Toplevel?.Dispose ();
  941. runState.Toplevel = null;
  942. runState.Dispose ();
  943. }
  944. #endregion Run (Begin, Run, End)
  945. #region Toplevel handling
  946. /// <summary>Holds the stack of TopLevel views.</summary>
  947. // BUGBUG: Techncally, this is not the full lst of TopLevels. THere be dragons hwre. E.g. see how Toplevel.Id is used. What
  948. // about TopLevels that are just a SubView of another View?
  949. internal static readonly Stack<Toplevel> _topLevels = new ();
  950. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  951. /// <value>The top.</value>
  952. public static Toplevel Top { get; private set; }
  953. /// <summary>
  954. /// The current <see cref="Toplevel"/> object. This is updated when
  955. /// <see cref="Application.Run(Func{Exception, bool})"/> enters and leaves to point to the current
  956. /// <see cref="Toplevel"/> .
  957. /// </summary>
  958. /// <value>The current.</value>
  959. public static Toplevel Current { get; private set; }
  960. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel Toplevel)
  961. {
  962. if (!Toplevel.Running
  963. || (Toplevel == Current && Toplevel.Visible)
  964. || OverlappedTop == null
  965. || _topLevels.Peek ().Modal)
  966. {
  967. return;
  968. }
  969. foreach (Toplevel top in _topLevels.Reverse ())
  970. {
  971. if (top.Modal && top != Current)
  972. {
  973. MoveCurrent (top);
  974. return;
  975. }
  976. }
  977. if (!Toplevel.Visible && Toplevel == Current)
  978. {
  979. OverlappedMoveNext ();
  980. }
  981. }
  982. private static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  983. {
  984. Rectangle startFrame = start.Frame;
  985. if (!startFrame.Contains (x, y))
  986. {
  987. resx = 0;
  988. resy = 0;
  989. return null;
  990. }
  991. if (_topLevels is { })
  992. {
  993. int count = _topLevels.Count;
  994. if (count > 0)
  995. {
  996. int rx = x - startFrame.X;
  997. int ry = y - startFrame.Y;
  998. foreach (Toplevel t in _topLevels)
  999. {
  1000. if (t != Current)
  1001. {
  1002. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  1003. {
  1004. start = t;
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. }
  1011. resx = x - startFrame.X;
  1012. resy = y - startFrame.Y;
  1013. return start;
  1014. }
  1015. private static View FindTopFromView (View view)
  1016. {
  1017. View top = view?.SuperView is { } && view?.SuperView != Top
  1018. ? view.SuperView
  1019. : view;
  1020. while (top?.SuperView is { } && top?.SuperView != Top)
  1021. {
  1022. top = top.SuperView;
  1023. }
  1024. return top;
  1025. }
  1026. // Only return true if the Current has changed.
  1027. private static bool MoveCurrent (Toplevel top)
  1028. {
  1029. // The Current is modal and the top is not modal Toplevel then
  1030. // the Current must be moved above the first not modal Toplevel.
  1031. if (OverlappedTop != null
  1032. && top != OverlappedTop
  1033. && top != Current
  1034. && Current?.Modal == true
  1035. && !_topLevels.Peek ().Modal)
  1036. {
  1037. lock (_topLevels)
  1038. {
  1039. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1040. }
  1041. var index = 0;
  1042. Toplevel [] savedToplevels = _topLevels.ToArray ();
  1043. foreach (Toplevel t in savedToplevels)
  1044. {
  1045. if (!t.Modal && t != Current && t != top && t != savedToplevels [index])
  1046. {
  1047. lock (_topLevels)
  1048. {
  1049. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  1050. }
  1051. }
  1052. index++;
  1053. }
  1054. return false;
  1055. }
  1056. // The Current and the top are both not running Toplevel then
  1057. // the top must be moved above the first not running Toplevel.
  1058. if (OverlappedTop != null
  1059. && top != OverlappedTop
  1060. && top != Current
  1061. && Current?.Running == false
  1062. && !top.Running)
  1063. {
  1064. lock (_topLevels)
  1065. {
  1066. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  1067. }
  1068. var index = 0;
  1069. foreach (Toplevel t in _topLevels.ToArray ())
  1070. {
  1071. if (!t.Running && t != Current && index > 0)
  1072. {
  1073. lock (_topLevels)
  1074. {
  1075. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  1076. }
  1077. }
  1078. index++;
  1079. }
  1080. return false;
  1081. }
  1082. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  1083. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  1084. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  1085. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  1086. {
  1087. lock (_topLevels)
  1088. {
  1089. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1090. Current = top;
  1091. }
  1092. }
  1093. return true;
  1094. }
  1095. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  1096. /// <remarks>
  1097. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  1098. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  1099. /// </remarks>
  1100. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  1101. /// <summary>
  1102. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  1103. /// <see cref="SizeChanging"/> event.
  1104. /// </summary>
  1105. /// <param name="args">The new size.</param>
  1106. /// <returns><see lanword="true"/>if the size was changed.</returns>
  1107. public static bool OnSizeChanging (SizeChangedEventArgs args)
  1108. {
  1109. SizeChanging?.Invoke (null, args);
  1110. if (args.Cancel)
  1111. {
  1112. return false;
  1113. }
  1114. foreach (Toplevel t in _topLevels)
  1115. {
  1116. t.SetRelativeLayout (new Rectangle (0, 0, args.Size.Width, args.Size.Height));
  1117. t.LayoutSubviews ();
  1118. t.PositionToplevels ();
  1119. t.OnSizeChanging (new SizeChangedEventArgs (args.Size));
  1120. }
  1121. Refresh ();
  1122. return true;
  1123. }
  1124. #endregion Toplevel handling
  1125. #region Mouse handling
  1126. /// <summary>Disable or enable the mouse. The mouse is enabled by default.</summary>
  1127. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1128. public static bool IsMouseDisabled { get; set; }
  1129. /// <summary>The current <see cref="View"/> object that wants continuous mouse button pressed events.</summary>
  1130. public static View WantContinuousButtonPressedView { get; private set; }
  1131. /// <summary>
  1132. /// Gets the view that grabbed the mouse (e.g. for dragging). When this is set, all mouse events will be routed to
  1133. /// this view until the view calls <see cref="UngrabMouse"/> or the mouse is released.
  1134. /// </summary>
  1135. public static View MouseGrabView { get; private set; }
  1136. /// <summary>Invoked when a view wants to grab the mouse; can be canceled.</summary>
  1137. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  1138. /// <summary>Invoked when a view wants un-grab the mouse; can be canceled.</summary>
  1139. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  1140. /// <summary>Invoked after a view has grabbed the mouse.</summary>
  1141. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  1142. /// <summary>Invoked after a view has un-grabbed the mouse.</summary>
  1143. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  1144. /// <summary>
  1145. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until <see cref="UngrabMouse"/>
  1146. /// is called.
  1147. /// </summary>
  1148. /// <param name="view">View that will receive all mouse events until <see cref="UngrabMouse"/> is invoked.</param>
  1149. public static void GrabMouse (View view)
  1150. {
  1151. if (view is null)
  1152. {
  1153. return;
  1154. }
  1155. if (!OnGrabbingMouse (view))
  1156. {
  1157. OnGrabbedMouse (view);
  1158. MouseGrabView = view;
  1159. }
  1160. }
  1161. /// <summary>Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.</summary>
  1162. public static void UngrabMouse ()
  1163. {
  1164. if (MouseGrabView is null)
  1165. {
  1166. return;
  1167. }
  1168. if (!OnUnGrabbingMouse (MouseGrabView))
  1169. {
  1170. OnUnGrabbedMouse (MouseGrabView);
  1171. MouseGrabView = null;
  1172. }
  1173. }
  1174. private static bool OnGrabbingMouse (View view)
  1175. {
  1176. if (view is null)
  1177. {
  1178. return false;
  1179. }
  1180. var evArgs = new GrabMouseEventArgs (view);
  1181. GrabbingMouse?.Invoke (view, evArgs);
  1182. return evArgs.Cancel;
  1183. }
  1184. private static bool OnUnGrabbingMouse (View view)
  1185. {
  1186. if (view is null)
  1187. {
  1188. return false;
  1189. }
  1190. var evArgs = new GrabMouseEventArgs (view);
  1191. UnGrabbingMouse?.Invoke (view, evArgs);
  1192. return evArgs.Cancel;
  1193. }
  1194. private static void OnGrabbedMouse (View view)
  1195. {
  1196. if (view is null)
  1197. {
  1198. return;
  1199. }
  1200. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1201. }
  1202. private static void OnUnGrabbedMouse (View view)
  1203. {
  1204. if (view is null)
  1205. {
  1206. return;
  1207. }
  1208. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  1209. }
  1210. // Used by OnMouseEvent to track the last view that was clicked on.
  1211. internal static View _mouseEnteredView;
  1212. /// <summary>Event fired when a mouse move or click occurs. Coordinates are screen relative.</summary>
  1213. /// <remarks>
  1214. /// <para>
  1215. /// Use this event to receive mouse events in screen coordinates. Use <see cref="Responder.MouseEvent"/> to
  1216. /// receive mouse events relative to a <see cref="View"/>'s bounds.
  1217. /// </para>
  1218. /// <para>The <see cref="MouseEvent.View"/> will contain the <see cref="View"/> that contains the mouse coordinates.</para>
  1219. /// </remarks>
  1220. public static event EventHandler<MouseEventEventArgs> MouseEvent;
  1221. /// <summary>Called when a mouse event occurs. Fires the <see cref="MouseEvent"/> event.</summary>
  1222. /// <remarks>This method can be used to simulate a mouse event, e.g. in unit tests.</remarks>
  1223. /// <param name="a">The mouse event with coordinates relative to the screen.</param>
  1224. public static void OnMouseEvent (MouseEventEventArgs a)
  1225. {
  1226. static bool OutsideRect (Point p, Rectangle r) { return p.X < 0 || p.X > r.Right || p.Y < 0 || p.Y > r.Bottom; }
  1227. if (IsMouseDisabled)
  1228. {
  1229. return;
  1230. }
  1231. var view = View.FindDeepestView (Current, a.MouseEvent.X, a.MouseEvent.Y, out int screenX, out int screenY);
  1232. if (view is { } && view.WantContinuousButtonPressed)
  1233. {
  1234. WantContinuousButtonPressedView = view;
  1235. }
  1236. else
  1237. {
  1238. WantContinuousButtonPressedView = null;
  1239. }
  1240. if (view is { })
  1241. {
  1242. a.MouseEvent.View = view;
  1243. }
  1244. MouseEvent?.Invoke (null, new MouseEventEventArgs (a.MouseEvent));
  1245. if (a.MouseEvent.Handled)
  1246. {
  1247. return;
  1248. }
  1249. if (MouseGrabView is { })
  1250. {
  1251. // If the mouse is grabbed, send the event to the view that grabbed it.
  1252. // The coordinates are relative to the Bounds of the view that grabbed the mouse.
  1253. Point newxy = MouseGrabView.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
  1254. var nme = new MouseEvent
  1255. {
  1256. X = newxy.X,
  1257. Y = newxy.Y,
  1258. Flags = a.MouseEvent.Flags,
  1259. OfX = a.MouseEvent.X - newxy.X,
  1260. OfY = a.MouseEvent.Y - newxy.Y,
  1261. View = view
  1262. };
  1263. if (OutsideRect (new Point (nme.X, nme.Y), MouseGrabView.Bounds))
  1264. {
  1265. // The mouse has moved outside the bounds of the the view that
  1266. // grabbed the mouse, so we tell the view that last got
  1267. // OnMouseEnter the mouse is leaving
  1268. // BUGBUG: That sentence makes no sense. Either I'm missing something
  1269. // or this logic is flawed.
  1270. _mouseEnteredView?.OnMouseLeave (a.MouseEvent);
  1271. }
  1272. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  1273. if (MouseGrabView?.OnMouseEvent (nme) == true)
  1274. {
  1275. return;
  1276. }
  1277. }
  1278. if ((view is null || view == OverlappedTop)
  1279. && Current is { Modal: false }
  1280. && OverlappedTop != null
  1281. && a.MouseEvent.Flags != MouseFlags.ReportMousePosition
  1282. && a.MouseEvent.Flags != 0)
  1283. {
  1284. View top = FindDeepestTop (Top, a.MouseEvent.X, a.MouseEvent.Y, out _, out _);
  1285. view = View.FindDeepestView (top, a.MouseEvent.X, a.MouseEvent.Y, out screenX, out screenY);
  1286. if (view is { } && view != OverlappedTop && top != Current)
  1287. {
  1288. MoveCurrent ((Toplevel)top);
  1289. }
  1290. }
  1291. bool AdornmentHandledMouseEvent (Adornment frame)
  1292. {
  1293. if (frame?.Thickness.Contains (frame.FrameToScreen (), a.MouseEvent.X, a.MouseEvent.Y) ?? false)
  1294. {
  1295. Point boundsPoint = frame.ScreenToBounds (a.MouseEvent.X, a.MouseEvent.Y);
  1296. var me = new MouseEvent
  1297. {
  1298. X = boundsPoint.X,
  1299. Y = boundsPoint.Y,
  1300. Flags = a.MouseEvent.Flags,
  1301. OfX = boundsPoint.X,
  1302. OfY = boundsPoint.Y,
  1303. View = frame
  1304. };
  1305. frame.OnMouseEvent (me);
  1306. return true;
  1307. }
  1308. return false;
  1309. }
  1310. if (view is { })
  1311. {
  1312. // Work inside-out (Padding, Border, Margin)
  1313. // TODO: Debate whether inside-out or outside-in is the right strategy
  1314. if (AdornmentHandledMouseEvent (view?.Padding))
  1315. {
  1316. return;
  1317. }
  1318. if (AdornmentHandledMouseEvent (view?.Border))
  1319. {
  1320. if (view is Toplevel)
  1321. {
  1322. // TODO: This is a temporary hack to work around the fact that
  1323. // drag handling is handled in Toplevel (See Issue #2537)
  1324. var me = new MouseEvent
  1325. {
  1326. X = screenX,
  1327. Y = screenY,
  1328. Flags = a.MouseEvent.Flags,
  1329. OfX = screenX,
  1330. OfY = screenY,
  1331. View = view
  1332. };
  1333. if (_mouseEnteredView is null)
  1334. {
  1335. _mouseEnteredView = view;
  1336. view.OnMouseEnter (me);
  1337. }
  1338. else if (_mouseEnteredView != view)
  1339. {
  1340. _mouseEnteredView.OnMouseLeave (me);
  1341. view.OnMouseEnter (me);
  1342. _mouseEnteredView = view;
  1343. }
  1344. if (!view.WantMousePositionReports && a.MouseEvent.Flags == MouseFlags.ReportMousePosition)
  1345. {
  1346. return;
  1347. }
  1348. WantContinuousButtonPressedView = view.WantContinuousButtonPressed ? view : null;
  1349. if (view.OnMouseEvent (me))
  1350. {
  1351. // Should we bubble up the event, if it is not handled?
  1352. //return;
  1353. }
  1354. BringOverlappedTopToFront ();
  1355. }
  1356. return;
  1357. }
  1358. if (AdornmentHandledMouseEvent (view?.Margin))
  1359. {
  1360. return;
  1361. }
  1362. Rectangle bounds = view.BoundsToScreen (view.Bounds);
  1363. if (bounds.Contains (a.MouseEvent.X, a.MouseEvent.Y))
  1364. {
  1365. Point boundsPoint = view.ScreenToBounds (a.MouseEvent.X, a.MouseEvent.Y);
  1366. var me = new MouseEvent
  1367. {
  1368. X = boundsPoint.X,
  1369. Y = boundsPoint.Y,
  1370. Flags = a.MouseEvent.Flags,
  1371. OfX = boundsPoint.X,
  1372. OfY = boundsPoint.Y,
  1373. View = view
  1374. };
  1375. if (_mouseEnteredView is null)
  1376. {
  1377. _mouseEnteredView = view;
  1378. view.OnMouseEnter (me);
  1379. }
  1380. else if (_mouseEnteredView != view)
  1381. {
  1382. _mouseEnteredView.OnMouseLeave (me);
  1383. view.OnMouseEnter (me);
  1384. _mouseEnteredView = view;
  1385. }
  1386. if (!view.WantMousePositionReports && a.MouseEvent.Flags == MouseFlags.ReportMousePosition)
  1387. {
  1388. return;
  1389. }
  1390. WantContinuousButtonPressedView = view.WantContinuousButtonPressed ? view : null;
  1391. if (view.OnMouseEvent (me))
  1392. {
  1393. // Should we bubble up the event, if it is not handled?
  1394. //return;
  1395. }
  1396. BringOverlappedTopToFront ();
  1397. }
  1398. }
  1399. }
  1400. #endregion Mouse handling
  1401. #region Keyboard handling
  1402. private static Key _alternateForwardKey = Key.Empty; // Defined in config.json
  1403. /// <summary>Alternative key to navigate forwards through views. Ctrl+Tab is the primary key.</summary>
  1404. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1405. [JsonConverter (typeof (KeyJsonConverter))]
  1406. public static Key AlternateForwardKey
  1407. {
  1408. get => _alternateForwardKey;
  1409. set
  1410. {
  1411. if (_alternateForwardKey != value)
  1412. {
  1413. Key oldKey = _alternateForwardKey;
  1414. _alternateForwardKey = value;
  1415. OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1416. }
  1417. }
  1418. }
  1419. private static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  1420. {
  1421. foreach (Toplevel top in _topLevels.ToArray ())
  1422. {
  1423. top.OnAlternateForwardKeyChanged (e);
  1424. }
  1425. }
  1426. private static Key _alternateBackwardKey = Key.Empty; // Defined in config.json
  1427. /// <summary>Alternative key to navigate backwards through views. Shift+Ctrl+Tab is the primary key.</summary>
  1428. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1429. [JsonConverter (typeof (KeyJsonConverter))]
  1430. public static Key AlternateBackwardKey
  1431. {
  1432. get => _alternateBackwardKey;
  1433. set
  1434. {
  1435. if (_alternateBackwardKey != value)
  1436. {
  1437. Key oldKey = _alternateBackwardKey;
  1438. _alternateBackwardKey = value;
  1439. OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1440. }
  1441. }
  1442. }
  1443. private static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs oldKey)
  1444. {
  1445. foreach (Toplevel top in _topLevels.ToArray ())
  1446. {
  1447. top.OnAlternateBackwardKeyChanged (oldKey);
  1448. }
  1449. }
  1450. private static Key _quitKey = Key.Empty; // Defined in config.json
  1451. /// <summary>Gets or sets the key to quit the application.</summary>
  1452. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  1453. [JsonConverter (typeof (KeyJsonConverter))]
  1454. public static Key QuitKey
  1455. {
  1456. get => _quitKey;
  1457. set
  1458. {
  1459. if (_quitKey != value)
  1460. {
  1461. Key oldKey = _quitKey;
  1462. _quitKey = value;
  1463. OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
  1464. }
  1465. }
  1466. }
  1467. private static void OnQuitKeyChanged (KeyChangedEventArgs e)
  1468. {
  1469. // Duplicate the list so if it changes during enumeration we're safe
  1470. foreach (Toplevel top in _topLevels.ToArray ())
  1471. {
  1472. top.OnQuitKeyChanged (e);
  1473. }
  1474. }
  1475. /// <summary>
  1476. /// Event fired when the user presses a key. Fired by <see cref="OnKeyDown"/>.
  1477. /// <para>
  1478. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1479. /// additional processing.
  1480. /// </para>
  1481. /// </summary>
  1482. /// <remarks>
  1483. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1484. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1485. /// <para>Fired after <see cref="KeyDown"/> and before <see cref="KeyUp"/>.</para>
  1486. /// </remarks>
  1487. public static event EventHandler<Key> KeyDown;
  1488. /// <summary>
  1489. /// Called by the <see cref="ConsoleDriver"/> when the user presses a key. Fires the <see cref="KeyDown"/> event
  1490. /// then calls <see cref="View.NewKeyDownEvent"/> on all top level views. Called after <see cref="OnKeyDown"/> and
  1491. /// before <see cref="OnKeyUp"/>.
  1492. /// </summary>
  1493. /// <remarks>Can be used to simulate key press events.</remarks>
  1494. /// <param name="keyEvent"></param>
  1495. /// <returns><see langword="true"/> if the key was handled.</returns>
  1496. public static bool OnKeyDown (Key keyEvent)
  1497. {
  1498. if (!_initialized)
  1499. {
  1500. return true;
  1501. }
  1502. KeyDown?.Invoke (null, keyEvent);
  1503. if (keyEvent.Handled)
  1504. {
  1505. return true;
  1506. }
  1507. foreach (Toplevel topLevel in _topLevels.ToList ())
  1508. {
  1509. if (topLevel.NewKeyDownEvent (keyEvent))
  1510. {
  1511. return true;
  1512. }
  1513. if (topLevel.Modal)
  1514. {
  1515. break;
  1516. }
  1517. }
  1518. // Invoke any Global KeyBindings
  1519. foreach (Toplevel topLevel in _topLevels.ToList ())
  1520. {
  1521. foreach (View view in topLevel.Subviews.Where (
  1522. v => v.KeyBindings.TryGet (
  1523. keyEvent,
  1524. KeyBindingScope.Application,
  1525. out KeyBinding _
  1526. )
  1527. ))
  1528. {
  1529. if (view.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.Application, out KeyBinding _))
  1530. {
  1531. bool? handled = view.OnInvokingKeyBindings (keyEvent);
  1532. if (handled is { } && (bool)handled)
  1533. {
  1534. return true;
  1535. }
  1536. }
  1537. }
  1538. }
  1539. return false;
  1540. }
  1541. /// <summary>
  1542. /// Event fired when the user releases a key. Fired by <see cref="OnKeyUp"/>.
  1543. /// <para>
  1544. /// Set <see cref="Key.Handled"/> to <see langword="true"/> to indicate the key was handled and to prevent
  1545. /// additional processing.
  1546. /// </para>
  1547. /// </summary>
  1548. /// <remarks>
  1549. /// All drivers support firing the <see cref="KeyDown"/> event. Some drivers (Curses) do not support firing the
  1550. /// <see cref="KeyDown"/> and <see cref="KeyUp"/> events.
  1551. /// <para>Fired after <see cref="KeyDown"/>.</para>
  1552. /// </remarks>
  1553. public static event EventHandler<Key> KeyUp;
  1554. /// <summary>
  1555. /// Called by the <see cref="ConsoleDriver"/> when the user releases a key. Fires the <see cref="KeyUp"/> event
  1556. /// then calls <see cref="View.NewKeyUpEvent"/> on all top level views. Called after <see cref="OnKeyDown"/>.
  1557. /// </summary>
  1558. /// <remarks>Can be used to simulate key press events.</remarks>
  1559. /// <param name="a"></param>
  1560. /// <returns><see langword="true"/> if the key was handled.</returns>
  1561. public static bool OnKeyUp (Key a)
  1562. {
  1563. if (!_initialized)
  1564. {
  1565. return true;
  1566. }
  1567. KeyUp?.Invoke (null, a);
  1568. if (a.Handled)
  1569. {
  1570. return true;
  1571. }
  1572. foreach (Toplevel topLevel in _topLevels.ToList ())
  1573. {
  1574. if (topLevel.NewKeyUpEvent (a))
  1575. {
  1576. return true;
  1577. }
  1578. if (topLevel.Modal)
  1579. {
  1580. break;
  1581. }
  1582. }
  1583. return false;
  1584. }
  1585. #endregion Keyboard handling
  1586. }
  1587. /// <summary>Event arguments for the <see cref="Application.Iteration"/> event.</summary>
  1588. public class IterationEventArgs
  1589. { }