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