diff --git a/.agents/skills/revit-toolkit-analyzers/SKILL.md b/.agents/skills/revit-toolkit-analyzers/SKILL.md deleted file mode 100644 index 72f6b2b..0000000 --- a/.agents/skills/revit-toolkit-analyzers/SKILL.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -name: revit-toolkit-analyzers -description: > - Author and extend the Roslyn tooling bundled in the Nice3point.Revit.Toolkit package: the incremental source generator that emits external-event boilerplate, the analyzers and code fixers that enforce its prerequisites, the RVTTK#### diagnostic catalog, and the dual-Roslyn packaging. - USE FOR: adding or changing a generator, analyzer, code fixer, or diagnostic in the Analyzers, CodeFixers, or SourceGenerators projects; assigning a diagnostic id; wiring the .Roslyn### twin projects and Directory.Roslyn.props; packaging the tooling into the analyzers/dotnet/roslyn paths; recording a rule in AnalyzerReleases. - DO NOT USE FOR: designing the runtime library types the generator emits against, such as the external-event classes and static contexts. -license: MIT ---- - -# Revit Toolkit Analyzers - -Nice3point.Revit.Toolkit ships Roslyn tooling inside the NuGet package: an incremental source generator that turns an `[ExternalEvent]`-annotated method into event properties, analyzers that enforce the annotation's prerequisites, and code fixers that resolve the diagnostics. -The generated API shape and the `RVTTK####` diagnostic ids are public surface; treat every id and generated name as a contract. -This skill covers authoring and extending that tooling; the generator and analyzers require `Microsoft.CodeAnalysis.CSharp`. - -## When to use - -- Adding or changing the `ExternalEventGenerator` entry point or its `ExternalEvents/Analysis` and `ExternalEvents/Emission` implementation. -- Adding a diagnostic to the `ExternalEventDiagnostics` catalog or a new analyzer or code fixer. -- Wiring a `.Roslyn###` twin project or editing `Directory.Roslyn.props`. -- Changing how the tooling assemblies pack into the `analyzers/dotnet/roslyn{4.14,5.0}` paths. - -## When not to use - -- Designing the runtime types the generator emits against (the external-event family, the static contexts). That is the library design contract, not the compiler tooling. - -## Architecture layout - -Public generator, analyzer, and code-fix entry points live at their project roots. -Their public namespaces remain stable. -Capability-specific implementation lives under the same subject name across projects, such as `ExternalEvents`. -The capability root holds its shared definitions; `Analysis` extracts and validates symbols, and `Emission` renders source. -The external-event diagnostic catalog lives in `Analyzers/ExternalEvents/ExternalEventDiagnostics.cs` and is linked into the other tooling projects. -Descriptor declarations follow diagnostic-ID order. - -`CSharp` holds language-specific symbol and source operations. -`Diagnostics` holds generator diagnostic reporting, and `IncrementalGeneration` holds value equality used by incremental pipelines. -These subjects have no dependency on `ExternalEvents`. -The public `EquatableArray` retains its existing `SourceGenerators.Models` namespace for compatibility; its file belongs to `IncrementalGeneration`. -Folders describe subjects rather than class forms; `Helpers`, `Extensions`, and `Models` are not storage categories. -New capabilities receive sibling subject folders instead of expanding the external-event implementation or a project-wide helper catalog. - -## Workflow - -### Step 1: Emit from the incremental generator - -`ExternalEventGenerator` is `[Generator(LanguageNames.CSharp)]` and implements `IIncrementalGenerator`. -It pipes matched methods with `ForAttributeWithMetadataName`, reports diagnostics, then registers source output. -Keep the pipeline incremental: extract into an equatable model in `ExternalEventExtractor`, and render text in `ExternalEventWriter`. - -```csharp -public void Initialize(IncrementalGeneratorInitializationContext context) -{ - var methodAnalyses = context.SyntaxProvider - .ForAttributeWithMetadataName( - ExternalEventTypeNames.ExternalEventAttribute.WithoutGlobalPrefix, - predicate: static (node, cancellationToken) => node is MethodDeclarationSyntax, - transform: static (syntaxContext, cancellationToken) => ExternalEventExtractor.AnalyzeMethod(syntaxContext, cancellationToken)); - - context.ReportDiagnostics(methodAnalyses.Select(static (methodAnalysis, cancellationToken) => methodAnalysis.Diagnostics)); - - var eventDefinitionsWithOptions = methodAnalyses - .Where(static methodAnalysis => methodAnalysis.Definition is not null) - .Select(static (methodAnalysis, cancellationToken) => methodAnalysis.Definition!) - .Combine(context.ParseOptionsProvider); - - context.RegisterSourceOutput(eventDefinitionsWithOptions, static (sourceProductionContext, generationInput) => - { - var (eventDefinition, _) = generationInput; - var generatedSource = ExternalEventWriter.GenerateSource(eventDefinition, useFieldKeyword: false, useLockType: false); - sourceProductionContext.AddSource(eventDefinition.HintName, SourceText.From(generatedSource, Encoding.UTF8)); - }); -} -``` - -Emit into the method's own namespace and a stable hint name derived from the type hierarchy, and treat every generated member name as public surface. -Never carry a `SyntaxNode`, `ISymbol`, or `Compilation` into the model; carry only equatable data. The pipeline then caches correctly. -Project consumer capabilities into equatable values before combining them with event definitions. -The `field` keyword depends on the consumer language version; `System.Threading.Lock` requires C# 13 or later and an accessible type in the consumer compilation. -Generated multi-parameter handlers use block-bodied lambdas, with a `return` statement for value-returning handlers. - -### Step 2: Register the diagnostic in the RVTTK catalog - -Diagnostics live in the internal `ExternalEventDiagnostics` catalog under the `ExternalEventGenerator` category, keyed by a `RVTTK####` id. -The shipped ids are `RVTTK0001` (returns `Task`), `RVTTK0002` (`async void`), `RVTTK0003` (generic), `RVTTK0004` (duplicate overloads), and `RVTTK0005` (containing type not partial). -Assign the next unused id, never reuse a retired one, and give it a title, a parameterized `messageFormat`, a category, and a severity. - -```csharp -public static readonly DiagnosticDescriptor ContainingTypeNotPartial = new( - id: "RVTTK0005", - title: "Containing type is not partial", - messageFormat: "The type '{0}' containing method '{1}' marked with [ExternalEvent] must be declared as partial", - category: "ExternalEventGenerator", - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true); -``` - -### Step 3: Report from the generator or a dedicated analyzer - -Choose the reporter by whether the check needs the full symbol model at edit time. -The generator's `ExternalEventExtractor.ValidateMethod` reports `RVTTK0001`, `RVTTK0003`, and `RVTTK0004` while building the model, returning `false` to skip emission. -`RVTTK0002` and `RVTTK0005` also have standalone analyzers (`AsyncVoidMethodAnalyzer`, `ContainingTypeNotPartialAnalyzer`); the IDE flags them live and a code fixer can attach. - -An analyzer resolves the attribute symbol once per compilation, then registers a symbol action. - -```csharp -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class AsyncVoidMethodAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics { get; } = [ExternalEventDiagnostics.AsyncVoidMethod]; - - public override void Initialize(AnalysisContext context) - { - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - context.EnableConcurrentExecution(); - - context.RegisterCompilationStartAction(static context => - { - var attributeSymbol = context.Compilation.GetTypeByMetadataName("Nice3point.Revit.Toolkit.External.ExternalEventAttribute"); - if (attributeSymbol is null) - { - return; - } - - context.RegisterSymbolAction(context => - { - if (context.Symbol is not IMethodSymbol { IsAsync: true, ReturnsVoid: true } methodSymbol) - { - return; - } - - if (!methodSymbol.HasAttribute(attributeSymbol)) - { - return; - } - - context.ReportDiagnostic(Diagnostic.Create( - descriptor: ExternalEventDiagnostics.AsyncVoidMethod, - location: methodSymbol.Locations[0], - messageArgs: methodSymbol.Name)); - }, SymbolKind.Method); - }); - } -} -``` - -Always call `ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None)` and `EnableConcurrentExecution()`, and bail out early when the attribute type is absent from the compilation. - -### Step 4: Add a code fixer when the fix is mechanical - -Add a fixer only when the violation resolves without a human decision. -A fixer is `[Shared]` and `[ExportCodeFixProvider(LanguageNames.CSharp)]`, lists the fixable id from the catalog, and returns `WellKnownFixAllProviders.BatchFixer`. - -```csharp -[Shared] -[ExportCodeFixProvider(LanguageNames.CSharp)] -public sealed class MakeTypePartialCodeFixer : CodeFixProvider -{ - private const string Title = "Make type partial"; - - public override ImmutableArray FixableDiagnosticIds { get; } = [ExternalEventDiagnostics.ContainingTypeNotPartial.Id]; - - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } - - public override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - var diagnostic = context.Diagnostics[0]; - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - var typeDeclaration = root!.FindNode(context.Span).FirstAncestorOrSelf(); - if (typeDeclaration is null) return; - - context.RegisterCodeFix( - CodeAction.Create( - title: Title, - createChangedDocument: cancellationToken => AddPartialModifier(context.Document, root, typeDeclaration, cancellationToken), - equivalenceKey: Title), - diagnostic); - } -} -``` - -Reference the fixable id through the catalog (`ExternalEventDiagnostics.X.Id`), never a string literal; an id can never drift between analyzer and fixer. - -### Step 5: Compile the same source against both Roslyn versions - -Every tooling project has a `.Roslyn###` twin that compiles the same source against an older Roslyn; the package works on older IDEs and SDKs. -`Directory.Roslyn.props` parses the suffix, links the base project's `.cs` files into the twin, and sets `ROSLYN*_OR_GREATER` constants. -Author the code once in the base project; the twin's csproj is empty except for the props import and a version-pinned `Microsoft.CodeAnalysis.CSharp`. - -```xml - - - - - - - -``` - -Guard any API that differs across Roslyn versions with the `ROSLYN5_0_0_OR_GREATER` / `ROSLYN4_14_0_OR_GREATER` constants, as `ExternalEventGenerator` does when it decides whether the `field` keyword is available. -Never copy source into a twin; `Directory.Roslyn.props` links it automatically via ``. - -### Step 6: Package into the version-specific analyzer paths - -The runtime library project is the only package-producing project. -It packs each tooling assembly into the matching Roslyn path; the right build loads per IDE and SDK. It references the tooling projects with `ReferenceOutputAssembly="false"` purely for build order. - -```xml - - -``` - -All tooling projects target `netstandard2.0` with `IsRoslynComponent=true` and `EnforceExtendedAnalyzerRules=true`, set in `Directory.Roslyn.props`. - -### Step 7: Record the rule, then test - -Add every new or changed rule to `AnalyzerReleases.Unshipped.md` in the analyzer project; the release-tracking analyzer fails the build otherwise. -The shipped ids are already in `AnalyzerReleases.Shipped.md`. - -```text -### New Rules - -Rule ID | Category | Severity | Notes ---------|----------|----------|------- -RVTTK0006 | ExternalEventGenerator | Warning | -``` - -Then cover the change in the tooling test projects and build. -Analyzer and fixer tests assert both the reported `RVTTK####` and the fixed source; generator tests drive the generator and verify the emitted source and diagnostics. - -```shell -dotnet run -c Release -``` - -## Validation - -- [ ] The generator stays incremental: only equatable data crosses into the model, and output goes to a stable hint name and namespace. -- [ ] A new diagnostic uses the next unused `RVTTK####` id in `ExternalEventDiagnostics`, with a title, parameterized message, category, and severity. -- [ ] Every analyzer configures generated-code analysis and concurrent execution and bails when the attribute type is absent. -- [ ] A code fixer is added only for a mechanical fix, is `[Shared]`/`[ExportCodeFixProvider]`, and references the fixable id through the catalog. -- [ ] Roslyn-version-specific APIs are guarded with `ROSLYN*_OR_GREATER`; no source is duplicated into a `.Roslyn###` twin. -- [ ] Each tooling assembly packs into both `analyzers/dotnet/roslyn5.0/cs` and `analyzers/dotnet/roslyn4.14/cs`. -- [ ] Every new or changed rule has an `AnalyzerReleases.Unshipped.md` entry and a test in the matching tooling test project. - -## Common Pitfalls - -| Pitfall | Correct approach | -|------------------------------------------------------------|--------------------------------------------------------------------------| -| Reusing or renumbering a retired `RVTTK####` id | Assign the next unused id; shipped ids are public surface. | -| Renaming a generated property or namespace | Generated names are public surface; deprecate, do not rename. | -| Capturing a symbol or `Compilation` in the generator model | Carry only equatable data; the incremental pipeline then caches. | -| Duplicating source into a `.Roslyn###` twin | Author once in the base project; the props file links the files. | -| A hard-coded diagnostic string in a code fixer | Reference `ExternalEventDiagnostics.X.Id`; analyzer and fixer stay in sync. | -| Skipping the `AnalyzerReleases.Unshipped.md` entry | Add every rule; release tracking fails the build without it. | -| Adding a code fixer for a fix that needs a human decision | Report the diagnostic only; fix mechanically resolvable cases. | diff --git a/.agents/skills/revit-toolkit-backward-compat/SKILL.md b/.agents/skills/revit-toolkit-backward-compat/SKILL.md deleted file mode 100644 index 0503e59..0000000 --- a/.agents/skills/revit-toolkit-backward-compat/SKILL.md +++ /dev/null @@ -1,145 +0,0 @@ ---- -name: revit-toolkit-backward-compat -description: > - Evolve the public surface of Nice3point.Revit.Toolkit without breaking downstream consumers: deprecate a renamed or replaced member with [Obsolete] with a JetBrains [CodeTemplate] auto-conversion, and treat both the generated API shape and the RVTTK#### diagnostic ids as stable public surface. - USE FOR: renaming, replacing, or removing any public type or member; adding an overload or parameter to a shipped API; changing a generated member name or a diagnostic id; recording the deprecation in the changelog. - DO NOT USE FOR: private implemetations and internal types. -license: MIT ---- - -# Revit Toolkit Backward Compatibility - -Nice3point.Revit.Toolkit is a public NuGet library with downstream consumers; a breaking change breaks other people's builds. -Never delete or change an existing public API; deprecate it and keep it working. -Public surface is broader than the hand-written types: the shape the source generator emits and the `RVTTK####` diagnostic ids the analyzers report are contracts too. - -## When to use - -- Renaming, replacing, or retiring a public type or member. -- Adding an overload or a parameter to an already shipped API. -- Changing a generated member name or introducing or renumbering a diagnostic id. -- Recording a deprecation or breaking change in the changelog. - -## Workflow - -### Step 1: Add, deprecate, but never change or delete - -The only safe evolutions are additive or a deprecation. - -- **Method signatures:** never change an existing signature; add a new overload. -- **Return types:** never change a return type. -- **Parameters:** add a new parameter only as optional, and only at the end of the list. -- **Renaming or removal:** use the deprecation pattern below and keep the old member functional indefinitely. - -### Step 2: Deprecate a member with [Obsolete] and [CodeTemplate] - -To rename or replace a member, mark the old one `[Obsolete]` with a message that names the replacement, and add a JetBrains `[CodeTemplate]`; ReSharper and Rider auto-convert call sites. -The obsolete member forwards to its replacement and stays functional. - -```csharp -[Obsolete("Use Application instead")] -[CodeTemplate( - searchTemplate: "UiApplication", - Message = "UiApplication is obsolete, use Application instead", - ReplaceTemplate = "Application", - ReplaceMessage = "Replace with Application")] -public UIApplication UiApplication => Application; -``` - -`searchTemplate` is the pattern ReSharper matches at a call site, and `ReplaceTemplate` is what it substitutes; `Message` shows on the obsolete member and `ReplaceMessage` on the quick-fix. - -### Step 3: Match the CodeTemplate placeholder to the member shape - -Use a `[CodeTemplate]` placeholder; the auto-conversion carries the call site's arguments and type arguments across. - -- Method arguments use `$args$` in both templates: - -```csharp -[Obsolete("Use RevitApiContext.BeginFailureSuppressionScope instead")] -[CodeTemplate( - searchTemplate: "Context.SuppressFailures($args$)", - Message = "Context.SuppressFailures is obsolete, use RevitApiContext.BeginFailureSuppressionScope with 'using' statement instead", - ReplaceTemplate = "RevitApiContext.BeginFailureSuppressionScope($args$)", - ReplaceMessage = "Replace with RevitApiContext.BeginFailureSuppressionScope")] -public static void SuppressFailures(bool resolveErrors = true) -{ - // original implementation kept intact -} -``` - -- Generic type arguments use a named placeholder such as `$T$`: - -```csharp -[Obsolete("Use BeginAssemblyResolveScope instead for automatic resource management")] -[CodeTemplate( - searchTemplate: "BeginAssemblyResolve<$T$>()", - Message = "BeginAssemblyResolve is obsolete. Use BeginAssemblyResolveScope with 'using' statement instead", - ReplaceTemplate = "BeginAssemblyResolveScope<$T$>()", - ReplaceMessage = "Replace with BeginAssemblyResolveScope")] -public static void BeginAssemblyResolve() -{ - BeginAssemblyResolveScope(typeof(T)); -} -``` - -Omit `[CodeTemplate]` only when there is no mechanical call-site rewrite, such as retiring a stateful method that a scope now replaces (`RestoreDialogs`), and still keep the member functional. - -### Step 4: Keep the obsolete member functional - -An obsolete member keeps calling the original implementation, or forwards to the property, field, or method it became. -It must not throw and must not silently change behavior; a consumer who has not migrated keeps building and running. -A simple rename forwards directly (`UiApplication => Application`); a replaced method forwards to the new API (`BeginAssemblyResolve` calls `BeginAssemblyResolveScope`). - -### Step 5: Deprecate a whole class the same way - -To replace a class, create the new type, mark the old one `[Obsolete]`, and keep it functional. -Keep `[PublicAPI]` on the deprecated class; its contract stays documented. - -```csharp -[PublicAPI] -[Obsolete("Use Nice3point.Revit.Toolkit.External.ExternalEvent class or ExternalEvent source-generator instead")] -public class ActionEventHandler : ExternalEventHandler -{ - // full implementation stays working -} -``` - -The static `Context` class shows the same pattern at scale: the type is `[Obsolete]` and every member carries its own `[Obsolete]` and `[CodeTemplate]` forwarding to `RevitContext`/`RevitApiContext`. - -### Step 6: Treat generated API and RVTTK ids as public surface - -The `[ExternalEvent]` generator's output and the analyzers' diagnostic ids are as much a contract as a hand-written method. - -- Never rename a generated property or record; renaming one is a breaking change for every consumer that references the generated name. -- Never renumber or reuse a shipped `RVTTK####` id; assign the next unused id for a new rule. -- Record every new or changed rule in `AnalyzerReleases.Unshipped.md`; the shipped ids stay in `AnalyzerReleases.Shipped.md`. - -### Step 7: Document, then verify - -Record every addition, deprecation, and behavior change in the current section of `CHANGELOG.md`, and add a migration example at the end of the section for any breaking change or deprecation. -Update the README and XML docs in the same change. -Then confirm the obsolete member still compiles and its callers still build. - -```shell -dotnet run -c Release -``` - -## Validation - -- [ ] No existing public signature, return type, or member name changed; new parameters are optional and appended. -- [ ] A renamed or replaced member carries `[Obsolete]` naming the replacement and a `[CodeTemplate]` whose placeholder matches the member shape (`$args$`, `$T$`). -- [ ] The obsolete member forwards to its replacement, stays functional, and neither throws nor changes behavior. -- [ ] A replaced class is `[Obsolete]` and still functional; the new class exists alongside it. -- [ ] No generated member name was renamed and no `RVTTK####` id was renumbered or reused; a new rule is recorded in `AnalyzerReleases.Unshipped.md`. -- [ ] The changelog, README, and XML docs record the change, with a migration example for any deprecation. - -## Common Pitfalls - -| Pitfall | Correct approach | -|----------------------------------------------------------|------------------------------------------------------------------------| -| Changing a method signature or return type in place | Add a new overload; leave the shipped one untouched. | -| Deleting or renaming a public member outright | Deprecate with `[Obsolete]` + `[CodeTemplate]` and keep it functional. | -| An obsolete member that throws or changes behavior | Forward to the replacement; unmigrated callers keep working. | -| Adding a required parameter to a shipped method | Add it as optional and only at the end, or add an overload. | -| Renaming a generated property or reusing a diagnostic id | Treat generated names and `RVTTK####` ids as public surface. | -| Deprecating without a changelog migration note | Record the change and add a migration example for the deprecation. | diff --git a/.agents/skills/revit-toolkit-internals/SKILL.md b/.agents/skills/revit-toolkit-internals/SKILL.md deleted file mode 100644 index 9cd6c10..0000000 --- a/.agents/skills/revit-toolkit-internals/SKILL.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -name: revit-toolkit-internals -description: > - Uphold the design contract of the Nice3point.Revit.Toolkit runtime library, that wraps the raw Revit add-in API. - USE FOR: adding or changing a runtime type in the External, External/Events, Options, Helpers, or Internal folders, or the static RevitApiContext/RevitContext; deciding where boilerplate lives and how a scope, handler, or context is shaped. - DO NOT USE FOR: authoring the bundled Roslyn analyzers, code fixers, or the source generator, which are a separate compiler tooling contract. -license: MIT ---- - -# Revit Toolkit Internals - -Nice3point.Revit.Toolkit removes add-in boilerplate by wrapping the awkward parts of the Revit API behind clean instance and static types. -The library adds ergonomics and lifecycle management, never new Revit behavior. -This skill is the design contract a maintainer upholds when adding or changing a runtime type. - -## When to use - -- Adding or changing a base class under `External/Commands` or `External/Applications`, an event type under `External/Events`, an option handler under `Options`, a helper under `Helpers`, or an accessor under `Internal`. -- Changing the static `RevitApiContext` or `RevitContext`, a `Begin...Scope()` operation, or a cross-thread handler. - -## When not to use - -- Authoring the bundled Roslyn analyzers, code fixers, or the `[ExternalEvent]` source generator. That is the compiler tooling contract with its own `RVTTK####` ids and dual-Roslyn packaging. - -## Workflow - -### Step 1: Choose instance base class or static context - -Model an add-in entry point as an **instance base class** the consumer inherits; model a global service as a **static class**. -A base class implements the Revit interface, marks the Revit-facing method `[EditorBrowsable(EditorBrowsableState.Never)]`, does the setup, and exposes a single `abstract` override; the consumer writes no plumbing. - -```csharp -[PublicAPI] -public abstract class ExternalCommand : IExternalCommand -{ - public UIApplication Application { get; private set; } = null!; - public Result Result { get; set; } = Result.Succeeded; - - [EditorBrowsable(EditorBrowsableState.Never)] - public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) - { - Application = commandData.Application; - using (ResolveHelper.BeginAssemblyResolveScope(GetType())) - { - Execute(); - } - return Result; - } - - public abstract void Execute(); -} -``` - -`RevitApiContext` (DB-level `Application`) and its subclass `RevitContext` (UI-level) are static, and their static constructors reflect against Revit internals. -Keep every consumer-visible entry point's boilerplate in the base class, never in the override. - -### Step 2: Model temporary state as a disposable Begin...Scope() - -A temporary state change (dialog suppression, failure suppression, assembly resolution, the API context) is a factory named `Begin...Scope()` that acquires the resource and returns an `IDisposable` reversing it. -Reference-count nested scopes under a `Lock`, and guard `Dispose` with `Interlocked.Exchange`; a double dispose is a no-op. - -```csharp -private static readonly Lock FailureLock = new(); -private static int _failureScopeCount; - -public static IDisposable BeginFailureSuppressionScope(bool resolveErrors = true) -{ - lock (FailureLock) - { - _suppressFailureErrors = resolveErrors; - if (_failureScopeCount++ == 0) - { - Application.FailuresProcessing += ResolveFailures; - } - } - - return new FailureSuppressionScope(); -} - -private sealed class FailureSuppressionScope : IDisposable -{ - private int _disposed; - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - - lock (FailureLock) - { - if (--_failureScopeCount == 0) - { - Application.FailuresProcessing -= ResolveFailures; - } - } - } -} -``` - -Name the factory for the action it begins (`BeginFailureSuppressionScope`, not `SuppressFailures`), and always unsubscribe from the Revit event when the last scope closes. - -### Step 3: Keep shared state thread-safe - -Every static context is reachable from any thread; all shared state is synchronized. -Use the `Lock` type for shared fields, keep lock sections minimal, track nested scopes with a counter mutated under the lock, and guard dispose flags with `Interlocked.Exchange`. -Read a shared value under the lock into a local before acting on it, as the failure and dialog resolvers do; do not touch the field outside the lock. - -### Step 4: Marshal cross-thread Revit work through an external event - -The Revit API may only be modified from the API context. -Wrap `Autodesk.Revit.UI.ExternalEvent`; a handler raised from any thread runs in the API context. Take a fast path that invokes the handler directly when already in API mode. - -```csharp -public override ExternalEventRequest Raise() -{ - if ((_options & ExternalEventOptions.AllowDirectInvocation) != 0 && RevitContext.IsRevitInApiMode) - { - Execute(RevitContext.UiApplication); - return ExternalEventRequest.Accepted; - } - - return base.Raise(); -} -``` - -Await completion with a `TaskCompletionSource` (see `AsyncExternalEvent.RaiseAsync`), and queue cross-thread work with a thread-safe structure such as `ConcurrentQueue` when a handler batches multiple actions. -The base `ExternalEventHandler` constructor creates the underlying Revit event inside `RevitContext.BeginApiContextScope()`; construction is valid off the API context. - -### Step 5: Pump messages with DispatcherFrame for async - -`async`/`await` inside a synchronous Revit command works by pumping a `DispatcherFrame`. -Complete the frame from a continuation scheduled on `TaskScheduler.Default`, not the UI synchronization context, or the continuation deadlocks against `PushFrame`. - -```csharp -public sealed override void Execute() -{ - var task = ExecuteAsync(); - if (task.IsCompleted) - { - task.GetAwaiter().GetResult(); - return; - } - - var frame = new DispatcherFrame(); - task.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default); - Dispatcher.PushFrame(frame); - task.GetAwaiter().GetResult(); -} -``` - -### Step 6: Confine native and reflection interop to Internal/ - -Reflection into Revit internals and native function-pointer marshaling stay non-public and never leak. -On modern runtimes the accessors use `[UnsafeAccessor]` (gated `#if NET8_0_OR_GREATER`, with a reflection fallback for the older target); function-pointer interop lives inside a private nested scope type. - -```csharp -internal static class UnsafeAccessors -{ - [UnsafeAccessor(UnsafeAccessorKind.Constructor)] - internal static extern Application CreateApplication(object proxy); -} -``` - -Never surface a pointer, delegate, or reflected member from `Internal/`; the API-context scope allocates and frees its native memory inside its own `Dispose`. - -### Step 7: Attribute the surface, gate the versions, then verify - -Mark every public class `[PublicAPI]`, every member Revit invokes but consumers must not call `[EditorBrowsable(EditorBrowsableState.Never)]`, and every read-only method `[Pure]`. -Wrap an option callback interface with ergonomic constructors, like `FamilyLoadOptions : IFamilyLoadOptions` and `DuplicateTypeNamesHandler : IDuplicateTypeNamesHandler`; keep the Revit-invoked method non-browsable. -Every type must compile under every declared `Debug.R20`..`R27` / `Release.R20`..`R27`; gate version-specific Revit APIs with `#if REVIT2024_OR_GREATER`-style directives and runtime features (`AssemblyLoadContext`, `UnsafeAccessor`) with `#if NET` or `#if NET8_0_OR_GREATER`. -Ship a test for the changed custom logic in `tests/Nice3point.Revit.Toolkit.Tests`, then build. - -```shell -dotnet test -c Debug.R27 -``` - -## Validation - -- [ ] Entry points are instance base classes with one `abstract` override; global contexts are static classes; boilerplate lives in the base, not the override. -- [ ] A temporary state change is a `Begin...Scope()` returning `IDisposable`, reference-counted under a `Lock`, with an `Interlocked.Exchange` dispose guard. -- [ ] All shared static state is synchronized; the Revit event is unsubscribed when the last scope closes. -- [ ] Cross-thread Revit work is marshaled through the external event with the API-mode fast path; async pumps a `DispatcherFrame` with a `TaskScheduler.Default` continuation. -- [ ] Reflection and native interop stay in `Internal/` and are never surfaced. -- [ ] Public classes carry `[PublicAPI]`, Revit callbacks `[EditorBrowsable(Never)]`, read-only methods `[Pure]`; every type compiles under every `Debug.RNN`/`Release.RNN`. -- [ ] A test covers the changed custom logic. - -## Common Pitfalls - -| Pitfall | Correct approach | -|----------------------------------------------------|------------------------------------------------------------------------------------| -| Putting Revit plumbing in the consumer's override | Keep setup in the base class; expose one `abstract` method. | -| A scope that forgets to reverse or double-reverses | Count under a `Lock` and guard `Dispose` with `Interlocked.Exchange`. | -| Touching a shared field outside the lock | Read it under the lock into a local, then act. | -| Calling the Revit API off the API context | Marshal through the external event; fast-path only when `IsRevitInApiMode`. | -| Completing the async frame on the UI context | Continue on `TaskScheduler.Default`; the UI context deadlocks against `PushFrame`. | -| Exposing a reflected member or native pointer | Keep it `internal` in `Internal/`; expose only the wrapped type. | -| A version-specific API without a compilation gate | Gate with `#if REVIT####_OR_GREATER` / `#if NET*` so every configuration compiles. | diff --git a/.claude/settings.json b/.claude/settings.json index 44706be..29fe611 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -15,13 +15,5 @@ }, "autoUpdate": true } - }, - "enabledPlugins": { - "dotnet@revit-skills": true, - "revit-testing@revit-skills": true, - "dotnet-msbuild@dotnet-agent-skills": true, - "dotnet-nuget@dotnet-agent-skills": true, - "dotnet-advanced@dotnet-agent-skills": true, - "dotnet-test@dotnet-agent-skills": true } } diff --git a/.claude/skills b/.claude/skills deleted file mode 120000 index 2b7a412..0000000 --- a/.claude/skills +++ /dev/null @@ -1 +0,0 @@ -../.agents/skills \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8967a20..28c57ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,34 @@ +# 2027.0.5 + +### External Applications + +#### No more failure dialog when Revit exits + +An add-in that awaits in `OnShutdownAsync`, for example the stop of a host, could end the Revit session with the **External Tool Failure** dialog and this exception in the journal: + +```text +System.InvalidOperationException: Cannot perform requested operation because the Dispatcher shut down. +``` + +The cause is Revit itself: it shuts down the WPF dispatcher of its thread after the main window closes, and `AsyncExternalApplication` waited for the task through that dispatcher. + +`OnShutdownAsync` completes in both states of the dispatcher, with no change to your code: + +```c# +public override async Task OnShutdownAsync() +{ + await _host.StopAsync(); + _host.Dispose(); +} +``` + +The code after an `await` runs on the Revit thread. +A dispatcher that has shut down cancels every operation posted to it, and `await Dispatcher.InvokeAsync(...)` throws `TaskCanceledException`: call that code directly. + +#### Fixes + +- `AsyncExternalApplication` and `AsyncExternalCommand` wait for the task when the dispatcher starts its shutdown during an `await`. Previously, the wait ended early and blocked the Revit thread. + # 2027.0.4 ### External Events diff --git a/build/appsettings.json b/build/appsettings.json index f1480ff..936e111 100644 --- a/build/appsettings.json +++ b/build/appsettings.json @@ -1,14 +1,14 @@ { "Build": { "Versions": { - "Release.R20": "2020.4.4", - "Release.R21": "2021.4.4", - "Release.R22": "2022.4.4", - "Release.R23": "2023.4.4", - "Release.R24": "2024.3.4", - "Release.R25": "2025.2.4", - "Release.R26": "2026.1.4", - "Release.R27": "2027.0.4" + "Release.R20": "2020.4.5", + "Release.R21": "2021.4.5", + "Release.R22": "2022.4.5", + "Release.R23": "2023.4.5", + "Release.R24": "2024.3.5", + "Release.R25": "2025.2.5", + "Release.R26": "2026.1.5", + "Release.R27": "2027.0.5" }, "OutputDirectory": "output" }, diff --git a/source/Nice3point.Revit.Toolkit/External/Applications/AsyncExternalApplication.cs b/source/Nice3point.Revit.Toolkit/External/Applications/AsyncExternalApplication.cs index 29b9f9d..47585ff 100644 --- a/source/Nice3point.Revit.Toolkit/External/Applications/AsyncExternalApplication.cs +++ b/source/Nice3point.Revit.Toolkit/External/Applications/AsyncExternalApplication.cs @@ -1,4 +1,4 @@ -using System.Windows.Threading; +using Nice3point.Revit.Toolkit.Internal; // ReSharper disable once CheckNamespace namespace Nice3point.Revit.Toolkit.External; @@ -8,13 +8,11 @@ namespace Nice3point.Revit.Toolkit.External; /// /// /// -/// Enables async/await patterns within Revit external applications while maintaining -/// execution on the Revit main thread. The Revit UI remains responsive during async operations -/// through dispatcher message pumping. +/// Enables async/await patterns within Revit external applications while maintaining execution on the Revit main thread. +/// The Revit UI remains responsive during async operations through dispatcher message pumping. /// /// -/// Ideal for I/O-bound operations such as HTTP requests, file operations, or database queries -/// during application startup and shutdown. +/// Ideal for I/O-bound operations such as HTTP requests, file operations, or database queries during application startup and shutdown. /// Revit API calls can be made before and after await points since execution resumes on the main thread. /// /// @@ -42,8 +40,14 @@ public abstract class AsyncExternalApplication : ExternalApplication /// Overload this method to execute some asynchronous tasks when Revit shuts down. /// /// - /// The method will not be executed if the value of the property in the - /// method is different from . + /// + /// The method will not be executed if the value of the property in the method is different from . + /// + /// + /// Revit shuts down the WPF dispatcher of its thread after the main window unloads, which can precede this method. + /// The code after an runs on the Revit thread in both states of the dispatcher. + /// A dispatcher that has shut down cancels every operation posted to it. + /// /// public virtual Task OnShutdownAsync() { @@ -55,7 +59,7 @@ public virtual Task OnShutdownAsync() /// public sealed override void OnStartup() { - ExecuteAsync(OnStartupAsync); + MessagePump.Run(OnStartupAsync); } /// @@ -63,28 +67,6 @@ public sealed override void OnStartup() /// public sealed override void OnShutdown() { - ExecuteAsync(OnShutdownAsync); - } - - private static void ExecuteAsync(Func asyncMethod) - { - var task = asyncMethod(); - if (task.IsCompleted) - { - //Rethrow exceptions - task.GetAwaiter().GetResult(); - return; - } - - var frame = new DispatcherFrame(); - - // TaskScheduler.Default ensures continuation runs on ThreadPool, not UI thread. - // Prevents deadlock: if continuation ran on UI thread via SynchronizationContext, - // it would wait for PushFrame to finish, which waits for continuation - deadlock. - task.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default); - - Dispatcher.PushFrame(frame); - - task.GetAwaiter().GetResult(); + MessagePump.Run(OnShutdownAsync); } } diff --git a/source/Nice3point.Revit.Toolkit/External/Commands/AsyncExternalCommand.cs b/source/Nice3point.Revit.Toolkit/External/Commands/AsyncExternalCommand.cs index ab47821..99fb856 100644 --- a/source/Nice3point.Revit.Toolkit/External/Commands/AsyncExternalCommand.cs +++ b/source/Nice3point.Revit.Toolkit/External/Commands/AsyncExternalCommand.cs @@ -1,4 +1,4 @@ -using System.Windows.Threading; +using Nice3point.Revit.Toolkit.Internal; // ReSharper disable once CheckNamespace namespace Nice3point.Revit.Toolkit.External; @@ -8,9 +8,8 @@ namespace Nice3point.Revit.Toolkit.External; /// /// /// -/// Enables async/await patterns within Revit external commands while maintaining -/// execution on the Revit main thread. The Revit UI remains responsive during async operations -/// through dispatcher message pumping. +/// Enables async/await patterns within Revit external commands while maintaining execution on the Revit main thread. +/// The Revit UI remains responsive during async operations through dispatcher message pumping. /// /// /// Ideal for I/O-bound operations such as HTTP requests, file operations, or database queries. @@ -54,23 +53,6 @@ public abstract class AsyncExternalCommand : ExternalCommand /// public sealed override void Execute() { - var task = ExecuteAsync(); - if (task.IsCompleted) - { - //Rethrow exceptions - task.GetAwaiter().GetResult(); - return; - } - - var frame = new DispatcherFrame(); - - // TaskScheduler.Default ensures continuation runs on ThreadPool, not UI thread. - // Prevents deadlock: if continuation ran on UI thread via SynchronizationContext, - // it would wait for PushFrame to finish, which waits for continuation - deadlock. - task.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default); - - Dispatcher.PushFrame(frame); - - task.GetAwaiter().GetResult(); + MessagePump.Run(ExecuteAsync); } } diff --git a/source/Nice3point.Revit.Toolkit/Internal/MessagePump.cs b/source/Nice3point.Revit.Toolkit/Internal/MessagePump.cs new file mode 100644 index 0000000..1b21ad7 --- /dev/null +++ b/source/Nice3point.Revit.Toolkit/Internal/MessagePump.cs @@ -0,0 +1,232 @@ +using System.Collections.Concurrent; +using System.Windows.Threading; +using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.UI.WindowsAndMessaging; + +namespace Nice3point.Revit.Toolkit.Internal; + +/// +/// Provides the synchronous wait that pumps the messages of the calling thread until an asynchronous method completes. +/// +/// +/// Revit shuts down the WPF dispatcher of its thread after the main window unloads, and the dispatcher pumps no from that moment. +/// +internal static class MessagePump +{ + /// + /// Runs an asynchronous method on the calling thread and pumps the messages of the thread until the method completes. + /// + /// The asynchronous method to run. + /// + /// + /// A thread with a running dispatcher pumps a . + /// The frame continues when the dispatcher starts its shutdown, and the dispatcher finishes the shutdown after the frame exits. + /// + /// + /// A thread whose dispatcher has shut down runs the continuations of the method on the calling thread and dispatches the window messages of the thread. + /// + /// + /// The method rethrows the exception of the asynchronous method. + /// + /// + public static void Run(Func asyncMethod) + { + if (Dispatcher.CurrentDispatcher.HasShutdownFinished) + { + RunWithoutDispatcher(asyncMethod); + return; + } + + var task = asyncMethod(); + if (!task.IsCompleted) + { + // A frame that exits on the shutdown request of the dispatcher returns before the task completes. + // The blocking wait after it deadlocks against the continuation posted to this thread. + var frame = new DispatcherFrame(false); + + // TaskScheduler.Default runs the continuation on the thread pool. + // A continuation scheduled on the synchronization context of this thread deadlocks against the frame. + task.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default); + + Dispatcher.PushFrame(frame); + } + + // Rethrows the exception of a faulted task. + task.GetAwaiter().GetResult(); + } + + /// + /// Runs an asynchronous method on a thread whose dispatcher has shut down. + /// + /// The asynchronous method to run. + /// + /// A dispatcher that has shut down aborts every operation posted to it, including the continuations of a . + /// The method installs a for the duration of the call and restores the previous context afterward. + /// + private static void RunWithoutDispatcher(Func asyncMethod) + { + var previousContext = SynchronizationContext.Current; + using var context = new CallbackQueueSynchronizationContext(); + + SynchronizationContext.SetSynchronizationContext(context); + try + { + var task = asyncMethod(); + if (!task.IsCompleted) + { + context.RunCallbacks(task); + } + + // Rethrows the exception of a faulted task. + task.GetAwaiter().GetResult(); + } + finally + { + SynchronizationContext.SetSynchronizationContext(previousContext); + } + } + + /// + /// Represents a synchronization context that queues the posted callbacks and runs them on the thread that created it. + /// + private sealed class CallbackQueueSynchronizationContext : SynchronizationContext, IDisposable + { + private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> _callbacks = new(); + private readonly AutoResetEvent _signal = new(false); + private readonly Lock _signalLock = new(); + private readonly int _threadId = Environment.CurrentManagedThreadId; + private bool _disposed; + + /// + public override void Post(SendOrPostCallback callback, object? state) + { + _callbacks.Enqueue((callback, state)); + Signal(); + } + + /// + /// Another thread sends the callback. + /// The context runs a callback sent from its own thread inline. + public override void Send(SendOrPostCallback callback, object? state) + { + if (Environment.CurrentManagedThreadId != _threadId) + { + throw new NotSupportedException("A synchronous callback must be sent from the thread that created the synchronization context."); + } + + callback(state); + } + + /// + public override SynchronizationContext CreateCopy() + { + return this; + } + + /// + /// Runs the posted callbacks and dispatches the window messages of the calling thread until a task completes. + /// + /// The task that ends the wait. + /// + /// The method removes a WM_QUIT message from the queue for the duration of the wait and posts it again before it returns. + /// + public void RunCallbacks(Task task) + { + // A task completed by another thread posts no callback to the queue. + task.ContinueWith(_ => Signal(), TaskScheduler.Default); + + int? exitCode = null; + try + { + while (true) + { + while (_callbacks.TryDequeue(out var callback)) + { + callback.Callback(callback.State); + } + + if (task.IsCompleted) + { + return; + } + + if (WaitForSignalOrMessages()) + { + DispatchMessages(ref exitCode); + } + } + } + finally + { + if (exitCode is not null) + { + PInvoke.PostQuitMessage(exitCode.Value); + } + } + } + + /// + public void Dispose() + { + lock (_signalLock) + { + _disposed = true; + _signal.Dispose(); + } + } + + /// + /// Wakes the thread that waits in . + /// + /// + /// A disposed context ignores the call: a callback posted after the asynchronous method completes never runs. + /// + private void Signal() + { + lock (_signalLock) + { + if (!_disposed) + { + _signal.Set(); + } + } + } + + /// + /// Blocks the calling thread until the context is signaled or the message queue of the thread has input. + /// + /// if the message queue has input; otherwise, . + private unsafe bool WaitForSignalOrMessages() + { + var signal = (HANDLE)_signal.SafeWaitHandle.DangerousGetHandle(); + var waitEvent = PInvoke.MsgWaitForMultipleObjectsEx( + 1, + &signal, + PInvoke.INFINITE, + QUEUE_STATUS_FLAGS.QS_ALLINPUT, + MSG_WAIT_FOR_MULTIPLE_OBJECTS_EX_FLAGS.MWMO_INPUTAVAILABLE); + + return waitEvent == WAIT_EVENT.WAIT_OBJECT_0 + 1; + } + + /// + /// Dispatches every message in the queue of the calling thread. + /// + /// When this method returns, contains the exit code of the WM_QUIT message if the queue had one. + private static void DispatchMessages(ref int? exitCode) + { + while (PInvoke.PeekMessage(out var message, HWND.Null, 0, 0, PEEK_MESSAGE_REMOVE_TYPE.PM_REMOVE)) + { + if (message.message == PInvoke.WM_QUIT) + { + exitCode = (int)message.wParam.Value; + continue; + } + + PInvoke.TranslateMessage(message); + PInvoke.DispatchMessage(message); + } + } + } +} diff --git a/source/Nice3point.Revit.Toolkit/NativeMethods.txt b/source/Nice3point.Revit.Toolkit/NativeMethods.txt index 98a664f..ec5b771 100644 --- a/source/Nice3point.Revit.Toolkit/NativeMethods.txt +++ b/source/Nice3point.Revit.Toolkit/NativeMethods.txt @@ -1,5 +1,12 @@ +DispatchMessage FindWindowEx GetCurrentThreadId GetWindowThreadProcessId +INFINITE +MsgWaitForMultipleObjectsEx +PeekMessage PostMessage +PostQuitMessage RegisterWindowMessage +TranslateMessage +WM_QUIT diff --git a/tests/Nice3point.Revit.Toolkit.Tests/AsyncExternalApplicationTests.cs b/tests/Nice3point.Revit.Toolkit.Tests/AsyncExternalApplicationTests.cs new file mode 100644 index 0000000..e1f756a --- /dev/null +++ b/tests/Nice3point.Revit.Toolkit.Tests/AsyncExternalApplicationTests.cs @@ -0,0 +1,297 @@ +using System.Windows.Threading; +using Nice3point.Revit.Toolkit.External; +using Nice3point.TUnit.Revit; +using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.UI.WindowsAndMessaging; + +namespace Nice3point.Revit.Toolkit.Tests; + +public sealed class AsyncExternalApplicationTests : RevitApiUiTest +{ + private const int QuitExitCode = 7; + private const uint TimerIntervalMilliseconds = 10; + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherRunning_ContinuesOnTheCallingThread(CancellationToken cancellationToken) + { + // Act + var (callingThreadId, continuationThreadId) = await RunOnDispatcherThreadAsync(static () => + { + var continuationThreadId = 0; + var application = new TestApplication(async () => + { + await Task.Yield(); + continuationThreadId = Environment.CurrentManagedThreadId; + }); + + SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher)); + application.OnShutdown(); + + return (Environment.CurrentManagedThreadId, continuationThreadId); + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(continuationThreadId).IsEqualTo(callingThreadId); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutdownPending_ContinuesOnTheCallingThread(CancellationToken cancellationToken) + { + // Act + var (callingThreadId, continuationThreadId) = await RunOnDispatcherThreadAsync(static () => + { + var continuationThreadId = 0; + var dispatcher = Dispatcher.CurrentDispatcher; + var application = new TestApplication(async () => + { + await Task.Yield(); + continuationThreadId = Environment.CurrentManagedThreadId; + }); + + SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(dispatcher)); + dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal); + application.OnShutdown(); + + return (Environment.CurrentManagedThreadId, continuationThreadId); + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(continuationThreadId).IsEqualTo(callingThreadId).Because("the frame continues after the dispatcher starts its shutdown"); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutdownPending_FinishesTheDispatcherShutdown(CancellationToken cancellationToken) + { + // Act + var hasShutdownFinished = await RunOnDispatcherThreadAsync(static () => + { + var dispatcher = Dispatcher.CurrentDispatcher; + var application = new TestApplication(static async () => await Task.Yield()); + + SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(dispatcher)); + dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal); + application.OnShutdown(); + + return dispatcher.HasShutdownFinished; + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(hasShutdownFinished).IsTrue(); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutDown_ContinuesOnTheCallingThread(CancellationToken cancellationToken) + { + // Act + var (callingThreadId, continuationThreadId) = await RunOnDispatcherThreadAsync(static () => + { + var continuationThreadId = 0; + var application = new TestApplication(async () => + { + await Task.Yield(); + continuationThreadId = Environment.CurrentManagedThreadId; + }); + + Dispatcher.CurrentDispatcher.InvokeShutdown(); + application.OnShutdown(); + + return (Environment.CurrentManagedThreadId, continuationThreadId); + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(continuationThreadId).IsEqualTo(callingThreadId); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutDownAndTaskCompletedByAnotherThread_ReturnsAfterTheTask(CancellationToken cancellationToken) + { + // Act + var isShutdownCompleted = await RunOnDispatcherThreadAsync(() => + { + var isShutdownCompleted = false; + var application = new TestApplication(async () => + { + await Task.Run(static () => { }, cancellationToken).ConfigureAwait(false); + isShutdownCompleted = true; + }); + + Dispatcher.CurrentDispatcher.InvokeShutdown(); + application.OnShutdown(); + + return isShutdownCompleted; + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(isShutdownCompleted).IsTrue(); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutDown_RestoresTheSynchronizationContext(CancellationToken cancellationToken) + { + // Act + var (previousContext, restoredContext) = await RunOnDispatcherThreadAsync(static () => + { + var previousContext = new SynchronizationContext(); + var application = new TestApplication(static async () => await Task.Yield()); + + SynchronizationContext.SetSynchronizationContext(previousContext); + Dispatcher.CurrentDispatcher.InvokeShutdown(); + application.OnShutdown(); + + return (previousContext, SynchronizationContext.Current); + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(restoredContext).IsSameReferenceAs(previousContext); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutDown_RethrowsTheShutdownException(CancellationToken cancellationToken) + { + // Act + var shutdownTask = RunOnDispatcherThreadAsync(static () => + { + var application = new TestApplication(static async () => + { + await Task.Yield(); + throw new InvalidOperationException("The shutdown failed."); + }); + + Dispatcher.CurrentDispatcher.InvokeShutdown(); + application.OnShutdown(); + + return true; + }); + + // Assert + await Assert.That(() => shutdownTask.WaitAsync(cancellationToken)) + .Throws() + .WithMessage("The shutdown failed."); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutDown_DispatchesTheWindowMessages(CancellationToken cancellationToken) + { + // Act + var isTimerMessageDispatched = await RunOnDispatcherThreadAsync(static () => + { + Dispatcher.CurrentDispatcher.InvokeShutdown(); + + return ShutdownAfterTimerMessage(); + }).WaitAsync(cancellationToken); + + // Assert + await Assert.That(isTimerMessageDispatched).IsTrue(); + } + + [Test] + [Timeout(10_000)] + public async Task OnShutdown_DispatcherShutDownAndQuitMessageInTheQueue_PostsTheQuitMessageAgain(CancellationToken cancellationToken) + { + // Act + var (hasQuitMessage, exitCode) = await RunOnDispatcherThreadAsync(static () => + { + Dispatcher.CurrentDispatcher.InvokeShutdown(); + TestPInvoke.PostQuitMessage(QuitExitCode); + + ShutdownAfterTimerMessage(); + + var hasQuitMessage = TestPInvoke.PeekMessage(out var message, HWND.Null, TestPInvoke.WM_QUIT, TestPInvoke.WM_QUIT, PEEK_MESSAGE_REMOVE_TYPE.PM_REMOVE); + return ((bool)hasQuitMessage, (int)message.wParam.Value); + }).WaitAsync(cancellationToken); + + // Assert + using (Assert.Multiple()) + { + await Assert.That(hasQuitMessage).IsTrue(); + await Assert.That(exitCode).IsEqualTo(QuitExitCode); + } + } + + /// + /// Shuts down an application that awaits the timer message of the calling thread. + /// + /// if the shutdown completed after the timer message; otherwise, . + /// + /// DispatchMessage calls the timer procedure: the shutdown never completes on a thread that dispatches no window messages. + /// + private static bool ShutdownAfterTimerMessage() + { + var isShutdownCompleted = false; + var timerMessage = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var application = new TestApplication(async () => + { + await timerMessage.Task; + isShutdownCompleted = true; + }); + + TIMERPROC timerProcedure = (_, _, _, _) => timerMessage.TrySetResult(true); + var timerId = TestPInvoke.SetTimer(HWND.Null, 0, TimerIntervalMilliseconds, timerProcedure); + try + { + application.OnShutdown(); + } + finally + { + TestPInvoke.KillTimer(HWND.Null, timerId); + GC.KeepAlive(timerProcedure); + } + + return isShutdownCompleted; + } + + /// + /// Runs a function on a new STA thread, which has a WPF dispatcher of its own. + /// + /// The type of the function result. + /// The function to run. + /// + /// A task that represents the asynchronous run operation. + /// The task result contains the result of the function. + /// + private static Task RunOnDispatcherThreadAsync(Func function) + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thread = new Thread(() => + { + try + { + completion.SetResult(function()); + } + catch (Exception exception) + { + completion.SetException(exception); + } + }) + { + IsBackground = true + }; + + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + + return completion.Task; + } + + private sealed class TestApplication(Func shutdown) : AsyncExternalApplication + { + public override Task OnStartupAsync() + { + return Task.CompletedTask; + } + + public override Task OnShutdownAsync() + { + return shutdown(); + } + } +} diff --git a/tests/Nice3point.Revit.Toolkit.Tests/NativeMethods.txt b/tests/Nice3point.Revit.Toolkit.Tests/NativeMethods.txt index 65bb2d2..9522a09 100644 --- a/tests/Nice3point.Revit.Toolkit.Tests/NativeMethods.txt +++ b/tests/Nice3point.Revit.Toolkit.Tests/NativeMethods.txt @@ -1,2 +1,7 @@ GetClientRect +KillTimer +PeekMessage +PostQuitMessage PrintWindow +SetTimer +WM_QUIT