Application.cs 51 KB

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