Skip to content

TouchMove intermediate points are not DPI aware #2072

Closed

Description

@dotMorten
  • .NET Core Version: 3.1 Preview1
  • Windows version: (winver) 1809
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: Yes
  • Is this bug related specifically to tooling in Visual Studio (e.g. XAML Designer, Code editing, etc...)? No

Problem description:
Using the TouchMove event in a multi-dpi scenario, the interpolated points returned are not correctly adjusting for DPI, whereas the current point is.
When using the event to draw a path, you can see the discrepancy between these two inputs:
image
In this case my main monitor is scale factor 1.5x, whereas my touch-monitor where I'm running the app on is 1.0x.
The app has been configured to support multi-monitor DPI via the app.manifest.

Update: It appears the root issue here is in a multi-mon dpi aware app, when the DPI changes, the transform applied to the intermediate points are not using the new dpi, as this value is only initialized once.

Actual behavior:
Touch events (red line) are about 30% off from the correct location. If I multiple the location with 1.5, the location is correct (apart from the distance of the window top-bar). This is however weird, as the screen the app is running on is 1.0x screen scale (but main monitor is 1.5x). I'd guess the app registers it needs to run at 1.5 screen scale, then realizes the app is now running at 1.x and but forgot intermediate points should no longer be divided by 1.5x.
If I multiply the reported values by 1.5, and add the 30px that the canvas has as margin (or remove the margin), I get a perfect alignment.

Note: The issue does not seem to happen on single-monitor high-dpi setups, so I'm assuming it's related to multiple monitors at different DPIs

Expected behavior:
Intermediate and current touch points coincide.

Minimal repro:
Xaml:

    <Grid>
        <Canvas Margin="30" x:Name="canvas" TouchMove="canvas_TouchMove" IsManipulationEnabled="True" Background="White" />
    </Grid>

xaml.cs code-behind:

     private PathFigure intermediatePoints;
        private PathFigure currentPoint;

        private void canvas_TouchMove(object sender, TouchEventArgs e)
        {
            foreach (var p in e.GetIntermediateTouchPoints(canvas))
                intermediatePoints = AddVertex(p.Position, intermediatePoints, Colors.Red, 3);
            currentPoint = AddVertex(e.GetTouchPoint(canvas).Position, currentPoint, Colors.Blue, 1);
        }

        private PathFigure AddVertex(Point point, PathFigure pf, Color color, double width)
        {
            if (pf == null)
            {
                pf = new PathFigure(point, new PathSegment[] { }, false);
                PathGeometry pg = new PathGeometry(new PathFigure[] { pf });
                Path p = new Path() { Data = pg };
                p.StrokeThickness = width;
                p.Stroke = new SolidColorBrush(color);
                canvas.Children.Add(p);
            }
            else
            {
                pf.Segments.Add(new System.Windows.Media.LineSegment(point, true));
            }
            return pf;
        }

app.manifest:

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- Windows 10 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
    </application>
  </compatibility>

  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitor</dpiAwareness>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
  </application>
</assembly>

Make sure you include the manifest in csproj:

  <PropertyGroup>
    <ApplicationManifest>app.manifest</ApplicationManifest>
  </PropertyGroup>

Repro project:
TouchMoveDpiRepro.zip

Activity

  1. rladuca commented on Oct 21, 2019

    @rladuca
    Member

    WPF stores its own set of intermediate points for touch moves due to the way in which it gets touch data in the first place. Since touch data comes off the message loop via a shared memory channel with WISP, there used to be an issue with flooding the UI thread with touch moves. We implemented a coalescing scheme in order to deal with that.

    That's done here:

    void CoalesceAndQueueStylusEvent(RawStylusInputReport inputReport)

    This is just the raw data directly from WISP though. The actual transformation and return is handled here:

    public override TouchPointCollection GetIntermediateTouchPoints(IInputElement relativeTo)

    I'll have to look further as to why the data isn't transforming correctly, but those are the investigative starting points.

  2. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor

    Yeah I'm trying to start using TouchMove's intermediate points to get a smoother curve because of this coalescing, but this dpi issue prevents me from really using it.

    I've been poking around too, and found it curious that the intermediate touch points does some transformation here:

    GetRootTransforms(relativeTo, out elementToRoot, out rootToElement);

    where's it doesn't do that for the current point:

  3. rladuca commented on Oct 21, 2019

    @rladuca
    Member

    Both GetPosition and GetStylusPoints do transformations. GetPosition is a lot less complicated as it doesn't reformat the collection.

    See here:

    internal override StylusPointCollection GetStylusPoints(IInputElement relativeTo, StylusPointDescription subsetToReformatTo)

    The reformatting is likely the culprit here:

    internal StylusPointCollection Reformat(StylusPointDescription subsetToReformatTo, GeneralTransform transform)

  4. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor

    Added the GetPosition to the GetIntermediateTouchPoints method, and the difference between the values returned are pretty clear (see pinned values):

    image

  5. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor

    The reformat method just moves the pixels 30 pixels up and over:
    image

  6. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor
  7. rladuca commented on Oct 21, 2019

    @rladuca
    Member

    If your window is very close to the top left of the screen, how far off are the numbers?

    WISP's raw data is relative to the client area IIRC.

  8. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor

    It doesn't look like it's relative to the screen, but it is indeed relative to the window.
    dpioffset

  9. rladuca commented on Oct 21, 2019

    @rladuca
    Member

    I don't have a touch screen right now (not in the office) and I don't have time to write injection code just now, but I can take a look a deeper look this week assuming you don't root cause it before then.

    Just poking around, this set of code makes me curious as to how we are storing and returning the raw data:

    I think we're missing some transformation similar to this for returning the intermediate points.

  10. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor

    OK. I'll poke around more as I'm set up to build and test out fixes, but feel free to give more pointers as this part of WPF is completely unknown to me.

  11. added
    Bug
    on Oct 21, 2019
  12. added this to the 5.0 milestone on Oct 21, 2019
  13. dotMorten commented on Oct 21, 2019

    @dotMorten
    ContributorAuthor

    So this is most likely not the correct fix (I wouldn't be surprised if it broke something else as I don't fully understand this code), but I managed to hack a fix into WispStylusDevice's UpdateState(RawStylusInputReport) method:

    image

  14. rladuca commented on Oct 22, 2019

    @rladuca
    Member

    @dotMorten Awesome! It seemed suspect that we weren't applying that transformation coming out of the intermediate points as well.

    I think we don't want to alter the actual raw points that are stored here. We probably just want to add to the transform coming out of GetIntermediateTouchPoints.

  15. 15 remaining items

  16. rladuca commented on Oct 27, 2019

    @rladuca
    Member

    I took a look at this, and I think the changes are going to require some re-thinking of a few pieces of code in the WISP stack.

    I was going to store the cached matrix in the PenContexts class that has a mapping in WispLogic (PresentationSource to PenContexts). The problem here is that the transformations are sometimes used to re-acquire a new PresentationSource if the old one became invalid during the time the input took to go from the StylusThread to the UI thread.

    private PresentationSource DetermineValidSource(PresentationSource inputSource, StylusPointCollection stylusPoints, PenContexts penContextsOfPoints)

    So that got me thinking about per-mon DPI and how we are processing points prior to actually having the window. I think that code above might need changing to something more akin to:

    private class WindowStartupTopLeftPointHelper

    Modifying that paradigm to deal with getting coordinates from a PenContext and trying to find them in the correct screen (much like we're doing for saved Top/Left coords). I'll have to put more thought into how to do this correctly.

    Anyway, I think this just belies a broader set of issues with the WISP based stack not working well in Per-Monitor DPI modes.

    The best way to deal with the basic storing of the matrix might be to (in WispLogic) just store it per DpiScale2 we see and then look that up based on the DpiScale2 of the HwndSource we are dealing with. This should work fine since TransformToDevice is just a scaling based on DPI.

    If we don't find a cached Matrix for that DpiScale2, then we query the actual TransformToDevice matrix. I think that's probably the best way to cache it as the various functions seemingly always have access to an HwndTarget via WispStylusDevice.CriticalActiveSource. We can just internally expose the DpiScale2 stored there for our purposes.

    I'll try to dedicate some more time to this soon, just to keep tracing through the potential touch points (awful term to use in this context) of all the code changes we'd need.

  17. rladuca commented on Oct 29, 2019

    @rladuca
    Member

    Working on changes in this branch: https://github.com/rladuca/wpf/tree/permonstylus.

    Feel free to pick up and go from what I have (or alter it if you find something wrong).

    I am going to do some very basic testing at some point today, but as of the posting of this comment I just verified it builds.

  18. rladuca commented on Oct 29, 2019

    @rladuca
    Member

    @dotMorten I took your repro and tested it out.

    On my main touch screen (200% scale) the lines tracked correctly. I then moved it to my secondary touch screen (125% scale) and they still tracked.

    You can see the results in the screenshot. THe "M" is from the main screen, the "S" is the secondary.

    image

    There is more testing and evaluation to be done here, but the set of changes seems promising.

  19. rladuca commented on Oct 29, 2019

    @rladuca
    Member

    @dotMorten Modified your repro to open multiple windows and that all seemed to work as well.

    After some thought, I don't really see the point in not caching this in HwndTarget itself. It's already responding to DPI changes to update the DPI scale, so it can just update the transform as well when that happens. I'll think about that further, but that's a lot nicer than caching it in WispLogic.

    @vatsan-madhavan Can you see any reason to not just cache the following transform and update on DPI changes?

  20. weltkante commented on Oct 29, 2019

    @weltkante

    I don't know how defensive you want to be, but you probably want to be careful that you aren't handing out direct references to a cached mutable object through public API. Users could edit it and mess up the cache, its probably a good idea to always hand out a frozen instance or a copy, or only make the cached instance available through internal API.

  21. TanayBhalani commented on Apr 12, 2020

    @TanayBhalani

    I have followed below article, and found it is now working perfect for me.
    I am using WPF .NET Framework 4.5.2 on Windows 10
    The solution is tested for .Net Core also and different windows version

    Per Monitor DPI Awareness

  22. vatsan-madhavan commented on Apr 13, 2020

    @vatsan-madhavan
    Member

    Can you see any reason to not just cache the following transform and update on DPI changes?

    It's not meant to be cached normally. Unless you are trying to keep track of the TransformToDevice at the time you decide to cache it (i.e, a point-in-time value, or a historical value), just keep track of the associated HwndTarget directly and look up the value of the transform whenever its needed - that way the transform would always be current.

  23. rladuca commented on Apr 13, 2020

    @rladuca
    Member

    It's not meant to be cached normally. Unless you are trying to keep track of the TransformToDevice at the time you decide to cache it (i.e, a point-in-time value, or a historical value), just keep track of the associated HwndTarget directly and look up the value of the transform whenever its needed - that way the transform would always be current.

    I mean to finish this off soon, the fix I have in my branch sidesteps needing the HwndTarget transform. Since these transforms solely depend on the DpiScale2, I'm just mapping that to a cached transform.

  24. removed their assignment
    on May 26, 2020
  25. rladuca commented on May 26, 2020

    @rladuca
    Member

    @fabiant3 Bumping this to triage and unassigning it. The PR is waiting for review.

  26. self-assigned this
    on May 27, 2020
  27. walterlv commented on Jun 22, 2020

    @walterlv
    Contributor

    stylus-move-points-not-pm-dpi

    I've also tested the per-monitor DPI and find the same issue.

  28. ryalanms commented on Feb 3, 2021

    @ryalanms
    Member

    @rladuca's fix is in master (.NET 6.0) and has been approved for the 5.0.4 servicing release.

  29. ghost locked as resolved and limited conversation to collaborators on Apr 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions