Application.cs 43 KB

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