using System;
using System.Runtime.InteropServices;
#if WINDOWS_UWP
using System.Runtime.InteropServices.WindowsRuntime;
#endif
using Microsoft.Graphics.Canvas;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if !WINDOWS_UWP
using WinRT;
using WinRT.Interop;
#endif
#nullable enable
namespace ComputeSharp.D2D1.UI.Tests.Helpers;
///
/// A helper type to marshal managed objects in unit tests.
///
internal static class Win2DHelper
{
///
/// Gets the managed wrapper for a given object.
///
/// The input object to get a wrapper for.
/// The realization instance to use.
/// The resulting managed wrapper for .
public static unsafe object GetOrCreate(ID2D1Image* d2D1Image, CanvasDevice? canvasDevice = null)
{
using ComPtr activationFactoryUnknown = default;
#if WINDOWS_UWP
IActivationFactory activationFactory = WindowsRuntimeMarshal.GetActivationFactory(typeof(CanvasDevice));
activationFactoryUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(activationFactory));
#else
ICanvasFactoryNative activationFactory = CanvasDevice.As();
activationFactoryUnknown.Attach((IUnknown*)MarshalInterface.FromManaged(activationFactory));
#endif
using ComPtr canvasFactoryNativeUnknown = default;
Guid uuidOfCanvasFactoryNativeUnknown = new("695C440D-04B3-4EDD-BFD9-63E51E9F7202");
//Get the ICanvasFactoryNative object
int hresult = activationFactoryUnknown.CopyTo(&uuidOfCanvasFactoryNativeUnknown, (void**)canvasFactoryNativeUnknown.GetAddressOf());
Marshal.ThrowExceptionForHR(hresult);
using ComPtr canvasDeviceUnknown = default;
if (canvasDevice is not null)
{
#if WINDOWS_UWP
canvasDeviceUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDevice));
#else
canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable.FromManaged(canvasDevice));
#endif
}
using ComPtr canvasDeviceInterfaceUnknown = default;
if (canvasDevice is not null)
{
Guid uuidOfCanvasDeviceInterface = new("A27F0B5D-EC2C-4D4F-948F-0AA1E95E33E6");
// Get the ICanvasDevice object (as an IUnknown* as well)
hresult = canvasDeviceUnknown.CopyTo(&uuidOfCanvasDeviceInterface, (void**)canvasDeviceInterfaceUnknown.GetAddressOf());
}
using ComPtr wrapperUnknown = default;
// Invoke GetOrCreate to get the inspectable wrapper
hresult = ((delegate* unmanaged[Stdcall])(*(void***)canvasFactoryNativeUnknown.Get())[6])(
canvasFactoryNativeUnknown.Get(),
canvasDeviceInterfaceUnknown.Get(),
(IUnknown*)d2D1Image,
0,
wrapperUnknown.GetAddressOf());
Marshal.ThrowExceptionForHR(hresult);
// Get or create a managed object for the native object
#if WINDOWS_UWP
return Marshal.GetObjectForIUnknown((IntPtr)wrapperUnknown.Get());
#else
return MarshalInspectable