KiCad PCB EDA Suite
Loading...
Searching...
No Matches
outline_font.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KICAD, a free EDA CAD application.
3 *
4 * Copyright (C) 2021 Ola Rinta-Koski <[email protected]>
5 * Copyright (C) 2021-2023 Kicad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25#include <limits>
26#include <harfbuzz/hb.h>
27#include <harfbuzz/hb-ft.h>
28#include <bezier_curves.h>
30#include <font/fontconfig.h>
31#include <font/outline_font.h>
32#include FT_GLYPH_H
33#include FT_BBOX_H
34#include <trigo.h>
35#include <font/fontconfig.h>
37#include <core/utf8.h>
38
39using namespace KIFONT;
40
41
42FT_Library OUTLINE_FONT::m_freeType = nullptr;
44
46 m_face(NULL),
47 m_faceSize( 16 ),
48 m_fakeBold( false ),
49 m_fakeItal( false )
50{
51 std::lock_guard<std::mutex> guard( m_freeTypeMutex );
52
53 if( !m_freeType )
54 FT_Init_FreeType( &m_freeType );
55}
56
57
58OUTLINE_FONT* OUTLINE_FONT::LoadFont( const wxString& aFontName, bool aBold, bool aItalic )
59{
60 std::unique_ptr<OUTLINE_FONT> font = std::make_unique<OUTLINE_FONT>();
61
62 wxString fontFile;
63 int faceIndex;
64 using fc = fontconfig::FONTCONFIG;
65
66 fc::FF_RESULT retval = Fontconfig()->FindFont( aFontName, fontFile, faceIndex, aBold, aItalic );
67
68 if( retval == fc::FF_RESULT::FF_ERROR )
69 return nullptr;
70
71 if( retval == fc::FF_RESULT::FF_MISSING_BOLD || retval == fc::FF_RESULT::FF_MISSING_BOLD_ITAL )
72 font->SetFakeBold();
73
74 if( retval == fc::FF_RESULT::FF_MISSING_ITAL || retval == fc::FF_RESULT::FF_MISSING_BOLD_ITAL )
75 font->SetFakeItal();
76
77 if( font->loadFace( fontFile, faceIndex ) != 0 )
78 return nullptr;
79
80 font->m_fontName = aFontName; // Keep asked-for name, even if we substituted.
81 font->m_fontFileName = fontFile;
82
83 return font.release();
84}
85
86
87FT_Error OUTLINE_FONT::loadFace( const wxString& aFontFileName, int aFaceIndex )
88{
89 std::lock_guard<std::mutex> guard( m_freeTypeMutex );
90
91 // TODO: check that going from wxString to char* with UTF-8
92 // conversion for filename makes sense on any/all platforms
93 FT_Error e = FT_New_Face( m_freeType, aFontFileName.mb_str( wxConvUTF8 ), aFaceIndex, &m_face );
94
95 if( !e )
96 {
97 FT_Select_Charmap( m_face, FT_Encoding::FT_ENCODING_UNICODE );
98 // params:
99 // m_face = handle to face object
100 // 0 = char width in 1/64th of points ( 0 = same as char height )
101 // faceSize() = char height in 1/64th of points
102 // GLYPH_RESOLUTION = horizontal device resolution (288dpi, 4x default)
103 // 0 = vertical device resolution ( 0 = same as horizontal )
104 FT_Set_Char_Size( m_face, 0, faceSize(), GLYPH_RESOLUTION, 0 );
105 }
106
107 return e;
108}
109
110
115double OUTLINE_FONT::GetInterline( double aGlyphHeight, const METRICS& aFontMetrics ) const
116{
117 double glyphToFontHeight = 1.0;
118
119 if( GetFace()->units_per_EM )
120 glyphToFontHeight = GetFace()->height / GetFace()->units_per_EM;
121
122 return aFontMetrics.GetInterline( aGlyphHeight * glyphToFontHeight );
123}
124
125
126static bool contourIsFilled( const CONTOUR& c )
127{
128 switch( c.m_Orientation )
129 {
130 case FT_ORIENTATION_TRUETYPE: return c.m_Winding == 1;
131 case FT_ORIENTATION_POSTSCRIPT: return c.m_Winding == -1;
132 default: return false;
133 }
134}
135
136
137static bool contourIsHole( const CONTOUR& c )
138{
139 return !contourIsFilled( c );
140}
141
142
143BOX2I OUTLINE_FONT::getBoundingBox( const std::vector<std::unique_ptr<GLYPH>>& aGlyphs ) const
144{
145 int minX = INT_MAX;
146 int minY = INT_MAX;
147 int maxX = INT_MIN;
148 int maxY = INT_MIN;
149
150 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
151 {
152 BOX2D bbox = glyph->BoundingBox();
153 bbox.Normalize();
154
155 if( minX > bbox.GetX() )
156 minX = bbox.GetX();
157
158 if( minY > bbox.GetY() )
159 minY = bbox.GetY();
160
161 if( maxX < bbox.GetRight() )
162 maxX = bbox.GetRight();
163
164 if( maxY < bbox.GetBottom() )
165 maxY = bbox.GetBottom();
166 }
167
168 BOX2I ret;
169 ret.SetOrigin( minX, minY );
170 ret.SetEnd( maxX, maxY );
171 return ret;
172}
173
174
175void OUTLINE_FONT::GetLinesAsGlyphs( std::vector<std::unique_ptr<GLYPH>>* aGlyphs,
176 const wxString& aText, const VECTOR2I& aPosition,
177 const TEXT_ATTRIBUTES& aAttrs,
178 const METRICS& aFontMetrics ) const
179{
180 wxArrayString strings;
181 std::vector<VECTOR2I> positions;
182 std::vector<VECTOR2I> extents;
183 TEXT_STYLE_FLAGS textStyle = 0;
184
185 if( aAttrs.m_Italic )
186 textStyle |= TEXT_STYLE::ITALIC;
187
188 getLinePositions( aText, aPosition, strings, positions, extents, aAttrs, aFontMetrics );
189
190 for( size_t i = 0; i < strings.GetCount(); i++ )
191 {
192 (void) drawMarkup( nullptr, aGlyphs, strings.Item( i ), positions[i], aAttrs.m_Size,
193 aAttrs.m_Angle, aAttrs.m_Mirrored, aPosition, textStyle, aFontMetrics );
194 }
195}
196
197
198VECTOR2I OUTLINE_FONT::GetTextAsGlyphs( BOX2I* aBBox, std::vector<std::unique_ptr<GLYPH>>* aGlyphs,
199 const wxString& aText, const VECTOR2I& aSize,
200 const VECTOR2I& aPosition, const EDA_ANGLE& aAngle,
201 bool aMirror, const VECTOR2I& aOrigin,
202 TEXT_STYLE_FLAGS aTextStyle ) const
203{
204 // HarfBuzz needs further processing to split tab-delimited text into text runs.
205
206 constexpr double TAB_WIDTH = 4 * 0.6;
207
208 VECTOR2I position = aPosition;
209 wxString textRun;
210
211 if( aBBox )
212 {
213 aBBox->SetOrigin( aPosition );
214 aBBox->SetEnd( aPosition );
215 }
216
217 for( wxUniChar c : aText )
218 {
219 // Handle tabs as locked to the nearest 4th column (in space-widths).
220 if( c == '\t' )
221 {
222 if( !textRun.IsEmpty() )
223 {
224 position = getTextAsGlyphs( aBBox, aGlyphs, textRun, aSize, position, aAngle,
225 aMirror, aOrigin, aTextStyle );
226 textRun.clear();
227 }
228
229 int tabWidth = KiROUND( aSize.x * TAB_WIDTH );
230 int currentIntrusion = ( position.x - aOrigin.x ) % tabWidth;
231
232 position.x += tabWidth - currentIntrusion;
233 }
234 else
235 {
236 textRun += c;
237 }
238 }
239
240 if( !textRun.IsEmpty() )
241 {
242 position = getTextAsGlyphs( aBBox, aGlyphs, textRun, aSize, position, aAngle, aMirror,
243 aOrigin, aTextStyle );
244 }
245
246 return position;
247}
248
249
250VECTOR2I OUTLINE_FONT::getTextAsGlyphs( BOX2I* aBBox, std::vector<std::unique_ptr<GLYPH>>* aGlyphs,
251 const wxString& aText, const VECTOR2I& aSize,
252 const VECTOR2I& aPosition, const EDA_ANGLE& aAngle,
253 bool aMirror, const VECTOR2I& aOrigin,
254 TEXT_STYLE_FLAGS aTextStyle ) const
255{
256 std::lock_guard<std::mutex> guard( m_freeTypeMutex );
257
258 return getTextAsGlyphsUnlocked( aBBox, aGlyphs, aText, aSize, aPosition, aAngle, aMirror,
259 aOrigin, aTextStyle );
260}
261
263 std::vector<std::unique_ptr<GLYPH>>* aGlyphs,
264 const wxString& aText, const VECTOR2I& aSize,
265 const VECTOR2I& aPosition, const EDA_ANGLE& aAngle,
266 bool aMirror, const VECTOR2I& aOrigin,
267 TEXT_STYLE_FLAGS aTextStyle ) const
268{
269 VECTOR2D glyphSize = aSize;
270 FT_Face face = m_face;
271 double scaler = faceSize();
272
273 if( IsSubscript( aTextStyle ) || IsSuperscript( aTextStyle ) )
274 {
275 scaler = subscriptSize();
276 }
277
278 // set glyph resolution so that FT_Load_Glyph() results are good enough for decomposing
279 FT_Set_Char_Size( face, 0, scaler, GLYPH_RESOLUTION, 0 );
280
281 hb_buffer_t* buf = hb_buffer_create();
282 hb_buffer_add_utf8( buf, UTF8( aText ).c_str(), -1, 0, -1 );
283 hb_buffer_guess_segment_properties( buf ); // guess direction, script, and language based on
284 // contents
285
286 hb_font_t* referencedFont = hb_ft_font_create_referenced( face );
287 hb_ft_font_set_funcs( referencedFont );
288 hb_shape( referencedFont, buf, nullptr, 0 );
289
290 unsigned int glyphCount;
291 hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos( buf, &glyphCount );
292 hb_glyph_position_t* glyphPos = hb_buffer_get_glyph_positions( buf, &glyphCount );
293
294 VECTOR2D scaleFactor( glyphSize.x / faceSize(), -glyphSize.y / faceSize() );
295 scaleFactor = scaleFactor * m_outlineFontSizeCompensation;
296
297 VECTOR2I cursor( 0, 0 );
298
299 if( aGlyphs )
300 aGlyphs->reserve( glyphCount );
301
302 for( unsigned int i = 0; i < glyphCount; i++ )
303 {
304 // Don't process glyphs that were already included in a previous cluster
305 if( i > 0 && glyphInfo[i].cluster == glyphInfo[i-1].cluster )
306 continue;
307
308 if( aGlyphs )
309 {
310 if( m_fakeItal )
311 {
312 FT_Matrix matrix;
313 // Create a 12 degree slant
314 const float angle = (float)( -M_PI * 12.0f ) / 180.0f;
315 matrix.xx = (FT_Fixed) ( cos( angle ) * 0x10000L );
316 matrix.xy = (FT_Fixed) ( -sin( angle ) * 0x10000L );
317 matrix.yx = (FT_Fixed) ( 0 * 0x10000L ); // Don't rotate in the y direction
318 matrix.yy = (FT_Fixed) ( 1 * 0x10000L );
319
320 FT_Set_Transform( face, &matrix, 0 );
321 }
322
323 FT_Load_Glyph( face, glyphInfo[i].codepoint, FT_LOAD_NO_BITMAP );
324
325 if( m_fakeBold )
326 FT_Outline_Embolden( &face->glyph->outline, 1 << 6 );
327
328 // contours is a collection of all outlines in the glyph; for example the 'o' glyph
329 // generally contains 2 contours, one for the glyph outline and one for the hole
330 CONTOURS contours;
331
332 OUTLINE_DECOMPOSER decomposer( face->glyph->outline );
333 decomposer.OutlineToSegments( &contours );
334
335 std::unique_ptr<OUTLINE_GLYPH> glyph = std::make_unique<OUTLINE_GLYPH>();
336 std::vector<SHAPE_LINE_CHAIN> holes;
337
338 for( CONTOUR& c : contours )
339 {
340 GLYPH_POINTS points = c.m_Points;
341 SHAPE_LINE_CHAIN shape;
342
343 shape.ReservePoints( points.size() );
344
345 for( const VECTOR2D& v : points )
346 {
347 VECTOR2D pt( v + cursor );
348
349 if( IsSubscript( aTextStyle ) )
350 pt.y += m_subscriptVerticalOffset * scaler;
351 else if( IsSuperscript( aTextStyle ) )
352 pt.y += m_superscriptVerticalOffset * scaler;
353
354 pt *= scaleFactor;
355 pt += aPosition;
356
357 if( aMirror )
358 pt.x = aOrigin.x - ( pt.x - aOrigin.x );
359
360 if( !aAngle.IsZero() )
361 RotatePoint( pt, aOrigin, aAngle );
362
363 shape.Append( pt.x, pt.y );
364 }
365
366 shape.SetClosed( true );
367
368 if( contourIsHole( c ) )
369 holes.push_back( std::move( shape ) );
370 else
371 glyph->AddOutline( std::move( shape ) );
372 }
373
374 for( SHAPE_LINE_CHAIN& hole : holes )
375 {
376 if( hole.PointCount() )
377 {
378 for( int ii = 0; ii < glyph->OutlineCount(); ++ii )
379 {
380 if( glyph->Outline( ii ).PointInside( hole.GetPoint( 0 ) ) )
381 {
382 glyph->AddHole( std::move( hole ), ii );
383 break;
384 }
385 }
386 }
387 }
388
389 aGlyphs->push_back( std::move( glyph ) );
390 }
391
392 hb_glyph_position_t& pos = glyphPos[i];
393 cursor.x += ( pos.x_advance * GLYPH_SIZE_SCALER );
394 cursor.y += ( pos.y_advance * GLYPH_SIZE_SCALER );
395 }
396
397 int ascender = abs( face->size->metrics.ascender * GLYPH_SIZE_SCALER );
398 int descender = abs( face->size->metrics.descender * GLYPH_SIZE_SCALER );
399 VECTOR2I extents( cursor.x * scaleFactor.x, ( ascender + descender ) * abs( scaleFactor.y ) );
400
401 hb_buffer_destroy( buf );
402 hb_font_destroy( referencedFont );
403
404 VECTOR2I cursorDisplacement( cursor.x * scaleFactor.x, -cursor.y * scaleFactor.y );
405
406 if( aBBox )
407 aBBox->Merge( aPosition + extents );
408
409 return VECTOR2I( aPosition.x + cursorDisplacement.x, aPosition.y + cursorDisplacement.y );
410}
411
412
413#undef OUTLINEFONT_RENDER_AS_PIXELS
414#ifdef OUTLINEFONT_RENDER_AS_PIXELS
415/*
416 * WIP: eeschema (and PDF output?) should use pixel rendering instead of linear segmentation
417 */
418void OUTLINE_FONT::RenderToOpenGLCanvas( KIGFX::OPENGL_GAL& aGal, const wxString& aString,
419 const VECTOR2D& aGlyphSize, const VECTOR2I& aPosition,
420 const EDA_ANGLE& aOrientation, bool aIsMirrored ) const
421{
422 hb_buffer_t* buf = hb_buffer_create();
423 hb_buffer_add_utf8( buf, UTF8( aString ).c_str(), -1, 0, -1 );
424 hb_buffer_guess_segment_properties( buf ); // guess direction, script, and language based on contents
425
426 unsigned int glyphCount;
427 hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos( buf, &glyphCount );
428 hb_glyph_position_t* glyphPos = hb_buffer_get_glyph_positions( buf, &glyphCount );
429
430 std::lock_guard<std::mutex> guard( m_freeTypeMutex );
431
432 hb_font_t* referencedFont = hb_ft_font_create_referenced( m_face );
433
434 hb_ft_font_set_funcs( referencedFont );
435 hb_shape( referencedFont, buf, nullptr, 0 );
436
437 const double mirror_factor = ( aIsMirrored ? 1 : -1 );
438 const double x_scaleFactor = mirror_factor * aGlyphSize.x / mScaler;
439 const double y_scaleFactor = aGlyphSize.y / mScaler;
440
441 hb_position_t cursor_x = 0;
442 hb_position_t cursor_y = 0;
443
444 for( unsigned int i = 0; i < glyphCount; i++ )
445 {
446 hb_glyph_position_t& pos = glyphPos[i];
447 int codepoint = glyphInfo[i].codepoint;
448
449 FT_Error e = FT_Load_Glyph( m_face, codepoint, FT_LOAD_DEFAULT );
450 // TODO handle FT_Load_Glyph error
451
452 FT_Glyph glyph;
453 e = FT_Get_Glyph( m_face->glyph, &glyph );
454 // TODO handle FT_Get_Glyph error
455
456 wxPoint pt( aPosition );
457 pt.x += ( cursor_x >> 6 ) * x_scaleFactor;
458 pt.y += ( cursor_y >> 6 ) * y_scaleFactor;
459
460 cursor_x += pos.x_advance;
461 cursor_y += pos.y_advance;
462 }
463
464 hb_buffer_destroy( buf );
465}
466#endif //OUTLINEFONT_RENDER_AS_PIXELS
void SetOrigin(const Vec &pos)
Definition: box2.h:203
BOX2< Vec > & Normalize()
Ensure that the height and width are positive.
Definition: box2.h:120
coord_type GetY() const
Definition: box2.h:182
coord_type GetX() const
Definition: box2.h:181
coord_type GetRight() const
Definition: box2.h:190
coord_type GetBottom() const
Definition: box2.h:191
void SetEnd(coord_type x, coord_type y)
Definition: box2.h:256
BOX2< Vec > & Merge(const BOX2< Vec > &aRect)
Modify the position and size of the rectangle in order to contain aRect.
Definition: box2.h:589
bool IsZero() const
Definition: eda_angle.h:169
void getLinePositions(const wxString &aText, const VECTOR2I &aPosition, wxArrayString &aTextLines, std::vector< VECTOR2I > &aPositions, std::vector< VECTOR2I > &aExtents, const TEXT_ATTRIBUTES &aAttrs, const METRICS &aFontMetrics) const
Definition: font.cpp:178
VECTOR2I drawMarkup(BOX2I *aBoundingBox, std::vector< std::unique_ptr< GLYPH > > *aGlyphs, const wxString &aText, const VECTOR2I &aPosition, const VECTOR2I &aSize, const EDA_ANGLE &aAngle, bool aMirror, const VECTOR2I &aOrigin, TEXT_STYLE_FLAGS aTextStyle, const METRICS &aFontMetrics) const
Definition: font.cpp:377
double GetInterline(double aFontHeight) const
Definition: font.h:114
void OutlineToSegments(CONTOURS *aContours)
Class OUTLINE_FONT implements outline font drawing.
Definition: outline_font.h:52
VECTOR2I getTextAsGlyphsUnlocked(BOX2I *aBoundingBox, std::vector< std::unique_ptr< GLYPH > > *aGlyphs, const wxString &aText, const VECTOR2I &aSize, const VECTOR2I &aPosition, const EDA_ANGLE &aAngle, bool aMirror, const VECTOR2I &aOrigin, TEXT_STYLE_FLAGS aTextStyle) const
static std::mutex m_freeTypeMutex
Mutex for freetype access, FT_Library and FT_Face are not thread safe.
Definition: outline_font.h:131
double GetInterline(double aGlyphHeight, const METRICS &aFontMetrics) const override
Compute the distance (interline) between 2 lines of text (for multiline texts).
static FT_Library m_freeType
Definition: outline_font.h:132
BOX2I getBoundingBox(const std::vector< std::unique_ptr< GLYPH > > &aGlyphs) const
FT_Error loadFace(const wxString &aFontFileName, int aFaceIndex)
static constexpr double m_superscriptVerticalOffset
Definition: outline_font.h:176
VECTOR2I getTextAsGlyphs(BOX2I *aBoundingBox, std::vector< std::unique_ptr< GLYPH > > *aGlyphs, const wxString &aText, const VECTOR2I &aSize, const VECTOR2I &aPosition, const EDA_ANGLE &aAngle, bool aMirror, const VECTOR2I &aOrigin, TEXT_STYLE_FLAGS aTextStyle) const
VECTOR2I GetTextAsGlyphs(BOX2I *aBoundingBox, std::vector< std::unique_ptr< GLYPH > > *aGlyphs, const wxString &aText, const VECTOR2I &aSize, const VECTOR2I &aPosition, const EDA_ANGLE &aAngle, bool aMirror, const VECTOR2I &aOrigin, TEXT_STYLE_FLAGS aTextStyle) const override
Convert text string to an array of GLYPHs.
const FT_Face & GetFace() const
Definition: outline_font.h:99
void GetLinesAsGlyphs(std::vector< std::unique_ptr< GLYPH > > *aGlyphs, const wxString &aText, const VECTOR2I &aPosition, const TEXT_ATTRIBUTES &aAttrs, const METRICS &aFontMetrics) const
int faceSize() const
Definition: outline_font.h:166
static constexpr double m_outlineFontSizeCompensation
Definition: outline_font.h:148
int subscriptSize() const
Definition: outline_font.h:173
static OUTLINE_FONT * LoadFont(const wxString &aFontFileName, bool aBold, bool aItalic)
Load an outline font.
static constexpr double m_subscriptVerticalOffset
Definition: outline_font.h:175
OpenGL implementation of the Graphics Abstraction Layer.
Definition: opengl_gal.h:71
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
void ReservePoints(size_t aSize)
Allocate a number of points all at once (for performance).
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition: utf8.h:71
unsigned int TEXT_STYLE_FLAGS
Definition: font.h:64
bool IsSuperscript(TEXT_STYLE_FLAGS aFlags)
Definition: font.h:79
bool IsSubscript(TEXT_STYLE_FLAGS aFlags)
Definition: font.h:85
FONTCONFIG * Fontconfig()
Definition: fontconfig.cpp:54
constexpr int GLYPH_RESOLUTION
Definition: glyph.h:46
std::vector< CONTOUR > CONTOURS
constexpr double GLYPH_SIZE_SCALER
Definition: glyph.h:47
std::vector< VECTOR2D > GLYPH_POINTS
Definition: glyph.h:115
static bool contourIsHole(const CONTOUR &c)
static bool contourIsFilled(const CONTOUR &c)
FT_Orientation m_Orientation
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition: trigo.cpp:228
constexpr ret_type KiROUND(fp_type v)
Round a floating point number to an integer using "round halfway cases away from zero".
Definition: util.h:85
VECTOR2< int > VECTOR2I
Definition: vector2d.h:588