FileDialog.cs 38 KB

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