FileDialog.cs 51 KB

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