Application.cs 51 KB

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