Skip to content
This repository was archived by the owner on Mar 3, 2023. It is now read-only.
This repository was archived by the owner on Mar 3, 2023. It is now read-only.

We need a better approach to text measurement #6055

Closed

Description

@nathansobo

When Chrome 39 added support for subpixel font scaling, it broke our approach to horizontal position measurement. We disabled subpixel scaling with a flag, but that was only a temporary stopgap measure. The truth is our existing approach to measuring horizontal positions on screen is somewhat ill-conceived, and it needs to be changed.

The existing approach

In our existing approach, we attempt to measure the width of characters in a given context. So, for example, we can determine that the width of an a character in the .source.coffee .meta.function.coffee is 11px at the current font size. Then, when we calculate the pixel position for a given row and column, we just simply total up the recorded width for every character we encounter.

The problem is that for non fixed-width fonts, a given character doesn't have a single width. Kerning, ligatures, and other stuff the type rendering engine does can result in an a taking up different amount of space in different contexts. I am not an expert in this area yet. What's worse, when subpixel font scaling is turned on, Chrome starts reporting different widths even for fixed width fonts. We're going to need a different approach.

Idea for a better approach

My current thinking is that when calculating a pixel position, we need to explicitly measure the distance from the beginning of the line to the column in question rather than consulting our encyclopedia of character widths. This was our original approach but I moved away from it because we were naively reading the DOM whenever we needed to translate positions, which was causing reflows.

But we actually can safely read this information, so long as we do so either at the start of an update before we actually update the DOM, or at the end of an update, after we are finished updating the DOM. When simply moving the cursor, we can measure before the update. When typing, however, we need to measure after the update in order for the content to be on screen, then trigger another update based on our measurement.

We may also be able to make these measurements off-DOM, like in an iframe or something. My main concern here is making sure that we capture all the styling that's applied to the text. We may be able to draw a line at the shadow boundary, and just say the only styling that we will apply for purposes of character measurement is the syntax themes. Theme stylesheets could easily be loaded in an iframe via the atom-styles element. Or we could set up the entire world in this iframe and measure there.

Or maybe there's some other, better approach to character measurement out there that Atom should apply instead. The main requirements are as follows:

  • Measurement should not force a blocking reflow.
  • Measurement should capture user styling as seamlessly as possible.
  • Measurement should handle different widths being reported for the same character in different contexts, as is currently the case with subpixel font scaling enabled.

Can anyone from the community help out with this? Ideas are welcome if they're specific. Code would be even more helpful. @as-cii I know I'm pinging you on a ton of stuff lately but this seems right in your wheelhouse based on your recent presenter work.

/cc @atom/non-github-maintainers

Activity

  1. superlou commented on May 5, 2015

    @superlou

    Would these new strategies for measurements allow positioning the cursor accurately in cases where padding/margins causes the div.line's characters to begin with an offset, e.g. padding in a line to create different soft-wraps based on grammar matches?

  2. nathansobo commented on May 5, 2015

    @nathansobo
    ContributorAuthor

    More might be required, but this would be an essential building block in that kind of power. I'd like to have a world where lots of things like this could be styled via CSS, but there may be limits on what we can do in a general way. For those kinds of things we'd need to introduce explicit APIs, such as the soft-wrap overhang.

  3. ahmadseleem commented on May 25, 2015

    @ahmadseleem

    Please take a look at chocolat app:
    https://chocolatapp.com
    They have a basic vim emulator and ligatures works perfectly.
    Cursor have two states one in normal mode which treats it as a one entity. Maybe they use extra margin on the sides for ligatures to be like a fixed width. I'm not sure.

  4. rajadain commented on May 25, 2015

    @rajadain

    One approach that I think both Hasklig and Fira Code follow is that their ligatures take the same amount of space as the underlying characters. For example, if three equals signs form a ligature === then the final ligature uses the same amount of space:

    Ligatures

    No Ligatures

    Wouldn't that assumption make cursor position calculation easier? Just count the number of characters. Admittedly, this is what the current code should be doing, and I'm not sure I understand why this doesn't work out of the box.

  5. alexandernst commented on May 25, 2015

    @alexandernst

    That won't work. A ligature is, by definition, not equal to the space taken by all characters it represents. Consider this: fn -> λ (or even function -> λ)

  6. tonsky commented on May 25, 2015

    @tonsky

    Right, but still, it’s not clear why it doesn’t work with Hasklig or Fira
    Code. E.g. === is 3em either if calculated from character width or taken
    from ligature width.

    On Tue, May 26, 2015 at 3:39 AM Alexander Nestorov [email protected]
    wrote:

    That won't work. A ligature is, by definition, not equal to the space
    taken by all characters it represents. Consider this: fn -> λ (or even function
    -> λ)

    —
    Reply to this email directly or view it on GitHub
    #6055 (comment).

  7. 190n commented on Jun 7, 2015

    @190n

    What about using Canvas and the Text Measurement API?

    function charWidth(char, fontString) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        ctx.font = fontString;
        return ctx.measureText(char).width;
    }
  8. nathansobo commented on Jun 8, 2015

    @nathansobo
    ContributorAuthor

    My concern with using canvas is that it requires us to measure every unique prefix of the line as a separate call, paying for all the text layout over again each time. I'm hoping we can find a solution that allows us to pay for layout once and then measure every column's position in a single pass. That's why I'm leaning toward something based on a DOM layout. Of course, I'm always open to my concerns being invalidated with measurements.

  9. as-cii commented on Jun 10, 2015

    @as-cii
    Contributor
    1. Measuring 12 lines with range.getBoundedClientRect: ~ 4-7ms (skinny DOM, no styles sampling)
    2. Measuring 12 lines with canvas.measureText: ~ 3-6ms (no styles sampling)

    TL; DR; I am afraid the iframe + range.getBoundedClientRect "eager" approach is not fast enough. Layout and style recalculation is not the actual bottleneck, 'cause they are already triggered when we render new lines. Measuring e.g. 12 lines char by char is just slow even on a skinny document and I am searching for an alternative.

    One of our most performance sensitive scenarios is text scrolling and we need to respect a ~16ms performance budget (although I think I'd be somewhat fine with 50 < FPS < 60).

    Based on the timings I collected (which vary among measurements), we can assume that with a remarkably fast scroll, each peak frame (i.e. a frame where a new tile has to be created and painted) takes up to 12ms on average (and, when the tiled gutter lands, we may shave 1-2ms more). That, in turn, means we could hypothetically have a reasonable slice of time where we could perform measurements.

    Averages are not great, though, as there will be some slow frames which'll be further slowed down by the new measurement technique and won't meet the 50-60FPS requirement. Even though I still think we can further speed up Layout and Recalculate Styles I'd ❤️ to have more control over text measurement.

    WebKit APIs won't currently allow that, but skimming through the codebases (i.e. skia, chromium, blink) revealed that per-glyph information is actually stored somewhere. In an ideal world, we could just access the already stored data and use it to fill our own database of character positions per line. On the other hand, I am not sure we can hack electron to "steal" this data. Maintainability could become a major pain point, but I still think it would be great to provide an API for this stuff, so it's still worth exploring IMHO.

    How could we implement such API? It needs to look at skia data structures (e.g. SkTextBlob should have glyph-by-glyph positions within each TextRun) and expose a simple method to access it. This approach would be both fast and correct, unless I am missing something (which is very likely). Is the maintainability tradeoff worth it? I don't know.

    While discussing with @nathansobo a while back, I proposed a lazily computed version of pixelPositionForScreenPosition. If you will, it means we would go back to the previous implementation and stop calculating everything for each line: we would do so only for the requested positions. And if we store them with absolute coordinates, we just need to:

    • Locate the node;
    • Create a 1 character wide Range within the node, corresponding to the requested position;
    • Return Range#getBoundingClientRect().left (without consulting any previous measurements within the same line);

    @nathansobo correctly argued that when lots of (cursors | decorations) are in place we might still experience some slowdowns and I somewhat agree, although the worst case time would be <= 7ms (i.e. we would measure all the characters for all the lines, as I did on the benchmarks above).

    Thoughts? 💭

  10. nathansobo commented on Jun 10, 2015

    @nathansobo
    ContributorAuthor

    Wow. Quite a write up. I think it makes perfect sense to perform measurement lazily, so long as it doesn't involve a blocking read of the main document. Are you proposing lazy measurement in an iframe? If so, I like the idea. Eager measurement was only really necessary when the only alternative was a blocking document read. If reading from an iframe works, we should for sure measure lazily.

    Also, there's an official measurement API being discussed here. Not sure it's the best use of time to start implementing this ourselves unless absolutely necessary, but we may want to use this as a starting point if we did.

    My vote is to proceed with lazy off-document measurement and see how things feel.

  11. as-cii commented on Jun 11, 2015

    @as-cii
    Contributor

    My vote is to proceed with lazy off-document measurement and see how things feel.

    Sound excellent! ✨

    I am going to work on that as soon as #7101 lands! 🎆

  12. ai commented on Jul 17, 2015

    @ai

    Ligatures is so awesome in code. Really useful.

  13. hamosapience commented on Jul 17, 2015

    @hamosapience

    Why not just calculate sizes of all ligatures AOT?

  14. as-cii commented on Jul 18, 2015

    @as-cii
    Contributor

    Why not just calculate sizes of all ligatures AOT?

    Hey @hamosapience, thanks for leaving your feedback here. Ligatures are, unfortunately, only a part of the picture: indeed, Chrome has introduced subpixel font scaling and, as a result, the same letter (or ligature) could have a different width based on its context.

    I think that relying on the document to inspect the actual characters positions is the way to go and I am experimenting something in #7945 if you are interested. Hopefully that approach will turn out to be as fast and as reliable as I expect and we can use it to solve this issue once for all (until a real measurement API lands in Chrome).

  15. winstliu commented on Oct 7, 2015

    @winstliu
    Contributor

    @nathansobo @as-cii Can this be closed now?

  16. nathansobo commented on Oct 8, 2015

    @nathansobo
    ContributorAuthor

    Yep. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions