FileDialog.cs 40 KB

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