FileDialog.cs 54 KB

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