diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..032c1bd --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d2ce7ab --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,33 @@ +version: 2 +updates: + - package-ecosystem: github-actions + cooldown: + default-days: 7 + directory: / + schedule: + interval: daily + open-pull-requests-limit: 5 + labels: + - internal + commit-message: + prefix: chore + groups: + github-actions: + patterns: + - "*" + + - package-ecosystem: nuget + cooldown: + default-days: 7 + directory: / + schedule: + interval: daily + open-pull-requests-limit: 10 + labels: + - internal + commit-message: + prefix: chore + groups: + nuget: + patterns: + - "*" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 493036e..e26a7df 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,39 +10,34 @@ on: jobs: build: runs-on: ubuntu-latest + permissions: + contents: read steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 # Need to fetch all for proper history - - name: Collect build info - id: info - run: | - # Get short SHA - SHA_SHORT=$(git rev-parse --short HEAD) - echo "sha_short=$SHA_SHORT" >> $GITHUB_OUTPUT - - # Extract version from csproj - VERSION=$(grep -oP '(?<=)[^<]+' BepisLocaleLoader.csproj) - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "Version found: $VERSION" - - uses: actions/setup-dotnet@v4 + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: "9.0.x" - - name: Build + global-json-file: global.json + - name: Build and create Thunderstore package + id: build run: | - dotnet build -c Release + dotnet build -c Release -t:PackTS dotnet pack -c Release --no-build -o ./bin/dist - # Copy the built DLL to dist folder - cp ./bin/Release/BepisLocaleLoader.dll ./bin/dist/ - - name: Create Thunderstore Package + cp ./BepisLocaleLoader/bin/Release/BepisLocaleLoader.dll ./bin/dist/ + - name: Show version + id: info + env: + VERSION: '${{ steps.build.outputs.version }}' run: | - dotnet tool restore - dotnet tcli build --package-version ${{ steps.info.outputs.version }} + echo "Version found: $VERSION" + echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: BepisLocaleLoader-${{ steps.info.outputs.version }}-${{ steps.info.outputs.sha_short }} + name: 'BepisLocaleLoader-${{ steps.build.outputs.version }}-${{ steps.info.outputs.sha_short }}' path: | ./bin/dist/*.nupkg ./bin/dist/*.dll - ./build/*.zip \ No newline at end of file + ./build/*.zip diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ef65fae..9ff7f09 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,34 +6,17 @@ on: jobs: release: runs-on: ubuntu-latest + permissions: + contents: read steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 # Need to fetch all for proper history - - name: Collect build info - id: info - run: | - # Get short SHA - SHA_SHORT=$(git rev-parse --short HEAD) - echo "sha_short=$SHA_SHORT" >> $GITHUB_OUTPUT - - # Extract version from csproj - VERSION=$(grep -oP '(?<=)[^<]+' BepisLocaleLoader.csproj) - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "Version found: $VERSION" - - uses: actions/setup-dotnet@v4 + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: "9.0.x" - - name: Build - run: | - dotnet build -c Release - - name: Create Thunderstore Package - run: | - dotnet tool restore - dotnet tcli build --package-version ${{ steps.info.outputs.version }} - - name: Publish to Thunderstore - run: | - ZIP_FILE=$(ls ./build/*.zip | head -1) - dotnet tcli publish --file "$ZIP_FILE" + global-json-file: global.json + - name: Build and publish Thunderstore package env: - TCLI_AUTH_TOKEN: ${{ secrets.TCLI_AUTH_TOKEN }} \ No newline at end of file + TCLI_AUTH_TOKEN: ${{ secrets.TCLI_AUTH_TOKEN }} + run: dotnet build -c Release -t:PackTS -P:PublishTS=true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e000836..ed03617 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,64 +18,45 @@ on: jobs: release: runs-on: ubuntu-latest + permissions: + contents: write + id-token: write + attestations: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 # Need to fetch all for proper history - - name: Collect build info - id: info - run: | - # Get short SHA - SHA_SHORT=$(git rev-parse --short HEAD) - echo "sha_short=$SHA_SHORT" >> $GITHUB_OUTPUT - - # Extract version from csproj - VERSION=$(grep -oP '(?<=)[^<]+' BepisLocaleLoader.csproj) - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "Version found: $VERSION" - - uses: actions/setup-dotnet@v4 + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: "9.0.x" - - name: Build + global-json-file: global.json + - name: Build and create Thunderstore package + id: build run: | - dotnet build -c Release + dotnet build -c Release -t:PackTS dotnet pack -c Release --no-build -o ./bin/dist - # Copy the built DLL to dist folder for release - cp ./bin/Release/BepisLocaleLoader.dll ./bin/dist/ - - name: Create Thunderstore Package - run: | - dotnet tool restore - dotnet tcli build --package-version ${{ steps.info.outputs.version }} - - name: Create Git Tag (if needed) - if: ${{ github.event_name == 'workflow_dispatch' }} - run: | - TAG_NAME="${{ steps.info.outputs.version }}" - # Check if tag already exists - if git rev-parse "$TAG_NAME" >/dev/null 2>&1; then - echo "Tag $TAG_NAME already exists" - else - echo "Creating tag $TAG_NAME" - git config user.name github-actions - git config user.email github-actions@github.com - git tag -a "$TAG_NAME" -m "Release $TAG_NAME" - git push origin "$TAG_NAME" - fi - - name: Publish to Nuget - run: | - dotnet nuget push ./bin/dist/*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://nuget-modding.resonite.net/v3/index.json --skip-duplicate - - name: Create GitHub Release - if: ${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')) || (github.event_name == 'workflow_dispatch' && github.event.inputs.create_release == 'true') }} - uses: softprops/action-gh-release@v2 + cp ./BepisLocaleLoader/bin/Release/BepisLocaleLoader.dll ./bin/dist/ + - name: Attest artifacts + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: - draft: true - prerelease: false - generate_release_notes: false - name: ${{ steps.info.outputs.version }} - tag_name: ${{ steps.info.outputs.version }} - target_commitish: ${{ github.sha }} - files: | + subject-path: | ./bin/dist/*.nupkg ./bin/dist/*.dll ./build/*.zip + - name: Publish to Nuget env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file + NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} + run: | + dotnet nuget push ./bin/dist/*.nupkg --api-key "$NUGET_API_KEY" --source https://nuget-modding.resonite.net/v3/index.json --skip-duplicate + - name: Create GitHub Release + if: ${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')) || (github.event_name == 'workflow_dispatch' && github.event.inputs.create_release == 'true') }} + env: + TAG_NAME: ${{ steps.build.outputs.version }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release create "$TAG_NAME" \ + --draft \ + --title "$TAG_NAME" \ + ./bin/dist/*.nupkg \ + ./bin/dist/*.dll \ + ./build/*.zip diff --git a/.gitignore b/.gitignore index 299dcd5..33d194b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,489 @@ -bin/ -obj/ -/packages/ -riderModule.iml -/_ReSharper.Caches/ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp + +# Thunderstore packaging +dist/ build/ -.vs/ \ No newline at end of file + +# Local build overrides (see Config.Build.user.props.template) +Config.Build.user.props \ No newline at end of file diff --git a/BepisLocaleLoader.slnx b/BepisLocaleLoader.slnx index 1ceb3dc..9891903 100644 --- a/BepisLocaleLoader.slnx +++ b/BepisLocaleLoader.slnx @@ -1,3 +1,3 @@ - + diff --git a/BepisLocaleLoader.csproj b/BepisLocaleLoader/BepisLocaleLoader.csproj similarity index 53% rename from BepisLocaleLoader.csproj rename to BepisLocaleLoader/BepisLocaleLoader.csproj index e5f5e9e..3f8a169 100644 --- a/BepisLocaleLoader.csproj +++ b/BepisLocaleLoader/BepisLocaleLoader.csproj @@ -1,39 +1,42 @@ - 1.2.1 ResoniteModding + $([System.String]::Copy('$(Authors)').Split(',')[0].Trim()) net10.0 - https://github.com/ResoniteModding/BepisLocaleLoader - https://github.com/ResoniteModding/BepisLocaleLoader - git - ResoniteModding.BepisLocaleLoader Bepis Locale Loader - BepisLocaleLoader + Loads locale files for plugins. + Copyright (c) ResoniteModding $([System.DateTime]::UtcNow.Year) + icon.png + README.md + See https://github.com/$(FirstAuthor)/$(AssemblyName)/releases + resonite; bepinex; mod; locale; bepis; BepisLoader + https://github.com/$(FirstAuthor) + https://github.com/$(FirstAuthor)/$(AssemblyName) + git + $(FirstAuthor).$(AssemblyName) + MIT + $(AssemblyName) enable enable - true - false - true true true embedded - $(ResonitePath)/ - $(MSBuildProgramFiles32)\Steam\steamapps\common\Resonite\ - $(HOME)/.steam/steam/steamapps/common/Resonite/ - $(GamePath)BepInEx\plugins\$(AssemblyName) - - https://nuget-modding.resonite.net/v3/index.json; - + true + true + + + + + - @@ -64,19 +67,4 @@ False - - - - - - - - - - - - - - true - diff --git a/ConfigLocale.cs b/BepisLocaleLoader/ConfigLocale.cs similarity index 100% rename from ConfigLocale.cs rename to BepisLocaleLoader/ConfigLocale.cs diff --git a/LocaleInjectionPatch.cs b/BepisLocaleLoader/LocaleInjectionPatch.cs similarity index 100% rename from LocaleInjectionPatch.cs rename to BepisLocaleLoader/LocaleInjectionPatch.cs diff --git a/LocaleLoader.cs b/BepisLocaleLoader/LocaleLoader.cs similarity index 97% rename from LocaleLoader.cs rename to BepisLocaleLoader/LocaleLoader.cs index 6bf01e5..c91c90e 100644 --- a/LocaleLoader.cs +++ b/BepisLocaleLoader/LocaleLoader.cs @@ -1,223 +1,223 @@ -using System.Text.Json; -using BepInEx; -using Elements.Assets; -using Elements.Core; -using FrooxEngine; - -namespace BepisLocaleLoader; - -/// -/// Public API for locale loading. -/// Primary locale injection happens via Harmony patch in LocaleInjectionPatch. -/// This class provides runtime APIs for adding locales after initial load. -/// -public static class LocaleLoader -{ - internal static readonly JsonSerializerOptions JsonOptions = new() - { - PropertyNameCaseInsensitive = true, - ReadCommentHandling = JsonCommentHandling.Skip, - AllowTrailingCommas = true - }; - - private static readonly object _pluginsLock = new(); - - /// - /// Tracks which plugins have locale files. - /// - public static readonly HashSet PluginsWithLocales = new(); - - /// - /// Thread-safe method to add a plugin to the tracking set. - /// - internal static void TrackPluginWithLocale(PluginInfo plugin) - { - lock (_pluginsLock) - { - PluginsWithLocales.Add(plugin); - } - } - - /// - /// Add a single locale string at runtime. - /// For bulk loading, use the Locale/ folder in your plugin directory. - /// - public static void AddLocaleString(string rawString, string localeString, bool force = false, string? authors = null) - { - string authorsSource = !string.IsNullOrWhiteSpace(authors) ? authors - : !string.IsNullOrWhiteSpace(Plugin.AUTHORS) ? Plugin.AUTHORS - : "BepInEx"; - - List finalAuthors = authorsSource.Split(", ", StringSplitOptions.RemoveEmptyEntries).ToList(); - - LocaleData localeData = new() - { - LocaleCode = "en-US", - Authors = finalAuthors, - Messages = new Dictionary - { - { rawString, localeString } - } - }; - - InjectLocaleData(localeData, force); - } - - /// - /// Add locales from a plugin's Locale/ folder at runtime. - /// Note: This is automatically handled by the Harmony patch during locale loading. - /// - public static void AddLocaleFromPlugin(PluginInfo plugin) - { - var localeFiles = GetPluginLocaleFiles(plugin).ToList(); - if (localeFiles.Count == 0) return; - - Plugin.Log.LogDebug($"Adding locale for {plugin.Metadata?.GUID ?? "unknown"}"); - - foreach (string file in localeFiles) - { - AddLocaleFromFile(file); - } - - TrackPluginWithLocale(plugin); - } - - /// - /// Gets all locale JSON files from a plugin's Locale/ folder. - /// - internal static IEnumerable GetPluginLocaleFiles(PluginInfo plugin) - { - string? pluginDir = Path.GetDirectoryName(plugin.Location); - if (string.IsNullOrEmpty(pluginDir)) - return []; - - string localeDir = Path.Combine(pluginDir, "Locale"); - - if (!Directory.Exists(localeDir)) - return []; - - return Directory.GetFiles(localeDir, "*.json", SearchOption.AllDirectories); - } - - /// - /// Add locale from a specific file at runtime. - /// - public static void AddLocaleFromFile(string path) - { - var localeData = LoadLocaleDataFromFile(path); - if (localeData == null) return; - - Plugin.Log.LogDebug($"- LocaleCode: {localeData.LocaleCode}, Message Count: {localeData.Messages.Count}"); - - InjectLocaleData(localeData, force: true); - } - - /// - /// Loads and parses a locale JSON file, returning the LocaleData or null on failure. - /// - internal static LocaleData? LoadLocaleDataFromFile(string path) - { - if (!File.Exists(path)) return null; - - string json; - try - { - json = File.ReadAllText(path); - } - catch (Exception e) - { - Plugin.Log.LogError($"Error reading locale file {path}: {e}"); - return null; - } - - LocaleData? localeData; - try - { - localeData = JsonSerializer.Deserialize(json, JsonOptions); - } - catch (Exception e) - { - Plugin.Log.LogError($"Error parsing locale file {path}: {e}"); - return null; - } - - if (localeData?.Messages == null) - { - Plugin.Log.LogError($"Invalid locale file (missing messages): {path}"); - return null; - } - - return localeData; - } - - /// - /// Inject locale data into the current locale provider. - /// - private static void InjectLocaleData(LocaleData localeData, bool force) - { - var localeProvider = Userspace.UserspaceWorld?.GetCoreLocale(); - - if (localeProvider?.Asset?.Data == null) - { - Plugin.Log.LogWarning("Cannot inject locale data - locale provider not available yet"); - return; - } - - if (!force) - { - string? firstKey = localeData.Messages.Keys.FirstOrDefault(); - if (firstKey != null) - { - bool alreadyExists = localeProvider.Asset.Data.Messages.Any(ld => ld.Key == firstKey); - if (alreadyExists) return; - } - } - - localeProvider.Asset.Data.LoadDataAdditively(localeData); - } - - #region String Formatting Extensions - - private static string GetFormattedLocaleString(this string key, string? format, Dictionary? dict, (string, object)[]? arguments) - { - var localeProvider = Userspace.UserspaceWorld?.GetCoreLocale(); - - Dictionary merged = dict != null ? new Dictionary(dict) : []; - if (arguments != null) - { - foreach ((string name, object value) in arguments) - { - merged[name] = value; - } - } - - string? formatted = localeProvider?.Asset?.Format(key, merged); - - if (!string.IsNullOrWhiteSpace(format)) - { - formatted = string.Format(format, formatted); - } - - return formatted ?? key; - } - - public static string GetFormattedLocaleString(this string key) => key.GetFormattedLocaleString(null, null, null); - public static string GetFormattedLocaleString(this string key, string format) => key.GetFormattedLocaleString(format, null, null); - public static string GetFormattedLocaleString(this string key, string argName, object argField) => key.GetFormattedLocaleString(null, null, [(argName, argField)]); - public static string GetFormattedLocaleString(this string key, string format, string argName, object argField) => key.GetFormattedLocaleString(format, null, [(argName, argField)]); - public static string GetFormattedLocaleString(this string key, params (string, object)[] arguments) => key.GetFormattedLocaleString(null, null, arguments); - public static string GetFormattedLocaleString(this string key, string format, params (string, object)[] arguments) => key.GetFormattedLocaleString(format, null, arguments); - - #endregion - - #region LocaleString Extensions - - public static LocaleString T(this string str, string argName, object argField) => str.AsLocaleKey(null, (argName, argField)); - public static LocaleString T(this string str, string format, string argName, object argField) => str.AsLocaleKey(format, (argName, argField)); - public static LocaleString T(this string str, params (string, object)[] arguments) => str.AsLocaleKey(null, arguments); - public static LocaleString T(this string str, string format, params (string, object)[] arguments) => str.AsLocaleKey(format, arguments); - public static LocaleString T(this string str, bool continuous, Dictionary? arguments = null) => new(str, null, true, continuous, arguments); - public static LocaleString T(this string str, string? format = null, bool continuous = true, Dictionary? arguments = null) => new(str, format, true, continuous, arguments); - - #endregion -} +using System.Text.Json; +using BepInEx; +using Elements.Assets; +using Elements.Core; +using FrooxEngine; + +namespace BepisLocaleLoader; + +/// +/// Public API for locale loading. +/// Primary locale injection happens via Harmony patch in LocaleInjectionPatch. +/// This class provides runtime APIs for adding locales after initial load. +/// +public static class LocaleLoader +{ + internal static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true + }; + + private static readonly object _pluginsLock = new(); + + /// + /// Tracks which plugins have locale files. + /// + public static readonly HashSet PluginsWithLocales = new(); + + /// + /// Thread-safe method to add a plugin to the tracking set. + /// + internal static void TrackPluginWithLocale(PluginInfo plugin) + { + lock (_pluginsLock) + { + PluginsWithLocales.Add(plugin); + } + } + + /// + /// Add a single locale string at runtime. + /// For bulk loading, use the Locale/ folder in your plugin directory. + /// + public static void AddLocaleString(string rawString, string localeString, bool force = false, string? authors = null) + { + string authorsSource = !string.IsNullOrWhiteSpace(authors) ? authors + : !string.IsNullOrWhiteSpace(Plugin.AUTHORS) ? Plugin.AUTHORS + : "BepInEx"; + + List finalAuthors = authorsSource.Split(", ", StringSplitOptions.RemoveEmptyEntries).ToList(); + + LocaleData localeData = new() + { + LocaleCode = "en-US", + Authors = finalAuthors, + Messages = new Dictionary + { + { rawString, localeString } + } + }; + + InjectLocaleData(localeData, force); + } + + /// + /// Add locales from a plugin's Locale/ folder at runtime. + /// Note: This is automatically handled by the Harmony patch during locale loading. + /// + public static void AddLocaleFromPlugin(PluginInfo plugin) + { + var localeFiles = GetPluginLocaleFiles(plugin).ToList(); + if (localeFiles.Count == 0) return; + + Plugin.Log.LogDebug($"Adding locale for {plugin.Metadata?.GUID ?? "unknown"}"); + + foreach (string file in localeFiles) + { + AddLocaleFromFile(file); + } + + TrackPluginWithLocale(plugin); + } + + /// + /// Gets all locale JSON files from a plugin's Locale/ folder. + /// + internal static IEnumerable GetPluginLocaleFiles(PluginInfo plugin) + { + string? pluginDir = Path.GetDirectoryName(plugin.Location); + if (string.IsNullOrEmpty(pluginDir)) + return []; + + string localeDir = Path.Combine(pluginDir, "Locale"); + + if (!Directory.Exists(localeDir)) + return []; + + return Directory.GetFiles(localeDir, "*.json", SearchOption.AllDirectories); + } + + /// + /// Add locale from a specific file at runtime. + /// + public static void AddLocaleFromFile(string path) + { + var localeData = LoadLocaleDataFromFile(path); + if (localeData == null) return; + + Plugin.Log.LogDebug($"- LocaleCode: {localeData.LocaleCode}, Message Count: {localeData.Messages.Count}"); + + InjectLocaleData(localeData, force: true); + } + + /// + /// Loads and parses a locale JSON file, returning the LocaleData or null on failure. + /// + internal static LocaleData? LoadLocaleDataFromFile(string path) + { + if (!File.Exists(path)) return null; + + string json; + try + { + json = File.ReadAllText(path); + } + catch (Exception e) + { + Plugin.Log.LogError($"Error reading locale file {path}: {e}"); + return null; + } + + LocaleData? localeData; + try + { + localeData = JsonSerializer.Deserialize(json, JsonOptions); + } + catch (Exception e) + { + Plugin.Log.LogError($"Error parsing locale file {path}: {e}"); + return null; + } + + if (localeData?.Messages == null) + { + Plugin.Log.LogError($"Invalid locale file (missing messages): {path}"); + return null; + } + + return localeData; + } + + /// + /// Inject locale data into the current locale provider. + /// + private static void InjectLocaleData(LocaleData localeData, bool force) + { + var localeProvider = Userspace.UserspaceWorld?.GetCoreLocale(); + + if (localeProvider?.Asset?.Data == null) + { + Plugin.Log.LogWarning("Cannot inject locale data - locale provider not available yet"); + return; + } + + if (!force) + { + string? firstKey = localeData.Messages.Keys.FirstOrDefault(); + if (firstKey != null) + { + bool alreadyExists = localeProvider.Asset.Data.Messages.Any(ld => ld.Key == firstKey); + if (alreadyExists) return; + } + } + + localeProvider.Asset.Data.LoadDataAdditively(localeData); + } + + #region String Formatting Extensions + + private static string GetFormattedLocaleString(this string key, string? format, Dictionary? dict, (string, object)[]? arguments) + { + var localeProvider = Userspace.UserspaceWorld?.GetCoreLocale(); + + Dictionary merged = dict != null ? new Dictionary(dict) : []; + if (arguments != null) + { + foreach ((string name, object value) in arguments) + { + merged[name] = value; + } + } + + string? formatted = localeProvider?.Asset?.Format(key, merged); + + if (!string.IsNullOrWhiteSpace(format)) + { + formatted = string.Format(format, formatted); + } + + return formatted ?? key; + } + + public static string GetFormattedLocaleString(this string key) => key.GetFormattedLocaleString(null, null, null); + public static string GetFormattedLocaleString(this string key, string format) => key.GetFormattedLocaleString(format, null, null); + public static string GetFormattedLocaleString(this string key, string argName, object argField) => key.GetFormattedLocaleString(null, null, [(argName, argField)]); + public static string GetFormattedLocaleString(this string key, string format, string argName, object argField) => key.GetFormattedLocaleString(format, null, [(argName, argField)]); + public static string GetFormattedLocaleString(this string key, params (string, object)[] arguments) => key.GetFormattedLocaleString(null, null, arguments); + public static string GetFormattedLocaleString(this string key, string format, params (string, object)[] arguments) => key.GetFormattedLocaleString(format, null, arguments); + + #endregion + + #region LocaleString Extensions + + public static LocaleString T(this string str, string argName, object argField) => str.AsLocaleKey(null, (argName, argField)); + public static LocaleString T(this string str, string format, string argName, object argField) => str.AsLocaleKey(format, (argName, argField)); + public static LocaleString T(this string str, params (string, object)[] arguments) => str.AsLocaleKey(null, arguments); + public static LocaleString T(this string str, string format, params (string, object)[] arguments) => str.AsLocaleKey(format, arguments); + public static LocaleString T(this string str, bool continuous, Dictionary? arguments = null) => new(str, null, true, continuous, arguments); + public static LocaleString T(this string str, string? format = null, bool continuous = true, Dictionary? arguments = null) => new(str, format, true, continuous, arguments); + + #endregion +} diff --git a/Plugin.cs b/BepisLocaleLoader/Plugin.cs similarity index 95% rename from Plugin.cs rename to BepisLocaleLoader/Plugin.cs index 5ab0e64..642e6aa 100644 --- a/Plugin.cs +++ b/BepisLocaleLoader/Plugin.cs @@ -1,22 +1,22 @@ -using BepInEx; -using BepInEx.Logging; -using BepInEx.NET.Common; -using HarmonyLib; - -namespace BepisLocaleLoader; - -[BepInAutoPlugin] -[BepInDependency(BepInExResoniteShim.PluginMetadata.GUID, BepInDependency.DependencyFlags.HardDependency)] -public partial class Plugin : BasePlugin -{ - internal new static ManualLogSource Log = null!; - - public override void Load() - { - Log = base.Log; - - HarmonyInstance.PatchAll(); - - Log.LogInfo($"Plugin {GUID} is loaded!"); - } -} +using BepInEx; +using BepInEx.Logging; +using BepInEx.NET.Common; +using HarmonyLib; + +namespace BepisLocaleLoader; + +[BepInAutoPlugin] +[BepInDependency(BepInExResoniteShim.PluginMetadata.GUID, BepInDependency.DependencyFlags.HardDependency)] +public partial class Plugin : BasePlugin +{ + internal new static ManualLogSource Log = null!; + + public override void Load() + { + Log = base.Log; + + HarmonyInstance.PatchAll(); + + Log.LogInfo($"Plugin {GUID} is loaded!"); + } +} diff --git a/Config.Build.user.props.template b/Config.Build.user.props.template new file mode 100644 index 0000000..4cac8ff --- /dev/null +++ b/Config.Build.user.props.template @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..38ed72d --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,30 @@ + + + + $(MSBuildThisFileDirectory) + + + + + + true + false + https://nuget-modding.resonite.net/v3/index.json + + + true + + + + $(MSBuildProgramFiles32)\Steam\steamapps\common\Resonite\ + $(HOME)/.steam/steam/steamapps/common/Resonite/ + + $(BepInExPath)/ + $(GamePath)BepInEx/ + $(APPDATA)\r2modmanPlus-local\Resonite\profiles\Default\BepInEx\ + $(XDG_CONFIG_HOME)/r2modmanPlus-local/Resonite/profiles/Default/BepInEx/ + $(APPDATA)\com.kesomannen.gale\resonite\profiles\Default\BepInEx\ + $(XDG_DATA_HOME)/com.kesomannen.gale/resonite/profiles/Default/BepInEx/ + + + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000..3aa5c78 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,37 @@ + + + + + + + + + + build + publish + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index 3b04ac0..88a2ab6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,14 @@ +

+ +

+ # BepisLocaleLoader +[![Thunderstore Version](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fthunderstore.io%2Fapi%2Fexperimental%2Fpackage%2FResoniteModding%2FBepisLocaleLoader%2F&query=%24.latest.version_number&label=Thunderstore&style=flat&logo=thunderstore&logoColor=white)](https://thunderstore.io/c/resonite/p/ResoniteModding/BepisLocaleLoader/) +[![Thunderstore Downloads](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fthunderstore.io%2Fapi%2Fv1%2Fpackage-metrics%2FResoniteModding%2FBepisLocaleLoader%2F&query=%24.downloads&label=downloads&style=flat&logo=thunderstore&logoColor=white)](https://thunderstore.io/c/resonite/p/ResoniteModding/BepisLocaleLoader/) +[![NuGet Version](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fnuget-modding.resonite.net%2Fv3%2Fregistration%2Fresonitemodding.bepislocaleloader%2Findex.json&query=%24.items%5B0%5D.upper&label=NuGet&style=flat&logo=nuget&logoColor=white&color=004880)](https://nuget-modding.resonite.net/packages/resonitemodding.bepislocaleloader) +[![Build](https://img.shields.io/github/actions/workflow/status/ResoniteModding/BepisLocaleLoader/build.yml?style=flat&logo=github)](https://github.com/ResoniteModding/BepisLocaleLoader/actions/workflows/build.yml) +[![License](https://img.shields.io/badge/license-MIT-blue?style=flat)](#license) + A [Resonite](https://resonite.com/) mod that Loads locale files for Plugins. ## Installation (Manual) @@ -120,4 +130,8 @@ Examples: - Loaded plugin locales are tracked in `LocaleLoader.PluginsWithLocales`. - Logs show which files are loaded and how many messages were registered. -- Errors during JSON parsing will be logged with details. \ No newline at end of file +- Errors during JSON parsing will be logged with details. + +## License + +This project is licensed under MIT License. See [LICENSE](LICENSE) for details. \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 0000000..8e32bb2 --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "10.0.401", + "rollForward": "major" + } +} \ No newline at end of file diff --git a/thunderstore.toml b/thunderstore.toml index eb6d6b0..4283d09 100644 --- a/thunderstore.toml +++ b/thunderstore.toml @@ -6,14 +6,14 @@ schemaVersion = "0.0.1" [package] namespace = "ResoniteModding" name = "BepisLocaleLoader" # Change this to your mod's name, no spaces or special characters, max 128 characters -versionNumber = "1.0.0" # Change this to your mod's version, must be in semantic versioning format (e.g. 1.0.0, 2.1.3, 0.1.0-alpha.1) +# versionNumber = "1.0.0" # Uncomment this if publishing via manual tcli! Change this to your mod's version, must be in semantic versioning format (e.g. 1.0.0, 2.1.3, 0.1.0-alpha.1) description = "Loads locale files for Plugins" websiteUrl = "https://github.com/ResoniteModding/BepisLocaleLoader" containsNsfwContent = false # List any dependencies your mod has here, in the format "namespace-modname" = "version-constraint" [package.dependencies] -ResoniteModding-BepisLoader = "1.4.1" +ResoniteModding-BepisLoader = "1.6.0" [build] icon = "./icon.png" @@ -22,14 +22,9 @@ outdir = "./build" # Copy the compiled DLL to the plugins folder in the mod package [[build.copy]] -source = "./bin/Release/BepisLocaleLoader.dll" +source = "./BepisLocaleLoader/bin/Release/BepisLocaleLoader.dll" target = "plugins/BepisLocaleLoader/" -# Include the PDB file for better debugging support -# [[build.copy]] -# source = "./bin/Release/BepisLocaleLoader.pdb" -# target = "plugins/BepisLocaleLoader/" - # Uncomment the following lines to include CHANGELOG file in your mod package. https://wiki.thunderstore.io/mods/updating-a-package#changelog # [[build.copy]] # source = "./CHANGELOG.md"