You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

857 lines
28 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2020 Jean-Pierre Charras, jp.charras at wanadoo.fr
  5. * Copyright (C) 1992-2022 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. /* Some info on basic items SVG format, used here:
  25. * The root element of all SVG files is the <svg> element.
  26. *
  27. * The <g> element is used to group SVG shapes together.
  28. * Once grouped you can transform the whole group of shapes as if it was a single shape.
  29. * This is an advantage compared to a nested <svg> element
  30. * which cannot be the target of transformation by itself.
  31. *
  32. * The <rect> element represents a rectangle.
  33. * Using this element you can draw rectangles of various width, height,
  34. * with different stroke (outline) and fill colors, with sharp or rounded corners etc.
  35. *
  36. * <svg xmlns="http://www.w3.org/2000/svg"
  37. * xmlns:xlink="http://www.w3.org/1999/xlink">
  38. *
  39. * <rect x="10" y="10" height="100" width="100"
  40. * style="stroke:#006600; fill: #00cc00"/>
  41. *
  42. * </svg>
  43. *
  44. * The <circle> element is used to draw circles.
  45. * <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
  46. *
  47. * The <ellipse> element is used to draw ellipses.
  48. * An ellipse is a circle that does not have equal height and width.
  49. * Its radius in the x and y directions are different, in other words.
  50. * <ellipse cx="40" cy="40" rx="30" ry="15"
  51. * style="stroke:#006600; fill:#00cc00"/>
  52. *
  53. * The <line> element is used to draw lines.
  54. *
  55. * <line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;"/>
  56. * <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600;"/>
  57. *
  58. * The <polyline> element is used to draw multiple connected lines
  59. * Here is a simple example:
  60. *
  61. * <polyline points="0,0 30,0 15,30" style="stroke:#006600;"/>
  62. *
  63. * The <polygon> element is used to draw with multiple (3 or more) sides / edges.
  64. * Here is a simple example:
  65. *
  66. * <polygon points="0,0 50,0 25,50" style="stroke:#660000; fill:#cc3333;"/>
  67. *
  68. * The <path> element is used to draw advanced shapes combined from lines and arcs,
  69. * with or without fill.
  70. * It is probably the most advanced and versatile SVG shape of them all.
  71. * It is probably also the hardest element to master.
  72. * <path d="M50,50
  73. * A30,30 0 0,1 35,20
  74. * L100,100
  75. * M110,110
  76. * L100,0"
  77. * style="stroke:#660000; fill:none;"/>
  78. *
  79. * Draw an elliptic arc: it is one of basic path command:
  80. * <path d="M(startx,starty) A(radiusx,radiusy)
  81. * rotation-axe-x
  82. * flag_arc_large,flag_sweep endx,endy">
  83. * flag_arc_large: 0 = small arc > 180 deg, 1 = large arc > 180 deg
  84. * flag_sweep : 0 = CCW, 1 = CW
  85. * The center of ellipse is automatically calculated.
  86. */
  87. #include <base64.h>
  88. #include <eda_rect.h>
  89. #include <eda_shape.h>
  90. #include <string_utils.h>
  91. #include <font/font.h>
  92. #include <macros.h>
  93. #include <trigo.h>
  94. #include <cstdint>
  95. #include <wx/mstream.h>
  96. #include <plotters/plotters_pslike.h>
  97. // Note:
  98. // During tests, we (JPC) found issues when the coordinates used 6 digits in mantissa
  99. // especially for stroke-width using very small (but not null) values < 0.00001 mm
  100. // So to avoid this king of issue, we are using 4 digits in mantissa
  101. // The resolution (m_precision ) is 0.1 micron, that looks enougt for a SVG file
  102. /**
  103. * Translates '<' to "&lt;", '>' to "&gt;" and so on, according to the spec:
  104. * http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping
  105. * May be moved to a library if needed generally, but not expecting that.
  106. */
  107. static wxString XmlEsc( const wxString& aStr, bool isAttribute = false )
  108. {
  109. wxString escaped;
  110. escaped.reserve( aStr.length() );
  111. for( wxString::const_iterator it = aStr.begin(); it != aStr.end(); ++it )
  112. {
  113. const wxChar c = *it;
  114. switch( c )
  115. {
  116. case wxS( '<' ):
  117. escaped.append( wxS( "&lt;" ) );
  118. break;
  119. case wxS( '>' ):
  120. escaped.append( wxS( "&gt;" ) );
  121. break;
  122. case wxS( '&' ):
  123. escaped.append( wxS( "&amp;" ) );
  124. break;
  125. case wxS( '\r' ):
  126. escaped.append( wxS( "&#xD;" ) );
  127. break;
  128. default:
  129. if( isAttribute )
  130. {
  131. switch( c )
  132. {
  133. case wxS( '"' ):
  134. escaped.append( wxS( "&quot;" ) );
  135. break;
  136. case wxS( '\t' ):
  137. escaped.append( wxS( "&#x9;" ) );
  138. break;
  139. case wxS( '\n' ):
  140. escaped.append( wxS( "&#xA;" ));
  141. break;
  142. default:
  143. escaped.append(c);
  144. }
  145. }
  146. else
  147. escaped.append(c);
  148. }
  149. }
  150. return escaped;
  151. }
  152. SVG_PLOTTER::SVG_PLOTTER()
  153. {
  154. m_graphics_changed = true;
  155. SetTextMode( PLOT_TEXT_MODE::STROKE );
  156. m_fillMode = FILL_T::NO_FILL; // or FILLED_SHAPE or FILLED_WITH_BG_BODYCOLOR
  157. m_pen_rgb_color = 0; // current color value (black)
  158. m_brush_rgb_color = 0; // current color value (black)
  159. m_brush_alpha = 1.0;
  160. m_dashed = PLOT_DASH_TYPE::SOLID;
  161. m_useInch = false; // millimeters are always the svg unit
  162. m_precision = 4; // default: 4 digits in mantissa.
  163. }
  164. void SVG_PLOTTER::SetViewport( const VECTOR2I& aOffset, double aIusPerDecimil,
  165. double aScale, bool aMirror )
  166. {
  167. m_plotMirror = aMirror;
  168. m_yaxisReversed = true; // unlike other plotters, SVG has Y axis reversed
  169. m_plotOffset = aOffset;
  170. m_plotScale = aScale;
  171. m_IUsPerDecimil = aIusPerDecimil;
  172. // Compute the paper size in IUs. for historical reasons the page size is in mils
  173. m_paperSize = m_pageInfo.GetSizeMils();
  174. m_paperSize.x *= 10.0 * aIusPerDecimil;
  175. m_paperSize.y *= 10.0 * aIusPerDecimil;
  176. // gives now a default value to iuPerDeviceUnit (because the units of the caller is now known)
  177. double iusPerMM = m_IUsPerDecimil / 2.54 * 1000;
  178. m_iuPerDeviceUnit = 1 / iusPerMM;
  179. SetSvgCoordinatesFormat( 4 );
  180. }
  181. void SVG_PLOTTER::SetSvgCoordinatesFormat( unsigned aPrecision )
  182. {
  183. // Only number of digits in mantissa are adjustable.
  184. // SVG units are always mm
  185. m_precision = aPrecision;
  186. }
  187. void SVG_PLOTTER::SetColor( const COLOR4D& color )
  188. {
  189. PSLIKE_PLOTTER::SetColor( color );
  190. if( m_graphics_changed )
  191. setSVGPlotStyle( GetCurrentLineWidth() );
  192. }
  193. void SVG_PLOTTER::setFillMode( FILL_T fill )
  194. {
  195. if( m_fillMode != fill )
  196. {
  197. m_graphics_changed = true;
  198. m_fillMode = fill;
  199. }
  200. }
  201. void SVG_PLOTTER::setSVGPlotStyle( int aLineWidth, bool aIsGroup, const std::string& aExtraStyle )
  202. {
  203. if( aIsGroup )
  204. fputs( "</g>\n<g ", m_outputFile );
  205. // output the background fill color
  206. fprintf( m_outputFile, "style=\"fill:#%6.6lX; ", m_brush_rgb_color );
  207. switch( m_fillMode )
  208. {
  209. case FILL_T::NO_FILL:
  210. fputs( "fill-opacity:0.0; ", m_outputFile );
  211. break;
  212. case FILL_T::FILLED_SHAPE:
  213. case FILL_T::FILLED_WITH_BG_BODYCOLOR:
  214. case FILL_T::FILLED_WITH_COLOR:
  215. fprintf( m_outputFile, "fill-opacity:%.*f; ", m_precision, m_brush_alpha );
  216. break;
  217. }
  218. double pen_w = userToDeviceSize( aLineWidth );
  219. if( pen_w < 0.0 ) // Ensure pen width validity
  220. pen_w = 0.0;
  221. // Fix a strange issue found in Inkscape: aWidth < 100 nm create issues on degrouping objects
  222. // So we use only 4 digits in mantissa for stroke-width.
  223. // TODO: perhaps used only 3 or 4 digits in mantissa for all values in mm, because some
  224. // issues were previouly reported reported when using nm as integer units
  225. fprintf( m_outputFile, "\nstroke:#%6.6lX; stroke-width:%.*f; stroke-opacity:1; \n",
  226. m_pen_rgb_color, m_precision, pen_w );
  227. fputs( "stroke-linecap:round; stroke-linejoin:round;", m_outputFile );
  228. //set any extra attributes for non-solid lines
  229. switch( m_dashed )
  230. {
  231. case PLOT_DASH_TYPE::DASH:
  232. fprintf( m_outputFile, "stroke-dasharray:%.*f,%.*f;",
  233. m_precision, GetDashMarkLenIU( aLineWidth ),
  234. m_precision, GetDashGapLenIU( aLineWidth ) );
  235. break;
  236. case PLOT_DASH_TYPE::DOT:
  237. fprintf( m_outputFile, "stroke-dasharray:%f,%f;",
  238. GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
  239. break;
  240. case PLOT_DASH_TYPE::DASHDOT:
  241. fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f;",
  242. GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
  243. GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
  244. break;
  245. case PLOT_DASH_TYPE::DASHDOTDOT:
  246. fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f,%f,%f;",
  247. GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
  248. GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
  249. GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
  250. break;
  251. case PLOT_DASH_TYPE::DEFAULT:
  252. case PLOT_DASH_TYPE::SOLID:
  253. default:
  254. //do nothing
  255. break;
  256. }
  257. if( aExtraStyle.length() )
  258. fputs( aExtraStyle.c_str(), m_outputFile );
  259. fputs( "\"", m_outputFile );
  260. if( aIsGroup )
  261. {
  262. fputs( ">", m_outputFile );
  263. m_graphics_changed = false;
  264. }
  265. fputs( "\n", m_outputFile );
  266. }
  267. void SVG_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
  268. {
  269. if( aWidth == DO_NOT_SET_LINE_WIDTH )
  270. return;
  271. else if( aWidth == USE_DEFAULT_LINE_WIDTH )
  272. aWidth = m_renderSettings->GetDefaultPenWidth();
  273. // Note: aWidth == 0 is fine: used for filled shapes with no outline thickness
  274. wxASSERT_MSG( aWidth >= 0, "Plotter called to set negative pen width" );
  275. if( aWidth != m_currentPenWidth )
  276. {
  277. m_graphics_changed = true;
  278. m_currentPenWidth = aWidth;
  279. }
  280. if( m_graphics_changed )
  281. setSVGPlotStyle( aWidth );
  282. }
  283. void SVG_PLOTTER::StartBlock( void* aData )
  284. {
  285. std::string* idstr = reinterpret_cast<std::string*>( aData );
  286. fputs( "<g ", m_outputFile );
  287. if( idstr )
  288. fprintf( m_outputFile, "id=\"%s\"", idstr->c_str() );
  289. fprintf( m_outputFile, ">\n" );
  290. }
  291. void SVG_PLOTTER::EndBlock( void* aData )
  292. {
  293. fprintf( m_outputFile, "</g>\n" );
  294. m_graphics_changed = true;
  295. }
  296. void SVG_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
  297. {
  298. int red = (int) ( 255.0 * r );
  299. int green = (int) ( 255.0 * g );
  300. int blue = (int) ( 255.0 * b );
  301. long rgb_color = (red << 16) | (green << 8) | blue;
  302. if( m_pen_rgb_color != rgb_color )
  303. {
  304. m_graphics_changed = true;
  305. m_pen_rgb_color = rgb_color;
  306. // Currently, use the same color for brush and pen (i.e. to draw and fill a contour).
  307. m_brush_rgb_color = rgb_color;
  308. m_brush_alpha = a;
  309. }
  310. }
  311. void SVG_PLOTTER::SetDash( int aLineWidth, PLOT_DASH_TYPE aLineStyle )
  312. {
  313. if( m_dashed != aLineStyle )
  314. {
  315. m_graphics_changed = true;
  316. m_dashed = aLineStyle;
  317. }
  318. if( m_graphics_changed )
  319. setSVGPlotStyle( aLineWidth );
  320. }
  321. void SVG_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width )
  322. {
  323. EDA_RECT rect( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
  324. rect.Normalize();
  325. VECTOR2D org_dev = userToDeviceCoordinates( rect.GetOrigin() );
  326. VECTOR2D end_dev = userToDeviceCoordinates( rect.GetEnd() );
  327. VECTOR2D size_dev = end_dev - org_dev;
  328. // Ensure size of rect in device coordinates is > 0
  329. // I don't know if this is a SVG issue or a Inkscape issue, but
  330. // Inkscape has problems with negative or null values for width and/or height, so avoid them
  331. DBOX rect_dev( org_dev, size_dev);
  332. rect_dev.Normalize();
  333. setFillMode( fill );
  334. SetCurrentLineWidth( width );
  335. // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
  336. // so use a line when happens.
  337. if( rect_dev.GetSize().x == 0.0 || rect_dev.GetSize().y == 0.0 ) // Draw a line
  338. {
  339. fprintf( m_outputFile,
  340. "<line x1=\"%.*f\" y1=\"%.*f\" x2=\"%.*f\" y2=\"%.*f\" />\n",
  341. m_precision, rect_dev.GetPosition().x, m_precision, rect_dev.GetPosition().y,
  342. m_precision, rect_dev.GetEnd().x, m_precision, rect_dev.GetEnd().y );
  343. }
  344. else
  345. {
  346. fprintf( m_outputFile,
  347. "<rect x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\" rx=\"%f\" />\n",
  348. rect_dev.GetPosition().x, rect_dev.GetPosition().y,
  349. rect_dev.GetSize().x, rect_dev.GetSize().y,
  350. 0.0 /* radius of rounded corners */ );
  351. }
  352. }
  353. void SVG_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T fill, int width )
  354. {
  355. VECTOR2D pos_dev = userToDeviceCoordinates( pos );
  356. double radius = userToDeviceSize( diametre / 2.0 );
  357. setFillMode( fill );
  358. SetCurrentLineWidth( width );
  359. // If diameter is less than width, switch to filled mode
  360. if( fill == FILL_T::NO_FILL && diametre < width )
  361. {
  362. setFillMode( FILL_T::FILLED_SHAPE );
  363. SetCurrentLineWidth( 0 );
  364. radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
  365. }
  366. fprintf( m_outputFile,
  367. "<circle cx=\"%.*f\" cy=\"%.*f\" r=\"%.*f\" /> \n",
  368. m_precision, pos_dev.x, m_precision, pos_dev.y, m_precision, radius );
  369. }
  370. void SVG_PLOTTER::Arc( const VECTOR2I& aCenter, const EDA_ANGLE& aStartAngle,
  371. const EDA_ANGLE& aEndAngle, int aRadius, FILL_T aFill, int aWidth )
  372. {
  373. /* Draws an arc of a circle, centered on (xc,yc), with starting point (x1, y1) and ending
  374. * at (x2, y2). The current pen is used for the outline and the current brush for filling
  375. * the shape.
  376. *
  377. * The arc is drawn in an anticlockwise direction from the start point to the end point.
  378. */
  379. if( aRadius <= 0 )
  380. {
  381. Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
  382. return;
  383. }
  384. EDA_ANGLE startAngle( aStartAngle );
  385. EDA_ANGLE endAngle( aEndAngle );
  386. if( startAngle > endAngle )
  387. std::swap( startAngle, endAngle );
  388. // Calculate start point.
  389. VECTOR2D centre_device = userToDeviceCoordinates( aCenter );
  390. double radius_device = userToDeviceSize( aRadius );
  391. if( !m_yaxisReversed ) // Should be never the case
  392. {
  393. std::swap( startAngle, endAngle );
  394. startAngle = -startAngle;
  395. endAngle = -endAngle;
  396. }
  397. if( m_plotMirror )
  398. {
  399. if( m_mirrorIsHorizontal )
  400. {
  401. std::swap( startAngle, endAngle );
  402. startAngle = ANGLE_180 - startAngle;
  403. endAngle = ANGLE_180 - endAngle;
  404. }
  405. else
  406. {
  407. startAngle = -startAngle;
  408. endAngle = -endAngle;
  409. }
  410. }
  411. VECTOR2D start;
  412. start.x = radius_device;
  413. RotatePoint( start, startAngle );
  414. VECTOR2D end;
  415. end.x = radius_device;
  416. RotatePoint( end, endAngle );
  417. start += centre_device;
  418. end += centre_device;
  419. double theta1 = startAngle.AsRadians();
  420. if( theta1 < 0 )
  421. theta1 = theta1 + M_PI * 2;
  422. double theta2 = endAngle.AsRadians();
  423. if( theta2 < 0 )
  424. theta2 = theta2 + M_PI * 2;
  425. if( theta2 < theta1 )
  426. theta2 = theta2 + M_PI * 2;
  427. int flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees
  428. if( fabs( theta2 - theta1 ) > M_PI )
  429. flg_arc = 1;
  430. int flg_sweep = 0; // flag for sweep always 0
  431. // Draw a single arc: an arc is one of 3 curve commands (2 other are 2 bezier curves)
  432. // params are start point, radius1, radius2, X axe rotation,
  433. // flag arc size (0 = small arc > 180 deg, 1 = large arc > 180 deg),
  434. // sweep arc ( 0 = CCW, 1 = CW),
  435. // end point
  436. if( aFill != FILL_T::NO_FILL )
  437. {
  438. // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on the arc
  439. // This needs to be drawn in two steps.
  440. setFillMode( aFill );
  441. SetCurrentLineWidth( 0 );
  442. fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f L %.*f %.*f Z\" />\n",
  443. m_precision, start.x, m_precision, start.y,
  444. m_precision, radius_device, m_precision, radius_device,
  445. flg_arc, flg_sweep,
  446. m_precision, end.x, m_precision, end.y,
  447. m_precision, centre_device.x, m_precision, centre_device.y );
  448. }
  449. setFillMode( FILL_T::NO_FILL );
  450. SetCurrentLineWidth( aWidth );
  451. fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f\" />\n",
  452. m_precision, start.x, m_precision, start.y,
  453. m_precision, radius_device, m_precision, radius_device,
  454. flg_arc, flg_sweep,
  455. m_precision, end.x, m_precision, end.y );
  456. }
  457. void SVG_PLOTTER::BezierCurve( const VECTOR2I& aStart, const VECTOR2I& aControl1,
  458. const VECTOR2I& aControl2, const VECTOR2I& aEnd,
  459. int aTolerance, int aLineThickness )
  460. {
  461. #if 1
  462. setFillMode( FILL_T::NO_FILL );
  463. SetCurrentLineWidth( aLineThickness );
  464. VECTOR2D start = userToDeviceCoordinates( aStart );
  465. VECTOR2D ctrl1 = userToDeviceCoordinates( aControl1 );
  466. VECTOR2D ctrl2 = userToDeviceCoordinates( aControl2 );
  467. VECTOR2D end = userToDeviceCoordinates( aEnd );
  468. // Generate a cubic curve: start point and 3 other control points.
  469. fprintf( m_outputFile, "<path d=\"M%.*f,%.*f C%.*f,%.*f %.*f,%.*f %.*f,%.*f\" />\n",
  470. m_precision, start.x, m_precision, start.y,
  471. m_precision, ctrl1.x, m_precision, ctrl1.y,
  472. m_precision, ctrl2.x, m_precision, ctrl2.y,
  473. m_precision, end.x, m_precision, end.y );
  474. #else
  475. PLOTTER::BezierCurve( aStart, aControl1, aControl2, aEnd, aTolerance, aLineThickness );
  476. #endif
  477. }
  478. void SVG_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill,
  479. int aWidth, void* aData )
  480. {
  481. if( aCornerList.size() <= 1 )
  482. return;
  483. setFillMode( aFill );
  484. SetCurrentLineWidth( aWidth );
  485. fprintf( m_outputFile, "<path ");
  486. switch( aFill )
  487. {
  488. case FILL_T::NO_FILL:
  489. setSVGPlotStyle( aWidth, false, "fill:none" );
  490. break;
  491. case FILL_T::FILLED_WITH_BG_BODYCOLOR:
  492. case FILL_T::FILLED_SHAPE:
  493. case FILL_T::FILLED_WITH_COLOR:
  494. setSVGPlotStyle( aWidth, false, "fill-rule:evenodd;" );
  495. break;
  496. }
  497. VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
  498. fprintf( m_outputFile, "d=\"M %.*f,%.*f\n", m_precision, pos.x, m_precision, pos.y );
  499. for( unsigned ii = 1; ii < aCornerList.size() - 1; ii++ )
  500. {
  501. pos = userToDeviceCoordinates( aCornerList[ii] );
  502. fprintf( m_outputFile, "%.*f,%.*f\n", m_precision, pos.x, m_precision, pos.y );
  503. }
  504. // If the corner list ends where it begins, then close the poly
  505. if( aCornerList.front() == aCornerList.back() )
  506. {
  507. fprintf( m_outputFile, "Z\" /> \n" );
  508. }
  509. else
  510. {
  511. pos = userToDeviceCoordinates( aCornerList.back() );
  512. fprintf( m_outputFile, "%.*f,%.*f\n\" /> \n", m_precision, pos.x, m_precision, pos.y );
  513. }
  514. }
  515. void SVG_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
  516. {
  517. VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
  518. // Requested size (in IUs)
  519. VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
  520. // calculate the bitmap start position
  521. VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y - drawsize.y / 2 );
  522. // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
  523. // so use a line when happens.
  524. if( drawsize.x == 0.0 || drawsize.y == 0.0 ) // Draw a line
  525. {
  526. PLOTTER::PlotImage( aImage, aPos, aScaleFactor );
  527. }
  528. else
  529. {
  530. wxMemoryOutputStream img_stream;
  531. aImage.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
  532. size_t input_len = img_stream.GetOutputStreamBuffer()->GetBufferSize();
  533. std::vector<uint8_t> buffer( input_len );
  534. std::vector<uint8_t> encoded;
  535. img_stream.CopyTo( buffer.data(), buffer.size() );
  536. base64::encode( buffer, encoded );
  537. fprintf( m_outputFile,
  538. "<image x=\"%f\" y=\"%f\" xlink:href=\"data:image/png;base64,",
  539. userToDeviceSize( start.x ), userToDeviceSize( start.y ) );
  540. for( size_t i = 0; i < encoded.size(); i++ )
  541. {
  542. fprintf( m_outputFile, "%c", static_cast<char>( encoded[i] ) );
  543. if( ( i % 64 ) == 63 )
  544. fprintf( m_outputFile, "\n" );
  545. }
  546. fprintf( m_outputFile, "\"\npreserveAspectRatio=\"none\" width=\"%.*f\" height=\"%.*f\" />",
  547. m_precision, userToDeviceSize( drawsize.x ), m_precision, userToDeviceSize( drawsize.y ) );
  548. }
  549. }
  550. void SVG_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
  551. {
  552. if( plume == 'Z' )
  553. {
  554. if( m_penState != 'Z' )
  555. {
  556. fputs( "\" />\n", m_outputFile );
  557. m_penState = 'Z';
  558. m_penLastpos.x = -1;
  559. m_penLastpos.y = -1;
  560. }
  561. return;
  562. }
  563. if( m_penState == 'Z' ) // here plume = 'D' or 'U'
  564. {
  565. VECTOR2D pos_dev = userToDeviceCoordinates( pos );
  566. // Ensure we do not use a fill mode when moving the pen,
  567. // in SVG mode (i;e. we are plotting only basic lines, not a filled area
  568. if( m_fillMode != FILL_T::NO_FILL )
  569. {
  570. setFillMode( FILL_T::NO_FILL );
  571. setSVGPlotStyle( GetCurrentLineWidth() );
  572. }
  573. fprintf( m_outputFile, "<path d=\"M%.*f %.*f\n",
  574. m_precision, pos_dev.x,
  575. m_precision, pos_dev.y );
  576. }
  577. else if( m_penState != plume || pos != m_penLastpos )
  578. {
  579. VECTOR2D pos_dev = userToDeviceCoordinates( pos );
  580. fprintf( m_outputFile, "L%.*f %.*f\n",
  581. m_precision, pos_dev.x,
  582. m_precision, pos_dev.y );
  583. }
  584. m_penState = plume;
  585. m_penLastpos = pos;
  586. }
  587. bool SVG_PLOTTER::StartPlot()
  588. {
  589. wxASSERT( m_outputFile );
  590. wxString msg;
  591. static const char* header[] =
  592. {
  593. "<?xml version=\"1.0\" standalone=\"no\"?>\n",
  594. " <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n",
  595. " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> \n",
  596. "<svg\n"
  597. " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"
  598. " xmlns=\"http://www.w3.org/2000/svg\"\n",
  599. " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n",
  600. " version=\"1.1\"\n",
  601. nullptr
  602. };
  603. // Write header.
  604. for( int ii = 0; header[ii] != nullptr; ii++ )
  605. {
  606. fputs( header[ii], m_outputFile );
  607. }
  608. // Write viewport pos and size
  609. VECTOR2D origin; // TODO set to actual value
  610. fprintf( m_outputFile, " width=\"%.*fmm\" height=\"%.*fmm\" viewBox=\"%.*f %.*f %.*f %.*f\">\n",
  611. m_precision, (double) m_paperSize.x / m_IUsPerDecimil * 2.54 / 1000,
  612. m_precision, (double) m_paperSize.y / m_IUsPerDecimil * 2.54 / 1000,
  613. m_precision, origin.x, m_precision, origin.y,
  614. m_precision, m_paperSize.x * m_iuPerDeviceUnit,
  615. m_precision, m_paperSize.y * m_iuPerDeviceUnit);
  616. // Write title
  617. char date_buf[250];
  618. time_t ltime = time( nullptr );
  619. strftime( date_buf, 250, "%Y/%m/%d %H:%M:%S", localtime( &ltime ) );
  620. fprintf( m_outputFile,
  621. "<title>SVG Picture created as %s date %s </title>\n",
  622. TO_UTF8( XmlEsc( wxFileName( m_filename ).GetFullName() ) ), date_buf );
  623. // End of header
  624. fprintf( m_outputFile, " <desc>Picture generated by %s </desc>\n",
  625. TO_UTF8( XmlEsc( m_creator ) ) );
  626. // output the pen and brush color (RVB values in hex) and opacity
  627. double opacity = 1.0; // 0.0 (transparent to 1.0 (solid)
  628. fprintf( m_outputFile,
  629. "<g style=\"fill:#%6.6lX; fill-opacity:%.*f;stroke:#%6.6lX; stroke-opacity:%.*f;\n",
  630. m_brush_rgb_color, m_precision, m_brush_alpha, m_pen_rgb_color, m_precision, opacity );
  631. // output the pen cap and line joint
  632. fputs( "stroke-linecap:round; stroke-linejoin:round;\"\n", m_outputFile );
  633. fputs( " transform=\"translate(0 0) scale(1 1)\">\n", m_outputFile );
  634. return true;
  635. }
  636. bool SVG_PLOTTER::EndPlot()
  637. {
  638. fputs( "</g> \n</svg>\n", m_outputFile );
  639. fclose( m_outputFile );
  640. m_outputFile = nullptr;
  641. return true;
  642. }
  643. void SVG_PLOTTER::Text( const VECTOR2I& aPos,
  644. const COLOR4D& aColor,
  645. const wxString& aText,
  646. const EDA_ANGLE& aOrient,
  647. const VECTOR2I& aSize,
  648. enum GR_TEXT_H_ALIGN_T aH_justify,
  649. enum GR_TEXT_V_ALIGN_T aV_justify,
  650. int aWidth,
  651. bool aItalic,
  652. bool aBold,
  653. bool aMultilineAllowed,
  654. KIFONT::FONT* aFont,
  655. void* aData )
  656. {
  657. setFillMode( FILL_T::NO_FILL );
  658. SetColor( aColor );
  659. SetCurrentLineWidth( aWidth );
  660. VECTOR2I text_pos = aPos;
  661. const char* hjust = "start";
  662. switch( aH_justify )
  663. {
  664. case GR_TEXT_H_ALIGN_CENTER: hjust = "middle"; break;
  665. case GR_TEXT_H_ALIGN_RIGHT: hjust = "end"; break;
  666. case GR_TEXT_H_ALIGN_LEFT: hjust = "start"; break;
  667. }
  668. switch( aV_justify )
  669. {
  670. case GR_TEXT_V_ALIGN_CENTER: text_pos.y += aSize.y / 2; break;
  671. case GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break;
  672. case GR_TEXT_V_ALIGN_BOTTOM: break;
  673. }
  674. VECTOR2I text_size;
  675. // aSize.x or aSize.y is < 0 for mirrored texts.
  676. // The actual text size value is the absolute value
  677. text_size.x = std::abs( GraphicTextWidth( aText, aFont, aSize, aWidth, aBold, aItalic ) );
  678. text_size.y = std::abs( aSize.x * 4/3 ); // Hershey font height to em size conversion
  679. VECTOR2D anchor_pos_dev = userToDeviceCoordinates( aPos );
  680. VECTOR2D text_pos_dev = userToDeviceCoordinates( text_pos );
  681. VECTOR2D sz_dev = userToDeviceSize( text_size );
  682. if( !aOrient.IsZero() )
  683. {
  684. fprintf( m_outputFile,
  685. "<g transform=\"rotate(%f %.*f %.*f)\">\n",
  686. - aOrient.AsDegrees(), m_precision, anchor_pos_dev.x, m_precision, anchor_pos_dev.y );
  687. }
  688. fprintf( m_outputFile, "<text x=\"%.*f\" y=\"%.*f\"\n",
  689. m_precision, text_pos_dev.x, m_precision, text_pos_dev.y );
  690. /// If the text is mirrored, we should also mirror the hidden text to match
  691. if( aSize.x < 0 )
  692. fprintf( m_outputFile, "transform=\"scale(-1 1) translate(%f 0)\"\n", -2 * text_pos_dev.x );
  693. fprintf( m_outputFile,
  694. "textLength=\"%.*f\" font-size=\"%.*f\" lengthAdjust=\"spacingAndGlyphs\"\n"
  695. "text-anchor=\"%s\" opacity=\"0\">%s</text>\n",
  696. m_precision, sz_dev.x, m_precision, sz_dev.y, hjust, TO_UTF8( XmlEsc( aText ) ) );
  697. if( !aOrient.IsZero() )
  698. fputs( "</g>\n", m_outputFile );
  699. fprintf( m_outputFile, "<g class=\"stroked-text\"><desc>%s</desc>\n",
  700. TO_UTF8( XmlEsc( aText ) ) );
  701. PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify, aWidth, aItalic,
  702. aBold, aMultilineAllowed, aFont );
  703. fputs( "</g>", m_outputFile );
  704. }