KiCad PCB EDA Suite
Loading...
Searching...
No Matches
test_pdf_unicode_plot.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 The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include <boost/test/unit_test.hpp>
21
22#include <wx/filename.h>
23#include <wx/filefn.h>
24#include <wx/ffile.h>
25#include <wx/utils.h>
26#include <wx/image.h>
27#include <zlib.h>
28
30#include <advanced_config.h>
31#include <render_settings.h>
32#include <trigo.h>
33#include <math/util.h>
34#include <font/font.h>
35#include <font/stroke_font.h>
38
39/* Test objective:
40 * Ensure PDF_PLOTTER can emit glyphs for ASCII plus some Cyrillic, Japanese and Chinese
41 * characters using stroke font fallback. We verify by checking resulting PDF file contains
42 * expected glyph names or UTF-16 hex sequences for those code points.
43 */
44
45BOOST_AUTO_TEST_SUITE( PDFUnicodePlot )
46
47static wxString getTempPdfPath( const wxString& name ) { return MakeTempPdfPath( name ); }
48
49// Comprehensive mapping test: emit all four style variants in a single PDF and verify that
50// every style's ToUnicode CMap contains expected codepoints (Cyrillic 041F, Japanese 65E5, Chinese 672C).
51BOOST_AUTO_TEST_CASE( PlotMultilingualAllStylesMappings )
52{
53 const std::string sampleUtf8 = "ABCDEF Привет 日本語 漢字";
54 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
55 wxString pdfPath = getTempPdfPath( "kicad_pdf_unicode_allstyles" );
56
57 PDF_PLOTTER plotter;
58 SIMPLE_RENDER_SETTINGS renderSettings;
59
60 plotter.SetRenderSettings( &renderSettings );
61 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
62 plotter.SetViewport( VECTOR2I(0,0), 1.0, 1.0, false );
63 BOOST_REQUIRE( plotter.StartPlot( wxT("1"), wxT("TestPage") ) );
64
65 auto emitStyle = [&]( bool bold, bool italic, int yoff )
66 {
67 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 3000, 300, bold, italic );
68 auto strokeFont = LoadStrokeFontUnique();
69 KIFONT::METRICS metrics;
70
71 plotter.PlotText( VECTOR2I( 50000, 60000 - yoff ), COLOR4D( 0, 0, 0, 1 ), sample, attrs,
72 strokeFont.get(), metrics );
73 };
74
75 emitStyle( false, false, 0 ); // normal
76 emitStyle( true, false, 8000 ); // bold
77 emitStyle( false, true, 16000 ); // italic
78 emitStyle( true, true, 24000 ); // bold-italic
79
80 plotter.EndPlot();
81
82 // Read entire PDF (may have compression). We'll search each Type3 font object's preceding
83 // name to separate CMaps logically.
84 std::string buffer; BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
85 BOOST_CHECK( buffer.rfind( "%PDF", 0 ) == 0 );
86
87 // Count how many distinct KiCadStrokeCMap names present; expect at least 4 (one per style).
88 int cmapCount = CountOccurrences( buffer, "/CMapName /KiCadStrokeCMap" );
89
90 BOOST_CHECK_MESSAGE( cmapCount >= 4, "Expected at least 4 CMaps (got " << cmapCount << ")" );
91
92 auto requireAll = [&]( const char* codeHex, const char* label ) {
93 int occurrences = CountOccurrences( buffer, codeHex );
94 BOOST_CHECK_MESSAGE( occurrences >= 4, "Codepoint " << label << " (" << codeHex
95 << ") expected in all 4 styles; found " << occurrences );
96 };
97
98 requireAll( "041F", "Cyrillic PE" );
99 requireAll( "65E5", "Kanji 日" );
100 requireAll( "672C", "Kanji 本" );
101
102 MaybeRemoveFile( pdfPath );
103}
104
105BOOST_AUTO_TEST_CASE( PlotMultilingualText )
106{
107 // UTF-8 sample with Latin, Cyrillic, Japanese, Chinese (shared Han) characters.
108 const std::string sampleUtf8 = "ABCDEF Привет 日本語 漢字";
109 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
110
111 wxString pdfPath = getTempPdfPath( "kicad_pdf_unicode" );
112
113 PDF_PLOTTER plotter;
114
115 // Force uncompressed PDF streams via environment so we can directly search for
116 // unicode hex strings in the output (otherwise they are Flate compressed).
117 // Do not force debug writer; allow normal compression so page content is valid.
118 // The plotter expects non-null render settings for default pen width and font queries.
119 // Provide a minimal concrete RENDER_SETTINGS implementation for the plotter.
120 SIMPLE_RENDER_SETTINGS renderSettings; plotter.SetRenderSettings( &renderSettings );
121
122 // Minimal viewport and plot setup. Use 1 IU per decimil so internal coordinates are small
123 // and resulting translation keeps text inside the page for rasterization.
124 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
125 plotter.SetViewport( VECTOR2I(0,0), 1.0, 1.0, false );
126 // StartPlot opens first page stream internally; use simple page number
127 BOOST_REQUIRE( plotter.StartPlot( wxT("1"), wxT("TestPage") ) );
128
129 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 3000, 300, false, false );
130 auto strokeFont = LoadStrokeFontUnique();
131 KIFONT::METRICS metrics; // not used for stroke fallback
132
133 // Plot near lower-left inside the page.
134 // Place text near the top of the page in internal units so after the 0.0072 scale it
135 // appears well within the MediaBox. Empirically m_paperSize.y ~ 116k internal units.
136 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0.0, 0.0, 0.0, 1.0 ), sample, attrs,
137 strokeFont.get(), metrics );
138
139 plotter.EndPlot();
140
141 // Read file back and check for expected UTF-16 hex encodings for some code points
142 // We expect CMap to contain mappings. E.g. '041F' (Cyrillic capital Pe), '65E5'(日), '672C'(本).
143 std::string buffer2; BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer2 ) );
144 auto contains = [&]( const char* needle ) { return PdfContains( buffer2, needle ); };
145
146 BOOST_CHECK_MESSAGE( contains( "041F" ), "Missing Cyrillic glyph mapping (041F)" );
147 BOOST_CHECK_MESSAGE( contains( "0420" ) || contains( "0440" ), "Missing Cyrillic glyph mapping (0420/0440)" );
148 BOOST_CHECK_MESSAGE( contains( "65E5" ), "Missing Japanese Kanji glyph mapping (65E5)" );
149 BOOST_CHECK_MESSAGE( contains( "672C" ), "Missing Japanese Kanji glyph mapping (672C)" );
150 BOOST_CHECK_MESSAGE( contains( "6F22" ) || contains( "6漢" ), "Expect Chinese Han character mapping (6F22 / 漢)" );
151
152 // Cleanup temp file (unless debugging requested)
153 // Optional: rasterize PDF to image (requires poppler 'pdftoppm').
154 // We treat absence of the tool as a skipped sub-check rather than a failure.
155 {
156 long darkPixels = 0;
157 if( RasterizePdfCountDark( pdfPath, 72, 240, darkPixels ) )
158 {
159 BOOST_CHECK_MESSAGE( darkPixels > 200,
160 "Rasterized PDF appears blank or too sparse (" << darkPixels
161 << " dark pixels)" );
162 }
163 else
164 {
165 BOOST_TEST_MESSAGE( "pdftoppm not available or failed; skipping raster validation" );
166 }
167 }
168
169 MaybeRemoveFile( pdfPath );
170}
171
172BOOST_AUTO_TEST_CASE( PlotMultilingualTextBold )
173{
174 const std::string sampleUtf8 = "ABCDEF Привет 日本語 漢字";
175 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
176
177 wxString pdfPath = getTempPdfPath( "kicad_pdf_unicode_bold" );
178
179 PDF_PLOTTER plotter;
180 SIMPLE_RENDER_SETTINGS renderSettings;
181 plotter.SetRenderSettings( &renderSettings );
182 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
183 plotter.SetViewport( VECTOR2I(0,0), 1.0, 1.0, false );
184 BOOST_REQUIRE( plotter.StartPlot( wxT("1"), wxT("TestPage") ) );
185
186 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 3000, 300, true, false );
187 auto strokeFont = LoadStrokeFontUnique();
188 KIFONT::METRICS metrics;
189 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0.0, 0.0, 0.0, 1.0 ), sample, attrs,
190 strokeFont.get(), metrics );
191 plotter.EndPlot();
192 std::string buffer3; BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer3 ) );
193 auto contains = [&]( const char* needle ) { return PdfContains( buffer3, needle ); };
194 BOOST_CHECK_MESSAGE( contains( "041F" ), "Missing Cyrillic glyph mapping (bold 041F)" );
195 BOOST_CHECK_MESSAGE( contains( "65E5" ), "Missing Japanese glyph mapping (bold 65E5)" );
196
197 MaybeRemoveFile( pdfPath );
198}
199
200BOOST_AUTO_TEST_CASE( PlotMultilingualTextItalic )
201{
202 const std::string sampleUtf8 = "ABCDEF Привет 日本語 漢字";
203 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
204 wxString pdfPath = getTempPdfPath( "kicad_pdf_unicode_italic" );
205 PDF_PLOTTER plotter;
206 SIMPLE_RENDER_SETTINGS renderSettings;
207
208 plotter.SetRenderSettings( &renderSettings );
209 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
210 plotter.SetViewport( VECTOR2I(0,0), 1.0, 1.0, false );
211 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "TestPage" ) ) );
212 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 3000, 300, false, true );
213 auto strokeFont = LoadStrokeFontUnique();
214 KIFONT::METRICS metrics;
215 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0, 0, 0, 1 ), sample, attrs, strokeFont.get(), metrics );
216 plotter.EndPlot();
217
218 std::string buffer4; BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer4 ) );
219 auto contains = [&]( const char* n ) { return PdfContains( buffer4, n ); };
220 BOOST_CHECK_MESSAGE( contains( "041F" ), "Missing Cyrillic glyph mapping (italic 041F)" );
221 BOOST_CHECK_MESSAGE( contains( "65E5" ), "Missing Japanese glyph mapping (italic 65E5)" );
222 MaybeRemoveFile( pdfPath );
223}
224
225BOOST_AUTO_TEST_CASE( PlotMultilingualTextBoldItalic )
226{
227 const std::string sampleUtf8 = "ABCDEF Привет 日本語 漢字";
228 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
229 wxString pdfPath = getTempPdfPath( "kicad_pdf_unicode_bolditalic" );
230 PDF_PLOTTER plotter;
231 SIMPLE_RENDER_SETTINGS renderSettings;
232
233 plotter.SetRenderSettings( &renderSettings );
234 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
235
236 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
237 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "TestPage" ) ) );
238
239 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 3000, 300, true, true );
240 auto strokeFont = LoadStrokeFontUnique();
241 KIFONT::METRICS metrics;
242
243 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0, 0, 0, 1 ), sample, attrs, strokeFont.get(), metrics );
244 plotter.EndPlot();
245
246 std::string buffer5; BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer5 ) );
247 auto contains = [&]( const char* n ) { return PdfContains( buffer5, n ); };
248 BOOST_CHECK_MESSAGE( contains( "041F" ), "Missing Cyrillic glyph mapping (bold-italic 041F)" );
249 BOOST_CHECK_MESSAGE( contains( "65E5" ), "Missing Japanese glyph mapping (bold-italic 65E5)" );
250 MaybeRemoveFile( pdfPath );
251}
252
253// Verify that d1 bounding boxes account for X offset and stroke width so PDF viewers don't
254// clip the rendered glyphs. Regression test for gitlab.com/kicad/code/kicad/-/issues/23621.
255BOOST_AUTO_TEST_CASE( GlyphBBoxIncludesOffsetAndStrokeWidth )
256{
257 const std::string sampleUtf8 = "MW";
258 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
259 wxString pdfPath = getTempPdfPath( "kicad_pdf_bbox_check" );
260
261 PDF_PLOTTER plotter;
262 SIMPLE_RENDER_SETTINGS renderSettings;
263
264 plotter.SetRenderSettings( &renderSettings );
265 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
266 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
267 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "BBoxTest" ) ) );
268
269 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 3000, 300, false, false );
270 auto strokeFont = LoadStrokeFontUnique();
271 KIFONT::METRICS metrics;
272
273 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0, 0, 0, 1 ), sample, attrs,
274 strokeFont.get(), metrics );
275 plotter.EndPlot();
276
277 std::string buffer;
278 BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
279
280 // Parse d1 operators: format is "width 0 minX minY maxX maxY d1"
281 // Verify that no glyph has a minX of exactly 0 (would mean X offset was not applied) and
282 // that the bbox extends beyond the stroke center coordinates by at least half the stroke
283 // width.
284 const ADVANCED_CFG& cfg = ADVANCED_CFG::GetCfg();
285 double unitsPerEm = 1000.0;
286 double expectedXOffset = cfg.m_PDFStrokeFontXOffset * unitsPerEm;
287 double widthFactor = 300.0 / 3000.0;
288 double expectedHalfStroke = unitsPerEm * widthFactor / 2.0;
289
290 // Find all d1 operators (skip .notdef which has all-zero bbox)
291 std::string::size_type pos = 0;
292 int checkedGlyphs = 0;
293
294 while( ( pos = buffer.find( " d1 ", pos ) ) != std::string::npos )
295 {
296 // Walk backwards to find the start of the d1 line
297 std::string::size_type lineStart = buffer.rfind( '\n', pos );
298
299 if( lineStart == std::string::npos )
300 lineStart = 0;
301 else
302 lineStart++;
303
304 std::string d1Line = buffer.substr( lineStart, pos + 3 - lineStart );
305
306 double width, wy, minX, minY, maxX, maxY;
307
308 if( sscanf( d1Line.c_str(), "%lf %lf %lf %lf %lf %lf", &width, &wy, &minX, &minY,
309 &maxX, &maxY ) == 6 )
310 {
311 // Skip .notdef (all zeros)
312 if( width == 0.0 && maxX == 0.0 )
313 {
314 pos += 4;
315 continue;
316 }
317
318 // The bbox minX should be shifted by the X offset minus half stroke width.
319 // With default offset 0.1 and stroke width 300 at size 3000, minX should be around
320 // 0.1*1000 - 0.1*1000/2 = 100 - 50 = 50, not 0.
321 BOOST_CHECK_MESSAGE( minX < -expectedHalfStroke + 1.0 || minX > 0.1,
322 "Glyph bbox minX (" << minX
323 << ") suggests X offset or stroke padding is missing" );
324
325 // maxX must exceed the advance width to account for offset + stroke padding
326 BOOST_CHECK_MESSAGE( maxX > width,
327 "Glyph bbox maxX (" << maxX << ") must exceed advance width ("
328 << width << ") to prevent clipping" );
329
330 checkedGlyphs++;
331 }
332
333 pos += 4;
334 }
335
336 BOOST_CHECK_MESSAGE( checkedGlyphs >= 2,
337 "Expected at least 2 non-notdef glyphs, found " << checkedGlyphs );
338
339 MaybeRemoveFile( pdfPath );
340}
341
342// Test Y offset bounding box fix: ensure characters are not clipped when Y offset is applied
343BOOST_AUTO_TEST_CASE( PlotMultilingualTextWithYOffset )
344{
345 // Temporarily modify the Y offset configuration
346 ADVANCED_CFG& cfg = const_cast<ADVANCED_CFG&>( ADVANCED_CFG::GetCfg() );
347 double originalOffset = cfg.m_PDFStrokeFontYOffset;
348 cfg.m_PDFStrokeFontYOffset = 0.2; // 20% of EM unit offset upward
349
350 const std::string sampleUtf8 = "Yg Test ñ"; // characters with ascenders and descenders
351 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
352 wxString pdfPath = getTempPdfPath( "kicad_pdf_unicode_yoffset" );
353
354 PDF_PLOTTER plotter;
355 SIMPLE_RENDER_SETTINGS renderSettings;
356
357 plotter.SetRenderSettings( &renderSettings );
358 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
359 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
360 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "TestPage" ) ) );
361
362 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 4000, 400, false, false );
363 auto strokeFont = LoadStrokeFontUnique();
364 KIFONT::METRICS metrics;
365 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0, 0, 0, 1 ), sample, attrs, strokeFont.get(), metrics );
366 plotter.EndPlot();
367
368
369 // Restore original Y offset
370 cfg.m_PDFStrokeFontYOffset = originalOffset;
371
372 // Basic PDF validation and decompression
373 std::string buffer6; BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer6 ) );
374 BOOST_CHECK( buffer6.rfind( "%PDF", 0 ) == 0 );
375
376 // Check that bounding boxes exist and are reasonable (not clipped)
377 // Look for d1 operators which specify character bounding boxes
378 BOOST_CHECK_MESSAGE( buffer6.find( "d1" ) != std::string::npos,
379 "PDF should contain d1 operators for glyph bounding boxes" );
380
381 MaybeRemoveFile( pdfPath );
382}
383
384BOOST_AUTO_TEST_CASE( PlotOutlineFontEmbedding )
385{
386 wxString pdfPath = getTempPdfPath( "kicad_pdf_outline_font" );
387
388 // Locate test font file (Noto Sans) in test resources
389 wxFileName fontFile( KI_TEST::GetTestDataRootDir() );
390 fontFile.RemoveLastDir();
391 fontFile.AppendDir( wxT( "resources" ) );
392 fontFile.AppendDir( wxT( "fonts" ) );
393 fontFile.SetFullName( wxT( "NotoSans-Regular.ttf" ) );
394 wxString fontPath = fontFile.GetFullPath();
395
396 BOOST_REQUIRE( wxFileExists( fontPath ) );
397
398 PDF_PLOTTER plotter;
399 SIMPLE_RENDER_SETTINGS renderSettings;
400
401 plotter.SetRenderSettings( &renderSettings );
402 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
403 plotter.SetViewport( VECTOR2I(0,0), 1.0, 1.0, false );
404 BOOST_REQUIRE( plotter.StartPlot( wxT("1"), wxT("OutlineFont") ) );
405
406 TEXT_ATTRIBUTES attrs = BuildTextAttributes( 4000, 0, false, false );
407
408 std::vector<wxString> embeddedFonts;
409 embeddedFonts.push_back( fontPath );
410
411 KIFONT::FONT* outlineFont = KIFONT::FONT::GetFont( wxT( "Noto Sans" ), false, false, &embeddedFonts );
412 KIFONT::METRICS metrics;
413
414 wxString sample = wxString::FromUTF8( "Outline café" );
415
416 plotter.PlotText( VECTOR2I( 42000, 52000 ), COLOR4D( 0, 0, 0, 1 ), sample, attrs,
417 outlineFont, metrics );
418
419 plotter.EndPlot();
420
421 wxFFile file( pdfPath, "rb" );
422 BOOST_REQUIRE( file.IsOpened() );
423 wxFileOffset len = file.Length();
424 std::string buffer; buffer.resize( (size_t) len ); file.Read( buffer.data(), len );
425 BOOST_CHECK( buffer.rfind( "%PDF", 0 ) == 0 );
426
427 auto appendDecompressed = [&]() { std::string tmp; ReadPdfWithDecompressedStreams( pdfPath, tmp ); buffer.swap( tmp ); };
428 appendDecompressed();
429
430 BOOST_CHECK_MESSAGE( buffer.find( "/CIDFontType2" ) != std::string::npos,
431 "Expected CIDFontType2 descendant font" );
432 BOOST_CHECK_MESSAGE( buffer.find( "/FontFile2" ) != std::string::npos,
433 "Embedded outline font should include FontFile2 stream" );
434 BOOST_CHECK_MESSAGE( buffer.find( "AAAAAA+Noto-Sans" ) != std::string::npos,
435 "BaseFont should reference Noto Sans subset" );
436 BOOST_CHECK_MESSAGE( buffer.find( "00E9" ) != std::string::npos,
437 "ToUnicode map should include Latin character with accent" );
438 BOOST_CHECK_MESSAGE( buffer.find( "/KiCadOutline" ) != std::string::npos,
439 "Outline font resource entry missing" );
440
441 // Optional: rasterize PDF to image (requires poppler 'pdftoppm').
442 // We treat absence of the tool as a skipped sub-check rather than a failure.
443 {
444 wxString rasterBase = wxFileName::CreateTempFileName( wxT("kicad_pdf_raster") );
445 wxString cmd = wxString::Format( wxT("pdftoppm -r 72 -singlefile -png \"%s\" \"%s\""),
446 pdfPath, rasterBase );
447
448 int ret = wxExecute( cmd, wxEXEC_SYNC );
449
450 if( ret == 0 )
451 {
452 wxString pngPath = rasterBase + wxT(".png");
453
454 if( wxFileExists( pngPath ) )
455 {
456 // Ensure PNG handler is available
457 if( !wxImage::FindHandler( wxBITMAP_TYPE_PNG ) )
458 wxImage::AddHandler( new wxPNGHandler );
459
460 wxImage img( pngPath );
461 BOOST_REQUIRE_MESSAGE( img.IsOk(), "Failed to load rasterized PDF image" );
462
463 long darkPixels = 0;
464 int w = img.GetWidth();
465 int h = img.GetHeight();
466
467 for( int y = 0; y < h; ++y )
468 {
469 for( int x = 0; x < w; ++x )
470 {
471 unsigned char r = img.GetRed( x, y );
472 unsigned char g = img.GetGreen( x, y );
473 unsigned char b = img.GetBlue( x, y );
474
475 // Count any non-near-white pixel as drawn content
476 if( r < 240 || g < 240 || b < 240 )
477 ++darkPixels;
478 }
479 }
480
481 // Demand at least 100 non-white pixels to consider outline font rendered correctly.
482 // This threshold is lower than stroke font since outline fonts may render differently.
483 BOOST_CHECK_MESSAGE( darkPixels > 100,
484 "Rasterized PDF appears blank or too sparse (" << darkPixels
485 << " dark pixels). Outline font may not be rendering correctly." );
486
487 // Housekeeping
488 wxRemoveFile( pngPath );
489 }
490 else
491 {
492 BOOST_TEST_MESSAGE( "pdftoppm succeeded but PNG output missing; skipping raster validation" );
493 }
494 }
495 else
496 {
497 BOOST_TEST_MESSAGE( "pdftoppm not available or failed; skipping raster validation" );
498 }
499 }
500
501 MaybeRemoveFile( pdfPath );
502}
503
504// Extract the device-space X translation of every stroke-font text block ("... cm BT") in a
505// decompressed PDF content stream, in stream order. The stroke plotter emits each rendered word
506// as "q a b c d e f cm BT ...", where the 5th number (e) is the text-matrix X origin.
507static std::vector<double> ExtractStrokeTextOriginsX( const std::string& aBuffer )
508{
509 std::vector<double> origins;
510 size_t pos = 0;
511
512 while( ( pos = aBuffer.find( "cm BT", pos ) ) != std::string::npos )
513 {
514 std::string head = aBuffer.substr( 0, pos );
515 std::vector<double> nums;
516
517 for( size_t end = head.size(); end > 0 && nums.size() < 6; )
518 {
519 size_t start = head.find_last_not_of( " \n\r\t", end - 1 );
520
521 if( start == std::string::npos )
522 break;
523
524 size_t tokStart = head.find_last_of( " \n\r\t", start );
525 tokStart = ( tokStart == std::string::npos ) ? 0 : tokStart + 1;
526
527 try
528 {
529 nums.push_back( std::stod( head.substr( tokStart, start - tokStart + 1 ) ) );
530 }
531 catch( ... )
532 {
533 break;
534 }
535
536 end = tokStart;
537 }
538
539 if( nums.size() == 6 )
540 origins.push_back( nums[1] ); // reversed order: e is second-from-last collected
541
542 pos += 5;
543 }
544
545 return origins;
546}
547
548
549// Issue #22606: PDF plotting of stroke-font text containing tab characters placed the following
550// text at the wrong tab stop. The plotter hardcoded the outline font's tab rule (2.4 * size),
551// but the default schematic font is the stroke font, whose tab stops are column based and land
552// much further right. The result was tabs that came out too short in the PDF versus on screen.
553//
554// This drives the plotter with the reporter's own text ("v07:\terstversion") and checks that the
555// text after the tab is placed exactly where the stroke font's own glyph model puts it.
556BOOST_AUTO_TEST_CASE( PlotStrokeTextTabStopMatchesFont )
557{
558 wxString pdfPath = getTempPdfPath( "kicad_pdf_tabs" );
559
560 PDF_PLOTTER plotter;
561 SIMPLE_RENDER_SETTINGS renderSettings;
562
563 plotter.SetRenderSettings( &renderSettings );
564 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
565 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
566 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "TabTest" ) ) );
567
568 const int sizeIu = 1270000; // 1.27 mm, the reporter's text size
569 TEXT_ATTRIBUTES attrs = BuildTextAttributes( sizeIu, sizeIu / 10, false, false );
570 auto strokeFont = LoadStrokeFontUnique();
571 KIFONT::METRICS metrics;
572
573 // Two reference words establish the linear user->device X scale of the viewport.
574 plotter.PlotText( VECTOR2I( 40000000, 60000000 ), COLOR4D( 0, 0, 0, 1 ), wxT( "M" ), attrs,
575 strokeFont.get(), metrics );
576 plotter.PlotText( VECTOR2I( 80000000, 60000000 ), COLOR4D( 0, 0, 0, 1 ), wxT( "M" ), attrs,
577 strokeFont.get(), metrics );
578
579 // The reporter's tabbed line: "v07:" then a tab then the rest of the line.
580 plotter.PlotText( VECTOR2I( 40000000, 40000000 ), COLOR4D( 0, 0, 0, 1 ), wxT( "v07:\terstversion" ),
581 attrs, strokeFont.get(), metrics );
582
583 plotter.EndPlot();
584
585 std::string buffer;
586 BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
587 BOOST_CHECK( buffer.rfind( "%PDF", 0 ) == 0 );
588
589 std::vector<double> origins = ExtractStrokeTextOriginsX( buffer );
590
591 // Two reference "M" blocks plus the two segments ("v07:" and "erstversion") of the tabbed line.
592 BOOST_REQUIRE_EQUAL( origins.size(), 4u );
593
594 const double scale = ( origins[1] - origins[0] ) / ( 80000000.0 - 40000000.0 );
595 BOOST_REQUIRE( std::abs( scale ) > 0.0 );
596
597 // Distance in user units from the "v07:" origin to the post-tab "erstversion" origin.
598 const double measuredOffsetIu = ( origins[3] - origins[2] ) / scale;
599
600 const VECTOR2I size( sizeIu, sizeIu );
601
602 // The stroke font's own glyph placement is the ground truth for the on-screen position.
603 const double expectedOffsetIu =
604 strokeFont->GetTextAsGlyphs( nullptr, nullptr, wxT( "v07:\t" ), size, VECTOR2I(),
605 ANGLE_0, false, VECTOR2I(), 0 )
606 .x;
607
608 // The old (buggy) hardcoded rule would have placed it here; kept only to document the gap.
609 const double widthV07 =
610 strokeFont->GetTextAsGlyphs( nullptr, nullptr, wxT( "v07:" ), size, VECTOR2I(), ANGLE_0,
611 false, VECTOR2I(), 0 )
612 .x;
613 const int oldTabWidth = KiROUND( sizeIu * 4 * 0.6 );
614 const double oldOffsetIu = widthV07 + ( oldTabWidth - KiROUND( widthV07 ) % oldTabWidth );
615
616 const double tolerance = sizeIu * 0.02;
617
618 BOOST_CHECK_MESSAGE( std::abs( measuredOffsetIu - expectedOffsetIu ) < tolerance,
619 "Post-tab text at " << measuredOffsetIu << " IU, font model expects "
620 << expectedOffsetIu << " IU (old buggy rule: "
621 << oldOffsetIu << " IU)" );
622
623 MaybeRemoveFile( pdfPath );
624}
625
626// Regression test for GitLab issue 23740: stroke-font Type3 glyphs in the PDF output were
627// plotted above and to the left of where they should have been. The old code derived the
628// vertical anchor from StringBoundaryLimits (which inflates by 3*thickness) and used
629// thickness-dependent CTM hacks. Alignment now goes through FONT::GetAlignedDrawPosition
630// (GAL getLinePositions), with a constant cancel of the baked Type3 glyph Y offset.
631//
632// The test plots the same character with V_TOP, V_CENTER and V_BOTTOM alignments at the same
633// anchor, parses the text-matrix ctm_f value out of the content stream, then verifies that
634// ctm_f deltas match FONT::getLinePositions (the constant YOffset cancel drops out of deltas).
635BOOST_AUTO_TEST_CASE( StrokeFontVerticalAlignmentMatchesScreen )
636{
637 wxString pdfPath = getTempPdfPath( "kicad_pdf_valign" );
638
639 PDF_PLOTTER plotter;
640 SIMPLE_RENDER_SETTINGS renderSettings;
641 plotter.SetRenderSettings( &renderSettings );
642 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
643 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
644 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "VAlignTest" ) ) );
645
646 const int anchorY = 60000;
647 const int sizeIU = 3000;
648 const int strokeW = 300;
649
650 auto plotAt = [&]( GR_TEXT_V_ALIGN_T aVJustify, bool aItalic )
651 {
652 TEXT_ATTRIBUTES attrs = BuildTextAttributes( sizeIU, strokeW, false, aItalic );
653 attrs.m_Valign = aVJustify;
654 auto strokeFont = LoadStrokeFontUnique();
655 KIFONT::METRICS metrics;
656 plotter.PlotText( VECTOR2I( 50000, anchorY ), COLOR4D( 0, 0, 0, 1 ), wxT( "T" ), attrs,
657 strokeFont.get(), metrics );
658 };
659
660 plotAt( GR_TEXT_V_ALIGN_TOP, false );
661 plotAt( GR_TEXT_V_ALIGN_CENTER, false );
662 plotAt( GR_TEXT_V_ALIGN_BOTTOM, false );
663 plotAt( GR_TEXT_V_ALIGN_TOP, true );
664 plotAt( GR_TEXT_V_ALIGN_CENTER, true );
665 plotter.EndPlot();
666
667 std::string buffer;
668 BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
669
670 // Capture the full text matrix for every `q ... cm BT ... Tj ET Q` block.
671 struct MATRIX_SAMPLE { double a, b, c, d, e, f; };
672 std::vector<MATRIX_SAMPLE> matrices;
673 std::string::size_type pos = 0;
674
675 while( ( pos = buffer.find( "cm BT", pos ) ) != std::string::npos )
676 {
677 std::string::size_type lineStart = buffer.rfind( '\n', pos );
678 lineStart = ( lineStart == std::string::npos ) ? 0 : lineStart + 1;
679
680 std::string cmLine = buffer.substr( lineStart, pos - lineStart );
681 MATRIX_SAMPLE m{};
682
683 if( sscanf( cmLine.c_str(), "q %lf %lf %lf %lf %lf %lf", &m.a, &m.b, &m.c, &m.d, &m.e,
684 &m.f ) == 6 )
685 {
686 matrices.push_back( m );
687 }
688
689 pos += 5;
690 }
691
692 BOOST_REQUIRE_EQUAL( matrices.size(), 5u );
693
694 const double fontSize = (double) sizeIU;
695 const double thickness = (double) strokeW;
696
697 // GAL cursor Y offsets from FONT::getLinePositions (single line, height = 1.17 * size),
698 // ignoring the strokeWidth*0.052 fudge which is the same for every V-align and cancels
699 // in the deltas:
700 // V_TOP = 1.000 * size
701 // V_CENTER = 0.415 * size
702 // V_BOTTOM = -0.17 * size
703 // PDF device Y decreases as IU Y increases, so ctm_f_TOP < ctm_f_CENTER < ctm_f_BOTTOM.
704 const double expected_delta_top_center = ( 1.000 - 0.415 ) * fontSize;
705 const double expected_delta_center_bot = ( 0.415 - ( -0.17 ) ) * fontSize;
706
707 const double observed_delta_top_center = matrices[1].f - matrices[0].f;
708 const double observed_delta_center_bot = matrices[2].f - matrices[1].f;
709
710 BOOST_CHECK_CLOSE( observed_delta_top_center, expected_delta_top_center, 1.0 );
711 BOOST_CHECK_CLOSE( observed_delta_center_bot, expected_delta_center_bot, 1.0 );
712
713 BOOST_CHECK_MESSAGE( matrices[0].f < matrices[1].f && matrices[1].f < matrices[2].f,
714 "Expected ctm_f_TOP < ctm_f_CENTER < ctm_f_BOTTOM, got "
715 << matrices[0].f << ", " << matrices[1].f << ", " << matrices[2].f );
716
717 // The uncorrected StringBoundaryLimits formula (pre-fix) would give
718 // 0.5 * (size + 3*thickness) for the V_TOP to V_CENTER delta.
719 const double uncorrectedDelta = 0.5 * ( fontSize + 3.0 * thickness );
720 BOOST_CHECK_MESSAGE( std::abs( observed_delta_top_center - uncorrectedDelta ) > 1.0,
721 "ctm_f delta for V_TOP vs V_CENTER matches the uncorrected formula; "
722 "the stroke-font alignment fix does not appear to be in effect." );
723
724 // Italic shear must still be present on the text matrix.
725 BOOST_CHECK_MESSAGE( std::abs( matrices[3].c ) > 0.01,
726 "Italic text matrix does not show the expected shear (adj_c == "
727 << matrices[3].c << ")" );
728
729 // Glyph YOffset cancel is constant across V-alignments. With GAL-based start positions,
730 // only IU Y differs between V_TOP and V_CENTER for horizontal text, so ctm_e must not
731 // change (old per-V-align deltaDev hacks incorrectly introduced a shear * Y correction
732 // into e). Same for italic and non-italic.
733 const double italic_delta_e = matrices[4].e - matrices[3].e;
734 const double nonitalic_delta_e = matrices[1].e - matrices[0].e;
735
736 BOOST_CHECK_SMALL( nonitalic_delta_e, 1.0 );
737 BOOST_CHECK_SMALL( italic_delta_e, 1.0 );
738
739 // V-alignment deltas on f remain the same under italic shear (Y cancel is constant).
740 const double italic_delta_top_center = matrices[4].f - matrices[3].f;
741 BOOST_CHECK_CLOSE( italic_delta_top_center, expected_delta_top_center, 1.0 );
742
743 MaybeRemoveFile( pdfPath );
744}
745
746
747// Regression test for https://gitlab.com/kicad/code/kicad/-/issues/24419
748// PDF_PLOTTER::renderWord used to advance the per-word cursor by
749// FONT::StringBoundaryLimits, which for stroke fonts inflates the returned
750// bounding box by 3*thickness. The Tj operator that actually renders the word
751// advances by the sum of glyph widths (no inflation), so successive words were
752// pushed too far apart in the rendered PDF. The bug was visible on silkscreen
753// text whose width exceeded the board edge in the exported PDF but fit on the
754// PCB editor canvas.
755//
756// The fix is to derive the cursor advance from FONT::GetTextAsGlyphs, which
757// matches exactly what Tj produces. This test plots a multi-word string and
758// verifies that the gap between word origins corresponds to the actual
759// glyph-width sum rather than the inflated bbox.
760BOOST_AUTO_TEST_CASE( StrokeFontWordSpacingMatchesGlyphAdvance )
761{
762 wxString pdfPath = getTempPdfPath( "kicad_pdf_wordspacing" );
763
764 PDF_PLOTTER plotter;
765 SIMPLE_RENDER_SETTINGS renderSettings;
766 plotter.SetRenderSettings( &renderSettings );
767 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
768 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
769 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "WordSpacingTest" ) ) );
770
771 const int sizeIU = 1900; // mimics the 1.9mm silk text from issue #24419
772 const int strokeW = 380; // bold thickness as in the issue file
773 TEXT_ATTRIBUTES attrs = BuildTextAttributes( sizeIU, strokeW, true, false );
776
777 auto strokeFont = LoadStrokeFontUnique();
778 const KIFONT::METRICS metrics;
779
780 plotter.PlotText( VECTOR2I( 50000, 60000 ), COLOR4D( 0, 0, 0, 1 ),
781 wxT( "TEST text Silkscreen" ), attrs, strokeFont.get(), metrics );
782 plotter.EndPlot();
783
784 std::string buffer;
785 BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
786
787 // Each word becomes one `q ... cm BT ... Tj ET Q` block. Capture the X translation (ctm_e)
788 // of each block so we can verify the gap between words.
789 std::vector<double> wordOriginX;
790 std::string::size_type pos = 0;
791
792 while( ( pos = buffer.find( "cm BT", pos ) ) != std::string::npos )
793 {
794 std::string::size_type lineStart = buffer.rfind( '\n', pos );
795 lineStart = ( lineStart == std::string::npos ) ? 0 : lineStart + 1;
796
797 std::string cmLine = buffer.substr( lineStart, pos - lineStart );
798 double a, b, c, d, e, f;
799
800 if( sscanf( cmLine.c_str(), "q %lf %lf %lf %lf %lf %lf", &a, &b, &c, &d, &e, &f ) == 6 )
801 wordOriginX.push_back( e );
802
803 pos += 5;
804 }
805
806 // Expect one block per word: "TEST", "text", "Silkscreen".
807 BOOST_REQUIRE_EQUAL( wordOriginX.size(), 3u );
808
809 // Compute the expected stroke-font cursor advance for "TEST " (word + trailing space) and
810 // "text " in IU. This is what the Tj operator will move the text cursor by and what the
811 // renderWord cursor should match. Compare ratios so we don't have to convert to device
812 // units (userToDeviceSize is protected).
813 auto strokeAdvanceIU = [&]( const wxString& aWord )
814 {
815 return strokeFont
816 ->GetTextAsGlyphs( nullptr, nullptr, aWord, VECTOR2I( sizeIU, sizeIU ),
818 .x;
819 };
820
821 const double expectedTestAdvanceIU = (double) strokeAdvanceIU( wxT( "TEST " ) );
822 const double expectedTextAdvanceIU = (double) strokeAdvanceIU( wxT( "text " ) );
823
824 const double observedTestAdvanceDev = wordOriginX[1] - wordOriginX[0];
825 const double observedTextAdvanceDev = wordOriginX[2] - wordOriginX[1];
826
827 // device-per-IU scale factor derived from the first observed gap.
828 const double scale = observedTestAdvanceDev / expectedTestAdvanceIU;
829
830 // The TEST -> text advance and the text -> Silkscreen advance must both follow the
831 // same IU-to-device scale: if the spacing matches glyph metrics, the second observed
832 // gap equals scale * expectedTextAdvanceIU.
833 const double expectedTextAdvanceDev = scale * expectedTextAdvanceIU;
834 BOOST_CHECK_CLOSE( observedTextAdvanceDev, expectedTextAdvanceDev, 0.5 );
835
836 // Sanity guard against regression to the inflated-bbox formula, which adds 3*thickness IU
837 // of slop per word. Use the second word so this check is independent of the scale derivation
838 // above.
839 const double inflatedTextAdvanceDev = scale * ( expectedTextAdvanceIU + 3.0 * strokeW );
840 BOOST_CHECK_MESSAGE( std::abs( observedTextAdvanceDev - inflatedTextAdvanceDev )
841 > 0.5 * ( inflatedTextAdvanceDev - expectedTextAdvanceDev ),
842 "Word spacing matches the buggy inflated-bbox formula ("
843 << observedTextAdvanceDev << " ~= " << inflatedTextAdvanceDev
844 << "); the renderWord cursor fix appears inactive." );
845
846 MaybeRemoveFile( pdfPath );
847}
848
849// Regression test for https://gitlab.com/kicad/code/kicad/-/issues/23843
850// A border-less filled shape with a dashed/dotted stroke is plotted with a zero pen width.
851// PDF_PLOTTER::SetDash then computed every dash element from that zero width, emitting an
852// all-zero dash array "[0 0] 0 d". Such an array is illegal in PDF and makes strict viewers
853// (Adobe Acrobat, Evince) abort rendering of the rest of the page, dropping the shape fill,
854// the page background and any junction dots that follow. SetDash must fall back to a solid
855// line "[] 0 d" when the requested pattern degenerates to all zeros.
856BOOST_AUTO_TEST_CASE( SetDashZeroWidthNoIllegalDashArray )
857{
858 wxString pdfPath = getTempPdfPath( "kicad_pdf_zero_dash" );
859
860 PDF_PLOTTER plotter;
861 SIMPLE_RENDER_SETTINGS renderSettings;
862
863 plotter.SetRenderSettings( &renderSettings );
864 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
865 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
866 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "DashTest" ) ) );
867
868 // Reproduce the border-less dotted filled rectangle from the issue: a dotted dash style
869 // with a zero pen width, followed by the filled (no-outline) rectangle itself. Exercise
870 // every dashed style so a regression in any of them is caught.
871 plotter.SetColor( COLOR4D( 1.0, 0.0, 0.0, 1.0 ) );
872
875 {
876 plotter.SetDash( 0, style );
877 }
878
879 plotter.SetDash( 0, LINE_STYLE::DOT );
880 plotter.Rect( VECTOR2I( 50000, 50000 ), VECTOR2I( 70000, 60000 ), FILL_T::FILLED_SHAPE, 0 );
881
882 plotter.EndPlot();
883
884 std::string buffer;
885 BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
886 BOOST_CHECK( buffer.rfind( "%PDF", 0 ) == 0 );
887
888 // No illegal all-zero dash array may be present anywhere in the content stream, for any
889 // of the dashed styles.
890 for( const char* illegalPattern : { "[0 0] 0 d", "[0 0 0 0] 0 d", "[0 0 0 0 0 0] 0 d" } )
891 {
892 BOOST_CHECK_MESSAGE( buffer.find( illegalPattern ) == std::string::npos,
893 "PDF contains an illegal all-zero dash array (" << illegalPattern
894 << "), which breaks strict viewers" );
895 }
896
897 // The zero-width dashed styles must have degenerated to a solid line.
898 BOOST_CHECK_MESSAGE( buffer.find( "[] 0 d" ) != std::string::npos,
899 "Zero-width dashed style should fall back to a solid dash array" );
900
901 // The fill operator for the rectangle must still be emitted.
902 BOOST_CHECK_MESSAGE( buffer.find( " re f" ) != std::string::npos
903 || buffer.find( "re\nf" ) != std::string::npos,
904 "Filled rectangle should still be plotted" );
905
906 MaybeRemoveFile( pdfPath );
907}
908
909
910// Companion to SetDashZeroWidthNoIllegalDashArray: the solid-line fallback must apply only to the
911// degenerate all-zero case. A normal non-zero pen width must still emit a real dashed array, so a
912// fix that collapsed every dashed style to solid would regress here.
913BOOST_AUTO_TEST_CASE( SetDashNonZeroWidthKeepsDashArray )
914{
915 wxString pdfPath = getTempPdfPath( "kicad_pdf_nonzero_dash" );
916
917 PDF_PLOTTER plotter;
918 SIMPLE_RENDER_SETTINGS renderSettings;
919
920 plotter.SetRenderSettings( &renderSettings );
921 BOOST_REQUIRE( plotter.OpenFile( pdfPath ) );
922 plotter.SetViewport( VECTOR2I( 0, 0 ), 1.0, 1.0, false );
923 BOOST_REQUIRE( plotter.StartPlot( wxT( "1" ), wxT( "DashTest" ) ) );
924
925 plotter.SetColor( COLOR4D( 1.0, 0.0, 0.0, 1.0 ) );
926 plotter.SetDash( 10000, LINE_STYLE::DASH );
927 plotter.MoveTo( VECTOR2I( 50000, 50000 ) );
928 plotter.FinishTo( VECTOR2I( 70000, 50000 ) );
929
930 plotter.EndPlot();
931
932 std::string buffer;
933 BOOST_REQUIRE( ReadPdfWithDecompressedStreams( pdfPath, buffer ) );
934
935 // The dash array elements scale with the pen width, so a non-zero width yields a real,
936 // non-zero pattern. Find the emitted array and confirm it is neither the solid fallback
937 // "[]" nor the all-zero degenerate form.
938 size_t dashPos = buffer.find( "] 0 d" );
939 BOOST_REQUIRE_MESSAGE( dashPos != std::string::npos, "No dash array was emitted" );
940
941 size_t openPos = buffer.rfind( '[', dashPos );
942 BOOST_REQUIRE( openPos != std::string::npos && openPos < dashPos );
943
944 std::string dashArray = buffer.substr( openPos, dashPos - openPos + 1 );
945
946 BOOST_CHECK_MESSAGE( dashArray.find_first_of( "123456789" ) != std::string::npos,
947 "Non-zero dashed style should emit a real, non-zero dash array, got "
948 << dashArray );
949 BOOST_CHECK_MESSAGE( dashArray != "[]",
950 "A non-zero pen width must not fall back to the solid line" );
951}
952
const char * name
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:986
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
static FONT * GetFont(const wxString &aFontName=wxEmptyString, bool aBold=false, bool aItalic=false, const std::vector< wxString > *aEmbeddedFiles=nullptr, bool aForDrawingSheet=false)
Definition font.cpp:143
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
virtual bool EndPlot() override
virtual void SetDash(int aLineWidth, LINE_STYLE aLineStyle) override
PDF supports dashed lines.
virtual bool OpenFile(const wxString &aFullFilename) override
Open or create the plot file aFullFilename.
virtual void Rect(const VECTOR2I &p1, const VECTOR2I &p2, FILL_T fill, int width, int aCornerRadius=0) override
Rectangles in PDF.
virtual bool StartPlot(const wxString &aPageNumber) override
The PDF engine supports multiple pages; the first one is opened 'for free' the following are to be cl...
virtual void SetViewport(const VECTOR2I &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
PDF can have multiple pages, so SetPageSettings can be called with the outputFile open (but not insid...
virtual void PlotText(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const TEXT_ATTRIBUTES &aAttributes, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
void SetRenderSettings(RENDER_SETTINGS *aSettings)
Definition plotter.h:163
void MoveTo(const VECTOR2I &pos)
Definition plotter.h:305
void FinishTo(const VECTOR2I &pos)
Definition plotter.h:315
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: the PSLIKE computes the rgb values,...
Minimal concrete render settings suitable for plotters in tests.
GR_TEXT_H_ALIGN_T m_Halign
GR_TEXT_V_ALIGN_T m_Valign
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:411
@ FILLED_SHAPE
Fill with object color.
Definition eda_shape.h:61
@ BOLD
Definition font.h:43
double m_PDFStrokeFontXOffset
Horizontal offset factor applied to stroke font glyph coordinates (in EM units) after to compensate m...
double m_PDFStrokeFontYOffset
Vertical offset factor applied to stroke font glyph coordinates (in EM units) after Y inversion to co...
std::string GetTestDataRootDir()
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:400
int CountOccurrences(const std::string &aHaystack, const std::string &aNeedle)
Count occurrences of a substring in a string (overlapping allowed).
bool PdfContains(const std::string &aBuffer, const char *aNeedle)
Convenience contains check.
bool ReadPdfWithDecompressedStreams(const wxString &aPdfPath, std::string &aOutBuffer)
Read a PDF file and append best-effort decompressed contents of any Flate streams to the returned buf...
std::unique_ptr< KIFONT::STROKE_FONT > LoadStrokeFontUnique()
Load the default stroke font and return a unique_ptr for RAII deletion.
TEXT_ATTRIBUTES BuildTextAttributes(int aSizeIu=3000, int aStrokeWidth=300, bool aBold=false, bool aItalic=false)
Build a commonly used set of text attributes for plotting text in tests.
bool RasterizePdfCountDark(const wxString &aPdfPath, int aDpi, int aNearWhiteThresh, long &aOutDarkPixels)
Rasterize a PDF page to PNG using pdftoppm if available and count non-near-white pixels.
wxString MakeTempPdfPath(const wxString &aPrefix)
Make a temporary file path with .pdf extension using a given prefix.
void MaybeRemoveFile(const wxString &aPath, const wxString &aEnvVar=wxT("KICAD_KEEP_TEST_PDF"))
Remove a file unless the given environment variable is set (defaults to KICAD_KEEP_TEST_PDF).
Plotting engines similar to ps (PostScript, Gerber, svg)
const int scale
LINE_STYLE
Dashed line types.
BOOST_AUTO_TEST_SUITE(CadstarPartParser)
BOOST_REQUIRE(intersection.has_value()==c.ExpectedIntersection.has_value())
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_CASE(PlotMultilingualAllStylesMappings)
static wxString getTempPdfPath(const wxString &name)
static std::vector< double > ExtractStrokeTextOriginsX(const std::string &aBuffer)
VECTOR2I end
BOOST_TEST_MESSAGE("Polyline has "<< chain.PointCount()<< " points")
@ GR_TEXT_H_ALIGN_LEFT
GR_TEXT_V_ALIGN_T
This is API surface mapped to common.types.VertialAlignment.
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683