Beispiel #1
0
        /// <summary>
        /// Shape an array of utf-32 code points replacing each grapheme cluster with a replacement character
        /// </summary>
        /// <param name="bufferSet">A re-usable text shaping buffer set that results will be allocated from</param>
        /// <param name="codePoints">The utf-32 code points to be shaped</param>
        /// <param name="style">The user style for the text</param>
        /// <param name="clusterAdjustment">A value to add to all reported cluster numbers</param>
        /// <returns>A TextShaper.Result representing the shaped text</returns>
        public Result ShapeReplacement(ResultBufferSet bufferSet, Slice <int> codePoints, IStyle style, int clusterAdjustment)
        {
            var   clusters   = GraphemeClusterAlgorithm.GetBoundaries(codePoints).ToArray();
            var   glyph      = _typeface.GetGlyph(style.ReplacementCharacter);
            var   font       = new SKFont(_typeface, overScale);
            float glyphScale = style.FontSize / overScale;

            float[]  widths = new float[1];
            SKRect[] bounds = new SKRect[1];
            font.GetGlyphWidths((new ushort[] { glyph }).AsSpan(), widths.AsSpan(), bounds.AsSpan());

            var r = new Result();

            r.GlyphIndicies    = bufferSet.GlyphIndicies.Add((int)clusters.Length - 1, false);
            r.GlyphPositions   = bufferSet.GlyphPositions.Add((int)clusters.Length - 1, false);
            r.Clusters         = bufferSet.Clusters.Add((int)clusters.Length - 1, false);
            r.CodePointXCoords = bufferSet.CodePointXCoords.Add(codePoints.Length, false);
            r.CodePointXCoords.Fill(0);

            float xCoord = 0;

            for (int i = 0; i < clusters.Length - 1; i++)
            {
                r.GlyphPositions[i].X = xCoord * glyphScale;
                r.GlyphPositions[i].Y = 0;
                r.GlyphIndicies[i]    = codePoints[clusters[i]] == 0x2029 ? (ushort)0 : glyph;
                r.Clusters[i]         = clusters[i] + clusterAdjustment;

                for (int j = clusters[i]; j < clusters[i + 1]; j++)
                {
                    r.CodePointXCoords[j] = r.GlyphPositions[i].X;
                }

                xCoord += widths[0] + style.LetterSpacing / glyphScale;
            }

            // Also return the end cursor position
            r.EndXCoord = new SKPoint(xCoord * glyphScale, 0);

            // And some other useful metrics
            r.Ascent  = _fontMetrics.Ascent * style.FontSize / overScale;
            r.Descent = _fontMetrics.Descent * style.FontSize / overScale;
            r.XMin    = _fontMetrics.XMin * style.FontSize / overScale;

            return(r);
        }
Beispiel #2
0
        /// <summary>
        /// Shape an array of utf-32 code points
        /// </summary>
        /// <param name="bufferSet">A re-usable text shaping buffer set that results will be allocated from</param>
        /// <param name="codePoints">The utf-32 code points to be shaped</param>
        /// <param name="style">The user style for the text</param>
        /// <param name="direction">LTR or RTL direction</param>
        /// <param name="clusterAdjustment">A value to add to all reported cluster numbers</param>
        /// <param name="asFallbackFor">The type face this font is a fallback for</param>
        /// <param name="textAlignment">The text alignment of the paragraph, used to control placement of glyphs within character cell when letter spacing used</param>
        /// <returns>A TextShaper.Result representing the shaped text</returns>
        public Result Shape(ResultBufferSet bufferSet, Slice <int> codePoints, IStyle style, TextDirection direction, int clusterAdjustment, SKTypeface asFallbackFor, TextAlignment textAlignment)
        {
            // Work out if we need to force this to a fixed pitch and if
            // so the unscale character width we need to use
            float forceFixedPitchWidth = 0;

            if (asFallbackFor != _typeface && asFallbackFor != null)
            {
                var originalTypefaceShaper = ForTypeface(asFallbackFor);
                if (originalTypefaceShaper._isFixedPitch)
                {
                    forceFixedPitchWidth = originalTypefaceShaper._fixedCharacterWidth;
                }
            }

            // Work out how much to shift glyphs in the character cell when using letter spacing
            // The idea here is to align the glyphs within the character cell the same way as the
            // text block alignment so that left/right aligned text still aligns with the margin
            // and centered text is still centered (and not shifted slightly due to the extra
            // space that would be at the right with normal letter spacing).
            float glyphLetterSpacingAdjustment = 0;

            switch (textAlignment)
            {
            case TextAlignment.Right:
                glyphLetterSpacingAdjustment = style.LetterSpacing;
                break;

            case TextAlignment.Center:
                glyphLetterSpacingAdjustment = style.LetterSpacing / 2;
                break;
            }


            using (var buffer = new HarfBuzzSharp.Buffer())
            {
                // Setup buffer
                buffer.AddUtf32(new ReadOnlySpan <int>(codePoints.Underlying, codePoints.Start, codePoints.Length), 0, -1);

                // Setup directionality (if supplied)
                switch (direction)
                {
                case TextDirection.LTR:
                    buffer.Direction = Direction.LeftToRight;
                    break;

                case TextDirection.RTL:
                    buffer.Direction = Direction.RightToLeft;
                    break;

                default:
                    throw new ArgumentException(nameof(direction));
                }

                // Guess other attributes
                buffer.GuessSegmentProperties();

                // Shape it
                _font.Shape(buffer);

                // RTL?
                bool rtl = buffer.Direction == Direction.RightToLeft;

                // Work out glyph scaling and offsetting for super/subscript
                float glyphScale   = style.FontSize / overScale;
                float glyphVOffset = 0;
                if (style.FontVariant == FontVariant.SuperScript)
                {
                    glyphScale   *= 0.65f;
                    glyphVOffset -= style.FontSize * 0.35f;
                }
                if (style.FontVariant == FontVariant.SubScript)
                {
                    glyphScale   *= 0.65f;
                    glyphVOffset += style.FontSize * 0.1f;
                }

                // Create results and get buffes
                var r = new Result();
                r.GlyphIndicies    = bufferSet.GlyphIndicies.Add((int)buffer.Length, false);
                r.GlyphPositions   = bufferSet.GlyphPositions.Add((int)buffer.Length, false);
                r.Clusters         = bufferSet.Clusters.Add((int)buffer.Length, false);
                r.CodePointXCoords = bufferSet.CodePointXCoords.Add(codePoints.Length, false);
                r.CodePointXCoords.Fill(0);

                // Convert points
                var   gp             = buffer.GlyphPositions;
                var   gi             = buffer.GlyphInfos;
                float cursorX        = 0;
                float cursorY        = 0;
                float cursorXCluster = 0;
                for (int i = 0; i < buffer.Length; i++)
                {
                    r.GlyphIndicies[i] = (ushort)gi[i].Codepoint;
                    r.Clusters[i]      = (int)gi[i].Cluster + clusterAdjustment;


                    // Update code point positions
                    if (!rtl)
                    {
                        // First cluster, different cluster, or same cluster with lower x-coord
                        if (i == 0 ||
                            (r.Clusters[i] != r.Clusters[i - 1]) ||
                            (cursorX < r.CodePointXCoords[r.Clusters[i] - clusterAdjustment]))
                        {
                            r.CodePointXCoords[r.Clusters[i] - clusterAdjustment] = cursorX;
                        }
                    }

                    // Get the position
                    var pos = gp[i];

                    // Update glyph position
                    r.GlyphPositions[i] = new SKPoint(
                        cursorX + pos.XOffset * glyphScale + glyphLetterSpacingAdjustment,
                        cursorY - pos.YOffset * glyphScale + glyphVOffset
                        );

                    // Update cursor position
                    cursorX += pos.XAdvance * glyphScale;
                    cursorY += pos.YAdvance * glyphScale;

                    if (i + 1 == gi.Length || gi[i].Cluster != gi[i + 1].Cluster)
                    {
                        cursorX += style.LetterSpacing;
                    }

                    // Are we falling back for a fixed pitch font and is the next character a
                    // new cluster?  If so advance by the width of the original font, not this
                    // fallback font
                    if (forceFixedPitchWidth != 0)
                    {
                        // New cluster?
                        if (i + 1 >= buffer.Length || gi[i].Cluster != gi[i + 1].Cluster)
                        {
                            // Work out fixed pitch position of next cluster
                            cursorXCluster += forceFixedPitchWidth * glyphScale;
                            if (cursorXCluster > cursorX)
                            {
                                // Nudge characters to center them in the fixed pitch width
                                if (i == 0 || gi[i - 1].Cluster != gi[i].Cluster)
                                {
                                    r.GlyphPositions[i].X += (cursorXCluster - cursorX) / 2;
                                }

                                // Use fixed width character position
                                cursorX = cursorXCluster;
                            }
                            else
                            {
                                // Character is wider (probably an emoji) so we
                                // allow it to exceed the fixed pitch character width
                                cursorXCluster = cursorX;
                            }
                        }
                    }

                    // Store RTL cursor position
                    if (rtl)
                    {
                        // First cluster, different cluster, or same cluster with lower x-coord
                        if (i == 0 ||
                            (r.Clusters[i] != r.Clusters[i - 1]) ||
                            (cursorX > r.CodePointXCoords[r.Clusters[i] - clusterAdjustment]))
                        {
                            r.CodePointXCoords[r.Clusters[i] - clusterAdjustment] = cursorX;
                        }
                    }
                }

                // Finalize cursor positions by filling in any that weren't
                // referenced by a cluster
                if (rtl)
                {
                    r.CodePointXCoords[0] = cursorX;
                    for (int i = codePoints.Length - 2; i >= 0; i--)
                    {
                        if (r.CodePointXCoords[i] == 0)
                        {
                            r.CodePointXCoords[i] = r.CodePointXCoords[i + 1];
                        }
                    }
                }
                else
                {
                    for (int i = 1; i < codePoints.Length; i++)
                    {
                        if (r.CodePointXCoords[i] == 0)
                        {
                            r.CodePointXCoords[i] = r.CodePointXCoords[i - 1];
                        }
                    }
                }

                // Also return the end cursor position
                r.EndXCoord = new SKPoint(cursorX, cursorY);

                // And some other useful metrics
                r.Ascent  = _fontMetrics.Ascent * style.FontSize / overScale;
                r.Descent = _fontMetrics.Descent * style.FontSize / overScale;
                r.XMin    = _fontMetrics.XMin * style.FontSize / overScale;

                // Done
                return(r);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Shape an array of utf-32 code points
        /// </summary>
        /// <param name="bufferSet">A re-usable text shaping buffer set that results will be allocated from</param>
        /// <param name="codePoints">The utf-32 code points to be shaped</param>
        /// <param name="style">The user style for the text</param>
        /// <param name="direction">LTR or RTL direction</param>
        /// <param name="clusterAdjustment">A value to add to all reported cluster numbers</param>
        /// <returns>A TextShaper.Result representing the shaped text</returns>
        public Result Shape(ResultBufferSet bufferSet, Slice <int> codePoints, IStyle style, TextDirection direction, int clusterAdjustment = 0)
        {
            using (var buffer = new HarfBuzzSharp.Buffer())
            {
                // Setup buffer
                unsafe
                {
                    fixed(int *pCodePoints = codePoints.Underlying)
                    {
                        hb_buffer_add_utf32(buffer.Handle, (IntPtr)(pCodePoints + codePoints.Start), codePoints.Length, 0, -1);
                    }
                }

                // Setup directionality (if supplied)
                switch (direction)
                {
                case TextDirection.LTR:
                    buffer.Direction = Direction.LeftToRight;
                    break;

                case TextDirection.RTL:
                    buffer.Direction = Direction.RightToLeft;
                    break;

                default:
                    throw new ArgumentException(nameof(direction));
                }

                // Guess other attributes
                buffer.GuessSegmentProperties();

                // Shape it
                _font.Shape(buffer);

                // RTL?
                bool rtl = buffer.Direction == Direction.RightToLeft;

                // Work out glyph scaling and offsetting for super/subscript
                float glyphScale   = style.FontSize / overScale;
                float glyphVOffset = 0;
                if (style.FontVariant == FontVariant.SuperScript)
                {
                    glyphScale   *= 0.65f;
                    glyphVOffset -= style.FontSize * 0.35f;
                }
                if (style.FontVariant == FontVariant.SubScript)
                {
                    glyphScale   *= 0.65f;
                    glyphVOffset += style.FontSize * 0.1f;
                }

                // Create results and get buffes
                var r = new Result();
                r.GlyphIndicies    = bufferSet.GlyphIndicies.Add((int)buffer.Length, false);
                r.GlyphPositions   = bufferSet.GlyphPositions.Add((int)buffer.Length, false);
                r.Clusters         = bufferSet.Clusters.Add((int)buffer.Length, false);
                r.CodePointXCoords = bufferSet.CodePointXCoords.Add(codePoints.Length, false);

                // Convert points
                var   gp      = buffer.GlyphPositions;
                var   gi      = buffer.GlyphInfos;
                float cursorX = 0;
                float cursorY = 0;
                for (int i = 0; i < buffer.Length; i++)
                {
                    r.GlyphIndicies[i] = (ushort)gi[i].Codepoint;
                    r.Clusters[i]      = (int)gi[i].Cluster + clusterAdjustment;

                    // Update code point positions
                    if (!rtl)
                    {
                        // First cluster, different cluster, or same cluster with lower x-coord
                        if (i == 0 ||
                            (r.Clusters[i] != r.Clusters[i - 1]) ||
                            (cursorX < r.CodePointXCoords[r.Clusters[i] - clusterAdjustment]))
                        {
                            r.CodePointXCoords[r.Clusters[i] - clusterAdjustment] = cursorX;
                        }
                    }

                    // Get the position
                    var pos = gp[i];

                    // Update glyph position
                    r.GlyphPositions[i] = new SKPoint(
                        cursorX + pos.XOffset * glyphScale,
                        cursorY - pos.YOffset * glyphScale + glyphVOffset
                        );

                    // Update cursor position
                    cursorX += pos.XAdvance * glyphScale;
                    cursorY += pos.YAdvance * glyphScale;

                    // Store RTL cursor position
                    if (rtl)
                    {
                        // First cluster, different cluster, or same cluster with lower x-coord
                        if (i == 0 ||
                            (r.Clusters[i] != r.Clusters[i - 1]) ||
                            (cursorX > r.CodePointXCoords[r.Clusters[i] - clusterAdjustment]))
                        {
                            r.CodePointXCoords[r.Clusters[i] - clusterAdjustment] = cursorX;
                        }
                    }
                }

                // Finalize cursor positions by filling in any that weren't
                // referenced by a cluster
                if (rtl)
                {
                    r.CodePointXCoords[0] = cursorX;
                    for (int i = codePoints.Length - 2; i >= 0; i--)
                    {
                        if (r.CodePointXCoords[i] == 0)
                        {
                            r.CodePointXCoords[i] = r.CodePointXCoords[i + 1];
                        }
                    }
                }
                else
                {
                    for (int i = 1; i < codePoints.Length; i++)
                    {
                        if (r.CodePointXCoords[i] == 0)
                        {
                            r.CodePointXCoords[i] = r.CodePointXCoords[i - 1];
                        }
                    }
                }

                // Also return the end cursor position
                r.EndXCoord = new SKPoint(cursorX, cursorY);

                // And some other useful metrics
                r.Ascent  = _fontMetrics.Ascent * style.FontSize / overScale;
                r.Descent = _fontMetrics.Descent * style.FontSize / overScale;
                r.XMin    = _fontMetrics.XMin * style.FontSize / overScale;

                // Done
                return(r);
            }
        }