20#include <boost/test/unit_test.hpp>
22#include <wx/filename.h>
53 const std::string sampleUtf8 =
"ABCDEF Привет 日本語 漢字";
54 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
55 wxString pdfPath =
getTempPdfPath(
"kicad_pdf_unicode_allstyles" );
65 auto emitStyle = [&](
bool bold,
bool italic,
int yoff )
72 strokeFont.get(), metrics );
75 emitStyle(
false,
false, 0 );
76 emitStyle(
true,
false, 8000 );
77 emitStyle(
false,
true, 16000 );
78 emitStyle(
true,
true, 24000 );
85 BOOST_CHECK( buffer.rfind(
"%PDF", 0 ) == 0 );
90 BOOST_CHECK_MESSAGE( cmapCount >= 4,
"Expected at least 4 CMaps (got " << cmapCount <<
")" );
92 auto requireAll = [&](
const char* codeHex,
const char* label ) {
94 BOOST_CHECK_MESSAGE( occurrences >= 4,
"Codepoint " << label <<
" (" << codeHex
95 <<
") expected in all 4 styles; found " << occurrences );
98 requireAll(
"041F",
"Cyrillic PE" );
99 requireAll(
"65E5",
"Kanji 日" );
100 requireAll(
"672C",
"Kanji 本" );
108 const std::string sampleUtf8 =
"ABCDEF Привет 日本語 漢字";
109 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
137 strokeFont.get(), metrics );
144 auto contains = [&](
const char* needle ) {
return PdfContains( buffer2, needle ); };
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 / 漢)" );
159 BOOST_CHECK_MESSAGE( darkPixels > 200,
160 "Rasterized PDF appears blank or too sparse (" << darkPixels
161 <<
" dark pixels)" );
174 const std::string sampleUtf8 =
"ABCDEF Привет 日本語 漢字";
175 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
190 strokeFont.get(), metrics );
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)" );
202 const std::string sampleUtf8 =
"ABCDEF Привет 日本語 漢字";
203 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
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)" );
227 const std::string sampleUtf8 =
"ABCDEF Привет 日本語 漢字";
228 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
229 wxString pdfPath =
getTempPdfPath(
"kicad_pdf_unicode_bolditalic" );
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)" );
257 const std::string sampleUtf8 =
"MW";
258 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
274 strokeFont.get(), metrics );
285 double unitsPerEm = 1000.0;
287 double widthFactor = 300.0 / 3000.0;
288 double expectedHalfStroke = unitsPerEm * widthFactor / 2.0;
291 std::string::size_type pos = 0;
292 int checkedGlyphs = 0;
294 while( ( pos = buffer.find(
" d1 ", pos ) ) != std::string::npos )
297 std::string::size_type lineStart = buffer.rfind(
'\n', pos );
299 if( lineStart == std::string::npos )
304 std::string d1Line = buffer.substr( lineStart, pos + 3 - lineStart );
306 double width, wy, minX, minY, maxX, maxY;
308 if( sscanf( d1Line.c_str(),
"%lf %lf %lf %lf %lf %lf", &width, &wy, &minX, &minY,
309 &maxX, &maxY ) == 6 )
312 if( width == 0.0 && maxX == 0.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" );
326 BOOST_CHECK_MESSAGE( maxX > width,
327 "Glyph bbox maxX (" << maxX <<
") must exceed advance width ("
328 << width <<
") to prevent clipping" );
336 BOOST_CHECK_MESSAGE( checkedGlyphs >= 2,
337 "Expected at least 2 non-notdef glyphs, found " << checkedGlyphs );
350 const std::string sampleUtf8 =
"Yg Test ñ";
351 wxString sample = wxString::FromUTF8( sampleUtf8.c_str() );
374 BOOST_CHECK( buffer6.rfind(
"%PDF", 0 ) == 0 );
378 BOOST_CHECK_MESSAGE( buffer6.find(
"d1" ) != std::string::npos,
379 "PDF should contain d1 operators for glyph bounding boxes" );
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();
408 std::vector<wxString> embeddedFonts;
409 embeddedFonts.push_back( fontPath );
414 wxString sample = wxString::FromUTF8(
"Outline café" );
417 outlineFont, metrics );
421 wxFFile file( pdfPath,
"rb" );
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 );
428 appendDecompressed();
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" );
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 );
448 int ret = wxExecute( cmd, wxEXEC_SYNC );
452 wxString pngPath = rasterBase + wxT(
".png");
454 if( wxFileExists( pngPath ) )
457 if( !wxImage::FindHandler( wxBITMAP_TYPE_PNG ) )
458 wxImage::AddHandler(
new wxPNGHandler );
460 wxImage img( pngPath );
461 BOOST_REQUIRE_MESSAGE( img.IsOk(),
"Failed to load rasterized PDF image" );
464 int w = img.GetWidth();
465 int h = img.GetHeight();
467 for(
int y = 0; y < h; ++y )
469 for(
int x = 0; x < w; ++x )
471 unsigned char r = img.GetRed( x, y );
472 unsigned char g = img.GetGreen( x, y );
473 unsigned char b = img.GetBlue( x, y );
476 if( r < 240 || g < 240 || b < 240 )
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." );
488 wxRemoveFile( pngPath );
492 BOOST_TEST_MESSAGE(
"pdftoppm succeeded but PNG output missing; skipping raster validation" );
509 std::vector<double> origins;
512 while( ( pos = aBuffer.find(
"cm BT", pos ) ) != std::string::npos )
514 std::string head = aBuffer.substr( 0, pos );
515 std::vector<double> nums;
517 for(
size_t end = head.size();
end > 0 && nums.size() < 6; )
519 size_t start = head.find_last_not_of(
" \n\r\t",
end - 1 );
521 if( start == std::string::npos )
524 size_t tokStart = head.find_last_of(
" \n\r\t", start );
525 tokStart = ( tokStart == std::string::npos ) ? 0 : tokStart + 1;
529 nums.push_back( std::stod( head.substr( tokStart, start - tokStart + 1 ) ) );
539 if( nums.size() == 6 )
540 origins.push_back( nums[1] );
568 const int sizeIu = 1270000;
575 strokeFont.get(), metrics );
577 strokeFont.get(), metrics );
581 attrs, strokeFont.get(), metrics );
587 BOOST_CHECK( buffer.rfind(
"%PDF", 0 ) == 0 );
592 BOOST_REQUIRE_EQUAL( origins.size(), 4u );
594 const double scale = ( origins[1] - origins[0] ) / ( 80000000.0 - 40000000.0 );
598 const double measuredOffsetIu = ( origins[3] - origins[2] ) /
scale;
600 const VECTOR2I size( sizeIu, sizeIu );
603 const double expectedOffsetIu =
604 strokeFont->GetTextAsGlyphs(
nullptr,
nullptr, wxT(
"v07:\t" ), size,
VECTOR2I(),
609 const double widthV07 =
610 strokeFont->GetTextAsGlyphs(
nullptr,
nullptr, wxT(
"v07:" ), size,
VECTOR2I(),
ANGLE_0,
613 const int oldTabWidth =
KiROUND( sizeIu * 4 * 0.6 );
614 const double oldOffsetIu = widthV07 + ( oldTabWidth -
KiROUND( widthV07 ) % oldTabWidth );
616 const double tolerance = sizeIu * 0.02;
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)" );
646 const int anchorY = 60000;
647 const int sizeIU = 3000;
648 const int strokeW = 300;
657 strokeFont.get(), metrics );
671 struct MATRIX_SAMPLE {
double a, b, c, d, e, f; };
672 std::vector<MATRIX_SAMPLE> matrices;
673 std::string::size_type pos = 0;
675 while( ( pos = buffer.find(
"cm BT", pos ) ) != std::string::npos )
677 std::string::size_type lineStart = buffer.rfind(
'\n', pos );
678 lineStart = ( lineStart == std::string::npos ) ? 0 : lineStart + 1;
680 std::string cmLine = buffer.substr( lineStart, pos - lineStart );
683 if( sscanf( cmLine.c_str(),
"q %lf %lf %lf %lf %lf %lf", &m.a, &m.b, &m.c, &m.d, &m.e,
686 matrices.push_back( m );
692 BOOST_REQUIRE_EQUAL( matrices.size(), 5u );
694 const double fontSize = (double) sizeIU;
695 const double thickness = (double) strokeW;
704 const double expected_delta_top_center = ( 1.000 - 0.415 ) * fontSize;
705 const double expected_delta_center_bot = ( 0.415 - ( -0.17 ) ) * fontSize;
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;
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 );
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 );
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." );
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 <<
")" );
733 const double italic_delta_e = matrices[4].e - matrices[3].e;
734 const double nonitalic_delta_e = matrices[1].e - matrices[0].e;
736 BOOST_CHECK_SMALL( nonitalic_delta_e, 1.0 );
737 BOOST_CHECK_SMALL( italic_delta_e, 1.0 );
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 );
771 const int sizeIU = 1900;
772 const int strokeW = 380;
781 wxT(
"TEST text Silkscreen" ), attrs, strokeFont.get(), metrics );
789 std::vector<double> wordOriginX;
790 std::string::size_type pos = 0;
792 while( ( pos = buffer.find(
"cm BT", pos ) ) != std::string::npos )
794 std::string::size_type lineStart = buffer.rfind(
'\n', pos );
795 lineStart = ( lineStart == std::string::npos ) ? 0 : lineStart + 1;
797 std::string cmLine = buffer.substr( lineStart, pos - lineStart );
798 double a, b, c, d, e, f;
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 );
807 BOOST_REQUIRE_EQUAL( wordOriginX.size(), 3u );
813 auto strokeAdvanceIU = [&](
const wxString& aWord )
816 ->GetTextAsGlyphs(
nullptr,
nullptr, aWord,
VECTOR2I( sizeIU, sizeIU ),
821 const double expectedTestAdvanceIU = (double) strokeAdvanceIU( wxT(
"TEST " ) );
822 const double expectedTextAdvanceIU = (double) strokeAdvanceIU( wxT(
"text " ) );
824 const double observedTestAdvanceDev = wordOriginX[1] - wordOriginX[0];
825 const double observedTextAdvanceDev = wordOriginX[2] - wordOriginX[1];
828 const double scale = observedTestAdvanceDev / expectedTestAdvanceIU;
833 const double expectedTextAdvanceDev =
scale * expectedTextAdvanceIU;
834 BOOST_CHECK_CLOSE( observedTextAdvanceDev, expectedTextAdvanceDev, 0.5 );
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." );
886 BOOST_CHECK( buffer.rfind(
"%PDF", 0 ) == 0 );
890 for(
const char* illegalPattern : {
"[0 0] 0 d",
"[0 0 0 0] 0 d",
"[0 0 0 0 0 0] 0 d" } )
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" );
898 BOOST_CHECK_MESSAGE( buffer.find(
"[] 0 d" ) != std::string::npos,
899 "Zero-width dashed style should fall back to a solid dash array" );
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" );
938 size_t dashPos = buffer.find(
"] 0 d" );
939 BOOST_REQUIRE_MESSAGE( dashPos != std::string::npos,
"No dash array was emitted" );
941 size_t openPos = buffer.rfind(
'[', dashPos );
942 BOOST_REQUIRE( openPos != std::string::npos && openPos < dashPos );
944 std::string dashArray = buffer.substr( openPos, dashPos - openPos + 1 );
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 "
949 BOOST_CHECK_MESSAGE( dashArray !=
"[]",
950 "A non-zero pen width must not fall back to the solid line" );
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
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.
static FONT * GetFont(const wxString &aFontName=wxEmptyString, bool aBold=false, bool aItalic=false, const std::vector< wxString > *aEmbeddedFiles=nullptr, bool aForDrawingSheet=false)
A color representation with 4 components: red, green, blue, alpha.
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)
void MoveTo(const VECTOR2I &pos)
void FinishTo(const VECTOR2I &pos)
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
@ FILLED_SHAPE
Fill with object color.
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)
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)
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)
BOOST_TEST_MESSAGE("Polyline has "<< chain.PointCount()<< " points")
GR_TEXT_V_ALIGN_T
This is API surface mapped to common.types.VertialAlignment.
VECTOR2< int32_t > VECTOR2I