FileDialog.cs 49 KB

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