Application.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Globalization;
  4. using System.Reflection;
  5. namespace Terminal.Gui;
  6. /// <summary>A static, singleton class representing the application. This class is the entry point for the application.</summary>
  7. /// <example>
  8. /// <code>
  9. /// Application.Init();
  10. /// var win = new Window ($"Example App ({Application.QuitKey} to quit)");
  11. /// Application.Run(win);
  12. /// win.Dispose();
  13. /// Application.Shutdown();
  14. /// </code>
  15. /// </example>
  16. /// <remarks>TODO: Flush this out.</remarks>
  17. public static partial class Application
  18. {
  19. /// <summary>Gets all cultures supported by the application without the invariant language.</summary>
  20. public static List<CultureInfo>? SupportedCultures { get; private set; }
  21. internal static List<CultureInfo> GetSupportedCultures ()
  22. {
  23. CultureInfo [] culture = CultureInfo.GetCultures (CultureTypes.AllCultures);
  24. // Get the assembly
  25. var assembly = Assembly.GetExecutingAssembly ();
  26. //Find the location of the assembly
  27. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  28. // Find the resource file name of the assembly
  29. var resourceFilename = $"{Path.GetFileNameWithoutExtension (AppContext.BaseDirectory)}.resources.dll";
  30. // Return all culture for which satellite folder found with culture code.
  31. return culture.Where (
  32. cultureInfo =>
  33. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  34. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  35. )
  36. .ToList ();
  37. }
  38. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  39. // Encapsulate all setting of initial state for Application; Having
  40. // this in a function like this ensures we don't make mistakes in
  41. // guaranteeing that the state of this singleton is deterministic when Init
  42. // starts running and after Shutdown returns.
  43. internal static void ResetState (bool ignoreDisposed = false)
  44. {
  45. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  46. // Init created. Apps that do any threading will need to code defensively for this.
  47. // e.g. see Issue #537
  48. foreach (Toplevel? t in _topLevels)
  49. {
  50. t!.Running = false;
  51. }
  52. _topLevels.Clear ();
  53. Current = null;
  54. #if DEBUG_IDISPOSABLE
  55. // Don't dispose the Top. It's up to caller dispose it
  56. if (!ignoreDisposed && Top is { })
  57. {
  58. Debug.Assert (Top.WasDisposed);
  59. // If End wasn't called _cachedRunStateToplevel may be null
  60. if (_cachedRunStateToplevel is { })
  61. {
  62. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  63. Debug.Assert (_cachedRunStateToplevel == Top);
  64. }
  65. }
  66. #endif
  67. Top = null;
  68. _cachedRunStateToplevel = null;
  69. // MainLoop stuff
  70. MainLoop?.Dispose ();
  71. MainLoop = null;
  72. _mainThreadId = -1;
  73. Iteration = null;
  74. EndAfterFirstIteration = false;
  75. // Driver stuff
  76. if (Driver is { })
  77. {
  78. Driver.SizeChanged -= Driver_SizeChanged;
  79. Driver.KeyDown -= Driver_KeyDown;
  80. Driver.KeyUp -= Driver_KeyUp;
  81. Driver.MouseEvent -= Driver_MouseEvent;
  82. Driver?.End ();
  83. Driver = null;
  84. }
  85. // Don't reset ForceDriver; it needs to be set before Init is called.
  86. //ForceDriver = string.Empty;
  87. //Force16Colors = false;
  88. _forceFakeConsole = false;
  89. // Run State stuff
  90. NotifyNewRunState = null;
  91. NotifyStopRunState = null;
  92. MouseGrabView = null;
  93. _initialized = false;
  94. // Mouse
  95. _mouseEnteredView = null;
  96. WantContinuousButtonPressedView = null;
  97. MouseEvent = null;
  98. GrabbedMouse = null;
  99. UnGrabbingMouse = null;
  100. GrabbedMouse = null;
  101. UnGrabbedMouse = null;
  102. // Keyboard
  103. AlternateBackwardKey = Key.Empty;
  104. AlternateForwardKey = Key.Empty;
  105. QuitKey = Key.Empty;
  106. KeyDown = null;
  107. KeyUp = null;
  108. SizeChanging = null;
  109. ClearKeyBindings ();
  110. Colors.Reset ();
  111. // Reset synchronization context to allow the user to run async/await,
  112. // as the main loop has been ended, the synchronization context from
  113. // gui.cs does no longer process any callbacks. See #1084 for more details:
  114. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  115. SynchronizationContext.SetSynchronizationContext (null);
  116. }
  117. // When `End ()` is called, it is possible `RunState.Toplevel` is a different object than `Top`.
  118. // This field is set in `End` in this case so that `Begin` correctly sets `Top`.
  119. // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
  120. // is ProgressBarStyles, and it's not clear it needs to.
  121. #region Toplevel handling
  122. /// <summary>Holds the stack of TopLevel views.</summary>
  123. // BUGBUG: Technically, this is not the full lst of TopLevels. There be dragons here, e.g. see how Toplevel.Id is used. What
  124. // about TopLevels that are just a SubView of another View?
  125. internal static readonly Stack<Toplevel> _topLevels = new ();
  126. /// <summary>The <see cref="Toplevel"/> object used for the application on startup (<seealso cref="Application.Top"/>)</summary>
  127. /// <value>The top.</value>
  128. public static Toplevel? Top { get; private set; }
  129. /// <summary>
  130. /// The current <see cref="Toplevel"/> object. This is updated in <see cref="Application.Begin"/> enters and leaves to
  131. /// point to the current
  132. /// <see cref="Toplevel"/> .
  133. /// </summary>
  134. /// <remarks>
  135. /// Only relevant in scenarios where <see cref="Toplevel.IsOverlappedContainer"/> is <see langword="true"/>.
  136. /// </remarks>
  137. /// <value>The current.</value>
  138. public static Toplevel? Current { get; private set; }
  139. private static void EnsureModalOrVisibleAlwaysOnTop (Toplevel topLevel)
  140. {
  141. if (!topLevel.Running
  142. || (topLevel == Current && topLevel.Visible)
  143. || OverlappedTop == null
  144. || _topLevels.Peek ().Modal)
  145. {
  146. return;
  147. }
  148. foreach (Toplevel? top in _topLevels.Reverse ())
  149. {
  150. if (top.Modal && top != Current)
  151. {
  152. MoveCurrent (top);
  153. return;
  154. }
  155. }
  156. if (!topLevel.Visible && topLevel == Current)
  157. {
  158. OverlappedMoveNext ();
  159. }
  160. }
  161. #nullable enable
  162. private static Toplevel? FindDeepestTop (Toplevel start, in Point location)
  163. {
  164. if (!start.Frame.Contains (location))
  165. {
  166. return null;
  167. }
  168. if (_topLevels is { Count: > 0 })
  169. {
  170. int rx = location.X - start.Frame.X;
  171. int ry = location.Y - start.Frame.Y;
  172. foreach (Toplevel? t in _topLevels)
  173. {
  174. if (t != Current)
  175. {
  176. if (t != start && t.Visible && t.Frame.Contains (rx, ry))
  177. {
  178. start = t;
  179. break;
  180. }
  181. }
  182. }
  183. }
  184. return start;
  185. }
  186. #nullable restore
  187. private static View FindTopFromView (View view)
  188. {
  189. View top = view?.SuperView is { } && view?.SuperView != Top
  190. ? view.SuperView
  191. : view;
  192. while (top?.SuperView is { } && top?.SuperView != Top)
  193. {
  194. top = top.SuperView;
  195. }
  196. return top;
  197. }
  198. #nullable enable
  199. // Only return true if the Current has changed.
  200. private static bool MoveCurrent (Toplevel top)
  201. {
  202. // The Current is modal and the top is not modal Toplevel then
  203. // the Current must be moved above the first not modal Toplevel.
  204. if (OverlappedTop is { }
  205. && top != OverlappedTop
  206. && top != Current
  207. && Current?.Modal == true
  208. && !_topLevels.Peek ().Modal)
  209. {
  210. lock (_topLevels)
  211. {
  212. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  213. }
  214. var index = 0;
  215. Toplevel? [] savedToplevels = _topLevels.ToArray ();
  216. foreach (Toplevel? t in savedToplevels)
  217. {
  218. if (!t!.Modal && t != Current && t != top && t != savedToplevels [index])
  219. {
  220. lock (_topLevels)
  221. {
  222. _topLevels.MoveTo (top, index, new ToplevelEqualityComparer ());
  223. }
  224. }
  225. index++;
  226. }
  227. return false;
  228. }
  229. // The Current and the top are both not running Toplevel then
  230. // the top must be moved above the first not running Toplevel.
  231. if (OverlappedTop is { }
  232. && top != OverlappedTop
  233. && top != Current
  234. && Current?.Running == false
  235. && top?.Running == false)
  236. {
  237. lock (_topLevels)
  238. {
  239. _topLevels.MoveTo (Current, 0, new ToplevelEqualityComparer ());
  240. }
  241. var index = 0;
  242. foreach (Toplevel? t in _topLevels.ToArray ())
  243. {
  244. if (!t.Running && t != Current && index > 0)
  245. {
  246. lock (_topLevels)
  247. {
  248. _topLevels.MoveTo (top, index - 1, new ToplevelEqualityComparer ());
  249. }
  250. }
  251. index++;
  252. }
  253. return false;
  254. }
  255. if ((OverlappedTop is { } && top?.Modal == true && _topLevels.Peek () != top)
  256. || (OverlappedTop is { } && Current != OverlappedTop && Current?.Modal == false && top == OverlappedTop)
  257. || (OverlappedTop is { } && Current?.Modal == false && top != Current)
  258. || (OverlappedTop is { } && Current?.Modal == true && top == OverlappedTop))
  259. {
  260. lock (_topLevels)
  261. {
  262. _topLevels.MoveTo (top, 0, new ToplevelEqualityComparer ());
  263. Current = top;
  264. }
  265. }
  266. return true;
  267. }
  268. #nullable restore
  269. /// <summary>Invoked when the terminal's size changed. The new size of the terminal is provided.</summary>
  270. /// <remarks>
  271. /// Event handlers can set <see cref="SizeChangedEventArgs.Cancel"/> to <see langword="true"/> to prevent
  272. /// <see cref="Application"/> from changing it's size to match the new terminal size.
  273. /// </remarks>
  274. public static event EventHandler<SizeChangedEventArgs> SizeChanging;
  275. /// <summary>
  276. /// Called when the application's size changes. Sets the size of all <see cref="Toplevel"/>s and fires the
  277. /// <see cref="SizeChanging"/> event.
  278. /// </summary>
  279. /// <param name="args">The new size.</param>
  280. /// <returns><see lanword="true"/>if the size was changed.</returns>
  281. public static bool OnSizeChanging (SizeChangedEventArgs args)
  282. {
  283. SizeChanging?.Invoke (null, args);
  284. if (args.Cancel || args.Size is null)
  285. {
  286. return false;
  287. }
  288. foreach (Toplevel t in _topLevels)
  289. {
  290. t.SetRelativeLayout (args.Size.Value);
  291. t.LayoutSubviews ();
  292. t.PositionToplevels ();
  293. t.OnSizeChanging (new (args.Size));
  294. if (PositionCursor (t))
  295. {
  296. Driver.UpdateCursor ();
  297. }
  298. }
  299. Refresh ();
  300. return true;
  301. }
  302. #endregion Toplevel handling
  303. /// <summary>
  304. /// Gets a string representation of the Application as rendered by <see cref="Driver"/>.
  305. /// </summary>
  306. /// <returns>A string representation of the Application </returns>
  307. public new static string ToString ()
  308. {
  309. ConsoleDriver driver = Driver;
  310. if (driver is null)
  311. {
  312. return string.Empty;
  313. }
  314. return ToString (driver);
  315. }
  316. /// <summary>
  317. /// Gets a string representation of the Application rendered by the provided <see cref="ConsoleDriver"/>.
  318. /// </summary>
  319. /// <param name="driver">The driver to use to render the contents.</param>
  320. /// <returns>A string representation of the Application </returns>
  321. public static string ToString (ConsoleDriver driver)
  322. {
  323. var sb = new StringBuilder ();
  324. Cell [,] contents = driver.Contents;
  325. for (var r = 0; r < driver.Rows; r++)
  326. {
  327. for (var c = 0; c < driver.Cols; c++)
  328. {
  329. Rune rune = contents [r, c].Rune;
  330. if (rune.DecodeSurrogatePair (out char [] sp))
  331. {
  332. sb.Append (sp);
  333. }
  334. else
  335. {
  336. sb.Append ((char)rune.Value);
  337. }
  338. if (rune.GetColumns () > 1)
  339. {
  340. c++;
  341. }
  342. // See Issue #2616
  343. //foreach (var combMark in contents [r, c].CombiningMarks) {
  344. // sb.Append ((char)combMark.Value);
  345. //}
  346. }
  347. sb.AppendLine ();
  348. }
  349. return sb.ToString ();
  350. }
  351. }