Application.cs 47 KB

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