2
0

FileDialog.cs 53 KB

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