FileDialog.cs 51 KB

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