Application.cs 64 KB

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