Application.cs 51 KB

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