2
0

Application.cs 53 KB

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