FileDialog.cs 53 KB

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