Application.cs 55 KB

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