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