FileDialog.cs 44 KB

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