FileDialog.cs 51 KB

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