Application.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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. internal static View mouseGrabView;
  521. /// <summary>
  522. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  523. /// </summary>
  524. /// <returns>The grab.</returns>
  525. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  526. public static void GrabMouse (View view)
  527. {
  528. if (view == null)
  529. return;
  530. mouseGrabView = view;
  531. Driver.UncookMouse ();
  532. }
  533. /// <summary>
  534. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  535. /// </summary>
  536. public static void UngrabMouse ()
  537. {
  538. mouseGrabView = null;
  539. Driver.CookMouse ();
  540. }
  541. /// <summary>
  542. /// Merely a debugging aid to see the raw mouse events
  543. /// </summary>
  544. public static Action<MouseEvent> RootMouseEvent;
  545. /// <summary>
  546. /// <para>
  547. /// Called for new KeyPress events before any processing is performed or
  548. /// views evaluate. Use for global key handling and/or debugging.
  549. /// </para>
  550. /// <para>Return true to suppress the KeyPress event</para>
  551. /// </summary>
  552. public static Func<KeyEvent, bool> RootKeyEvent;
  553. static View lastMouseOwnerView;
  554. static void ProcessMouseEvent (MouseEvent me)
  555. {
  556. if (IsMouseDisabled) {
  557. return;
  558. }
  559. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  560. if (view != null && view.WantContinuousButtonPressed)
  561. WantContinuousButtonPressedView = view;
  562. else
  563. WantContinuousButtonPressedView = null;
  564. if (view != null) {
  565. me.View = view;
  566. }
  567. RootMouseEvent?.Invoke (me);
  568. if (mouseGrabView != null) {
  569. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  570. var nme = new MouseEvent () {
  571. X = newxy.X,
  572. Y = newxy.Y,
  573. Flags = me.Flags,
  574. OfX = me.X - newxy.X,
  575. OfY = me.Y - newxy.Y,
  576. View = view
  577. };
  578. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame)) {
  579. lastMouseOwnerView?.OnMouseLeave (me);
  580. }
  581. // System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  582. if (mouseGrabView != null) {
  583. mouseGrabView.OnMouseEvent (nme);
  584. return;
  585. }
  586. }
  587. if ((view == null || view == MdiTop) && !Current.Modal && MdiTop != null
  588. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  589. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  590. view = FindDeepestView (top, me.X, me.Y, out rx, out ry);
  591. if (view != null && view != MdiTop && top != Current) {
  592. MoveCurrent ((Toplevel)top);
  593. }
  594. }
  595. if (view != null) {
  596. var nme = new MouseEvent () {
  597. X = rx,
  598. Y = ry,
  599. Flags = me.Flags,
  600. OfX = 0,
  601. OfY = 0,
  602. View = view
  603. };
  604. if (lastMouseOwnerView == null) {
  605. lastMouseOwnerView = view;
  606. view.OnMouseEnter (nme);
  607. } else if (lastMouseOwnerView != view) {
  608. lastMouseOwnerView.OnMouseLeave (nme);
  609. view.OnMouseEnter (nme);
  610. lastMouseOwnerView = view;
  611. }
  612. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  613. return;
  614. if (view.WantContinuousButtonPressed)
  615. WantContinuousButtonPressedView = view;
  616. else
  617. WantContinuousButtonPressedView = null;
  618. // Should we bubbled up the event, if it is not handled?
  619. view.OnMouseEvent (nme);
  620. EnsuresTopOnFront ();
  621. }
  622. }
  623. // Only return true if the Current has changed.
  624. static bool MoveCurrent (Toplevel top)
  625. {
  626. // The Current is modal and the top is not modal toplevel then
  627. // the Current must be moved above the first not modal toplevel.
  628. if (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == true && !toplevels.Peek ().Modal) {
  629. lock (toplevels) {
  630. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  631. }
  632. var index = 0;
  633. var savedToplevels = toplevels.ToArray ();
  634. foreach (var t in savedToplevels) {
  635. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  636. lock (toplevels) {
  637. toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  638. }
  639. }
  640. index++;
  641. }
  642. return false;
  643. }
  644. // The Current and the top are both not running toplevel then
  645. // the top must be moved above the first not running toplevel.
  646. if (MdiTop != null && top != MdiTop && top != Current && Current?.Running == false && !top.Running) {
  647. lock (toplevels) {
  648. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  649. }
  650. var index = 0;
  651. foreach (var t in toplevels.ToArray ()) {
  652. if (!t.Running && t != Current && index > 0) {
  653. lock (toplevels) {
  654. toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  655. }
  656. }
  657. index++;
  658. }
  659. return false;
  660. }
  661. if ((MdiTop != null && top?.Modal == true && toplevels.Peek () != top)
  662. || (MdiTop != null && Current != MdiTop && Current?.Modal == false && top == MdiTop)
  663. || (MdiTop != null && Current?.Modal == false && top != Current)
  664. || (MdiTop != null && Current?.Modal == true && top == MdiTop)) {
  665. lock (toplevels) {
  666. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  667. Current = top;
  668. }
  669. }
  670. return true;
  671. }
  672. static bool OutsideFrame (Point p, Rect r)
  673. {
  674. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  675. }
  676. /// <summary>
  677. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  678. /// </summary>
  679. /// <returns>The runstate handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  680. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  681. /// <remarks>
  682. /// This method prepares the provided toplevel for running with the focus,
  683. /// it adds this to the list of toplevels, sets up the mainloop to process the
  684. /// event, lays out the subviews, focuses the first element, and draws the
  685. /// toplevel in the screen. This is usually followed by executing
  686. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  687. /// undo these changes.
  688. /// </remarks>
  689. public static RunState Begin (Toplevel toplevel)
  690. {
  691. if (toplevel == null) {
  692. throw new ArgumentNullException (nameof (toplevel));
  693. } else if (toplevel.IsMdiContainer && MdiTop != null) {
  694. throw new InvalidOperationException ("Only one Mdi Container is allowed.");
  695. }
  696. var rs = new RunState (toplevel);
  697. Init ();
  698. if (toplevel is ISupportInitializeNotification initializableNotification &&
  699. !initializableNotification.IsInitialized) {
  700. initializableNotification.BeginInit ();
  701. initializableNotification.EndInit ();
  702. } else if (toplevel is ISupportInitialize initializable) {
  703. initializable.BeginInit ();
  704. initializable.EndInit ();
  705. }
  706. lock (toplevels) {
  707. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  708. var count = 1;
  709. var id = (toplevels.Count + count).ToString ();
  710. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  711. count++;
  712. id = (toplevels.Count + count).ToString ();
  713. }
  714. toplevel.Id = (toplevels.Count + count).ToString ();
  715. toplevels.Push (toplevel);
  716. } else {
  717. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  718. if (dup == null) {
  719. toplevels.Push (toplevel);
  720. }
  721. }
  722. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  723. throw new ArgumentException ("There are duplicates toplevels Id's");
  724. }
  725. }
  726. if (toplevel.IsMdiContainer) {
  727. Top = toplevel;
  728. }
  729. var refreshDriver = true;
  730. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  731. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  732. if (toplevel.Visible) {
  733. Current = toplevel;
  734. SetCurrentAsTop ();
  735. } else {
  736. refreshDriver = false;
  737. }
  738. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  739. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  740. refreshDriver = false;
  741. MoveCurrent (toplevel);
  742. } else {
  743. refreshDriver = false;
  744. MoveCurrent (Current);
  745. }
  746. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  747. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  748. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  749. toplevel.LayoutSubviews ();
  750. toplevel.PositionToplevels ();
  751. toplevel.WillPresent ();
  752. if (refreshDriver) {
  753. if (MdiTop != null) {
  754. MdiTop.OnChildLoaded (toplevel);
  755. }
  756. toplevel.OnLoaded ();
  757. Redraw (toplevel);
  758. toplevel.PositionCursor ();
  759. Driver.Refresh ();
  760. }
  761. return rs;
  762. }
  763. /// <summary>
  764. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  765. /// </summary>
  766. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  767. public static void End (RunState runState)
  768. {
  769. if (runState == null)
  770. throw new ArgumentNullException (nameof (runState));
  771. if (MdiTop != null) {
  772. MdiTop.OnChildUnloaded (runState.Toplevel);
  773. } else {
  774. runState.Toplevel.OnUnloaded ();
  775. }
  776. runState.Dispose ();
  777. }
  778. /// <summary>
  779. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>
  780. /// </summary>
  781. public static void Shutdown ()
  782. {
  783. ResetState ();
  784. }
  785. // Encapsulate all setting of initial state for Application; Having
  786. // this in a function like this ensures we don't make mistakes in
  787. // guaranteeing that the state of this singleton is deterministic when Init
  788. // starts running and after Shutdown returns.
  789. static void ResetState ()
  790. {
  791. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  792. // Init created. Apps that do any threading will need to code defensively for this.
  793. // e.g. see Issue #537
  794. // TODO: Some of this state is actually related to Begin/End (not Init/Shutdown) and should be moved to `RunState` (#520)
  795. foreach (var t in toplevels) {
  796. t.Running = false;
  797. t.Dispose ();
  798. }
  799. toplevels.Clear ();
  800. Current = null;
  801. Top = null;
  802. MainLoop = null;
  803. Driver?.End ();
  804. Driver = null;
  805. Iteration = null;
  806. RootMouseEvent = null;
  807. RootKeyEvent = null;
  808. Resized = null;
  809. _mainThreadId = -1;
  810. NotifyNewRunState = null;
  811. NotifyStopRunState = null;
  812. _initialized = false;
  813. mouseGrabView = null;
  814. // Reset synchronization context to allow the user to run async/await,
  815. // as the main loop has been ended, the synchronization context from
  816. // gui.cs does no longer process any callbacks. See #1084 for more details:
  817. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  818. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  819. }
  820. static void Redraw (View view)
  821. {
  822. view.Redraw (view.Bounds);
  823. Driver.Refresh ();
  824. }
  825. static void Refresh (View view)
  826. {
  827. view.Redraw (view.Bounds);
  828. Driver.Refresh ();
  829. }
  830. /// <summary>
  831. /// Triggers a refresh of the entire display.
  832. /// </summary>
  833. public static void Refresh ()
  834. {
  835. Driver.UpdateOffScreen ();
  836. View last = null;
  837. foreach (var v in toplevels.Reverse ()) {
  838. if (v.Visible) {
  839. v.SetNeedsDisplay ();
  840. v.Redraw (v.Bounds);
  841. }
  842. last = v;
  843. }
  844. last?.PositionCursor ();
  845. Driver.Refresh ();
  846. }
  847. internal static void End (View view)
  848. {
  849. if (toplevels.Peek () != view)
  850. throw new ArgumentException ("The view that you end with must be balanced");
  851. toplevels.Pop ();
  852. (view as Toplevel)?.OnClosed ((Toplevel)view);
  853. if (MdiTop != null && !((Toplevel)view).Modal && view != MdiTop) {
  854. MdiTop.OnChildClosed (view as Toplevel);
  855. }
  856. if (toplevels.Count == 0) {
  857. Current = null;
  858. } else {
  859. Current = toplevels.Peek ();
  860. if (toplevels.Count == 1 && Current == MdiTop) {
  861. MdiTop.OnAllChildClosed ();
  862. } else {
  863. SetCurrentAsTop ();
  864. }
  865. Refresh ();
  866. }
  867. }
  868. /// <summary>
  869. /// Building block API: Runs the main loop for the created dialog
  870. /// </summary>
  871. /// <remarks>
  872. /// Use the wait parameter to control whether this is a
  873. /// blocking or non-blocking call.
  874. /// </remarks>
  875. /// <param name="state">The state returned by the Begin method.</param>
  876. /// <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>
  877. public static void RunLoop (RunState state, bool wait = true)
  878. {
  879. if (state == null)
  880. throw new ArgumentNullException (nameof (state));
  881. if (state.Toplevel == null)
  882. throw new ObjectDisposedException ("state");
  883. bool firstIteration = true;
  884. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  885. if (ExitRunLoopAfterFirstIteration && !firstIteration)
  886. return;
  887. RunMainLoopIteration (ref state, wait, ref firstIteration);
  888. }
  889. }
  890. /// <summary>
  891. /// Run one iteration of the MainLoop.
  892. /// </summary>
  893. /// <param name="state">The state returned by the Begin method.</param>
  894. /// <param name="wait">If will execute the runloop waiting for events.</param>
  895. /// <param name="firstIteration">If it's the first run loop iteration.</param>
  896. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  897. {
  898. if (MainLoop.EventsPending (wait)) {
  899. // Notify Toplevel it's ready
  900. if (firstIteration) {
  901. state.Toplevel.OnReady ();
  902. }
  903. MainLoop.MainIteration ();
  904. Iteration?.Invoke ();
  905. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  906. if ((state.Toplevel != Current && Current?.Modal == true)
  907. || (state.Toplevel != Current && Current?.Modal == false)) {
  908. MdiTop?.OnDeactivate (state.Toplevel);
  909. state.Toplevel = Current;
  910. MdiTop?.OnActivate (state.Toplevel);
  911. Top.SetChildNeedsDisplay ();
  912. Refresh ();
  913. }
  914. if (Driver.EnsureCursorVisibility ()) {
  915. state.Toplevel.SetNeedsDisplay ();
  916. }
  917. } else if (!wait) {
  918. return;
  919. }
  920. firstIteration = false;
  921. if (state.Toplevel != Top
  922. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  923. Top.Redraw (Top.Bounds);
  924. foreach (var top in toplevels.Reverse ()) {
  925. if (top != Top && top != state.Toplevel) {
  926. top.SetNeedsDisplay ();
  927. top.Redraw (top.Bounds);
  928. }
  929. }
  930. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  931. }
  932. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.ChildNeedsDisplay || state.Toplevel.LayoutNeeded
  933. || MdiChildNeedsDisplay ()) {
  934. state.Toplevel.Redraw (state.Toplevel.Bounds);
  935. if (DebugDrawBounds) {
  936. DrawBounds (state.Toplevel);
  937. }
  938. state.Toplevel.PositionCursor ();
  939. Driver.Refresh ();
  940. } else {
  941. Driver.UpdateCursor ();
  942. }
  943. if (state.Toplevel != Top && !state.Toplevel.Modal
  944. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  945. Top.Redraw (Top.Bounds);
  946. }
  947. }
  948. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  949. {
  950. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  951. return;
  952. }
  953. foreach (var top in toplevels.Reverse ()) {
  954. if (top.Modal && top != Current) {
  955. MoveCurrent (top);
  956. return;
  957. }
  958. }
  959. if (!toplevel.Visible && toplevel == Current) {
  960. MoveNext ();
  961. }
  962. }
  963. static bool MdiChildNeedsDisplay ()
  964. {
  965. if (MdiTop == null) {
  966. return false;
  967. }
  968. foreach (var top in toplevels) {
  969. if (top != Current && top.Visible && (!top.NeedDisplay.IsEmpty || top.ChildNeedsDisplay || top.LayoutNeeded)) {
  970. MdiTop.SetChildNeedsDisplay ();
  971. return true;
  972. }
  973. }
  974. return false;
  975. }
  976. internal static bool DebugDrawBounds = false;
  977. // Need to look into why this does not work properly.
  978. static void DrawBounds (View v)
  979. {
  980. v.DrawFrame (v.Frame, padding: 0, fill: false);
  981. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  982. foreach (var sub in v.InternalSubviews)
  983. DrawBounds (sub);
  984. }
  985. /// <summary>
  986. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>
  987. /// </summary>
  988. public static void Run (Func<Exception, bool> errorHandler = null)
  989. {
  990. Run (Top, errorHandler);
  991. }
  992. /// <summary>
  993. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with a new instance of the specified <see cref="Toplevel"/>-derived class
  994. /// </summary>
  995. public static void Run<T> (Func<Exception, bool> errorHandler = null) where T : Toplevel, new()
  996. {
  997. if (_initialized && Driver != null) {
  998. var top = new T ();
  999. var type = top.GetType ().BaseType;
  1000. while (type != typeof (Toplevel) && type != typeof (object)) {
  1001. type = type.BaseType;
  1002. }
  1003. if (type != typeof (Toplevel)) {
  1004. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1005. }
  1006. Run (top, errorHandler);
  1007. } else {
  1008. Init (() => new T ());
  1009. Run (Top, errorHandler);
  1010. }
  1011. }
  1012. /// <summary>
  1013. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1014. /// </summary>
  1015. /// <remarks>
  1016. /// <para>
  1017. /// This method is used to start processing events
  1018. /// for the main application, but it is also used to
  1019. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1020. /// </para>
  1021. /// <para>
  1022. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1023. /// </para>
  1024. /// <para>
  1025. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1026. /// and then calling <see cref="End(RunState)"/>.
  1027. /// </para>
  1028. /// <para>
  1029. /// Alternatively, to have a program control the main loop and
  1030. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1031. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1032. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1033. /// then return control immediately.
  1034. /// </para>
  1035. /// <para>
  1036. /// When <paramref name="errorHandler"/> is null the exception is rethrown, when it returns true the application is resumed and when false method exits gracefully.
  1037. /// </para>
  1038. /// </remarks>
  1039. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1040. /// <param name="errorHandler">Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1041. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1042. {
  1043. var resume = true;
  1044. while (resume) {
  1045. #if !DEBUG
  1046. try {
  1047. #endif
  1048. resume = false;
  1049. var runToken = Begin (view);
  1050. RunLoop (runToken);
  1051. if (!ExitRunLoopAfterFirstIteration)
  1052. End (runToken);
  1053. else
  1054. // If ExitRunLoopAfterFirstIteration is true then the user must deal his disposing when it ends
  1055. // by using NotifyStopRunState event.
  1056. NotifyNewRunState?.Invoke (runToken);
  1057. #if !DEBUG
  1058. }
  1059. catch (Exception error)
  1060. {
  1061. if (errorHandler == null)
  1062. {
  1063. throw;
  1064. }
  1065. resume = errorHandler(error);
  1066. }
  1067. #endif
  1068. }
  1069. }
  1070. /// <summary>
  1071. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1072. /// </summary>
  1073. /// <param name="top">The toplevel to request stop.</param>
  1074. /// <remarks>
  1075. /// <para>
  1076. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1077. /// </para>
  1078. /// <para>
  1079. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1080. /// </para>
  1081. /// </remarks>
  1082. public static void RequestStop (Toplevel top = null)
  1083. {
  1084. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1085. top = Current;
  1086. }
  1087. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1088. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1089. MdiTop.RequestStop ();
  1090. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1091. && top.Modal && top.Running) {
  1092. var ev = new ToplevelClosingEventArgs (Current);
  1093. Current.OnClosing (ev);
  1094. if (ev.Cancel) {
  1095. return;
  1096. }
  1097. ev = new ToplevelClosingEventArgs (top);
  1098. top.OnClosing (ev);
  1099. if (ev.Cancel) {
  1100. return;
  1101. }
  1102. Current.Running = false;
  1103. OnNotifyStopRunState (Current);
  1104. top.Running = false;
  1105. OnNotifyStopRunState (top);
  1106. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1107. && Current?.Running == true && !top.Running)
  1108. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1109. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1110. MoveCurrent (top);
  1111. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1112. && Current?.Modal == true && top.Modal) {
  1113. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1114. Current.Running = false;
  1115. OnNotifyStopRunState (Current);
  1116. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1117. && Current?.Modal == true && top.Modal) {
  1118. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1119. // both are the same, so needed to set the Current.Running to false too.
  1120. Current.Running = false;
  1121. OnNotifyStopRunState (Current);
  1122. } else {
  1123. Toplevel currentTop;
  1124. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1125. currentTop = Current;
  1126. } else {
  1127. currentTop = top;
  1128. }
  1129. if (!currentTop.Running) {
  1130. return;
  1131. }
  1132. var ev = new ToplevelClosingEventArgs (currentTop);
  1133. currentTop.OnClosing (ev);
  1134. if (ev.Cancel) {
  1135. return;
  1136. }
  1137. currentTop.Running = false;
  1138. OnNotifyStopRunState (currentTop);
  1139. }
  1140. }
  1141. static void OnNotifyStopRunState (Toplevel top)
  1142. {
  1143. if (ExitRunLoopAfterFirstIteration)
  1144. NotifyStopRunState?.Invoke (top);
  1145. }
  1146. /// <summary>
  1147. /// Event arguments for the <see cref="Application.Resized"/> event.
  1148. /// </summary>
  1149. public class ResizedEventArgs : EventArgs {
  1150. /// <summary>
  1151. /// The number of rows in the resized terminal.
  1152. /// </summary>
  1153. public int Rows { get; set; }
  1154. /// <summary>
  1155. /// The number of columns in the resized terminal.
  1156. /// </summary>
  1157. public int Cols { get; set; }
  1158. }
  1159. /// <summary>
  1160. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1161. /// </summary>
  1162. public static Action<ResizedEventArgs> Resized;
  1163. static void TerminalResized ()
  1164. {
  1165. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1166. SetToplevelsSize (full);
  1167. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1168. Driver.Clip = full;
  1169. foreach (var t in toplevels) {
  1170. t.SetRelativeLayout (full);
  1171. t.LayoutSubviews ();
  1172. t.PositionToplevels ();
  1173. t.OnResized (full.Size);
  1174. }
  1175. Refresh ();
  1176. }
  1177. static void SetToplevelsSize (Rect full)
  1178. {
  1179. if (MdiTop == null) {
  1180. foreach (var t in toplevels) {
  1181. if (t?.SuperView == null && !t.Modal) {
  1182. t.Frame = full;
  1183. t.Width = full.Width;
  1184. t.Height = full.Height;
  1185. }
  1186. }
  1187. } else {
  1188. Top.Frame = full;
  1189. Top.Width = full.Width;
  1190. Top.Height = full.Height;
  1191. }
  1192. }
  1193. static bool SetCurrentAsTop ()
  1194. {
  1195. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1196. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1197. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1198. }
  1199. Top = Current;
  1200. return true;
  1201. }
  1202. return false;
  1203. }
  1204. /// <summary>
  1205. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1206. /// </summary>
  1207. public static void MoveNext ()
  1208. {
  1209. if (MdiTop != null && !Current.Modal) {
  1210. lock (toplevels) {
  1211. toplevels.MoveNext ();
  1212. var isMdi = false;
  1213. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1214. if (!isMdi && toplevels.Peek () == MdiTop) {
  1215. isMdi = true;
  1216. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1217. MoveCurrent (Top);
  1218. break;
  1219. }
  1220. toplevels.MoveNext ();
  1221. }
  1222. Current = toplevels.Peek ();
  1223. }
  1224. }
  1225. }
  1226. /// <summary>
  1227. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1228. /// </summary>
  1229. public static void MovePrevious ()
  1230. {
  1231. if (MdiTop != null && !Current.Modal) {
  1232. lock (toplevels) {
  1233. toplevels.MovePrevious ();
  1234. var isMdi = false;
  1235. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1236. if (!isMdi && toplevels.Peek () == MdiTop) {
  1237. isMdi = true;
  1238. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1239. MoveCurrent (Top);
  1240. break;
  1241. }
  1242. toplevels.MovePrevious ();
  1243. }
  1244. Current = toplevels.Peek ();
  1245. }
  1246. }
  1247. }
  1248. internal static bool ShowChild (Toplevel top)
  1249. {
  1250. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1251. lock (toplevels) {
  1252. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1253. Current = top;
  1254. }
  1255. return true;
  1256. }
  1257. return false;
  1258. }
  1259. /// <summary>
  1260. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1261. /// </summary>
  1262. public static void DoEvents ()
  1263. {
  1264. MainLoop.Driver.Wakeup ();
  1265. }
  1266. /// <summary>
  1267. /// Ensures that the superview of the most focused view is on front.
  1268. /// </summary>
  1269. public static void EnsuresTopOnFront ()
  1270. {
  1271. if (MdiTop != null) {
  1272. return;
  1273. }
  1274. var top = FindTopFromView (Top?.MostFocused);
  1275. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1276. Top.BringSubviewToFront (top);
  1277. }
  1278. }
  1279. internal static List<CultureInfo> GetSupportedCultures ()
  1280. {
  1281. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1282. // Get the assembly
  1283. Assembly assembly = Assembly.GetExecutingAssembly ();
  1284. //Find the location of the assembly
  1285. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1286. // Find the resource file name of the assembly
  1287. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1288. // Return all culture for which satellite folder found with culture code.
  1289. return culture.Where (cultureInfo =>
  1290. assemblyLocation != null &&
  1291. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1292. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1293. ).ToList ();
  1294. }
  1295. }
  1296. }