FileDialog.cs 43 KB

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