Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c44a7e6dda
|
||
|
|
f9c249a4d1
|
||
|
|
4ec3011320
|
||
|
|
2b8e568efa
|
||
|
|
3265cbe9b8
|
||
|
|
8adc334bfa
|
||
|
|
c5e29cb313
|
||
|
|
3bcfa56fae
|
||
|
|
64ce75a341
|
||
|
|
8aa4c79604
|
||
|
|
a6011cd01d | ||
|
|
cdd9dbdb73 | ||
|
|
7d7c0de907 | ||
|
|
d7ae6016cb | ||
|
|
ba84865d7a | ||
|
|
58f21a02c2 | ||
|
|
5c5de37fdf | ||
|
|
85401b9485 |
@@ -0,0 +1,123 @@
|
||||
name: Publish NuGet packages
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
env:
|
||||
NUGET_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1'
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
LD_LIBRARY_PATH: /opt/dotnet-libs/usr/lib/x86_64-linux-gnu
|
||||
SSL_CERT_FILE: /opt/ca-certificates.crt
|
||||
steps:
|
||||
- name: Fetch exact tagged source
|
||||
env:
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag="${GITEA_REF#refs/tags/}"
|
||||
case "$tag" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||
esac
|
||||
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/${GITEA_REPOSITORY}/archive/${tag}.tar.gz"
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||
NODE
|
||||
mkdir release
|
||||
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||
rm -f release.tar.gz
|
||||
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||
|
||||
- name: Install .NET 8 SDK
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { rootCertificates } from 'node:tls';
|
||||
|
||||
await writeFile('/opt/ca-certificates.crt', rootCertificates.join('\n'));
|
||||
|
||||
const metadataResponse = await fetch('https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/8.0/releases.json');
|
||||
if (!metadataResponse.ok) throw new Error(`Release metadata download failed: ${metadataResponse.status}`);
|
||||
const metadata = await metadataResponse.json();
|
||||
const sdkVersion = metadata['latest-sdk'];
|
||||
const release = metadata.releases.find(item => item.sdk?.version === sdkVersion);
|
||||
const file = release?.sdk?.files?.find(item => item.rid === 'linux-x64' && item.name.endsWith('.tar.gz'));
|
||||
if (!file) throw new Error(`Linux x64 SDK archive not found for ${sdkVersion}`);
|
||||
const archiveResponse = await fetch(file.url);
|
||||
if (!archiveResponse.ok) throw new Error(`SDK download failed: ${archiveResponse.status}`);
|
||||
await writeFile('/tmp/dotnet-sdk.tar.gz', new Uint8Array(await archiveResponse.arrayBuffer()));
|
||||
|
||||
const poolUrl = 'https://deb.debian.org/debian-security/pool/updates/main/o/openssl/';
|
||||
const poolResponse = await fetch(poolUrl);
|
||||
if (!poolResponse.ok) throw new Error(`OpenSSL package index download failed: ${poolResponse.status}`);
|
||||
const poolIndex = await poolResponse.text();
|
||||
const packages = [...poolIndex.matchAll(/href="(libssl3_[^"]+_amd64\.deb)"/g)].map(match => match[1]).sort();
|
||||
const packageName = packages.at(-1);
|
||||
if (!packageName) throw new Error('Debian libssl3 package was not found');
|
||||
const packageResponse = await fetch(poolUrl + packageName);
|
||||
if (!packageResponse.ok) throw new Error(`OpenSSL package download failed: ${packageResponse.status}`);
|
||||
await writeFile('/tmp/libssl3.deb', new Uint8Array(await packageResponse.arrayBuffer()));
|
||||
NODE
|
||||
mkdir -p /opt/dotnet
|
||||
tar -xzf /tmp/dotnet-sdk.tar.gz -C /opt/dotnet
|
||||
mkdir -p /opt/dotnet-libs
|
||||
dpkg-deb -x /tmp/libssl3.deb /opt/dotnet-libs
|
||||
rm -f /tmp/dotnet-sdk.tar.gz
|
||||
rm -f /tmp/libssl3.deb
|
||||
/opt/dotnet/dotnet --info
|
||||
|
||||
- name: Validate, pack and publish
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
: "${NUGET_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||
export PATH="/opt/dotnet:$PATH"
|
||||
cd release
|
||||
tag="$(cat .shrink-sdk-release-tag)"
|
||||
projects=()
|
||||
if [[ -d DotNet~ ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find DotNet~ -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
if [[ -d Godot~ ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find Godot~ -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
if [[ "${#projects[@]}" -eq 0 ]]; then
|
||||
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find . -maxdepth 1 -type f -name '*.csproj' -print0)
|
||||
fi
|
||||
test "${#projects[@]}" -gt 0
|
||||
if [[ -f package.json ]]; then
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
else
|
||||
version="$(dotnet msbuild "${projects[0]}" -getProperty:Version -nologo)"
|
||||
fi
|
||||
test "$tag" = "v$version"
|
||||
mkdir -p packages
|
||||
for project in "${projects[@]}"; do
|
||||
dotnet restore "$project" --configfile NuGet.Config
|
||||
dotnet pack "$project" --configuration Release --no-restore --output "$PWD/packages" --include-symbols --include-source
|
||||
done
|
||||
find packages -maxdepth 1 -name '*.nupkg' -type f | grep -q .
|
||||
dotnet nuget push 'packages/*.nupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||
if compgen -G 'packages/*.snupkg' > /dev/null; then
|
||||
dotnet nuget push 'packages/*.snupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||
fi
|
||||
@@ -15,22 +15,39 @@ jobs:
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||
steps:
|
||||
- name: Fetch tagged revision
|
||||
- name: Fetch exact tagged release archive
|
||||
env:
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
ref="${{ gitea.sha }}"
|
||||
test -n "$ref"
|
||||
git init .
|
||||
git remote add origin "https://git.crash.work/ShrinkSDK/ShrinkEventBus.git"
|
||||
git fetch --depth=1 origin "$ref"
|
||||
git checkout --detach FETCH_HEAD
|
||||
tag="${GITEA_REF#refs/tags/}"
|
||||
case "$tag" in
|
||||
v[0-9]*) ;;
|
||||
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||
esac
|
||||
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/ShrinkSDK/ShrinkEventBus/archive/${tag}.tar.gz"
|
||||
node --input-type=module <<'NODE'
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||
NODE
|
||||
mkdir release
|
||||
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||
rm -f release.tar.gz
|
||||
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||
|
||||
- name: Validate immutable release version
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
tag="$(git describe --exact-match --tags HEAD)"
|
||||
cd release
|
||||
tag="$(cat .shrink-sdk-release-tag)"
|
||||
version="$(node -p "require('./package.json').version")"
|
||||
test "$tag" = "v$version"
|
||||
npm pack --dry-run
|
||||
@@ -40,10 +57,11 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
: "${NODE_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||
cd release
|
||||
npmrc="$HOME/.npmrc"
|
||||
cleanup() { rm -f "$npmrc"; }
|
||||
trap cleanup EXIT
|
||||
printf '%s\n' \
|
||||
'registry=https://git.crash.work/api/packages/ShrinkSDK/npm/' \
|
||||
'//git.crash.work/api/packages/ShrinkSDK/npm/:_authToken=${NODE_AUTH_TOKEN}' > "$npmrc"
|
||||
npm publish --registry=https://git.crash.work/api/packages/ShrinkSDK/npm/
|
||||
npm publish --registry=https://git.crash.work/api/packages/ShrinkSDK/npm/
|
||||
|
||||
@@ -26,12 +26,17 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
machine_id_file="/root/.local/share/unity3d/Unity/.machine-id"
|
||||
if test -s "$machine_id_file"; then
|
||||
cat "$machine_id_file" > /etc/machine-id
|
||||
echo "Unity machine identity restored"
|
||||
fi
|
||||
git config --global url."https://ghfast.top/https://github.com/".insteadOf "https://github.com/"
|
||||
unity_bin="$(command -v unity-editor || command -v unity || command -v Unity || true)"
|
||||
test -n "$unity_bin"
|
||||
"$unity_bin" \
|
||||
-batchmode \
|
||||
-nographics \
|
||||
-quit \
|
||||
-projectPath "$PWD/Development~/UnityProject" \
|
||||
-runTests \
|
||||
-testPlatform EditMode \
|
||||
|
||||
+13
@@ -30,6 +30,16 @@
|
||||
/[Aa]ssets/Plugins/Editor/JetBrains*
|
||||
# Jetbrains Rider personal-layer settings
|
||||
*.DotSettings.user
|
||||
!DotNet~/*.csproj
|
||||
!DotNet~/**/*.csproj
|
||||
/DotNet~/**/[Bb]in/
|
||||
/DotNet~/**/[Oo]bj/
|
||||
/Godot~/**/[Bb]in/
|
||||
/Godot~/**/[Oo]bj/
|
||||
/artifacts/
|
||||
/packages/
|
||||
!DotNet~/**/*.csproj
|
||||
!Godot~/**/*.csproj
|
||||
|
||||
# Visual Studio cache directory
|
||||
.vs/
|
||||
@@ -41,6 +51,7 @@
|
||||
ExportedObj/
|
||||
.consulo/
|
||||
*.csproj
|
||||
!Tools~/DotNet/**/*.csproj
|
||||
*.unityproj
|
||||
*.sln
|
||||
*.suo
|
||||
@@ -107,3 +118,5 @@ InitTestScene*.unity*
|
||||
/Tools~/**/[Oo]bj/
|
||||
*.user
|
||||
*.DotSettings.user
|
||||
!DotNet~/*.csproj
|
||||
!DotNet~/**/*.csproj
|
||||
|
||||
@@ -6,3 +6,9 @@ Tools~/
|
||||
*.sln
|
||||
*.user
|
||||
*.DotSettings.user
|
||||
DotNet~/
|
||||
Godot~/
|
||||
NuGet.Config
|
||||
Directory.Build.props
|
||||
NuGet.Config.meta
|
||||
Directory.Build.props.meta
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
|
||||
本文件记录 `ShrinkEventBus` 在当前工作区中的包内变更。
|
||||
|
||||
## [2.0.1] - 2026-08-28
|
||||
|
||||
### Added
|
||||
|
||||
- `ShrinkEventSubscriberAttribute` 新增显式 `Lifetime`,选择 `AwakeToDestroy` 的 `MonoBehaviour` 会由 ILPostProcessor 在编译期织入生成绑定的 `Attach` 与 `Dispose`,禁用对象时保持订阅,销毁时自动释放。
|
||||
- 自动生命周期支持已有或缺失的 `Awake` / `OnDestroy`,并保留可重写基类生命周期调用;默认仍为 `Manual`,避免既有 2.0 使用方升级后重复订阅。
|
||||
|
||||
## [2.0.0] - 2026-08-23
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
using Mono.Cecil.Rocks;
|
||||
using Mono.Cecil.Pdb;
|
||||
using ShrinkShared.CodeGen;
|
||||
using Unity.CompilationPipeline.Common.Diagnostics;
|
||||
using Unity.CompilationPipeline.Common.ILPostProcessing;
|
||||
|
||||
@@ -15,515 +9,14 @@ namespace ShrinkEventBus.CodeGen
|
||||
{
|
||||
public sealed class EventBusILPostProcessor : ILPostProcessor
|
||||
{
|
||||
private const string RuntimeAssemblyName = "ShrinkEventBus.Runtime";
|
||||
public override ILPostProcessor GetInstance() => this;
|
||||
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
if (!ReferencesAssembly(compiledAssembly, RuntimeAssemblyName))
|
||||
return false;
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly) =>
|
||||
UnityShrinkCodeGenAdapter.ReferencesAny(compiledAssembly, "ShrinkEventBus.Runtime");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
var diagnostics = new List<DiagnosticMessage>();
|
||||
if (!WillProcess(compiledAssembly))
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
|
||||
var assemblyDefinition = AssemblyDefinitionFor(compiledAssembly);
|
||||
var module = assemblyDefinition.MainModule;
|
||||
|
||||
try
|
||||
{
|
||||
var generatedSubscriberType = FindType(module, "ShrinkEventBus.ShrinkEventSubscriberAttribute", RuntimeAssemblyName);
|
||||
var generatedSubscribeType = FindType(module, "ShrinkEventBus.ShrinkSubscribeAttribute", RuntimeAssemblyName);
|
||||
if (generatedSubscriberType == null || generatedSubscribeType == null)
|
||||
return GetResult(assemblyDefinition, diagnostics);
|
||||
|
||||
foreach (var type in GetAllTypes(module.Types)
|
||||
.Where(type => !type.IsInterface && !type.IsAbstract)
|
||||
.Where(type => HasAttribute(type, generatedSubscriberType))
|
||||
.Where(type => type.Methods.Any(method =>
|
||||
!method.IsStatic && HasAttribute(method, generatedSubscribeType))))
|
||||
{
|
||||
InjectGeneratedBinding(type, module, generatedSubscribeType);
|
||||
}
|
||||
|
||||
var staticSubscriberTypes = GetAllTypes(module.Types)
|
||||
.Where(type => HasAttribute(type, generatedSubscriberType))
|
||||
.Where(type => type.Methods.Any(method =>
|
||||
method.IsStatic && HasAttribute(method, generatedSubscribeType)))
|
||||
.ToArray();
|
||||
if (staticSubscriberTypes.Length > 0)
|
||||
InjectStaticBootstrap(module, staticSubscriberTypes, generatedSubscribeType);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics.Add(new DiagnosticMessage
|
||||
{
|
||||
DiagnosticType = DiagnosticType.Error,
|
||||
MessageData = $"[ShrinkEventBus.CodeGen] {ex.Message}"
|
||||
});
|
||||
}
|
||||
|
||||
return GetResult(assemblyDefinition, diagnostics);
|
||||
}
|
||||
|
||||
private static bool ReferencesAssembly(ICompiledAssembly compiledAssembly, string assemblyName)
|
||||
{
|
||||
return compiledAssembly.References.Any(reference =>
|
||||
string.Equals(Path.GetFileNameWithoutExtension(reference), assemblyName, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static bool HasAttribute(ICustomAttributeProvider provider, TypeReference expectedAttributeType)
|
||||
{
|
||||
return provider.CustomAttributes.Any(attribute => attribute.AttributeType.FullName == expectedAttributeType.FullName);
|
||||
}
|
||||
|
||||
private static IEnumerable<TypeDefinition> GetAllTypes(IEnumerable<TypeDefinition> roots)
|
||||
{
|
||||
foreach (var type in roots)
|
||||
{
|
||||
yield return type;
|
||||
foreach (var nested in GetAllTypes(type.NestedTypes))
|
||||
yield return nested;
|
||||
}
|
||||
}
|
||||
|
||||
private static void InjectGeneratedBinding(TypeDefinition type, ModuleDefinition module,
|
||||
TypeReference subscribeAttributeType)
|
||||
{
|
||||
var generatedInterface = FindType(module,
|
||||
"ShrinkEventBus.IShrinkGeneratedSubscriber", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkGeneratedSubscriber was not found.");
|
||||
if (type.Interfaces.Any(item => item.InterfaceType.FullName == generatedInterface.FullName))
|
||||
return;
|
||||
|
||||
var resolverType = FindType(module, "ShrinkEventBus.IShrinkBusResolver", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkBusResolver was not found.");
|
||||
var busKeyType = FindType(module, "ShrinkEventBus.ShrinkBusKey", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkBusKey was not found.");
|
||||
var bindingType = FindType(module, "ShrinkEventBus.ShrinkEventBinding", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkEventBinding was not found.");
|
||||
var bindingHelperType = FindType(module, "ShrinkEventBus.ShrinkGeneratedBinding", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkGeneratedBinding was not found.");
|
||||
var priorityType = FindType(module, "ShrinkEventBus.ShrinkEventPriority", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkEventPriority was not found.");
|
||||
var asyncHandlerType = FindType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkAsyncEventHandler was not found.");
|
||||
|
||||
var nullableBusKey = new GenericInstanceType(module.ImportReference(typeof(Nullable<>)));
|
||||
nullableBusKey.GenericArguments.Add(busKeyType);
|
||||
var disposableType = module.ImportReference(typeof(IDisposable));
|
||||
var bindingDefinition = bindingType.Resolve()
|
||||
?? throw new InvalidOperationException("ShrinkEventBinding could not be resolved.");
|
||||
var bindingCtor = module.ImportReference(bindingDefinition.Methods.Single(method =>
|
||||
method.IsConstructor && method.Parameters.Count == 0));
|
||||
var bindingAdd = module.ImportReference(bindingDefinition.Methods.Single(method =>
|
||||
method.Name == "Add" && method.Parameters.Count == 1));
|
||||
|
||||
var helperDefinition = bindingHelperType.Resolve()
|
||||
?? throw new InvalidOperationException("ShrinkGeneratedBinding could not be resolved.");
|
||||
var syncSubscribe = module.ImportReference(helperDefinition.Methods.Single(method =>
|
||||
method.Name == "Subscribe" && method.HasGenericParameters));
|
||||
var asyncSubscribe = module.ImportReference(helperDefinition.Methods.Single(method =>
|
||||
method.Name == "SubscribeAsync" && method.HasGenericParameters));
|
||||
var legacyAsyncSubscribe = module.ImportReference(helperDefinition.Methods.Single(method =>
|
||||
method.Name == "SubscribeAsyncLegacy" && method.HasGenericParameters));
|
||||
|
||||
var interfaceDefinition = generatedInterface.Resolve()
|
||||
?? throw new InvalidOperationException("IShrinkGeneratedSubscriber could not be resolved.");
|
||||
var interfaceMethod = module.ImportReference(interfaceDefinition.Methods.Single(method =>
|
||||
method.Name == "AttachGenerated"));
|
||||
|
||||
var generatedMethod = new MethodDefinition(
|
||||
"ShrinkEventBus.IShrinkGeneratedSubscriber.AttachGenerated",
|
||||
MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig |
|
||||
MethodAttributes.NewSlot | MethodAttributes.Virtual,
|
||||
disposableType);
|
||||
generatedMethod.Parameters.Add(new ParameterDefinition("resolver", ParameterAttributes.None, resolverType));
|
||||
generatedMethod.Parameters.Add(new ParameterDefinition("defaultBus", ParameterAttributes.Optional,
|
||||
nullableBusKey));
|
||||
generatedMethod.Overrides.Add(interfaceMethod);
|
||||
generatedMethod.Body.InitLocals = true;
|
||||
var bindingLocal = new VariableDefinition(bindingType);
|
||||
generatedMethod.Body.Variables.Add(bindingLocal);
|
||||
var il = generatedMethod.Body.GetILProcessor();
|
||||
il.Emit(OpCodes.Newobj, bindingCtor);
|
||||
il.Emit(OpCodes.Stloc, bindingLocal);
|
||||
|
||||
var classDefaultBus = ReadStringProperty(
|
||||
type.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == "ShrinkEventBus.ShrinkEventSubscriberAttribute"),
|
||||
"DefaultBus");
|
||||
|
||||
foreach (var handler in type.Methods.Where(method =>
|
||||
!method.IsStatic && HasAttribute(method, subscribeAttributeType)).ToArray())
|
||||
{
|
||||
EmitGeneratedSubscription(il, module, type, handler,
|
||||
handler.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == subscribeAttributeType.FullName),
|
||||
classDefaultBus, bindingLocal, bindingAdd, syncSubscribe, asyncSubscribe,
|
||||
legacyAsyncSubscribe, asyncHandlerType);
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ret);
|
||||
type.Interfaces.Add(new InterfaceImplementation(generatedInterface));
|
||||
type.Methods.Add(generatedMethod);
|
||||
}
|
||||
|
||||
private static void EmitGeneratedSubscription(ILProcessor il, ModuleDefinition module,
|
||||
TypeDefinition ownerType, MethodDefinition handler, CustomAttribute attribute,
|
||||
string classDefaultBus, VariableDefinition bindingLocal, MethodReference bindingAdd,
|
||||
MethodReference syncSubscribe, MethodReference asyncSubscribe,
|
||||
MethodReference legacyAsyncSubscribe, TypeReference asyncHandlerType)
|
||||
{
|
||||
if (handler.Parameters.Count is < 1 or > 2)
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} must have one event parameter and an optional CancellationToken.");
|
||||
|
||||
var eventType = module.ImportReference(handler.Parameters[0].ParameterType);
|
||||
var eventInterface = FindType(module, "ShrinkEventBus.IShrinkEvent", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkEvent was not found.");
|
||||
if (!ImplementsInterface(eventType, eventInterface.FullName))
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} event parameter must implement IShrinkEvent.");
|
||||
|
||||
var bus = ReadStringProperty(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus))
|
||||
bus = classDefaultBus;
|
||||
var priority = ReadIntProperty(attribute, "Priority", 2);
|
||||
var numericPriority = ReadIntProperty(attribute, "NumericPriority", 0);
|
||||
var receiveCanceled = ReadBoolProperty(attribute, "ReceiveCanceled", false);
|
||||
|
||||
MethodReference openSubscribe;
|
||||
TypeReference delegateType;
|
||||
if (handler.ReturnType.FullName == module.TypeSystem.Void.FullName && handler.Parameters.Count == 1)
|
||||
{
|
||||
openSubscribe = syncSubscribe;
|
||||
delegateType = MakeGenericType(module, typeof(Action<>), eventType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 1)
|
||||
{
|
||||
openSubscribe = legacyAsyncSubscribe;
|
||||
var uniTaskType = FindType(module, "Cysharp.Threading.Tasks.UniTask", "UniTask")
|
||||
?? module.ImportReference(handler.ReturnType);
|
||||
delegateType = MakeGenericType(module, typeof(Func<,>), eventType, uniTaskType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 2 &&
|
||||
handler.Parameters[1].ParameterType.FullName == typeof(System.Threading.CancellationToken).FullName)
|
||||
{
|
||||
openSubscribe = asyncSubscribe;
|
||||
var closedAsyncHandler = new GenericInstanceType(asyncHandlerType);
|
||||
closedAsyncHandler.GenericArguments.Add(eventType);
|
||||
delegateType = closedAsyncHandler;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Unsupported [ShrinkSubscribe] signature: {handler.FullName}. Use void(T), UniTask(T), or UniTask(T, CancellationToken).");
|
||||
}
|
||||
|
||||
var closedSubscribe = new GenericInstanceMethod(openSubscribe);
|
||||
closedSubscribe.GenericArguments.Add(eventType);
|
||||
var delegateCtor = MakeDelegateConstructor(module, delegateType);
|
||||
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldftn, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Newobj, delegateCtor);
|
||||
il.Emit(OpCodes.Ldc_I4, priority);
|
||||
il.Emit(OpCodes.Ldc_I4, numericPriority);
|
||||
il.Emit(receiveCanceled ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
|
||||
il.Emit(OpCodes.Call, closedSubscribe);
|
||||
il.Emit(OpCodes.Callvirt, bindingAdd);
|
||||
}
|
||||
|
||||
private static void InjectStaticBootstrap(ModuleDefinition module,
|
||||
IReadOnlyList<TypeDefinition> subscriberTypes, TypeReference subscribeAttributeType)
|
||||
{
|
||||
var registryType = FindType(module, "ShrinkEventBus.ShrinkStaticBindingRegistry", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkStaticBindingRegistry was not found.");
|
||||
var asyncHandlerType = FindType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("ShrinkAsyncEventHandler was not found.");
|
||||
var registryDefinition = registryType.Resolve()
|
||||
?? throw new InvalidOperationException("ShrinkStaticBindingRegistry could not be resolved.");
|
||||
var syncRegister = module.ImportReference(registryDefinition.Methods.Single(method =>
|
||||
method.Name == "Register" && method.HasGenericParameters));
|
||||
var asyncRegister = module.ImportReference(registryDefinition.Methods.Single(method =>
|
||||
method.Name == "RegisterAsync" && method.HasGenericParameters));
|
||||
var legacyAsyncRegister = module.ImportReference(registryDefinition.Methods.Single(method =>
|
||||
method.Name == "RegisterAsyncLegacy" && method.HasGenericParameters));
|
||||
|
||||
var bootstrap = new TypeDefinition("ShrinkEventBus.Generated",
|
||||
"ShrinkGeneratedStaticBindings",
|
||||
TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.NotPublic,
|
||||
module.TypeSystem.Object);
|
||||
module.Types.Add(bootstrap);
|
||||
|
||||
var register = new MethodDefinition("Register",
|
||||
MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig,
|
||||
module.TypeSystem.Void);
|
||||
bootstrap.Methods.Add(register);
|
||||
var il = register.Body.GetILProcessor();
|
||||
|
||||
foreach (var type in subscriberTypes)
|
||||
{
|
||||
var classDefaultBus = ReadStringProperty(
|
||||
type.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == "ShrinkEventBus.ShrinkEventSubscriberAttribute"),
|
||||
"DefaultBus");
|
||||
foreach (var handler in type.Methods.Where(method =>
|
||||
method.IsStatic && HasAttribute(method, subscribeAttributeType)).ToArray())
|
||||
{
|
||||
EmitStaticGeneratedSubscription(il, module, handler,
|
||||
handler.CustomAttributes.First(attribute =>
|
||||
attribute.AttributeType.FullName == subscribeAttributeType.FullName),
|
||||
classDefaultBus, syncRegister, asyncRegister,
|
||||
legacyAsyncRegister, asyncHandlerType);
|
||||
}
|
||||
}
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
InjectModuleInitializer(module, register);
|
||||
}
|
||||
|
||||
private static void EmitStaticGeneratedSubscription(ILProcessor il, ModuleDefinition module,
|
||||
MethodDefinition handler, CustomAttribute attribute, string classDefaultBus,
|
||||
MethodReference syncRegister, MethodReference asyncRegister,
|
||||
MethodReference legacyAsyncRegister, TypeReference asyncHandlerType)
|
||||
{
|
||||
if (handler.Parameters.Count is < 1 or > 2)
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} must have one event parameter and an optional CancellationToken.");
|
||||
|
||||
var eventType = module.ImportReference(handler.Parameters[0].ParameterType);
|
||||
var eventInterface = FindType(module, "ShrinkEventBus.IShrinkEvent", RuntimeAssemblyName)
|
||||
?? throw new InvalidOperationException("IShrinkEvent was not found.");
|
||||
if (!ImplementsInterface(eventType, eventInterface.FullName))
|
||||
throw new InvalidOperationException(
|
||||
$"[ShrinkSubscribe] method {handler.FullName} event parameter must implement IShrinkEvent.");
|
||||
|
||||
var bus = ReadStringProperty(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus))
|
||||
bus = classDefaultBus;
|
||||
var priority = ReadIntProperty(attribute, "Priority", 2);
|
||||
var numericPriority = ReadIntProperty(attribute, "NumericPriority", 0);
|
||||
var receiveCanceled = ReadBoolProperty(attribute, "ReceiveCanceled", false);
|
||||
|
||||
MethodReference openRegister;
|
||||
TypeReference delegateType;
|
||||
if (handler.ReturnType.FullName == module.TypeSystem.Void.FullName && handler.Parameters.Count == 1)
|
||||
{
|
||||
openRegister = syncRegister;
|
||||
delegateType = MakeGenericType(module, typeof(Action<>), eventType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 1)
|
||||
{
|
||||
openRegister = legacyAsyncRegister;
|
||||
var uniTaskType = FindType(module, "Cysharp.Threading.Tasks.UniTask", "UniTask")
|
||||
?? module.ImportReference(handler.ReturnType);
|
||||
delegateType = MakeGenericType(module, typeof(Func<,>), eventType, uniTaskType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" &&
|
||||
handler.Parameters.Count == 2 &&
|
||||
handler.Parameters[1].ParameterType.FullName == typeof(System.Threading.CancellationToken).FullName)
|
||||
{
|
||||
openRegister = asyncRegister;
|
||||
var closedAsyncHandler = new GenericInstanceType(asyncHandlerType);
|
||||
closedAsyncHandler.GenericArguments.Add(eventType);
|
||||
delegateType = closedAsyncHandler;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Unsupported static [ShrinkSubscribe] signature: {handler.FullName}.");
|
||||
}
|
||||
|
||||
var closedRegister = new GenericInstanceMethod(openRegister);
|
||||
closedRegister.GenericArguments.Add(eventType);
|
||||
var delegateCtor = MakeDelegateConstructor(module, delegateType);
|
||||
var handlerBridge = CreateStaticHandlerBridge(module, handler);
|
||||
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldnull);
|
||||
il.Emit(OpCodes.Ldftn, module.ImportReference(handlerBridge));
|
||||
il.Emit(OpCodes.Newobj, delegateCtor);
|
||||
il.Emit(OpCodes.Ldc_I4, priority);
|
||||
il.Emit(OpCodes.Ldc_I4, numericPriority);
|
||||
il.Emit(receiveCanceled ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
|
||||
il.Emit(OpCodes.Call, closedRegister);
|
||||
}
|
||||
|
||||
private static MethodDefinition CreateStaticHandlerBridge(ModuleDefinition module,
|
||||
MethodDefinition handler)
|
||||
{
|
||||
var bridge = new MethodDefinition(
|
||||
$"ShrinkEventBus.GeneratedStaticHandler_{handler.MetadataToken.ToInt32():X8}",
|
||||
MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig,
|
||||
module.ImportReference(handler.ReturnType));
|
||||
for (var i = 0; i < handler.Parameters.Count; i++)
|
||||
{
|
||||
var parameter = handler.Parameters[i];
|
||||
bridge.Parameters.Add(new ParameterDefinition(parameter.Name, parameter.Attributes,
|
||||
module.ImportReference(parameter.ParameterType)));
|
||||
}
|
||||
|
||||
var il = bridge.Body.GetILProcessor();
|
||||
for (var i = 0; i < bridge.Parameters.Count; i++)
|
||||
il.Emit(OpCodes.Ldarg, bridge.Parameters[i]);
|
||||
il.Emit(OpCodes.Call, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Ret);
|
||||
handler.DeclaringType.Methods.Add(bridge);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
private static void InjectModuleInitializer(ModuleDefinition module, MethodReference register)
|
||||
{
|
||||
var moduleType = module.Types.First(type => type.Name == "<Module>");
|
||||
var initializer = moduleType.Methods.FirstOrDefault(method => method.Name == ".cctor");
|
||||
if (initializer == null)
|
||||
{
|
||||
initializer = new MethodDefinition(".cctor",
|
||||
MethodAttributes.Private | MethodAttributes.Static |
|
||||
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
|
||||
MethodAttributes.RTSpecialName,
|
||||
module.TypeSystem.Void);
|
||||
initializer.Body.GetILProcessor().Emit(OpCodes.Ret);
|
||||
moduleType.Methods.Add(initializer);
|
||||
}
|
||||
|
||||
var processor = initializer.Body.GetILProcessor();
|
||||
processor.InsertBefore(initializer.Body.Instructions[0],
|
||||
processor.Create(OpCodes.Call, register));
|
||||
}
|
||||
|
||||
private static GenericInstanceType MakeGenericType(ModuleDefinition module, Type openType,
|
||||
params TypeReference[] arguments)
|
||||
{
|
||||
var result = new GenericInstanceType(module.ImportReference(openType));
|
||||
foreach (var argument in arguments)
|
||||
result.GenericArguments.Add(argument);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MethodReference MakeDelegateConstructor(ModuleDefinition module, TypeReference delegateType)
|
||||
{
|
||||
var ctor = new MethodReference(".ctor", module.TypeSystem.Void, delegateType)
|
||||
{
|
||||
HasThis = true,
|
||||
CallingConvention = MethodCallingConvention.Default
|
||||
};
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.Object));
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.IntPtr));
|
||||
return ctor;
|
||||
}
|
||||
|
||||
private static bool ImplementsInterface(TypeReference type, string interfaceFullName)
|
||||
{
|
||||
TypeDefinition? current;
|
||||
try
|
||||
{
|
||||
current = type.Resolve();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
while (current != null)
|
||||
{
|
||||
if (current.Interfaces.Any(item => item.InterfaceType.FullName == interfaceFullName))
|
||||
return true;
|
||||
try
|
||||
{
|
||||
current = current.BaseType?.Resolve();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string ReadStringProperty(CustomAttribute attribute, string name)
|
||||
{
|
||||
foreach (var property in attribute.Properties)
|
||||
{
|
||||
if (property.Name == name)
|
||||
return property.Argument.Value as string ?? string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static int ReadIntProperty(CustomAttribute attribute, string name, int defaultValue)
|
||||
{
|
||||
foreach (var property in attribute.Properties)
|
||||
{
|
||||
if (property.Name == name)
|
||||
return Convert.ToInt32(property.Argument.Value);
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private static bool ReadBoolProperty(CustomAttribute attribute, string name, bool defaultValue)
|
||||
{
|
||||
foreach (var property in attribute.Properties)
|
||||
{
|
||||
if (property.Name == name)
|
||||
return Convert.ToBoolean(property.Argument.Value);
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private static TypeReference? FindType(ModuleDefinition module, string fullName, string assemblyName)
|
||||
{
|
||||
var resolved = Type.GetType($"{fullName}, {assemblyName}", false);
|
||||
return resolved == null ? null : module.ImportReference(resolved);
|
||||
}
|
||||
|
||||
private static AssemblyDefinition AssemblyDefinitionFor(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
var assemblyResolver = new PostProcessorAssemblyResolver(compiledAssembly);
|
||||
var readerParameters = new ReaderParameters
|
||||
{
|
||||
SymbolStream = new MemoryStream(compiledAssembly.InMemoryAssembly.PdbData.ToArray()),
|
||||
SymbolReaderProvider = new PdbReaderProvider(),
|
||||
AssemblyResolver = assemblyResolver,
|
||||
ReflectionImporterProvider = new PostProcessorReflectionImporterProvider(),
|
||||
ReadingMode = ReadingMode.Immediate
|
||||
};
|
||||
|
||||
var assemblyDefinition = AssemblyDefinition.ReadAssembly(
|
||||
new MemoryStream(compiledAssembly.InMemoryAssembly.PeData.ToArray()),
|
||||
readerParameters);
|
||||
assemblyResolver.AddAssemblyDefinitionBeingOperatedOn(assemblyDefinition);
|
||||
return assemblyDefinition;
|
||||
}
|
||||
|
||||
private static ILPostProcessResult GetResult(AssemblyDefinition assemblyDefinition, List<DiagnosticMessage> diagnostics)
|
||||
{
|
||||
var pe = new MemoryStream();
|
||||
var pdb = new MemoryStream();
|
||||
assemblyDefinition.Write(pe, new WriterParameters
|
||||
{
|
||||
SymbolWriterProvider = new PdbWriterProvider(),
|
||||
SymbolStream = pdb,
|
||||
WriteSymbols = true
|
||||
});
|
||||
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), diagnostics);
|
||||
}
|
||||
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) =>
|
||||
WillProcess(compiledAssembly)
|
||||
? UnityShrinkCodeGenAdapter.Process(compiledAssembly, "ShrinkEventBus.CodeGen")
|
||||
: new ILPostProcessResult(compiledAssembly.InMemoryAssembly, new List<DiagnosticMessage>());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"name": "Unity.ShrinkEventBus.CodeGen",
|
||||
"rootNamespace": "ShrinkEventBus.CodeGen",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime"
|
||||
"ShrinkEventBus.Runtime",
|
||||
"Unity.ShrinkShared.CodeGen"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"com.unity.test-framework": "1.1.33",
|
||||
"com.cneicy.shrink-eventbus": "file:../../.."
|
||||
}
|
||||
"com.cneicy.shrink-eventbus": "file:../../..",
|
||||
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b"
|
||||
},
|
||||
"testables": [
|
||||
"com.cneicy.shrink-eventbus"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<Deterministic>true</Deterministic>
|
||||
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
||||
<Authors>ShrinkSDK</Authors>
|
||||
<Company>ShrinkSDK</Company>
|
||||
<RepositoryUrl>https://git.crash.work/ShrinkSDK</RepositoryUrl>
|
||||
<IncludeSymbols>true</IncludeSymbols>
|
||||
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bb9607b086e27c14c9be7469aac61d0d
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
<AssemblyName>ShrinkEventBus.Runtime</AssemblyName>
|
||||
<RootNamespace>ShrinkEventBus</RootNamespace>
|
||||
<PackageId>ShrinkSDK.EventBus</PackageId>
|
||||
<Version>2.1.0</Version>
|
||||
<Description>ShrinkSDK typed event bus runtime.</Description>
|
||||
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="..\Runtime\**\*.cs"
|
||||
Exclude="..\Runtime\ShrinkMonoEventScope.cs" />
|
||||
<PackageReference Include="UniTask" Version="2.5.10" />
|
||||
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.1.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<clear />
|
||||
<add key="ShrinkSDK" value="https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json" />
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
@@ -0,0 +1,32 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cc42bc8ffa8649949aa6d63f9a225d27
|
||||
PluginImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
iconMap: {}
|
||||
executionOrder: {}
|
||||
defineConstraints: []
|
||||
isPreloaded: 0
|
||||
isOverridable: 0
|
||||
isExplicitlyReferenced: 0
|
||||
validateReferences: 1
|
||||
platformData:
|
||||
- first:
|
||||
Any:
|
||||
second:
|
||||
enabled: 0
|
||||
settings: {}
|
||||
- first:
|
||||
Editor: Editor
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
DefaultValueInitialized: true
|
||||
- first:
|
||||
Windows Store Apps: WindowsStoreApps
|
||||
second:
|
||||
enabled: 1
|
||||
settings: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
ShrinkEventBus 2.0 是面向 Unity、普通 C# 宿主和 Entities/Burst 生产端的统一事件总线。运行时只有一种事件模型、一个订阅入口和一组发布 API;不同 Bus 只表达生命周期、所有权与调度策略。
|
||||
|
||||
Godot 和普通 .NET 项目安装 `ShrinkSDK.EventBus`;可打包源码位于 `DotNet~`,订阅注册由 `ShrinkSDK.CodeGen` 在构建时织入。
|
||||
|
||||
## 核心契约
|
||||
|
||||
```csharp
|
||||
@@ -80,7 +82,18 @@ Bus 解析顺序:方法 `Bus`、类型 `DefaultBus`、`Attach` 传入默认 Bu
|
||||
using var binding = EventBus.Attach(new PlayerHandlers());
|
||||
```
|
||||
|
||||
MonoBehaviour 不需要继承 SDK 基类。可自行在 `OnEnable/OnDisable` 中 Attach/Dispose,也可以在 GameObject 上添加 `ShrinkMonoEventScope`,由它统一绑定同对象或子层级中的生成 subscriber。
|
||||
MonoBehaviour 不需要继承 SDK 基类。需要从 `Awake` 持续订阅到 `OnDestroy` 时,可以显式选择编译期生命周期织入:
|
||||
|
||||
```csharp
|
||||
[ShrinkEventSubscriber(Lifetime = ShrinkSubscriberLifetime.AwakeToDestroy)]
|
||||
public sealed class PlayerHandlers : MonoBehaviour
|
||||
{
|
||||
[ShrinkSubscribe]
|
||||
private void OnJoined(PlayerJoinedEvent value) { }
|
||||
}
|
||||
```
|
||||
|
||||
默认 `Lifetime` 为 `Manual`,普通对象与由 Context、Scene 或 Mod 宿主管理的实例继续自行持有 `EventBus.Attach(...)` 返回的绑定。需要随启用状态反复订阅的 MonoBehaviour 可以自行在 `OnEnable/OnDisable` 中 Attach/Dispose,也可以在 GameObject 上添加 `ShrinkMonoEventScope`,由它统一绑定同对象或子层级中的生成 subscriber。
|
||||
|
||||
静态类型同样只使用特性:
|
||||
|
||||
|
||||
@@ -189,7 +189,11 @@ namespace ShrinkEventBus
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
UnityEngine.Debug.LogException(exception);
|
||||
#else
|
||||
System.Diagnostics.Trace.TraceError(exception.ToString());
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
@@ -206,15 +208,17 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkMainThreadScheduler : IShrinkBusScheduler
|
||||
{
|
||||
private readonly ShrinkSchedulerQueue _queue;
|
||||
private readonly IShrinkMainThreadDispatcher _dispatcher;
|
||||
private int _pumpScheduled;
|
||||
private int _disposed;
|
||||
|
||||
public ShrinkMainThreadScheduler(string name, ShrinkBusOptions options)
|
||||
{
|
||||
_queue = new ShrinkSchedulerQueue(name, options);
|
||||
_dispatcher = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => PlayerLoopHelper.IsMainThread;
|
||||
public bool IsOnSchedulerThread => _dispatcher.IsMainThread;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
@@ -276,12 +280,15 @@ namespace ShrinkEventBus
|
||||
{
|
||||
if (Interlocked.Exchange(ref _pumpScheduled, 1) != 0)
|
||||
return;
|
||||
UniTask.Void(PumpAsync);
|
||||
if (_dispatcher.TryPost(() => PumpAsync().Forget()))
|
||||
return;
|
||||
Interlocked.Exchange(ref _pumpScheduled, 0);
|
||||
ShrinkEventDiagnostics.LogException(new InvalidOperationException(
|
||||
"The configured main-thread dispatcher rejected an EventBus pump."));
|
||||
}
|
||||
|
||||
private async UniTaskVoid PumpAsync()
|
||||
private async UniTask PumpAsync()
|
||||
{
|
||||
await UniTask.SwitchToMainThread();
|
||||
try
|
||||
{
|
||||
while (_queue.TryDequeue(out var item))
|
||||
@@ -453,7 +460,8 @@ namespace ShrinkEventBus
|
||||
var waitMs = timeout == Timeout.InfiniteTimeSpan
|
||||
? Timeout.Infinite
|
||||
: Math.Max(0, (int)Math.Min(int.MaxValue, timeout.TotalMilliseconds));
|
||||
var stopped = await UniTask.RunOnThreadPool(() => _stopped.Wait(waitMs));
|
||||
var stopped = await Task.Run(() => _stopped.Wait(waitMs))
|
||||
.AsUniTask(useCurrentSynchronizationContext: false);
|
||||
if (!stopped)
|
||||
{
|
||||
_queue.DropPending();
|
||||
@@ -538,7 +546,7 @@ namespace ShrinkEventBus
|
||||
queue.DropPending();
|
||||
return;
|
||||
}
|
||||
await UniTask.Delay(1, ignoreTimeScale: true);
|
||||
await Task.Delay(1).AsUniTask(useCurrentSynchronizationContext: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,18 @@ using System;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public enum ShrinkSubscriberLifetime
|
||||
{
|
||||
Manual = 0,
|
||||
AwakeToDestroy = 1
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
||||
public sealed class ShrinkEventSubscriberAttribute : Attribute
|
||||
{
|
||||
public string OwnerId { get; set; } = string.Empty;
|
||||
public string DefaultBus { get; set; } = string.Empty;
|
||||
public ShrinkSubscriberLifetime Lifetime { get; set; } = ShrinkSubscriberLifetime.Manual;
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
"name": "ShrinkEventBus.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus",
|
||||
"references": [
|
||||
"UniTask"
|
||||
"UniTask",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"autoReferenced": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public static class ShrinkEventBusRuntime
|
||||
{
|
||||
private static IShrinkMainThreadDispatcher _mainThreadDispatcher = CreateDefaultDispatcher();
|
||||
|
||||
public static IShrinkMainThreadDispatcher MainThreadDispatcher =>
|
||||
Volatile.Read(ref _mainThreadDispatcher);
|
||||
|
||||
public static void ConfigureMainThreadDispatcher(IShrinkMainThreadDispatcher dispatcher)
|
||||
{
|
||||
if (dispatcher == null)
|
||||
throw new ArgumentNullException(nameof(dispatcher));
|
||||
Volatile.Write(ref _mainThreadDispatcher, dispatcher);
|
||||
}
|
||||
|
||||
private static IShrinkMainThreadDispatcher CreateDefaultDispatcher()
|
||||
{
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
return new ShrinkUnityMainThreadDispatcher();
|
||||
#else
|
||||
return new ShrinkSynchronizationContextDispatcher(
|
||||
SynchronizationContext.Current,
|
||||
Thread.CurrentThread.ManagedThreadId);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
internal sealed class ShrinkUnityMainThreadDispatcher : IShrinkMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => Cysharp.Threading.Tasks.PlayerLoopHelper.IsMainThread;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
Cysharp.Threading.Tasks.PlayerLoopHelper.AddContinuation(
|
||||
Cysharp.Threading.Tasks.PlayerLoopTiming.Update,
|
||||
action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#else
|
||||
internal sealed class ShrinkSynchronizationContextDispatcher : IShrinkMainThreadDispatcher
|
||||
{
|
||||
private readonly SynchronizationContext? _context;
|
||||
private readonly int _threadId;
|
||||
|
||||
public ShrinkSynchronizationContextDispatcher(SynchronizationContext? context, int threadId)
|
||||
{
|
||||
_context = context;
|
||||
_threadId = threadId;
|
||||
}
|
||||
|
||||
public bool IsMainThread => Thread.CurrentThread.ManagedThreadId == _threadId;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
if (IsMainThread)
|
||||
{
|
||||
action();
|
||||
return true;
|
||||
}
|
||||
if (_context == null)
|
||||
return false;
|
||||
_context.Post(static state => ((Action)state!).Invoke(), action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3badb120248f61b4e9af7b571431a681
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -14,6 +14,41 @@ namespace ShrinkEventBus.PlayMode.Tests
|
||||
public int Value { get; }
|
||||
}
|
||||
|
||||
internal readonly struct AwakeToDestroyEvent : IShrinkEvent
|
||||
{
|
||||
public AwakeToDestroyEvent(int value) => Value = value;
|
||||
public int Value { get; }
|
||||
}
|
||||
|
||||
[ShrinkEventSubscriber(
|
||||
DefaultBus = "game",
|
||||
Lifetime = ShrinkSubscriberLifetime.AwakeToDestroy)]
|
||||
internal sealed class AwakeToDestroyTarget : MonoBehaviour
|
||||
{
|
||||
public static int Sum { get; set; }
|
||||
public static int AwakeCalls { get; set; }
|
||||
public static int DestroyCalls { get; set; }
|
||||
|
||||
private void Awake() => AwakeCalls++;
|
||||
private void OnDestroy() => DestroyCalls++;
|
||||
|
||||
[ShrinkSubscribe]
|
||||
private void OnEvent(AwakeToDestroyEvent value) => Sum += value.Value;
|
||||
}
|
||||
|
||||
[ShrinkEventSubscriber(Lifetime = ShrinkSubscriberLifetime.AwakeToDestroy)]
|
||||
internal abstract class AbstractAwakeToDestroyTarget : MonoBehaviour
|
||||
{
|
||||
public static int Sum { get; set; }
|
||||
|
||||
[ShrinkSubscribe]
|
||||
private void OnEvent(AwakeToDestroyEvent value) => Sum += value.Value;
|
||||
}
|
||||
|
||||
internal sealed class ConcreteAwakeToDestroyTarget : AbstractAwakeToDestroyTarget
|
||||
{
|
||||
}
|
||||
|
||||
[ShrinkEventSubscriber(DefaultBus = "game")]
|
||||
internal sealed class MonoLifecycleTarget : MonoBehaviour
|
||||
{
|
||||
@@ -25,6 +60,53 @@ namespace ShrinkEventBus.PlayMode.Tests
|
||||
|
||||
public sealed class ShrinkMonoEventScopePlayModeTests
|
||||
{
|
||||
[UnityTest]
|
||||
public IEnumerator AwakeToDestroyLifetimeIsInjectedWithoutManualBinding()
|
||||
{
|
||||
AwakeToDestroyTarget.Sum = 0;
|
||||
AwakeToDestroyTarget.AwakeCalls = 0;
|
||||
AwakeToDestroyTarget.DestroyCalls = 0;
|
||||
var gameObject = new GameObject("ShrinkEventBus-AwakeToDestroy");
|
||||
var target = gameObject.AddComponent<AwakeToDestroyTarget>();
|
||||
|
||||
yield return null;
|
||||
Assert.IsInstanceOf<IShrinkGeneratedSubscriber>(target);
|
||||
Assert.AreEqual(1, AwakeToDestroyTarget.AwakeCalls);
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(3)).ToCoroutine();
|
||||
Assert.AreEqual(3, AwakeToDestroyTarget.Sum);
|
||||
|
||||
gameObject.SetActive(false);
|
||||
yield return null;
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(5)).ToCoroutine();
|
||||
Assert.AreEqual(8, AwakeToDestroyTarget.Sum,
|
||||
"AwakeToDestroy subscriptions must survive OnDisable.");
|
||||
|
||||
Object.Destroy(gameObject);
|
||||
yield return null;
|
||||
Assert.AreEqual(1, AwakeToDestroyTarget.DestroyCalls);
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(7)).ToCoroutine();
|
||||
Assert.AreEqual(8, AwakeToDestroyTarget.Sum,
|
||||
"The generated OnDestroy release must remove the subscription.");
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator AwakeToDestroyLifetimeSupportsAbstractSubscriberBasesWithoutLifecycleMethods()
|
||||
{
|
||||
AbstractAwakeToDestroyTarget.Sum = 0;
|
||||
var gameObject = new GameObject("ShrinkEventBus-AbstractAwakeToDestroy");
|
||||
var target = gameObject.AddComponent<ConcreteAwakeToDestroyTarget>();
|
||||
|
||||
yield return null;
|
||||
Assert.IsInstanceOf<IShrinkGeneratedSubscriber>(target);
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(11)).ToCoroutine();
|
||||
Assert.AreEqual(11, AbstractAwakeToDestroyTarget.Sum);
|
||||
|
||||
Object.Destroy(gameObject);
|
||||
yield return null;
|
||||
yield return EventBus.PostAsync(new AwakeToDestroyEvent(13)).ToCoroutine();
|
||||
Assert.AreEqual(11, AbstractAwakeToDestroyTarget.Sum);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator OnEnableAttachesAndOnDisableReleases()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
<AssemblyName>ShrinkEventBus.Core</AssemblyName>
|
||||
<RootNamespace>ShrinkEventBus</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="ShrinkEventBus.cs" />
|
||||
<Compile Include="Schedulers.cs" />
|
||||
<Compile Include="../../../Runtime/ShrinkEventContracts.cs" Link="Runtime/ShrinkEventContracts.cs" />
|
||||
<Compile Include="../../../Runtime/ShrinkEventAttributes.cs" Link="Runtime/ShrinkEventAttributes.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
<IncludeBuildOutput>false</IncludeBuildOutput>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<LangVersion>9.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../ShrinkEventBus.Core/ShrinkEventBus.Core.csproj" />
|
||||
<ProjectReference Include="../ShrinkEventBus.Generator/ShrinkEventBus.Generator.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "com.cneicy.shrink-eventbus",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.0",
|
||||
"displayName": "ShrinkEventBus",
|
||||
"description": "多 Bus、特性强类型注册、UniTask 调度与低分配发布的 Unity 事件总线。",
|
||||
"unity": "2022.3",
|
||||
@@ -9,7 +9,9 @@
|
||||
"licensesUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus/src/branch/main/LICENSE",
|
||||
"dependencies": {
|
||||
"com.cysharp.unitask": "2.5.10",
|
||||
"com.unity.nuget.mono-cecil": "1.11.4"
|
||||
"com.unity.nuget.mono-cecil": "1.11.4",
|
||||
"com.cneicy.shrink-shared-codegen": "0.1.1",
|
||||
"com.cneicy.shrink-runtime-abstractions": "0.1.0"
|
||||
},
|
||||
"keywords": [
|
||||
"eventbus",
|
||||
|
||||
Reference in New Issue
Block a user