Application.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  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) {
  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. throw new InvalidOperationException ("You must clean up (Dispose) the Toplevel before calling Application.RunState.Dispose");
  468. // BUGBUG: It's insidious that we call EndFirstTopLevel here so I moved it to End.
  469. //EndFirstTopLevel (Toplevel);
  470. //Toplevel.Dispose ();
  471. //Toplevel = null;
  472. }
  473. }
  474. }
  475. static void ProcessKeyEvent (KeyEvent ke)
  476. {
  477. if (RootKeyEvent?.Invoke (ke) ?? false) {
  478. return;
  479. }
  480. var chain = toplevels.ToList ();
  481. foreach (var topLevel in chain) {
  482. if (topLevel.ProcessHotKey (ke)) {
  483. EnsuresMdiTopOnFrontIfMdiTopMostFocused ();
  484. return;
  485. }
  486. if (topLevel.Modal)
  487. break;
  488. }
  489. foreach (var topLevel in chain) {
  490. if (topLevel.ProcessKey (ke))
  491. return;
  492. if (topLevel.Modal)
  493. break;
  494. }
  495. foreach (var topLevel in chain) {
  496. // Process the key normally
  497. if (topLevel.ProcessColdKey (ke))
  498. return;
  499. if (topLevel.Modal)
  500. break;
  501. }
  502. }
  503. static void ProcessKeyDownEvent (KeyEvent ke)
  504. {
  505. var chain = toplevels.ToList ();
  506. foreach (var topLevel in chain) {
  507. if (topLevel.OnKeyDown (ke))
  508. return;
  509. if (topLevel.Modal)
  510. break;
  511. }
  512. }
  513. static void ProcessKeyUpEvent (KeyEvent ke)
  514. {
  515. var chain = toplevels.ToList ();
  516. foreach (var topLevel in chain) {
  517. if (topLevel.OnKeyUp (ke))
  518. return;
  519. if (topLevel.Modal)
  520. break;
  521. }
  522. }
  523. static View FindDeepestTop (Toplevel start, int x, int y, out int resx, out int resy)
  524. {
  525. var startFrame = start.Frame;
  526. if (!startFrame.Contains (x, y)) {
  527. resx = 0;
  528. resy = 0;
  529. return null;
  530. }
  531. if (toplevels != null) {
  532. int count = toplevels.Count;
  533. if (count > 0) {
  534. var rx = x - startFrame.X;
  535. var ry = y - startFrame.Y;
  536. foreach (var t in toplevels) {
  537. if (t != Current) {
  538. if (t != start && t.Visible && t.Frame.Contains (rx, ry)) {
  539. start = t;
  540. break;
  541. }
  542. }
  543. }
  544. }
  545. }
  546. resx = x - startFrame.X;
  547. resy = y - startFrame.Y;
  548. return start;
  549. }
  550. static View FindDeepestMdiView (View start, int x, int y, out int resx, out int resy)
  551. {
  552. if (start.GetType ().BaseType != typeof (Toplevel)
  553. && !((Toplevel)start).IsMdiContainer) {
  554. resx = 0;
  555. resy = 0;
  556. return null;
  557. }
  558. var startFrame = start.Frame;
  559. if (!startFrame.Contains (x, y)) {
  560. resx = 0;
  561. resy = 0;
  562. return null;
  563. }
  564. int count = toplevels.Count;
  565. for (int i = count - 1; i >= 0; i--) {
  566. foreach (var top in toplevels) {
  567. var rx = x - startFrame.X;
  568. var ry = y - startFrame.Y;
  569. if (top.Visible && top.Frame.Contains (rx, ry)) {
  570. var deep = FindDeepestView (top, rx, ry, out resx, out resy);
  571. if (deep == null)
  572. return FindDeepestMdiView (top, rx, ry, out resx, out resy);
  573. if (deep != MdiTop)
  574. return deep;
  575. }
  576. }
  577. }
  578. resx = x - startFrame.X;
  579. resy = y - startFrame.Y;
  580. return start;
  581. }
  582. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  583. {
  584. var startFrame = start.Frame;
  585. if (!startFrame.Contains (x, y)) {
  586. resx = 0;
  587. resy = 0;
  588. return null;
  589. }
  590. if (start.InternalSubviews != null) {
  591. int count = start.InternalSubviews.Count;
  592. if (count > 0) {
  593. var rx = x - startFrame.X;
  594. var ry = y - startFrame.Y;
  595. for (int i = count - 1; i >= 0; i--) {
  596. View v = start.InternalSubviews [i];
  597. if (v.Visible && v.Frame.Contains (rx, ry)) {
  598. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  599. if (deep == null)
  600. return v;
  601. return deep;
  602. }
  603. }
  604. }
  605. }
  606. resx = x - startFrame.X;
  607. resy = y - startFrame.Y;
  608. return start;
  609. }
  610. static View FindTopFromView (View view)
  611. {
  612. View top = view?.SuperView != null && view?.SuperView != Top
  613. ? view.SuperView : view;
  614. while (top?.SuperView != null && top?.SuperView != Top) {
  615. top = top.SuperView;
  616. }
  617. return top;
  618. }
  619. static View mouseGrabView;
  620. /// <summary>
  621. /// The view that grabbed the mouse, to where will be routed all the mouse events.
  622. /// </summary>
  623. public static View MouseGrabView => mouseGrabView;
  624. /// <summary>
  625. /// Event to be invoked when a view grab the mouse.
  626. /// </summary>
  627. public static event Action<View> GrabbedMouse;
  628. /// <summary>
  629. /// Event to be invoked when a view ungrab the mouse.
  630. /// </summary>
  631. public static event Action<View> UnGrabbedMouse;
  632. /// <summary>
  633. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  634. /// </summary>
  635. /// <returns>The grab.</returns>
  636. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  637. public static void GrabMouse (View view)
  638. {
  639. if (view == null)
  640. return;
  641. OnGrabbedMouse (view);
  642. mouseGrabView = view;
  643. Driver.UncookMouse ();
  644. }
  645. /// <summary>
  646. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  647. /// </summary>
  648. public static void UngrabMouse ()
  649. {
  650. if (mouseGrabView == null)
  651. return;
  652. OnUnGrabbedMouse (mouseGrabView);
  653. mouseGrabView = null;
  654. Driver.CookMouse ();
  655. }
  656. static void OnGrabbedMouse (View view)
  657. {
  658. if (view == null)
  659. return;
  660. GrabbedMouse?.Invoke (view);
  661. }
  662. static void OnUnGrabbedMouse (View view)
  663. {
  664. if (view == null)
  665. return;
  666. UnGrabbedMouse?.Invoke (view);
  667. }
  668. /// <summary>
  669. /// Merely a debugging aid to see the raw mouse events
  670. /// </summary>
  671. public static Action<MouseEvent> RootMouseEvent;
  672. /// <summary>
  673. /// <para>
  674. /// Called for new KeyPress events before any processing is performed or
  675. /// views evaluate. Use for global key handling and/or debugging.
  676. /// </para>
  677. /// <para>Return true to suppress the KeyPress event</para>
  678. /// </summary>
  679. public static Func<KeyEvent, bool> RootKeyEvent;
  680. static View lastMouseOwnerView;
  681. static void ProcessMouseEvent (MouseEvent me)
  682. {
  683. if (IsMouseDisabled) {
  684. return;
  685. }
  686. EnsuresMdiTopOnFrontIfMdiTopMostFocused ();
  687. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  688. if (view != null && view.WantContinuousButtonPressed)
  689. WantContinuousButtonPressedView = view;
  690. else
  691. WantContinuousButtonPressedView = null;
  692. if (view != null) {
  693. me.View = view;
  694. }
  695. RootMouseEvent?.Invoke (me);
  696. if (me.Handled) {
  697. return;
  698. }
  699. if (mouseGrabView != null) {
  700. if (view == null) {
  701. view = mouseGrabView;
  702. }
  703. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  704. var nme = new MouseEvent () {
  705. X = newxy.X,
  706. Y = newxy.Y,
  707. Flags = me.Flags,
  708. OfX = me.X - newxy.X,
  709. OfY = me.Y - newxy.Y,
  710. View = view
  711. };
  712. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame)) {
  713. lastMouseOwnerView?.OnMouseLeave (me);
  714. }
  715. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  716. if (mouseGrabView?.OnMouseEvent (nme) == true) {
  717. return;
  718. }
  719. }
  720. if ((view == null || view == MdiTop || view.SuperView == MdiTop) && !Current.Modal && MdiTop != null
  721. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  722. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  723. view = FindDeepestView (top, me.X, me.Y, out rx, out ry);
  724. if (view != null && view != MdiTop && top != Current && top.MostFocused != null
  725. && top.MostFocused.GetType ().Name != "ContentView") {
  726. MoveCurrent ((Toplevel)top);
  727. }
  728. }
  729. if (view != null) {
  730. var nme = new MouseEvent () {
  731. X = rx,
  732. Y = ry,
  733. Flags = me.Flags,
  734. OfX = 0,
  735. OfY = 0,
  736. View = view
  737. };
  738. if (lastMouseOwnerView == null) {
  739. lastMouseOwnerView = view;
  740. view.OnMouseEnter (nme);
  741. } else if (lastMouseOwnerView != view) {
  742. lastMouseOwnerView.OnMouseLeave (nme);
  743. view.OnMouseEnter (nme);
  744. lastMouseOwnerView = view;
  745. }
  746. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  747. return;
  748. if (view.WantContinuousButtonPressed)
  749. WantContinuousButtonPressedView = view;
  750. else
  751. WantContinuousButtonPressedView = null;
  752. // Should we bubbled up the event, if it is not handled?
  753. if (view.OnMouseEvent (nme)) {
  754. EnsuresMdiTopOnFrontIfMdiTopMostFocused ();
  755. }
  756. EnsuresTopOnFront ();
  757. }
  758. }
  759. static void EnsuresMdiTopOnFrontIfMdiTopMostFocused ()
  760. {
  761. if (MdiTop != null && Current != MdiTop && MdiTop.MostFocused != null
  762. && MdiTop.MostFocused.GetType ().Name != "ContentView") {
  763. MoveCurrent (Top);
  764. }
  765. }
  766. // Only return true if the Current has changed.
  767. static bool MoveCurrent (Toplevel top)
  768. {
  769. // The Current is modal and the top is not modal toplevel then
  770. // the Current must be moved above the first not modal toplevel.
  771. if (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == true && !toplevels.Peek ().Modal) {
  772. lock (toplevels) {
  773. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  774. }
  775. var index = 0;
  776. var savedToplevels = toplevels.ToArray ();
  777. foreach (var t in savedToplevels) {
  778. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  779. lock (toplevels) {
  780. toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  781. }
  782. }
  783. index++;
  784. }
  785. return false;
  786. }
  787. // The Current and the top are both not running toplevel then
  788. // the top must be moved above the first not running toplevel.
  789. if (MdiTop != null && top != MdiTop && top != Current && Current?.Running == false && !top.Running) {
  790. lock (toplevels) {
  791. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  792. }
  793. var index = 0;
  794. foreach (var t in toplevels.ToArray ()) {
  795. if (!t.Running && t != Current && index > 0) {
  796. lock (toplevels) {
  797. toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  798. }
  799. }
  800. index++;
  801. }
  802. return false;
  803. }
  804. if ((MdiTop != null && top?.Modal == true && toplevels.Peek () != top)
  805. || (MdiTop != null && Current != MdiTop && Current?.Modal == false && top == MdiTop)
  806. || (MdiTop != null && Current?.Modal == false && top != Current)
  807. || (MdiTop != null && Current?.Modal == true && top == MdiTop)) {
  808. lock (toplevels) {
  809. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  810. Current = top;
  811. }
  812. }
  813. return true;
  814. }
  815. static bool OutsideFrame (Point p, Rect r)
  816. {
  817. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  818. }
  819. /// <summary>
  820. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  821. /// </summary>
  822. /// <returns>The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  823. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  824. /// <remarks>
  825. /// This method prepares the provided toplevel for running with the focus,
  826. /// it adds this to the list of toplevels, sets up the mainloop to process the
  827. /// event, lays out the subviews, focuses the first element, and draws the
  828. /// toplevel in the screen. This is usually followed by executing
  829. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  830. /// undo these changes.
  831. /// </remarks>
  832. public static RunState Begin (Toplevel toplevel)
  833. {
  834. if (toplevel == null) {
  835. throw new ArgumentNullException (nameof (toplevel));
  836. } else if (toplevel.IsMdiContainer && MdiTop != toplevel && MdiTop != null) {
  837. throw new InvalidOperationException ("Only one Mdi Container is allowed.");
  838. }
  839. var rs = new RunState (toplevel);
  840. if (toplevel is ISupportInitializeNotification initializableNotification &&
  841. !initializableNotification.IsInitialized) {
  842. initializableNotification.BeginInit ();
  843. initializableNotification.EndInit ();
  844. } else if (toplevel is ISupportInitialize initializable) {
  845. initializable.BeginInit ();
  846. initializable.EndInit ();
  847. }
  848. lock (toplevels) {
  849. // If Top was already initialized with Init, and Begin has never been called
  850. // Top was not added to the toplevels Stack. It will thus never get disposed.
  851. // Clean it up here:
  852. if (Top != null && toplevel != Top && !toplevels.Contains (Top)) {
  853. Top.Dispose ();
  854. Top = null;
  855. } else if (Top != null && toplevel != Top && toplevels.Contains (Top)) {
  856. Top.OnLeave (toplevel);
  857. }
  858. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  859. var count = 1;
  860. var id = (toplevels.Count + count).ToString ();
  861. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  862. count++;
  863. id = (toplevels.Count + count).ToString ();
  864. }
  865. toplevel.Id = (toplevels.Count + count).ToString ();
  866. toplevels.Push (toplevel);
  867. } else {
  868. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  869. if (dup == null) {
  870. toplevels.Push (toplevel);
  871. }
  872. }
  873. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  874. throw new ArgumentException ("There are duplicates toplevels Id's");
  875. }
  876. }
  877. // Fix $520 - Set Top = toplevel if Top == null
  878. if (Top == null || toplevel.IsMdiContainer) {
  879. Top = toplevel;
  880. }
  881. var refreshDriver = true;
  882. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  883. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  884. if (toplevel.Visible) {
  885. Current = toplevel;
  886. SetCurrentAsTop ();
  887. } else {
  888. refreshDriver = false;
  889. }
  890. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  891. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  892. refreshDriver = false;
  893. MoveCurrent (toplevel);
  894. } else {
  895. refreshDriver = false;
  896. MoveCurrent (Current);
  897. }
  898. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  899. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  900. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  901. toplevel.LayoutSubviews ();
  902. toplevel.PositionToplevels ();
  903. toplevel.WillPresent ();
  904. if (refreshDriver) {
  905. MdiTop?.OnChildLoaded (toplevel);
  906. toplevel.OnLoaded ();
  907. Redraw (toplevel);
  908. toplevel.PositionCursor ();
  909. Driver.Refresh ();
  910. }
  911. NotifyNewRunState?.Invoke (rs);
  912. return rs;
  913. }
  914. /// <summary>
  915. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  916. /// </summary>
  917. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  918. public static void End (RunState runState)
  919. {
  920. if (runState == null)
  921. throw new ArgumentNullException (nameof (runState));
  922. if (MdiTop != null) {
  923. MdiTop.OnChildUnloaded (runState.Toplevel);
  924. } else {
  925. runState.Toplevel.OnUnloaded ();
  926. }
  927. // End the RunState.Toplevel
  928. // First, take it off the toplevel Stack
  929. if (toplevels.Count > 0) {
  930. if (toplevels.Peek () != runState.Toplevel) {
  931. // If there the top of the stack is not the RunState.Toplevel then
  932. // this call to End is not balanced with the call to Begin that started the RunState
  933. throw new ArgumentException ("End must be balanced with calls to Begin");
  934. }
  935. toplevels.Pop ();
  936. }
  937. // Notify that it is closing
  938. runState.Toplevel?.OnClosed (runState.Toplevel);
  939. // If there is a MdiTop that is not the RunState.Toplevel then runstate.TopLevel
  940. // is a child of MidTop and we should notify the MdiTop that it is closing
  941. if (MdiTop != null && !(runState.Toplevel).Modal && runState.Toplevel != MdiTop) {
  942. MdiTop.OnChildClosed (runState.Toplevel);
  943. }
  944. // Set Current and Top to the next TopLevel on the stack
  945. if (toplevels.Count == 0) {
  946. Current = null;
  947. } else {
  948. Current = toplevels.Peek ();
  949. if (toplevels.Count == 1 && Current == MdiTop) {
  950. MdiTop.OnAllChildClosed ();
  951. } else {
  952. SetCurrentAsTop ();
  953. runState.Toplevel.OnLeave (Current);
  954. Current.OnEnter (runState.Toplevel);
  955. }
  956. Refresh ();
  957. }
  958. runState.Toplevel?.Dispose ();
  959. runState.Toplevel = null;
  960. runState.Dispose ();
  961. }
  962. /// <summary>
  963. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  964. /// </summary>
  965. /// <remarks>
  966. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  967. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  968. /// </remarks>
  969. public static void Shutdown ()
  970. {
  971. ResetState ();
  972. }
  973. // Encapsulate all setting of initial state for Application; Having
  974. // this in a function like this ensures we don't make mistakes in
  975. // guaranteeing that the state of this singleton is deterministic when Init
  976. // starts running and after Shutdown returns.
  977. static void ResetState ()
  978. {
  979. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  980. // Init created. Apps that do any threading will need to code defensively for this.
  981. // e.g. see Issue #537
  982. foreach (var t in toplevels) {
  983. t.Running = false;
  984. t.Dispose ();
  985. }
  986. toplevels.Clear ();
  987. Current = null;
  988. Top?.Dispose ();
  989. Top = null;
  990. // BUGBUG: MdiTop is not cleared here, but it should be?
  991. MainLoop = null;
  992. Driver?.End ();
  993. Driver = null;
  994. Iteration = null;
  995. RootMouseEvent = null;
  996. RootKeyEvent = null;
  997. Resized = null;
  998. _mainThreadId = -1;
  999. NotifyNewRunState = null;
  1000. NotifyStopRunState = null;
  1001. _initialized = false;
  1002. mouseGrabView = null;
  1003. // Reset synchronization context to allow the user to run async/await,
  1004. // as the main loop has been ended, the synchronization context from
  1005. // gui.cs does no longer process any callbacks. See #1084 for more details:
  1006. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  1007. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  1008. }
  1009. static void Redraw (View view)
  1010. {
  1011. view.Redraw (view.Bounds);
  1012. Driver.Refresh ();
  1013. }
  1014. /// <summary>
  1015. /// Triggers a refresh of the entire display.
  1016. /// </summary>
  1017. public static void Refresh ()
  1018. {
  1019. Driver.UpdateOffScreen ();
  1020. View last = null;
  1021. foreach (var v in toplevels.Reverse ()) {
  1022. if (v.Visible) {
  1023. v.SetNeedsDisplay ();
  1024. v.Redraw (v.Bounds);
  1025. }
  1026. last = v;
  1027. }
  1028. last?.PositionCursor ();
  1029. Driver.Refresh ();
  1030. }
  1031. /// <summary>
  1032. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  1033. /// </summary>
  1034. /// <remarks>
  1035. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  1036. /// </remarks>
  1037. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1038. /// <param name="wait">By default this is <see langword="true"/> which will execute the runloop waiting for events,
  1039. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  1040. public static void RunLoop (RunState state, bool wait = true)
  1041. {
  1042. if (state == null)
  1043. throw new ArgumentNullException (nameof (state));
  1044. if (state.Toplevel == null)
  1045. throw new ObjectDisposedException ("state");
  1046. bool firstIteration = true;
  1047. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1048. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  1049. return;
  1050. }
  1051. RunMainLoopIteration (ref state, wait, ref firstIteration);
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// Run one iteration of the <see cref="MainLoop"/>.
  1056. /// </summary>
  1057. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  1058. /// <param name="wait">If <see langword="true"/> will execute the runloop waiting for events. If <see langword="true"/>
  1059. /// will return after a single iteration.</param>
  1060. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  1061. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  1062. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  1063. {
  1064. if (MainLoop.EventsPending (wait)) {
  1065. // Notify Toplevel it's ready
  1066. if (firstIteration) {
  1067. state.Toplevel.OnReady ();
  1068. }
  1069. MainLoop.MainIteration ();
  1070. Iteration?.Invoke ();
  1071. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  1072. if (!EnsuresNotModalNotRunningAndNotCurrent (state.Toplevel)) {
  1073. EnsuresMdiChildOnFrontIfMdiTopNotMostFocused ();
  1074. }
  1075. if ((state.Toplevel != Current && Current?.Modal == true)
  1076. || (state.Toplevel != Current && Current?.Modal == false)) {
  1077. MdiTop?.OnDeactivate (state.Toplevel);
  1078. state.Toplevel = Current;
  1079. MdiTop?.OnActivate (state.Toplevel);
  1080. Top.SetChildNeedsDisplay ();
  1081. Refresh ();
  1082. }
  1083. if (Driver.EnsureCursorVisibility ()) {
  1084. state.Toplevel.SetNeedsDisplay ();
  1085. }
  1086. } else if (!wait) {
  1087. return;
  1088. }
  1089. firstIteration = false;
  1090. if (state.Toplevel != Top
  1091. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  1092. Top.Redraw (Top.Bounds);
  1093. foreach (var top in toplevels.Reverse ()) {
  1094. if (top != Top && top != state.Toplevel) {
  1095. top.SetNeedsDisplay ();
  1096. top.Redraw (top.Bounds);
  1097. }
  1098. }
  1099. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  1100. }
  1101. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.ChildNeedsDisplay || state.Toplevel.LayoutNeeded
  1102. || MdiChildNeedsDisplay ()) {
  1103. bool isTopNeedsDisplay;
  1104. do {
  1105. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1106. if (DebugDrawBounds) {
  1107. DrawBounds (state.Toplevel);
  1108. }
  1109. state.Toplevel.PositionCursor ();
  1110. Driver.Refresh ();
  1111. isTopNeedsDisplay = IsTopNeedsDisplay (state.Toplevel);
  1112. if (isTopNeedsDisplay) {
  1113. Top.Redraw (Top.Bounds);
  1114. state.Toplevel.SetNeedsDisplay ();
  1115. }
  1116. } while (isTopNeedsDisplay);
  1117. } else {
  1118. Driver.UpdateCursor ();
  1119. }
  1120. bool IsTopNeedsDisplay (Toplevel toplevel)
  1121. {
  1122. if (toplevel != Top && !toplevel.Modal
  1123. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  1124. return true;
  1125. }
  1126. return false;
  1127. }
  1128. }
  1129. static void EnsuresMdiChildOnFrontIfMdiTopNotMostFocused ()
  1130. {
  1131. if (MdiTop != null && Current == MdiTop && (MdiTop.MostFocused == null
  1132. || MdiTop.MostFocused.GetType ().Name == "ContentView")) {
  1133. MoveNext ();
  1134. }
  1135. }
  1136. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  1137. {
  1138. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  1139. return;
  1140. }
  1141. foreach (var top in toplevels.Reverse ()) {
  1142. if (top.Modal && top != Current) {
  1143. MoveCurrent (top);
  1144. return;
  1145. }
  1146. }
  1147. if (!toplevel.Visible && toplevel == Current) {
  1148. MoveNext ();
  1149. }
  1150. }
  1151. static bool EnsuresNotModalNotRunningAndNotCurrent (Toplevel curRunStateTop)
  1152. {
  1153. if (MdiTop == null || !curRunStateTop.Running) {
  1154. return false;
  1155. }
  1156. foreach (var top in toplevels) {
  1157. if (!top.IsMdiContainer && top?.Running == false && top != Current && top?.Modal == false) {
  1158. MoveCurrent (top);
  1159. return true;
  1160. }
  1161. }
  1162. return false;
  1163. }
  1164. static bool MdiChildNeedsDisplay ()
  1165. {
  1166. if (MdiTop == null) {
  1167. return false;
  1168. }
  1169. foreach (var top in toplevels) {
  1170. if (top != Current && top.Visible && (!top.NeedDisplay.IsEmpty || top.ChildNeedsDisplay || top.LayoutNeeded)) {
  1171. MdiTop.SetChildNeedsDisplay ();
  1172. return true;
  1173. }
  1174. }
  1175. return false;
  1176. }
  1177. internal static bool DebugDrawBounds = false;
  1178. // Need to look into why this does not work properly.
  1179. static void DrawBounds (View v)
  1180. {
  1181. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1182. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1183. foreach (var sub in v.InternalSubviews)
  1184. DrawBounds (sub);
  1185. }
  1186. /// <summary>
  1187. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  1188. /// </summary>
  1189. /// <remarks>
  1190. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1191. /// </remarks>
  1192. public static void Run (Func<Exception, bool> errorHandler = null)
  1193. {
  1194. Run (Top, errorHandler);
  1195. }
  1196. /// <summary>
  1197. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  1198. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  1199. /// <para>
  1200. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialze the application.
  1201. /// </para>
  1202. /// <para>
  1203. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  1204. /// returned) to ensure resources are cleaned up and terminal settings restored.
  1205. /// </para>
  1206. /// </summary>
  1207. /// <remarks>
  1208. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1209. /// </remarks>
  1210. /// <param name="errorHandler"></param>
  1211. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  1212. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  1213. /// This parameteter must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  1214. /// </param>
  1215. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  1216. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  1217. {
  1218. if (_initialized) {
  1219. if (Driver != null) {
  1220. // Init() has been called and we have a driver, so just run the app.
  1221. var top = new T ();
  1222. var type = top.GetType ().BaseType;
  1223. while (type != typeof (Toplevel) && type != typeof (object)) {
  1224. type = type.BaseType;
  1225. }
  1226. if (type != typeof (Toplevel)) {
  1227. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1228. }
  1229. Run (top, errorHandler);
  1230. } else {
  1231. // This codepath should be impossible because Init(null, null) will select the platform default driver
  1232. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  1233. }
  1234. } else {
  1235. // Init() has NOT been called.
  1236. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  1237. Run (Top, errorHandler);
  1238. }
  1239. }
  1240. /// <summary>
  1241. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1242. /// </summary>
  1243. /// <remarks>
  1244. /// <para>
  1245. /// This method is used to start processing events
  1246. /// for the main application, but it is also used to
  1247. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1248. /// </para>
  1249. /// <para>
  1250. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1251. /// </para>
  1252. /// <para>
  1253. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1254. /// and then calling <see cref="End(RunState)"/>.
  1255. /// </para>
  1256. /// <para>
  1257. /// Alternatively, to have a program control the main loop and
  1258. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1259. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1260. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1261. /// then return control immediately.
  1262. /// </para>
  1263. /// <para>
  1264. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  1265. /// Otheriwse, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  1266. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  1267. /// this method will exit.
  1268. /// </para>
  1269. /// </remarks>
  1270. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1271. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1272. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1273. {
  1274. var resume = true;
  1275. while (resume) {
  1276. #if !DEBUG
  1277. try {
  1278. #endif
  1279. resume = false;
  1280. var runToken = Begin (view);
  1281. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  1282. // by using NotifyStopRunState event.
  1283. RunLoop (runToken);
  1284. if (!ExitRunLoopAfterFirstIteration) {
  1285. End (runToken);
  1286. }
  1287. #if !DEBUG
  1288. }
  1289. catch (Exception error)
  1290. {
  1291. if (errorHandler == null)
  1292. {
  1293. throw;
  1294. }
  1295. resume = errorHandler(error);
  1296. }
  1297. #endif
  1298. }
  1299. }
  1300. /// <summary>
  1301. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1302. /// </summary>
  1303. /// <param name="top">The toplevel to request stop.</param>
  1304. /// <remarks>
  1305. /// <para>
  1306. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1307. /// </para>
  1308. /// <para>
  1309. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1310. /// </para>
  1311. /// </remarks>
  1312. public static void RequestStop (Toplevel top = null)
  1313. {
  1314. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1315. top = Current;
  1316. }
  1317. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1318. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1319. MdiTop.RequestStop ();
  1320. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1321. && top.Modal && top.Running) {
  1322. var ev = new ToplevelClosingEventArgs (Current);
  1323. Current.OnClosing (ev);
  1324. if (ev.Cancel) {
  1325. return;
  1326. }
  1327. ev = new ToplevelClosingEventArgs (top);
  1328. top.OnClosing (ev);
  1329. if (ev.Cancel) {
  1330. return;
  1331. }
  1332. Current.Running = false;
  1333. OnNotifyStopRunState (Current);
  1334. top.Running = false;
  1335. OnNotifyStopRunState (top);
  1336. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1337. && Current?.Running == true && !top.Running)
  1338. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1339. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1340. MoveCurrent (top);
  1341. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1342. && Current?.Modal == true && top.Modal) {
  1343. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1344. Current.Running = false;
  1345. OnNotifyStopRunState (Current);
  1346. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1347. && Current?.Modal == true && top.Modal) {
  1348. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1349. // both are the same, so needed to set the Current.Running to false too.
  1350. Current.Running = false;
  1351. OnNotifyStopRunState (Current);
  1352. } else {
  1353. Toplevel currentTop;
  1354. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1355. currentTop = Current;
  1356. } else {
  1357. currentTop = top;
  1358. }
  1359. if (!currentTop.Running) {
  1360. return;
  1361. }
  1362. var ev = new ToplevelClosingEventArgs (currentTop);
  1363. currentTop.OnClosing (ev);
  1364. if (ev.Cancel) {
  1365. return;
  1366. }
  1367. currentTop.Running = false;
  1368. OnNotifyStopRunState (currentTop);
  1369. }
  1370. }
  1371. static void OnNotifyStopRunState (Toplevel top)
  1372. {
  1373. if (ExitRunLoopAfterFirstIteration) {
  1374. NotifyStopRunState?.Invoke (top);
  1375. }
  1376. }
  1377. /// <summary>
  1378. /// Event arguments for the <see cref="Application.Resized"/> event.
  1379. /// </summary>
  1380. public class ResizedEventArgs : EventArgs {
  1381. /// <summary>
  1382. /// The number of rows in the resized terminal.
  1383. /// </summary>
  1384. public int Rows { get; set; }
  1385. /// <summary>
  1386. /// The number of columns in the resized terminal.
  1387. /// </summary>
  1388. public int Cols { get; set; }
  1389. }
  1390. /// <summary>
  1391. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1392. /// </summary>
  1393. public static Action<ResizedEventArgs> Resized;
  1394. static void TerminalResized ()
  1395. {
  1396. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1397. SetToplevelsSize (full);
  1398. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1399. Driver.Clip = full;
  1400. foreach (var t in toplevels) {
  1401. t.SetRelativeLayout (full);
  1402. t.LayoutSubviews ();
  1403. t.PositionToplevels ();
  1404. t.OnResized (full.Size);
  1405. }
  1406. Refresh ();
  1407. }
  1408. static void SetToplevelsSize (Rect full)
  1409. {
  1410. if (MdiTop == null) {
  1411. foreach (var t in toplevels) {
  1412. if (t?.SuperView == null && !t.Modal) {
  1413. t.Frame = full;
  1414. t.Width = full.Width;
  1415. t.Height = full.Height;
  1416. }
  1417. }
  1418. } else {
  1419. Top.Frame = full;
  1420. Top.Width = full.Width;
  1421. Top.Height = full.Height;
  1422. }
  1423. }
  1424. static bool SetCurrentAsTop ()
  1425. {
  1426. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1427. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1428. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1429. }
  1430. Top = Current;
  1431. return true;
  1432. }
  1433. return false;
  1434. }
  1435. /// <summary>
  1436. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1437. /// </summary>
  1438. public static void MoveNext ()
  1439. {
  1440. if (MdiTop != null && !Current.Modal) {
  1441. lock (toplevels) {
  1442. toplevels.MoveNext ();
  1443. var isMdi = false;
  1444. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1445. if (!isMdi && toplevels.Peek () == MdiTop) {
  1446. isMdi = true;
  1447. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1448. MoveCurrent (Top);
  1449. break;
  1450. }
  1451. toplevels.MoveNext ();
  1452. }
  1453. Current = toplevels.Peek ();
  1454. }
  1455. }
  1456. }
  1457. /// <summary>
  1458. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1459. /// </summary>
  1460. public static void MovePrevious ()
  1461. {
  1462. if (MdiTop != null && !Current.Modal) {
  1463. lock (toplevels) {
  1464. toplevels.MovePrevious ();
  1465. var isMdi = false;
  1466. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1467. if (!isMdi && toplevels.Peek () == MdiTop) {
  1468. isMdi = true;
  1469. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1470. MoveCurrent (Top);
  1471. break;
  1472. }
  1473. toplevels.MovePrevious ();
  1474. }
  1475. Current = toplevels.Peek ();
  1476. }
  1477. }
  1478. }
  1479. internal static bool ShowChild (Toplevel top)
  1480. {
  1481. if (Current == top) {
  1482. return false;
  1483. }
  1484. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1485. lock (toplevels) {
  1486. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1487. Current = top;
  1488. }
  1489. return true;
  1490. }
  1491. return false;
  1492. }
  1493. /// <summary>
  1494. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1495. /// </summary>
  1496. public static void DoEvents ()
  1497. {
  1498. MainLoop.Driver.Wakeup ();
  1499. }
  1500. /// <summary>
  1501. /// Ensures that the superview of the most focused view is on front.
  1502. /// </summary>
  1503. public static void EnsuresTopOnFront ()
  1504. {
  1505. if (MdiTop != null) {
  1506. return;
  1507. }
  1508. var top = FindTopFromView (Top?.MostFocused);
  1509. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1510. Top.BringSubviewToFront (top);
  1511. }
  1512. }
  1513. internal static List<CultureInfo> GetSupportedCultures ()
  1514. {
  1515. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1516. // Get the assembly
  1517. Assembly assembly = Assembly.GetExecutingAssembly ();
  1518. //Find the location of the assembly
  1519. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1520. // Find the resource file name of the assembly
  1521. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1522. // Return all culture for which satellite folder found with culture code.
  1523. return culture.Where (cultureInfo =>
  1524. assemblyLocation != null &&
  1525. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1526. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1527. ).ToList ();
  1528. }
  1529. }
  1530. }