FileDialog.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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 (true);
  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. tableView.EnsureValidSelection ();
  445. var col = tableView.SelectedColumn;
  446. var style = tableView.Style.GetColumnStyleIfAny (tableView.Table.Columns [col]);
  447. var collection = tableView
  448. .Table
  449. .Rows
  450. .Cast<DataRow> ()
  451. .Select ((o, idx) => col == 0 ?
  452. RowToStats(idx).FileSystemInfo.Name :
  453. style.GetRepresentation (o [0])?.TrimStart('.'))
  454. .ToArray ();
  455. collectionNavigator = new CollectionNavigator (collection);
  456. }
  457. /// <summary>
  458. /// Gets or Sets which <see cref="System.IO.FileSystemInfo"/> type can be selected.
  459. /// Defaults to <see cref="OpenMode.Mixed"/> (i.e. <see cref="DirectoryInfo"/> or
  460. /// <see cref="FileInfo"/>).
  461. /// </summary>
  462. public OpenMode OpenMode { get; set; } = OpenMode.Mixed;
  463. /// <summary>
  464. /// Gets or Sets the selected path in the dialog. This is the result that should
  465. /// be used if <see cref="AllowsMultipleSelection"/> is off and <see cref="Canceled"/>
  466. /// is true.
  467. /// </summary>
  468. public string Path {
  469. get => this.tbPath.Text.ToString ();
  470. set {
  471. this.tbPath.Text = value;
  472. this.tbPath.MoveEnd ();
  473. }
  474. }
  475. /// <summary>
  476. /// Defines how the dialog matches files/folders when using the search
  477. /// box. Provide a custom implementation if you want to tailor how matching
  478. /// is performed.
  479. /// </summary>
  480. public ISearchMatcher SearchMatcher { get; set; } = new DefaultSearchMatcher ();
  481. /// <summary>
  482. /// Gets or Sets a value indicating whether to allow selecting
  483. /// multiple existing files/directories. Defaults to false.
  484. /// </summary>
  485. public bool AllowsMultipleSelection {
  486. get => this.tableView.MultiSelect;
  487. set => this.tableView.MultiSelect = value;
  488. }
  489. /// <summary>
  490. /// Gets or Sets a collection of file types that the user can/must select. Only applies
  491. /// when <see cref="OpenMode"/> is <see cref="OpenMode.File"/> or <see cref="OpenMode.Mixed"/>.
  492. /// </summary>
  493. /// <remarks><see cref="AllowedTypeAny"/> adds the option to select any type (*.*). If this
  494. /// collection is empty then any type is supported and no Types drop-down is shown.</remarks>
  495. public List<IAllowedType> AllowedTypes { get; set; } = new List<IAllowedType> ();
  496. /// <summary>
  497. /// Gets a value indicating whether the <see cref="FileDialog"/> was closed
  498. /// without confirming a selection.
  499. /// </summary>
  500. public bool Canceled { get; private set; } = true;
  501. /// <summary>
  502. /// Gets all files/directories selected or an empty collection
  503. /// <see cref="AllowsMultipleSelection"/> is <see langword="false"/> or <see cref="Canceled"/>.
  504. /// </summary>
  505. /// <remarks>If selecting only a single file/directory then you should use <see cref="Path"/> instead.</remarks>
  506. public IReadOnlyList<string> MultiSelected { get; private set; }
  507. = Enumerable.Empty<string> ().ToList ().AsReadOnly ();
  508. /// <inheritdoc/>
  509. public override void Redraw (Rect bounds)
  510. {
  511. base.Redraw (bounds);
  512. if (!string.IsNullOrWhiteSpace (feedback)) {
  513. var feedbackWidth = feedback.Sum (c => Rune.ColumnWidth (c));
  514. var feedbackPadLeft = ((bounds.Width - feedbackWidth) / 2) - 1;
  515. feedbackPadLeft = Math.Min (bounds.Width, feedbackPadLeft);
  516. feedbackPadLeft = Math.Max (0, feedbackPadLeft);
  517. var feedbackPadRight = bounds.Width - (feedbackPadLeft + feedbackWidth + 2);
  518. feedbackPadRight = Math.Min (bounds.Width, feedbackPadRight);
  519. feedbackPadRight = Math.Max (0, feedbackPadRight);
  520. Move (0, Bounds.Height / 2);
  521. Driver.SetAttribute (new Attribute (Color.Red, this.ColorScheme.Normal.Background));
  522. Driver.AddStr (new string (' ', feedbackPadLeft));
  523. Driver.AddStr (feedback);
  524. Driver.AddStr (new string (' ', feedbackPadRight));
  525. }
  526. }
  527. /// <inheritdoc/>
  528. public override void OnLoaded ()
  529. {
  530. base.OnLoaded ();
  531. if (loaded) {
  532. return;
  533. }
  534. loaded = true;
  535. // May have been updated after instance was constructed
  536. this.btnOk.Text = Style.OkButtonText;
  537. this.btnUp.Text = this.GetUpButtonText();
  538. this.btnBack.Text = this.GetBackButtonText();
  539. this.btnForward.Text = this.GetForwardButtonText();
  540. this.btnToggleSplitterCollapse.Text = this.GetToggleSplitterText(false);
  541. tbPath.Autocomplete.ColorScheme.Normal = Attribute.Make (Color.Black, tbPath.ColorScheme.Normal.Background);
  542. treeView.AddObjects (Style.TreeRootGetter ());
  543. // if filtering on file type is configured then create the ComboBox and establish
  544. // initial filtering by extension(s)
  545. if (this.AllowedTypes.Any ()) {
  546. this.CurrentFilter = this.AllowedTypes [0];
  547. // Fiddle factor
  548. var width = this.AllowedTypes.Max (a => a.ToString ().Length) + 6;
  549. allowedTypeMenu = new MenuBarItem ("<placeholder>",
  550. allowedTypeMenuItems = AllowedTypes.Select (
  551. (a, i) => new MenuItem (a.ToString (), null, () => {
  552. AllowedTypeMenuClicked (i);
  553. }))
  554. .ToArray ());
  555. allowedTypeMenuBar = new MenuBar (new [] { allowedTypeMenu }) {
  556. Width = width,
  557. Y = 1,
  558. X = Pos.AnchorEnd (width),
  559. // TODO: Does not work, if this worked then we could tab to it instead
  560. // of having to hit F9
  561. CanFocus = true,
  562. TabStop = true
  563. };
  564. AllowedTypeMenuClicked (0);
  565. allowedTypeMenuBar.Enter += (s, e) => {
  566. allowedTypeMenuBar.OpenMenu (0);
  567. };
  568. allowedTypeMenuBar.DrawContentComplete += (s, e) => {
  569. allowedTypeMenuBar.Move (e.Rect.Width - 1, 0);
  570. Driver.AddRune (Driver.DownArrow);
  571. };
  572. this.Add (allowedTypeMenuBar);
  573. }
  574. // if no path has been provided
  575. if (this.tbPath.Text.Length <= 0) {
  576. this.tbPath.Text = Environment.CurrentDirectory;
  577. }
  578. // to streamline user experience and allow direct typing of paths
  579. // with zero navigation we start with focus in the text box and any
  580. // default/current path fully selected and ready to be overwritten
  581. this.tbPath.FocusFirst ();
  582. this.tbPath.SelectAll ();
  583. if (ustring.IsNullOrEmpty (Title)) {
  584. switch (OpenMode) {
  585. case OpenMode.File:
  586. this.Title = $"{Strings.fdOpen} {(MustExist ? Strings.fdExisting + " " : "")}{Strings.fdFile}";
  587. break;
  588. case OpenMode.Directory:
  589. this.Title = $"{Strings.fdOpen} {(MustExist ? Strings.fdExisting + " " : "")}{Strings.fdDirectory}";
  590. break;
  591. case OpenMode.Mixed:
  592. this.Title = $"{Strings.fdOpen} {(MustExist ? Strings.fdExisting : "")}";
  593. break;
  594. }
  595. }
  596. this.LayoutSubviews ();
  597. }
  598. private void AllowedTypeMenuClicked (int idx)
  599. {
  600. var allow = AllowedTypes [idx];
  601. for (int i = 0; i < AllowedTypes.Count; i++) {
  602. allowedTypeMenuItems [i].Checked = i == idx;
  603. }
  604. allowedTypeMenu.Title = allow.ToString ();
  605. this.CurrentFilter = allow;
  606. this.tbPath.ClearAllSelection ();
  607. this.tbPath.Autocomplete.ClearSuggestions ();
  608. if (this.State != null) {
  609. this.State.RefreshChildren ();
  610. this.WriteStateToTableView ();
  611. }
  612. }
  613. private void SuppressIfBadChar (KeyEventEventArgs k)
  614. {
  615. // don't let user type bad letters
  616. var ch = (char)k.KeyEvent.KeyValue;
  617. if (badChars.Contains (ch)) {
  618. k.Handled = true;
  619. }
  620. }
  621. private bool TreeView_KeyDown (KeyEvent keyEvent)
  622. {
  623. if (this.treeView.HasFocus && Separators.Contains ((char)keyEvent.KeyValue)) {
  624. this.tbPath.FocusFirst ();
  625. // let that keystroke go through on the tbPath instead
  626. return true;
  627. }
  628. return false;
  629. }
  630. private void AcceptIf (KeyEventEventArgs keyEvent, Key isKey)
  631. {
  632. if (!keyEvent.Handled && keyEvent.KeyEvent.Key == isKey) {
  633. keyEvent.Handled = true;
  634. // User hit Enter in text box so probably wants the
  635. // contents of the text box as their selection not
  636. // whatever lingering selection is in TableView
  637. this.Accept (false);
  638. }
  639. }
  640. private void Accept (IEnumerable<FileSystemInfoStats> toMultiAccept)
  641. {
  642. if (!this.AllowsMultipleSelection) {
  643. return;
  644. }
  645. // Don't include ".." (IsParent) in multiselections
  646. this.MultiSelected = toMultiAccept
  647. .Where(s=>!s.IsParent)
  648. .Select (s => s.FileSystemInfo.FullName)
  649. .ToList ().AsReadOnly ();
  650. this.tbPath.Text = this.MultiSelected.Count == 1 ? this.MultiSelected [0] : string.Empty;
  651. FinishAccept ();
  652. }
  653. private void Accept (IFileInfo f)
  654. {
  655. if (!this.IsCompatibleWithOpenMode (f.FullName, out var reason)) {
  656. feedback = reason;
  657. SetNeedsDisplay ();
  658. return;
  659. }
  660. this.tbPath.Text = f.FullName;
  661. if (AllowsMultipleSelection) {
  662. this.MultiSelected = new List<string> { f.FullName }.AsReadOnly ();
  663. }
  664. FinishAccept ();
  665. }
  666. private void Accept (bool allowMulti)
  667. {
  668. if(allowMulti && TryAcceptMulti())
  669. {
  670. return;
  671. }
  672. if (!this.IsCompatibleWithOpenMode (this.tbPath.Text.ToString (), out string reason)) {
  673. if (reason != null) {
  674. feedback = reason;
  675. SetNeedsDisplay ();
  676. }
  677. return;
  678. }
  679. FinishAccept ();
  680. }
  681. private void FinishAccept ()
  682. {
  683. var e = new FilesSelectedEventArgs (this);
  684. this.FilesSelected?.Invoke (this, e);
  685. if (e.Cancel) {
  686. return;
  687. }
  688. // if user uses Path selection mode (e.g. Enter in text box)
  689. // then also copy to MultiSelected
  690. if (AllowsMultipleSelection && (!MultiSelected.Any ())) {
  691. MultiSelected = string.IsNullOrWhiteSpace (Path) ?
  692. Enumerable.Empty<string> ().ToList ().AsReadOnly () :
  693. new List<string> () { Path }.AsReadOnly ();
  694. }
  695. this.Canceled = false;
  696. Application.RequestStop ();
  697. }
  698. private void NavigateIf (KeyEventEventArgs keyEvent, Key isKey, View to)
  699. {
  700. if (!keyEvent.Handled) {
  701. if (NavigateIf (keyEvent.KeyEvent, isKey, to)) {
  702. keyEvent.Handled = true;
  703. }
  704. }
  705. }
  706. private bool NavigateIf (KeyEvent keyEvent, Key isKey, View to)
  707. {
  708. if (keyEvent.Key == isKey) {
  709. to.FocusFirst ();
  710. if (to == tbPath) {
  711. tbPath.MoveEnd ();
  712. }
  713. return true;
  714. }
  715. return false;
  716. }
  717. private void TreeView_SelectionChanged (object sender, SelectionChangedEventArgs<object> e)
  718. {
  719. if (e.NewValue == null) {
  720. return;
  721. }
  722. this.tbPath.Text = FileDialogTreeBuilder.NodeToDirectory (e.NewValue).FullName;
  723. }
  724. private void UpdateNavigationVisibility ()
  725. {
  726. this.btnBack.Visible = this.history.CanBack ();
  727. this.btnForward.Visible = this.history.CanForward ();
  728. this.btnUp.Visible = this.history.CanUp ();
  729. }
  730. private void TableView_SelectedCellChanged (object sender, SelectedCellChangedEventArgs obj)
  731. {
  732. if (!this.tableView.HasFocus || obj.NewRow == -1 || obj.Table.Rows.Count == 0) {
  733. return;
  734. }
  735. if (this.tableView.MultiSelect && this.tableView.MultiSelectedRegions.Any ()) {
  736. return;
  737. }
  738. var stats = this.RowToStats (obj.NewRow);
  739. if (stats == null) {
  740. return;
  741. }
  742. IFileSystemInfo dest;
  743. if (stats.IsParent) {
  744. dest = State.Directory;
  745. } else {
  746. dest = stats.FileSystemInfo;
  747. }
  748. try {
  749. this.pushingState = true;
  750. this.tbPath.Text = dest.FullName;
  751. this.State.Selected = stats;
  752. this.tbPath.Autocomplete.ClearSuggestions ();
  753. } finally {
  754. this.pushingState = false;
  755. }
  756. if (obj.NewCol != obj.OldCol) {
  757. UpdateCollectionNavigator ();
  758. }
  759. }
  760. private bool TableView_KeyUp (KeyEvent keyEvent)
  761. {
  762. if (keyEvent.Key == Key.Backspace) {
  763. return this.history.Back ();
  764. }
  765. if (keyEvent.Key == (Key.ShiftMask | Key.Backspace)) {
  766. return this.history.Forward ();
  767. }
  768. if (keyEvent.Key == Key.DeleteChar) {
  769. Delete ();
  770. return true;
  771. }
  772. if (keyEvent.Key == (Key.CtrlMask | Key.R)) {
  773. Rename ();
  774. return true;
  775. }
  776. if (keyEvent.Key == (Key.CtrlMask | Key.N)) {
  777. New ();
  778. return true;
  779. }
  780. return false;
  781. }
  782. private void SetupTableColumns ()
  783. {
  784. this.dtFiles = new DataTable ();
  785. var nameStyle = this.tableView.Style.GetOrCreateColumnStyle (
  786. filenameColumn = this.dtFiles.Columns.Add (Style.FilenameColumnName, typeof (int))
  787. );
  788. nameStyle.RepresentationGetter = (i) => {
  789. var stats = this.State?.Children [(int)i];
  790. if (stats == null) {
  791. return string.Empty;
  792. }
  793. var icon = stats.IsParent ? null : Style.IconGetter?.Invoke (stats.FileSystemInfo);
  794. if (icon != null) {
  795. return icon + stats.Name;
  796. }
  797. return stats.Name;
  798. };
  799. nameStyle.MinWidth = 50;
  800. var sizeStyle = this.tableView.Style.GetOrCreateColumnStyle (this.dtFiles.Columns.Add (Style.SizeColumnName, typeof (int)));
  801. sizeStyle.RepresentationGetter = (i) => this.State?.Children [(int)i].HumanReadableLength ?? string.Empty;
  802. nameStyle.MinWidth = 10;
  803. var dateModifiedStyle = this.tableView.Style.GetOrCreateColumnStyle (this.dtFiles.Columns.Add (Style.ModifiedColumnName, typeof (int)));
  804. dateModifiedStyle.RepresentationGetter = (i) =>
  805. {
  806. var s = this.State?.Children [(int)i];
  807. if(s == null || s.IsParent || s.LastWriteTime == null)
  808. {
  809. return string.Empty;
  810. }
  811. return s.LastWriteTime.Value.ToString (Style.DateFormat);
  812. };
  813. dateModifiedStyle.MinWidth = 30;
  814. var typeStyle = this.tableView.Style.GetOrCreateColumnStyle (this.dtFiles.Columns.Add (Style.TypeColumnName, typeof (int)));
  815. typeStyle.RepresentationGetter = (i) => this.State?.Children [(int)i].Type ?? string.Empty;
  816. typeStyle.MinWidth = 6;
  817. foreach(var colStyle in Style.TableStyle.ColumnStyles) {
  818. colStyle.Value.ColorGetter = this.ColorGetter;
  819. }
  820. }
  821. private void CellActivate (object sender, CellActivatedEventArgs obj)
  822. {
  823. if(TryAcceptMulti())
  824. {
  825. return;
  826. }
  827. var stats = this.RowToStats (obj.Row);
  828. if (stats.FileSystemInfo is IDirectoryInfo d) {
  829. this.PushState (d, true);
  830. return;
  831. }
  832. if (stats.FileSystemInfo is IFileInfo f) {
  833. this.Accept (f);
  834. }
  835. }
  836. private bool TryAcceptMulti ()
  837. {
  838. var multi = this.MultiRowToStats ();
  839. string reason = null;
  840. if (!multi.Any ())
  841. {
  842. return false;
  843. }
  844. if (multi.All (m => this.IsCompatibleWithOpenMode (
  845. m.FileSystemInfo.FullName, out reason)))
  846. {
  847. this.Accept (multi);
  848. return true;
  849. }
  850. else
  851. {
  852. if (reason != null) {
  853. feedback = reason;
  854. SetNeedsDisplay ();
  855. }
  856. return false;
  857. }
  858. }
  859. /// <summary>
  860. /// Returns true if there are no <see cref="AllowedTypes"/> or one of them agrees
  861. /// that <paramref name="file"/> <see cref="IAllowedType.IsAllowed(string)"/>.
  862. /// </summary>
  863. /// <param name="file"></param>
  864. /// <returns></returns>
  865. public bool IsCompatibleWithAllowedExtensions (IFileInfo file)
  866. {
  867. // no restrictions
  868. if (!this.AllowedTypes.Any ()) {
  869. return true;
  870. }
  871. return this.MatchesAllowedTypes (file);
  872. }
  873. private bool IsCompatibleWithAllowedExtensions (string path)
  874. {
  875. // no restrictions
  876. if (!this.AllowedTypes.Any ()) {
  877. return true;
  878. }
  879. return this.AllowedTypes.Any (t => t.IsAllowed (path));
  880. }
  881. /// <summary>
  882. /// Returns true if any <see cref="AllowedTypes"/> matches <paramref name="file"/>.
  883. /// </summary>
  884. /// <param name="file"></param>
  885. /// <returns></returns>
  886. private bool MatchesAllowedTypes (IFileInfo file)
  887. {
  888. return this.AllowedTypes.Any (t => t.IsAllowed (file.FullName));
  889. }
  890. private bool IsCompatibleWithOpenMode (string s, out string reason)
  891. {
  892. reason = null;
  893. if (string.IsNullOrWhiteSpace (s)) {
  894. return false;
  895. }
  896. if (!this.IsCompatibleWithAllowedExtensions (s)) {
  897. reason = Style.WrongFileTypeFeedback;
  898. return false;
  899. }
  900. switch (this.OpenMode) {
  901. case OpenMode.Directory:
  902. if (MustExist && !Directory.Exists (s)) {
  903. reason = Style.DirectoryMustExistFeedback;
  904. return false;
  905. }
  906. if (File.Exists (s)) {
  907. reason = Style.FileAlreadyExistsFeedback;
  908. return false;
  909. }
  910. return true;
  911. case OpenMode.File:
  912. if (MustExist && !File.Exists (s)) {
  913. reason = Style.FileMustExistFeedback;
  914. return false;
  915. }
  916. if (Directory.Exists (s)) {
  917. reason = Style.DirectoryAlreadyExistsFeedback;
  918. return false;
  919. }
  920. return true;
  921. case OpenMode.Mixed:
  922. if (MustExist && !File.Exists (s) && !Directory.Exists (s)) {
  923. reason = Style.FileOrDirectoryMustExistFeedback;
  924. return false;
  925. }
  926. return true;
  927. default: throw new ArgumentOutOfRangeException (nameof (this.OpenMode));
  928. }
  929. }
  930. /// <summary>
  931. /// Changes the dialog such that <paramref name="d"/> is being explored.
  932. /// </summary>
  933. /// <param name="d"></param>
  934. /// <param name="addCurrentStateToHistory"></param>
  935. /// <param name="setPathText"></param>
  936. /// <param name="clearForward"></param>
  937. /// <param name="pathText">Optional alternate string to set path to.</param>
  938. internal void PushState (IDirectoryInfo d, bool addCurrentStateToHistory, bool setPathText = true, bool clearForward = true, string pathText = null)
  939. {
  940. // no change of state
  941. if (d == this.State?.Directory) {
  942. return;
  943. }
  944. if (d.FullName == this.State?.Directory.FullName) {
  945. return;
  946. }
  947. PushState (new FileDialogState (d, this), addCurrentStateToHistory, setPathText, clearForward, pathText);
  948. }
  949. private void RefreshState ()
  950. {
  951. State.RefreshChildren ();
  952. PushState (State, false, false, false);
  953. }
  954. private void PushState (FileDialogState newState, bool addCurrentStateToHistory, bool setPathText = true, bool clearForward = true, string pathText = null)
  955. {
  956. if (State is SearchState search) {
  957. search.Cancel ();
  958. }
  959. try {
  960. this.pushingState = true;
  961. // push the old state to history
  962. if (addCurrentStateToHistory) {
  963. this.history.Push (this.State, clearForward);
  964. }
  965. this.tbPath.Autocomplete.ClearSuggestions ();
  966. if(pathText != null)
  967. {
  968. this.tbPath.Text = pathText;
  969. this.tbPath.MoveEnd ();
  970. }
  971. else
  972. if (setPathText) {
  973. this.tbPath.Text = newState.Directory.FullName;
  974. this.tbPath.MoveEnd ();
  975. }
  976. this.State = newState;
  977. this.tbPath.Autocomplete.GenerateSuggestions (
  978. new AutocompleteFilepathContext (tbPath.Text, tbPath.CursorPosition, this.State));
  979. this.WriteStateToTableView ();
  980. if (clearForward) {
  981. this.history.ClearForward ();
  982. }
  983. this.tableView.RowOffset = 0;
  984. this.tableView.SelectedRow = 0;
  985. this.SetNeedsDisplay ();
  986. this.UpdateNavigationVisibility ();
  987. } finally {
  988. this.pushingState = false;
  989. }
  990. ClearFeedback ();
  991. }
  992. private void WriteStateToTableView ()
  993. {
  994. if (this.State == null) {
  995. return;
  996. }
  997. this.dtFiles.Rows.Clear ();
  998. for (int i = 0; i < this.State.Children.Length; i++) {
  999. this.BuildRow (i);
  1000. }
  1001. this.sorter.ApplySort ();
  1002. this.tableView.Update ();
  1003. UpdateCollectionNavigator ();
  1004. }
  1005. private void BuildRow (int idx)
  1006. {
  1007. this.tableView.Table.Rows.Add (idx, idx, idx, idx);
  1008. }
  1009. private ColorScheme ColorGetter (TableView.CellColorGetterArgs args)
  1010. {
  1011. var stats = this.RowToStats (args.RowIndex);
  1012. if (!Style.UseColors) {
  1013. return tableView.ColorScheme;
  1014. }
  1015. if (stats.IsDir ()) {
  1016. return Style.ColorSchemeDirectory;
  1017. }
  1018. if (stats.IsImage ()) {
  1019. return Style.ColorSchemeImage;
  1020. }
  1021. if (stats.IsExecutable ()) {
  1022. return Style.ColorSchemeExeOrRecommended;
  1023. }
  1024. if (stats.FileSystemInfo is IFileInfo f && this.MatchesAllowedTypes (f)) {
  1025. return Style.ColorSchemeExeOrRecommended;
  1026. }
  1027. return Style.ColorSchemeOther;
  1028. }
  1029. /// <summary>
  1030. /// If <see cref="TableView.MultiSelect"/> is this returns a union of all
  1031. /// <see cref="FileSystemInfoStats"/> in the selection.
  1032. /// </summary>
  1033. /// <returns></returns>
  1034. private IEnumerable<FileSystemInfoStats> MultiRowToStats ()
  1035. {
  1036. var toReturn = new HashSet<FileSystemInfoStats> ();
  1037. if (this.AllowsMultipleSelection && this.tableView.MultiSelectedRegions.Any ()) {
  1038. foreach (var p in this.tableView.GetAllSelectedCells ()) {
  1039. var add = this.State?.Children [(int)this.tableView.Table.Rows [p.Y] [0]];
  1040. if (add != null) {
  1041. toReturn.Add (add);
  1042. }
  1043. }
  1044. }
  1045. return toReturn;
  1046. }
  1047. private FileSystemInfoStats RowToStats (int rowIndex)
  1048. {
  1049. return this.State?.Children [(int)this.tableView.Table.Rows [rowIndex] [0]];
  1050. }
  1051. private int? StatsToRow (IFileSystemInfo fileSystemInfo)
  1052. {
  1053. // find array index of the current state for the stats
  1054. var idx = State?.Children.IndexOf ((f) => f.FileSystemInfo.FullName == fileSystemInfo.FullName);
  1055. if (idx != -1 && idx != null) {
  1056. // find the row number in our DataTable where the cell
  1057. // contains idx
  1058. var match = tableView.Table.Rows
  1059. .Cast<DataRow> ()
  1060. .Select ((r, rIdx) => new { row = r, rowIdx = rIdx })
  1061. .Where (t => (int)t.row [0] == idx)
  1062. .ToArray ();
  1063. if (match.Length == 1) {
  1064. return match [0].rowIdx;
  1065. }
  1066. }
  1067. return null;
  1068. }
  1069. private void PathChanged ()
  1070. {
  1071. // avoid re-entry
  1072. if (this.pushingState) {
  1073. return;
  1074. }
  1075. var path = this.tbPath.Text?.ToString ();
  1076. if (string.IsNullOrWhiteSpace (path)) {
  1077. return;
  1078. }
  1079. var dir = this.StringToDirectoryInfo (path);
  1080. if (dir.Exists) {
  1081. this.PushState (dir, true, false);
  1082. } else
  1083. if (dir.Parent?.Exists ?? false) {
  1084. this.PushState (dir.Parent, true, false);
  1085. }
  1086. tbPath.Autocomplete.GenerateSuggestions (new AutocompleteFilepathContext (tbPath.Text, tbPath.CursorPosition, State));
  1087. }
  1088. private IDirectoryInfo StringToDirectoryInfo (string path)
  1089. {
  1090. // if you pass new DirectoryInfo("C:") you get a weird object
  1091. // where the FullName is in fact the current working directory.
  1092. // really not what most users would expect
  1093. if (Regex.IsMatch (path, "^\\w:$")) {
  1094. return fileSystem.DirectoryInfo.New(path + System.IO.Path.DirectorySeparatorChar);
  1095. }
  1096. return fileSystem.DirectoryInfo.New(path);
  1097. }
  1098. /// <summary>
  1099. /// Select <paramref name="toRestore"/> in the table view (if present)
  1100. /// </summary>
  1101. /// <param name="toRestore"></param>
  1102. internal void RestoreSelection (IFileSystemInfo toRestore)
  1103. {
  1104. var toReselect = StatsToRow (toRestore);
  1105. if (toReselect.HasValue) {
  1106. tableView.SelectedRow = toReselect.Value;
  1107. tableView.EnsureSelectedCellIsVisible ();
  1108. }
  1109. }
  1110. private class FileDialogSorter {
  1111. private readonly FileDialog dlg;
  1112. private TableView tableView;
  1113. private DataColumn currentSort = null;
  1114. private bool currentSortIsAsc = true;
  1115. public FileDialogSorter (FileDialog dlg, TableView tableView)
  1116. {
  1117. this.dlg = dlg;
  1118. this.tableView = tableView;
  1119. // if user clicks the mouse in TableView
  1120. this.tableView.MouseClick += (s, e) => {
  1121. var clickedCell = this.tableView.ScreenToCell (e.MouseEvent.X, e.MouseEvent.Y, out DataColumn clickedCol);
  1122. if (clickedCol != null) {
  1123. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  1124. // left click in a header
  1125. this.SortColumn (clickedCol);
  1126. } else if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) {
  1127. // right click in a header
  1128. this.ShowHeaderContextMenu (clickedCol, e);
  1129. }
  1130. } else {
  1131. if (clickedCell != null && e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) {
  1132. // right click in rest of table
  1133. this.ShowCellContextMenu (clickedCell, e);
  1134. }
  1135. }
  1136. };
  1137. }
  1138. internal void ApplySort ()
  1139. {
  1140. var col = this.currentSort;
  1141. // TODO: Consider preserving selection
  1142. this.tableView.Table.Rows.Clear ();
  1143. var colName = col == null ? null : StripArrows (col.ColumnName);
  1144. var stats = this.dlg.State?.Children ?? new FileSystemInfoStats [0];
  1145. // Do we sort on a column or just use the default sort order?
  1146. Func<FileSystemInfoStats, object> sortAlgorithm;
  1147. if (colName == null) {
  1148. sortAlgorithm = (v) => v.GetOrderByDefault ();
  1149. this.currentSortIsAsc = true;
  1150. } else {
  1151. sortAlgorithm = (v) => v.GetOrderByValue (dlg, colName);
  1152. }
  1153. // This portion is never reordered (aways .. at top then folders)
  1154. var forcedOrder = stats.Select ((v, i) => new { v, i })
  1155. .OrderByDescending (f => f.v.IsParent)
  1156. .ThenBy (f => f.v.IsDir() ? -1:100);
  1157. // This portion is flexible based on the column clicked (e.g. alphabetical)
  1158. var ordered =
  1159. this.currentSortIsAsc ?
  1160. forcedOrder.ThenBy (f => sortAlgorithm (f.v)):
  1161. forcedOrder.ThenByDescending (f => sortAlgorithm (f.v));
  1162. foreach (var o in ordered) {
  1163. this.dlg.BuildRow (o.i);
  1164. }
  1165. foreach (DataColumn c in this.tableView.Table.Columns) {
  1166. // remove any lingering sort indicator
  1167. c.ColumnName = StripArrows (c.ColumnName);
  1168. // add a new one if this the one that is being sorted
  1169. if (c == col) {
  1170. c.ColumnName += this.currentSortIsAsc ? " (▲)" : " (▼)";
  1171. }
  1172. }
  1173. this.tableView.Update ();
  1174. dlg.UpdateCollectionNavigator ();
  1175. }
  1176. private static string StripArrows (string columnName)
  1177. {
  1178. return columnName.Replace (" (▼)", string.Empty).Replace (" (▲)", string.Empty);
  1179. }
  1180. private void SortColumn (DataColumn clickedCol)
  1181. {
  1182. this.GetProposedNewSortOrder (clickedCol, out var isAsc);
  1183. this.SortColumn (clickedCol, isAsc);
  1184. }
  1185. internal void SortColumn (DataColumn col, bool isAsc)
  1186. {
  1187. // set a sort order
  1188. this.currentSort = col;
  1189. this.currentSortIsAsc = isAsc;
  1190. this.ApplySort ();
  1191. }
  1192. private string GetProposedNewSortOrder (DataColumn clickedCol, out bool isAsc)
  1193. {
  1194. // work out new sort order
  1195. if (this.currentSort == clickedCol && this.currentSortIsAsc) {
  1196. isAsc = false;
  1197. return $"{clickedCol.ColumnName} DESC";
  1198. } else {
  1199. isAsc = true;
  1200. return $"{clickedCol.ColumnName} ASC";
  1201. }
  1202. }
  1203. private void ShowHeaderContextMenu (DataColumn clickedCol, MouseEventEventArgs e)
  1204. {
  1205. var sort = this.GetProposedNewSortOrder (clickedCol, out var isAsc);
  1206. var contextMenu = new ContextMenu (
  1207. e.MouseEvent.X + 1,
  1208. e.MouseEvent.Y + 1,
  1209. new MenuBarItem (new MenuItem []
  1210. {
  1211. new MenuItem($"Hide {StripArrows(clickedCol.ColumnName)}", string.Empty, () => this.HideColumn(clickedCol)),
  1212. new MenuItem($"Sort {StripArrows(sort)}",string.Empty, ()=> this.SortColumn(clickedCol,isAsc)),
  1213. })
  1214. );
  1215. contextMenu.Show ();
  1216. }
  1217. private void ShowCellContextMenu (Point? clickedCell, MouseEventEventArgs e)
  1218. {
  1219. if (clickedCell == null) {
  1220. return;
  1221. }
  1222. var contextMenu = new ContextMenu (
  1223. e.MouseEvent.X + 1,
  1224. e.MouseEvent.Y + 1,
  1225. new MenuBarItem (new MenuItem []
  1226. {
  1227. new MenuItem($"New", string.Empty, () => dlg.New()),
  1228. new MenuItem($"Rename",string.Empty, ()=> dlg.Rename()),
  1229. new MenuItem($"Delete",string.Empty, ()=> dlg.Delete()),
  1230. })
  1231. );
  1232. dlg.tableView.SetSelection (clickedCell.Value.X, clickedCell.Value.Y, false);
  1233. contextMenu.Show ();
  1234. }
  1235. private void HideColumn (DataColumn clickedCol)
  1236. {
  1237. var style = this.tableView.Style.GetOrCreateColumnStyle (clickedCol);
  1238. style.Visible = false;
  1239. this.tableView.Update ();
  1240. }
  1241. }
  1242. /// <summary>
  1243. /// State representing a recursive search from <see cref="FileDialogState.Directory"/>
  1244. /// downwards.
  1245. /// </summary>
  1246. internal class SearchState : FileDialogState {
  1247. bool cancel = false;
  1248. bool finished = false;
  1249. // TODO: Add thread safe child adding
  1250. List<FileSystemInfoStats> found = new List<FileSystemInfoStats> ();
  1251. object oLockFound = new object ();
  1252. CancellationTokenSource token = new CancellationTokenSource ();
  1253. public SearchState (IDirectoryInfo dir, FileDialog parent, string searchTerms) : base (dir, parent)
  1254. {
  1255. parent.SearchMatcher.Initialize (searchTerms);
  1256. Children = new FileSystemInfoStats [0];
  1257. BeginSearch ();
  1258. }
  1259. private void BeginSearch ()
  1260. {
  1261. Task.Run (() => {
  1262. RecursiveFind (Directory);
  1263. finished = true;
  1264. });
  1265. Task.Run (() => {
  1266. UpdateChildren ();
  1267. });
  1268. }
  1269. private void UpdateChildren ()
  1270. {
  1271. lock (Parent.onlyOneSearchLock) {
  1272. while (!cancel && !finished) {
  1273. try {
  1274. Task.Delay (250).Wait (token.Token);
  1275. } catch (OperationCanceledException) {
  1276. cancel = true;
  1277. }
  1278. if (cancel || finished) {
  1279. break;
  1280. }
  1281. UpdateChildrenToFound ();
  1282. }
  1283. if (finished && !cancel) {
  1284. UpdateChildrenToFound ();
  1285. }
  1286. Application.MainLoop.Invoke (() => {
  1287. Parent.spinnerView.Visible = false;
  1288. });
  1289. }
  1290. }
  1291. private void UpdateChildrenToFound ()
  1292. {
  1293. lock (oLockFound) {
  1294. Children = found.ToArray ();
  1295. }
  1296. Application.MainLoop.Invoke (() => {
  1297. Parent.tbPath.Autocomplete.GenerateSuggestions (
  1298. new AutocompleteFilepathContext (Parent.tbPath.Text, Parent.tbPath.CursorPosition, this)
  1299. );
  1300. Parent.WriteStateToTableView ();
  1301. Parent.spinnerView.Visible = true;
  1302. Parent.spinnerView.SetNeedsDisplay ();
  1303. });
  1304. }
  1305. private void RecursiveFind (IDirectoryInfo directory)
  1306. {
  1307. foreach (var f in GetChildren (directory)) {
  1308. if (cancel) {
  1309. return;
  1310. }
  1311. if (f.IsParent) {
  1312. continue;
  1313. }
  1314. lock (oLockFound) {
  1315. if (found.Count >= FileDialog.MaxSearchResults) {
  1316. finished = true;
  1317. return;
  1318. }
  1319. }
  1320. if (Parent.SearchMatcher.IsMatch (f.FileSystemInfo)) {
  1321. lock (oLockFound) {
  1322. found.Add (f);
  1323. }
  1324. }
  1325. if (f.FileSystemInfo is IDirectoryInfo sub) {
  1326. RecursiveFind (sub);
  1327. }
  1328. }
  1329. }
  1330. internal override void RefreshChildren ()
  1331. {
  1332. }
  1333. /// <summary>
  1334. /// Cancels the current search (if any). Returns true if a search
  1335. /// was running and cancellation was successfully set.
  1336. /// </summary>
  1337. /// <returns></returns>
  1338. internal bool Cancel ()
  1339. {
  1340. var alreadyCancelled = token.IsCancellationRequested || cancel;
  1341. cancel = true;
  1342. token.Cancel ();
  1343. return !alreadyCancelled;
  1344. }
  1345. }
  1346. }
  1347. }