FileDialog.cs 51 KB

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