Application.cs 55 KB

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