Application.cs 50 KB

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