FileDialog.cs 41 KB

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