Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

InvalidCastException when call CanvasDevice.GetSharedDevice() #354

Closed
HppZ opened this issue May 24, 2016 · 3 comments
Closed

InvalidCastException when call CanvasDevice.GetSharedDevice() #354

HppZ opened this issue May 24, 2016 · 3 comments
Labels

Comments

@HppZ
Copy link

HppZ commented May 24, 2016

I do not know if it is a bug, so please pull this repo here and check the comments I leave in code. Thanks.

@shawnhar shawnhar added the bug label May 25, 2016
@shawnhar
Copy link
Member

Thanks for the bug report! This is due to some of the WinRT class activation factories not correctly being marked as agile. I'm working on a fix now.

A workaround in your code that will avoid hitting this problem is to remove your "await Task.Run" operation, and put the for loop directly inside the body of the CreateImage method instead. You don't actually need a Task.Run here to get asynchronous behavior, and it's probably not actually doing what you think as you are passing an anonymous delegate to Task.Run, which means that outermost await will complete while your inner async work is still in progress (anonymous delegates + await have some surprising behaviors that are usually not what people actually want).

@HppZ
Copy link
Author

HppZ commented May 25, 2016

:)

I use Task.Run just for reproducing the bug.

And I did some output at 3 places: 1, before Task.Run. 2, after for loop. 3, after Task.Run, the output order is 123, so I don't think that the outermost await will complete while the inner async work is still in progress. Am I somewhere misunderstanding? :)

shawnhar added a commit that referenced this issue May 25, 2016
We were incorrectly using WRL ActivationFactory<> instead of AgileActivationFactory<>.
This meant our factory implementations were not inheriting FtmBase (unlike the actual
runtime classes, which use WRL RuntimeClass<> that picks up FtmBase by default).

This could result in QI failures when Win2D constructors or static methods were called
from different threads in rapid succession.
@shawnhar
Copy link
Member

I pushed a fix - you can clone and build to pick this up. Alternatively this will be in the next update to the Win2D NuGet package.

Thanks for the report!

yejie2012 pushed a commit to yejie2012/Win2D that referenced this issue Dec 8, 2018
* Expose typography options for text layouts.

* Add CanvasVirtualControl and CanvasVirtualImageSource to the Example Gallery DPI test

* Add an option to pause the swapchain animation in CompositionExample (by tapping anywhere in the window)

This allows testing the scenario where the graphics device becomes lost while no drawing is taking place.

* CompositionExample uses DisplayContentsInvalidated to recover from lost devices even when no rendering is taking place

* Fix bug with CanvasVirtualBitmap as source to an effect drawn at high DPI

Effect graphs were inserting DPI compensation for CanvasVirtualBitmap as well as
CanvasBitmap, but this is not necessary in D2D so the images were getting compensated
twice and thus scaled wrongly.

* Add RegionsInvalidated to the list of event handlers that handle device lost

Fixes microsoft#194

* Bump version to 1.11.0

* Add CanvasImage.SaveAsync

* Update GetBounds documentation to indicate that it respects the current unit mode

* Optionally delay sign while building the managed numerics assembly

* Add method GetDesignGlyphMetrics and GetGdiCompatibleGlyphMetrics  to CanvasFontFace

no message

* Unit test for GetGdiCompatibleGlyphMetrics uses the correct scaling factor.

* Expose matching of fonts using system font fallbacks.

* Add CanvasDevice.MaximumCacheSize, CanvasDevice.LowPriority, and make CanvasDevice.Trim call ID2D1Device::ClearResources

* Size optimization: don't inline the "throw std::bad_alloc()" part of CheckMakeResult

* Change compiler settings to optimize for size rather than speed

* Size optimization: don't inline the "what HRESULT does this exception represent" part of ExceptionBoundary

* Clean up some incorrect return value handling

* Replace CanvasCharacterRangeFont with CanvasScaledFont.

* Fix docs for CanvasCharacterRange.

* Optimize-for-size compiler settings only apply to the Win2D DLL itself, no longer unit tests + samples

This avoids a VS 2013 x86 release mode codegen bug that we were hitting in test.external

* Add script analysis to CanvasTextAnalyzer.

* DrawInk saves and restores D2D device context state around the call into DirectInk

This avoids unintentionally modifying the antialiasing and/or primitive blend settings

* Add support for block compressed CanvasBitmaps

This adds support for BC1_UNORM, BC2_UNORM and BC3_UNORM format textures.

CanvasBitmap.LoadAsync now supports loading DDS files.

* Pixel format bug fix, doc corrections, and better test coverage

Bugfix: when calling the CanvasBitmap.CreateFromBytes overload that doesn't specify an
alpha mode, we were always choosing premultiplied. In fact the valid alpha options vary
depending on the pixel format, so CreateFromBytes overloads would fail when used on
formats that have no alpha. (we previously made a similar fix in
CreateFromDirect3D11Surface, but missed that CreateFromBytes had the same issue)

Doc fix: was missing 10.10.10.2 from the list of supported formats.

Doc fix: mention that R8, R8G8, and A8 formats are only partially supported by D2D.

New test: validate all the above, crafted in such a way that if D2D ever adds new
formats, this test will alert us to the need for a matching Win2D doc update.

* Add overloads of CanvasBitmap CreateFromBytes, SetPixelBytes, and GetPixelBytes, which operate on IBuffer data rather than byte arrays

* Fix pixel format test failure - now return same failure HRESULT regardless which layer of the implementation detects an unsupported format

* Update Particles sample to use compressed textures

* Add some docs about BlockCompression

* Add CanvasTextAnalyzer.GetGlyphs.

* CanvasBitmap.SetPixelBytes accepts arrays that are larger than strictly required

This brings it in line with the behavior of CanvasBitmap.CreateFromBytes

* CanvasBitmap::CopyPixelsFromBitmap can now copy between bitmaps on different devices

* Add CustomTextLayouts demo to ExampleGallery.

* Bump version to 1.12.0

* Fix CanvasDrawingSession.Close to release all resources it is holding

This prevents the "D2D DEBUG WARNING - A large number of unreleased interfaces were found"
warning, mentioned in microsoft#207.

* Call RoClearError when handling device lost errors

This prevents the error state from staying around, which can cause
problems if there's a later error that doesn't call RoOriginateError.

XAML uses the error state to override the error code.  The result here
is that the UnhandledException handler will get called with the
device lost error state, rather than the real error state that was unhandled.

This is related to issue microsoft#194 where it looked like a device lost exception
was being unhandled, when instead it was another error.

* Make ValidateStoredErrorState fail the test if there is no error state (rather than crash)

* Fix RecreatableDeviceManager to not clear the error state if it is going to rethrow it

* Ink example simplification

This now relies on the InkManager to store lists of dried strokes, rather than maintaining our own parallel copy of that state.

Also simplified some of the is-dirty flag handling.

* Ink Example defers calling EndDry, to avoid flicker where wet ink could be turned off before the dry ink is visible

* Add test that fails if we don't clear the error state after handling a DeviceLostException

* Simplify logic for creating zero sized bitmaps, and make this work even if the provided pixel array is zero size or null

* Add information about the tint parameter to SpriteBatch documentation

* Bugfix: GetPixelBytes and SetPixelBytes didn't work with A8 pixel format on feature level 9.3 devices

On 9.x feature levels, D2D sometimes emulates A8 format using a BGRA32 surface.
ScopedBitmapMappedPixelAccess needs to know about this to convert data between the
internal DXGI and external D2D formats.

* Remove unnecessary semicolons

* Better exception messages when trying to create a bitmap, rendertarget, swapchain, or image source larger than the max GPU texture size

* Simpler and more robust approach for the D3D interop example keeping its rendertarget in sync with the size of the CanvasAnimatedControl

* Use the RaiseException trick to give the game loop thread a human readable name

* Sort the type table in interop.aml by Win2D class name

* Scrub interop docs to make sure we fully describe all the types that are different between 8.1 and UAP

* Calling CanvasImageSource or CanvasVirtualImageSource CreateDrawingSession on non-UI thread now generates a more helpful exception

* Fix test break introduced by the new *_MaxSizeError external tests

When running tests on a WARP device, MaximumBitmapSizeInPixels is much larger than on any
real HW GPU. Large enough that when the tests declare:

	auto badSize = MaximumBitmapSizeInPixels + 1;

and then cast this to a float to pass to Win2D constructor APIs, the resulting float
rounds back downward and ends up the same as the legit max size!

Fix is to more carefully choose a bad value that is accurately representable using 32 bit
float as well as int parameter types.

* CanvasRenderTarget.CreateDrawingSession docs clarify that the drawing session must be closed before using the rendertarget elsewhere

* Better error message if you attempt to create multiple simultaneous drawing sessions on the same target

This affects:

- CanvasRenderTarget
- CanvasCommandList
- CanvasImageSource
- CanvasVirtualImageSource
- CanvasSwapChain

* Gradient mesh constructor passes a non-null pointer into D2D, even when the patch count is 0

D2D debug layer becomes unhappy if this is not the case.

* test.external enables the D2D debug layer

This is only turned on in debug builds, and only when the debug layer is
available: we'll still run tests without it if it's not installed.

* test.managed enables the D2D debug layer

* Improve interactions between CanvasDevice.DebugLevel and GetSharedDevice

1. If you explicitly Close a shared device, subsequent calls to GetSharedDevice will
create a new device (used to enter a broken state where GetSharedDevice would throw
object disposed error).

2. If you change DebugLevel after creating a shared device, subsequent calls to
GetSharedDevice will throw (used to return a device with the wrong debug level, which
could be confusing).

* Example Gallery includes an option (on the Developer Tools page) to enable the debug layer

* Fix data hazard when updating Win2D bitmaps

Bug: when updating a bitmap via D3D, D2D did not know it changed:

1. SetPixelBytes
2. DrawImage
3. SetPixelBytes again on the same bitmap
4. DrawImage again

Should see two different images, but actually DrawImage microsoft#2 was picking up the
result of SetPixelBytes microsoft#3, because SetPixelBytes was implemented at the D3D
level, which bypasses the usual D2D hazard mechanisms.

Changes to address this:

- ScopedBitmapMappedPixelAccess is now only for reading bitmap contents

- Writes are mostly done using CopyFromMemory instead
    - Affects SetPixelBytes and SetPixelColors
    - Also the cross-device CopyPixelsFromBitmap path

- CanvasDevice::CreateBitmapFromDdsFrame passes init data when constructing the D2D bitmap
    - Requires an extra CPU buffer, but removes a GPU staging surface so we come out even or possibly ahead

- ScopedBitmapMappedPixelAccess read path uses D2D rather than D3D to allocate the staging surface
    - Greatly reduces code size & complexity
    - Removes the need for our custom A8 format conversion (D2D now handles that for us)

* Bump version to 1.13.0

* ExportSample tweak: move RuntimeDirectives.rd.xml from Shared to UAP folder

* ExportSample tweak: remove the Shared folder from CompositionExample (which is only for UAP, so has no shared project)

* ExportSample tweak: simplify the output projects by flattening MSBuild 'Condition' attributes that will always pass or fail

* Use RoTransformError rather than RoClearError

fixes microsoft#224

* Bump version to 1.14.0

* Add CanvasTextAnalyzer analysis methods.

* Validate null brush passed to CanvasDrawingSession.DrawGlyphRun.

* Add ETW tracing to StepTimer

* Code cleanup: change static_cast to StaticCastAs

* Code cleanup: fix lambda indentations

* Code cleanup: tabs -> spaces

* Code cleanup: lambdas with no parameters should be written just [], not []()

* Code cleanup: spaces after keywords

* Update the copyright checker tool to also validate common source formatting errors, and rename it from "Copyright" to "CheckCode"

Currently implemented checks:

- Tabs should be spaces
- Missing space after keyword
- Lambda with no parameters should not include ()
- Lambda indentation

* Updated ETW tracing for StepTimer

* Add ColorManagementEffect and TableTransfer3DEffect

Details:

- Adds the supporting types ColorManagementProfile and EffectTransferTable3D
- Adds effect codegen support for adding manually authored static methods (used to implement ColorManagementEffectFactory::IsBestQualitySupported)
- Copies latest API description XML from the Windows tree - lots of churn here but it's all just reformatting and adding comment strings
- Extends ComArray to handle arrays of non-POD types ComPtr and WinString (nice side effect is this fixes a preexisting leak in the CanvasTextFormatFactory::GetSystemFontFamiliesFromLocaleList error path)
- CanvasEffect supports interface effect property types
- Moved Color -> BGRA conversion from CanvasBitmap -> DxgiUtilities
- Moved GetRefCount helper from RefCountTests to Helpers.h

* Add text justification to CanvasTextAnalyzer.

* Add ETW logging for CanvasAnimatedControl tick

* Change when CanvasAnimatedControl calls WaitForVerticalBlank

Previously, WaitForVerticalBlank was always called at the beginning of
each tick.  If the previous frame was delayed for some reason (eg the
Present() blocked) past the VBlank, then this wait would compound the
problem, resulting in a missed frame.

This version only calls WaitForVerticalBlank if we did not present a
frame.

Generally, Present() blocks anyway to prevent the CPU getting
too far ahead of the GPU, so the CPU is not busy looping in this case.

However, in the cases where Present() does return early enough that
it isn't time to do a tick then it is worth waiting for the vblank to
avoid busy waiting.

* Set ParticleExample to use sprite batch by default, if it is supported

* Fix CanvasBitmap::SaveAsync to support pixel formats other than B8G8R8A8UIntNormalized

This change makes SaveAsync use IWICImageEncoder, rather than directly
locking the surface and passing the pixel data to WIC.

IWICImageEncoder will, if necessary, convert the bitmap to
B8G8R8A8UintNormalized before saving it.

Note that a bug (6184116) IWICImageEncoder means that the debug layer
will issue a message / debug break whenever the a bitmap is saved. For
this reason the tests disable the debug layer when testing SaveAsync.

* Fix CanvasBitmap_SaveToFileAsync_PixelFormats test when run on platforms that don't support a particular pixel format

* Remove histogram effect from codegen tool

Not needed - we're going to implement this functionality a different way, not relying on effect codegen.

* Sort using statements, and remove unused namespaces

* Add CanvasImage.ComputeHistogram

* Add missing "experimental" tag to CanvasImage docs

* Add Device property to CanvasVirtualBitmap

* Stop CanvasPrintEventArgs from keeping the IPrintDocumentPackageTarget alive

While the target is kept active, print targets such as the PDF printer
don't close the output file.

Fixes microsoft#230

* CanvasVirtualImageSource and CanvasVirtualControl support rendering from non-UI threads

It turned out our implementation was already basically ok, except we need to turn on the D3D multithread flag before drawing to a VSiS on a background thread. So now we do that.

Also updated docs to give more detail about threaded rendering.

* CanvasGradientMesh.GetBounds ignores the drawing session transform (same as ICanvasImage.GetBounds)

* Apps can query for supported typographic features

* Bump version to 1.15.0

* CanvasFontSet can be created from a URI.

* Change GetBounds methods to take a ICanvasResourceCreator rather than a CanvasDrawingSession

This makes it possible to GetBounds without a drawing session.

This is a non-breaking change at the source code level since
CanvasDrawingSession implements ICanvasResourceCreator
and so any existing code will naturally work with this change.

* Consolidate Matrix3x2 identity constants

* CanvasFontSet is not default activatable

* CanvasFontSet.TryFindFontFace is a Win10-only API

* Ensure that all runtimeclasses have the version, marshaling_behavior and threading attributes set

* Remove workaround for intellisense XML files not being picked up by VS2015

The latest version picks them up now.

* Standardize CanvasTextAnalyzer's method names.

* Make ExampleGallery use the native UWP back button

* Document a way to detect whether font files are loadable

* Arrange for CanvasAnimatedControl::get_Size to return a consistent size while a Tick is running

* Fix CanvasVirtualControl to render at least the clear color in the designer

* Make CanvasAnimatedControl display its ClearColor in the designer

When run in the designer, CanvasAnimatedControl displays itself using
a Rectangle (rather than a swap chain panel).

* Make CanvasControl handle E_SURFACE_CONTENTS_LOST when it tries to redraw itself

* Remove the "experimental" warning tag from some of our older, more stable APIs

APIs that are no longer experimental:

    CanvasBitmap.CreateFromSoftwareBitmap
    CanvasComposition
    CanvasDevice.GetSharedDevice
    CanvasDrawingSession.DrawInk

    CanvasGeometry:
        CreateInk
        CreateText

    CanvasGradientMesh
    CanvasGradientMeshPatchEdge
    CanvasGradientMeshPatch
    CanvasDrawingSession.DrawGradientMesh

    CanvasSpriteBatch
    CanvasSpriteFlip
    CanvasSpriteOptions
    CanvasSpriteSortMode
    CanvasDrawingSession.CreateSpriteBatch

    CanvasTextFormat:
        LastLineWrapping
        LineSpacingMode
        GetSystemFontFamilies
        OpticalAlignment
        VerticalGlyphOrientation

    CanvasTextLayout:
        ClusterMetrics
        LineMetrics
        LineSpacingMode
        LayoutBoundsIncludingTrailingWhitespace
        MaximumBidiReorderingDepth

    CanvasLineSpacingMode
    CanvasLineMetrics
    CanvasClusterMetrics
    CanvasClusterProperties

* CustomTextLayouts sample uses Arabic/RtL text

* Add a space for formatting style

* Move features list from github wiki into the main Win2D docs, and update backlog links to point at github issues rather than wiki

* Fix github microsoft#254 (Geometry dry ink crashes the Win2D Example Gallery)

Root cause appears to be a .NET Native marshalling bug, which we have filed internally.

In the meantime, Example Gallery can workaround by passing a simple List<>
(rather than result of a Linq groupby query) into the Win2D geometry API.

* Add CanvasTextLayout.GetGlyphOrientationTransform

* Bump version to 1.16.0

* Remove the "experimental" warning tag from a set of APIs that we now consider stable

APIs that are no longer experimental:

    CanvasImage
    CanvasVirtualBitmap
    CanvasVirtualBitmapOptions
    CanvasVirtualControl
    CanvasVirtualImageSource
    CanvasRegionsInvalidatedEventArgs

    PixelShaderEffect
    SamplerCoordinateMapping

    CanvasPrintDocument
    CanvasPrintTaskOptionsChangedEventArgs
    CanvasPreviewEventArgs
    CanvasPrintEventArgs
    CanvasPrintDeferral

    CanvasDevice:
        IsPixelFormatSupported
        IsBufferPrecisionSupported
        MaximumCacheSize
        LowPriority

    CanvasDrawingSession:
        EffectTileSize
        EffectBufferPrecision

    ICanvasEffect:
        BufferPrecision
        CacheOutput
        GetInvalidRectangles
        GetRequiredSourceRectangle
        GetRequiredSourceRectangles
        InvalidateSourceRectangle

* Bump version to 1.17.0

* Fix race condition in GameLoopThreadTests

Our stub ProcessEvents implementation was waiting on a condition variable that might have
already been signalled, but this is not how condition variables work. If notify is called
before wait, there's nothing to notify so that's a no-op. Therefore we should only wait
if there isn't already work queued up.

* Update print preview when switching printers

If you switch printers the print preview doesn't update until you change
another property like Orientation. This is noticeable when switch from
something like print to PDF which has no margins to a physical printer
that does. (bug microsoft#292)

Fix is to listen to OptionChanged and invalidate the preview when an
event with a null OptionId is raised.

* Convert test.external.uap to use CppUnitTestFramework.Universal

This was previously using the non-universal version of the test framework, which somehow
managed to work ok with VS 2015 Update 1, but is not the right thing and broke with
Update 2.

Also reorganized the directory structure to keep things clear as this test project now
includes some UAP-only app files. test.external is split into Shared, UAP, Windows, and
WindowsPhone sub folders, just like we already did for the samples and test.managed.

* Fix github microsoft#319: Creating CanvasAnimatedControl in code sometimes hangs

Turns out that when a custom XAML control is used as an inline element within a Paragraph
(via InlineUIContainer), its Loaded event gets raised twice in a row, followed by a pair
of Unloaded when the control is later removed.

Win2D CanvasAnimatedControl did not expect this, and did not handle it well.

The fix is to maintain a count of how many times the control has been loaded, and only
actually do init or cleanup work on the outermost pair.

* Remove the "experimental" warning tag from a final set of APIs that we now consider stable

APIs that are no longer experimental:

    HDR color support
        *Hdr properties matching all existing Color properties
        CanvasSolidColorBrush constructor overload
        CanvasGradientStopHdr
        CanvasDrawingSession.Clear overload

    ColorManagementEffect
    ColorManagementProfile
    ColorManagementEffectQuality
    ColorManagementRenderingIntent

    TableTransfer3DEffect
    EffectTransferTable3D

    CanvasTextFormat
        CustomTrimmingSign
        TrimmingSign

    CanvasTextLayout
        CustomTrimmingSign
        DrawToTextRenderer
        GetCustomBrush
        GetTypography
        SetCustomBrush
        SetInlineObject
        SetTypography
        TrimmingSign

    CanvasAnalyzedBidi
    CanvasAnalyzedBreakpoint
    CanvasAnalyzedGlyphOrientation
    CanvasAnalyzedScript
    CanvasCharacterRange
    CanvasFontFace
    CanvasFontFileFormatType
    CanvasFontInformation
    CanvasFontProperty
    CanvasFontPropertyIdentifier
    CanvasFontSet
    CanvasFontSimulations
    CanvasGlyph
    CanvasGlyphJustification
    CanvasGlyphMetrics
    CanvasGlyphOrientation
    CanvasGlyphShaping
    CanvasJustificationOpportunity
    CanvasLineBreakCondition
    CanvasNumberSubstitution
    CanvasNumberSubstitutionMethod
    CanvasScaledFont
    CanvasScriptProperties
    CanvasScriptShape
    CanvasTextAnalyzer
    CanvasTextGridFit
    CanvasTextMeasuringMode
    CanvasTextRenderingMode
    CanvasTextRenderingParameters
    CanvasTrimmingSign
    CanvasTypography
    CanvasTypographyFeature
    CanvasTypographyFeatureName
    CanvasUnicodeRange
    ICanvasTextAnalyzerOptions
    ICanvasTextInlineObject
    ICanvasTextRenderer

    CanvasGeometry.CreateGlyphRun
    CanvasDrawingSession.TextRenderingParameters

* Remove irrelevant TODO comments from unit test boilerplate

* Add @responseFile feature to CommandLineParser

This allows arguments to be passed via a file rather than directly on the commandline,
which is useful for tools that take a large amount of parameter data.

* Doc build uses response files to avoid passing very long commandlines

This fixes github #microsoft#283 (Exception in building package)

* Bump version to 1.18.0

* Added how to use a color type with the vector4 as tint (microsoft#325)

Added how to use a color type with the vector4 as tint

* Update test certificate, as our previous one expired today

This time around, I figured out how to customize the key expiry date,
so we'll be good up until the end of 2099.

* Ignore *.VC.db

* CanvasGameLoop now uses a recursive mutex.

This is to handle the case where CanvasGameLoop::ScheduleTick calls
RunAsync and the async action completes before it calls put_Completed.
In this case the completion handler is called on the current thread.
Since the current thread has locked m_mutex and the completion handler
also needs to lock the mutex we the second lock fails when m_mutex is
non-recursive.

Previously this exception was being swallowed since, internally,
put_Completed ignores the result of the completion handler.
This shows up real-life environments since Dispatcher would call
RoReportFailedDelegate, ultimately triggering XAML's UnhandledException
handler.

CanvasGameLoop has now been modified to fail fast
(via RoFailFastWithErrorContext) if TickCompleted fails for some reason.
This will at least generate a failure / crash dump closer to the error if this
happens again.

* Make BuildDocs create the output directory so that it can write the response file to it

* Bump version to 1.19.0

* Add "no81" option to build.cmd, and fix bug where it would try to package UAP even if "nouap" was specified

* UpdateApiResourceFiles.cmd had a stale path to the copyright.txt header

* RunCodeChecks.proj ignores .db extension

* WinRT activation factories should be agile (fixes github microsoft#354)

We were incorrectly using WRL ActivationFactory<> instead of AgileActivationFactory<>.
This meant our factory implementations were not inheriting FtmBase (unlike the actual
runtime classes, which use WRL RuntimeClass<> that picks up FtmBase by default).

This could result in QI failures when Win2D constructors or static methods were called
from different threads in rapid succession.

* CanvasRegionsInvalidatedEventArgs should not be activatable

There is no activation factory for this type, so it was never actually possible for an
app to construct one, but the IDL incorrectly marked the type as activatable. This meant
the docs showed it as having a default constructor. Code attempting to call that would
compile but then fail at runtime.

* Switch UAP build from Windows SDK 10586 to 14346

* Rename Win10NovUpdate documentation tag to Win10_10586

"NovUpdate" terminology becomes unclear now we're no longer in the same year when that
update was released. Looks like the OS build # is the mostly widely used way to identify
a specific revision of Win10, and developers will already be familiar with that from the
Visual Studio SDK selection UI, so let's use it in the Win2D docs as well.

* Update Win2D copies of the D2D API description XML

* Add 4 new image effects: AlphaMaskEffect, CrossFadeEffect, OpacityEffect, and TintEffect

This change adds Win2D support for new effect types that have been added to Direct2D in
the latest version of Windows.

These are just convenience helpers, as identical functionality was previously available
from specific configurations of CompositeEffect, ArithmeticCompositeEffect, and
ColorMatrixEffect. The new effect shorthands make it easier to do some of the most common
operations for which those more complex and configurable effects were previously required.

* Add Microsoft Open Source Code of Conduct to readme

* Add arbitrary subscript and superscript example to ExampleGallery

* Remove dead code in InkExample

* Replace deprecated [uuid(x)] syntax with __declspec(uuid("x"))

* Disable warning C4467 (deprecated uuid() attribute syntax) because WRL headers still use that

* CanvasStrokeStyle::put_CustomDashStyle should not create a checked_array_iterator if the array is empty/null

* Added VB to the Introduction (microsoft#401)

* added vb

* Added code example for Visual Basic

* Inserted VB code example into documention

Inserted VB code example into documention\introduction. microsoft#401

* Switch Win2D UAP builds from Windows SDK 14346 to 14393 (which is the final Win10 Anniversary Update SDK)

* Update sample code to account for breaking change in BackgroundAccessStatus API

* Fix CanvasTextAnalyzer tests to use a different not-in-any-font character

Win10 Anniversary Update added support for the obscure character that we previously expected not to exist :-)

* Add Experimental doc tag to the 4 new image effects

* Add pencil rendering to the Example Gallery Ink demo

* Docs mention that CanvasGeometry.CreateInk does not support pencil strokes

* Fix github microsoft#377 (Crash while using CanvasAnimatedControl)

* Better docs about DpiCompensationEffect

* Include C++/CX code snippets in the readme and doc introduction page

* Docs describe how to use 'delete' in C++ as well as 'using' in C#

* Temporarily disable building docs, until github microsoft#390 is fixed

* Update mock generator to support new SAL annotations used by latest D2D API descriptions

* Still build Intellisense even though main doc build is disabled

* Bump version to 1.20.0

* Fixed microsoft#373: Added Measure() call to the canvas control. (microsoft#406)

* SpriteBatch.Close() clears its internal std::vector

In response to a Win2D customer report.  I don't think there's really a problem here, but this cleanup does reduce memory usage in some cases.

* Revert temporary disable of doc build

This reverts the two commits:

"Still build Intellisense even though main doc build is disabled" (66adb0f)

"Temporarily disable building docs, until github microsoft#390 is fixed" (13f2033)

* Update to latest Sandcastle package

This fixes github microsoft#390 (Sandcastle cannot build Win2D docs using VS 2015 Update 3)

Note that the resulting docs are still not correct due to what appears to be a
recent Sandcastle regression in handling of enum and struct types
(EWSoftware/SHFB#343)

* Build doc reference assembly against .NETCore rather than full desktop framework references

We were previously mixing up reference framework versions, building against the full
desktop version but then generating docs against the UWP reference set. Previous versions
of Sandcastle didn't care, but the latest doc tools get confused (resulting in
misformatted pages for enum and struct types) unless we keep these properly matching.

* Make sure CanvasControl::Changed always executes on the UI thread

The Changed implementation calls a couple of XAML APIs that have thread affinity, so
will fail if called on any other thread.

- Multithreaded Win2D app shares a device across more than one thread
- Hit TDR
- CanvasDevice.DeviceLost event is raised on whichever thread notices the TDR first
- BaseControl.OnDeviceLost for other controls executes on the thread of the event sender (which may not be their UI thread)
- OnDeviceLost calls Changed
- CanvasControl.Changed calls IsWindowVisible
- This throws "The application called an interface that was marshalled for a different thread."

The solution is for Changed to marshall itself back onto the UI thread if invoked
anywhere else. CanvasAnimatedControl and CanvasVirtualControl already do that - it is
only CanvasControl where this was a problem.

Also merged the two different ways that BaseControl had to query window visiblity.
IsWindowVisible polled on every call, which is always correct but has UI thread affinity.
IsVisible cached a state and listened for change events, which allows querying from any
thread but returned wrong data if the window was already hidden when the control was
first created. Now we have a single implementation that queries on load, then listens
to subsequent change events.

Fixes github microsoft#445 - "Device lost handling can lead to calling IWindow::get_Visible on the wrong thread"

* Fix codegen.test to find the Windows SDK even if that is installed in subfolders (which is done to support side-by-side in more recent versions of Visual Studio)

* Fix HSTRING double-free in Win2D unit test

Incorrect refcounting was causing intermittent failures during test cleanup

* AlphaMaskEffect, CrossFadeEffect, OpacityEffect, and TintEffect are no longer experimental APIs

* Fix github microsoft#435 - ExampleGallery Ink demo crashes when you "clear" then "save"

* Bump version to 1.21.0

* Some fixes to CanvasGeometry documentation

* Docs for AlphaMaskEffect, CrossFadeEffect, OpacityEffect, and TintEffect link to the corresponding Direct2D docs

We initially skipped this because D2D had not yet published these docs to MSDN.

* Fix GitHub#498; diagram in documentation for CanvasGradientMesh.CreateTensorPatch had a mistake

* Merged PR 100: Update Win2D to support VS 2017

* Merged PR 99: Allow apps to draw SVG documents

* Fix 8.1 build and clean up warnings

* Fix 8.1 build

* Fix copyright and code style

* Add new entries for D2DSvgTypes.xml and MockD2DSvgDocument.h in tools.sln's unit tests

* Allow apps to add SVG string-specified elements to SVG documents

* Fix crash when passing a CanvasCommandList to CanvasImage.SaveAsync (github microsoft#515)

CanvasImageFactory::SaveWithQualityAndBufferPrecisionAsync was calling
GetWrappedResource, when it should be using GetD2DImage. The former is intended for
interop, and skips behaviors such as closing active command lists that are necessary
before the D2D interface can be treated as a regular source image.

* RegisteredEvent::Release no longer throws on failure (github microsoft#496)

* ComputeHistogram no longer ignores its source rectangle parameter (github microsoft#487)

We had misinterpreted how this works in Direct2D. Turns out that passing a rectangle to
the DrawImage call when evaluating a histogram has no effect. Instead, we must configure
an AtlasEffect to apply the rectangle selection, then feed the atlas output into our
HistogramEffect.

* Merged PR 103: SVGExample and tests should fail gracefully on RS1

* Fix CanvasVirtualControl OnRegionsInvalidated not triggered when launching app (github microsoft#479)

If the control was loaded while hidden, then later became visible, we were never getting
around to creating the underlying image source.

* CanvasControl and CanvasVirtualControl disable the accessibility view (github microsoft#491)

We can't automatically enable Narrator (screen reader) for custom Win2D controls,
but this change stops it from reading out the word "image" when it encounters the
internal image control that backs a Win2D CanvasControl or CanvasAnimatedControl.
This leaves a blank slate ready for anyone who wants to start implementing
meaningful custom narration support for their custom controls.

* Fix crash when resource loading completes after CanvasControl has been unloaded (github microsoft#486)

* Add CanvasComposition.CreateDrawingSession overload that allows specifying DPI (github microsoft#425)

* Merged PR 105: Add programmatic attributes, DOM manipulation methods to CanvasSvgElement and CanvasSvgDocument

* Build fix: re-run mockgen to ensure the mock tests pass, and fix an #include that was improperly merged

* Merged PR 107: Add a bullet point about SVG to Features.aml; add missing versioning and Experimental flags

* Merged PR 108: Add a reference to SVG in Namespaces.xml

* Extend ColorManagementProfile to support Simple and Extended types of color profile

This adds additional color management options alongside the existing ICC style profiles.

* Set Win2d.uap.sln to open in VS2017

* Merged PR 109: Remove a misplaced keyword from code sample on CanvasSvgDocument docpage

* Skip CanvasDrawingSession_DrawSvgDocument_ZeroSizedViewportIsInvalid test when running on an OS that doesn't support SVG

* Support loading and saving JpegXR images using float16, float32, and int16 pixel formats

This change alters the behavior of CanvasBitmap.LoadAsync, CanvasVirtualBitmap.LoadAsync,
CanvasBitmap.SaveAsync, and CanvasImage.SaveAsync, when operating on JpegXR format files
using HDR pixel formats.

* Merged PR 104: Update effects documentation to reflect composition support

Updating effects documentation to reflect changes in supported effects in Composition in Anniversary Update and Creators Update.

* Fix lifetime management issue in Composition Example

Sample code wasn't hanging onto references to the root visual or composition target, so
it was possible these could be prematurely garbage collected (leading to an object
disposed exception).

* Bump version to 1.22.0

* Merged PR 110: Add documentation note about CanvasStrokeStyle defaults and zero-length dashes

* Update NuGet copyright string to follow standard Microsoft convention

* Merged PR 112: Add check for VS150COMNTOOLS when looking for vstest.console.exe

This is so Win2D can be built on machines that don't have VS2015 installed.

* Remove 8.1 support: delete 8.1 project files and no-longer-used numerics implementation

* Remove 8.1 support: merge the .uap and .shared projects

This flattens a layer of no-longer-needed filesystem and Solution Explorer hierarchy.

* Remove 8.1 support: assorted other cleanups

* Remove 8.1 support: update docs and readme

* Merged PR 114: Fix BufferStreamWrapper handling of negative stream seek offsets on x64

This was adding only the low 32 bits of the provided offset value to a size_t. On x64,
that resulted in small negative offsets being misinterpreted as large positive ones.

This would be fine if the caller always provided positive offets - but that's not always
the case :-)

* Merged PR 113: Remove Experimental tag from Win10_15063 API additions

The Win2D SVG APIs and ColorManagementProfile enhancements, which
were introduced with Windows 10 Creators Update, are no longer marked
as experimental.

* Merged PR 116: Win2D.uwp.targets no longer checks for TargetPlatformIdentifier=UWP (issue microsoft#583)

This is a step towards enabling use of Win2D with the Desktop Bridge (http://aka.ms/desktopbridge)

* Refactor: decouple CanvasGeometry and CanvasPathBuilder from CanvasDevice

This is a pure refactoring (no behavior change) in preparation for my next change (which will enable using CanvasGeometry and CanvasPathBuilder without creating a device first).

D2D geometry objects are now created using a dedicated adapter singleton, rather than via ICanvasDeviceInternal.  Tests are updated to use a mock version of that adapter.

CanvasGeometry and CanvasPathBuilder no longer store a direct reference to a CanvasDevice - instead this goes through a GeometryDevicePtr intermediate type.  GeometryDevicePtr is currently a trivial wrapper over a ComPtr<ICanvasDevice>, but this new abstraction centralizes all the places where geometry touches a device, which will make it easier to change that logic in the future.

* Allow use of CanvasGeometry and CanvasPathBuilder without a CanvasDevice

This change allows a null resource creator to be specified when creating geometry objects.  The resulting geometry can still be manipulated in all the normal ways, but cannot be drawn via a CanvasDrawingSession or converted into a CanvasCachedGeometry.  Attempting to do so will fail with the existing error mechanism that handles resources from mismatched devices.

The motivation for this is to allow use of Win2D for geometry manipulation in situations where the cost of creating D3D+D2D devices is undesirable.

* Enable ControlFlowGuard compiler setting

This makes Win2D compliant with the binskim static analysis tool.

* Fix race condition if TrackAsyncAction is passed an action that has already completed (issue microsoft#585)

* Change project.json to .csproj NuGet references

The UWP C# project system has migrated from project.json to a newer .csproj mechanism for referencing NuGet packages, and newer versions of the commandline nuget.exe no longer support restoring packages from project.json.   This change updates Win2D to match.

* Update test.managed to MSTest v2

* Restore NuGet packages separately for all platforms * configurations

Turns out this is required when consuming new style .csproj NuGet references. The NuGet
restore operation generates temp files into the obj folder, which is unique per config,
so restoring just one config doesn't enable building others.

This change also switches from restoring individual projects to restoring the top level
.sln. We previously avoided that to work around a NuGet bug that is no longer relevant.
Restoring the .sln is simpler and MUCH faster.

* Remove obsolete Newtonsoft.Json reference

This was missed from an earlier change

* Move from RS2 to RS3 SDK

* Optionally consume the Windows SDK via NuGet package

This is for internal Microsoft builds that want to consume prerelease SDK versions

* Update typedefs for compatibility with latest compiler

The most recent Visual Studio update changed some details of how templates are parsed.

* Update mdmerge and reference paths to match Visual Studio 2017 version 15.6.4

* Work around NuGet restore bug

* Update test.external project to match Visual Studio 2017 version 15.6.4

* Remove obsolete WindowsMobile SDK reference

* Move to RS4 SDK

* CanvasBitmap_CreateFromSoftwareBitmap_PixelFormats test skips the prerelease BitmapPixelFormat.P010

* Update doc build to match the location of Windows.winmd in recent SDKs

* Fix sample exporter handling of "Shared" subfolder

This was legacy from how sample projects used to be split across UAP and 8.1 project variants. It caused the imageTiger used by Example Gallery to be placed in a Shared subfolder, which is no longer the desired location.

* CanvasGeometry implements IGeometrySource2D

This allows using Win2D to construct and manipulate geometry paths for use with the new Windows.UI.Composition geometry APIs.

After this change, Win2D geometry APIs are no longer compatible with Windows SDK versions < RS4.

* Disable running test.external from Win2D.proj due to vstest bug, and link vstest workarounds to the bugs that track them

* Update Visual Studio and SDK version mentions in docs

* Update to SDK 17134 (April 2018 Update)

* Bump version to 1.23.0

* Add .targets validation to give a better error message if Windows SDK version is too old

* Change NuGet package output path (to support package signing)

* Bump version to 1.24.0

* Fix AV when a non-existent element is passed to CanvasSvgDocument.FindElementByID (microsoft#635)

* add C++/WinRT example to interop article (microsoft#655)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants