Application.cs 51 KB

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