using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using Win32 = TerraFX.Interop.Windows.Windows;
#if WINDOWS_UWP
namespace ComputeSharp.D2D1.Uwp.Extensions;
#else
namespace ComputeSharp.D2D1.WinUI.Extensions;
#endif
///
/// A with extensions for the type.
///
internal static unsafe class ICanvasDeviceExtensions
{
///
/// Gets the underlying object from an object.
///
/// The input object.
/// The underlying object for .
/// The for the operation.
public static HRESULT GetD2DDevice(this ref ICanvasDevice canvasDevice, ID2D1Device1** d2D1Device1)
{
using ComPtr canvasDeviceResourceWrapperNative = default;
// Get the ICanvasResourceWrapperNative wrapper around the input device
canvasDevice.QueryInterface(
riid: Win32.__uuidof(),
ppvObject: canvasDeviceResourceWrapperNative.GetVoidAddressOf()).Assert();
// Get the underlying ID2D1Device1 instance in use
HRESULT hresult = canvasDeviceResourceWrapperNative.Get()->GetNativeResource(
device: null,
dpi: 0,
iid: Win32.__uuidof(),
resource: (void**)d2D1Device1);
return hresult;
}
///
/// Retrieves a usable from an input if one is not available.
/// If a new one had to be rented from the pool, it also returns the owning instance.
///
/// The input object.
/// The current object, if available.
/// The resulting instance to use.
/// The resulting object, if used.
///
/// When this method returns, is guaranteed to not be .
///
public static void GetEffectiveD2DDeviceContextWithOptionalLease(
this ref ICanvasDevice canvasDevice,
ID2D1DeviceContext* d2D1DeviceContext,
ID2D1DeviceContext** d2D1DeviceContextEffective,
ID2D1DeviceContextLease** d2D1DeviceContextLease)
{
// If there is no input device context, just create a new one from the input canvas device
if (d2D1DeviceContext is null)
{
using (ComPtr d2D1DeviceContextPool = default)
{
// Get the ID2D1DeviceContextPool interface reference
canvasDevice.QueryInterface(
riid: Win32.__uuidof(),
ppvObject: d2D1DeviceContextPool.GetVoidAddressOf()).Assert();
// Get a new ID2D1DeviceContextLease object from the retrieved pool
d2D1DeviceContextPool.Get()->GetDeviceContextLease(d2D1DeviceContextLease).Assert();
}
// Get the underlying device context from the lease (this is much faster than creating a new device context)
(*d2D1DeviceContextLease)->GetD2DDeviceContext(d2D1DeviceContextEffective).Assert();
}
else
{
// Otherwise, just use the input device context
*d2D1DeviceContextEffective = new ComPtr(d2D1DeviceContext);
}
}
}