Application.cs 55 KB

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