FileDialog.cs 41 KB

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