FileDialog.cs 51 KB

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