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.

870 lines
28 KiB

14 years ago
14 years ago
14 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
12 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  1. /**
  2. * @file PDF_plotter.cpp
  3. * @brief Kicad: specialized plotter for PDF files format
  4. */
  5. /*
  6. * This program source code file is part of KiCad, a free EDA CAD application.
  7. *
  8. * Copyright (C) 1992-2012 Lorenzo Marcantonio, l.marcantonio@logossrl.com
  9. * Copyright (C) 1992-2017 KiCad Developers, see AUTHORS.txt for contributors.
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU General Public License
  13. * as published by the Free Software Foundation; either version 2
  14. * of the License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program; if not, you may find one here:
  23. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  24. * or you may search the http://www.gnu.org website for the version 2 license,
  25. * or you may write to the Free Software Foundation, Inc.,
  26. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  27. */
  28. #include <fctsys.h>
  29. #include <pgm_base.h>
  30. #include <trigo.h>
  31. #include <eda_base_frame.h>
  32. #include <base_struct.h>
  33. #include <common.h>
  34. #include <plotter.h>
  35. #include <macros.h>
  36. #include <kicad_string.h>
  37. #include <wx/zstream.h>
  38. #include <wx/mstream.h>
  39. /*
  40. * Open or create the plot file aFullFilename
  41. * return true if success, false if the file cannot be created/opened
  42. *
  43. * Opens the PDF file in binary mode
  44. */
  45. bool PDF_PLOTTER::OpenFile( const wxString& aFullFilename )
  46. {
  47. filename = aFullFilename;
  48. wxASSERT( !outputFile );
  49. // Open the PDF file in binary mode
  50. outputFile = wxFopen( filename, wxT( "wb" ) );
  51. if( outputFile == NULL )
  52. return false ;
  53. return true;
  54. }
  55. void PDF_PLOTTER::SetPageSettings( const PAGE_INFO& aPageSettings )
  56. {
  57. pageInfo = aPageSettings;
  58. }
  59. void PDF_PLOTTER::SetViewport( const wxPoint& aOffset, double aIusPerDecimil,
  60. double aScale, bool aMirror )
  61. {
  62. m_plotMirror = aMirror;
  63. plotOffset = aOffset;
  64. plotScale = aScale;
  65. m_IUsPerDecimil = aIusPerDecimil;
  66. // The CTM is set to 1 user unit per decimil
  67. iuPerDeviceUnit = 1.0 / aIusPerDecimil;
  68. SetDefaultLineWidth( 100 / iuPerDeviceUnit ); // arbitrary default
  69. /* The paper size in this engined is handled page by page
  70. Look in the StartPage function */
  71. }
  72. /**
  73. * Pen width setting for PDF. Since the specs *explicitly* says that a 0
  74. * width is a bad thing to use (since it results in 1 pixel traces), we
  75. * convert such requests to the minimal width (like 1)
  76. * Note pen width = 0 is used in plot polygons to plot filled polygons with
  77. * no outline thickness
  78. * use in this case pen width = 1 does not actally change the polygon
  79. */
  80. void PDF_PLOTTER::SetCurrentLineWidth( int width, void* aData )
  81. {
  82. wxASSERT( workFile );
  83. int pen_width;
  84. if( width > 0 )
  85. pen_width = width;
  86. else if( width == 0 )
  87. pen_width = 1;
  88. else
  89. pen_width = defaultPenWidth;
  90. if( pen_width != currentPenWidth )
  91. fprintf( workFile, "%g w\n",
  92. userToDeviceSize( pen_width ) );
  93. currentPenWidth = pen_width;
  94. }
  95. /**
  96. * PDF supports colors fully. It actually has distinct fill and pen colors,
  97. * but we set both at the same time.
  98. *
  99. * XXX Keeping them divided could result in a minor optimization in
  100. * eeschema filled shapes, but would propagate to all the other plot
  101. * engines. Also arcs are filled as pies but only the arc is stroked so
  102. * it would be difficult to handle anyway.
  103. */
  104. void PDF_PLOTTER::emitSetRGBColor( double r, double g, double b )
  105. {
  106. wxASSERT( workFile );
  107. fprintf( workFile, "%g %g %g rg %g %g %g RG\n",
  108. r, g, b, r, g, b );
  109. }
  110. /**
  111. * PDF supports dashed lines
  112. */
  113. void PDF_PLOTTER::SetDash( int dashed )
  114. {
  115. wxASSERT( workFile );
  116. switch( dashed )
  117. {
  118. case PLOTDASHTYPE_DASH:
  119. fprintf( workFile, "[%d %d] 0 d\n",
  120. (int) GetDashMarkLenIU(), (int) GetDashGapLenIU() );
  121. break;
  122. case PLOTDASHTYPE_DOT:
  123. fprintf( workFile, "[%d %d] 0 d\n",
  124. (int) GetDotMarkLenIU(), (int) GetDashGapLenIU() );
  125. break;
  126. case PLOTDASHTYPE_DASHDOT:
  127. fprintf( workFile, "[%d %d %d %d] 0 d\n",
  128. (int) GetDashMarkLenIU(), (int) GetDashGapLenIU(),
  129. (int) GetDotMarkLenIU(), (int) GetDashGapLenIU() );
  130. break;
  131. default:
  132. fputs( "[] 0 d\n", workFile );
  133. }
  134. }
  135. /**
  136. * Rectangles in PDF. Supported by the native operator
  137. */
  138. void PDF_PLOTTER::Rect( const wxPoint& p1, const wxPoint& p2, FILL_T fill, int width )
  139. {
  140. wxASSERT( workFile );
  141. DPOINT p1_dev = userToDeviceCoordinates( p1 );
  142. DPOINT p2_dev = userToDeviceCoordinates( p2 );
  143. SetCurrentLineWidth( width );
  144. fprintf( workFile, "%g %g %g %g re %c\n", p1_dev.x, p1_dev.y,
  145. p2_dev.x - p1_dev.x, p2_dev.y - p1_dev.y,
  146. fill == NO_FILL ? 'S' : 'B' );
  147. }
  148. /**
  149. * Circle drawing for PDF. They're approximated by curves, but fill is supported
  150. */
  151. void PDF_PLOTTER::Circle( const wxPoint& pos, int diametre, FILL_T aFill, int width )
  152. {
  153. wxASSERT( workFile );
  154. DPOINT pos_dev = userToDeviceCoordinates( pos );
  155. double radius = userToDeviceSize( diametre / 2.0 );
  156. /* OK. Here's a trick. PDF doesn't support circles or circular angles, that's
  157. a fact. You'll have to do with cubic beziers. These *can't* represent
  158. circular arcs (NURBS can, beziers don't). But there is a widely known
  159. approximation which is really good
  160. */
  161. SetCurrentLineWidth( width );
  162. // If diameter is less than width, switch to filled mode
  163. if( aFill == NO_FILL && diametre < width )
  164. {
  165. aFill = FILLED_SHAPE;
  166. SetCurrentLineWidth( 0 );
  167. radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
  168. }
  169. double magic = radius * 0.551784; // You don't want to know where this come from
  170. // This is the convex hull for the bezier approximated circle
  171. fprintf( workFile, "%g %g m "
  172. "%g %g %g %g %g %g c "
  173. "%g %g %g %g %g %g c "
  174. "%g %g %g %g %g %g c "
  175. "%g %g %g %g %g %g c %c\n",
  176. pos_dev.x - radius, pos_dev.y,
  177. pos_dev.x - radius, pos_dev.y + magic,
  178. pos_dev.x - magic, pos_dev.y + radius,
  179. pos_dev.x, pos_dev.y + radius,
  180. pos_dev.x + magic, pos_dev.y + radius,
  181. pos_dev.x + radius, pos_dev.y + magic,
  182. pos_dev.x + radius, pos_dev.y,
  183. pos_dev.x + radius, pos_dev.y - magic,
  184. pos_dev.x + magic, pos_dev.y - radius,
  185. pos_dev.x, pos_dev.y - radius,
  186. pos_dev.x - magic, pos_dev.y - radius,
  187. pos_dev.x - radius, pos_dev.y - magic,
  188. pos_dev.x - radius, pos_dev.y,
  189. aFill == NO_FILL ? 's' : 'b' );
  190. }
  191. /**
  192. * The PDF engine can't directly plot arcs, it uses the base emulation.
  193. * So no filled arcs (not a great loss... )
  194. */
  195. void PDF_PLOTTER::Arc( const wxPoint& centre, double StAngle, double EndAngle, int radius,
  196. FILL_T fill, int width )
  197. {
  198. wxASSERT( workFile );
  199. if( radius <= 0 )
  200. {
  201. Circle( centre, width, FILLED_SHAPE, 0 );
  202. return;
  203. }
  204. /* Arcs are not so easily approximated by beziers (in the general case),
  205. so we approximate them in the old way */
  206. wxPoint start, end;
  207. const int delta = 50; // increment (in 0.1 degrees) to draw circles
  208. if( StAngle > EndAngle )
  209. std::swap( StAngle, EndAngle );
  210. SetCurrentLineWidth( width );
  211. // Usual trig arc plotting routine...
  212. start.x = centre.x + KiROUND( cosdecideg( radius, -StAngle ) );
  213. start.y = centre.y + KiROUND( sindecideg( radius, -StAngle ) );
  214. DPOINT pos_dev = userToDeviceCoordinates( start );
  215. fprintf( workFile, "%g %g m ", pos_dev.x, pos_dev.y );
  216. for( int ii = StAngle + delta; ii < EndAngle; ii += delta )
  217. {
  218. end.x = centre.x + KiROUND( cosdecideg( radius, -ii ) );
  219. end.y = centre.y + KiROUND( sindecideg( radius, -ii ) );
  220. pos_dev = userToDeviceCoordinates( end );
  221. fprintf( workFile, "%g %g l ", pos_dev.x, pos_dev.y );
  222. }
  223. end.x = centre.x + KiROUND( cosdecideg( radius, -EndAngle ) );
  224. end.y = centre.y + KiROUND( sindecideg( radius, -EndAngle ) );
  225. pos_dev = userToDeviceCoordinates( end );
  226. fprintf( workFile, "%g %g l ", pos_dev.x, pos_dev.y );
  227. // The arc is drawn... if not filled we stroke it, otherwise we finish
  228. // closing the pie at the center
  229. if( fill == NO_FILL )
  230. {
  231. fputs( "S\n", workFile );
  232. }
  233. else
  234. {
  235. pos_dev = userToDeviceCoordinates( centre );
  236. fprintf( workFile, "%g %g l b\n", pos_dev.x, pos_dev.y );
  237. }
  238. }
  239. /**
  240. * Polygon plotting for PDF. Everything is supported
  241. */
  242. void PDF_PLOTTER::PlotPoly( const std::vector< wxPoint >& aCornerList,
  243. FILL_T aFill, int aWidth, void * aData )
  244. {
  245. wxASSERT( workFile );
  246. if( aCornerList.size() <= 1 )
  247. return;
  248. SetCurrentLineWidth( aWidth );
  249. DPOINT pos = userToDeviceCoordinates( aCornerList[0] );
  250. fprintf( workFile, "%g %g m\n", pos.x, pos.y );
  251. for( unsigned ii = 1; ii < aCornerList.size(); ii++ )
  252. {
  253. pos = userToDeviceCoordinates( aCornerList[ii] );
  254. fprintf( workFile, "%g %g l\n", pos.x, pos.y );
  255. }
  256. // Close path and stroke(/fill)
  257. fprintf( workFile, "%c\n", aFill == NO_FILL ? 'S' : 'b' );
  258. }
  259. void PDF_PLOTTER::PenTo( const wxPoint& pos, char plume )
  260. {
  261. wxASSERT( workFile );
  262. if( plume == 'Z' )
  263. {
  264. if( penState != 'Z' )
  265. {
  266. fputs( "S\n", workFile );
  267. penState = 'Z';
  268. penLastpos.x = -1;
  269. penLastpos.y = -1;
  270. }
  271. return;
  272. }
  273. if( penState != plume || pos != penLastpos )
  274. {
  275. DPOINT pos_dev = userToDeviceCoordinates( pos );
  276. fprintf( workFile, "%g %g %c\n",
  277. pos_dev.x, pos_dev.y,
  278. ( plume=='D' ) ? 'l' : 'm' );
  279. }
  280. penState = plume;
  281. penLastpos = pos;
  282. }
  283. /**
  284. * PDF images are handles as inline, not XObject streams...
  285. */
  286. void PDF_PLOTTER::PlotImage( const wxImage & aImage, const wxPoint& aPos,
  287. double aScaleFactor )
  288. {
  289. wxASSERT( workFile );
  290. wxSize pix_size( aImage.GetWidth(), aImage.GetHeight() );
  291. // Requested size (in IUs)
  292. DPOINT drawsize( aScaleFactor * pix_size.x,
  293. aScaleFactor * pix_size.y );
  294. // calculate the bitmap start position
  295. wxPoint start( aPos.x - drawsize.x / 2,
  296. aPos.y + drawsize.y / 2);
  297. DPOINT dev_start = userToDeviceCoordinates( start );
  298. /* PDF has an uhm... simplified coordinate system handling. There is
  299. *one* operator to do everything (the PS concat equivalent). At least
  300. they kept the matrix stack to save restore environments. Also images
  301. are always emitted at the origin with a size of 1x1 user units.
  302. What we need to do is:
  303. 1) save the CTM end estabilish the new one
  304. 2) plot the image
  305. 3) restore the CTM
  306. 4) profit
  307. */
  308. fprintf( workFile, "q %g 0 0 %g %g %g cm\n", // Step 1
  309. userToDeviceSize( drawsize.x ),
  310. userToDeviceSize( drawsize.y ),
  311. dev_start.x, dev_start.y );
  312. /* An inline image is a cross between a dictionary and a stream.
  313. A real ugly construct (compared with the elegance of the PDF
  314. format). Also it accepts some 'abbreviations', which is stupid
  315. since the content stream is usually compressed anyway... */
  316. fprintf( workFile,
  317. "BI\n"
  318. " /BPC 8\n"
  319. " /CS %s\n"
  320. " /W %d\n"
  321. " /H %d\n"
  322. "ID\n", colorMode ? "/RGB" : "/G", pix_size.x, pix_size.y );
  323. /* Here comes the stream (in binary!). I *could* have hex or ascii84
  324. encoded it, but who cares? I'll go through zlib anyway */
  325. for( int y = 0; y < pix_size.y; y++ )
  326. {
  327. for( int x = 0; x < pix_size.x; x++ )
  328. {
  329. unsigned char r = aImage.GetRed( x, y ) & 0xFF;
  330. unsigned char g = aImage.GetGreen( x, y ) & 0xFF;
  331. unsigned char b = aImage.GetBlue( x, y ) & 0xFF;
  332. // As usual these days, stdio buffering has to suffeeeeerrrr
  333. if( colorMode )
  334. {
  335. putc( r, workFile );
  336. putc( g, workFile );
  337. putc( b, workFile );
  338. }
  339. else
  340. {
  341. // Grayscale conversion
  342. putc( (r + g + b) / 3, workFile );
  343. }
  344. }
  345. }
  346. fputs( "EI Q\n", workFile ); // Finish step 2 and do step 3
  347. }
  348. /**
  349. * Allocate a new handle in the table of the PDF object. The
  350. * handle must be completed using startPdfObject. It's an in-RAM operation
  351. * only, no output is done.
  352. */
  353. int PDF_PLOTTER::allocPdfObject()
  354. {
  355. xrefTable.push_back( 0 );
  356. return xrefTable.size() - 1;
  357. }
  358. /**
  359. * Open a new PDF object and returns the handle if the parameter is -1.
  360. * Otherwise fill in the xref entry for the passed object
  361. */
  362. int PDF_PLOTTER::startPdfObject(int handle)
  363. {
  364. wxASSERT( outputFile );
  365. wxASSERT( !workFile );
  366. if( handle < 0)
  367. handle = allocPdfObject();
  368. xrefTable[handle] = ftell( outputFile );
  369. fprintf( outputFile, "%d 0 obj\n", handle );
  370. return handle;
  371. }
  372. /**
  373. * Close the current PDF object
  374. */
  375. void PDF_PLOTTER::closePdfObject()
  376. {
  377. wxASSERT( outputFile );
  378. wxASSERT( !workFile );
  379. fputs( "endobj\n", outputFile );
  380. }
  381. /**
  382. * Starts a PDF stream (for the page). Returns the object handle opened
  383. * Pass -1 (default) for a fresh object. Especially from PDF 1.5 streams
  384. * can contain a lot of things, but for the moment we only handle page
  385. * content.
  386. */
  387. int PDF_PLOTTER::startPdfStream(int handle)
  388. {
  389. wxASSERT( outputFile );
  390. wxASSERT( !workFile );
  391. handle = startPdfObject( handle );
  392. // This is guaranteed to be handle+1 but needs to be allocated since
  393. // you could allocate more object during stream preparation
  394. streamLengthHandle = allocPdfObject();
  395. fprintf( outputFile,
  396. "<< /Length %d 0 R /Filter /FlateDecode >>\n" // Length is deferred
  397. "stream\n", handle + 1 );
  398. // Open a temporary file to accumulate the stream
  399. workFilename = filename + wxT(".tmp");
  400. workFile = wxFopen( workFilename, wxT( "w+b" ));
  401. wxASSERT( workFile );
  402. return handle;
  403. }
  404. /**
  405. * Finish the current PDF stream (writes the deferred length, too)
  406. */
  407. void PDF_PLOTTER::closePdfStream()
  408. {
  409. wxASSERT( workFile );
  410. long stream_len = ftell( workFile );
  411. if( stream_len < 0 )
  412. {
  413. wxASSERT( false );
  414. return;
  415. }
  416. // Rewind the file, read in the page stream and DEFLATE it
  417. fseek( workFile, 0, SEEK_SET );
  418. unsigned char *inbuf = new unsigned char[stream_len];
  419. int rc = fread( inbuf, 1, stream_len, workFile );
  420. wxASSERT( rc == stream_len );
  421. (void) rc;
  422. // We are done with the temporary file, junk it
  423. fclose( workFile );
  424. workFile = 0;
  425. ::wxRemoveFile( workFilename );
  426. // NULL means memos owns the memory, but provide a hint on optimum size needed.
  427. wxMemoryOutputStream memos( NULL, std::max( 2000l, stream_len ) ) ;
  428. {
  429. /* Somewhat standard parameters to compress in DEFLATE. The PDF spec is
  430. * misleading, it says it wants a DEFLATE stream but it really want a ZLIB
  431. * stream! (a DEFLATE stream would be generated with -15 instead of 15)
  432. * rc = deflateInit2( &zstrm, Z_BEST_COMPRESSION, Z_DEFLATED, 15,
  433. * 8, Z_DEFAULT_STRATEGY );
  434. */
  435. wxZlibOutputStream zos( memos, wxZ_BEST_COMPRESSION, wxZLIB_ZLIB );
  436. zos.Write( inbuf, stream_len );
  437. delete[] inbuf;
  438. } // flush the zip stream using zos destructor
  439. wxStreamBuffer* sb = memos.GetOutputStreamBuffer();
  440. unsigned out_count = sb->Tell();
  441. fwrite( sb->GetBufferStart(), 1, out_count, outputFile );
  442. fputs( "endstream\n", outputFile );
  443. closePdfObject();
  444. // Writing the deferred length as an indirect object
  445. startPdfObject( streamLengthHandle );
  446. fprintf( outputFile, "%u\n", out_count );
  447. closePdfObject();
  448. }
  449. /**
  450. * Starts a new page in the PDF document
  451. */
  452. void PDF_PLOTTER::StartPage()
  453. {
  454. wxASSERT( outputFile );
  455. wxASSERT( !workFile );
  456. // Compute the paper size in IUs
  457. paperSize = pageInfo.GetSizeMils();
  458. paperSize.x *= 10.0 / iuPerDeviceUnit;
  459. paperSize.y *= 10.0 / iuPerDeviceUnit;
  460. // Open the content stream; the page object will go later
  461. pageStreamHandle = startPdfStream();
  462. /* Now, until ClosePage *everything* must be wrote in workFile, to be
  463. compressed later in closePdfStream */
  464. // Default graphic settings (coordinate system, default color and line style)
  465. fprintf( workFile,
  466. "%g 0 0 %g 0 0 cm 1 J 1 j 0 0 0 rg 0 0 0 RG %g w\n",
  467. 0.0072 * plotScaleAdjX, 0.0072 * plotScaleAdjY,
  468. userToDeviceSize( defaultPenWidth ) );
  469. }
  470. /**
  471. * Close the current page in the PDF document (and emit its compressed stream)
  472. */
  473. void PDF_PLOTTER::ClosePage()
  474. {
  475. wxASSERT( workFile );
  476. // Close the page stream (and compress it)
  477. closePdfStream();
  478. // Emit the page object and put it in the page list for later
  479. pageHandles.push_back( startPdfObject() );
  480. /* Page size is in 1/72 of inch (default user space units)
  481. Works like the bbox in postscript but there is no need for
  482. swapping the sizes, since PDF doesn't require a portrait page.
  483. We use the MediaBox but PDF has lots of other less used boxes
  484. to use */
  485. const double BIGPTsPERMIL = 0.072;
  486. wxSize psPaperSize = pageInfo.GetSizeMils();
  487. fprintf( outputFile,
  488. "<<\n"
  489. "/Type /Page\n"
  490. "/Parent %d 0 R\n"
  491. "/Resources <<\n"
  492. " /ProcSet [/PDF /Text /ImageC /ImageB]\n"
  493. " /Font %d 0 R >>\n"
  494. "/MediaBox [0 0 %d %d]\n"
  495. "/Contents %d 0 R\n"
  496. ">>\n",
  497. pageTreeHandle,
  498. fontResDictHandle,
  499. int( ceil( psPaperSize.x * BIGPTsPERMIL ) ),
  500. int( ceil( psPaperSize.y * BIGPTsPERMIL ) ),
  501. pageStreamHandle );
  502. closePdfObject();
  503. // Mark the page stream as idle
  504. pageStreamHandle = 0;
  505. }
  506. /**
  507. * The PDF engine supports multiple pages; the first one is opened
  508. * 'for free' the following are to be closed and reopened. Between
  509. * each page parameters can be set
  510. */
  511. bool PDF_PLOTTER::StartPlot()
  512. {
  513. wxASSERT( outputFile );
  514. // First things first: the customary null object
  515. xrefTable.clear();
  516. xrefTable.push_back( 0 );
  517. /* The header (that's easy!). The second line is binary junk required
  518. to make the file binary from the beginning (the important thing is
  519. that they must have the bit 7 set) */
  520. fputs( "%PDF-1.5\n%\200\201\202\203\n", outputFile );
  521. /* Allocate an entry for the page tree root, it will go in every page
  522. parent entry */
  523. pageTreeHandle = allocPdfObject();
  524. /* In the same way, the font resource dictionary is used by every page
  525. (it *could* be inherited via the Pages tree */
  526. fontResDictHandle = allocPdfObject();
  527. /* Now, the PDF is read from the end, (more or less)... so we start
  528. with the page stream for page 1. Other more important stuff is written
  529. at the end */
  530. StartPage();
  531. return true;
  532. }
  533. bool PDF_PLOTTER::EndPlot()
  534. {
  535. wxASSERT( outputFile );
  536. // Close the current page (often the only one)
  537. ClosePage();
  538. /* We need to declare the resources we're using (fonts in particular)
  539. The useful standard one is the Helvetica family. Adding external fonts
  540. is *very* involved! */
  541. struct {
  542. const char *psname;
  543. const char *rsname;
  544. int font_handle;
  545. } fontdefs[4] = {
  546. { "/Helvetica", "/KicadFont", 0 },
  547. { "/Helvetica-Oblique", "/KicadFontI", 0 },
  548. { "/Helvetica-Bold", "/KicadFontB", 0 },
  549. { "/Helvetica-BoldOblique", "/KicadFontBI", 0 }
  550. };
  551. /* Declare the font resources. Since they're builtin fonts, no descriptors (yay!)
  552. We'll need metrics anyway to do any aligment (these are in the shared with
  553. the postscript engine) */
  554. for( int i = 0; i < 4; i++ )
  555. {
  556. fontdefs[i].font_handle = startPdfObject();
  557. fprintf( outputFile,
  558. "<< /BaseFont %s\n"
  559. " /Type /Font\n"
  560. " /Subtype /Type1\n"
  561. /* Adobe is so Mac-based that the nearest thing to Latin1 is
  562. the Windows ANSI encoding! */
  563. " /Encoding /WinAnsiEncoding\n"
  564. ">>\n",
  565. fontdefs[i].psname );
  566. closePdfObject();
  567. }
  568. // Named font dictionary (was allocated, now we emit it)
  569. startPdfObject( fontResDictHandle );
  570. fputs( "<<\n", outputFile );
  571. for( int i = 0; i < 4; i++ )
  572. {
  573. fprintf( outputFile, " %s %d 0 R\n",
  574. fontdefs[i].rsname, fontdefs[i].font_handle );
  575. }
  576. fputs( ">>\n", outputFile );
  577. closePdfObject();
  578. /* The page tree: it's a B-tree but luckily we only have few pages!
  579. So we use just an array... The handle was allocated at the beginning,
  580. now we instantiate the corresponding object */
  581. startPdfObject( pageTreeHandle );
  582. fputs( "<<\n"
  583. "/Type /Pages\n"
  584. "/Kids [\n", outputFile );
  585. for( unsigned i = 0; i < pageHandles.size(); i++ )
  586. fprintf( outputFile, "%d 0 R\n", pageHandles[i] );
  587. fprintf( outputFile,
  588. "]\n"
  589. "/Count %ld\n"
  590. ">>\n", (long) pageHandles.size() );
  591. closePdfObject();
  592. // The info dictionary
  593. int infoDictHandle = startPdfObject();
  594. char date_buf[250];
  595. time_t ltime = time( NULL );
  596. strftime( date_buf, 250, "D:%Y%m%d%H%M%S",
  597. localtime( &ltime ) );
  598. if( title.IsEmpty() )
  599. {
  600. // Windows uses '\' and other platforms ue '/' as sepatator
  601. title = filename.AfterLast('\\');
  602. title = title.AfterLast('/');
  603. }
  604. fprintf( outputFile,
  605. "<<\n"
  606. "/Producer (KiCAD PDF)\n"
  607. "/CreationDate (%s)\n"
  608. "/Creator (%s)\n"
  609. "/Title (%s)\n"
  610. "/Trapped false\n",
  611. date_buf,
  612. TO_UTF8( creator ),
  613. TO_UTF8( title ) );
  614. fputs( ">>\n", outputFile );
  615. closePdfObject();
  616. // The catalog, at last
  617. int catalogHandle = startPdfObject();
  618. fprintf( outputFile,
  619. "<<\n"
  620. "/Type /Catalog\n"
  621. "/Pages %d 0 R\n"
  622. "/Version /1.5\n"
  623. "/PageMode /UseNone\n"
  624. "/PageLayout /SinglePage\n"
  625. ">>\n", pageTreeHandle );
  626. closePdfObject();
  627. /* Emit the xref table (format is crucial to the byte, each entry must
  628. be 20 bytes long, and object zero must be done in that way). Also
  629. the offset must be kept along for the trailer */
  630. long xref_start = ftell( outputFile );
  631. fprintf( outputFile,
  632. "xref\n"
  633. "0 %ld\n"
  634. "0000000000 65535 f \n", (long) xrefTable.size() );
  635. for( unsigned i = 1; i < xrefTable.size(); i++ )
  636. {
  637. fprintf( outputFile, "%010ld 00000 n \n", xrefTable[i] );
  638. }
  639. // Done the xref, go for the trailer
  640. fprintf( outputFile,
  641. "trailer\n"
  642. "<< /Size %lu /Root %d 0 R /Info %d 0 R >>\n"
  643. "startxref\n"
  644. "%ld\n" // The offset we saved before
  645. "%%%%EOF\n",
  646. (unsigned long) xrefTable.size(), catalogHandle, infoDictHandle, xref_start );
  647. fclose( outputFile );
  648. outputFile = NULL;
  649. return true;
  650. }
  651. void PDF_PLOTTER::Text( const wxPoint& aPos,
  652. const COLOR4D aColor,
  653. const wxString& aText,
  654. double aOrient,
  655. const wxSize& aSize,
  656. enum EDA_TEXT_HJUSTIFY_T aH_justify,
  657. enum EDA_TEXT_VJUSTIFY_T aV_justify,
  658. int aWidth,
  659. bool aItalic,
  660. bool aBold,
  661. bool aMultilineAllowed,
  662. void* aData )
  663. {
  664. // PDF files do not like 0 sized texts which create broken files.
  665. if( aSize.x == 0 || aSize.y == 0 )
  666. return;
  667. // Fix me: see how to use PDF text mode for multiline texts
  668. if( aMultilineAllowed && !aText.Contains( wxT( "\n" ) ) )
  669. aMultilineAllowed = false; // the text has only one line.
  670. // Emit native PDF text (if requested)
  671. // Currently: is not supported, because only our stroke font is alloxed: disable it
  672. // However, shadowed texts (searchable texts) works reasonably well because
  673. // pixel accurate precision is not requested, so we add searchable texts
  674. // behind our stroked font texts
  675. bool use_native_font = false;
  676. // render_mode 0 shows the text, render_mode 3 is invisible
  677. int render_mode = use_native_font ? 0 : 3;
  678. const char *fontname = aItalic ? (aBold ? "/KicadFontBI" : "/KicadFontI")
  679. : (aBold ? "/KicadFontB" : "/KicadFont");
  680. // Compute the copious tranformation parameters of the Curent Transform Matrix
  681. double ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f;
  682. double wideningFactor, heightFactor;
  683. computeTextParameters( aPos, aText, aOrient, aSize, m_plotMirror, aH_justify,
  684. aV_justify, aWidth, aItalic, aBold,
  685. &wideningFactor, &ctm_a, &ctm_b, &ctm_c,
  686. &ctm_d, &ctm_e, &ctm_f, &heightFactor );
  687. SetColor( aColor );
  688. SetCurrentLineWidth( aWidth, aData );
  689. /* We use the full CTM instead of the text matrix because the same
  690. coordinate system will be used for the overlining. Also the %f
  691. for the trig part of the matrix to avoid %g going in exponential
  692. format (which is not supported)
  693. render_mode 0 shows the text, render_mode 3 is invisible */
  694. fprintf( workFile, "q %f %f %f %f %g %g cm BT %s %g Tf %d Tr %g Tz ",
  695. ctm_a, ctm_b, ctm_c, ctm_d, ctm_e, ctm_f,
  696. fontname, heightFactor, render_mode,
  697. wideningFactor * 100 );
  698. // The text must be escaped correctly
  699. fputsPostscriptString( workFile, aText );
  700. fputs( " Tj ET\n", workFile );
  701. // We are in text coordinates, plot the overbars, if we're not doing phantom text
  702. if( use_native_font )
  703. {
  704. std::vector<int> pos_pairs;
  705. postscriptOverlinePositions( aText, aSize.x, aItalic, aBold, &pos_pairs );
  706. int overbar_y = KiROUND( aSize.y * 1.1 );
  707. for( unsigned i = 0; i < pos_pairs.size(); i += 2)
  708. {
  709. /* This is a nontrivial situation: we are *not* in the user
  710. coordinate system, so the userToDeviceCoordinates function
  711. can't be used! Strange as it may seem, the userToDeviceSize
  712. is the right function to use here... */
  713. DPOINT dev_from = userToDeviceSize( wxSize( pos_pairs[i], overbar_y ) );
  714. DPOINT dev_to = userToDeviceSize( wxSize( pos_pairs[i + 1], overbar_y ) );
  715. fprintf( workFile, "%g %g m %g %g l ",
  716. dev_from.x, dev_from.y, dev_to.x, dev_to.y );
  717. }
  718. }
  719. // Stroke and restore the CTM
  720. fputs( "S Q\n", workFile );
  721. // Plot the stroked text (if requested)
  722. if( !use_native_font )
  723. {
  724. PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify,
  725. aWidth, aItalic, aBold, aMultilineAllowed );
  726. }
  727. }