FileDialog.cs 51 KB

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