FileDialog.cs 38 KB

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