Application.cs 54 KB

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