FileDialog.cs 51 KB

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