Application.cs 49 KB

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