FileDialog.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. #nullable enable
  2. using System.IO.Abstractions;
  3. using System.Text.RegularExpressions;
  4. namespace Terminal.Gui.Views;
  5. /// <summary>
  6. /// The base-class for <see cref="OpenDialog"/> and <see cref="SaveDialog"/>
  7. /// </summary>
  8. public class FileDialog : Dialog, IDesignable
  9. {
  10. private const int ALIGNMENT_GROUP_COMPLETE = 55;
  11. /// <summary>Gets the Path separators for the operating system</summary>
  12. // ReSharper disable once InconsistentNaming
  13. internal static char [] Separators =
  14. [
  15. System.IO.Path.AltDirectorySeparatorChar,
  16. System.IO.Path.DirectorySeparatorChar
  17. ];
  18. /// <summary>
  19. /// Characters to prevent entry into <see cref="_tbPath"/>. Note that this is not using
  20. /// <see cref="System.IO.Path.GetInvalidFileNameChars"/> because we do want to allow directory separators, arrow keys
  21. /// etc.
  22. /// </summary>
  23. private static readonly char [] _badChars = ['"', '<', '>', '|', '*', '?'];
  24. /// <summary>Locking object for ensuring only a single <see cref="SearchState"/> executes at once.</summary>
  25. internal object _onlyOneSearchLock = new ();
  26. private readonly Button _btnBack;
  27. private readonly Button _btnCancel;
  28. private readonly Button _btnForward;
  29. private readonly Button _btnOk;
  30. private readonly Button _btnUp;
  31. private readonly Button _btnTreeToggle;
  32. private readonly IFileSystem? _fileSystem;
  33. private readonly FileDialogHistory _history;
  34. private readonly SpinnerView _spinnerView;
  35. private readonly View _tableViewContainer;
  36. private readonly TableView _tableView;
  37. private readonly TextField _tbFind;
  38. private readonly TextField _tbPath;
  39. private readonly TreeView<IFileSystemInfo> _treeView;
  40. private MenuBarItem? _allowedTypeMenu;
  41. private MenuBar? _allowedTypeMenuBar;
  42. private MenuItem []? _allowedTypeMenuItems;
  43. private int _currentSortColumn;
  44. private bool _currentSortIsAsc = true;
  45. private bool _disposed;
  46. private string? _feedback;
  47. private bool _loaded;
  48. private bool _pushingState;
  49. private Dictionary<IDirectoryInfo, string> _treeRoots = new ();
  50. /// <summary>Initializes a new instance of the <see cref="FileDialog"/> class.</summary>
  51. public FileDialog () : this (new FileSystem ()) { }
  52. /// <summary>Initializes a new instance of the <see cref="FileDialog"/> class with a custom <see cref="IFileSystem"/>.</summary>
  53. /// <remarks>This overload is mainly useful for testing.</remarks>
  54. internal FileDialog (IFileSystem? fileSystem)
  55. {
  56. Height = Dim.Percent (80);
  57. Width = Dim.Percent (80);
  58. // Assume canceled
  59. Canceled = true;
  60. _fileSystem = fileSystem;
  61. Style = new (fileSystem);
  62. _btnOk = new ()
  63. {
  64. X = Pos.Align (Alignment.End, AlignmentModes.AddSpaceBetweenItems, ALIGNMENT_GROUP_COMPLETE),
  65. Y = Pos.AnchorEnd (),
  66. IsDefault = true, Text = Style.OkButtonText
  67. };
  68. _btnOk.Accepting += (s, e) =>
  69. {
  70. if (e.Handled)
  71. {
  72. return;
  73. }
  74. Accept (true);
  75. e.Handled = true;
  76. };
  77. _btnCancel = new ()
  78. {
  79. X = Pos.Align (Alignment.End, AlignmentModes.AddSpaceBetweenItems, ALIGNMENT_GROUP_COMPLETE),
  80. Y = Pos.AnchorEnd (),
  81. Text = Strings.btnCancel
  82. };
  83. _btnCancel.Accepting += (s, e) =>
  84. {
  85. if (e.Handled)
  86. {
  87. return;
  88. }
  89. e.Handled = true;
  90. if (Modal)
  91. {
  92. Application.RequestStop ();
  93. }
  94. };
  95. // Tree toggle button - shares alignment group with OK/Cancel
  96. _btnTreeToggle = new ()
  97. {
  98. X = 0,//Pos.Align (Alignment.End, AlignmentModes.AddSpaceBetweenItems, ALIGNMENT_GROUP_COMPLETE),
  99. Y = Pos.AnchorEnd (),
  100. NoPadding = true
  101. };
  102. _btnTreeToggle.Accepting += (s, e) =>
  103. {
  104. e.Handled = true;
  105. ToggleTreeVisibility ();
  106. };
  107. _btnUp = new () { X = 0, Y = 1, NoPadding = true };
  108. _btnUp.Text = GetUpButtonText ();
  109. _btnUp.Accepting += (s, e) =>
  110. {
  111. _history?.Up ();
  112. e.Handled = true;
  113. };
  114. _btnBack = new () { X = Pos.Right (_btnUp) + 1, Y = 1, NoPadding = true };
  115. _btnBack.Text = GetBackButtonText ();
  116. _btnBack.Accepting += (s, e) =>
  117. {
  118. _history?.Back ();
  119. e.Handled = true;
  120. };
  121. _btnForward = new () { X = Pos.Right (_btnBack) + 1, Y = 1, NoPadding = true };
  122. _btnForward.Text = GetForwardButtonText ();
  123. _btnForward.Accepting += (s, e) =>
  124. {
  125. _history?.Forward ();
  126. e.Handled = true;
  127. };
  128. _tbPath = new () { Width = Dim.Fill (),/* CaptionColor = new (Color.Black)*/ };
  129. _tbPath.KeyDown += (s, k) =>
  130. {
  131. ClearFeedback ();
  132. AcceptIf (k, KeyCode.Enter);
  133. SuppressIfBadChar (k);
  134. };
  135. _tbPath.Autocomplete = new AppendAutocomplete (_tbPath);
  136. _tbPath.Autocomplete.SuggestionGenerator = new FilepathSuggestionGenerator ();
  137. // Create tree view container (left pane)
  138. _treeView = new ()
  139. {
  140. X = 0,
  141. Y = Pos.Bottom (_btnBack),
  142. Width = Dim.Fill (Dim.Func (_ => IsInitialized ? _tableViewContainer!.Frame.Width - 30 : 30)),
  143. Height = Dim.Fill (Dim.Func (_ => IsInitialized ? _btnOk.Frame.Height : 1)),
  144. Visible = false
  145. };
  146. // Create table view container (right pane)
  147. _tableViewContainer = new ()
  148. {
  149. X = 0,
  150. Y = Pos.Bottom (_btnBack),
  151. Width = Dim.Fill (),
  152. Height = Dim.Fill (Dim.Func (_ => IsInitialized ? _btnOk.Frame.Height : 1)),
  153. Arrangement = ViewArrangement.LeftResizable,
  154. BorderStyle = LineStyle.Dashed,
  155. SuperViewRendersLineCanvas = true,
  156. CanFocus = true,
  157. Id = "_tableViewContainer"
  158. };
  159. _tableView = new ()
  160. {
  161. Width = Dim.Fill (),
  162. Height = Dim.Fill (1),
  163. FullRowSelect = true,
  164. Id = "_tableView"
  165. };
  166. _tableView.CollectionNavigator = new FileDialogCollectionNavigator (this, _tableView);
  167. _tableView.KeyBindings.ReplaceCommands (Key.Space, Command.Select);
  168. _tableView.MouseClick += OnTableViewMouseClick;
  169. Style.TableStyle = _tableView.Style;
  170. ColumnStyle nameStyle = Style.TableStyle.GetOrCreateColumnStyle (0);
  171. nameStyle.MinWidth = 10;
  172. nameStyle.ColorGetter = ColorGetter;
  173. ColumnStyle sizeStyle = Style.TableStyle.GetOrCreateColumnStyle (1);
  174. sizeStyle.MinWidth = 10;
  175. sizeStyle.ColorGetter = ColorGetter;
  176. ColumnStyle dateModifiedStyle = Style.TableStyle.GetOrCreateColumnStyle (2);
  177. dateModifiedStyle.MinWidth = 30;
  178. dateModifiedStyle.ColorGetter = ColorGetter;
  179. ColumnStyle typeStyle = Style.TableStyle.GetOrCreateColumnStyle (3);
  180. typeStyle.MinWidth = 6;
  181. typeStyle.ColorGetter = ColorGetter;
  182. var fileDialogTreeBuilder = new FileSystemTreeBuilder ();
  183. _treeView.TreeBuilder = fileDialogTreeBuilder;
  184. _treeView.AspectGetter = AspectGetter;
  185. Style.TreeStyle = _treeView.Style;
  186. _treeView.SelectionChanged += TreeView_SelectionChanged;
  187. _tableViewContainer.Add (_tableView);
  188. _tableView.Style.ShowHorizontalHeaderOverline = true;
  189. _tableView.Style.ShowVerticalCellLines = true;
  190. _tableView.Style.ShowVerticalHeaderLines = true;
  191. _tableView.Style.AlwaysShowHeaders = true;
  192. _tableView.Style.ShowHorizontalHeaderUnderline = true;
  193. _tableView.Style.ShowHorizontalScrollIndicators = true;
  194. _history = new (this);
  195. _tbPath.TextChanged += (s, e) => PathChanged ();
  196. _tableView.CellActivated += CellActivate;
  197. _tableView.KeyDown += (s, k) => k.Handled = TableView_KeyUp (k);
  198. _tableView.SelectedCellChanged += TableView_SelectedCellChanged;
  199. _tableView.KeyBindings.ReplaceCommands (Key.Home, Command.Start);
  200. _tableView.KeyBindings.ReplaceCommands (Key.End, Command.End);
  201. _tableView.KeyBindings.ReplaceCommands (Key.Home.WithShift, Command.StartExtend);
  202. _tableView.KeyBindings.ReplaceCommands (Key.End.WithShift, Command.EndExtend);
  203. _tbFind = new ()
  204. {
  205. X = 0,
  206. Width = Dim.Fill (),
  207. Y = Pos.AnchorEnd (),
  208. HotKey = Key.F.WithAlt,
  209. Id = "_tbFind",
  210. };
  211. _spinnerView = new ()
  212. {
  213. // The spinner view is positioned over the last column of _tbFind
  214. X = Pos.Right (_tbFind) - 1,
  215. Y = Pos.Top (_tbFind),
  216. Visible = false
  217. };
  218. _tbFind.TextChanged += (s, o) => RestartSearch ();
  219. _tbFind.KeyDown += (s, o) =>
  220. {
  221. if (o.KeyCode == KeyCode.Enter)
  222. {
  223. RestartSearch ();
  224. o.Handled = true;
  225. }
  226. if (o.KeyCode == KeyCode.Esc)
  227. {
  228. if (CancelSearch ())
  229. {
  230. o.Handled = true;
  231. }
  232. }
  233. };
  234. AllowsMultipleSelection = false;
  235. UpdateNavigationVisibility ();
  236. base.Add (_tbPath);
  237. base.Add (_btnUp);
  238. base.Add (_btnBack);
  239. base.Add (_btnForward);
  240. base.Add (_treeView);
  241. base.Add (_tableViewContainer);
  242. _tableViewContainer.Add (_tbFind);
  243. _tableViewContainer.Add (_spinnerView);
  244. // Add the toggle along with OK/Cancel so they align as a group
  245. base.Add (_btnTreeToggle);
  246. base.Add (_btnOk);
  247. base.Add (_btnCancel);
  248. // Default: Tree hidden and splitter hidden
  249. SetTreeVisible (false);
  250. }
  251. /// <summary>
  252. /// Gets or Sets a collection of file types that the user can/must select. Only applies when
  253. /// <see cref="OpenMode"/> is <see cref="OpenMode.File"/> or <see cref="OpenMode.Mixed"/>.
  254. /// </summary>
  255. /// <remarks>
  256. /// <see cref="AllowedTypeAny"/> adds the option to select any type (*.*). If this collection is empty then any
  257. /// type is supported and no Types drop-down is shown.
  258. /// </remarks>
  259. public List<IAllowedType> AllowedTypes { get; set; } = [];
  260. /// <summary>
  261. /// Gets or Sets a value indicating whether to allow selecting multiple existing files/directories. Defaults to
  262. /// false.
  263. /// </summary>
  264. public bool AllowsMultipleSelection
  265. {
  266. get => _tableView.MultiSelect;
  267. set => _tableView.MultiSelect = value;
  268. }
  269. /// <summary>The UI selected <see cref="IAllowedType"/> from combo box. May be null.</summary>
  270. public IAllowedType? CurrentFilter { get; private set; }
  271. /// <summary>
  272. /// Gets or sets behavior of the <see cref="FileDialog"/> when the user attempts to delete a selected file(s). Set
  273. /// to null to prevent deleting.
  274. /// </summary>
  275. /// <remarks>
  276. /// Ensure you use a try/catch block with appropriate error handling (e.g. showing a <see cref="MessageBox"/>
  277. /// </remarks>
  278. public IFileOperations FileOperationsHandler { get; set; } = new DefaultFileOperations ();
  279. /// <summary>The maximum number of results that will be collected when searching before stopping.</summary>
  280. /// <remarks>This prevents performance issues e.g. when searching root of file system for a common letter (e.g. 'e').</remarks>
  281. [ConfigurationProperty (Scope = typeof (SettingsScope))]
  282. public static int MaxSearchResults { get; set; } = 10000;
  283. /// <summary>
  284. /// Gets all files/directories selected or an empty collection <see cref="AllowsMultipleSelection"/> is
  285. /// <see langword="false"/> or <see cref="CancelSearch"/>.
  286. /// </summary>
  287. /// <remarks>If selecting only a single file/directory then you should use <see cref="Path"/> instead.</remarks>
  288. public IReadOnlyList<string> MultiSelected { get; private set; }
  289. = Enumerable.Empty<string> ().ToList ().AsReadOnly ();
  290. /// <summary>
  291. /// True if the file/folder must exist already to be selected. This prevents user from entering the name of
  292. /// something that doesn't exist. Defaults to false.
  293. /// </summary>
  294. public bool MustExist { get; set; }
  295. /// <summary>
  296. /// Gets or Sets which <see cref="System.IO.FileSystemInfo"/> type can be selected. Defaults to
  297. /// <see cref="OpenMode.Mixed"/> (i.e. <see cref="DirectoryInfo"/> or <see cref="FileInfo"/>).
  298. /// </summary>
  299. public virtual OpenMode OpenMode { get; set; } = OpenMode.Mixed;
  300. /// <summary>
  301. /// Gets or Sets the selected path in the dialog. This is the result that should be used if
  302. /// <see cref="AllowsMultipleSelection"/> is off and <see cref="CancelSearch"/> is true.
  303. /// </summary>
  304. public string Path
  305. {
  306. get => _tbPath.Text;
  307. set
  308. {
  309. _tbPath.Text = value;
  310. _tbPath.MoveEnd ();
  311. }
  312. }
  313. /// <summary>
  314. /// Defines how the dialog matches files/folders when using the search box. Provide a custom implementation if you
  315. /// want to tailor how matching is performed.
  316. /// </summary>
  317. public ISearchMatcher SearchMatcher { get; set; } = new DefaultSearchMatcher ();
  318. /// <summary>
  319. /// Gets settings for controlling how visual elements behave. Style changes should be made before the
  320. /// <see cref="Dialog"/> is loaded and shown to the user for the first time.
  321. /// </summary>
  322. public FileDialogStyle Style { get; }
  323. /// <summary>Gets the currently open directory and known children presented in the dialog.</summary>
  324. internal FileDialogState? State { get; private set; }
  325. /// <summary>
  326. /// Event fired when user attempts to confirm a selection (or multi selection). Allows you to cancel the selection
  327. /// or undertake alternative behavior e.g. open a dialog "File already exists, Overwrite? yes/no".
  328. /// </summary>
  329. public event EventHandler<FilesSelectedEventArgs>? FilesSelected;
  330. /// <summary>
  331. /// Returns true if there are no <see cref="AllowedTypes"/> or one of them agrees that <paramref name="file"/>
  332. /// <see cref="IAllowedType.IsAllowed(string)"/>.
  333. /// </summary>
  334. /// <param name="file"></param>
  335. /// <returns></returns>
  336. public bool IsCompatibleWithAllowedExtensions (IFileInfo file)
  337. {
  338. // no restrictions
  339. if (!AllowedTypes.Any ())
  340. {
  341. return true;
  342. }
  343. return MatchesAllowedTypes (file);
  344. }
  345. /// <inheritdoc/>
  346. protected override bool OnDrawingContent ()
  347. {
  348. if (!string.IsNullOrWhiteSpace (_feedback))
  349. {
  350. int feedbackWidth = _feedback.EnumerateRunes ().Sum (c => c.GetColumns ());
  351. int feedbackPadLeft = (Viewport.Width - feedbackWidth) / 2 - 1;
  352. feedbackPadLeft = Math.Min (Viewport.Width, feedbackPadLeft);
  353. feedbackPadLeft = Math.Max (0, feedbackPadLeft);
  354. int feedbackPadRight = Viewport.Width - (feedbackPadLeft + feedbackWidth + 2);
  355. feedbackPadRight = Math.Min (Viewport.Width, feedbackPadRight);
  356. feedbackPadRight = Math.Max (0, feedbackPadRight);
  357. Move (0, Viewport.Height / 2);
  358. SetAttribute (new (Color.Red, GetAttributeForRole (VisualRole.Normal).Background));
  359. AddStr (new (' ', feedbackPadLeft));
  360. AddStr (_feedback);
  361. AddStr (new (' ', feedbackPadRight));
  362. }
  363. return true;
  364. }
  365. /// <inheritdoc/>
  366. public override void OnLoaded ()
  367. {
  368. base.OnLoaded ();
  369. if (_loaded)
  370. {
  371. return;
  372. }
  373. Arrangement |= ViewArrangement.Resizable;
  374. _loaded = true;
  375. // May have been updated after instance was constructed
  376. _btnOk.Text = Style.OkButtonText;
  377. _btnCancel.Text = Style.CancelButtonText;
  378. _btnUp.Text = GetUpButtonText ();
  379. _btnBack.Text = GetBackButtonText ();
  380. _btnForward.Text = GetForwardButtonText ();
  381. _tbPath.Caption = Style.PathCaption;
  382. _tbFind.Caption = Style.SearchCaption;
  383. _tbPath.Autocomplete.Scheme = new (_tbPath.GetScheme ())
  384. {
  385. Normal = new (Color.Black, _tbPath.GetAttributeForRole (VisualRole.Normal).Background)
  386. };
  387. _treeRoots = Style.TreeRootGetter ();
  388. Style.IconProvider.IsOpenGetter = _treeView.IsExpanded;
  389. _treeView.AddObjects (_treeRoots.Keys);
  390. // if filtering on file type is configured then create the ComboBox and establish
  391. // initial filtering by extension(s)
  392. if (AllowedTypes.Any ())
  393. {
  394. CurrentFilter = AllowedTypes [0];
  395. // Fiddle factor
  396. int width = AllowedTypes.Max (a => a.ToString ()!.Length) + 6;
  397. _allowedTypeMenu = new (
  398. "<placeholder>",
  399. _allowedTypeMenuItems = AllowedTypes.Select (
  400. (a, i) => new MenuItem (
  401. a.ToString (),
  402. null,
  403. () => { AllowedTypeMenuClicked (i); })
  404. )
  405. .ToArray ()
  406. );
  407. _allowedTypeMenuBar = new ()
  408. {
  409. Width = width,
  410. Y = 1,
  411. X = Pos.AnchorEnd (width),
  412. // TODO: Does not work, if this worked then we could tab to it instead
  413. // of having to hit F9
  414. CanFocus = true,
  415. TabStop = TabBehavior.TabStop,
  416. Menus = [_allowedTypeMenu]
  417. };
  418. AllowedTypeMenuClicked (0);
  419. // TODO: Using v1's menu bar here is a hack. Need to upgrade this.
  420. _allowedTypeMenuBar.DrawingContent += (s, e) =>
  421. {
  422. _allowedTypeMenuBar.Move (e.NewViewport.Width - 1, 0);
  423. AddRune (Glyphs.DownArrow);
  424. };
  425. Add (_allowedTypeMenuBar);
  426. }
  427. // if no path has been provided
  428. if (_tbPath.Text.Length <= 0)
  429. {
  430. Path = _fileSystem!.Directory.GetCurrentDirectory ();
  431. }
  432. // to streamline user experience and allow direct typing of paths
  433. // with zero navigation we start with focus in the text box and any
  434. // default/current path fully selected and ready to be overwritten
  435. _tbPath.SetFocus ();
  436. _tbPath.SelectAll ();
  437. if (string.IsNullOrEmpty (Title))
  438. {
  439. Title = GetDefaultTitle ();
  440. }
  441. if (Style.FlipOkCancelButtonLayoutOrder)
  442. {
  443. _btnCancel.X = Pos.Func (CalculateOkButtonPosX);
  444. _btnOk.X = Pos.Right (_btnCancel) + 1;
  445. MoveSubViewTowardsStart (_btnCancel);
  446. }
  447. // Ensure toggle button text matches current state after sizing
  448. SetTreeVisible (false);
  449. SetNeedsDraw ();
  450. SetNeedsLayout ();
  451. }
  452. /// <inheritdoc/>
  453. protected override void Dispose (bool disposing)
  454. {
  455. _disposed = true;
  456. base.Dispose (disposing);
  457. CancelSearch ();
  458. }
  459. /// <summary>
  460. /// Gets a default dialog title, when <see cref="View.Title"/> is not set or empty, result of the function will be
  461. /// shown.
  462. /// </summary>
  463. protected virtual string GetDefaultTitle ()
  464. {
  465. List<string> titleParts = [Strings.fdOpen];
  466. if (MustExist)
  467. {
  468. titleParts.Add (Strings.fdExisting);
  469. }
  470. switch (OpenMode)
  471. {
  472. case OpenMode.File:
  473. titleParts.Add (Strings.fdFile);
  474. break;
  475. case OpenMode.Directory:
  476. titleParts.Add (Strings.fdDirectory);
  477. break;
  478. }
  479. return string.Join (' ', titleParts);
  480. }
  481. internal void ApplySort ()
  482. {
  483. FileSystemInfoStats [] stats = State?.Children ?? [];
  484. // This portion is never reordered (always .. at top then folders)
  485. IOrderedEnumerable<FileSystemInfoStats> forcedOrder = stats
  486. .OrderByDescending (f => f.IsParent)
  487. .ThenBy (f => f.IsDir ? -1 : 100);
  488. // This portion is flexible based on the column clicked (e.g. alphabetical)
  489. IOrderedEnumerable<FileSystemInfoStats> ordered =
  490. _currentSortIsAsc
  491. ? forcedOrder.ThenBy (
  492. f =>
  493. FileDialogTableSource.GetRawColumnValue (_currentSortColumn, f)
  494. )
  495. : forcedOrder.ThenByDescending (
  496. f =>
  497. FileDialogTableSource.GetRawColumnValue (_currentSortColumn, f)
  498. );
  499. State!.Children = ordered.ToArray ();
  500. _tableView.Update ();
  501. }
  502. /// <summary>Changes the dialog such that <paramref name="d"/> is being explored.</summary>
  503. /// <param name="d"></param>
  504. /// <param name="addCurrentStateToHistory"></param>
  505. /// <param name="setPathText"></param>
  506. /// <param name="clearForward"></param>
  507. /// <param name="pathText">Optional alternate string to set path to.</param>
  508. internal void PushState (
  509. IDirectoryInfo d,
  510. bool addCurrentStateToHistory,
  511. bool setPathText = true,
  512. bool clearForward = true,
  513. string? pathText = null
  514. )
  515. {
  516. // no change of state
  517. if (d == State?.Directory)
  518. {
  519. return;
  520. }
  521. if (d.FullName == State?.Directory.FullName)
  522. {
  523. return;
  524. }
  525. PushState (
  526. new FileDialogState (d, this),
  527. addCurrentStateToHistory,
  528. setPathText,
  529. clearForward,
  530. pathText
  531. );
  532. }
  533. /// <summary>Select <paramref name="toRestore"/> in the table view (if present)</summary>
  534. /// <param name="toRestore"></param>
  535. internal void RestoreSelection (IFileSystemInfo toRestore)
  536. {
  537. _tableView.SelectedRow = State!.Children.IndexOf (r => r.FileSystemInfo == toRestore);
  538. _tableView.EnsureSelectedCellIsVisible ();
  539. }
  540. internal void SortColumn (int col, bool isAsc)
  541. {
  542. // set a sort order
  543. _currentSortColumn = col;
  544. _currentSortIsAsc = isAsc;
  545. ApplySort ();
  546. }
  547. private void Accept (IEnumerable<FileSystemInfoStats> toMultiAccept)
  548. {
  549. if (!AllowsMultipleSelection)
  550. {
  551. return;
  552. }
  553. // Don't include ".." (IsParent) in multi-selections
  554. MultiSelected = toMultiAccept
  555. .Where (s => !s.IsParent)
  556. .Select (s => s.FileSystemInfo.FullName)
  557. .ToList ()
  558. .AsReadOnly ();
  559. Path = MultiSelected.Count == 1 ? MultiSelected [0] : string.Empty;
  560. FinishAccept ();
  561. }
  562. private void Accept (IFileInfo f)
  563. {
  564. if (!IsCompatibleWithOpenMode (f.FullName, out string reason))
  565. {
  566. _feedback = reason;
  567. SetNeedsDraw ();
  568. return;
  569. }
  570. Path = f.FullName;
  571. if (AllowsMultipleSelection)
  572. {
  573. MultiSelected = new List<string> { f.FullName }.AsReadOnly ();
  574. }
  575. FinishAccept ();
  576. }
  577. private void Accept (bool allowMulti)
  578. {
  579. if (allowMulti && TryAcceptMulti ())
  580. {
  581. return;
  582. }
  583. if (!IsCompatibleWithOpenMode (_tbPath.Text, out string reason))
  584. {
  585. _feedback = reason;
  586. SetNeedsDraw ();
  587. return;
  588. }
  589. FinishAccept ();
  590. }
  591. private void AcceptIf (Key key, KeyCode isKey)
  592. {
  593. if (!key.Handled && key.KeyCode == isKey)
  594. {
  595. key.Handled = true;
  596. // User hit Enter in text box so probably wants the
  597. // contents of the text box as their selection not
  598. // whatever lingering selection is in TableView
  599. Accept (false);
  600. }
  601. }
  602. private void AllowedTypeMenuClicked (int idx)
  603. {
  604. IAllowedType allow = AllowedTypes [idx];
  605. for (var i = 0; i < AllowedTypes.Count; i++)
  606. {
  607. _allowedTypeMenuItems! [i].Checked = i == idx;
  608. }
  609. _allowedTypeMenu!.Title = allow.ToString ()!;
  610. CurrentFilter = allow;
  611. _tbPath.ClearAllSelection ();
  612. _tbPath.Autocomplete.ClearSuggestions ();
  613. State!.RefreshChildren ();
  614. WriteStateToTableView ();
  615. }
  616. private string AspectGetter (object o)
  617. {
  618. var fsi = (IFileSystemInfo)o;
  619. if (o is IDirectoryInfo dir && _treeRoots.ContainsKey (dir))
  620. {
  621. // Directory has a special name e.g. 'Pictures'
  622. return _treeRoots [dir];
  623. }
  624. return (Style.IconProvider.GetIconWithOptionalSpace (fsi) + fsi.Name).Trim ();
  625. }
  626. private int CalculateOkButtonPosX (View? _)
  627. {
  628. if (!IsInitialized || !_btnOk.IsInitialized || !_btnCancel.IsInitialized)
  629. {
  630. return 0;
  631. }
  632. return Viewport.Width
  633. - _btnOk.Viewport.Width
  634. - _btnCancel.Viewport.Width
  635. - 1
  636. // TODO: Fiddle factor, seems the Viewport are wrong for someone
  637. - 2;
  638. }
  639. private bool CancelSearch ()
  640. {
  641. if (State is SearchState search)
  642. {
  643. return search.Cancel ();
  644. }
  645. return false;
  646. }
  647. private void CellActivate (object? sender, CellActivatedEventArgs obj)
  648. {
  649. if (TryAcceptMulti ())
  650. {
  651. return;
  652. }
  653. FileSystemInfoStats stats = RowToStats (obj.Row);
  654. if (stats.FileSystemInfo is IDirectoryInfo d)
  655. {
  656. PushState (d, true);
  657. //if (d == State?.Directory || d.FullName == State?.Directory.FullName)
  658. //{
  659. // FinishAccept ();
  660. //}
  661. return;
  662. }
  663. if (stats.FileSystemInfo is IFileInfo f)
  664. {
  665. Accept (f);
  666. }
  667. }
  668. private void ClearFeedback () { _feedback = null; }
  669. private Scheme ColorGetter (CellColorGetterArgs args)
  670. {
  671. FileSystemInfoStats stats = RowToStats (args.RowIndex);
  672. if (!Style.UseColors)
  673. {
  674. return _tableView.GetScheme ();
  675. }
  676. Color color = Style.ColorProvider.GetColor (stats.FileSystemInfo) ?? new Color (Color.White);
  677. var black = new Color (Color.Black);
  678. // TODO: Add some kind of cache for this
  679. return new ()
  680. {
  681. Normal = new (color, black),
  682. HotNormal = new (color, black),
  683. Focus = new (black, color),
  684. HotFocus = new (black, color)
  685. };
  686. }
  687. private void Delete ()
  688. {
  689. IFileSystemInfo [] toDelete = GetFocusedFiles ()!;
  690. if (FileOperationsHandler.Delete (toDelete))
  691. {
  692. RefreshState ();
  693. }
  694. }
  695. private void FinishAccept ()
  696. {
  697. var e = new FilesSelectedEventArgs (this);
  698. FilesSelected?.Invoke (this, e);
  699. if (e.Cancel)
  700. {
  701. return;
  702. }
  703. // if user uses Path selection mode (e.g. Enter in text box)
  704. // then also copy to MultiSelected
  705. if (AllowsMultipleSelection && !MultiSelected.Any ())
  706. {
  707. MultiSelected = string.IsNullOrWhiteSpace (Path)
  708. ? Enumerable.Empty<string> ().ToList ().AsReadOnly ()
  709. : new List<string> { Path }.AsReadOnly ();
  710. }
  711. Canceled = false;
  712. if (Modal)
  713. {
  714. Application.RequestStop ();
  715. }
  716. }
  717. private string GetBackButtonText () { return Glyphs.LeftArrow + "-"; }
  718. private IFileSystemInfo []? GetFocusedFiles ()
  719. {
  720. if (!_tableView.HasFocus || !_tableView.CanFocus)
  721. {
  722. return null;
  723. }
  724. _tableView.EnsureValidSelection ();
  725. if (_tableView.SelectedRow < 0)
  726. {
  727. return null;
  728. }
  729. return _tableView.GetAllSelectedCells ()
  730. .Select (c => c.Y)
  731. .Distinct ()
  732. .Select (RowToStats)
  733. .Where (s => !s.IsParent)
  734. .Select (d => d.FileSystemInfo)
  735. .ToArray ();
  736. }
  737. private string GetForwardButtonText () { return "-" + Glyphs.RightArrow; }
  738. private string GetProposedNewSortOrder (int clickedCol, out bool isAsc)
  739. {
  740. // work out new sort order
  741. if (_currentSortColumn == clickedCol && _currentSortIsAsc)
  742. {
  743. isAsc = false;
  744. return string.Format (Strings.fdCtxSortDesc, _tableView.Table.ColumnNames [clickedCol]);
  745. }
  746. isAsc = true;
  747. return string.Format (Strings.fdCtxSortAsc, _tableView.Table.ColumnNames [clickedCol]);
  748. }
  749. private string GetUpButtonText () { return Style.UseUnicodeCharacters ? "◭" : "▲"; }
  750. private void HideColumn (int clickedCol)
  751. {
  752. ColumnStyle style = _tableView.Style.GetOrCreateColumnStyle (clickedCol);
  753. style.Visible = false;
  754. _tableView.Update ();
  755. }
  756. private bool IsCompatibleWithAllowedExtensions (string path)
  757. {
  758. // no restrictions
  759. if (!AllowedTypes.Any ())
  760. {
  761. return true;
  762. }
  763. return AllowedTypes.Any (t => t.IsAllowed (path));
  764. }
  765. private bool IsCompatibleWithOpenMode (string s, out string reason)
  766. {
  767. reason = string.Empty;
  768. if (string.IsNullOrWhiteSpace (s))
  769. {
  770. return false;
  771. }
  772. if (!IsCompatibleWithAllowedExtensions (s))
  773. {
  774. reason = Style.WrongFileTypeFeedback;
  775. return false;
  776. }
  777. switch (OpenMode)
  778. {
  779. case OpenMode.Directory:
  780. if (MustExist && !Directory.Exists (s))
  781. {
  782. reason = Style.DirectoryMustExistFeedback;
  783. return false;
  784. }
  785. if (File.Exists (s))
  786. {
  787. reason = Style.FileAlreadyExistsFeedback;
  788. return false;
  789. }
  790. return true;
  791. case OpenMode.File:
  792. if (MustExist && !File.Exists (s))
  793. {
  794. reason = Style.FileMustExistFeedback;
  795. return false;
  796. }
  797. if (Directory.Exists (s))
  798. {
  799. reason = Style.DirectoryAlreadyExistsFeedback;
  800. return false;
  801. }
  802. return true;
  803. case OpenMode.Mixed:
  804. if (MustExist && !File.Exists (s) && !Directory.Exists (s))
  805. {
  806. reason = Style.FileOrDirectoryMustExistFeedback;
  807. return false;
  808. }
  809. return true;
  810. default: throw new ArgumentOutOfRangeException (nameof (OpenMode));
  811. }
  812. }
  813. /// <summary>Returns true if any <see cref="AllowedTypes"/> matches <paramref name="file"/>.</summary>
  814. /// <param name="file"></param>
  815. /// <returns></returns>
  816. private bool MatchesAllowedTypes (IFileInfo file) { return AllowedTypes.Any (t => t.IsAllowed (file.FullName)); }
  817. /// <summary>
  818. /// If <see cref="TableView.MultiSelect"/> is this returns a union of all <see cref="FileSystemInfoStats"/> in the
  819. /// selection.
  820. /// </summary>
  821. /// <returns></returns>
  822. private IEnumerable<FileSystemInfoStats> MultiRowToStats ()
  823. {
  824. HashSet<FileSystemInfoStats> toReturn = new ();
  825. if (AllowsMultipleSelection && _tableView.MultiSelectedRegions.Any ())
  826. {
  827. foreach (Point p in _tableView.GetAllSelectedCells ())
  828. {
  829. FileSystemInfoStats add = State?.Children [p.Y]!;
  830. toReturn.Add (add);
  831. }
  832. }
  833. return toReturn;
  834. }
  835. private void New ()
  836. {
  837. {
  838. IFileSystemInfo created = FileOperationsHandler.New (_fileSystem, State!.Directory);
  839. if (created is { })
  840. {
  841. RefreshState ();
  842. RestoreSelection (created);
  843. }
  844. }
  845. }
  846. private void OnTableViewMouseClick (object? sender, MouseEventArgs e)
  847. {
  848. Point? clickedCell = _tableView.ScreenToCell (e.Position.X, e.Position.Y, out int? clickedCol);
  849. if (clickedCol is { })
  850. {
  851. if (e.Flags.HasFlag (MouseFlags.Button1Clicked))
  852. {
  853. // left click in a header
  854. SortColumn (clickedCol.Value);
  855. }
  856. else if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  857. {
  858. // right click in a header
  859. ShowHeaderContextMenu (clickedCol.Value, e);
  860. }
  861. }
  862. else
  863. {
  864. if (clickedCell is { } && e.Flags.HasFlag (MouseFlags.Button3Clicked))
  865. {
  866. // right click in rest of table
  867. ShowCellContextMenu (clickedCell, e);
  868. }
  869. }
  870. }
  871. private void PathChanged ()
  872. {
  873. // avoid re-entry
  874. if (_pushingState)
  875. {
  876. return;
  877. }
  878. string path = _tbPath.Text;
  879. if (string.IsNullOrWhiteSpace (path))
  880. {
  881. return;
  882. }
  883. IDirectoryInfo dir = StringToDirectoryInfo (path);
  884. if (dir.Exists)
  885. {
  886. PushState (dir, true, false);
  887. }
  888. else if (dir.Parent?.Exists ?? false)
  889. {
  890. PushState (dir.Parent, true, false);
  891. }
  892. _tbPath.Autocomplete.GenerateSuggestions (
  893. new AutocompleteFilepathContext (_tbPath.Text, _tbPath.CursorPosition, State)
  894. );
  895. }
  896. private void PushState (
  897. FileDialogState newState,
  898. bool addCurrentStateToHistory,
  899. bool setPathText = true,
  900. bool clearForward = true,
  901. string? pathText = null
  902. )
  903. {
  904. if (State is SearchState search)
  905. {
  906. search.Cancel ();
  907. }
  908. try
  909. {
  910. _pushingState = true;
  911. // push the old state to history
  912. if (addCurrentStateToHistory)
  913. {
  914. _history.Push (State, clearForward);
  915. }
  916. _tbPath.Autocomplete.ClearSuggestions ();
  917. if (pathText is { })
  918. {
  919. Path = pathText;
  920. }
  921. else if (setPathText)
  922. {
  923. SetPathToSelectedObject (newState.Directory);
  924. }
  925. State = newState;
  926. _tbPath.Autocomplete.GenerateSuggestions (
  927. new AutocompleteFilepathContext (_tbPath.Text, _tbPath.CursorPosition, State)
  928. );
  929. WriteStateToTableView ();
  930. if (clearForward)
  931. {
  932. _history.ClearForward ();
  933. }
  934. _tableView.RowOffset = 0;
  935. _tableView.SelectedRow = 0;
  936. SetNeedsDraw ();
  937. UpdateNavigationVisibility ();
  938. }
  939. finally
  940. {
  941. _pushingState = false;
  942. }
  943. ClearFeedback ();
  944. }
  945. private void RefreshState ()
  946. {
  947. State!.RefreshChildren ();
  948. PushState (State, false, false, false);
  949. }
  950. private void Rename ()
  951. {
  952. IFileSystemInfo [] toRename = GetFocusedFiles ()!;
  953. if (toRename?.Length == 1)
  954. {
  955. IFileSystemInfo newNamed = FileOperationsHandler.Rename (_fileSystem, toRename.Single ());
  956. if (newNamed is { })
  957. {
  958. RefreshState ();
  959. RestoreSelection (newNamed);
  960. }
  961. }
  962. }
  963. private void RestartSearch ()
  964. {
  965. if (_disposed || State?.Directory is null)
  966. {
  967. return;
  968. }
  969. if (State is SearchState oldSearch)
  970. {
  971. oldSearch.Cancel ();
  972. }
  973. // user is clearing search terms
  974. if (_tbFind.Text is null || _tbFind.Text.Length == 0)
  975. {
  976. // Wait for search cancellation (if any) to finish
  977. // then push the current dir state
  978. lock (_onlyOneSearchLock)
  979. {
  980. PushState (new FileDialogState (State.Directory, this), false);
  981. }
  982. return;
  983. }
  984. PushState (new SearchState (State?.Directory!, this, _tbFind.Text), true);
  985. }
  986. private FileSystemInfoStats RowToStats (int rowIndex) { return State?.Children [rowIndex]!; }
  987. private void ShowCellContextMenu (Point? clickedCell, MouseEventArgs e)
  988. {
  989. if (clickedCell is null)
  990. {
  991. return;
  992. }
  993. PopoverMenu? contextMenu = new (
  994. [
  995. new (Strings.fdCtxNew, string.Empty, New),
  996. new (Strings.fdCtxRename, string.Empty, Rename),
  997. new (Strings.fdCtxDelete, string.Empty, Delete)
  998. ]);
  999. _tableView.SetSelection (clickedCell.Value.X, clickedCell.Value.Y, false);
  1000. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  1001. // and the context menu is disposed when it is closed.
  1002. Application.Popover?.Register (contextMenu);
  1003. contextMenu?.MakeVisible (e.ScreenPosition);
  1004. }
  1005. private void ShowHeaderContextMenu (int clickedCol, MouseEventArgs e)
  1006. {
  1007. string sort = GetProposedNewSortOrder (clickedCol, out bool isAsc);
  1008. PopoverMenu? contextMenu = new (
  1009. [
  1010. new (
  1011. string.Format (
  1012. Strings.fdCtxHide,
  1013. StripArrows (_tableView.Table.ColumnNames [clickedCol])
  1014. ),
  1015. string.Empty,
  1016. () => HideColumn (clickedCol)
  1017. ),
  1018. new (
  1019. StripArrows (sort),
  1020. string.Empty,
  1021. () => SortColumn (clickedCol, isAsc))
  1022. ]
  1023. );
  1024. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  1025. // and the context menu is disposed when it is closed.
  1026. Application.Popover?.Register (contextMenu);
  1027. contextMenu?.MakeVisible (e.ScreenPosition);
  1028. }
  1029. private void SortColumn (int clickedCol)
  1030. {
  1031. GetProposedNewSortOrder (clickedCol, out bool isAsc);
  1032. SortColumn (clickedCol, isAsc);
  1033. _tableView.Table =
  1034. new FileDialogTableSource (this, State, Style, _currentSortColumn, _currentSortIsAsc);
  1035. }
  1036. private IDirectoryInfo StringToDirectoryInfo (string path)
  1037. {
  1038. // if you pass new DirectoryInfo("C:") you get a weird object
  1039. // where the FullName is in fact the current working directory.
  1040. // really not what most users would expect
  1041. if (Regex.IsMatch (path, "^\\w:$"))
  1042. {
  1043. return _fileSystem!.DirectoryInfo.New (path + _fileSystem.Path.DirectorySeparatorChar);
  1044. }
  1045. return _fileSystem!.DirectoryInfo.New (path);
  1046. }
  1047. private static string StripArrows (string columnName) { return columnName.Replace (" (▼)", string.Empty).Replace (" (▲)", string.Empty); }
  1048. private void SuppressIfBadChar (Key k)
  1049. {
  1050. // don't let user type bad letters
  1051. var ch = (char)k;
  1052. if (_badChars.Contains (ch))
  1053. {
  1054. k.Handled = true;
  1055. }
  1056. }
  1057. private bool TableView_KeyUp (Key keyEvent)
  1058. {
  1059. if (keyEvent.KeyCode == KeyCode.Backspace)
  1060. {
  1061. return _history.Back ();
  1062. }
  1063. if (keyEvent.KeyCode == (KeyCode.ShiftMask | KeyCode.Backspace))
  1064. {
  1065. return _history.Forward ();
  1066. }
  1067. if (keyEvent.KeyCode == KeyCode.Delete)
  1068. {
  1069. Delete ();
  1070. return true;
  1071. }
  1072. if (keyEvent.KeyCode == (KeyCode.CtrlMask | KeyCode.R))
  1073. {
  1074. Rename ();
  1075. return true;
  1076. }
  1077. if (keyEvent.KeyCode == (KeyCode.CtrlMask | KeyCode.N))
  1078. {
  1079. New ();
  1080. return true;
  1081. }
  1082. return false;
  1083. }
  1084. private void TableView_SelectedCellChanged (object? sender, SelectedCellChangedEventArgs obj)
  1085. {
  1086. if (!_tableView.HasFocus || obj.NewRow == -1 || obj.Table.Rows == 0)
  1087. {
  1088. return;
  1089. }
  1090. if (_tableView.MultiSelect && _tableView.MultiSelectedRegions.Any ())
  1091. {
  1092. return;
  1093. }
  1094. FileSystemInfoStats stats = RowToStats (obj.NewRow);
  1095. IFileSystemInfo dest;
  1096. if (stats.IsParent)
  1097. {
  1098. dest = State!.Directory;
  1099. }
  1100. else
  1101. {
  1102. dest = stats.FileSystemInfo;
  1103. }
  1104. try
  1105. {
  1106. _pushingState = true;
  1107. SetPathToSelectedObject (dest);
  1108. State!.Selected = stats;
  1109. _tbPath.Autocomplete.ClearSuggestions ();
  1110. }
  1111. finally
  1112. {
  1113. _pushingState = false;
  1114. }
  1115. }
  1116. private void TreeView_SelectionChanged (object? sender, SelectionChangedEventArgs<IFileSystemInfo> e)
  1117. {
  1118. SetPathToSelectedObject (e.NewValue);
  1119. }
  1120. private void SetPathToSelectedObject (IFileSystemInfo? selected)
  1121. {
  1122. if (selected is null)
  1123. {
  1124. return;
  1125. }
  1126. if (selected is IDirectoryInfo && Style.PreserveFilenameOnDirectoryChanges)
  1127. {
  1128. if (!string.IsNullOrWhiteSpace (Path) && !_fileSystem!.Directory.Exists (Path))
  1129. {
  1130. var currentFile = _fileSystem.Path.GetFileName (Path);
  1131. if (!string.IsNullOrWhiteSpace (currentFile))
  1132. {
  1133. Path = _fileSystem.Path.Combine (selected.FullName, currentFile);
  1134. return;
  1135. }
  1136. }
  1137. }
  1138. Path = selected.FullName;
  1139. }
  1140. private bool TryAcceptMulti ()
  1141. {
  1142. IEnumerable<FileSystemInfoStats> multi = MultiRowToStats ();
  1143. string? reason = null;
  1144. IEnumerable<FileSystemInfoStats> fileSystemInfoStatsEnumerable = multi as FileSystemInfoStats [] ?? multi.ToArray ();
  1145. if (!fileSystemInfoStatsEnumerable.Any ())
  1146. {
  1147. return false;
  1148. }
  1149. if (fileSystemInfoStatsEnumerable.All (
  1150. m => IsCompatibleWithOpenMode (
  1151. m.FileSystemInfo.FullName,
  1152. out reason
  1153. )
  1154. ))
  1155. {
  1156. Accept (fileSystemInfoStatsEnumerable);
  1157. return true;
  1158. }
  1159. if (reason is { })
  1160. {
  1161. _feedback = reason;
  1162. SetNeedsDraw ();
  1163. }
  1164. return false;
  1165. }
  1166. private void UpdateNavigationVisibility ()
  1167. {
  1168. _btnBack.Visible = _history.CanBack ();
  1169. _btnForward.Visible = _history.CanForward ();
  1170. _btnUp.Visible = _history.CanUp ();
  1171. }
  1172. private void WriteStateToTableView ()
  1173. {
  1174. _tableView.Table =
  1175. new FileDialogTableSource (this, State, Style, _currentSortColumn, _currentSortIsAsc);
  1176. ApplySort ();
  1177. _tableView.Update ();
  1178. }
  1179. // --- Tree visibility management ---
  1180. private void ToggleTreeVisibility ()
  1181. {
  1182. SetTreeVisible (!_treeView.Visible);
  1183. }
  1184. private void SetTreeVisible (bool visible)
  1185. {
  1186. _treeView.Enabled = visible;
  1187. _treeView.Visible = visible;
  1188. if (visible)
  1189. {
  1190. // When visible, the table view's left edge is a splitter next to the tree
  1191. _treeView.Width = Dim.Fill (Dim.Func (_ => IsInitialized ? _tableViewContainer!.Frame.Width - 30 : 30));
  1192. _tableViewContainer.X = 30;
  1193. _tableViewContainer.Arrangement = ViewArrangement.LeftResizable;
  1194. _tableViewContainer.Border!.Thickness = new (1, 0, 0, 0);
  1195. }
  1196. else
  1197. {
  1198. // When hidden, table occupies full width and splitter is hidden/disabled
  1199. _treeView.Width = 0;
  1200. _tableViewContainer.X = 0;
  1201. _tableViewContainer.Width = Dim.Fill ();
  1202. _tableViewContainer.Arrangement = ViewArrangement.Fixed;
  1203. _tableViewContainer.Border!.Thickness = new (0, 0, 0, 0);
  1204. }
  1205. _btnTreeToggle.Text = GetTreeToggleText (visible);
  1206. SetNeedsLayout ();
  1207. SetNeedsDraw ();
  1208. }
  1209. private string GetTreeToggleText (bool visible)
  1210. {
  1211. return visible
  1212. ? $"{Glyphs.LeftArrow}{Strings.fdTree}"
  1213. : $"{Glyphs.RightArrow}{Strings.fdTree}";
  1214. }
  1215. /// <summary>State representing a recursive search from <see cref="FileDialogState.Directory"/> downwards.</summary>
  1216. internal class SearchState : FileDialogState
  1217. {
  1218. // TODO: Add thread safe child adding
  1219. private readonly List<FileSystemInfoStats> _found = [];
  1220. private readonly object _oLockFound = new ();
  1221. private readonly CancellationTokenSource _token = new ();
  1222. private bool _cancel;
  1223. private bool _finished;
  1224. public SearchState (IDirectoryInfo dir, FileDialog parent, string searchTerms) : base (dir, parent)
  1225. {
  1226. parent.SearchMatcher.Initialize (searchTerms);
  1227. Children = [];
  1228. BeginSearch ();
  1229. }
  1230. /// <summary>
  1231. /// Cancels the current search (if any). Returns true if a search was running and cancellation was successfully
  1232. /// set.
  1233. /// </summary>
  1234. /// <returns></returns>
  1235. internal bool Cancel ()
  1236. {
  1237. bool alreadyCancelled = _token.IsCancellationRequested || _cancel;
  1238. _cancel = true;
  1239. _token.Cancel ();
  1240. return !alreadyCancelled;
  1241. }
  1242. internal override void RefreshChildren () { }
  1243. private void BeginSearch ()
  1244. {
  1245. Task.Run (
  1246. () =>
  1247. {
  1248. RecursiveFind (Directory);
  1249. _finished = true;
  1250. }
  1251. );
  1252. Task.Run (UpdateChildren);
  1253. }
  1254. private void RecursiveFind (IDirectoryInfo directory)
  1255. {
  1256. foreach (FileSystemInfoStats f in GetChildren (directory))
  1257. {
  1258. if (_cancel)
  1259. {
  1260. return;
  1261. }
  1262. if (f.IsParent)
  1263. {
  1264. continue;
  1265. }
  1266. lock (_oLockFound)
  1267. {
  1268. if (_found.Count >= MaxSearchResults)
  1269. {
  1270. _finished = true;
  1271. return;
  1272. }
  1273. }
  1274. if (Parent.SearchMatcher.IsMatch (f.FileSystemInfo))
  1275. {
  1276. lock (_oLockFound)
  1277. {
  1278. _found.Add (f);
  1279. }
  1280. }
  1281. if (f.FileSystemInfo is IDirectoryInfo sub)
  1282. {
  1283. RecursiveFind (sub);
  1284. }
  1285. }
  1286. }
  1287. private void UpdateChildren ()
  1288. {
  1289. lock (Parent._onlyOneSearchLock)
  1290. {
  1291. while (!_cancel && !_finished)
  1292. {
  1293. try
  1294. {
  1295. Task.Delay (250).Wait (_token.Token);
  1296. }
  1297. catch (OperationCanceledException)
  1298. {
  1299. _cancel = true;
  1300. }
  1301. if (_cancel || _finished)
  1302. {
  1303. break;
  1304. }
  1305. UpdateChildrenToFound ();
  1306. }
  1307. if (_finished && !_cancel)
  1308. {
  1309. UpdateChildrenToFound ();
  1310. }
  1311. Application.Invoke (() => { Parent._spinnerView.Visible = false; });
  1312. }
  1313. }
  1314. private void UpdateChildrenToFound ()
  1315. {
  1316. lock (_oLockFound)
  1317. {
  1318. Children = _found.ToArray ();
  1319. }
  1320. Application.Invoke (
  1321. () =>
  1322. {
  1323. Parent._tbPath.Autocomplete.GenerateSuggestions (
  1324. new AutocompleteFilepathContext (
  1325. Parent._tbPath.Text,
  1326. Parent._tbPath.CursorPosition,
  1327. this
  1328. )
  1329. );
  1330. Parent.WriteStateToTableView ();
  1331. Parent._spinnerView.Visible = true;
  1332. Parent._spinnerView.SetNeedsDraw ();
  1333. }
  1334. );
  1335. }
  1336. }
  1337. bool IDesignable.EnableForDesign ()
  1338. {
  1339. Modal = false;
  1340. OnLoaded ();
  1341. return true;
  1342. }
  1343. }