Tk Source Code

View Ticket
Login
Ticket UUID: 7655f65ae71cbf61dd594e03846723073d23adb1
Title: fix text positioning issues in entry widgets (and possibly elsewhere)
Type: Patch Version: 8.6.10
Submitter: chrstphrchvz Created on: 2020-04-16 01:23:12
Subsystem: 07. [entry] Assigned To: chrstphrchvz
Priority: 5 Medium Severity: Minor
Status: Closed Last Modified: 2024-11-14 16:26:38
Resolution: Fixed Closed By: jan.nijtmans
    Closed on: 2024-11-14 16:26:38
Description:

Both the Ttk and non-Ttk entry widgets (in tkEntry.c:DisplayEntry() and ttkEntry.c:EntryDisplay() respectively) draw the entire visible text and then redraw the selected (highlighted) portion again using a different gc. This approach is not ideal on Aqua, because the selected text may not line up perfectly with where it occurs within the entire visible text, leading to "shadow" artifacts; and even when it does line up perfectly, antialiasing can still leave behind "outline" artifacts, especially when -foreground and -selectforeground differ. In general, Tk should not be assuming that redrawing text on top of where it was already drawn will look right on Aqua; doing so may also also be inefficient compared to drawing glyphs only once.

Example where selected text should disappear completely:

pack [entry .e -font {{Courier New Bold} 64} -width 12 \
    -background darkblue -foreground white \
    -selectforeground black -selectbackground black]
pack [ttk::entry .te -font {{Courier New Bold} 64} -width 12 \
    -foreground white]
ttk::style configure TEntry -selectforeground black -selectbackground black

"Shadow" misalignment artifacts:

"Outline" antialiasing artifacts:

Rewriting DisplayEntry()/EntryDisplay() to draw the selected and unselected portions separately eliminates the artifacts:

But addressing this issue causes another to appear: the visible glyphs can shift by about 1 pixel as the selection changes (APNG demo):

My understanding is that this is because Aqua lays out text for an entire line/string expecting that it will be provided that entire line again when drawing, even if only a portion of it is to be drawn, so that glyphs are positioned correctly with subpixel precision. It is inadequate to use Tk_DrawChars() and similar functions to draw a substring since they don't provide provide Aqua the entire string for reference. It is possible to instead use TkpDrawCharsInContext() and similar functions (as done in tkTextDisp.c) to draw a substring while providing Aqua the entire string to ensure correct positioning.

These two fixes combined provide the appearance I expect: no artifacts when selecting text, and no shifting of glyphs based on selection range, cursor position, etc. (APNG demo):

I am preparing a couple of patches which I believe should address these issues.

User Comments: jan.nijtmans added on 2024-11-14 16:26:38:
I don't know if refactoring is going to happen or already happened, but anyway, I think this ticket can be closed.

fvogel added on 2020-07-13 16:51:49:

I have now merged the bugfix branch in core-8-6-branch and in trunk (the latter was a bit more complicated due to conflict with the implementation of TIP #496 but I should have got this right).

I'm closing the bugfix branch but I'm leaving this ticket open, so that refactoring can happen.


chrstphrchvz added on 2020-07-12 14:09:12:

Looks good—thanks, Francois!


fvogel added on 2020-07-12 09:36:41:
Hi Christopher,

I have taken all your input I think, and committed everything accordingly. Could you please check and confirm?

Thanks!

chrstphrchvz added on 2020-07-11 16:56:24:

There indeed was a regression: if an entry contains a multi-byte character, and a range is selected which includes or occurs after that character, then an incorrect range is used to draw selected text. I have attached a patch which I believe fixes this: TkpDrawCharsInContext() and TkpDrawAngledCharsInContext() should be provided (firstByte - chunkPtr->start) rather than firstChar, and (lastByte - firstByte) rather than (numDisplayChars - firstChar).

Note that when merging core-8-6-branch and the bugfix branch, a portion removed from tkFont.c by [4eafaf969c] needs to be restored in order for the fix in [f7f8ba2e3e] to have an effect:

#if defined(MAC_OSX_TK)
#include "tkMacOSXInt.h"
#endif

This is needed because tkMacOSXInt.h is what defines TK_DRAW_IN_CONTEXT.


chrstphrchvz added on 2020-07-11 13:03:50:

I'd like for this fix to appear in 8.6.11 if possible; I will forego optional refactoring until after 8.6.11 is released. There is a tiny conflict with [bfa04527b3] (work done for [a179564826]), but this is a stronger indication of the possible regression I mentioned; I am currently verifying if there is indeed a problem. It would probably be good to leave comments that the draw-in-context functions in tkUnixFont.c, tkUnixRFont.c, and tkWinFont.c are unused and possibly unfinished, and to see this ticket.


chrstphrchvz added on 2020-05-18 14:22:24:

Please hold off merging this for now. I was most of the way through the refactoring/optimization, got sidetracked, and didn't finished testing it. But I now notice there might be a regression where using the draw-in-context functions bypasses the index vs. byte offset discrepancy handling done Tk_DrawTextLayout()/TkDrawAngledTextLayout(). Even if there's no regression, maybe it indicates this sort of handling should still be replicated or moved somewhere more universally applicable.


fvogel added on 2020-05-01 12:06:13:

I have now merged bug-cd8714756c and bug-2712f43f6e in the bugfix branch dedicated to the present ticket.


chrstphrchvz added on 2020-04-26 22:35:35:

X Error crash discussed in [2712f43f6e].

Moreover I would like to add test cases in the test suite…

For the entry artifacts issue, it seems strange to want to have a regression test for it, because the cause is at a relatively high level: it was directly caused by the old approach used to draw entry text (intentionally draw selection on top of all visible text); there's no chance of artifacts spontaneously reappearing unless someone reverts to using the old approach.

For the moving text issue, the cause is at a lower level, and makes more sense to have a text for. A test similar to the partially-automatic one added in [2d463458cb] (for [2712f43f6e]) should be sufficient to see text move as it is selected/unselected; adding more characters helps exaggerate the issue.

tk scaling 1.0
grid [canvas .c -background darkblue -selectforeground orange -height 350 -width 500]
set id [.c create text 20 300 -anchor w -text "A somewhat longer line of angled text" -angle 30 -font {Helvetica 32} -fill lime]
for {set sel_amt 0} {$sel_amt <= 18} {incr sel_amt 1} {
    update
    after 400
    .c select clear
    .c select from $id [expr {18-$sel_amt}]
    .c select to   $id [expr {18+$sel_amt}]
    update
    after 400
    .c select clear
    .c select from $id [expr {18-$sel_amt}]
    .c select to   $id [expr {19+$sel_amt}]
}

Current behavior on Windows:

What I'm however slightly hesitant is about your removal of the if (angle == 0.0) optimizations. While the performance speed is perhaps small, angled text seems to be much less often used than horizontal test, thus optimizing this latter case still makes sense to me, especially since there could be use cases displaying a large number of text canvas items for instance.

In that case, there are various other places where there should already be such (angle == 0.0) optimizations. Some of the structures have caches for sine and cosine that might also be used more. At this point I'd prefer waiting for bug-cd8714756c and probably also bug-2712f43f6e to be merged before I do any refactoring.


fvogel added on 2020-04-22 21:19:24:

Sorry, I'm only catching up now.

Using the mentioned "Text items in canvases" demo I can see the shifting of rotated text when the angle is not zero, in both the bugfix branch and core-8-6-branch. That's fine. I only wanted to make sure this effect was not newly introduced by the patches. Especially since it seems ([2816150]) that this is really hard to fix, we don't need to address this in the present ticket.

*Selecting text sometimes causes Tk to crash, and this seems to only happen when Xft is disabled. This happens on core-8-6-branch.
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  53 (X_CreatePixmap)
  Value in failed request:  0x0
  Serial number of failed request:  141416
  Current serial number in output stream:  141421

Selection of rotated text causing crashes deserves its own ticket IMO. There were similar reports in the past, (message looked the same), but never linked to selection of rotated text when Xft is disabled, to my knowledge. Again not a regression since you say it's happening in core-8-6-branch. Would you mind opening such a ticket, if you can reproduce?

Those were more just ideas for eventual refactoring, but I wouldn't mind trying to implement them now as a separate patch. Also, I would think computing sin() and cos() once or twice is insignificant compared to actually drawing a chunk of text, so I would also remove the if (angle == 0.0) {…} optimizations.

I would happily examine such a patch from yours :-).

What I'm however slightly hesitant is about your removal of the if (angle == 0.0) optimizations. While the performance speed is perhaps small, angled text seems to be much less often used than horizontal text, thus optimizing this latter case still makes sense to me, especially since there could be use cases displaying a large number of text canvas items for instance.

would it be alright to clarify the check-in comment for [52f87eb1a8]

Sure. I changed it, I hope it's OK now.


chrstphrchvz added on 2020-04-22 16:58:27:

…the point being that the text color isn't responsible for the problem (removing the optimization makes the text shift even when -fill and -selectedforeground are identical).


chrstphrchvz added on 2020-04-22 16:50:42:

…and only when the canvas' -selectforeground color is effectively different from the text's -fill color

This happens because of the optimization in DisplayCanvText() that draws selected and unselected text separately only when their GCs differ:

if ((selFirstChar >= 0) && (textPtr->selTextGC != textPtr->gc)) {
    /* Draw selected and unselected text separately */
} else {
    /* Draw entire text */
}


chrstphrchvz added on 2020-04-22 14:15:11:

Francois, would it be alright to clarify the check-in comment for [52f87eb1a8]? Reading it, my impression is that the first patch only worsens what happens on Aqua. I would argue it makes a partial improvement on Aqua (the purpose of the first patch is to completely eliminates artifacts for selected text in entry widgets on all platforms). The subsequent check-in addresses text positioning/shifting problems (only apparent on Aqua) rather than artifacts, which already exist before applying the first patch even though I originally phrased this as "addressing [the first] issue causes another to appear" (the positioning issue is what causes "shadow" misalignment artifacts; were the second patch applied before the first, misalignment artifacts would be absent but antialiasing ones would still be present).


chrstphrchvz added on 2020-04-22 05:17:28:

My testing for this is stumbling onto a few other bugs, some long-known and which were already determined to likely have no easy fix for, particularly [2816150] which suggests rotated text positioning issues on Windows are intractable with the old Win32 API unless dealt with at the level of individual characters/glyphs. I think a better idea at this point might be to migrate to a newer API like DirectWrite (Windows Vista and later) and not put too much more work into the old Win32 API usage (but can leave it in if needed). But I might be approaching a stopping point for this issue.


chrstphrchvz added on 2020-04-21 20:37:06:

I now remember that canvas text does support selection, and that the "Text items in canvases" widget demo (ctext.tcl) can be used to test this. Canvas text is drawn using TkDrawAngledTextLayout(), which in turn uses Tk_DrawChars() and TkDrawAngledChars() (or, with these patches, TkpDrawCharsInContext() and TkpDrawAngledCharsInContext() if TK_DRAW_IN_CONTEXT is defined).

Using that demo, I verified that rotated text shifting happens under core-8-6-branch and earlier, at least on Windows and on X11 with Xft disabled* (I haven't noticed it with Xft enabled), and only when the canvas' -selectforeground color is effectively different from the text's -fill color (which it can be by default on some platforms). It also seems to depend on the font used, so I am still trying to find a good reproducible example. This is a rather noticeable issue, because portions of text may shift by multiple character widths and become clipped by other text portions or the drawing bounds for all of the text. Even unselected rotated text can be clipped.

Interestingly someone noticed a long time ago for canvas text that selected and unselected portions needed to be drawn separately to prevent antialiasing artifacts ([968725]).

Finally, regarding your last paragraph in your answer below, my understanding is that there is still some low hanging work/improvements to do.

Those were more just ideas for eventual refactoring, but I wouldn't mind trying to implement them now as a separate patch. Also, I would think computing sin() and cos() once or twice is insignificant compared to actually drawing a chunk of text, so I would also remove the if (angle == 0.0) {…} optimizations.

*Selecting text sometimes causes Tk to crash, and this seems to only happen when Xft is disabled. This happens on core-8-6-branch.

X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  53 (X_CreatePixmap)
  Value in failed request:  0x0
  Serial number of failed request:  141416
  Current serial number in output stream:  141421


fvogel added on 2020-04-21 07:10:18:

Again, thank you for this (third) patch. I have now committed it in branch bug-7655f65ae for easier testing. Btw, do you perhaps have a ready to use visual test script that you could share, especially for rotated text?

Moreover I would like to add test cases in the test suite, but I'm not sure it is possible since this is all about fixing a visual artifact. The bounding box of a rotated text could perhaps be tested as a result of some of the new routines (but I don't remember off the top of my head if this bounding box rotates as well as the text or not). If automatic testing is not possible we could look at adding something to the visual test suite of Tk (visual_bb.test and companion files).

And I really would like to get testing results from a mac user (beyond you as the author).

Jittering of rotated text while selecting it is something we should make sure was already present before your patches (this sounds easy enough: does it happen in core-8-6-branch?)

Finally, regarding your last paragraph in your answer below, my understanding is that there is still some low hanging work/improvements to do.


chrstphrchvz added on 2020-04-20 01:11:57:

I am working on a third patch (to apply on top of [f7f8ba2e3e])…

Now uploaded.


chrstphrchvz added on 2020-04-19 23:16:50:

I am working on a third patch (to apply on top of [f7f8ba2e3e]) which will do the following:

  • Fix the TkpDrawAngledCharsInContext() implementations for angle != 0.0: widthFromStart needs to be scaled by cos(angle * PI/180.0) and -sin(angle * PI/180.0) before passing to TkDrawAngledChars().
  • Copy the TkpDrawCharsInContext() and TkpDrawAngledCharsInContext() implementations from tkUnixFont.c to tkUnixRFont.c, since tkUnixFont.c is for when Xft support is disabled. (Is there a better way of sharing implementations between these two files?)
  • Unmark TkpDrawCharsInContext() and TkpDrawAngledCharsInContext() as UNTESTED.

I believe I have now completely tested these patches' changes on Windows and X11, including the unused TkpDrawCharsInContext() and TkpDrawAngledCharsInContext() on Windows and X11.

On Windows and X11, I notice that for angle != 0.0 the chunks of a string may shift slightly as the selection moves, similar to what I noticed on Mac without the second patch. (I think this is an existing issue I notice while testing my patches rather than an issue I introduced.) This may not be an issue in core Tk, since it doesn't seem to have any rotated widgets supporting text selection, but not sure if possibly still an issue for extensions. I haven't spotted what causes this, though I'm not certain it can be fixed since the Win32 and X11 functions used by Tk_MeasureChars() don't appear to return subpixel measurements.

Finally is it that ultimately the #if 0 in Tk_DrawTextLayout in tkFont.c should become an #if 1 (that is: remove everything else in that function)?

I had left in the #if 0 to illustrate how I tested TkDrawAngledTextLayout(), but to reduce the number of lines to maintain and avoid code repetition, I think Tk_DrawTextLayout() should just call TkDrawAngledTextLayout() with angle = 0.0. I don't think the former is sufficiently simpler or faster to justify keeping separate. Likewise any Tk_DrawChars() implementations should just use TkDrawAngledChars() with angle = 0.0, and possibly even the TK_DRAW_IN_CONTEXT portions should be done on all platforms unconditionally.


fvogel added on 2020-04-19 10:28:11:

Thank you for this work, it looks very good!

I have reviewed and applied your "entrywidgets" patch, this patch is fully OK for me. It is quite straightforward, as you mentioned, and works for me on Windows (and since this is generic code, I'm sure it works on the other platforms as well, besides you already checked it).

Regarding the second patch, I have committed it as well, in the same bugfix branch bug-7655f65ae. While I do understand what you're doing here, I would like someone with a better access to a mac to review in details, try the patch in practice, and test extensively.

There is also some more work to do based on this second patch, as you have listed in your message below dated 2020-04-16 02:49:11.

Finally is it that ultimately the #if 0 in Tk_DrawTextLayout in tkFont.c should become an #if 1 (that is: remove everything else in that function)? This will have an impact on Windows and Linux in addition to the mac, I could test this if needed. What I can tell right now for Windows is that the test suite is happy on Windows with either #if 0 or #if 1.


chrstphrchvz added on 2020-04-16 11:49:24:

It turns out that "outline" antialiasing artifacts occur on Windows (left) and X11 (right) as well:


The 7655f65ae7-entrywidgets patch eliminates the artifacts:


chrstphrchvz added on 2020-04-16 03:20:39:

Reuploading 7655f65ae7-drawtextincontext: forgot to remove static void DrawCharsInContext(…) declaration.


chrstphrchvz added on 2020-04-16 02:49:11:

  • The 7655f65ae7-entrywidgets patch is rather straightforward: it makes the entry and ttk::entry widgets draw the selected and unselected text portions separately, which avoids redrawing the selected text.
  • The 7655f65ae7-drawtextincontext patch is slightly more involved. It fixes the alignment issue within the more widely-used Tk_DrawTextLayout() function. The TK_DRAW_IN_CONTEXT define (currently only used by tkTextDisp.c) is used to select between TkpDrawCharsInContext() and Tk_DrawChars(). The patch currently leaves in place variables and function calls not needed under TK_DRAW_IN_CONTEXT.

    The issue and corresponding fix also apply to Tk_DrawAngledTextLayout(). However, while it can immediately use TkpDrawCharsInContext() instead of Tk_DrawChars() for angle == 0.0, there is not already an analogous replacement for TkDrawAngledChars() when angle != 0.0. I have added this missing function, TkpDrawAngledCharsInContext(), and used it in Tk_DrawAngledTextLayout(). Its implementation for Aqua is actually the existing DrawCharsInContext(), and while it isn't already implemented for Windows or X11, I have added what I believe those should be, even though they would currently be unused, and I have not yet tested them. They are not very long, and are modeled after the existing TkpDrawCharsInContext() for those platforms, making use of TkDrawAngledChars() instead of Tk_DrawChars().

    A few other changes to note:

    On Aqua, TkpDrawAngledTextLayout() had arguments double x, y which when passed to DrawCharsInContext() were being truncated to become int x, y; TkpDrawAngledCharsInContext() avoids this by having arguments double x, y. This also means CGFloat textX, textY in DrawCharsInContext(), which were recently added to deal with [89354dae31], aren't needed; though the patch leaves them as-is.

    The comment for Tk_DrawChars() on Aqua had not been updated to reflect DrawCharsInContext() being split from TkpDrawCharsInContext() back in [a2e7757328]; that no longer an issue with this patch.

I'm not yet aware of any regressions these changes introduce. I will test these changes on Windows and X11 soon.


Attachments: