using System;
using System.Runtime.InteropServices;
using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.Windows;
using TerraFX.Interop.WinRT;
using Windows.Graphics.Effects;
namespace ComputeSharp.D2D1.Uwp.Helpers;
///
/// A helper type to replicate Win2D's ResourceManager type.
///
///
/// This type provides an entry point to use the Win2D activation factory.
///
internal static class ResourceManager
{
///
/// Gets or creates an instance for a native resource.
///
/// The input canvas device (as a marshalled ).
/// The input native resource to create a wrapper for.
/// The realization DPIs for
/// The resulting wrapper instance.
/// Thrown if the managed wrapper could not be retrieved.
public static unsafe IGraphicsEffectSource GetOrCreate(ICanvasDevice* device, IUnknown* resource, float dpi)
{
using ComPtr canvasFactoryNative = default;
const string activatableClassId = "Microsoft.Graphics.Canvas.CanvasDevice";
fixed (char* pActivatableClassId = activatableClassId)
{
HSTRING_HEADER hStringHeaderActivatableClassId;
HSTRING hStringActivatableClass;
// Create a fast-pass HSTRING for "Microsoft.Graphics.Canvas.CanvasDevice"
WinRT.WindowsCreateStringReference(
sourceString: (ushort*)pActivatableClassId,
length: (uint)activatableClassId.Length,
hstringHeader: &hStringHeaderActivatableClassId,
@string: &hStringActivatableClass).Assert();
Guid canvasFactoryNativeId = typeof(ICanvasFactoryNative).GUID;
// Get the activation factory for CanvasDevice
WinRT.RoGetActivationFactory(
activatableClassId: hStringActivatableClass,
iid: &canvasFactoryNativeId,
factory: canvasFactoryNative.GetVoidAddressOf()).Assert();
}
using ComPtr wrapperUnknown = default;
// Get or create a WinRT wrapper for the resource
canvasFactoryNative.Get()->GetOrCreate(
device: device,
resource: resource,
dpi: dpi,
wrapper: wrapperUnknown.GetVoidAddressOf()).Assert();
// Get the runtime-provided RCW for the resulting WinRT wrapper
object wrapper = Marshal.GetObjectForIUnknown((IntPtr)wrapperUnknown.Get());
return (IGraphicsEffectSource)wrapper;
}
}