FileDialog.cs 40 KB

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