FileDialog.cs 40 KB

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