| 1 | using TextMateSharp.Grammars; |
| 2 | |
| 3 | namespace CascadeIDE.Services; |
| 4 | |
| 5 | /// <summary> |
| 6 | /// TextMateSharp's embedded bundle has no TOML scope; we ship a VS Code-style grammar under <c>TextMateGrammars/toml/</c> (MIT, taplo — see folder README). |
| 7 | /// </summary> |
| 8 | public static class TextMateTomlGrammar |
| 9 | { |
| 10 | /// <summary>Relative to <see cref="AppContext.BaseDirectory"/> unless <paramref name="baseDirectory"/> is set.</summary> |
| 11 | public const string PackageJsonRelativePath = "TextMateGrammars/toml/package.json"; |
| 12 | |
| 13 | private static readonly string[] s_embeddedTomlGrammarFiles = |
| 14 | [ |
| 15 | "TextMateGrammars/toml/package.json", |
| 16 | "TextMateGrammars/toml/syntaxes/toml.tmLanguage.json", |
| 17 | ]; |
| 18 | |
| 19 | private static string? s_cachedExtractedPackagePath; |
| 20 | |
| 21 | /// <summary>Loads the bundled TOML grammar into the registry (no-op if package file is missing on disk and in resources).</summary> |
| 22 | public static void TryLoadInto(RegistryOptions registry, string? baseDirectory = null) |
| 23 | { |
| 24 | baseDirectory ??= AppContext.BaseDirectory; |
| 25 | var packagePath = CanonicalFilePath.Normalize(Path.Combine(baseDirectory, PackageJsonRelativePath)); |
| 26 | if (File.Exists(packagePath)) |
| 27 | { |
| 28 | registry.LoadFromLocalFile("TOML", packagePath, overwrite: false); |
| 29 | return; |
| 30 | } |
| 31 | |
| 32 | packagePath = EnsureExtractedPackagePathFromEmbedded(); |
| 33 | if (packagePath is null || !File.Exists(packagePath)) |
| 34 | return; |
| 35 | registry.LoadFromLocalFile("TOML", packagePath, overwrite: false); |
| 36 | } |
| 37 | |
| 38 | private static string? EnsureExtractedPackagePathFromEmbedded() |
| 39 | { |
| 40 | if (s_cachedExtractedPackagePath is not null && File.Exists(s_cachedExtractedPackagePath)) |
| 41 | return s_cachedExtractedPackagePath; |
| 42 | |
| 43 | var extractRoot = Path.Combine(SettingsService.GetSettingsDirectory(), "cache", "embedded-textmate-toml"); |
| 44 | try |
| 45 | { |
| 46 | Directory.CreateDirectory(extractRoot); |
| 47 | foreach (var rel in s_embeddedTomlGrammarFiles) |
| 48 | { |
| 49 | if (!BundledAppContent.TryReadEmbeddedText(rel, out var text)) |
| 50 | return null; |
| 51 | var dest = Path.Combine(extractRoot, rel.Replace('/', Path.DirectorySeparatorChar)); |
| 52 | var dir = Path.GetDirectoryName(dest); |
| 53 | if (dir is not null) |
| 54 | Directory.CreateDirectory(dir); |
| 55 | File.WriteAllText(dest, text); |
| 56 | } |
| 57 | |
| 58 | var package = Path.Combine(extractRoot, PackageJsonRelativePath.Replace('/', Path.DirectorySeparatorChar)); |
| 59 | if (!File.Exists(package)) |
| 60 | return null; |
| 61 | s_cachedExtractedPackagePath = package; |
| 62 | return package; |
| 63 | } |
| 64 | catch |
| 65 | { |
| 66 | return null; |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |