Application.cs 54 KB

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