FileDialog.cs 50 KB

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