FileDialog.cs 51 KB

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