Application.cs 62 KB

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