FileDialog.cs 41 KB

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