2
0

AutocompleteFilepathContext.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #nullable disable
  2. using System.IO.Abstractions;
  3. using System.Runtime.InteropServices;
  4. namespace Terminal.Gui.Views;
  5. internal class AutocompleteFilepathContext (string currentLine, int cursorPosition, FileDialogState state)
  6. : AutocompleteContext (Cell.ToCellList (currentLine), cursorPosition)
  7. {
  8. public FileDialogState State { get; set; } = state;
  9. }
  10. internal class FilepathSuggestionGenerator : ISuggestionGenerator
  11. {
  12. private FileDialogState _state;
  13. public IEnumerable<Suggestion> GenerateSuggestions (AutocompleteContext context)
  14. {
  15. if (context is AutocompleteFilepathContext fileState)
  16. {
  17. _state = fileState.State;
  18. }
  19. if (_state is null)
  20. {
  21. return Enumerable.Empty<Suggestion> ();
  22. }
  23. var path = Cell.ToString (context.CurrentLine);
  24. int last = path.LastIndexOfAny (FileDialog.Separators);
  25. if (string.IsNullOrWhiteSpace (path) || !Path.IsPathRooted (path))
  26. {
  27. return Enumerable.Empty<Suggestion> ();
  28. }
  29. string term = path.Substring (last + 1);
  30. // If path is /tmp/ then don't just list everything in it
  31. if (string.IsNullOrWhiteSpace (term))
  32. {
  33. return Enumerable.Empty<Suggestion> ();
  34. }
  35. if (term.Equals (_state?.Directory?.Name))
  36. {
  37. // Clear suggestions
  38. return Enumerable.Empty<Suggestion> ();
  39. }
  40. bool isWindows = RuntimeInformation.IsOSPlatform (OSPlatform.Windows);
  41. string [] suggestions = _state!.Children.Where (d => !d.IsParent)
  42. .Select (
  43. e => e.FileSystemInfo is IDirectoryInfo d
  44. ? d.Name + Path.DirectorySeparatorChar
  45. : e.FileSystemInfo.Name
  46. )
  47. .ToArray ();
  48. string [] validSuggestions = suggestions
  49. .Where (
  50. s => s.StartsWith (
  51. term,
  52. isWindows
  53. ? StringComparison.InvariantCultureIgnoreCase
  54. : StringComparison.InvariantCulture
  55. )
  56. )
  57. .OrderBy (m => m.Length)
  58. .ToArray ();
  59. // nothing to suggest
  60. if (validSuggestions.Length == 0 || validSuggestions [0].Length == term.Length)
  61. {
  62. return Enumerable.Empty<Suggestion> ();
  63. }
  64. return validSuggestions.Select (
  65. f => new Suggestion (term.Length, f, f)
  66. )
  67. .ToList ();
  68. }
  69. public bool IsWordChar (string text)
  70. {
  71. if (text == "\n")
  72. {
  73. return false;
  74. }
  75. return true;
  76. }
  77. }