FileDialog.cs 54 KB

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