FileDialog.cs 41 KB

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