Application.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  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 ($"Example App ({Application.QuitKey} 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 partial 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 (new KeyChangedEventArgs (oldKey, value));
  154. }
  155. }
  156. }
  157. static void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  158. {
  159. foreach (var top in toplevels.ToArray ()) {
  160. top.OnAlternateForwardKeyChanged (e);
  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 (new KeyChangedEventArgs (oldKey, value));
  175. }
  176. }
  177. }
  178. static void OnAlternateBackwardKeyChanged (KeyChangedEventArgs 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 (new KeyChangedEventArgs (oldKey, value));
  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 (KeyChangedEventArgs e)
  205. {
  206. // Duplicate the list so if it changes during enumeration we're safe
  207. foreach (var top in toplevels.ToArray ()) {
  208. top.OnQuitKeyChanged (e);
  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 EventHandler<RunStateEventArgs> 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 EventHandler<ToplevelEventArgs> 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. /// <summary>
  607. /// Finds the deepest view at the specified coordinates, specified relative to <paramref name="start"/>'s superview.
  608. /// </summary>
  609. /// <param name="start"></param>
  610. /// <param name="x"></param>
  611. /// <param name="y"></param>
  612. /// <param name="resx"></param>
  613. /// <param name="resy"></param>
  614. /// <returns></returns>
  615. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  616. {
  617. //var startFrame = start.Frame;
  618. var startRect = new Rect (start.Frame.X + start.GetBoundsOffset().X, start.Frame.Y + start.GetBoundsOffset ().Y, start.Bounds.Width, start.Bounds.Height);
  619. if (!startRect.Contains (x, y)) {
  620. resx = 0;
  621. resy = 0;
  622. return null;
  623. }
  624. //startFrame = start.Padding.Thickness.GetInside (start.BorderFrame.Thickness.GetInside (start.Margin.Thickness.GetInside (startFrame)));
  625. if (start.InternalSubviews != null) {
  626. int count = start.InternalSubviews.Count;
  627. if (count > 0) {
  628. var rx = x - startRect.X;
  629. var ry = y - startRect.Y;
  630. for (int i = count - 1; i >= 0; i--) {
  631. View v = start.InternalSubviews [i];
  632. // BUGBUG: v2 - I think it's a bug that we use v.Frame.Contains here vs. Frame + v.GetBoundsOffset
  633. if (v.Visible && v.Frame.Contains (rx, ry)) {
  634. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  635. if (deep == null)
  636. return v;
  637. return deep;
  638. }
  639. }
  640. }
  641. }
  642. resx = x - startRect.X;
  643. resy = y - startRect.Y;
  644. return start;
  645. }
  646. static View FindTopFromView (View view)
  647. {
  648. View top = view?.SuperView != null && view?.SuperView != Top
  649. ? view.SuperView : view;
  650. while (top?.SuperView != null && top?.SuperView != Top) {
  651. top = top.SuperView;
  652. }
  653. return top;
  654. }
  655. static View mouseGrabView;
  656. /// <summary>
  657. /// The view that grabbed the mouse, to where will be routed all the mouse events.
  658. /// </summary>
  659. public static View MouseGrabView => mouseGrabView;
  660. /// <summary>
  661. /// Event to be invoked when a view want grab the mouse which can be canceled.
  662. /// </summary>
  663. public static event EventHandler<GrabMouseEventArgs> GrabbingMouse;
  664. /// <summary>
  665. /// Event to be invoked when a view want ungrab the mouse which can be canceled.
  666. /// </summary>
  667. public static event EventHandler<GrabMouseEventArgs> UnGrabbingMouse;
  668. /// <summary>
  669. /// Event to be invoked when a view grab the mouse.
  670. /// </summary>
  671. public static event EventHandler<ViewEventArgs> GrabbedMouse;
  672. /// <summary>
  673. /// Event to be invoked when a view ungrab the mouse.
  674. /// </summary>
  675. public static event EventHandler<ViewEventArgs> UnGrabbedMouse;
  676. /// <summary>
  677. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  678. /// </summary>
  679. /// <returns>The grab.</returns>
  680. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  681. public static void GrabMouse (View view)
  682. {
  683. if (view == null)
  684. return;
  685. if (!OnGrabbingMouse (view)) {
  686. OnGrabbedMouse (view);
  687. mouseGrabView = view;
  688. Driver.UncookMouse ();
  689. }
  690. }
  691. /// <summary>
  692. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  693. /// </summary>
  694. public static void UngrabMouse ()
  695. {
  696. if (mouseGrabView == null)
  697. return;
  698. if (!OnUnGrabbingMouse (mouseGrabView)) {
  699. OnUnGrabbedMouse (mouseGrabView);
  700. mouseGrabView = null;
  701. Driver.CookMouse ();
  702. }
  703. }
  704. static bool OnGrabbingMouse (View view)
  705. {
  706. if (view == null)
  707. return false;
  708. var evArgs = new GrabMouseEventArgs (view);
  709. GrabbingMouse?.Invoke (view, evArgs);
  710. return evArgs.Cancel;
  711. }
  712. static bool OnUnGrabbingMouse (View view)
  713. {
  714. if (view == null)
  715. return false;
  716. var evArgs = new GrabMouseEventArgs (view);
  717. UnGrabbingMouse?.Invoke (view, evArgs);
  718. return evArgs.Cancel;
  719. }
  720. static void OnGrabbedMouse (View view)
  721. {
  722. if (view == null)
  723. return;
  724. GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  725. }
  726. static void OnUnGrabbedMouse (View view)
  727. {
  728. if (view == null)
  729. return;
  730. UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
  731. }
  732. /// <summary>
  733. /// Merely a debugging aid to see the raw mouse events
  734. /// </summary>
  735. public static Action<MouseEvent> RootMouseEvent;
  736. /// <summary>
  737. /// <para>
  738. /// Called for new KeyPress events before any processing is performed or
  739. /// views evaluate. Use for global key handling and/or debugging.
  740. /// </para>
  741. /// <para>Return true to suppress the KeyPress event</para>
  742. /// </summary>
  743. public static Func<KeyEvent, bool> RootKeyEvent;
  744. static View lastMouseOwnerView;
  745. static void ProcessMouseEvent (MouseEvent me)
  746. {
  747. if (IsMouseDisabled) {
  748. return;
  749. }
  750. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  751. if (view != null && view.WantContinuousButtonPressed)
  752. WantContinuousButtonPressedView = view;
  753. else
  754. WantContinuousButtonPressedView = null;
  755. if (view != null) {
  756. me.View = view;
  757. }
  758. RootMouseEvent?.Invoke (me);
  759. if (me.Handled) {
  760. return;
  761. }
  762. if (mouseGrabView != null) {
  763. view ??= mouseGrabView;
  764. var newxy = mouseGrabView.ScreenToBounds (me.X, me.Y);
  765. var nme = new MouseEvent () {
  766. X = newxy.X,
  767. Y = newxy.Y,
  768. Flags = me.Flags,
  769. OfX = me.X - newxy.X,
  770. OfY = me.Y - newxy.Y,
  771. View = view
  772. };
  773. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame)) {
  774. lastMouseOwnerView?.OnMouseLeave (me);
  775. }
  776. //System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  777. if (mouseGrabView?.OnMouseEvent (nme) == true) {
  778. return;
  779. }
  780. }
  781. if ((view == null || view == MdiTop) && !Current.Modal && MdiTop != null
  782. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  783. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  784. view = FindDeepestView (top, me.X, me.Y, out rx, out ry);
  785. if (view != null && view != MdiTop && top != Current) {
  786. MoveCurrent ((Toplevel)top);
  787. }
  788. }
  789. if (view != null) {
  790. var nme = new MouseEvent () {
  791. X = rx,
  792. Y = ry,
  793. Flags = me.Flags,
  794. OfX = 0,
  795. OfY = 0,
  796. View = view
  797. };
  798. if (lastMouseOwnerView == null) {
  799. lastMouseOwnerView = view;
  800. view.OnMouseEnter (nme);
  801. } else if (lastMouseOwnerView != view) {
  802. lastMouseOwnerView.OnMouseLeave (nme);
  803. view.OnMouseEnter (nme);
  804. lastMouseOwnerView = view;
  805. }
  806. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  807. return;
  808. if (view.WantContinuousButtonPressed)
  809. WantContinuousButtonPressedView = view;
  810. else
  811. WantContinuousButtonPressedView = null;
  812. // Should we bubbled up the event, if it is not handled?
  813. view.OnMouseEvent (nme);
  814. EnsuresTopOnFront ();
  815. }
  816. }
  817. // Only return true if the Current has changed.
  818. static bool MoveCurrent (Toplevel top)
  819. {
  820. // The Current is modal and the top is not modal toplevel then
  821. // the Current must be moved above the first not modal toplevel.
  822. if (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == true && !toplevels.Peek ().Modal) {
  823. lock (toplevels) {
  824. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  825. }
  826. var index = 0;
  827. var savedToplevels = toplevels.ToArray ();
  828. foreach (var t in savedToplevels) {
  829. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  830. lock (toplevels) {
  831. toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  832. }
  833. }
  834. index++;
  835. }
  836. return false;
  837. }
  838. // The Current and the top are both not running toplevel then
  839. // the top must be moved above the first not running toplevel.
  840. if (MdiTop != null && top != MdiTop && top != Current && Current?.Running == false && !top.Running) {
  841. lock (toplevels) {
  842. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  843. }
  844. var index = 0;
  845. foreach (var t in toplevels.ToArray ()) {
  846. if (!t.Running && t != Current && index > 0) {
  847. lock (toplevels) {
  848. toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  849. }
  850. }
  851. index++;
  852. }
  853. return false;
  854. }
  855. if ((MdiTop != null && top?.Modal == true && toplevels.Peek () != top)
  856. || (MdiTop != null && Current != MdiTop && Current?.Modal == false && top == MdiTop)
  857. || (MdiTop != null && Current?.Modal == false && top != Current)
  858. || (MdiTop != null && Current?.Modal == true && top == MdiTop)) {
  859. lock (toplevels) {
  860. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  861. Current = top;
  862. }
  863. }
  864. return true;
  865. }
  866. static bool OutsideFrame (Point p, Rect r)
  867. {
  868. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  869. }
  870. /// <summary>
  871. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  872. /// </summary>
  873. /// <returns>The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  874. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  875. /// <remarks>
  876. /// This method prepares the provided toplevel for running with the focus,
  877. /// it adds this to the list of toplevels, sets up the mainloop to process the
  878. /// event, lays out the subviews, focuses the first element, and draws the
  879. /// toplevel in the screen. This is usually followed by executing
  880. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  881. /// undo these changes.
  882. /// </remarks>
  883. public static RunState Begin (Toplevel toplevel)
  884. {
  885. if (toplevel == null) {
  886. throw new ArgumentNullException (nameof (toplevel));
  887. } else if (toplevel.IsMdiContainer && MdiTop != toplevel && MdiTop != null) {
  888. throw new InvalidOperationException ("Only one Mdi Container is allowed.");
  889. }
  890. var rs = new RunState (toplevel);
  891. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  892. if (!toplevel.IsInitialized) {
  893. toplevel.BeginInit ();
  894. toplevel.EndInit ();
  895. }
  896. lock (toplevels) {
  897. // If Top was already initialized with Init, and Begin has never been called
  898. // Top was not added to the toplevels Stack. It will thus never get disposed.
  899. // Clean it up here:
  900. if (Top != null && toplevel != Top && !toplevels.Contains (Top)) {
  901. Top.Dispose ();
  902. Top = null;
  903. } else if (Top != null && toplevel != Top && toplevels.Contains (Top)) {
  904. Top.OnLeave (toplevel);
  905. }
  906. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  907. var count = 1;
  908. var id = (toplevels.Count + count).ToString ();
  909. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  910. count++;
  911. id = (toplevels.Count + count).ToString ();
  912. }
  913. toplevel.Id = (toplevels.Count + count).ToString ();
  914. toplevels.Push (toplevel);
  915. } else {
  916. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  917. if (dup == null) {
  918. toplevels.Push (toplevel);
  919. }
  920. }
  921. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  922. throw new ArgumentException ("There are duplicates toplevels Id's");
  923. }
  924. }
  925. // Fix $520 - Set Top = toplevel if Top == null
  926. if (Top == null || toplevel.IsMdiContainer) {
  927. Top = toplevel;
  928. }
  929. var refreshDriver = true;
  930. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  931. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  932. if (toplevel.Visible) {
  933. Current = toplevel;
  934. SetCurrentAsTop ();
  935. } else {
  936. refreshDriver = false;
  937. }
  938. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  939. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  940. refreshDriver = false;
  941. MoveCurrent (toplevel);
  942. } else {
  943. refreshDriver = false;
  944. MoveCurrent (Current);
  945. }
  946. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  947. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  948. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  949. toplevel.LayoutSubviews ();
  950. toplevel.PositionToplevels ();
  951. toplevel.WillPresent ();
  952. if (refreshDriver) {
  953. MdiTop?.OnChildLoaded (toplevel);
  954. toplevel.OnLoaded ();
  955. Redraw (toplevel);
  956. toplevel.PositionCursor ();
  957. Driver.Refresh ();
  958. }
  959. NotifyNewRunState?.Invoke (toplevel, new RunStateEventArgs (rs));
  960. return rs;
  961. }
  962. /// <summary>
  963. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  964. /// </summary>
  965. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  966. public static void End (RunState runState)
  967. {
  968. if (runState == null)
  969. throw new ArgumentNullException (nameof (runState));
  970. if (MdiTop != null) {
  971. MdiTop.OnChildUnloaded (runState.Toplevel);
  972. } else {
  973. runState.Toplevel.OnUnloaded ();
  974. }
  975. // End the RunState.Toplevel
  976. // First, take it off the toplevel Stack
  977. if (toplevels.Count > 0) {
  978. if (toplevels.Peek () != runState.Toplevel) {
  979. // If there the top of the stack is not the RunState.Toplevel then
  980. // this call to End is not balanced with the call to Begin that started the RunState
  981. throw new ArgumentException ("End must be balanced with calls to Begin");
  982. }
  983. toplevels.Pop ();
  984. }
  985. // Notify that it is closing
  986. runState.Toplevel?.OnClosed (runState.Toplevel);
  987. // If there is a MdiTop that is not the RunState.Toplevel then runstate.TopLevel
  988. // is a child of MidTop and we should notify the MdiTop that it is closing
  989. if (MdiTop != null && !(runState.Toplevel).Modal && runState.Toplevel != MdiTop) {
  990. MdiTop.OnChildClosed (runState.Toplevel);
  991. }
  992. // Set Current and Top to the next TopLevel on the stack
  993. if (toplevels.Count == 0) {
  994. Current = null;
  995. } else {
  996. Current = toplevels.Peek ();
  997. if (toplevels.Count == 1 && Current == MdiTop) {
  998. MdiTop.OnAllChildClosed ();
  999. } else {
  1000. SetCurrentAsTop ();
  1001. Current.OnEnter (Current);
  1002. }
  1003. Refresh ();
  1004. }
  1005. runState.Toplevel?.Dispose ();
  1006. runState.Toplevel = null;
  1007. runState.Dispose ();
  1008. }
  1009. /// <summary>
  1010. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  1011. /// </summary>
  1012. /// <remarks>
  1013. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  1014. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  1015. /// </remarks>
  1016. public static void Shutdown ()
  1017. {
  1018. ResetState ();
  1019. ConfigurationManager.PrintJsonErrors ();
  1020. }
  1021. // Encapsulate all setting of initial state for Application; Having
  1022. // this in a function like this ensures we don't make mistakes in
  1023. // guaranteeing that the state of this singleton is deterministic when Init
  1024. // starts running and after Shutdown returns.
  1025. static void ResetState ()
  1026. {
  1027. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  1028. // Init created. Apps that do any threading will need to code defensively for this.
  1029. // e.g. see Issue #537
  1030. foreach (var t in toplevels) {
  1031. t.Running = false;
  1032. t.Dispose ();
  1033. }
  1034. toplevels.Clear ();
  1035. Current = null;
  1036. Top?.Dispose ();
  1037. Top = null;
  1038. // BUGBUG: MdiTop is not cleared here, but it should be?
  1039. MainLoop = null;
  1040. Driver?.End ();
  1041. Driver = null;
  1042. Iteration = null;
  1043. RootMouseEvent = null;
  1044. RootKeyEvent = null;
  1045. Resized = null;
  1046. _mainThreadId = -1;
  1047. NotifyNewRunState = null;
  1048. NotifyStopRunState = null;
  1049. _initialized = false;
  1050. mouseGrabView = null;
  1051. _enableConsoleScrolling = false;
  1052. lastMouseOwnerView = null;
  1053. // Reset synchronization context to allow the user to run async/await,
  1054. // as the main loop has been ended, the synchronization context from
  1055. // gui.cs does no longer process any callbacks. See #1084 for more details:
  1056. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  1057. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  1058. }
  1059. static void Redraw (View view)
  1060. {
  1061. view.Redraw (view.Bounds);
  1062. Driver.Refresh ();
  1063. }
  1064. /// <summary>
  1065. /// Triggers a refresh of the entire display.
  1066. /// </summary>
  1067. public static void Refresh ()
  1068. {
  1069. Driver.UpdateOffScreen ();
  1070. View last = null;
  1071. foreach (var v in toplevels.Reverse ()) {
  1072. if (v.Visible) {
  1073. v.SetNeedsDisplay ();
  1074. v.Redraw (v.Bounds);
  1075. }
  1076. last = v;
  1077. }
  1078. last?.PositionCursor ();
  1079. Driver.Refresh ();
  1080. }
  1081. /// <summary>
  1082. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  1083. /// </summary>
  1084. /// <remarks>
  1085. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  1086. /// </remarks>
  1087. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1088. /// <param name="wait">By default this is <see langword="true"/> which will execute the runloop waiting for events,
  1089. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  1090. public static void RunLoop (RunState state, bool wait = true)
  1091. {
  1092. if (state == null)
  1093. throw new ArgumentNullException (nameof (state));
  1094. if (state.Toplevel == null)
  1095. throw new ObjectDisposedException ("state");
  1096. bool firstIteration = true;
  1097. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1098. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  1099. return;
  1100. }
  1101. RunMainLoopIteration (ref state, wait, ref firstIteration);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Run one iteration of the <see cref="MainLoop"/>.
  1106. /// </summary>
  1107. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  1108. /// <param name="wait">If <see langword="true"/> will execute the runloop waiting for events. If <see langword="true"/>
  1109. /// will return after a single iteration.</param>
  1110. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  1111. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  1112. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  1113. {
  1114. if (MainLoop.EventsPending (wait)) {
  1115. // Notify Toplevel it's ready
  1116. if (firstIteration) {
  1117. state.Toplevel.OnReady ();
  1118. }
  1119. MainLoop.MainIteration ();
  1120. Iteration?.Invoke ();
  1121. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  1122. if ((state.Toplevel != Current && Current?.Modal == true)
  1123. || (state.Toplevel != Current && Current?.Modal == false)) {
  1124. MdiTop?.OnDeactivate (state.Toplevel);
  1125. state.Toplevel = Current;
  1126. MdiTop?.OnActivate (state.Toplevel);
  1127. Top.SetSubViewNeedsDisplay ();
  1128. Refresh ();
  1129. }
  1130. if (Driver.EnsureCursorVisibility ()) {
  1131. state.Toplevel.SetNeedsDisplay ();
  1132. }
  1133. } else if (!wait) {
  1134. return;
  1135. }
  1136. firstIteration = false;
  1137. if (state.Toplevel != Top
  1138. && (!Top._needsDisplay.IsEmpty || Top._childNeedsDisplay || Top.LayoutNeeded)) {
  1139. Top.Redraw (Top.Bounds);
  1140. foreach (var top in toplevels.Reverse ()) {
  1141. if (top != Top && top != state.Toplevel) {
  1142. top.SetNeedsDisplay ();
  1143. top.Redraw (top.Bounds);
  1144. }
  1145. }
  1146. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  1147. }
  1148. if (toplevels.Count == 1 && state.Toplevel == Top
  1149. && (Driver.Cols != state.Toplevel.Frame.Width || Driver.Rows != state.Toplevel.Frame.Height)
  1150. && (!state.Toplevel._needsDisplay.IsEmpty || state.Toplevel._childNeedsDisplay || state.Toplevel.LayoutNeeded)) {
  1151. Driver.SetAttribute (Colors.TopLevel.Normal);
  1152. state.Toplevel.Clear (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1153. }
  1154. if (!state.Toplevel._needsDisplay.IsEmpty || state.Toplevel._childNeedsDisplay || state.Toplevel.LayoutNeeded
  1155. || MdiChildNeedsDisplay ()) {
  1156. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1157. if (DebugDrawBounds) {
  1158. DrawBounds (state.Toplevel);
  1159. }
  1160. state.Toplevel.PositionCursor ();
  1161. Driver.Refresh ();
  1162. } else {
  1163. Driver.UpdateCursor ();
  1164. }
  1165. if (state.Toplevel != Top && !state.Toplevel.Modal
  1166. && (!Top._needsDisplay.IsEmpty || Top._childNeedsDisplay || Top.LayoutNeeded)) {
  1167. Top.Redraw (Top.Bounds);
  1168. }
  1169. }
  1170. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  1171. {
  1172. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  1173. return;
  1174. }
  1175. foreach (var top in toplevels.Reverse ()) {
  1176. if (top.Modal && top != Current) {
  1177. MoveCurrent (top);
  1178. return;
  1179. }
  1180. }
  1181. if (!toplevel.Visible && toplevel == Current) {
  1182. MoveNext ();
  1183. }
  1184. }
  1185. static bool MdiChildNeedsDisplay ()
  1186. {
  1187. if (MdiTop == null) {
  1188. return false;
  1189. }
  1190. foreach (var top in toplevels) {
  1191. if (top != Current && top.Visible && (!top._needsDisplay.IsEmpty || top._childNeedsDisplay || top.LayoutNeeded)) {
  1192. MdiTop.SetSubViewNeedsDisplay ();
  1193. return true;
  1194. }
  1195. }
  1196. return false;
  1197. }
  1198. internal static bool DebugDrawBounds = false;
  1199. // Need to look into why this does not work properly.
  1200. static void DrawBounds (View v)
  1201. {
  1202. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1203. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1204. foreach (var sub in v.InternalSubviews)
  1205. DrawBounds (sub);
  1206. }
  1207. /// <summary>
  1208. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  1209. /// </summary>
  1210. /// <remarks>
  1211. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1212. /// </remarks>
  1213. public static void Run (Func<Exception, bool> errorHandler = null)
  1214. {
  1215. Run (Top, errorHandler);
  1216. }
  1217. /// <summary>
  1218. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  1219. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  1220. /// <para>
  1221. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialze the application.
  1222. /// </para>
  1223. /// <para>
  1224. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  1225. /// returned) to ensure resources are cleaned up and terminal settings restored.
  1226. /// </para>
  1227. /// </summary>
  1228. /// <remarks>
  1229. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1230. /// </remarks>
  1231. /// <param name="errorHandler"></param>
  1232. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  1233. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  1234. /// This parameteter must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  1235. /// </param>
  1236. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  1237. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  1238. {
  1239. if (_initialized) {
  1240. if (Driver != null) {
  1241. // Init() has been called and we have a driver, so just run the app.
  1242. var top = new T ();
  1243. var type = top.GetType ().BaseType;
  1244. while (type != typeof (Toplevel) && type != typeof (object)) {
  1245. type = type.BaseType;
  1246. }
  1247. if (type != typeof (Toplevel)) {
  1248. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1249. }
  1250. Run (top, errorHandler);
  1251. } else {
  1252. // This codepath should be impossible because Init(null, null) will select the platform default driver
  1253. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  1254. }
  1255. } else {
  1256. // Init() has NOT been called.
  1257. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  1258. Run (Top, errorHandler);
  1259. }
  1260. }
  1261. /// <summary>
  1262. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1263. /// </summary>
  1264. /// <remarks>
  1265. /// <para>
  1266. /// This method is used to start processing events
  1267. /// for the main application, but it is also used to
  1268. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1269. /// </para>
  1270. /// <para>
  1271. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1272. /// </para>
  1273. /// <para>
  1274. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1275. /// and then calling <see cref="End(RunState)"/>.
  1276. /// </para>
  1277. /// <para>
  1278. /// Alternatively, to have a program control the main loop and
  1279. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1280. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1281. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1282. /// then return control immediately.
  1283. /// </para>
  1284. /// <para>
  1285. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  1286. /// Otheriwse, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  1287. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  1288. /// this method will exit.
  1289. /// </para>
  1290. /// </remarks>
  1291. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1292. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1293. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1294. {
  1295. var resume = true;
  1296. while (resume) {
  1297. #if !DEBUG
  1298. try {
  1299. #endif
  1300. resume = false;
  1301. var runToken = Begin (view);
  1302. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  1303. // by using NotifyStopRunState event.
  1304. RunLoop (runToken);
  1305. if (!ExitRunLoopAfterFirstIteration) {
  1306. End (runToken);
  1307. }
  1308. #if !DEBUG
  1309. }
  1310. catch (Exception error)
  1311. {
  1312. if (errorHandler == null)
  1313. {
  1314. throw;
  1315. }
  1316. resume = errorHandler(error);
  1317. }
  1318. #endif
  1319. }
  1320. }
  1321. /// <summary>
  1322. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1323. /// </summary>
  1324. /// <param name="top">The toplevel to request stop.</param>
  1325. /// <remarks>
  1326. /// <para>
  1327. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1328. /// </para>
  1329. /// <para>
  1330. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1331. /// </para>
  1332. /// </remarks>
  1333. public static void RequestStop (Toplevel top = null)
  1334. {
  1335. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1336. top = Current;
  1337. }
  1338. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1339. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1340. MdiTop.RequestStop ();
  1341. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1342. && top.Modal && top.Running) {
  1343. var ev = new ToplevelClosingEventArgs (Current);
  1344. Current.OnClosing (ev);
  1345. if (ev.Cancel) {
  1346. return;
  1347. }
  1348. ev = new ToplevelClosingEventArgs (top);
  1349. top.OnClosing (ev);
  1350. if (ev.Cancel) {
  1351. return;
  1352. }
  1353. Current.Running = false;
  1354. OnNotifyStopRunState (Current);
  1355. top.Running = false;
  1356. OnNotifyStopRunState (top);
  1357. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1358. && Current?.Running == true && !top.Running)
  1359. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1360. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1361. MoveCurrent (top);
  1362. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1363. && Current?.Modal == true && top.Modal) {
  1364. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1365. Current.Running = false;
  1366. OnNotifyStopRunState (Current);
  1367. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1368. && Current?.Modal == true && top.Modal) {
  1369. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1370. // both are the same, so needed to set the Current.Running to false too.
  1371. Current.Running = false;
  1372. OnNotifyStopRunState (Current);
  1373. } else {
  1374. Toplevel currentTop;
  1375. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1376. currentTop = Current;
  1377. } else {
  1378. currentTop = top;
  1379. }
  1380. if (!currentTop.Running) {
  1381. return;
  1382. }
  1383. var ev = new ToplevelClosingEventArgs (currentTop);
  1384. currentTop.OnClosing (ev);
  1385. if (ev.Cancel) {
  1386. return;
  1387. }
  1388. currentTop.Running = false;
  1389. OnNotifyStopRunState (currentTop);
  1390. }
  1391. }
  1392. static void OnNotifyStopRunState (Toplevel top)
  1393. {
  1394. if (ExitRunLoopAfterFirstIteration) {
  1395. NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
  1396. }
  1397. }
  1398. /// <summary>
  1399. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1400. /// </summary>
  1401. public static Action<ResizedEventArgs> Resized;
  1402. static void TerminalResized ()
  1403. {
  1404. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1405. SetToplevelsSize (full);
  1406. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1407. Driver.Clip = full;
  1408. foreach (var t in toplevels) {
  1409. t.SetRelativeLayout (full);
  1410. t.LayoutSubviews ();
  1411. t.PositionToplevels ();
  1412. t.OnResized (new SizeChangedEventArgs (full.Size));
  1413. }
  1414. Refresh ();
  1415. }
  1416. static void SetToplevelsSize (Rect full)
  1417. {
  1418. if (MdiTop == null) {
  1419. foreach (var t in toplevels) {
  1420. if (t?.SuperView == null && !t.Modal) {
  1421. t.Frame = full;
  1422. t.Width = full.Width;
  1423. t.Height = full.Height;
  1424. }
  1425. }
  1426. } else {
  1427. Top.Frame = full;
  1428. Top.Width = full.Width;
  1429. Top.Height = full.Height;
  1430. }
  1431. }
  1432. static bool SetCurrentAsTop ()
  1433. {
  1434. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1435. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1436. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1437. }
  1438. Top = Current;
  1439. return true;
  1440. }
  1441. return false;
  1442. }
  1443. /// <summary>
  1444. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1445. /// </summary>
  1446. public static void MoveNext ()
  1447. {
  1448. if (MdiTop != null && !Current.Modal) {
  1449. lock (toplevels) {
  1450. toplevels.MoveNext ();
  1451. var isMdi = false;
  1452. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1453. if (!isMdi && toplevels.Peek () == MdiTop) {
  1454. isMdi = true;
  1455. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1456. MoveCurrent (Top);
  1457. break;
  1458. }
  1459. toplevels.MoveNext ();
  1460. }
  1461. Current = toplevels.Peek ();
  1462. }
  1463. }
  1464. }
  1465. /// <summary>
  1466. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1467. /// </summary>
  1468. public static void MovePrevious ()
  1469. {
  1470. if (MdiTop != null && !Current.Modal) {
  1471. lock (toplevels) {
  1472. toplevels.MovePrevious ();
  1473. var isMdi = false;
  1474. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1475. if (!isMdi && toplevels.Peek () == MdiTop) {
  1476. isMdi = true;
  1477. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1478. MoveCurrent (Top);
  1479. break;
  1480. }
  1481. toplevels.MovePrevious ();
  1482. }
  1483. Current = toplevels.Peek ();
  1484. }
  1485. }
  1486. }
  1487. internal static bool ShowChild (Toplevel top)
  1488. {
  1489. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1490. lock (toplevels) {
  1491. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1492. Current = top;
  1493. }
  1494. return true;
  1495. }
  1496. return false;
  1497. }
  1498. /// <summary>
  1499. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1500. /// </summary>
  1501. public static void DoEvents ()
  1502. {
  1503. MainLoop.Driver.Wakeup ();
  1504. }
  1505. /// <summary>
  1506. /// Ensures that the superview of the most focused view is on front.
  1507. /// </summary>
  1508. public static void EnsuresTopOnFront ()
  1509. {
  1510. if (MdiTop != null) {
  1511. return;
  1512. }
  1513. var top = FindTopFromView (Top?.MostFocused);
  1514. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1515. Top.BringSubviewToFront (top);
  1516. }
  1517. }
  1518. internal static List<CultureInfo> GetSupportedCultures ()
  1519. {
  1520. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1521. // Get the assembly
  1522. Assembly assembly = Assembly.GetExecutingAssembly ();
  1523. //Find the location of the assembly
  1524. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1525. // Find the resource file name of the assembly
  1526. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1527. // Return all culture for which satellite folder found with culture code.
  1528. return culture.Where (cultureInfo =>
  1529. assemblyLocation != null &&
  1530. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1531. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1532. ).ToList ();
  1533. }
  1534. }
  1535. }