Application.cs 51 KB

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