FileDialog.cs 40 KB

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