Application.cs 51 KB

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