Application.cs 42 KB

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