Application.cs 53 KB

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