FileDialog.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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. 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. this.Accept ();
  635. }
  636. }
  637. private void Accept (IEnumerable<FileSystemInfoStats> toMultiAccept)
  638. {
  639. if (!this.AllowsMultipleSelection) {
  640. return;
  641. }
  642. this.MultiSelected = toMultiAccept.Select (s => s.FileSystemInfo.FullName).ToList ().AsReadOnly ();
  643. this.tbPath.Text = this.MultiSelected.Count == 1 ? this.MultiSelected [0] : string.Empty;
  644. FinishAccept ();
  645. }
  646. private void Accept (IFileInfo f)
  647. {
  648. if (!this.IsCompatibleWithOpenMode (f.FullName, out var reason)) {
  649. feedback = reason;
  650. SetNeedsDisplay ();
  651. return;
  652. }
  653. this.tbPath.Text = f.FullName;
  654. if (AllowsMultipleSelection) {
  655. this.MultiSelected = new List<string> { f.FullName }.AsReadOnly ();
  656. }
  657. FinishAccept ();
  658. }
  659. private void Accept ()
  660. {
  661. if (!this.IsCompatibleWithOpenMode (this.tbPath.Text.ToString (), out string reason)) {
  662. if (reason != null) {
  663. feedback = reason;
  664. SetNeedsDisplay ();
  665. }
  666. return;
  667. }
  668. FinishAccept ();
  669. }
  670. private void FinishAccept ()
  671. {
  672. var e = new FilesSelectedEventArgs (this);
  673. this.FilesSelected?.Invoke (this, e);
  674. if (e.Cancel) {
  675. return;
  676. }
  677. // if user uses Path selection mode (e.g. Enter in text box)
  678. // then also copy to MultiSelected
  679. if (AllowsMultipleSelection && (!MultiSelected.Any ())) {
  680. MultiSelected = string.IsNullOrWhiteSpace (Path) ?
  681. Enumerable.Empty<string> ().ToList ().AsReadOnly () :
  682. new List<string> () { Path }.AsReadOnly ();
  683. }
  684. this.Canceled = false;
  685. Application.RequestStop ();
  686. }
  687. private void NavigateIf (KeyEventEventArgs keyEvent, Key isKey, View to)
  688. {
  689. if (!keyEvent.Handled) {
  690. if (NavigateIf (keyEvent.KeyEvent, isKey, to)) {
  691. keyEvent.Handled = true;
  692. }
  693. }
  694. }
  695. private bool NavigateIf (KeyEvent keyEvent, Key isKey, View to)
  696. {
  697. if (keyEvent.Key == isKey) {
  698. to.FocusFirst ();
  699. if (to == tbPath) {
  700. tbPath.MoveEnd ();
  701. }
  702. return true;
  703. }
  704. return false;
  705. }
  706. private void TreeView_SelectionChanged (object sender, SelectionChangedEventArgs<object> e)
  707. {
  708. if (e.NewValue == null) {
  709. return;
  710. }
  711. this.tbPath.Text = FileDialogTreeBuilder.NodeToDirectory (e.NewValue).FullName;
  712. }
  713. private void UpdateNavigationVisibility ()
  714. {
  715. this.btnBack.Visible = this.history.CanBack ();
  716. this.btnForward.Visible = this.history.CanForward ();
  717. this.btnUp.Visible = this.history.CanUp ();
  718. }
  719. private void TableView_SelectedCellChanged (object sender, SelectedCellChangedEventArgs obj)
  720. {
  721. if (!this.tableView.HasFocus || obj.NewRow == -1 || obj.Table.Rows.Count == 0) {
  722. return;
  723. }
  724. if (this.tableView.MultiSelect && this.tableView.MultiSelectedRegions.Any ()) {
  725. return;
  726. }
  727. var stats = this.RowToStats (obj.NewRow);
  728. if (stats == null) {
  729. return;
  730. }
  731. IFileSystemInfo dest;
  732. if (stats.IsParent) {
  733. dest = State.Directory;
  734. } else {
  735. dest = stats.FileSystemInfo;
  736. }
  737. try {
  738. this.pushingState = true;
  739. this.tbPath.Text = dest.FullName;
  740. this.State.Selected = stats;
  741. this.tbPath.Autocomplete.ClearSuggestions ();
  742. } finally {
  743. this.pushingState = false;
  744. }
  745. if (obj.NewCol != obj.OldCol) {
  746. UpdateCollectionNavigator ();
  747. }
  748. }
  749. private bool TableView_KeyUp (KeyEvent keyEvent)
  750. {
  751. if (keyEvent.Key == Key.Backspace) {
  752. return this.history.Back ();
  753. }
  754. if (keyEvent.Key == (Key.ShiftMask | Key.Backspace)) {
  755. return this.history.Forward ();
  756. }
  757. if (keyEvent.Key == Key.DeleteChar) {
  758. Delete ();
  759. return true;
  760. }
  761. if (keyEvent.Key == (Key.CtrlMask | Key.R)) {
  762. Rename ();
  763. return true;
  764. }
  765. if (keyEvent.Key == (Key.CtrlMask | Key.N)) {
  766. New ();
  767. return true;
  768. }
  769. return false;
  770. }
  771. private void SetupTableColumns ()
  772. {
  773. this.dtFiles = new DataTable ();
  774. var nameStyle = this.tableView.Style.GetOrCreateColumnStyle (
  775. filenameColumn = this.dtFiles.Columns.Add (Style.FilenameColumnName, typeof (int))
  776. );
  777. nameStyle.RepresentationGetter = (i) => {
  778. var stats = this.State?.Children [(int)i];
  779. if (stats == null) {
  780. return string.Empty;
  781. }
  782. var icon = stats.IsParent ? null : Style.IconGetter?.Invoke (stats.FileSystemInfo);
  783. if (icon != null) {
  784. return icon + stats.Name;
  785. }
  786. return stats.Name;
  787. };
  788. nameStyle.MinWidth = 50;
  789. var sizeStyle = this.tableView.Style.GetOrCreateColumnStyle (this.dtFiles.Columns.Add (Style.SizeColumnName, typeof (int)));
  790. sizeStyle.RepresentationGetter = (i) => this.State?.Children [(int)i].HumanReadableLength ?? string.Empty;
  791. nameStyle.MinWidth = 10;
  792. var dateModifiedStyle = this.tableView.Style.GetOrCreateColumnStyle (this.dtFiles.Columns.Add (Style.ModifiedColumnName, typeof (int)));
  793. dateModifiedStyle.RepresentationGetter = (i) =>
  794. {
  795. var s = this.State?.Children [(int)i];
  796. if(s == null || s.IsParent || s.LastWriteTime == null)
  797. {
  798. return string.Empty;
  799. }
  800. return s.LastWriteTime.Value.ToString (Style.DateFormat);
  801. };
  802. dateModifiedStyle.MinWidth = 30;
  803. var typeStyle = this.tableView.Style.GetOrCreateColumnStyle (this.dtFiles.Columns.Add (Style.TypeColumnName, typeof (int)));
  804. typeStyle.RepresentationGetter = (i) => this.State?.Children [(int)i].Type ?? string.Empty;
  805. typeStyle.MinWidth = 6;
  806. foreach(var colStyle in Style.TableStyle.ColumnStyles) {
  807. colStyle.Value.ColorGetter = this.ColorGetter;
  808. }
  809. }
  810. private void CellActivate (object sender, CellActivatedEventArgs obj)
  811. {
  812. var multi = this.MultiRowToStats ();
  813. string reason = null;
  814. if (multi.Any ()) {
  815. if (multi.All (m => this.IsCompatibleWithOpenMode (m.FileSystemInfo.FullName, out reason))) {
  816. this.Accept (multi);
  817. return;
  818. } else {
  819. if (reason != null) {
  820. feedback = reason;
  821. SetNeedsDisplay ();
  822. }
  823. return;
  824. }
  825. }
  826. var stats = this.RowToStats (obj.Row);
  827. if (stats.FileSystemInfo is IDirectoryInfo d) {
  828. this.PushState (d, true);
  829. return;
  830. }
  831. if (stats.FileSystemInfo is IFileInfo f) {
  832. this.Accept (f);
  833. }
  834. }
  835. /// <summary>
  836. /// Returns true if there are no <see cref="AllowedTypes"/> or one of them agrees
  837. /// that <paramref name="file"/> <see cref="IAllowedType.IsAllowed(string)"/>.
  838. /// </summary>
  839. /// <param name="file"></param>
  840. /// <returns></returns>
  841. public bool IsCompatibleWithAllowedExtensions (IFileInfo file)
  842. {
  843. // no restrictions
  844. if (!this.AllowedTypes.Any ()) {
  845. return true;
  846. }
  847. return this.MatchesAllowedTypes (file);
  848. }
  849. private bool IsCompatibleWithAllowedExtensions (string path)
  850. {
  851. // no restrictions
  852. if (!this.AllowedTypes.Any ()) {
  853. return true;
  854. }
  855. return this.AllowedTypes.Any (t => t.IsAllowed (path));
  856. }
  857. /// <summary>
  858. /// Returns true if any <see cref="AllowedTypes"/> matches <paramref name="file"/>.
  859. /// </summary>
  860. /// <param name="file"></param>
  861. /// <returns></returns>
  862. private bool MatchesAllowedTypes (IFileInfo file)
  863. {
  864. return this.AllowedTypes.Any (t => t.IsAllowed (file.FullName));
  865. }
  866. private bool IsCompatibleWithOpenMode (string s, out string reason)
  867. {
  868. reason = null;
  869. if (string.IsNullOrWhiteSpace (s)) {
  870. return false;
  871. }
  872. if (!this.IsCompatibleWithAllowedExtensions (s)) {
  873. reason = Style.WrongFileTypeFeedback;
  874. return false;
  875. }
  876. switch (this.OpenMode) {
  877. case OpenMode.Directory:
  878. if (MustExist && !Directory.Exists (s)) {
  879. reason = Style.DirectoryMustExistFeedback;
  880. return false;
  881. }
  882. if (File.Exists (s)) {
  883. reason = Style.FileAlreadyExistsFeedback;
  884. return false;
  885. }
  886. return true;
  887. case OpenMode.File:
  888. if (MustExist && !File.Exists (s)) {
  889. reason = Style.FileMustExistFeedback;
  890. return false;
  891. }
  892. if (Directory.Exists (s)) {
  893. reason = Style.DirectoryAlreadyExistsFeedback;
  894. return false;
  895. }
  896. return true;
  897. case OpenMode.Mixed:
  898. if (MustExist && !File.Exists (s) && !Directory.Exists (s)) {
  899. reason = Style.FileOrDirectoryMustExistFeedback;
  900. return false;
  901. }
  902. return true;
  903. default: throw new ArgumentOutOfRangeException (nameof (this.OpenMode));
  904. }
  905. }
  906. /// <summary>
  907. /// Changes the dialog such that <paramref name="d"/> is being explored.
  908. /// </summary>
  909. /// <param name="d"></param>
  910. /// <param name="addCurrentStateToHistory"></param>
  911. /// <param name="setPathText"></param>
  912. /// <param name="clearForward"></param>
  913. internal void PushState (IDirectoryInfo d, bool addCurrentStateToHistory, bool setPathText = true, bool clearForward = true)
  914. {
  915. // no change of state
  916. if (d == this.State?.Directory) {
  917. return;
  918. }
  919. if (d.FullName == this.State?.Directory.FullName) {
  920. return;
  921. }
  922. PushState (new FileDialogState (d, this), addCurrentStateToHistory, setPathText, clearForward);
  923. }
  924. private void RefreshState ()
  925. {
  926. State.RefreshChildren ();
  927. PushState (State, false, false, false);
  928. }
  929. private void PushState (FileDialogState newState, bool addCurrentStateToHistory, bool setPathText = true, bool clearForward = true)
  930. {
  931. if (State is SearchState search) {
  932. search.Cancel ();
  933. }
  934. try {
  935. this.pushingState = true;
  936. // push the old state to history
  937. if (addCurrentStateToHistory) {
  938. this.history.Push (this.State, clearForward);
  939. }
  940. this.tbPath.Autocomplete.ClearSuggestions ();
  941. if (setPathText) {
  942. this.tbPath.Text = newState.Directory.FullName;
  943. this.tbPath.MoveEnd ();
  944. }
  945. this.State = newState;
  946. this.tbPath.Autocomplete.GenerateSuggestions (
  947. new AutocompleteFilepathContext (tbPath.Text, tbPath.CursorPosition, this.State));
  948. this.WriteStateToTableView ();
  949. if (clearForward) {
  950. this.history.ClearForward ();
  951. }
  952. this.tableView.RowOffset = 0;
  953. this.tableView.SelectedRow = 0;
  954. this.SetNeedsDisplay ();
  955. this.UpdateNavigationVisibility ();
  956. } finally {
  957. this.pushingState = false;
  958. }
  959. ClearFeedback ();
  960. }
  961. private void WriteStateToTableView ()
  962. {
  963. if (this.State == null) {
  964. return;
  965. }
  966. this.dtFiles.Rows.Clear ();
  967. for (int i = 0; i < this.State.Children.Length; i++) {
  968. this.BuildRow (i);
  969. }
  970. this.sorter.ApplySort ();
  971. this.tableView.Update ();
  972. UpdateCollectionNavigator ();
  973. }
  974. private void BuildRow (int idx)
  975. {
  976. this.tableView.Table.Rows.Add (idx, idx, idx, idx);
  977. }
  978. private ColorScheme ColorGetter (TableView.CellColorGetterArgs args)
  979. {
  980. var stats = this.RowToStats (args.RowIndex);
  981. if (!Style.UseColors) {
  982. return tableView.ColorScheme;
  983. }
  984. if (stats.IsDir ()) {
  985. return Style.ColorSchemeDirectory;
  986. }
  987. if (stats.IsImage ()) {
  988. return Style.ColorSchemeImage;
  989. }
  990. if (stats.IsExecutable ()) {
  991. return Style.ColorSchemeExeOrRecommended;
  992. }
  993. if (stats.FileSystemInfo is IFileInfo f && this.MatchesAllowedTypes (f)) {
  994. return Style.ColorSchemeExeOrRecommended;
  995. }
  996. return Style.ColorSchemeOther;
  997. }
  998. /// <summary>
  999. /// If <see cref="TableView.MultiSelect"/> is on and multiple rows are selected
  1000. /// this returns a union of all <see cref="FileSystemInfoStats"/> in the selection.
  1001. /// </summary>
  1002. /// <remarks>Returns an empty collection if there are not at least 2 rows in the selection</remarks>
  1003. /// <returns></returns>
  1004. private IEnumerable<FileSystemInfoStats> MultiRowToStats ()
  1005. {
  1006. var toReturn = new HashSet<FileSystemInfoStats> ();
  1007. if (this.AllowsMultipleSelection && this.tableView.MultiSelectedRegions.Any ()) {
  1008. foreach (var p in this.tableView.GetAllSelectedCells ()) {
  1009. var add = this.State?.Children [(int)this.tableView.Table.Rows [p.Y] [0]];
  1010. if (add != null) {
  1011. toReturn.Add (add);
  1012. }
  1013. }
  1014. }
  1015. return toReturn.Count > 1 ? toReturn : Enumerable.Empty<FileSystemInfoStats> ();
  1016. }
  1017. private FileSystemInfoStats RowToStats (int rowIndex)
  1018. {
  1019. return this.State?.Children [(int)this.tableView.Table.Rows [rowIndex] [0]];
  1020. }
  1021. private int? StatsToRow (IFileSystemInfo fileSystemInfo)
  1022. {
  1023. // find array index of the current state for the stats
  1024. var idx = State?.Children.IndexOf ((f) => f.FileSystemInfo.FullName == fileSystemInfo.FullName);
  1025. if (idx != -1 && idx != null) {
  1026. // find the row number in our DataTable where the cell
  1027. // contains idx
  1028. var match = tableView.Table.Rows
  1029. .Cast<DataRow> ()
  1030. .Select ((r, rIdx) => new { row = r, rowIdx = rIdx })
  1031. .Where (t => (int)t.row [0] == idx)
  1032. .ToArray ();
  1033. if (match.Length == 1) {
  1034. return match [0].rowIdx;
  1035. }
  1036. }
  1037. return null;
  1038. }
  1039. private void PathChanged ()
  1040. {
  1041. // avoid re-entry
  1042. if (this.pushingState) {
  1043. return;
  1044. }
  1045. var path = this.tbPath.Text?.ToString ();
  1046. if (string.IsNullOrWhiteSpace (path)) {
  1047. return;
  1048. }
  1049. var dir = this.StringToDirectoryInfo (path);
  1050. if (dir.Exists) {
  1051. this.PushState (dir, true, false);
  1052. } else
  1053. if (dir.Parent?.Exists ?? false) {
  1054. this.PushState (dir.Parent, true, false);
  1055. }
  1056. tbPath.Autocomplete.GenerateSuggestions (new AutocompleteFilepathContext (tbPath.Text, tbPath.CursorPosition, State));
  1057. }
  1058. private IDirectoryInfo StringToDirectoryInfo (string path)
  1059. {
  1060. // if you pass new DirectoryInfo("C:") you get a weird object
  1061. // where the FullName is in fact the current working directory.
  1062. // really not what most users would expect
  1063. if (Regex.IsMatch (path, "^\\w:$")) {
  1064. return fileSystem.DirectoryInfo.New(path + System.IO.Path.DirectorySeparatorChar);
  1065. }
  1066. return fileSystem.DirectoryInfo.New(path);
  1067. }
  1068. /// <summary>
  1069. /// Select <paramref name="toRestore"/> in the table view (if present)
  1070. /// </summary>
  1071. /// <param name="toRestore"></param>
  1072. internal void RestoreSelection (IFileSystemInfo toRestore)
  1073. {
  1074. var toReselect = StatsToRow (toRestore);
  1075. if (toReselect.HasValue) {
  1076. tableView.SelectedRow = toReselect.Value;
  1077. tableView.EnsureSelectedCellIsVisible ();
  1078. }
  1079. }
  1080. private class FileDialogSorter {
  1081. private readonly FileDialog dlg;
  1082. private TableView tableView;
  1083. private DataColumn currentSort = null;
  1084. private bool currentSortIsAsc = true;
  1085. public FileDialogSorter (FileDialog dlg, TableView tableView)
  1086. {
  1087. this.dlg = dlg;
  1088. this.tableView = tableView;
  1089. // if user clicks the mouse in TableView
  1090. this.tableView.MouseClick += (s, e) => {
  1091. var clickedCell = this.tableView.ScreenToCell (e.MouseEvent.X, e.MouseEvent.Y, out DataColumn clickedCol);
  1092. if (clickedCol != null) {
  1093. if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  1094. // left click in a header
  1095. this.SortColumn (clickedCol);
  1096. } else if (e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) {
  1097. // right click in a header
  1098. this.ShowHeaderContextMenu (clickedCol, e);
  1099. }
  1100. } else {
  1101. if (clickedCell != null && e.MouseEvent.Flags.HasFlag (MouseFlags.Button3Clicked)) {
  1102. // right click in rest of table
  1103. this.ShowCellContextMenu (clickedCell, e);
  1104. }
  1105. }
  1106. };
  1107. }
  1108. internal void ApplySort ()
  1109. {
  1110. var col = this.currentSort;
  1111. // TODO: Consider preserving selection
  1112. this.tableView.Table.Rows.Clear ();
  1113. var colName = col == null ? null : StripArrows (col.ColumnName);
  1114. var stats = this.dlg.State?.Children ?? new FileSystemInfoStats [0];
  1115. // Do we sort on a column or just use the default sort order?
  1116. Func<FileSystemInfoStats, object> sortAlgorithm;
  1117. if (colName == null) {
  1118. sortAlgorithm = (v) => v.GetOrderByDefault ();
  1119. this.currentSortIsAsc = true;
  1120. } else {
  1121. sortAlgorithm = (v) => v.GetOrderByValue (dlg, colName);
  1122. }
  1123. // This portion is never reordered (aways .. at top then folders)
  1124. var forcedOrder = stats.Select ((v, i) => new { v, i })
  1125. .OrderByDescending (f => f.v.IsParent)
  1126. .ThenBy (f => f.v.IsDir() ? -1:100);
  1127. // This portion is flexible based on the column clicked (e.g. alphabetical)
  1128. var ordered =
  1129. this.currentSortIsAsc ?
  1130. forcedOrder.ThenBy (f => sortAlgorithm (f.v)):
  1131. forcedOrder.ThenByDescending (f => sortAlgorithm (f.v));
  1132. foreach (var o in ordered) {
  1133. this.dlg.BuildRow (o.i);
  1134. }
  1135. foreach (DataColumn c in this.tableView.Table.Columns) {
  1136. // remove any lingering sort indicator
  1137. c.ColumnName = StripArrows (c.ColumnName);
  1138. // add a new one if this the one that is being sorted
  1139. if (c == col) {
  1140. c.ColumnName += this.currentSortIsAsc ? " (▲)" : " (▼)";
  1141. }
  1142. }
  1143. this.tableView.Update ();
  1144. dlg.UpdateCollectionNavigator ();
  1145. }
  1146. private static string StripArrows (string columnName)
  1147. {
  1148. return columnName.Replace (" (▼)", string.Empty).Replace (" (▲)", string.Empty);
  1149. }
  1150. private void SortColumn (DataColumn clickedCol)
  1151. {
  1152. this.GetProposedNewSortOrder (clickedCol, out var isAsc);
  1153. this.SortColumn (clickedCol, isAsc);
  1154. }
  1155. internal void SortColumn (DataColumn col, bool isAsc)
  1156. {
  1157. // set a sort order
  1158. this.currentSort = col;
  1159. this.currentSortIsAsc = isAsc;
  1160. this.ApplySort ();
  1161. }
  1162. private string GetProposedNewSortOrder (DataColumn clickedCol, out bool isAsc)
  1163. {
  1164. // work out new sort order
  1165. if (this.currentSort == clickedCol && this.currentSortIsAsc) {
  1166. isAsc = false;
  1167. return $"{clickedCol.ColumnName} DESC";
  1168. } else {
  1169. isAsc = true;
  1170. return $"{clickedCol.ColumnName} ASC";
  1171. }
  1172. }
  1173. private void ShowHeaderContextMenu (DataColumn clickedCol, MouseEventEventArgs e)
  1174. {
  1175. var sort = this.GetProposedNewSortOrder (clickedCol, out var isAsc);
  1176. var contextMenu = new ContextMenu (
  1177. e.MouseEvent.X + 1,
  1178. e.MouseEvent.Y + 1,
  1179. new MenuBarItem (new MenuItem []
  1180. {
  1181. new MenuItem($"Hide {StripArrows(clickedCol.ColumnName)}", string.Empty, () => this.HideColumn(clickedCol)),
  1182. new MenuItem($"Sort {StripArrows(sort)}",string.Empty, ()=> this.SortColumn(clickedCol,isAsc)),
  1183. })
  1184. );
  1185. contextMenu.Show ();
  1186. }
  1187. private void ShowCellContextMenu (Point? clickedCell, MouseEventEventArgs e)
  1188. {
  1189. if (clickedCell == null) {
  1190. return;
  1191. }
  1192. var contextMenu = new ContextMenu (
  1193. e.MouseEvent.X + 1,
  1194. e.MouseEvent.Y + 1,
  1195. new MenuBarItem (new MenuItem []
  1196. {
  1197. new MenuItem($"New", string.Empty, () => dlg.New()),
  1198. new MenuItem($"Rename",string.Empty, ()=> dlg.Rename()),
  1199. new MenuItem($"Delete",string.Empty, ()=> dlg.Delete()),
  1200. })
  1201. );
  1202. dlg.tableView.SetSelection (clickedCell.Value.X, clickedCell.Value.Y, false);
  1203. contextMenu.Show ();
  1204. }
  1205. private void HideColumn (DataColumn clickedCol)
  1206. {
  1207. var style = this.tableView.Style.GetOrCreateColumnStyle (clickedCol);
  1208. style.Visible = false;
  1209. this.tableView.Update ();
  1210. }
  1211. }
  1212. /// <summary>
  1213. /// State representing a recursive search from <see cref="FileDialogState.Directory"/>
  1214. /// downwards.
  1215. /// </summary>
  1216. internal class SearchState : FileDialogState {
  1217. bool cancel = false;
  1218. bool finished = false;
  1219. // TODO: Add thread safe child adding
  1220. List<FileSystemInfoStats> found = new List<FileSystemInfoStats> ();
  1221. object oLockFound = new object ();
  1222. CancellationTokenSource token = new CancellationTokenSource ();
  1223. public SearchState (IDirectoryInfo dir, FileDialog parent, string searchTerms) : base (dir, parent)
  1224. {
  1225. parent.SearchMatcher.Initialize (searchTerms);
  1226. Children = new FileSystemInfoStats [0];
  1227. BeginSearch ();
  1228. }
  1229. private void BeginSearch ()
  1230. {
  1231. Task.Run (() => {
  1232. RecursiveFind (Directory);
  1233. finished = true;
  1234. });
  1235. Task.Run (() => {
  1236. UpdateChildren ();
  1237. });
  1238. }
  1239. private void UpdateChildren ()
  1240. {
  1241. lock (Parent.onlyOneSearchLock) {
  1242. while (!cancel && !finished) {
  1243. try {
  1244. Task.Delay (250).Wait (token.Token);
  1245. } catch (OperationCanceledException) {
  1246. cancel = true;
  1247. }
  1248. if (cancel || finished) {
  1249. break;
  1250. }
  1251. UpdateChildrenToFound ();
  1252. }
  1253. if (finished && !cancel) {
  1254. UpdateChildrenToFound ();
  1255. }
  1256. Application.MainLoop.Invoke (() => {
  1257. Parent.spinnerView.Visible = false;
  1258. });
  1259. }
  1260. }
  1261. private void UpdateChildrenToFound ()
  1262. {
  1263. lock (oLockFound) {
  1264. Children = found.ToArray ();
  1265. }
  1266. Application.MainLoop.Invoke (() => {
  1267. Parent.tbPath.Autocomplete.GenerateSuggestions (
  1268. new AutocompleteFilepathContext (Parent.tbPath.Text, Parent.tbPath.CursorPosition, this)
  1269. );
  1270. Parent.WriteStateToTableView ();
  1271. Parent.spinnerView.Visible = true;
  1272. Parent.spinnerView.SetNeedsDisplay ();
  1273. });
  1274. }
  1275. private void RecursiveFind (IDirectoryInfo directory)
  1276. {
  1277. foreach (var f in GetChildren (directory)) {
  1278. if (cancel) {
  1279. return;
  1280. }
  1281. if (f.IsParent) {
  1282. continue;
  1283. }
  1284. lock (oLockFound) {
  1285. if (found.Count >= FileDialog.MaxSearchResults) {
  1286. finished = true;
  1287. return;
  1288. }
  1289. }
  1290. if (Parent.SearchMatcher.IsMatch (f.FileSystemInfo)) {
  1291. lock (oLockFound) {
  1292. found.Add (f);
  1293. }
  1294. }
  1295. if (f.FileSystemInfo is IDirectoryInfo sub) {
  1296. RecursiveFind (sub);
  1297. }
  1298. }
  1299. }
  1300. internal override void RefreshChildren ()
  1301. {
  1302. }
  1303. /// <summary>
  1304. /// Cancels the current search (if any). Returns true if a search
  1305. /// was running and cancellation was successfully set.
  1306. /// </summary>
  1307. /// <returns></returns>
  1308. internal bool Cancel ()
  1309. {
  1310. var alreadyCancelled = token.IsCancellationRequested || cancel;
  1311. cancel = true;
  1312. token.Cancel ();
  1313. return !alreadyCancelled;
  1314. }
  1315. }
  1316. }
  1317. }