Handling text cursor

Issue #1398 new
Oleg Dudka
created an issue

Is there any simple way to obtain text character index at given x-coordinate? Or find substring width without actually split string?

If no, I propose add getGlyphWidth(uint32) and getGlyphKerning(uint32,uint32) methods into Font class, to be able manually iterate through string until width sum reach required x-coordinate.

It would be quite helpful for creating text fields.

Comments (2)

  1. Gabe Stilez

    https://love2d.org/wiki/Font:getWidth

    I'd rather see an additional parameter to the above linked function to give the maximum amount of codepoints it should count, that way the string splitting may be averted, though that depends on how it's already implenented internally. (Otherwise your getGlypWidth and getGlyphKerning functions are no better than storing all singular characters and character pairs, and calculating their width and the distance between the pairs.)

    As for getting the codepoint index under the cursor or whatever, that needs to be calculated.

  2. Oleg Dudka reporter

    Otherwise your getGlypWidth and getGlyphKerning functions are no better than storing all singular characters and character pairs, and calculating their width and the distance between the pairs.

    All that already stored inside love, we just don't have access to it from lua. At the moment I'm using next patch to retrieve this info:

    // wrap_Font.cpp (v10.2)
    
    int w_Font_getGlyphWidth(lua_State *L)
    {
        Font *t = luax_checkfont(L, 1);
        uint32 glyph = luaL_checknumber(L, 2);
        const Font::Glyph &g = t->findGlyph(glyph);
        lua_pushnumber(L, g.spacing);
        return 1;
    }
    
    int w_Font_getGlyphKerning(lua_State *L)
    {
        Font *t = luax_checkfont(L, 1);
        uint32 leftglyph = luaL_checknumber(L, 2);
        uint32 rightglyph = luaL_checknumber(L, 3);
        lua_pushnumber(L, t->getKerning(leftglyph, rightglyph));
        return 1;
    }
    
    ...
    static const luaL_Reg w_Font_functions[] =
    {
        { "getHeight", w_Font_getHeight },
        { "getWidth", w_Font_getWidth },
        { "getWrap", w_Font_getWrap },
        { "setLineHeight", w_Font_setLineHeight },
        { "getLineHeight", w_Font_getLineHeight },
        { "getGlyphWidth", w_Font_getGlyphWidth},
        { "getGlyphKerning", w_Font_getGlyphKerning},
        { "setFilter", w_Font_setFilter },
        { "getFilter", w_Font_getFilter },
        { "getAscent", w_Font_getAscent },
        { "getDescent", w_Font_getDescent },
        { "getBaseline", w_Font_getBaseline },
        { "hasGlyphs", w_Font_hasGlyphs },
        { "setFallbacks", w_Font_setFallbacks },
        { 0, 0 }
    };
    
  3. Log in to comment