FileDialog.cs 40 KB

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