FileDialog.cs 41 KB

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