FileDialog.cs 51 KB

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