FileDialog.cs 40 KB

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