Application.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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. Driver.UncookMouse ();
  634. }
  635. /// <summary>
  636. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  637. /// </summary>
  638. public static void UngrabMouse ()
  639. {
  640. if (mouseGrabView == null)
  641. return;
  642. OnUnGrabbedMouse (mouseGrabView);
  643. mouseGrabView = null;
  644. Driver.CookMouse ();
  645. }
  646. static void OnGrabbedMouse (View view)
  647. {
  648. if (view == null)
  649. return;
  650. GrabbedMouse?.Invoke (view);
  651. }
  652. static void OnUnGrabbedMouse (View view)
  653. {
  654. if (view == null)
  655. return;
  656. UnGrabbedMouse?.Invoke (view);
  657. }
  658. /// <summary>
  659. /// Merely a debugging aid to see the raw mouse events
  660. /// </summary>
  661. public static Action<MouseEvent> RootMouseEvent;
  662. /// <summary>
  663. /// <para>
  664. /// Called for new KeyPress events before any processing is performed or
  665. /// views evaluate. Use for global key handling and/or debugging.
  666. /// </para>
  667. /// <para>Return true to suppress the KeyPress event</para>
  668. /// </summary>
  669. public static Func<KeyEvent, bool> RootKeyEvent;
  670. static View lastMouseOwnerView;
  671. static void ProcessMouseEvent (MouseEvent me)
  672. {
  673. if (IsMouseDisabled) {
  674. return;
  675. }
  676. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  677. if (view != null && view.WantContinuousButtonPressed)
  678. WantContinuousButtonPressedView = view;
  679. else
  680. WantContinuousButtonPressedView = null;
  681. if (view != null) {
  682. me.View = view;
  683. }
  684. RootMouseEvent?.Invoke (me);
  685. if (me.Handled) {
  686. return;
  687. }
  688. if (mouseGrabView != null) {
  689. if (view == null) {
  690. UngrabMouse ();
  691. return;
  692. }
  693. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  694. var nme = new MouseEvent () {
  695. X = newxy.X,
  696. Y = newxy.Y,
  697. Flags = me.Flags,
  698. OfX = me.X - newxy.X,
  699. OfY = me.Y - newxy.Y,
  700. View = view
  701. };
  702. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame)) {
  703. lastMouseOwnerView?.OnMouseLeave (me);
  704. }
  705. // System.Diagnostics.Debug.WriteLine ($"{nme.Flags};{nme.X};{nme.Y};{mouseGrabView}");
  706. if (mouseGrabView?.OnMouseEvent (nme) == true) {
  707. return;
  708. }
  709. }
  710. if ((view == null || view == MdiTop) && !Current.Modal && MdiTop != null
  711. && me.Flags != MouseFlags.ReportMousePosition && me.Flags != 0) {
  712. var top = FindDeepestTop (Top, me.X, me.Y, out _, out _);
  713. view = FindDeepestView (top, me.X, me.Y, out rx, out ry);
  714. if (view != null && view != MdiTop && top != Current) {
  715. MoveCurrent ((Toplevel)top);
  716. }
  717. }
  718. if (view != null) {
  719. var nme = new MouseEvent () {
  720. X = rx,
  721. Y = ry,
  722. Flags = me.Flags,
  723. OfX = 0,
  724. OfY = 0,
  725. View = view
  726. };
  727. if (lastMouseOwnerView == null) {
  728. lastMouseOwnerView = view;
  729. view.OnMouseEnter (nme);
  730. } else if (lastMouseOwnerView != view) {
  731. lastMouseOwnerView.OnMouseLeave (nme);
  732. view.OnMouseEnter (nme);
  733. lastMouseOwnerView = view;
  734. }
  735. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  736. return;
  737. if (view.WantContinuousButtonPressed)
  738. WantContinuousButtonPressedView = view;
  739. else
  740. WantContinuousButtonPressedView = null;
  741. // Should we bubbled up the event, if it is not handled?
  742. view.OnMouseEvent (nme);
  743. EnsuresTopOnFront ();
  744. }
  745. }
  746. // Only return true if the Current has changed.
  747. static bool MoveCurrent (Toplevel top)
  748. {
  749. // The Current is modal and the top is not modal toplevel then
  750. // the Current must be moved above the first not modal toplevel.
  751. if (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == true && !toplevels.Peek ().Modal) {
  752. lock (toplevels) {
  753. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  754. }
  755. var index = 0;
  756. var savedToplevels = toplevels.ToArray ();
  757. foreach (var t in savedToplevels) {
  758. if (!t.Modal && t != Current && t != top && t != savedToplevels [index]) {
  759. lock (toplevels) {
  760. toplevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  761. }
  762. }
  763. index++;
  764. }
  765. return false;
  766. }
  767. // The Current and the top are both not running toplevel then
  768. // the top must be moved above the first not running toplevel.
  769. if (MdiTop != null && top != MdiTop && top != Current && Current?.Running == false && !top.Running) {
  770. lock (toplevels) {
  771. toplevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  772. }
  773. var index = 0;
  774. foreach (var t in toplevels.ToArray ()) {
  775. if (!t.Running && t != Current && index > 0) {
  776. lock (toplevels) {
  777. toplevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  778. }
  779. }
  780. index++;
  781. }
  782. return false;
  783. }
  784. if ((MdiTop != null && top?.Modal == true && toplevels.Peek () != top)
  785. || (MdiTop != null && Current != MdiTop && Current?.Modal == false && top == MdiTop)
  786. || (MdiTop != null && Current?.Modal == false && top != Current)
  787. || (MdiTop != null && Current?.Modal == true && top == MdiTop)) {
  788. lock (toplevels) {
  789. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  790. Current = top;
  791. }
  792. }
  793. return true;
  794. }
  795. static bool OutsideFrame (Point p, Rect r)
  796. {
  797. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  798. }
  799. /// <summary>
  800. /// Building block API: Prepares the provided <see cref="Toplevel"/> for execution.
  801. /// </summary>
  802. /// <returns>The <see cref="RunState"/> handle that needs to be passed to the <see cref="End(RunState)"/> method upon completion.</returns>
  803. /// <param name="toplevel">The <see cref="Toplevel"/> to prepare execution for.</param>
  804. /// <remarks>
  805. /// This method prepares the provided toplevel for running with the focus,
  806. /// it adds this to the list of toplevels, sets up the mainloop to process the
  807. /// event, lays out the subviews, focuses the first element, and draws the
  808. /// toplevel in the screen. This is usually followed by executing
  809. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  810. /// undo these changes.
  811. /// </remarks>
  812. public static RunState Begin (Toplevel toplevel)
  813. {
  814. if (toplevel == null) {
  815. throw new ArgumentNullException (nameof (toplevel));
  816. } else if (toplevel.IsMdiContainer && MdiTop != toplevel && MdiTop != null) {
  817. throw new InvalidOperationException ("Only one Mdi Container is allowed.");
  818. }
  819. var rs = new RunState (toplevel);
  820. if (toplevel is ISupportInitializeNotification initializableNotification &&
  821. !initializableNotification.IsInitialized) {
  822. initializableNotification.BeginInit ();
  823. initializableNotification.EndInit ();
  824. } else if (toplevel is ISupportInitialize initializable) {
  825. initializable.BeginInit ();
  826. initializable.EndInit ();
  827. }
  828. lock (toplevels) {
  829. // If Top was already initialized with Init, and Begin has never been called
  830. // Top was not added to the toplevels Stack. It will thus never get disposed.
  831. // Clean it up here:
  832. if (Top != null && toplevel != Top && !toplevels.Contains (Top)) {
  833. Top.Dispose ();
  834. Top = null;
  835. }
  836. if (string.IsNullOrEmpty (toplevel.Id.ToString ())) {
  837. var count = 1;
  838. var id = (toplevels.Count + count).ToString ();
  839. while (toplevels.Count > 0 && toplevels.FirstOrDefault (x => x.Id.ToString () == id) != null) {
  840. count++;
  841. id = (toplevels.Count + count).ToString ();
  842. }
  843. toplevel.Id = (toplevels.Count + count).ToString ();
  844. toplevels.Push (toplevel);
  845. } else {
  846. var dup = toplevels.FirstOrDefault (x => x.Id.ToString () == toplevel.Id);
  847. if (dup == null) {
  848. toplevels.Push (toplevel);
  849. }
  850. }
  851. if (toplevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0) {
  852. throw new ArgumentException ("There are duplicates toplevels Id's");
  853. }
  854. }
  855. // Fix $520 - Set Top = toplevel if Top == null
  856. if (Top == null || toplevel.IsMdiContainer) {
  857. Top = toplevel;
  858. }
  859. var refreshDriver = true;
  860. if (MdiTop == null || toplevel.IsMdiContainer || (Current?.Modal == false && toplevel.Modal)
  861. || (Current?.Modal == false && !toplevel.Modal) || (Current?.Modal == true && toplevel.Modal)) {
  862. if (toplevel.Visible) {
  863. Current = toplevel;
  864. SetCurrentAsTop ();
  865. } else {
  866. refreshDriver = false;
  867. }
  868. } else if ((MdiTop != null && toplevel != MdiTop && Current?.Modal == true && !toplevels.Peek ().Modal)
  869. || (MdiTop != null && toplevel != MdiTop && Current?.Running == false)) {
  870. refreshDriver = false;
  871. MoveCurrent (toplevel);
  872. } else {
  873. refreshDriver = false;
  874. MoveCurrent (Current);
  875. }
  876. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  877. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  878. toplevel.SetRelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  879. toplevel.LayoutSubviews ();
  880. toplevel.PositionToplevels ();
  881. toplevel.WillPresent ();
  882. if (refreshDriver) {
  883. if (MdiTop != null) {
  884. MdiTop.OnChildLoaded (toplevel);
  885. }
  886. toplevel.OnLoaded ();
  887. Redraw (toplevel);
  888. toplevel.PositionCursor ();
  889. Driver.Refresh ();
  890. }
  891. NotifyNewRunState?.Invoke (rs);
  892. return rs;
  893. }
  894. /// <summary>
  895. /// Building block API: completes the execution of a <see cref="Toplevel"/> that was started with <see cref="Begin(Toplevel)"/> .
  896. /// </summary>
  897. /// <param name="runState">The <see cref="RunState"/> returned by the <see cref="Begin(Toplevel)"/> method.</param>
  898. public static void End (RunState runState)
  899. {
  900. if (runState == null)
  901. throw new ArgumentNullException (nameof (runState));
  902. if (MdiTop != null) {
  903. MdiTop.OnChildUnloaded (runState.Toplevel);
  904. } else {
  905. runState.Toplevel.OnUnloaded ();
  906. }
  907. // End the RunState.Toplevel
  908. // First, take it off the toplevel Stack
  909. if (toplevels.Count > 0) {
  910. if (toplevels.Peek () != runState.Toplevel) {
  911. // If there the top of the stack is not the RunState.Toplevel then
  912. // this call to End is not balanced with the call to Begin that started the RunState
  913. throw new ArgumentException ("End must be balanced with calls to Begin");
  914. }
  915. toplevels.Pop ();
  916. }
  917. // Notify that it is closing
  918. runState.Toplevel?.OnClosed (runState.Toplevel);
  919. // If there is a MdiTop that is not the RunState.Toplevel then runstate.TopLevel
  920. // is a child of MidTop and we should notify the MdiTop that it is closing
  921. if (MdiTop != null && !(runState.Toplevel).Modal && runState.Toplevel != MdiTop) {
  922. MdiTop.OnChildClosed (runState.Toplevel);
  923. }
  924. // Set Current and Top to the next TopLevel on the stack
  925. if (toplevels.Count == 0) {
  926. Current = null;
  927. } else {
  928. Current = toplevels.Peek ();
  929. if (toplevels.Count == 1 && Current == MdiTop) {
  930. MdiTop.OnAllChildClosed ();
  931. } else {
  932. SetCurrentAsTop ();
  933. }
  934. Refresh ();
  935. }
  936. runState.Toplevel?.Dispose ();
  937. runState.Toplevel = null;
  938. runState.Dispose ();
  939. }
  940. /// <summary>
  941. /// Shutdown an application initialized with <see cref="Init(ConsoleDriver, IMainLoopDriver)"/>.
  942. /// </summary>
  943. /// <remarks>
  944. /// Shutdown must be called for every call to <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> or <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  945. /// to ensure all resources are cleaned up (Disposed) and terminal settings are restored.
  946. /// </remarks>
  947. public static void Shutdown ()
  948. {
  949. ResetState ();
  950. }
  951. // Encapsulate all setting of initial state for Application; Having
  952. // this in a function like this ensures we don't make mistakes in
  953. // guaranteeing that the state of this singleton is deterministic when Init
  954. // starts running and after Shutdown returns.
  955. static void ResetState ()
  956. {
  957. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  958. // Init created. Apps that do any threading will need to code defensively for this.
  959. // e.g. see Issue #537
  960. foreach (var t in toplevels) {
  961. t.Running = false;
  962. t.Dispose ();
  963. }
  964. toplevels.Clear ();
  965. Current = null;
  966. Top?.Dispose ();
  967. Top = null;
  968. // BUGBUG: MdiTop is not cleared here, but it should be?
  969. MainLoop = null;
  970. Driver?.End ();
  971. Driver = null;
  972. Iteration = null;
  973. RootMouseEvent = null;
  974. RootKeyEvent = null;
  975. Resized = null;
  976. _mainThreadId = -1;
  977. NotifyNewRunState = null;
  978. NotifyStopRunState = null;
  979. _initialized = false;
  980. mouseGrabView = null;
  981. // Reset synchronization context to allow the user to run async/await,
  982. // as the main loop has been ended, the synchronization context from
  983. // gui.cs does no longer process any callbacks. See #1084 for more details:
  984. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  985. SynchronizationContext.SetSynchronizationContext (syncContext: null);
  986. }
  987. static void Redraw (View view)
  988. {
  989. view.Redraw (view.Bounds);
  990. Driver.Refresh ();
  991. }
  992. static void Refresh (View view)
  993. {
  994. view.Redraw (view.Bounds);
  995. Driver.Refresh ();
  996. }
  997. /// <summary>
  998. /// Triggers a refresh of the entire display.
  999. /// </summary>
  1000. public static void Refresh ()
  1001. {
  1002. Driver.UpdateOffScreen ();
  1003. View last = null;
  1004. foreach (var v in toplevels.Reverse ()) {
  1005. if (v.Visible) {
  1006. v.SetNeedsDisplay ();
  1007. v.Redraw (v.Bounds);
  1008. }
  1009. last = v;
  1010. }
  1011. last?.PositionCursor ();
  1012. Driver.Refresh ();
  1013. }
  1014. /// <summary>
  1015. /// Building block API: Runs the <see cref="MainLoop"/> for the created <see cref="Toplevel"/>.
  1016. /// </summary>
  1017. /// <remarks>
  1018. /// Use the <paramref name="wait"/> parameter to control whether this is a blocking or non-blocking call.
  1019. /// </remarks>
  1020. /// <param name="state">The state returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1021. /// <param name="wait">By default this is <see langword="true"/> which will execute the runloop waiting for events,
  1022. /// if set to <see langword="false"/>, a single iteration will execute.</param>
  1023. public static void RunLoop (RunState state, bool wait = true)
  1024. {
  1025. if (state == null)
  1026. throw new ArgumentNullException (nameof (state));
  1027. if (state.Toplevel == null)
  1028. throw new ObjectDisposedException ("state");
  1029. bool firstIteration = true;
  1030. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1031. if (ExitRunLoopAfterFirstIteration && !firstIteration) {
  1032. return;
  1033. }
  1034. RunMainLoopIteration (ref state, wait, ref firstIteration);
  1035. }
  1036. }
  1037. /// <summary>
  1038. /// Run one iteration of the <see cref="MainLoop"/>.
  1039. /// </summary>
  1040. /// <param name="state">The state returned by <see cref="Begin(Toplevel)"/>.</param>
  1041. /// <param name="wait">If <see langword="true"/> will execute the runloop waiting for events. If <see langword="true"/>
  1042. /// will return after a single iteration.</param>
  1043. /// <param name="firstIteration">Set to <see langword="true"/> if this is the first run loop iteration. Upon return,
  1044. /// it will be set to <see langword="false"/> if at least one iteration happened.</param>
  1045. public static void RunMainLoopIteration (ref RunState state, bool wait, ref bool firstIteration)
  1046. {
  1047. if (MainLoop.EventsPending (wait)) {
  1048. // Notify Toplevel it's ready
  1049. if (firstIteration) {
  1050. state.Toplevel.OnReady ();
  1051. }
  1052. MainLoop.MainIteration ();
  1053. Iteration?.Invoke ();
  1054. EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
  1055. if ((state.Toplevel != Current && Current?.Modal == true)
  1056. || (state.Toplevel != Current && Current?.Modal == false)) {
  1057. MdiTop?.OnDeactivate (state.Toplevel);
  1058. state.Toplevel = Current;
  1059. MdiTop?.OnActivate (state.Toplevel);
  1060. Top.SetChildNeedsDisplay ();
  1061. Refresh ();
  1062. }
  1063. if (Driver.EnsureCursorVisibility ()) {
  1064. state.Toplevel.SetNeedsDisplay ();
  1065. }
  1066. } else if (!wait) {
  1067. return;
  1068. }
  1069. firstIteration = false;
  1070. if (state.Toplevel != Top
  1071. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  1072. Top.Redraw (Top.Bounds);
  1073. foreach (var top in toplevels.Reverse ()) {
  1074. if (top != Top && top != state.Toplevel) {
  1075. top.SetNeedsDisplay ();
  1076. top.Redraw (top.Bounds);
  1077. }
  1078. }
  1079. state.Toplevel.SetNeedsDisplay (state.Toplevel.Bounds);
  1080. }
  1081. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.ChildNeedsDisplay || state.Toplevel.LayoutNeeded
  1082. || MdiChildNeedsDisplay ()) {
  1083. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1084. if (DebugDrawBounds) {
  1085. DrawBounds (state.Toplevel);
  1086. }
  1087. state.Toplevel.PositionCursor ();
  1088. Driver.Refresh ();
  1089. } else {
  1090. Driver.UpdateCursor ();
  1091. }
  1092. if (state.Toplevel != Top && !state.Toplevel.Modal
  1093. && (!Top.NeedDisplay.IsEmpty || Top.ChildNeedsDisplay || Top.LayoutNeeded)) {
  1094. Top.Redraw (Top.Bounds);
  1095. }
  1096. }
  1097. static void EnsureModalOrVisibleAlwaysOnTop (Toplevel toplevel)
  1098. {
  1099. if (!toplevel.Running || (toplevel == Current && toplevel.Visible) || MdiTop == null || toplevels.Peek ().Modal) {
  1100. return;
  1101. }
  1102. foreach (var top in toplevels.Reverse ()) {
  1103. if (top.Modal && top != Current) {
  1104. MoveCurrent (top);
  1105. return;
  1106. }
  1107. }
  1108. if (!toplevel.Visible && toplevel == Current) {
  1109. MoveNext ();
  1110. }
  1111. }
  1112. static bool MdiChildNeedsDisplay ()
  1113. {
  1114. if (MdiTop == null) {
  1115. return false;
  1116. }
  1117. foreach (var top in toplevels) {
  1118. if (top != Current && top.Visible && (!top.NeedDisplay.IsEmpty || top.ChildNeedsDisplay || top.LayoutNeeded)) {
  1119. MdiTop.SetChildNeedsDisplay ();
  1120. return true;
  1121. }
  1122. }
  1123. return false;
  1124. }
  1125. internal static bool DebugDrawBounds = false;
  1126. // Need to look into why this does not work properly.
  1127. static void DrawBounds (View v)
  1128. {
  1129. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1130. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1131. foreach (var sub in v.InternalSubviews)
  1132. DrawBounds (sub);
  1133. }
  1134. /// <summary>
  1135. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/> with the value of <see cref="Top"/>.
  1136. /// </summary>
  1137. /// <remarks>
  1138. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1139. /// </remarks>
  1140. public static void Run (Func<Exception, bool> errorHandler = null)
  1141. {
  1142. Run (Top, errorHandler);
  1143. }
  1144. /// <summary>
  1145. /// Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool})"/>
  1146. /// with a new instance of the specified <see cref="Toplevel"/>-derived class.
  1147. /// <para>
  1148. /// Calling <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> first is not needed as this function will initialze the application.
  1149. /// </para>
  1150. /// <para>
  1151. /// <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has
  1152. /// returned) to ensure resources are cleaned up and terminal settings restored.
  1153. /// </para>
  1154. /// </summary>
  1155. /// <remarks>
  1156. /// See <see cref="Run(Toplevel, Func{Exception, bool})"/> for more details.
  1157. /// </remarks>
  1158. /// <param name="errorHandler"></param>
  1159. /// <param name="driver">The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the
  1160. /// platform will be used (<see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>).
  1161. /// This parameteter must be <see langword="null"/> if <see cref="Init(ConsoleDriver, IMainLoopDriver)"/> has already been called.
  1162. /// </param>
  1163. /// <param name="mainLoopDriver">Specifies the <see cref="MainLoop"/> to use.</param>
  1164. public static void Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null, IMainLoopDriver mainLoopDriver = null) where T : Toplevel, new()
  1165. {
  1166. if (_initialized) {
  1167. if (Driver != null) {
  1168. // Init() has been called and we have a driver, so just run the app.
  1169. var top = new T ();
  1170. var type = top.GetType ().BaseType;
  1171. while (type != typeof (Toplevel) && type != typeof (object)) {
  1172. type = type.BaseType;
  1173. }
  1174. if (type != typeof (Toplevel)) {
  1175. throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
  1176. }
  1177. Run (top, errorHandler);
  1178. } else {
  1179. // This codepath should be impossible because Init(null, null) will select the platform default driver
  1180. throw new InvalidOperationException ("Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called.");
  1181. }
  1182. } else {
  1183. // Init() has NOT been called.
  1184. InternalInit (() => new T (), driver, mainLoopDriver, calledViaRunT: true);
  1185. Run (Top, errorHandler);
  1186. }
  1187. }
  1188. /// <summary>
  1189. /// Runs the main loop on the given <see cref="Toplevel"/> container.
  1190. /// </summary>
  1191. /// <remarks>
  1192. /// <para>
  1193. /// This method is used to start processing events
  1194. /// for the main application, but it is also used to
  1195. /// run other modal <see cref="View"/>s such as <see cref="Dialog"/> boxes.
  1196. /// </para>
  1197. /// <para>
  1198. /// To make a <see cref="Run(Toplevel, Func{Exception, bool})"/> stop execution, call <see cref="Application.RequestStop"/>.
  1199. /// </para>
  1200. /// <para>
  1201. /// Calling <see cref="Run(Toplevel, Func{Exception, bool})"/> is equivalent to calling <see cref="Begin(Toplevel)"/>, followed by <see cref="RunLoop(RunState, bool)"/>,
  1202. /// and then calling <see cref="End(RunState)"/>.
  1203. /// </para>
  1204. /// <para>
  1205. /// Alternatively, to have a program control the main loop and
  1206. /// process events manually, call <see cref="Begin(Toplevel)"/> to set things up manually and then
  1207. /// repeatedly call <see cref="RunLoop(RunState, bool)"/> with the wait parameter set to false. By doing this
  1208. /// the <see cref="RunLoop(RunState, bool)"/> method will only process any pending events, timers, idle handlers and
  1209. /// then return control immediately.
  1210. /// </para>
  1211. /// <para>
  1212. /// RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exeptions will be rethrown.
  1213. /// Otheriwse, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
  1214. /// returns <see langword="true"/> the <see cref="RunLoop(RunState, bool)"/> will resume; otherwise
  1215. /// this method will exit.
  1216. /// </para>
  1217. /// </remarks>
  1218. /// <param name="view">The <see cref="Toplevel"/> to run modally.</param>
  1219. /// <param name="errorHandler">RELEASE builds only: Handler for any unhandled exceptions (resumes when returns true, rethrows when null).</param>
  1220. public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null)
  1221. {
  1222. var resume = true;
  1223. while (resume) {
  1224. #if !DEBUG
  1225. try {
  1226. #endif
  1227. resume = false;
  1228. var runToken = Begin (view);
  1229. // If ExitRunLoopAfterFirstIteration is true then the user must dispose of the runToken
  1230. // by using NotifyStopRunState event.
  1231. RunLoop (runToken);
  1232. if (!ExitRunLoopAfterFirstIteration) {
  1233. End (runToken);
  1234. }
  1235. #if !DEBUG
  1236. }
  1237. catch (Exception error)
  1238. {
  1239. if (errorHandler == null)
  1240. {
  1241. throw;
  1242. }
  1243. resume = errorHandler(error);
  1244. }
  1245. #endif
  1246. }
  1247. }
  1248. /// <summary>
  1249. /// Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.
  1250. /// </summary>
  1251. /// <param name="top">The toplevel to request stop.</param>
  1252. /// <remarks>
  1253. /// <para>
  1254. /// This will cause <see cref="Application.Run(Func{Exception, bool})"/> to return.
  1255. /// </para>
  1256. /// <para>
  1257. /// Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/> property on the currently running <see cref="Toplevel"/> to false.
  1258. /// </para>
  1259. /// </remarks>
  1260. public static void RequestStop (Toplevel top = null)
  1261. {
  1262. if (MdiTop == null || top == null || (MdiTop == null && top != null)) {
  1263. top = Current;
  1264. }
  1265. if (MdiTop != null && top.IsMdiContainer && top?.Running == true
  1266. && (Current?.Modal == false || (Current?.Modal == true && Current?.Running == false))) {
  1267. MdiTop.RequestStop ();
  1268. } else if (MdiTop != null && top != Current && Current?.Running == true && Current?.Modal == true
  1269. && top.Modal && top.Running) {
  1270. var ev = new ToplevelClosingEventArgs (Current);
  1271. Current.OnClosing (ev);
  1272. if (ev.Cancel) {
  1273. return;
  1274. }
  1275. ev = new ToplevelClosingEventArgs (top);
  1276. top.OnClosing (ev);
  1277. if (ev.Cancel) {
  1278. return;
  1279. }
  1280. Current.Running = false;
  1281. OnNotifyStopRunState (Current);
  1282. top.Running = false;
  1283. OnNotifyStopRunState (top);
  1284. } else if ((MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1285. && Current?.Running == true && !top.Running)
  1286. || (MdiTop != null && top != MdiTop && top != Current && Current?.Modal == false
  1287. && Current?.Running == false && !top.Running && toplevels.ToArray () [1].Running)) {
  1288. MoveCurrent (top);
  1289. } else if (MdiTop != null && Current != top && Current?.Running == true && !top.Running
  1290. && Current?.Modal == true && top.Modal) {
  1291. // The Current and the top are both modal so needed to set the Current.Running to false too.
  1292. Current.Running = false;
  1293. OnNotifyStopRunState (Current);
  1294. } else if (MdiTop != null && Current == top && MdiTop?.Running == true && Current?.Running == true && top.Running
  1295. && Current?.Modal == true && top.Modal) {
  1296. // The MdiTop was requested to stop inside a modal toplevel which is the Current and top,
  1297. // both are the same, so needed to set the Current.Running to false too.
  1298. Current.Running = false;
  1299. OnNotifyStopRunState (Current);
  1300. } else {
  1301. Toplevel currentTop;
  1302. if (top == Current || (Current?.Modal == true && !top.Modal)) {
  1303. currentTop = Current;
  1304. } else {
  1305. currentTop = top;
  1306. }
  1307. if (!currentTop.Running) {
  1308. return;
  1309. }
  1310. var ev = new ToplevelClosingEventArgs (currentTop);
  1311. currentTop.OnClosing (ev);
  1312. if (ev.Cancel) {
  1313. return;
  1314. }
  1315. currentTop.Running = false;
  1316. OnNotifyStopRunState (currentTop);
  1317. }
  1318. }
  1319. static void OnNotifyStopRunState (Toplevel top)
  1320. {
  1321. if (ExitRunLoopAfterFirstIteration) {
  1322. NotifyStopRunState?.Invoke (top);
  1323. }
  1324. }
  1325. /// <summary>
  1326. /// Event arguments for the <see cref="Application.Resized"/> event.
  1327. /// </summary>
  1328. public class ResizedEventArgs : EventArgs {
  1329. /// <summary>
  1330. /// The number of rows in the resized terminal.
  1331. /// </summary>
  1332. public int Rows { get; set; }
  1333. /// <summary>
  1334. /// The number of columns in the resized terminal.
  1335. /// </summary>
  1336. public int Cols { get; set; }
  1337. }
  1338. /// <summary>
  1339. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  1340. /// </summary>
  1341. public static Action<ResizedEventArgs> Resized;
  1342. static void TerminalResized ()
  1343. {
  1344. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1345. SetToplevelsSize (full);
  1346. Resized?.Invoke (new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  1347. Driver.Clip = full;
  1348. foreach (var t in toplevels) {
  1349. t.SetRelativeLayout (full);
  1350. t.LayoutSubviews ();
  1351. t.PositionToplevels ();
  1352. t.OnResized (full.Size);
  1353. }
  1354. Refresh ();
  1355. }
  1356. static void SetToplevelsSize (Rect full)
  1357. {
  1358. if (MdiTop == null) {
  1359. foreach (var t in toplevels) {
  1360. if (t?.SuperView == null && !t.Modal) {
  1361. t.Frame = full;
  1362. t.Width = full.Width;
  1363. t.Height = full.Height;
  1364. }
  1365. }
  1366. } else {
  1367. Top.Frame = full;
  1368. Top.Width = full.Width;
  1369. Top.Height = full.Height;
  1370. }
  1371. }
  1372. static bool SetCurrentAsTop ()
  1373. {
  1374. if (MdiTop == null && Current != Top && Current?.SuperView == null && Current?.Modal == false) {
  1375. if (Current.Frame != new Rect (0, 0, Driver.Cols, Driver.Rows)) {
  1376. Current.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1377. }
  1378. Top = Current;
  1379. return true;
  1380. }
  1381. return false;
  1382. }
  1383. /// <summary>
  1384. /// Move to the next Mdi child from the <see cref="MdiTop"/>.
  1385. /// </summary>
  1386. public static void MoveNext ()
  1387. {
  1388. if (MdiTop != null && !Current.Modal) {
  1389. lock (toplevels) {
  1390. toplevels.MoveNext ();
  1391. var isMdi = false;
  1392. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1393. if (!isMdi && toplevels.Peek () == MdiTop) {
  1394. isMdi = true;
  1395. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1396. MoveCurrent (Top);
  1397. break;
  1398. }
  1399. toplevels.MoveNext ();
  1400. }
  1401. Current = toplevels.Peek ();
  1402. }
  1403. }
  1404. }
  1405. /// <summary>
  1406. /// Move to the previous Mdi child from the <see cref="MdiTop"/>.
  1407. /// </summary>
  1408. public static void MovePrevious ()
  1409. {
  1410. if (MdiTop != null && !Current.Modal) {
  1411. lock (toplevels) {
  1412. toplevels.MovePrevious ();
  1413. var isMdi = false;
  1414. while (toplevels.Peek () == MdiTop || !toplevels.Peek ().Visible) {
  1415. if (!isMdi && toplevels.Peek () == MdiTop) {
  1416. isMdi = true;
  1417. } else if (isMdi && toplevels.Peek () == MdiTop) {
  1418. MoveCurrent (Top);
  1419. break;
  1420. }
  1421. toplevels.MovePrevious ();
  1422. }
  1423. Current = toplevels.Peek ();
  1424. }
  1425. }
  1426. }
  1427. internal static bool ShowChild (Toplevel top)
  1428. {
  1429. if (top.Visible && MdiTop != null && Current?.Modal == false) {
  1430. lock (toplevels) {
  1431. toplevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  1432. Current = top;
  1433. }
  1434. return true;
  1435. }
  1436. return false;
  1437. }
  1438. /// <summary>
  1439. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  1440. /// </summary>
  1441. public static void DoEvents ()
  1442. {
  1443. MainLoop.Driver.Wakeup ();
  1444. }
  1445. /// <summary>
  1446. /// Ensures that the superview of the most focused view is on front.
  1447. /// </summary>
  1448. public static void EnsuresTopOnFront ()
  1449. {
  1450. if (MdiTop != null) {
  1451. return;
  1452. }
  1453. var top = FindTopFromView (Top?.MostFocused);
  1454. if (top != null && Top.Subviews.Count > 1 && Top.Subviews [Top.Subviews.Count - 1] != top) {
  1455. Top.BringSubviewToFront (top);
  1456. }
  1457. }
  1458. internal static List<CultureInfo> GetSupportedCultures ()
  1459. {
  1460. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  1461. // Get the assembly
  1462. Assembly assembly = Assembly.GetExecutingAssembly ();
  1463. //Find the location of the assembly
  1464. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  1465. // Find the resource file name of the assembly
  1466. string resourceFilename = $"{Path.GetFileNameWithoutExtension (assembly.Location)}.resources.dll";
  1467. // Return all culture for which satellite folder found with culture code.
  1468. return culture.Where (cultureInfo =>
  1469. assemblyLocation != null &&
  1470. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name)) &&
  1471. File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  1472. ).ToList ();
  1473. }
  1474. }
  1475. }