FileDialog.cs 53 KB

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