KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pcb_io_kicad_sexpr.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2012 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25#include <wx/dir.h>
26#include <wx/ffile.h>
27#include <wx/log.h>
28#include <wx/msgdlg.h>
29#include <wx/mstream.h>
30
31#include <board.h>
33#include <callback_gal.h>
34#include <confirm.h>
35#include <convert_basic_shapes_to_polygon.h> // for enum RECT_CHAMFER_POSITIONS definition
36#include <fmt/core.h>
37#include <font/fontconfig.h>
38#include <footprint.h>
40#include <kiface_base.h>
41#include <layer_range.h>
42#include <macros.h>
43#include <pad.h>
44#include <pcb_dimension.h>
45#include <pcb_generator.h>
46#include <pcb_group.h>
49#include <pcb_point.h>
50#include <pcb_reference_image.h>
51#include <pcb_shape.h>
52#include <pcb_table.h>
53#include <pcb_tablecell.h>
54#include <pcb_target.h>
55#include <pcb_text.h>
56#include <pcb_textbox.h>
57#include <pcb_track.h>
58#include <pcbnew_settings.h>
59#include <pgm_base.h>
60#include <progress_reporter.h>
61#include <reporter.h>
62#include <string_utils.h>
63#include <trace_helpers.h>
65#include <zone.h>
66
67#include <build_version.h>
68#include <filter_reader.h>
69#include <ctl_flags.h>
70
71
72using namespace PCB_KEYS_T;
73
74
75FP_CACHE_ENTRY::FP_CACHE_ENTRY( FOOTPRINT* aFootprint, const WX_FILENAME& aFileName ) :
76 m_filename( aFileName ),
77 m_footprint( aFootprint )
78{ }
79
80
81FP_CACHE::FP_CACHE( PCB_IO_KICAD_SEXPR* aOwner, const wxString& aLibraryPath )
82{
83 m_owner = aOwner;
84 m_lib_raw_path = aLibraryPath;
85 m_lib_path.SetPath( aLibraryPath );
87 m_cache_dirty = true;
88}
89
90
91void FP_CACHE::Save( FOOTPRINT* aFootprintFilter )
92{
94
95 if( !m_lib_path.DirExists() && !m_lib_path.Mkdir() )
96 {
97 THROW_IO_ERROR( wxString::Format( _( "Cannot create footprint library '%s'." ),
99 }
100
101 if( !m_lib_path.IsDirWritable() )
102 {
103 THROW_IO_ERROR( wxString::Format( _( "Footprint library '%s' is read only." ),
104 m_lib_raw_path ) );
105 }
106
107 for( auto it = m_footprints.begin(); it != m_footprints.end(); ++it )
108 {
109 FP_CACHE_ENTRY* fpCacheEntry = it->second;
110 std::unique_ptr<FOOTPRINT>& footprint = fpCacheEntry->GetFootprint();
111
112 if( aFootprintFilter && footprint.get() != aFootprintFilter )
113 continue;
114
115 // If we've requested to embed the fonts in the footprint, do so. Otherwise, clear the
116 // embedded fonts from the footprint. Embedded fonts will be used if available.
117 if( footprint->GetAreFontsEmbedded() )
118 footprint->EmbedFonts();
119 else
120 footprint->GetEmbeddedFiles()->ClearEmbeddedFonts();
121
122 WX_FILENAME fn = fpCacheEntry->GetFileName();
123 wxString fileName = fn.GetFullPath();
124
125 // Allow file output stream to go out of scope to close the file stream before
126 // renaming the file.
127 {
128 wxLogTrace( traceKicadPcbPlugin, wxT( "Writing library file '%s'." ),
129 fileName );
130
131 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( fileName );
132
133 m_owner->SetOutputFormatter( &formatter );
134 m_owner->Format( footprint.get() );
135 }
136
138 }
139
140 if( m_lib_path.IsFileReadable() && m_lib_path.GetModificationTime().IsValid() )
141 m_cache_timestamp += m_lib_path.GetModificationTime().GetValue().GetValue();
142
143 // If we've saved the full cache, we clear the dirty flag.
144 if( !aFootprintFilter )
145 m_cache_dirty = false;
146}
147
148
150{
151 m_cache_dirty = false;
153
154 wxDir dir( m_lib_raw_path );
155
156 if( !dir.IsOpened() )
157 {
158 wxString msg = wxString::Format( _( "Footprint library '%s' not found." ),
160 THROW_IO_ERROR( msg );
161 }
162
163 wxString fullName;
164 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadFootprintFileExtension );
165
166 // wxFileName construction is egregiously slow. Construct it once and just swap out
167 // the filename thereafter.
168 WX_FILENAME fn( m_lib_raw_path, wxT( "dummyName" ) );
169
170 if( dir.GetFirst( &fullName, fileSpec ) )
171 {
172 wxString cacheError;
173
174 do
175 {
176 fn.SetFullName( fullName );
177
178 // Queue I/O errors so only files that fail to parse don't get loaded.
179 try
180 {
181 FILE_LINE_READER reader( fn.GetFullPath() );
182 PCB_IO_KICAD_SEXPR_PARSER parser( &reader, nullptr, nullptr );
183
184 FOOTPRINT* footprint = dynamic_cast<FOOTPRINT*>( parser.Parse() );
185 wxString fpName = fn.GetName();
186
187 if( !footprint )
188 THROW_IO_ERROR( wxEmptyString ); // caught locally, just below...
189
190 footprint->SetFPID( LIB_ID( wxEmptyString, fpName ) );
191 m_footprints.insert( fpName, new FP_CACHE_ENTRY( footprint, fn ) );
192 }
193 catch( const IO_ERROR& ioe )
194 {
195 if( !cacheError.IsEmpty() )
196 cacheError += wxT( "\n\n" );
197
198 cacheError += wxString::Format( _( "Unable to read file '%s'" ) + '\n',
199 fn.GetFullPath() );
200 cacheError += ioe.What();
201 }
202 } while( dir.GetNext( &fullName ) );
203
205
206 if( !cacheError.IsEmpty() )
207 THROW_IO_ERROR( cacheError );
208 }
209}
210
211
212void FP_CACHE::Remove( const wxString& aFootprintName )
213{
214 auto it = m_footprints.find( aFootprintName );
215
216 if( it == m_footprints.end() )
217 {
218 wxString msg = wxString::Format( _( "Library '%s' has no footprint '%s'." ),
220 aFootprintName );
221 THROW_IO_ERROR( msg );
222 }
223
224 // Remove the footprint from the cache and delete the footprint file from the library.
225 wxString fullPath = it->second->GetFileName().GetFullPath();
226 m_footprints.erase( aFootprintName );
227 wxRemoveFile( fullPath );
228}
229
230
231bool FP_CACHE::IsPath( const wxString& aPath ) const
232{
233 return aPath == m_lib_raw_path;
234}
235
236
237void FP_CACHE::SetPath( const wxString& aPath )
238{
239 m_lib_raw_path = aPath;
240 m_lib_path.SetPath( aPath );
241
242
243 for( const auto& footprint : GetFootprints() )
244 footprint.second->SetFilePath( aPath );
245}
246
247
249{
251
252 return m_cache_dirty;
253}
254
255
256long long FP_CACHE::GetTimestamp( const wxString& aLibPath )
257{
258 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadFootprintFileExtension );
259
260 return TimestampDir( aLibPath, fileSpec );
261}
262
263
264bool PCB_IO_KICAD_SEXPR::CanReadBoard( const wxString& aFileName ) const
265{
266 if( !PCB_IO::CanReadBoard( aFileName ) )
267 return false;
268
269 try
270 {
271 FILE_LINE_READER reader( aFileName );
272 PCB_IO_KICAD_SEXPR_PARSER parser( &reader, nullptr, m_queryUserCallback );
273
274 return parser.IsValidBoardHeader();
275 }
276 catch( const IO_ERROR& )
277 {
278 }
279
280 return false;
281}
282
283
284void PCB_IO_KICAD_SEXPR::SaveBoard( const wxString& aFileName, BOARD* aBoard,
285 const std::map<std::string, UTF8>* aProperties )
286{
287 wxString sanityResult = aBoard->GroupsSanityCheck();
288
289 if( sanityResult != wxEmptyString && m_queryUserCallback )
290 {
292 _( "Internal Group Data Error" ), wxICON_ERROR,
293 wxString::Format( _( "Please report this bug. Error validating group "
294 "structure: %s\n\nSave anyway?" ), sanityResult ),
295 _( "Save Anyway" ) ) )
296 {
297 return;
298 }
299 }
300
301 init( aProperties );
302
303 m_board = aBoard; // after init()
304
305 // If the user wants fonts embedded, make sure that they are added to the board. Otherwise,
306 // remove any fonts that were previously embedded.
307 if( m_board->GetAreFontsEmbedded() )
308 m_board->EmbedFonts();
309 else
310 m_board->GetEmbeddedFiles()->ClearEmbeddedFonts();
311
312 // Prepare net mapping that assures that net codes saved in a file are consecutive integers
313 m_mapping->SetBoard( aBoard );
314
315 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( aFileName );
316
317 m_out = &formatter; // no ownership
318
319 m_out->Print( "(kicad_pcb (version %d) (generator \"pcbnew\") (generator_version %s)",
321 m_out->Quotew( GetMajorMinorVersion() ).c_str() );
322
323 Format( aBoard );
324
325 m_out->Print( ")" );
326 m_out->Finish();
327
328 m_out = nullptr;
329}
330
331
332BOARD_ITEM* PCB_IO_KICAD_SEXPR::Parse( const wxString& aClipboardSourceInput )
333{
334 std::string input = TO_UTF8( aClipboardSourceInput );
335
336 STRING_LINE_READER reader( input, wxT( "clipboard" ) );
337 PCB_IO_KICAD_SEXPR_PARSER parser( &reader, nullptr, m_queryUserCallback );
338
339 try
340 {
341 return parser.Parse();
342 }
343 catch( const PARSE_ERROR& parse_error )
344 {
345 if( parser.IsTooRecent() )
346 throw FUTURE_FORMAT_ERROR( parse_error, parser.GetRequiredVersion() );
347 else
348 throw;
349 }
350}
351
352
353void PCB_IO_KICAD_SEXPR::Format( const BOARD_ITEM* aItem ) const
354{
355 switch( aItem->Type() )
356 {
357 case PCB_T:
358 format( static_cast<const BOARD*>( aItem ) );
359 break;
360
362 case PCB_DIM_CENTER_T:
363 case PCB_DIM_RADIAL_T:
365 case PCB_DIM_LEADER_T:
366 format( static_cast<const PCB_DIMENSION_BASE*>( aItem ) );
367 break;
368
369 case PCB_SHAPE_T:
370 format( static_cast<const PCB_SHAPE*>( aItem ) );
371 break;
372
374 format( static_cast<const PCB_REFERENCE_IMAGE*>( aItem ) );
375 break;
376
377 case PCB_POINT_T:
378 format( static_cast<const PCB_POINT*>( aItem ) );
379 break;
380
381 case PCB_TARGET_T:
382 format( static_cast<const PCB_TARGET*>( aItem ) );
383 break;
384
385 case PCB_FOOTPRINT_T:
386 format( static_cast<const FOOTPRINT*>( aItem ) );
387 break;
388
389 case PCB_PAD_T:
390 format( static_cast<const PAD*>( aItem ) );
391 break;
392
393 case PCB_FIELD_T:
394 // Handled in the footprint formatter when properties are formatted
395 break;
396
397 case PCB_TEXT_T:
398 format( static_cast<const PCB_TEXT*>( aItem ) );
399 break;
400
401 case PCB_TEXTBOX_T:
402 format( static_cast<const PCB_TEXTBOX*>( aItem ) );
403 break;
404
405 case PCB_TABLE_T:
406 format( static_cast<const PCB_TABLE*>( aItem ) );
407 break;
408
409 case PCB_GROUP_T:
410 format( static_cast<const PCB_GROUP*>( aItem ) );
411 break;
412
413 case PCB_GENERATOR_T:
414 format( static_cast<const PCB_GENERATOR*>( aItem ) );
415 break;
416
417 case PCB_TRACE_T:
418 case PCB_ARC_T:
419 case PCB_VIA_T:
420 format( static_cast<const PCB_TRACK*>( aItem ) );
421 break;
422
423 case PCB_ZONE_T:
424 format( static_cast<const ZONE*>( aItem ) );
425 break;
426
427 default:
428 wxFAIL_MSG( wxT( "Cannot format item " ) + aItem->GetClass() );
429 }
430}
431
432
433std::string formatInternalUnits( int aValue )
434{
436}
437
438
439std::string formatInternalUnits( const VECTOR2I& aCoord )
440{
442}
443
444
445std::string formatInternalUnits( const VECTOR2I& aCoord, const FOOTPRINT* aParentFP )
446{
447 if( aParentFP )
448 {
449 VECTOR2I coord = aCoord - aParentFP->GetPosition();
450 RotatePoint( coord, -aParentFP->GetOrientation() );
451 return formatInternalUnits( coord );
452 }
453
454 return formatInternalUnits( aCoord );
455}
456
457
458void PCB_IO_KICAD_SEXPR::formatLayer( PCB_LAYER_ID aLayer, bool aIsKnockout ) const
459{
460 m_out->Print( "(layer %s %s)",
461 m_out->Quotew( LSET::Name( aLayer ) ).c_str(),
462 aIsKnockout ? "knockout" : "" );
463}
464
465
467 const FOOTPRINT* aParentFP ) const
468{
469 m_out->Print( "(pts" );
470
471 for( int ii = 0; ii < outline.PointCount(); ++ii )
472 {
473 int ind = outline.ArcIndex( ii );
474
475 if( ind < 0 )
476 {
477 m_out->Print( "(xy %s)",
478 formatInternalUnits( outline.CPoint( ii ), aParentFP ).c_str() );
479 }
480 else
481 {
482 const SHAPE_ARC& arc = outline.Arc( ind );
483 m_out->Print( "(arc (start %s) (mid %s) (end %s))",
484 formatInternalUnits( arc.GetP0(), aParentFP ).c_str(),
485 formatInternalUnits( arc.GetArcMid(), aParentFP ).c_str(),
486 formatInternalUnits( arc.GetP1(), aParentFP ).c_str() );
487
488 do
489 {
490 ++ii;
491 } while( ii < outline.PointCount() && outline.ArcIndex( ii ) == ind );
492
493 --ii;
494 }
495 }
496
497 m_out->Print( ")" );
498}
499
500
502{
503 wxString resolvedText( aText->GetShownText( true ) );
504 std::vector<std::unique_ptr<KIFONT::GLYPH>>* cache = aText->GetRenderCache( aText->GetFont(),
505 resolvedText );
506
507 m_out->Print( "(render_cache %s %s",
508 m_out->Quotew( resolvedText ).c_str(),
509 EDA_UNIT_UTILS::FormatAngle( aText->GetDrawRotation() ).c_str() );
510
512
513 CALLBACK_GAL callback_gal( empty_opts,
514 // Polygon callback
515 [&]( const SHAPE_LINE_CHAIN& aPoly )
516 {
517 m_out->Print( "(polygon" );
518 formatPolyPts( aPoly );
519 m_out->Print( ")" );
520 } );
521
522 callback_gal.SetLineWidth( aText->GetTextThickness() );
523 callback_gal.DrawGlyphs( *cache );
524
525 m_out->Print( ")" );
526}
527
528
529void PCB_IO_KICAD_SEXPR::formatSetup( const BOARD* aBoard ) const
530{
531 // Setup
532 m_out->Print( "(setup" );
533
534 // Save the board physical stackup structure
535 const BOARD_STACKUP& stackup = aBoard->GetDesignSettings().GetStackupDescriptor();
536
537 if( aBoard->GetDesignSettings().m_HasStackup )
538 stackup.FormatBoardStackup( m_out, aBoard );
539
540 BOARD_DESIGN_SETTINGS& dsnSettings = aBoard->GetDesignSettings();
541
542 m_out->Print( "(pad_to_mask_clearance %s)",
543 formatInternalUnits( dsnSettings.m_SolderMaskExpansion ).c_str() );
544
545 if( dsnSettings.m_SolderMaskMinWidth )
546 {
547 m_out->Print( "(solder_mask_min_width %s)",
548 formatInternalUnits( dsnSettings.m_SolderMaskMinWidth ).c_str() );
549 }
550
551 if( dsnSettings.m_SolderPasteMargin != 0 )
552 {
553 m_out->Print( "(pad_to_paste_clearance %s)",
554 formatInternalUnits( dsnSettings.m_SolderPasteMargin ).c_str() );
555 }
556
557 if( dsnSettings.m_SolderPasteMarginRatio != 0 )
558 {
559 m_out->Print( "(pad_to_paste_clearance_ratio %s)",
560 FormatDouble2Str( dsnSettings.m_SolderPasteMarginRatio ).c_str() );
561 }
562
563 KICAD_FORMAT::FormatBool( m_out, "allow_soldermask_bridges_in_footprints",
564 dsnSettings.m_AllowSoldermaskBridgesInFPs );
565
566 m_out->Print( 0, " (tenting " );
567 KICAD_FORMAT::FormatBool( m_out, "front", dsnSettings.m_TentViasFront );
568 KICAD_FORMAT::FormatBool( m_out, "back", dsnSettings.m_TentViasBack );
569 m_out->Print( 0, ")" );
570
571 m_out->Print( 0, " (covering " );
572 KICAD_FORMAT::FormatBool( m_out, "front", dsnSettings.m_CoverViasFront );
573 KICAD_FORMAT::FormatBool( m_out, "back", dsnSettings.m_CoverViasBack );
574 m_out->Print( 0, ")" );
575
576 m_out->Print( 0, " (plugging " );
577 KICAD_FORMAT::FormatBool( m_out, "front", dsnSettings.m_PlugViasFront );
578 KICAD_FORMAT::FormatBool( m_out, "back", dsnSettings.m_PlugViasBack );
579 m_out->Print( 0, ")" );
580
581 KICAD_FORMAT::FormatBool( m_out, "capping", dsnSettings.m_CapVias );
582
583 KICAD_FORMAT::FormatBool( m_out, "filling", dsnSettings.m_FillVias );
584
585 if( !dsnSettings.GetDefaultZoneSettings().m_LayerProperties.empty() )
586 {
587 m_out->Print( 0, " (zone_defaults" );
588
589 for( const auto& [layer, properties] : dsnSettings.GetDefaultZoneSettings().m_LayerProperties )
590 format( properties, 0, layer );
591
592 m_out->Print( 0, ")\n" );
593 }
594
595 VECTOR2I origin = dsnSettings.GetAuxOrigin();
596
597 if( origin != VECTOR2I( 0, 0 ) )
598 {
599 m_out->Print( "(aux_axis_origin %s %s)",
600 formatInternalUnits( origin.x ).c_str(),
601 formatInternalUnits( origin.y ).c_str() );
602 }
603
604 origin = dsnSettings.GetGridOrigin();
605
606 if( origin != VECTOR2I( 0, 0 ) )
607 {
608 m_out->Print( "(grid_origin %s %s)",
609 formatInternalUnits( origin.x ).c_str(),
610 formatInternalUnits( origin.y ).c_str() );
611 }
612
613 aBoard->GetPlotOptions().Format( m_out );
614
615 m_out->Print( ")" );
616}
617
618
619void PCB_IO_KICAD_SEXPR::formatGeneral( const BOARD* aBoard ) const
620{
621 const BOARD_DESIGN_SETTINGS& dsnSettings = aBoard->GetDesignSettings();
622
623 m_out->Print( "(general" );
624
625 m_out->Print( "(thickness %s)",
626 formatInternalUnits( dsnSettings.GetBoardThickness() ).c_str() );
627
628 KICAD_FORMAT::FormatBool( m_out, "legacy_teardrops", aBoard->LegacyTeardrops() );
629
630 m_out->Print( ")" );
631
632 aBoard->GetPageSettings().Format( m_out );
633 aBoard->GetTitleBlock().Format( m_out );
634}
635
636
638{
639 m_out->Print( "(layers" );
640
641 // Save only the used copper layers from front to back.
642
643 for( PCB_LAYER_ID layer : aBoard->GetEnabledLayers().CuStack() )
644 {
645 m_out->Print( "(%d %s %s %s)",
646 layer,
647 m_out->Quotew( LSET::Name( layer ) ).c_str(),
648 LAYER::ShowType( aBoard->GetLayerType( layer ) ),
649 LSET::Name( layer ) == m_board->GetLayerName( layer )
650 ? ""
651 : m_out->Quotew( m_board->GetLayerName( layer ) ).c_str() );
652
653 }
654
655 // Save used non-copper layers in the order they are defined.
656 LSEQ seq = aBoard->GetEnabledLayers().TechAndUserUIOrder();
657
658 for( PCB_LAYER_ID layer : seq )
659 {
660 bool print_type = false;
661
662 // User layers (layer id >= User_1) have a qualifier
663 // default is "user", but other qualifiers exist
664 if( layer >= User_1 )
665 {
666 if( IsCopperLayer( layer ) )
667 print_type = true;
668
669 if( aBoard->GetLayerType( layer ) == LT_FRONT
670 || aBoard->GetLayerType( layer ) == LT_BACK )
671 print_type = true;
672 }
673
674 m_out->Print( "(%d %s %s %s)",
675 layer,
676 m_out->Quotew( LSET::Name( layer ) ).c_str(),
677 print_type
678 ? LAYER::ShowType( aBoard->GetLayerType( layer ) )
679 : "user",
680 m_board->GetLayerName( layer ) == LSET::Name( layer )
681 ? ""
682 : m_out->Quotew( m_board->GetLayerName( layer ) ).c_str() );
683 }
684
685 m_out->Print( ")" );
686}
687
688
690{
691 for( NETINFO_ITEM* net : *m_mapping )
692 {
693 if( net == nullptr ) // Skip not actually existing nets (orphan nets)
694 continue;
695
696 m_out->Print( "(net %d %s)",
697 m_mapping->Translate( net->GetNetCode() ),
698 m_out->Quotew( net->GetNetname() ).c_str() );
699 }
700}
701
702
704{
705 for( const std::pair<const wxString, wxString>& prop : aBoard->GetProperties() )
706 {
707 m_out->Print( "(property %s %s)",
708 m_out->Quotew( prop.first ).c_str(),
709 m_out->Quotew( prop.second ).c_str() );
710 }
711}
712
713
714void PCB_IO_KICAD_SEXPR::formatHeader( const BOARD* aBoard ) const
715{
716 formatGeneral( aBoard );
717
718 // Layers list.
719 formatBoardLayers( aBoard );
720
721 // Setup
722 formatSetup( aBoard );
723
724 // Properties
725 formatProperties( aBoard );
726
727 // Save net codes and names
728 formatNetInformation( aBoard );
729}
730
731
733{
734 static const TEARDROP_PARAMETERS defaults;
735
736 return tdParams.m_Enabled == defaults.m_Enabled
737 && tdParams.m_BestLengthRatio == defaults.m_BestLengthRatio
738 && tdParams.m_TdMaxLen == defaults.m_TdMaxLen
739 && tdParams.m_BestWidthRatio == defaults.m_BestWidthRatio
740 && tdParams.m_TdMaxWidth == defaults.m_TdMaxWidth
741 && tdParams.m_CurvedEdges == defaults.m_CurvedEdges
743 && tdParams.m_AllowUseTwoTracks == defaults.m_AllowUseTwoTracks
744 && tdParams.m_TdOnPadsInZones == defaults.m_TdOnPadsInZones;
745}
746
747
749{
750 m_out->Print( "(teardrops (best_length_ratio %s) (max_length %s) (best_width_ratio %s) "
751 "(max_width %s)",
752 FormatDouble2Str( tdParams.m_BestLengthRatio ).c_str(),
753 formatInternalUnits( tdParams.m_TdMaxLen ).c_str(),
754 FormatDouble2Str( tdParams.m_BestWidthRatio ).c_str(),
755 formatInternalUnits( tdParams.m_TdMaxWidth ).c_str() );
756
757 KICAD_FORMAT::FormatBool( m_out, "curved_edges", tdParams.m_CurvedEdges );
758
759 m_out->Print( "(filter_ratio %s)",
760 FormatDouble2Str( tdParams.m_WidthtoSizeFilterRatio ).c_str() );
761
762 KICAD_FORMAT::FormatBool( m_out, "enabled", tdParams.m_Enabled );
763 KICAD_FORMAT::FormatBool( m_out, "allow_two_segments", tdParams.m_AllowUseTwoTracks );
764 KICAD_FORMAT::FormatBool( m_out, "prefer_zone_connections", !tdParams.m_TdOnPadsInZones );
765 m_out->Print( ")" );
766}
767
768
769void PCB_IO_KICAD_SEXPR::format( const BOARD* aBoard ) const
770{
771 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_footprints( aBoard->Footprints().begin(),
772 aBoard->Footprints().end() );
773 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_drawings( aBoard->Drawings().begin(),
774 aBoard->Drawings().end() );
775 std::set<PCB_TRACK*, PCB_TRACK::cmp_tracks> sorted_tracks( aBoard->Tracks().begin(),
776 aBoard->Tracks().end() );
777 std::set<PCB_POINT*, BOARD_ITEM::ptr_cmp> sorted_points( aBoard->Points().begin(),
778 aBoard->Points().end() );
779 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_zones( aBoard->Zones().begin(),
780 aBoard->Zones().end() );
781 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_groups( aBoard->Groups().begin(),
782 aBoard->Groups().end() );
783 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_generators( aBoard->Generators().begin(),
784 aBoard->Generators().end() );
785 formatHeader( aBoard );
786
787 // Save the footprints.
788 for( BOARD_ITEM* footprint : sorted_footprints )
789 Format( footprint );
790
791 // Save the graphical items on the board (not owned by a footprint)
792 for( BOARD_ITEM* item : sorted_drawings )
793 Format( item );
794
795 // Save the points
796 for( PCB_POINT* point : sorted_points )
797 Format( point );
798
799 // Do not save PCB_MARKERs, they can be regenerated easily.
800
801 // Save the tracks and vias.
802 for( PCB_TRACK* track : sorted_tracks )
803 Format( track );
804
805 // Save the polygon (which are the newer technology) zones.
806 for( auto zone : sorted_zones )
807 Format( zone );
808
809 // Save the groups
810 for( BOARD_ITEM* group : sorted_groups )
811 Format( group );
812
813 // Save the generators
814 for( BOARD_ITEM* gen : sorted_generators )
815 Format( gen );
816
817 // Save any embedded files
818 // Consolidate the embedded models in footprints into a single map
819 // to avoid duplicating the same model in the board file.
820 EMBEDDED_FILES files_to_write;
821
822 for( auto& file : aBoard->GetEmbeddedFiles()->EmbeddedFileMap() )
823 files_to_write.AddFile( file.second );
824
825 for( BOARD_ITEM* item : sorted_footprints )
826 {
827 FOOTPRINT* fp = static_cast<FOOTPRINT*>( item );
828
829 for( auto& file : fp->GetEmbeddedFiles()->EmbeddedFileMap() )
830 files_to_write.AddFile( file.second );
831 }
832
833 m_out->Print( "(embedded_fonts %s)",
834 aBoard->GetEmbeddedFiles()->GetAreFontsEmbedded() ? "yes" : "no" );
835
836 if( !files_to_write.IsEmpty() )
837 files_to_write.WriteEmbeddedFiles( *m_out, ( m_ctl & CTL_FOR_BOARD ) );
838
839 // Remove the files so that they are not freed in the DTOR
840 files_to_write.ClearEmbeddedFiles( false );
841}
842
843
844void PCB_IO_KICAD_SEXPR::format( const PCB_DIMENSION_BASE* aDimension ) const
845{
846 const PCB_DIM_ALIGNED* aligned = dynamic_cast<const PCB_DIM_ALIGNED*>( aDimension );
847 const PCB_DIM_ORTHOGONAL* ortho = dynamic_cast<const PCB_DIM_ORTHOGONAL*>( aDimension );
848 const PCB_DIM_CENTER* center = dynamic_cast<const PCB_DIM_CENTER*>( aDimension );
849 const PCB_DIM_RADIAL* radial = dynamic_cast<const PCB_DIM_RADIAL*>( aDimension );
850 const PCB_DIM_LEADER* leader = dynamic_cast<const PCB_DIM_LEADER*>( aDimension );
851
852 m_out->Print( "(dimension" );
853
854 if( ortho ) // must be tested before aligned, because ortho is derived from aligned
855 // and aligned is not null
856 m_out->Print( "(type orthogonal)" );
857 else if( aligned )
858 m_out->Print( "(type aligned)" );
859 else if( leader )
860 m_out->Print( "(type leader)" );
861 else if( center )
862 m_out->Print( "(type center)" );
863 else if( radial )
864 m_out->Print( "(type radial)" );
865 else
866 wxFAIL_MSG( wxT( "Cannot format unknown dimension type!" ) );
867
868 if( aDimension->IsLocked() )
869 KICAD_FORMAT::FormatBool( m_out, "locked", aDimension->IsLocked() );
870
871 formatLayer( aDimension->GetLayer() );
872
873 KICAD_FORMAT::FormatUuid( m_out, aDimension->m_Uuid );
874
875 m_out->Print( "(pts (xy %s %s) (xy %s %s))",
876 formatInternalUnits( aDimension->GetStart().x ).c_str(),
877 formatInternalUnits( aDimension->GetStart().y ).c_str(),
878 formatInternalUnits( aDimension->GetEnd().x ).c_str(),
879 formatInternalUnits( aDimension->GetEnd().y ).c_str() );
880
881 if( aligned )
882 m_out->Print( "(height %s)", formatInternalUnits( aligned->GetHeight() ).c_str() );
883
884 if( radial )
885 {
886 m_out->Print( "(leader_length %s)",
887 formatInternalUnits( radial->GetLeaderLength() ).c_str() );
888 }
889
890 if( ortho )
891 m_out->Print( "(orientation %d)", static_cast<int>( ortho->GetOrientation() ) );
892
893 if( !center )
894 {
895 m_out->Print( "(format (prefix %s) (suffix %s) (units %d) (units_format %d) (precision %d)",
896 m_out->Quotew( aDimension->GetPrefix() ).c_str(),
897 m_out->Quotew( aDimension->GetSuffix() ).c_str(),
898 static_cast<int>( aDimension->GetUnitsMode() ),
899 static_cast<int>( aDimension->GetUnitsFormat() ),
900 static_cast<int>( aDimension->GetPrecision() ) );
901
902 if( aDimension->GetOverrideTextEnabled() )
903 {
904 m_out->Print( "(override_value %s)",
905 m_out->Quotew( aDimension->GetOverrideText() ).c_str() );
906 }
907
908 if( aDimension->GetSuppressZeroes() )
909 KICAD_FORMAT::FormatBool( m_out, "suppress_zeroes", true );
910
911 m_out->Print( ")" );
912 }
913
914 m_out->Print( "(style (thickness %s) (arrow_length %s) (text_position_mode %d)",
915 formatInternalUnits( aDimension->GetLineThickness() ).c_str(),
916 formatInternalUnits( aDimension->GetArrowLength() ).c_str(),
917 static_cast<int>( aDimension->GetTextPositionMode() ) );
918
919 if( ortho || aligned )
920 {
921 switch( aDimension->GetArrowDirection() )
922 {
924 m_out->Print( "(arrow_direction outward)" );
925 break;
927 m_out->Print( "(arrow_direction inward)" );
928 break;
929 // No default, handle all cases
930 }
931 }
932
933 if( aligned )
934 {
935 m_out->Print( "(extension_height %s)",
936 formatInternalUnits( aligned->GetExtensionHeight() ).c_str() );
937 }
938
939 if( leader )
940 m_out->Print( "(text_frame %d)", static_cast<int>( leader->GetTextBorder() ) );
941
942 m_out->Print( "(extension_offset %s)",
943 formatInternalUnits( aDimension->GetExtensionOffset() ).c_str() );
944
945 if( aDimension->GetKeepTextAligned() )
946 KICAD_FORMAT::FormatBool( m_out, "keep_text_aligned", true );
947
948 m_out->Print( ")" );
949
950 // Write dimension text after all other options to be sure the
951 // text options are known when reading the file
952 if( !center )
953 format( static_cast<const PCB_TEXT*>( aDimension ) );
954
955 m_out->Print( ")" );
956}
957
958
959void PCB_IO_KICAD_SEXPR::format( const PCB_SHAPE* aShape ) const
960{
961 FOOTPRINT* parentFP = aShape->GetParentFootprint();
962 std::string prefix = parentFP ? "fp" : "gr";
963
964 switch( aShape->GetShape() )
965 {
966 case SHAPE_T::SEGMENT:
967 m_out->Print( "(%s_line (start %s) (end %s)",
968 prefix.c_str(),
969 formatInternalUnits( aShape->GetStart(), parentFP ).c_str(),
970 formatInternalUnits( aShape->GetEnd(), parentFP ).c_str() );
971 break;
972
974 m_out->Print( "(%s_rect (start %s) (end %s)",
975 prefix.c_str(),
976 formatInternalUnits( aShape->GetStart(), parentFP ).c_str(),
977 formatInternalUnits( aShape->GetEnd(), parentFP ).c_str() );
978
979 if( aShape->GetCornerRadius() > 0 )
980 m_out->Print( " (radius %s)", formatInternalUnits( aShape->GetCornerRadius() ).c_str() );
981 break;
982
983 case SHAPE_T::CIRCLE:
984 m_out->Print( "(%s_circle (center %s) (end %s)",
985 prefix.c_str(),
986 formatInternalUnits( aShape->GetStart(), parentFP ).c_str(),
987 formatInternalUnits( aShape->GetEnd(), parentFP ).c_str() );
988 break;
989
990 case SHAPE_T::ARC:
991 m_out->Print( "(%s_arc (start %s) (mid %s) (end %s)",
992 prefix.c_str(),
993 formatInternalUnits( aShape->GetStart(), parentFP ).c_str(),
994 formatInternalUnits( aShape->GetArcMid(), parentFP ).c_str(),
995 formatInternalUnits( aShape->GetEnd(), parentFP ).c_str() );
996 break;
997
998 case SHAPE_T::POLY:
999 if( aShape->IsPolyShapeValid() )
1000 {
1001 const SHAPE_POLY_SET& poly = aShape->GetPolyShape();
1002 const SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
1003
1004 m_out->Print( "(%s_poly", prefix.c_str() );
1005 formatPolyPts( outline, parentFP );
1006 }
1007 else
1008 {
1009 return;
1010 }
1011
1012 break;
1013
1014 case SHAPE_T::BEZIER:
1015 m_out->Print( "(%s_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
1016 prefix.c_str(),
1017 formatInternalUnits( aShape->GetStart(), parentFP ).c_str(),
1018 formatInternalUnits( aShape->GetBezierC1(), parentFP ).c_str(),
1019 formatInternalUnits( aShape->GetBezierC2(), parentFP ).c_str(),
1020 formatInternalUnits( aShape->GetEnd(), parentFP ).c_str() );
1021 break;
1022
1023 default:
1025 return;
1026 };
1027
1028 aShape->GetStroke().Format( m_out, pcbIUScale );
1029
1030 // The filled flag represents if a solid fill is present on circles, rectangles and polygons
1031 if( ( aShape->GetShape() == SHAPE_T::POLY )
1032 || ( aShape->GetShape() == SHAPE_T::RECTANGLE )
1033 || ( aShape->GetShape() == SHAPE_T::CIRCLE ) )
1034 {
1035 switch( aShape->GetFillMode() )
1036 {
1037 case FILL_T::HATCH:
1038 m_out->Print( "(fill hatch)" );
1039 break;
1040
1042 m_out->Print( "(fill reverse_hatch)" );
1043 break;
1044
1046 m_out->Print( "(fill cross_hatch)" );
1047 break;
1048
1050 KICAD_FORMAT::FormatBool( m_out, "fill", true );
1051 break;
1052
1053 default:
1054 KICAD_FORMAT::FormatBool( m_out, "fill", false );
1055 break;
1056 }
1057 }
1058
1059 if( aShape->IsLocked() )
1060 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1061
1062 if( aShape->GetLayerSet().count() > 1 )
1063 formatLayers( aShape->GetLayerSet(), false /* enumerate layers */ );
1064 else
1065 formatLayer( aShape->GetLayer() );
1066
1067 if( aShape->HasSolderMask()
1068 && aShape->GetLocalSolderMaskMargin().has_value()
1069 && IsExternalCopperLayer( aShape->GetLayer() ) )
1070 {
1071 m_out->Print( "(solder_mask_margin %s)",
1072 formatInternalUnits( aShape->GetLocalSolderMaskMargin().value() ).c_str() );
1073 }
1074
1075 if( aShape->GetNetCode() > 0 )
1076 m_out->Print( "(net %d)", m_mapping->Translate( aShape->GetNetCode() ) );
1077
1079 m_out->Print( ")" );
1080}
1081
1082
1084{
1085 wxCHECK_RET( aBitmap != nullptr && m_out != nullptr, "" );
1086
1087 const REFERENCE_IMAGE& refImage = aBitmap->GetReferenceImage();
1088
1089 const wxImage* image = refImage.GetImage().GetImageData();
1090
1091 wxCHECK_RET( image != nullptr, "wxImage* is NULL" );
1092
1093 m_out->Print( "(image (at %s %s)",
1094 formatInternalUnits( aBitmap->GetPosition().x ).c_str(),
1095 formatInternalUnits( aBitmap->GetPosition().y ).c_str() );
1096
1097 formatLayer( aBitmap->GetLayer() );
1098
1099 if( refImage.GetImageScale() != 1.0 )
1100 m_out->Print( "%s", fmt::format("(scale {:g})", refImage.GetImageScale()).c_str() );
1101
1102 if( aBitmap->IsLocked() )
1103 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1104
1105 wxMemoryOutputStream ostream;
1106 refImage.GetImage().SaveImageData( ostream );
1107
1108 KICAD_FORMAT::FormatStreamData( *m_out, *ostream.GetOutputStreamBuffer() );
1109
1111 m_out->Print( ")" ); // Closes image token.
1112}
1113
1114
1115void PCB_IO_KICAD_SEXPR::format( const PCB_POINT* aPoint ) const
1116{
1117 m_out->Print( "(point (at %s) (size %s)",
1118 formatInternalUnits( aPoint->GetPosition() ).c_str(),
1119 formatInternalUnits( aPoint->GetSize() ).c_str()
1120 );
1121
1122 formatLayer( aPoint->GetLayer() );
1123
1125 m_out->Print( ")" );
1126}
1127
1128
1129void PCB_IO_KICAD_SEXPR::format( const PCB_TARGET* aTarget ) const
1130{
1131 m_out->Print( "(target %s (at %s) (size %s)",
1132 ( aTarget->GetShape() ) ? "x" : "plus",
1133 formatInternalUnits( aTarget->GetPosition() ).c_str(),
1134 formatInternalUnits( aTarget->GetSize() ).c_str() );
1135
1136 if( aTarget->GetWidth() != 0 )
1137 m_out->Print( "(width %s)", formatInternalUnits( aTarget->GetWidth() ).c_str() );
1138
1139 formatLayer( aTarget->GetLayer() );
1141 m_out->Print( ")" );
1142}
1143
1144
1145void PCB_IO_KICAD_SEXPR::format( const FOOTPRINT* aFootprint ) const
1146{
1147 if( !( m_ctl & CTL_OMIT_INITIAL_COMMENTS ) )
1148 {
1149 const wxArrayString* initial_comments = aFootprint->GetInitialComments();
1150
1151 if( initial_comments )
1152 {
1153 for( unsigned i = 0; i < initial_comments->GetCount(); ++i )
1154 m_out->Print( "%s\n", TO_UTF8( (*initial_comments)[i] ) );
1155 }
1156 }
1157
1158 if( m_ctl & CTL_OMIT_LIBNAME )
1159 {
1160 m_out->Print( "(footprint %s",
1161 m_out->Quotes( aFootprint->GetFPID().GetLibItemName() ).c_str() );
1162 }
1163 else
1164 {
1165 m_out->Print( "(footprint %s",
1166 m_out->Quotes( aFootprint->GetFPID().Format() ).c_str() );
1167 }
1168
1170 {
1171 m_out->Print( "(version %d) (generator \"pcbnew\") (generator_version %s)",
1173 m_out->Quotew( GetMajorMinorVersion() ).c_str() );
1174 }
1175
1176 if( aFootprint->IsLocked() )
1177 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1178
1179 if( aFootprint->IsPlaced() )
1180 KICAD_FORMAT::FormatBool( m_out, "placed", true );
1181
1182 formatLayer( aFootprint->GetLayer() );
1183
1184 if( !( m_ctl & CTL_OMIT_UUIDS ) )
1185 KICAD_FORMAT::FormatUuid( m_out, aFootprint->m_Uuid );
1186
1187 if( !( m_ctl & CTL_OMIT_AT ) )
1188 {
1189 m_out->Print( "(at %s %s)",
1190 formatInternalUnits( aFootprint->GetPosition() ).c_str(),
1191 aFootprint->GetOrientation().IsZero()
1192 ? ""
1193 : EDA_UNIT_UTILS::FormatAngle( aFootprint->GetOrientation() ).c_str() );
1194 }
1195
1196 if( !aFootprint->GetLibDescription().IsEmpty() )
1197 m_out->Print( "(descr %s)", m_out->Quotew( aFootprint->GetLibDescription() ).c_str() );
1198
1199 if( !aFootprint->GetKeywords().IsEmpty() )
1200 m_out->Print( "(tags %s)", m_out->Quotew( aFootprint->GetKeywords() ).c_str() );
1201
1202 for( const PCB_FIELD* field : aFootprint->GetFields() )
1203 {
1204 m_out->Print( "(property %s %s",
1205 m_out->Quotew( field->GetCanonicalName() ).c_str(),
1206 m_out->Quotew( field->GetText() ).c_str() );
1207
1208 format( field );
1209
1210 m_out->Print( ")" );
1211 }
1212
1213 if( const COMPONENT_CLASS* compClass = aFootprint->GetStaticComponentClass() )
1214 {
1215 if( !compClass->IsEmpty() )
1216 {
1217 m_out->Print( "(component_classes" );
1218
1219 for( const COMPONENT_CLASS* constituent : compClass->GetConstituentClasses() )
1220 m_out->Print( "(class %s)", m_out->Quotew( constituent->GetName() ).c_str() );
1221
1222 m_out->Print( ")" );
1223 }
1224 }
1225
1226 if( !aFootprint->GetFilters().empty() )
1227 {
1228 m_out->Print( "(property ki_fp_filters %s)",
1229 m_out->Quotew( aFootprint->GetFilters() ).c_str() );
1230 }
1231
1232 if( !( m_ctl & CTL_OMIT_PATH ) && !aFootprint->GetPath().empty() )
1233 m_out->Print( "(path %s)", m_out->Quotew( aFootprint->GetPath().AsString() ).c_str() );
1234
1235 if( !aFootprint->GetSheetname().empty() )
1236 m_out->Print( "(sheetname %s)", m_out->Quotew( aFootprint->GetSheetname() ).c_str() );
1237
1238 if( !aFootprint->GetSheetfile().empty() )
1239 m_out->Print( "(sheetfile %s)", m_out->Quotew( aFootprint->GetSheetfile() ).c_str() );
1240
1241 if( aFootprint->GetLocalSolderMaskMargin().has_value() )
1242 {
1243 m_out->Print( "(solder_mask_margin %s)",
1244 formatInternalUnits( aFootprint->GetLocalSolderMaskMargin().value() ).c_str() );
1245 }
1246
1247 if( aFootprint->GetLocalSolderPasteMargin().has_value() )
1248 {
1249 m_out->Print( "(solder_paste_margin %s)",
1250 formatInternalUnits( aFootprint->GetLocalSolderPasteMargin().value() ).c_str() );
1251 }
1252
1253 if( aFootprint->GetLocalSolderPasteMarginRatio().has_value() )
1254 {
1255 m_out->Print( "(solder_paste_margin_ratio %s)",
1256 FormatDouble2Str( aFootprint->GetLocalSolderPasteMarginRatio().value() ).c_str() );
1257 }
1258
1259 if( aFootprint->GetLocalClearance().has_value() )
1260 {
1261 m_out->Print( "(clearance %s)",
1262 formatInternalUnits( aFootprint->GetLocalClearance().value() ).c_str() );
1263 }
1264
1266 {
1267 m_out->Print( "(zone_connect %d)",
1268 static_cast<int>( aFootprint->GetLocalZoneConnection() ) );
1269 }
1270
1271 // Attributes
1272 if( aFootprint->GetAttributes()
1273 || aFootprint->AllowMissingCourtyard()
1274 || aFootprint->AllowSolderMaskBridges() )
1275 {
1276 m_out->Print( "(attr" );
1277
1278 if( aFootprint->GetAttributes() & FP_SMD )
1279 m_out->Print( " smd" );
1280
1281 if( aFootprint->GetAttributes() & FP_THROUGH_HOLE )
1282 m_out->Print( " through_hole" );
1283
1284 if( aFootprint->GetAttributes() & FP_BOARD_ONLY )
1285 m_out->Print( " board_only" );
1286
1287 if( aFootprint->GetAttributes() & FP_EXCLUDE_FROM_POS_FILES )
1288 m_out->Print( " exclude_from_pos_files" );
1289
1290 if( aFootprint->GetAttributes() & FP_EXCLUDE_FROM_BOM )
1291 m_out->Print( " exclude_from_bom" );
1292
1293 if( aFootprint->AllowMissingCourtyard() )
1294 m_out->Print( " allow_missing_courtyard" );
1295
1296 if( aFootprint->GetAttributes() & FP_DNP )
1297 m_out->Print( " dnp" );
1298
1299 if( aFootprint->AllowSolderMaskBridges() )
1300 m_out->Print( " allow_soldermask_bridges" );
1301
1302 m_out->Print( ")" );
1303 }
1304
1305 // Expand inner layers is the default stackup mode
1307 {
1308 m_out->Print( "(stackup" );
1309
1310 const LSET& fpLset = aFootprint->GetStackupLayers();
1311 for( PCB_LAYER_ID layer : fpLset.Seq() )
1312 {
1313 wxString canonicalName( LSET::Name( layer ) );
1314 m_out->Print( "(layer %s)", m_out->Quotew( canonicalName ).c_str() );
1315 }
1316
1317 m_out->Print( ")" );
1318 }
1319
1320 if( aFootprint->GetPrivateLayers().any() )
1321 {
1322 m_out->Print( "(private_layers" );
1323
1324 for( PCB_LAYER_ID layer : aFootprint->GetPrivateLayers().Seq() )
1325 {
1326 wxString canonicalName( LSET::Name( layer ) );
1327 m_out->Print( " %s", m_out->Quotew( canonicalName ).c_str() );
1328 }
1329
1330 m_out->Print( ")" );
1331 }
1332
1333 if( aFootprint->IsNetTie() )
1334 {
1335 m_out->Print( "(net_tie_pad_groups" );
1336
1337 for( const wxString& group : aFootprint->GetNetTiePadGroups() )
1338 m_out->Print( " %s", m_out->Quotew( group ).c_str() );
1339
1340 m_out->Print( ")" );
1341 }
1342
1343 KICAD_FORMAT::FormatBool( m_out, "duplicate_pad_numbers_are_jumpers",
1344 aFootprint->GetDuplicatePadNumbersAreJumpers() );
1345
1346 const std::vector<std::set<wxString>>& jumperGroups = aFootprint->JumperPadGroups();
1347
1348 if( !jumperGroups.empty() )
1349 {
1350 m_out->Print( "(jumper_pad_groups" );
1351
1352 for( const std::set<wxString>& group : jumperGroups )
1353 {
1354 m_out->Print( "(" );
1355
1356 for( const wxString& padName : group )
1357 m_out->Print( "%s ", m_out->Quotew( padName ).c_str() );
1358
1359 m_out->Print( ")" );
1360 }
1361
1362 m_out->Print( ")" );
1363 }
1364
1365 Format( (BOARD_ITEM*) &aFootprint->Reference() );
1366 Format( (BOARD_ITEM*) &aFootprint->Value() );
1367
1368 std::set<PAD*, FOOTPRINT::cmp_pads> sorted_pads( aFootprint->Pads().begin(),
1369 aFootprint->Pads().end() );
1370 std::set<BOARD_ITEM*, FOOTPRINT::cmp_drawings> sorted_drawings(
1371 aFootprint->GraphicalItems().begin(),
1372 aFootprint->GraphicalItems().end() );
1373 std::set<PCB_POINT*, FOOTPRINT::ptr_cmp> sorted_points(
1374 aFootprint->Points().begin(),
1375 aFootprint->Points().end() );
1376 std::set<ZONE*, FOOTPRINT::cmp_zones> sorted_zones( aFootprint->Zones().begin(),
1377 aFootprint->Zones().end() );
1378 std::set<BOARD_ITEM*, PCB_GROUP::ptr_cmp> sorted_groups( aFootprint->Groups().begin(),
1379 aFootprint->Groups().end() );
1380
1381 // Save drawing elements.
1382
1383 for( BOARD_ITEM* gr : sorted_drawings )
1384 Format( gr );
1385
1386 for( PCB_POINT* point : sorted_points )
1387 Format( point );
1388
1389 // Save pads.
1390 for( PAD* pad : sorted_pads )
1391 Format( pad );
1392
1393 // Save zones.
1394 for( BOARD_ITEM* zone : sorted_zones )
1395 Format( zone );
1396
1397 // Save groups.
1398 for( BOARD_ITEM* group : sorted_groups )
1399 Format( group );
1400
1401 KICAD_FORMAT::FormatBool( m_out, "embedded_fonts",
1402 aFootprint->GetEmbeddedFiles()->GetAreFontsEmbedded() );
1403
1404 if( !aFootprint->GetEmbeddedFiles()->IsEmpty() )
1405 aFootprint->WriteEmbeddedFiles( *m_out, !( m_ctl & CTL_FOR_BOARD ) );
1406
1407 // Save 3D info.
1408 auto bs3D = aFootprint->Models().begin();
1409 auto es3D = aFootprint->Models().end();
1410
1411 while( bs3D != es3D )
1412 {
1413 if( !bs3D->m_Filename.IsEmpty() )
1414 {
1415 m_out->Print( "(model %s", m_out->Quotew( bs3D->m_Filename ).c_str() );
1416
1417 if( !bs3D->m_Show )
1418 KICAD_FORMAT::FormatBool( m_out, "hide", !bs3D->m_Show );
1419
1420 if( bs3D->m_Opacity != 1.0 )
1421 m_out->Print( "%s", fmt::format("(opacity {:.4f})", bs3D->m_Opacity).c_str() );
1422
1423 m_out->Print( "(offset (xyz %s %s %s))",
1424 FormatDouble2Str( bs3D->m_Offset.x ).c_str(),
1425 FormatDouble2Str( bs3D->m_Offset.y ).c_str(),
1426 FormatDouble2Str( bs3D->m_Offset.z ).c_str() );
1427
1428 m_out->Print( "(scale (xyz %s %s %s))",
1429 FormatDouble2Str( bs3D->m_Scale.x ).c_str(),
1430 FormatDouble2Str( bs3D->m_Scale.y ).c_str(),
1431 FormatDouble2Str( bs3D->m_Scale.z ).c_str() );
1432
1433 m_out->Print( "(rotate (xyz %s %s %s))",
1434 FormatDouble2Str( bs3D->m_Rotation.x ).c_str(),
1435 FormatDouble2Str( bs3D->m_Rotation.y ).c_str(),
1436 FormatDouble2Str( bs3D->m_Rotation.z ).c_str() );
1437
1438 m_out->Print( ")" );
1439 }
1440
1441 ++bs3D;
1442 }
1443
1444 m_out->Print( ")" );
1445}
1446
1447
1448void PCB_IO_KICAD_SEXPR::formatLayers( LSET aLayerMask, bool aEnumerateLayers, bool aIsZone ) const
1449{
1450 static const LSET cu_all( LSET::AllCuMask() );
1451 static const LSET fr_bk( { B_Cu, F_Cu } );
1452 static const LSET adhes( { B_Adhes, F_Adhes } );
1453 static const LSET paste( { B_Paste, F_Paste } );
1454 static const LSET silks( { B_SilkS, F_SilkS } );
1455 static const LSET mask( { B_Mask, F_Mask } );
1456 static const LSET crt_yd( { B_CrtYd, F_CrtYd } );
1457 static const LSET fab( { B_Fab, F_Fab } );
1458
1459 LSET cu_board_mask = LSET::AllCuMask( m_board ? m_board->GetCopperLayerCount() : MAX_CU_LAYERS );
1460
1461 std::string output;
1462
1463 if( !aEnumerateLayers )
1464 {
1465 // If all copper layers present on the board are enabled, then output the wildcard
1466 if( ( aLayerMask & cu_board_mask ) == cu_board_mask )
1467 {
1468 output += ' ' + m_out->Quotew( "*.Cu" );
1469
1470 // Clear all copper bits because pads might have internal layers that aren't part of the
1471 // board enabled, and we don't want to output those in the layers listing if we already
1472 // output the wildcard.
1473 aLayerMask &= ~cu_all;
1474 }
1475 else if( ( aLayerMask & cu_board_mask ) == fr_bk )
1476 {
1477 if( aIsZone )
1478 output += ' ' + m_out->Quotew( "F&B.Cu" );
1479 else
1480 output += ' ' + m_out->Quotew( "*.Cu" );
1481
1482 aLayerMask &= ~fr_bk;
1483 }
1484
1485 if( ( aLayerMask & adhes ) == adhes )
1486 {
1487 output += ' ' + m_out->Quotew( "*.Adhes" );
1488 aLayerMask &= ~adhes;
1489 }
1490
1491 if( ( aLayerMask & paste ) == paste )
1492 {
1493 output += ' ' + m_out->Quotew( "*.Paste" );
1494 aLayerMask &= ~paste;
1495 }
1496
1497 if( ( aLayerMask & silks ) == silks )
1498 {
1499 output += ' ' + m_out->Quotew( "*.SilkS" );
1500 aLayerMask &= ~silks;
1501 }
1502
1503 if( ( aLayerMask & mask ) == mask )
1504 {
1505 output += ' ' + m_out->Quotew( "*.Mask" );
1506 aLayerMask &= ~mask;
1507 }
1508
1509 if( ( aLayerMask & crt_yd ) == crt_yd )
1510 {
1511 output += ' ' + m_out->Quotew( "*.CrtYd" );
1512 aLayerMask &= ~crt_yd;
1513 }
1514
1515 if( ( aLayerMask & fab ) == fab )
1516 {
1517 output += ' ' + m_out->Quotew( "*.Fab" );
1518 aLayerMask &= ~fab;
1519 }
1520 }
1521
1522 // output any individual layers not handled in wildcard combos above
1523 for( int layer = 0; layer < PCB_LAYER_ID_COUNT; ++layer )
1524 {
1525 if( aLayerMask[layer] )
1526 output += ' ' + m_out->Quotew( LSET::Name( PCB_LAYER_ID( layer ) ) );
1527 }
1528
1529 m_out->Print( "(layers %s)", output.c_str() );
1530}
1531
1532
1533void PCB_IO_KICAD_SEXPR::format( const PAD* aPad ) const
1534{
1535 const BOARD* board = aPad->GetBoard();
1536
1537 auto shapeName =
1538 [&]( PCB_LAYER_ID aLayer )
1539 {
1540 switch( aPad->GetShape( aLayer ) )
1541 {
1542 case PAD_SHAPE::CIRCLE: return "circle";
1543 case PAD_SHAPE::RECTANGLE: return "rect";
1544 case PAD_SHAPE::OVAL: return "oval";
1545 case PAD_SHAPE::TRAPEZOID: return "trapezoid";
1547 case PAD_SHAPE::ROUNDRECT: return "roundrect";
1548 case PAD_SHAPE::CUSTOM: return "custom";
1549
1550 default:
1551 THROW_IO_ERROR( wxString::Format( _( "unknown pad type: %d"),
1552 aPad->GetShape( aLayer ) ) );
1553 }
1554 };
1555
1556 const char* type;
1557
1558 switch( aPad->GetAttribute() )
1559 {
1560 case PAD_ATTRIB::PTH: type = "thru_hole"; break;
1561 case PAD_ATTRIB::SMD: type = "smd"; break;
1562 case PAD_ATTRIB::CONN: type = "connect"; break;
1563 case PAD_ATTRIB::NPTH: type = "np_thru_hole"; break;
1564
1565 default:
1566 THROW_IO_ERROR( wxString::Format( wxT( "unknown pad attribute: %d" ),
1567 aPad->GetAttribute() ) );
1568 }
1569
1570 const char* property = nullptr;
1571
1572 switch( aPad->GetProperty() )
1573 {
1574 case PAD_PROP::NONE: break; // could be "none"
1575 case PAD_PROP::BGA: property = "pad_prop_bga"; break;
1576 case PAD_PROP::FIDUCIAL_GLBL: property = "pad_prop_fiducial_glob"; break;
1577 case PAD_PROP::FIDUCIAL_LOCAL: property = "pad_prop_fiducial_loc"; break;
1578 case PAD_PROP::TESTPOINT: property = "pad_prop_testpoint"; break;
1579 case PAD_PROP::HEATSINK: property = "pad_prop_heatsink"; break;
1580 case PAD_PROP::CASTELLATED: property = "pad_prop_castellated"; break;
1581 case PAD_PROP::MECHANICAL: property = "pad_prop_mechanical"; break;
1582 case PAD_PROP::PRESSFIT: property = "pad_prop_pressfit"; break;
1583
1584 default:
1585 THROW_IO_ERROR( wxString::Format( wxT( "unknown pad property: %d" ),
1586 aPad->GetProperty() ) );
1587 }
1588
1589 m_out->Print( "(pad %s %s %s",
1590 m_out->Quotew( aPad->GetNumber() ).c_str(),
1591 type,
1592 shapeName( PADSTACK::ALL_LAYERS ) );
1593
1594 m_out->Print( "(at %s %s)",
1595 formatInternalUnits( aPad->GetFPRelativePosition() ).c_str(),
1596 aPad->GetOrientation().IsZero()
1597 ? ""
1598 : EDA_UNIT_UTILS::FormatAngle( aPad->GetOrientation() ).c_str() );
1599
1600 m_out->Print( "(size %s)", formatInternalUnits( aPad->GetSize( PADSTACK::ALL_LAYERS ) ).c_str() );
1601
1602 if( aPad->GetDelta( PADSTACK::ALL_LAYERS ).x != 0
1603 || aPad->GetDelta( PADSTACK::ALL_LAYERS ).y != 0 )
1604 {
1605 m_out->Print( "(rect_delta %s)",
1607 }
1608
1609 VECTOR2I sz = aPad->GetDrillSize();
1610 VECTOR2I shapeoffset = aPad->GetOffset( PADSTACK::ALL_LAYERS );
1611
1612 if( (sz.x > 0) || (sz.y > 0) ||
1613 (shapeoffset.x != 0) || (shapeoffset.y != 0) )
1614 {
1615 m_out->Print( "(drill" );
1616
1617 if( aPad->GetDrillShape() == PAD_DRILL_SHAPE::OBLONG )
1618 m_out->Print( " oval" );
1619
1620 if( sz.x > 0 )
1621 m_out->Print( " %s", formatInternalUnits( sz.x ).c_str() );
1622
1623 if( sz.y > 0 && sz.x != sz.y )
1624 m_out->Print( " %s", formatInternalUnits( sz.y ).c_str() );
1625
1626 // NOTE: Shape offest is a property of the copper shape, not of the drill, but this was put
1627 // in the file format under the drill section. So, it is left here to minimize file format
1628 // changes, but note that the other padstack layers (if present) will have an offset stored
1629 // separately.
1630 if( shapeoffset.x != 0 || shapeoffset.y != 0 )
1631 {
1632 m_out->Print( "(offset %s)",
1634 }
1635
1636 m_out->Print( ")" );
1637 }
1638
1639 // Add pad property, if exists.
1640 if( property )
1641 m_out->Print( "(property %s)", property );
1642
1643 formatLayers( aPad->GetLayerSet(), false /* enumerate layers */ );
1644
1645 if( aPad->GetAttribute() == PAD_ATTRIB::PTH )
1646 {
1647 KICAD_FORMAT::FormatBool( m_out, "remove_unused_layers", aPad->GetRemoveUnconnected() );
1648
1649 if( aPad->GetRemoveUnconnected() )
1650 {
1651 KICAD_FORMAT::FormatBool( m_out, "keep_end_layers", aPad->GetKeepTopBottom() );
1652
1653 if( board ) // Will be nullptr in footprint library
1654 {
1655 m_out->Print( "(zone_layer_connections" );
1656
1657 for( PCB_LAYER_ID layer : board->GetEnabledLayers().CuStack() )
1658 {
1659 if( aPad->GetZoneLayerOverride( layer ) == ZLO_FORCE_FLASHED )
1660 m_out->Print( " %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
1661 }
1662
1663 m_out->Print( ")" );
1664 }
1665 }
1666 }
1667
1668 auto formatCornerProperties =
1669 [&]( PCB_LAYER_ID aLayer )
1670 {
1671 // Output the radius ratio for rounded and chamfered rect pads
1672 if( aPad->GetShape( aLayer ) == PAD_SHAPE::ROUNDRECT
1673 || aPad->GetShape( aLayer ) == PAD_SHAPE::CHAMFERED_RECT)
1674 {
1675 m_out->Print( "(roundrect_rratio %s)",
1676 FormatDouble2Str( aPad->GetRoundRectRadiusRatio( aLayer ) ).c_str() );
1677 }
1678
1679 // Output the chamfer corners for chamfered rect pads
1680 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CHAMFERED_RECT)
1681 {
1682 m_out->Print( "(chamfer_ratio %s)",
1683 FormatDouble2Str( aPad->GetChamferRectRatio( aLayer ) ).c_str() );
1684
1685 m_out->Print( "(chamfer" );
1686
1687 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_TOP_LEFT ) )
1688 m_out->Print( " top_left" );
1689
1690 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_TOP_RIGHT ) )
1691 m_out->Print( " top_right" );
1692
1693 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_BOTTOM_LEFT ) )
1694 m_out->Print( " bottom_left" );
1695
1696 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_BOTTOM_RIGHT ) )
1697 m_out->Print( " bottom_right" );
1698
1699 m_out->Print( ")" );
1700 }
1701
1702 };
1703
1704 // For normal padstacks, this is the one and only set of properties. For complex ones, this
1705 // will represent the front layer properties, and other layers will be formatted below
1706 formatCornerProperties( PADSTACK::ALL_LAYERS );
1707
1708 // Unconnected pad is default net so don't save it.
1710 {
1711 m_out->Print( "(net %d %s)", m_mapping->Translate( aPad->GetNetCode() ),
1712 m_out->Quotew( aPad->GetNetname() ).c_str() );
1713 }
1714
1715 // Pin functions and types are closely related to nets, so if CTL_OMIT_NETS is set, omit
1716 // them as well (for instance when saved from library editor).
1717 if( !( m_ctl & CTL_OMIT_PAD_NETS ) )
1718 {
1719 if( !aPad->GetPinFunction().IsEmpty() )
1720 m_out->Print( "(pinfunction %s)", m_out->Quotew( aPad->GetPinFunction() ).c_str() );
1721
1722 if( !aPad->GetPinType().IsEmpty() )
1723 m_out->Print( "(pintype %s)", m_out->Quotew( aPad->GetPinType() ).c_str() );
1724 }
1725
1726 if( aPad->GetPadToDieLength() != 0 )
1727 {
1728 m_out->Print( "(die_length %s)",
1729 formatInternalUnits( aPad->GetPadToDieLength() ).c_str() );
1730 }
1731
1732 if( aPad->GetPadToDieDelay() != 0 )
1733 {
1734 m_out->Print( "(die_delay %s)", formatInternalUnits( aPad->GetPadToDieDelay() ).c_str() );
1735 }
1736
1737 if( aPad->GetLocalSolderMaskMargin().has_value() )
1738 {
1739 m_out->Print( "(solder_mask_margin %s)",
1740 formatInternalUnits( aPad->GetLocalSolderMaskMargin().value() ).c_str() );
1741 }
1742
1743 if( aPad->GetLocalSolderPasteMargin().has_value() )
1744 {
1745 m_out->Print( "(solder_paste_margin %s)",
1746 formatInternalUnits( aPad->GetLocalSolderPasteMargin().value() ).c_str() );
1747 }
1748
1749 if( aPad->GetLocalSolderPasteMarginRatio().has_value() )
1750 {
1751 m_out->Print( "(solder_paste_margin_ratio %s)",
1752 FormatDouble2Str( aPad->GetLocalSolderPasteMarginRatio().value() ).c_str() );
1753 }
1754
1755 if( aPad->GetLocalClearance().has_value() )
1756 {
1757 m_out->Print( "(clearance %s)",
1758 formatInternalUnits( aPad->GetLocalClearance().value() ).c_str() );
1759 }
1760
1762 {
1763 m_out->Print( "(zone_connect %d)",
1764 static_cast<int>( aPad->GetLocalZoneConnection() ) );
1765 }
1766
1767 if( aPad->GetLocalThermalSpokeWidthOverride().has_value() )
1768 {
1769 m_out->Print( "(thermal_bridge_width %s)",
1770 formatInternalUnits( aPad->GetLocalThermalSpokeWidthOverride().value() ).c_str() );
1771 }
1772
1773 EDA_ANGLE defaultThermalSpokeAngle = ANGLE_90;
1774
1778 {
1779 defaultThermalSpokeAngle = ANGLE_45;
1780 }
1781
1782 if( aPad->GetThermalSpokeAngle() != defaultThermalSpokeAngle )
1783 {
1784 m_out->Print( "(thermal_bridge_angle %s)",
1786 }
1787
1788 if( aPad->GetLocalThermalGapOverride().has_value() )
1789 {
1790 m_out->Print( "(thermal_gap %s)",
1791 formatInternalUnits( aPad->GetLocalThermalGapOverride().value() ).c_str() );
1792 }
1793
1794 auto anchorShape =
1795 [&]( PCB_LAYER_ID aLayer )
1796 {
1797 switch( aPad->GetAnchorPadShape( aLayer ) )
1798 {
1799 case PAD_SHAPE::RECTANGLE: return "rect";
1800 default:
1801 case PAD_SHAPE::CIRCLE: return "circle";
1802 }
1803 };
1804
1805 auto formatPrimitives =
1806 [&]( PCB_LAYER_ID aLayer )
1807 {
1808 m_out->Print( "(primitives" );
1809
1810 // Output all basic shapes
1811 for( const std::shared_ptr<PCB_SHAPE>& primitive : aPad->GetPrimitives( aLayer ) )
1812 {
1813 switch( primitive->GetShape() )
1814 {
1815 case SHAPE_T::SEGMENT:
1816 if( primitive->IsProxyItem() )
1817 {
1818 m_out->Print( "(gr_vector (start %s) (end %s)",
1819 formatInternalUnits( primitive->GetStart() ).c_str(),
1820 formatInternalUnits( primitive->GetEnd() ).c_str() );
1821 }
1822 else
1823 {
1824 m_out->Print( "(gr_line (start %s) (end %s)",
1825 formatInternalUnits( primitive->GetStart() ).c_str(),
1826 formatInternalUnits( primitive->GetEnd() ).c_str() );
1827 }
1828 break;
1829
1830 case SHAPE_T::RECTANGLE:
1831 if( primitive->IsProxyItem() )
1832 {
1833 m_out->Print( "(gr_bbox (start %s) (end %s)",
1834 formatInternalUnits( primitive->GetStart() ).c_str(),
1835 formatInternalUnits( primitive->GetEnd() ).c_str() );
1836 }
1837 else
1838 {
1839 m_out->Print( "(gr_rect (start %s) (end %s)",
1840 formatInternalUnits( primitive->GetStart() ).c_str(),
1841 formatInternalUnits( primitive->GetEnd() ).c_str() );
1842
1843 if( primitive->GetCornerRadius() > 0 )
1844 m_out->Print( " (radius %s)", formatInternalUnits( primitive->GetCornerRadius() ).c_str() );
1845 }
1846 break;
1847
1848 case SHAPE_T::ARC:
1849 m_out->Print( "(gr_arc (start %s) (mid %s) (end %s)",
1850 formatInternalUnits( primitive->GetStart() ).c_str(),
1851 formatInternalUnits( primitive->GetArcMid() ).c_str(),
1852 formatInternalUnits( primitive->GetEnd() ).c_str() );
1853 break;
1854
1855 case SHAPE_T::CIRCLE:
1856 m_out->Print( "(gr_circle (center %s) (end %s)",
1857 formatInternalUnits( primitive->GetStart() ).c_str(),
1858 formatInternalUnits( primitive->GetEnd() ).c_str() );
1859 break;
1860
1861 case SHAPE_T::BEZIER:
1862 m_out->Print( "(gr_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
1863 formatInternalUnits( primitive->GetStart() ).c_str(),
1864 formatInternalUnits( primitive->GetBezierC1() ).c_str(),
1865 formatInternalUnits( primitive->GetBezierC2() ).c_str(),
1866 formatInternalUnits( primitive->GetEnd() ).c_str() );
1867 break;
1868
1869 case SHAPE_T::POLY:
1870 if( primitive->IsPolyShapeValid() )
1871 {
1872 const SHAPE_POLY_SET& poly = primitive->GetPolyShape();
1873 const SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
1874
1875 m_out->Print( "(gr_poly" );
1876 formatPolyPts( outline );
1877 }
1878 break;
1879
1880 default:
1881 break;
1882 }
1883
1884 if( !primitive->IsProxyItem() )
1885 m_out->Print( "(width %s)", formatInternalUnits( primitive->GetWidth() ).c_str() );
1886
1887 // The filled flag represents if a solid fill is present on circles,
1888 // rectangles and polygons
1889 if( ( primitive->GetShape() == SHAPE_T::POLY )
1890 || ( primitive->GetShape() == SHAPE_T::RECTANGLE )
1891 || ( primitive->GetShape() == SHAPE_T::CIRCLE ) )
1892 {
1893 KICAD_FORMAT::FormatBool( m_out, "fill", primitive->IsSolidFill() );
1894 }
1895
1896 m_out->Print( ")" );
1897 }
1898
1899 m_out->Print( ")" ); // end of (primitives
1900 };
1901
1903 {
1904 m_out->Print( "(options" );
1905
1907 m_out->Print( "(clearance convexhull)" );
1908 else
1909 m_out->Print( "(clearance outline)" );
1910
1911 // Output the anchor pad shape (circle/rect)
1912 m_out->Print( "(anchor %s)", anchorShape( PADSTACK::ALL_LAYERS ) );
1913
1914 m_out->Print( ")"); // end of (options ...
1915
1916 // Output graphic primitive of the pad shape
1917 formatPrimitives( PADSTACK::ALL_LAYERS );
1918 }
1919
1922
1923 m_out->Print( 0, " (tenting " );
1928 m_out->Print( 0, ")" );
1929
1931
1932 // TODO: Refactor so that we call formatPadLayer( ALL_LAYERS ) above instead of redundant code
1933 auto formatPadLayer =
1934 [&]( PCB_LAYER_ID aLayer )
1935 {
1936 const PADSTACK& padstack = aPad->Padstack();
1937
1938 m_out->Print( "(shape %s)", shapeName( aLayer ) );
1939 m_out->Print( "(size %s)", formatInternalUnits( aPad->GetSize( aLayer ) ).c_str() );
1940
1941 const VECTOR2I& delta = aPad->GetDelta( aLayer );
1942
1943 if( delta.x != 0 || delta.y != 0 )
1944 m_out->Print( "(rect_delta %s)", formatInternalUnits( delta ).c_str() );
1945
1946 shapeoffset = aPad->GetOffset( aLayer );
1947
1948 if( shapeoffset.x != 0 || shapeoffset.y != 0 )
1949 m_out->Print( "(offset %s)", formatInternalUnits( shapeoffset ).c_str() );
1950
1951 formatCornerProperties( aLayer );
1952
1953 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
1954 {
1955 m_out->Print( "(options" );
1956
1957 // Output the anchor pad shape (circle/rect)
1958 m_out->Print( "(anchor %s)", anchorShape( aLayer ) );
1959
1960 m_out->Print( ")" ); // end of (options ...
1961
1962 // Output graphic primitive of the pad shape
1963 formatPrimitives( aLayer );
1964 }
1965
1966 EDA_ANGLE defaultLayerAngle = ANGLE_90;
1967
1968 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CIRCLE ||
1969 ( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM
1970 && aPad->GetAnchorPadShape( aLayer ) == PAD_SHAPE::CIRCLE ) )
1971 {
1972 defaultLayerAngle = ANGLE_45;
1973 }
1974
1975 EDA_ANGLE layerSpokeAngle = padstack.ThermalSpokeAngle( aLayer );
1976
1977 if( layerSpokeAngle != defaultLayerAngle )
1978 {
1979 m_out->Print( "(thermal_bridge_angle %s)",
1980 EDA_UNIT_UTILS::FormatAngle( layerSpokeAngle ).c_str() );
1981 }
1982
1983 if( padstack.ThermalGap( aLayer ).has_value() )
1984 {
1985 m_out->Print( "(thermal_gap %s)",
1986 formatInternalUnits( *padstack.ThermalGap( aLayer ) ).c_str() );
1987 }
1988
1989 if( padstack.ThermalSpokeWidth( aLayer ).has_value() )
1990 {
1991 m_out->Print( "(thermal_bridge_width %s)",
1992 formatInternalUnits( *padstack.ThermalSpokeWidth( aLayer ) ).c_str() );
1993 }
1994
1995 if( padstack.Clearance( aLayer ).has_value() )
1996 {
1997 m_out->Print( "(clearance %s)",
1998 formatInternalUnits( *padstack.Clearance( aLayer ) ).c_str() );
1999 }
2000
2001 if( padstack.ZoneConnection( aLayer ).has_value() )
2002 {
2003 m_out->Print( "(zone_connect %d)",
2004 static_cast<int>( *padstack.ZoneConnection( aLayer ) ) );
2005 }
2006 };
2007
2008
2009 if( aPad->Padstack().Mode() != PADSTACK::MODE::NORMAL )
2010 {
2012 {
2013 m_out->Print( "(padstack (mode front_inner_back)" );
2014
2015 m_out->Print( "(layer \"Inner\"" );
2016 formatPadLayer( PADSTACK::INNER_LAYERS );
2017 m_out->Print( ")" );
2018 m_out->Print( "(layer \"B.Cu\"" );
2019 formatPadLayer( B_Cu );
2020 m_out->Print( ")" );
2021 }
2022 else
2023 {
2024 m_out->Print( "(padstack (mode custom)" );
2025
2026 int layerCount = board ? board->GetCopperLayerCount() : MAX_CU_LAYERS;
2027
2028 for( PCB_LAYER_ID layer : LAYER_RANGE( F_Cu, B_Cu, layerCount ) )
2029 {
2030 if( layer == F_Cu )
2031 continue;
2032
2033 m_out->Print( "(layer %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
2034 formatPadLayer( layer );
2035 m_out->Print( ")" );
2036 }
2037 }
2038
2039 m_out->Print( ")" );
2040 }
2041
2042 m_out->Print( ")" );
2043}
2044
2045
2046void PCB_IO_KICAD_SEXPR::format( const PCB_TEXT* aText ) const
2047{
2048 FOOTPRINT* parentFP = aText->GetParentFootprint();
2049 std::string prefix;
2050 std::string type;
2051 VECTOR2I pos = aText->GetTextPos();
2052 const PCB_FIELD* field = dynamic_cast<const PCB_FIELD*>( aText );
2053
2054 // Always format dimension text as gr_text
2055 if( dynamic_cast<const PCB_DIMENSION_BASE*>( aText ) )
2056 parentFP = nullptr;
2057
2058 if( parentFP )
2059 {
2060 prefix = "fp";
2061 type = "user";
2062
2063 pos -= parentFP->GetPosition();
2064 RotatePoint( pos, -parentFP->GetOrientation() );
2065 }
2066 else
2067 {
2068 prefix = "gr";
2069 }
2070
2071 if( !field )
2072 {
2073 m_out->Print( "(%s_text %s %s",
2074 prefix.c_str(),
2075 type.c_str(),
2076 m_out->Quotew( aText->GetText() ).c_str() );
2077
2078 if( aText->IsLocked() )
2079 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2080 }
2081
2082 m_out->Print( "(at %s %s)",
2083 formatInternalUnits( pos ).c_str(),
2084 EDA_UNIT_UTILS::FormatAngle( aText->GetTextAngle() ).c_str() );
2085
2086 if( parentFP && !aText->IsKeepUpright() )
2087 KICAD_FORMAT::FormatBool( m_out, "unlocked", true );
2088
2089 formatLayer( aText->GetLayer(), aText->IsKnockout() );
2090
2091 if( field && !field->IsVisible() )
2092 KICAD_FORMAT::FormatBool( m_out, "hide", true );
2093
2095
2096 // Currently, texts have no specific color and no hyperlink.
2097 // so ensure they are never written in kicad_pcb file
2098 int ctl_flags = CTL_OMIT_COLOR | CTL_OMIT_HYPERLINK;
2099
2100 aText->EDA_TEXT::Format( m_out, ctl_flags );
2101
2102 if( aText->GetFont() && aText->GetFont()->IsOutline() )
2103 formatRenderCache( aText );
2104
2105 if( !field )
2106 m_out->Print( ")" );
2107}
2108
2109
2110void PCB_IO_KICAD_SEXPR::format( const PCB_TEXTBOX* aTextBox ) const
2111{
2112 FOOTPRINT* parentFP = aTextBox->GetParentFootprint();
2113
2114 m_out->Print( "(%s %s",
2115 aTextBox->Type() == PCB_TABLECELL_T ? "table_cell"
2116 : parentFP ? "fp_text_box"
2117 : "gr_text_box",
2118 m_out->Quotew( aTextBox->GetText() ).c_str() );
2119
2120 if( aTextBox->IsLocked() )
2121 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2122
2123 if( aTextBox->GetShape() == SHAPE_T::RECTANGLE )
2124 {
2125 m_out->Print( "(start %s) (end %s)",
2126 formatInternalUnits( aTextBox->GetStart(), parentFP ).c_str(),
2127 formatInternalUnits( aTextBox->GetEnd(), parentFP ).c_str() );
2128 }
2129 else if( aTextBox->GetShape() == SHAPE_T::POLY )
2130 {
2131 const SHAPE_POLY_SET& poly = aTextBox->GetPolyShape();
2132 const SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
2133
2134 formatPolyPts( outline, parentFP );
2135 }
2136 else
2137 {
2138 UNIMPLEMENTED_FOR( aTextBox->SHAPE_T_asString() );
2139 }
2140
2141 m_out->Print( "(margins %s %s %s %s)",
2142 formatInternalUnits( aTextBox->GetMarginLeft() ).c_str(),
2143 formatInternalUnits( aTextBox->GetMarginTop() ).c_str(),
2144 formatInternalUnits( aTextBox->GetMarginRight() ).c_str(),
2145 formatInternalUnits( aTextBox->GetMarginBottom() ).c_str() );
2146
2147 if( const PCB_TABLECELL* cell = dynamic_cast<const PCB_TABLECELL*>( aTextBox ) )
2148 m_out->Print( "(span %d %d)", cell->GetColSpan(), cell->GetRowSpan() );
2149
2150 EDA_ANGLE angle = aTextBox->GetTextAngle();
2151
2152 if( parentFP )
2153 {
2154 angle -= parentFP->GetOrientation();
2155 angle.Normalize720();
2156 }
2157
2158 if( !angle.IsZero() )
2159 m_out->Print( "(angle %s)", EDA_UNIT_UTILS::FormatAngle( angle ).c_str() );
2160
2161 formatLayer( aTextBox->GetLayer() );
2162
2164
2165 aTextBox->EDA_TEXT::Format( m_out, 0 );
2166
2167 if( aTextBox->Type() != PCB_TABLECELL_T )
2168 {
2169 KICAD_FORMAT::FormatBool( m_out, "border", aTextBox->IsBorderEnabled() );
2170 aTextBox->GetStroke().Format( m_out, pcbIUScale );
2171
2172 KICAD_FORMAT::FormatBool( m_out, "knockout", aTextBox->IsKnockout() );
2173 }
2174
2175 if( aTextBox->GetFont() && aTextBox->GetFont()->IsOutline() )
2176 formatRenderCache( aTextBox );
2177
2178 m_out->Print( ")" );
2179}
2180
2181
2182void PCB_IO_KICAD_SEXPR::format( const PCB_TABLE* aTable ) const
2183{
2184 wxCHECK_RET( aTable != nullptr && m_out != nullptr, "" );
2185
2186 m_out->Print( "(table (column_count %d)", aTable->GetColCount() );
2187
2189
2190 if( aTable->IsLocked() )
2191 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2192
2193 formatLayer( aTable->GetLayer() );
2194
2195 m_out->Print( "(border" );
2196 KICAD_FORMAT::FormatBool( m_out, "external", aTable->StrokeExternal() );
2198
2199 if( aTable->StrokeExternal() || aTable->StrokeHeaderSeparator() )
2200 aTable->GetBorderStroke().Format( m_out, pcbIUScale );
2201
2202 m_out->Print( ")" ); // Close `border` token.
2203
2204 m_out->Print( "(separators" );
2205 KICAD_FORMAT::FormatBool( m_out, "rows", aTable->StrokeRows() );
2206 KICAD_FORMAT::FormatBool( m_out, "cols", aTable->StrokeColumns() );
2207
2208 if( aTable->StrokeRows() || aTable->StrokeColumns() )
2210
2211 m_out->Print( ")" ); // Close `separators` token.
2212
2213 m_out->Print( "(column_widths" );
2214
2215 for( int col = 0; col < aTable->GetColCount(); ++col )
2216 m_out->Print( " %s", formatInternalUnits( aTable->GetColWidth( col ) ).c_str() );
2217
2218 m_out->Print( ")" );
2219
2220 m_out->Print( "(row_heights" );
2221
2222 for( int row = 0; row < aTable->GetRowCount(); ++row )
2223 m_out->Print( " %s", formatInternalUnits( aTable->GetRowHeight( row ) ).c_str() );
2224
2225 m_out->Print( ")" );
2226
2227 m_out->Print( "(cells" );
2228
2229 for( PCB_TABLECELL* cell : aTable->GetCells() )
2230 format( static_cast<PCB_TEXTBOX*>( cell ) );
2231
2232 m_out->Print( ")" ); // Close `cells` token.
2233 m_out->Print( ")" ); // Close `table` token.
2234}
2235
2236
2237void PCB_IO_KICAD_SEXPR::format( const PCB_GROUP* aGroup ) const
2238{
2239 // Don't write empty groups
2240 if( aGroup->GetItems().empty() )
2241 return;
2242
2243 m_out->Print( "(group %s", m_out->Quotew( aGroup->GetName() ).c_str() );
2244
2246
2247 if( aGroup->IsLocked() )
2248 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2249
2250 if( aGroup->HasDesignBlockLink() )
2251 m_out->Print( "(lib_id \"%s\")", aGroup->GetDesignBlockLibId().Format().c_str() );
2252
2253 wxArrayString memberIds;
2254
2255 for( EDA_ITEM* member : aGroup->GetItems() )
2256 memberIds.Add( member->m_Uuid.AsString() );
2257
2258 memberIds.Sort();
2259
2260 m_out->Print( "(members" );
2261
2262 for( const wxString& memberId : memberIds )
2263 m_out->Print( " %s", m_out->Quotew( memberId ).c_str() );
2264
2265 m_out->Print( ")" ); // Close `members` token.
2266 m_out->Print( ")" ); // Close `group` token.
2267}
2268
2269
2270void PCB_IO_KICAD_SEXPR::format( const PCB_GENERATOR* aGenerator ) const
2271{
2272 // Some conditions appear to still be creating ghost tuning patterns. Don't save them.
2273 if( aGenerator->GetGeneratorType() == wxT( "tuning_pattern" )
2274 && aGenerator->GetItems().empty() )
2275 {
2276 return;
2277 }
2278
2279 m_out->Print( "(generated" );
2280
2281 KICAD_FORMAT::FormatUuid( m_out, aGenerator->m_Uuid );
2282
2283 m_out->Print( "(type %s) (name %s) (layer %s)",
2284 TO_UTF8( aGenerator->GetGeneratorType() ),
2285 m_out->Quotew( aGenerator->GetName() ).c_str(),
2286 m_out->Quotew( LSET::Name( aGenerator->GetLayer() ) ).c_str() );
2287
2288 if( aGenerator->IsLocked() )
2289 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2290
2291 for( const auto& [key, value] : aGenerator->GetProperties() )
2292 {
2293 if( value.CheckType<double>() || value.CheckType<int>() || value.CheckType<long>()
2294 || value.CheckType<long long>() )
2295 {
2296 double val;
2297
2298 if( !value.GetAs( &val ) )
2299 continue;
2300
2301 std::string buf = fmt::format( "{:.10g}", val );
2302
2303 // Don't quote numbers
2304 m_out->Print( "(%s %s)", key.c_str(), buf.c_str() );
2305 }
2306 else if( value.CheckType<bool>() )
2307 {
2308 bool val;
2309 value.GetAs( &val );
2310
2311 KICAD_FORMAT::FormatBool( m_out, key, val );
2312 }
2313 else if( value.CheckType<VECTOR2I>() )
2314 {
2315 VECTOR2I val;
2316 value.GetAs( &val );
2317
2318 m_out->Print( "(%s (xy %s))",
2319 key.c_str(),
2320 formatInternalUnits( val ).c_str() );
2321 }
2322 else if( value.CheckType<SHAPE_LINE_CHAIN>() )
2323 {
2324 SHAPE_LINE_CHAIN val;
2325 value.GetAs( &val );
2326
2327 m_out->Print( "(%s ", key.c_str() );
2328 formatPolyPts( val );
2329 m_out->Print( ")" );
2330 }
2331 else
2332 {
2333 wxString val;
2334
2335 if( value.CheckType<wxString>() )
2336 {
2337 value.GetAs( &val );
2338 }
2339 else if( value.CheckType<std::string>() )
2340 {
2341 std::string str;
2342 value.GetAs( &str );
2343
2344 val = wxString::FromUTF8( str );
2345 }
2346
2347 m_out->Print( "(%s %s)", key.c_str(), m_out->Quotew( val ).c_str() );
2348 }
2349 }
2350
2351 wxArrayString memberIds;
2352
2353 for( EDA_ITEM* member : aGenerator->GetItems() )
2354 memberIds.Add( member->m_Uuid.AsString() );
2355
2356 memberIds.Sort();
2357
2358 m_out->Print( "(members" );
2359
2360 for( const wxString& memberId : memberIds )
2361 m_out->Print( " %s", m_out->Quotew( memberId ).c_str() );
2362
2363 m_out->Print( ")" ); // Close `members` token.
2364 m_out->Print( ")" ); // Close `generated` token.
2365}
2366
2367
2368void PCB_IO_KICAD_SEXPR::format( const PCB_TRACK* aTrack ) const
2369{
2370 if( aTrack->Type() == PCB_VIA_T )
2371 {
2372 PCB_LAYER_ID layer1, layer2;
2373
2374 const PCB_VIA* via = static_cast<const PCB_VIA*>( aTrack );
2375 const BOARD* board = via->GetBoard();
2376
2377 wxCHECK_RET( board != nullptr, wxT( "Via has no parent." ) );
2378
2379 m_out->Print( "(via" );
2380
2381 via->LayerPair( &layer1, &layer2 );
2382
2383 switch( via->GetViaType() )
2384 {
2385 case VIATYPE::THROUGH: // Default shape not saved.
2386 break;
2387
2389 m_out->Print( " blind " );
2390 break;
2391
2392 case VIATYPE::MICROVIA:
2393 m_out->Print( " micro " );
2394 break;
2395
2396 default:
2397 THROW_IO_ERROR( wxString::Format( _( "unknown via type %d" ), via->GetViaType() ) );
2398 }
2399
2400 m_out->Print( "(at %s) (size %s)",
2401 formatInternalUnits( aTrack->GetStart() ).c_str(),
2402 formatInternalUnits( via->GetWidth( F_Cu ) ).c_str() );
2403
2404 // Old boards were using UNDEFINED_DRILL_DIAMETER value in file for via drill when
2405 // via drill was the netclass value.
2406 // recent boards always set the via drill to the actual value, but now we need to
2407 // always store the drill value, because netclass value is not stored in the board file.
2408 // Otherwise the drill value of some (old) vias can be unknown
2409 if( via->GetDrill() != UNDEFINED_DRILL_DIAMETER )
2410 m_out->Print( "(drill %s)", formatInternalUnits( via->GetDrill() ).c_str() );
2411 else
2412 m_out->Print( "(drill %s)", formatInternalUnits( via->GetDrillValue() ).c_str() );
2413
2414 m_out->Print( "(layers %s %s)",
2415 m_out->Quotew( LSET::Name( layer1 ) ).c_str(),
2416 m_out->Quotew( LSET::Name( layer2 ) ).c_str() );
2417
2418 switch( via->Padstack().UnconnectedLayerMode() )
2419 {
2421 KICAD_FORMAT::FormatBool( m_out, "remove_unused_layers", true );
2422 KICAD_FORMAT::FormatBool( m_out, "keep_end_layers", false );
2423 break;
2424
2426 KICAD_FORMAT::FormatBool( m_out, "remove_unused_layers", true );
2427 KICAD_FORMAT::FormatBool( m_out, "keep_end_layers", true );
2428 break;
2429
2431 KICAD_FORMAT::FormatBool( m_out, "start_end_only", true );
2432 break;
2433
2435 break;
2436 }
2437
2438 if( via->IsLocked() )
2439 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2440
2441 if( via->GetIsFree() )
2442 KICAD_FORMAT::FormatBool( m_out, "free", true );
2443
2444 if( via->GetRemoveUnconnected() )
2445 {
2446 m_out->Print( "(zone_layer_connections" );
2447
2448 for( PCB_LAYER_ID layer : board->GetEnabledLayers().CuStack() )
2449 {
2450 if( via->GetZoneLayerOverride( layer ) == ZLO_FORCE_FLASHED )
2451 m_out->Print( " %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
2452 }
2453
2454 m_out->Print( ")" );
2455 }
2456
2457 const PADSTACK& padstack = via->Padstack();
2458
2459 m_out->Print( 0, " (tenting " );
2462 m_out->Print( 0, ")" );
2463
2464 KICAD_FORMAT::FormatOptBool( m_out, "capping", padstack.Drill().is_capped );
2465
2466 m_out->Print( 0, " (covering " );
2469 m_out->Print( 0, ")" );
2470
2471 m_out->Print( 0, " (plugging " );
2474 m_out->Print( 0, ")" );
2475
2476 KICAD_FORMAT::FormatOptBool( m_out, "filling", padstack.Drill().is_filled );
2477
2478 if( padstack.Mode() != PADSTACK::MODE::NORMAL )
2479 {
2480 m_out->Print( "(padstack" );
2481
2482 if( padstack.Mode() == PADSTACK::MODE::FRONT_INNER_BACK )
2483 {
2484 m_out->Print( "(mode front_inner_back)" );
2485
2486 m_out->Print( "(layer \"Inner\"" );
2487 m_out->Print( "(size %s)",
2488 formatInternalUnits( padstack.Size( PADSTACK::INNER_LAYERS ).x ).c_str() );
2489 m_out->Print( ")" );
2490 m_out->Print( "(layer \"B.Cu\"" );
2491 m_out->Print( "(size %s)",
2492 formatInternalUnits( padstack.Size( B_Cu ).x ).c_str() );
2493 m_out->Print( ")" );
2494 }
2495 else
2496 {
2497 m_out->Print( "(mode custom)" );
2498
2499 for( PCB_LAYER_ID layer : LAYER_RANGE( F_Cu, B_Cu, board->GetCopperLayerCount() ) )
2500 {
2501 if( layer == F_Cu )
2502 continue;
2503
2504 m_out->Print( "(layer %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
2505 m_out->Print( "(size %s)",
2506 formatInternalUnits( padstack.Size( layer ).x ).c_str() );
2507 m_out->Print( ")" );
2508 }
2509 }
2510
2511 m_out->Print( ")" );
2512 }
2513
2514 if( !isDefaultTeardropParameters( via->GetTeardropParams() ) )
2515 formatTeardropParameters( via->GetTeardropParams() );
2516 }
2517 else
2518 {
2519 if( aTrack->Type() == PCB_ARC_T )
2520 {
2521 const PCB_ARC* arc = static_cast<const PCB_ARC*>( aTrack );
2522
2523 m_out->Print( "(arc (start %s) (mid %s) (end %s) (width %s)",
2524 formatInternalUnits( arc->GetStart() ).c_str(),
2525 formatInternalUnits( arc->GetMid() ).c_str(),
2526 formatInternalUnits( arc->GetEnd() ).c_str(),
2527 formatInternalUnits( arc->GetWidth() ).c_str() );
2528 }
2529 else
2530 {
2531 m_out->Print( "(segment (start %s) (end %s) (width %s)",
2532 formatInternalUnits( aTrack->GetStart() ).c_str(),
2533 formatInternalUnits( aTrack->GetEnd() ).c_str(),
2534 formatInternalUnits( aTrack->GetWidth() ).c_str() );
2535 }
2536
2537 if( aTrack->IsLocked() )
2538 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2539
2540 if( aTrack->GetLayerSet().count() > 1 )
2541 formatLayers( aTrack->GetLayerSet(), false /* enumerate layers */ );
2542 else
2543 formatLayer( aTrack->GetLayer() );
2544
2545 if( aTrack->HasSolderMask()
2546 && aTrack->GetLocalSolderMaskMargin().has_value()
2547 && IsExternalCopperLayer( aTrack->GetLayer() ) )
2548 {
2549 m_out->Print( "(solder_mask_margin %s)",
2550 formatInternalUnits( aTrack->GetLocalSolderMaskMargin().value() ).c_str() );
2551 }
2552 }
2553
2554 m_out->Print( "(net %d)", m_mapping->Translate( aTrack->GetNetCode() ) );
2555
2557 m_out->Print( ")" );
2558}
2559
2560
2561void PCB_IO_KICAD_SEXPR::format( const ZONE* aZone ) const
2562{
2563 // Save the NET info.
2564 // For keepout and non copper zones, net code and net name are irrelevant
2565 // so be sure a dummy value is stored, just for ZONE compatibility
2566 // (perhaps netcode and netname should be not stored)
2567
2568 bool has_no_net = aZone->GetIsRuleArea() || !aZone->IsOnCopperLayer();
2569
2570 m_out->Print( "(zone (net %d) (net_name %s)",
2571 has_no_net ? 0 : m_mapping->Translate( aZone->GetNetCode() ),
2572 m_out->Quotew( has_no_net ? wxString( wxT("") ) : aZone->GetNetname() ).c_str() );
2573
2574 if( aZone->IsLocked() )
2575 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2576
2577 // If a zone exists on multiple layers, format accordingly
2578 LSET layers = aZone->GetLayerSet();
2579
2580 if( aZone->GetBoard() )
2581 layers &= aZone->GetBoard()->GetEnabledLayers();
2582
2583 // Always enumerate every layer for a zone on a copper layer
2584 if( layers.count() > 1 )
2585 formatLayers( layers, aZone->IsOnCopperLayer(), true );
2586 else
2587 formatLayer( aZone->GetFirstLayer() );
2588
2589 if( !aZone->IsTeardropArea() )
2591
2592 if( !aZone->GetZoneName().empty() && !aZone->IsTeardropArea() )
2593 m_out->Print( "(name %s)", m_out->Quotew( aZone->GetZoneName() ).c_str() );
2594
2595 // Save the outline aux info
2596 std::string hatch;
2597
2598 switch( aZone->GetHatchStyle() )
2599 {
2600 default:
2601 case ZONE_BORDER_DISPLAY_STYLE::NO_HATCH: hatch = "none"; break;
2602 case ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_EDGE: hatch = "edge"; break;
2603 case ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_FULL: hatch = "full"; break;
2604 }
2605
2606 m_out->Print( "(hatch %s %s)", hatch.c_str(),
2607 formatInternalUnits( aZone->GetBorderHatchPitch() ).c_str() );
2608
2609
2610
2611 if( aZone->GetAssignedPriority() > 0 )
2612 m_out->Print( "(priority %d)", aZone->GetAssignedPriority() );
2613
2614 // Add teardrop keywords in file: (attr (teardrop (type xxx))) where xxx is the teardrop type
2615 if( aZone->IsTeardropArea() )
2616 {
2617 m_out->Print( "(attr (teardrop (type %s)))",
2618 aZone->GetTeardropAreaType() == TEARDROP_TYPE::TD_VIAPAD ? "padvia"
2619 : "track_end" );
2620 }
2621
2622 m_out->Print( "(connect_pads" );
2623
2624 switch( aZone->GetPadConnection() )
2625 {
2626 default:
2627 case ZONE_CONNECTION::THERMAL: // Default option not saved or loaded.
2628 break;
2629
2631 m_out->Print( " thru_hole_only" );
2632 break;
2633
2635 m_out->Print( " yes" );
2636 break;
2637
2639 m_out->Print( " no" );
2640 break;
2641 }
2642
2643 m_out->Print( "(clearance %s)",
2644 formatInternalUnits( aZone->GetLocalClearance().value() ).c_str() );
2645
2646 m_out->Print( ")" );
2647
2648 m_out->Print( "(min_thickness %s)",
2649 formatInternalUnits( aZone->GetMinThickness() ).c_str() );
2650
2651 if( aZone->GetIsRuleArea() )
2652 {
2653 // Keepout settings
2654 m_out->Print( "(keepout (tracks %s) (vias %s) (pads %s) (copperpour %s) (footprints %s))",
2655 aZone->GetDoNotAllowTracks() ? "not_allowed" : "allowed",
2656 aZone->GetDoNotAllowVias() ? "not_allowed" : "allowed",
2657 aZone->GetDoNotAllowPads() ? "not_allowed" : "allowed",
2658 aZone->GetDoNotAllowZoneFills() ? "not_allowed" : "allowed",
2659 aZone->GetDoNotAllowFootprints() ? "not_allowed" : "allowed" );
2660
2661 // Multichannel settings
2662 m_out->Print( "(placement" );
2664
2665 switch( aZone->GetPlacementAreaSourceType() )
2666 {
2668 m_out->Print( "(sheetname %s)", m_out->Quotew( aZone->GetPlacementAreaSource() ).c_str() );
2669 break;
2671 m_out->Print( "(component_class %s)", m_out->Quotew( aZone->GetPlacementAreaSource() ).c_str() );
2672 break;
2674 m_out->Print( "(group %s)", m_out->Quotew( aZone->GetPlacementAreaSource() ).c_str() );
2675 break;
2676 // These are transitory and should not be saved
2678 break;
2679 }
2680
2681 m_out->Print( ")" );
2682 }
2683
2684 m_out->Print( "(fill" );
2685
2686 // Default is not filled.
2687 if( aZone->IsFilled() )
2688 m_out->Print( " yes" );
2689
2690 // Default is polygon filled.
2692 m_out->Print( "(mode hatch)" );
2693
2694 if( !aZone->IsTeardropArea() )
2695 {
2696 m_out->Print( "(thermal_gap %s) (thermal_bridge_width %s)",
2697 formatInternalUnits( aZone->GetThermalReliefGap() ).c_str(),
2698 formatInternalUnits( aZone->GetThermalReliefSpokeWidth() ).c_str() );
2699 }
2700
2702 {
2703 switch( aZone->GetCornerSmoothingType() )
2704 {
2706 m_out->Print( "(smoothing chamfer)" );
2707 break;
2708
2710 m_out->Print( "(smoothing fillet)" );
2711 break;
2712
2713 default:
2714 THROW_IO_ERROR( wxString::Format( _( "unknown zone corner smoothing type %d" ),
2715 aZone->GetCornerSmoothingType() ) );
2716 }
2717
2718 if( aZone->GetCornerRadius() != 0 )
2719 m_out->Print( "(radius %s)", formatInternalUnits( aZone->GetCornerRadius() ).c_str() );
2720 }
2721
2722 m_out->Print( "(island_removal_mode %d)",
2723 static_cast<int>( aZone->GetIslandRemovalMode() ) );
2724
2726 {
2727 m_out->Print( "(island_area_min %s)",
2728 formatInternalUnits( aZone->GetMinIslandArea() / pcbIUScale.IU_PER_MM ).c_str() );
2729 }
2730
2732 {
2733 m_out->Print( "(hatch_thickness %s) (hatch_gap %s) (hatch_orientation %s)",
2734 formatInternalUnits( aZone->GetHatchThickness() ).c_str(),
2735 formatInternalUnits( aZone->GetHatchGap() ).c_str(),
2736 FormatDouble2Str( aZone->GetHatchOrientation().AsDegrees() ).c_str() );
2737
2738 if( aZone->GetHatchSmoothingLevel() > 0 )
2739 {
2740 m_out->Print( "(hatch_smoothing_level %d) (hatch_smoothing_value %s)",
2741 aZone->GetHatchSmoothingLevel(),
2742 FormatDouble2Str( aZone->GetHatchSmoothingValue() ).c_str() );
2743 }
2744
2745 m_out->Print( "(hatch_border_algorithm %s) (hatch_min_hole_area %s)",
2746 aZone->GetHatchBorderAlgorithm() ? "hatch_thickness" : "min_thickness",
2747 FormatDouble2Str( aZone->GetHatchHoleMinArea() ).c_str() );
2748 }
2749
2750 m_out->Print( ")" );
2751
2752 for( const auto& [layer, properties] : aZone->LayerProperties() )
2753 {
2754 format( properties, 0, layer );
2755 }
2756
2757 if( aZone->GetNumCorners() )
2758 {
2759 SHAPE_POLY_SET::POLYGON poly = aZone->Outline()->Polygon(0);
2760
2761 for( const SHAPE_LINE_CHAIN& chain : poly )
2762 {
2763 m_out->Print( "(polygon" );
2765 m_out->Print( ")" );
2766 }
2767 }
2768
2769 // Save the PolysList (filled areas)
2770 for( PCB_LAYER_ID layer : aZone->GetLayerSet().Seq() )
2771 {
2772 const std::shared_ptr<SHAPE_POLY_SET>& fv = aZone->GetFilledPolysList( layer );
2773
2774 for( int ii = 0; ii < fv->OutlineCount(); ++ii )
2775 {
2776 m_out->Print( "(filled_polygon" );
2777 m_out->Print( "(layer %s)", m_out->Quotew( LSET::Name( layer ) ).c_str() );
2778
2779 if( aZone->IsIsland( layer, ii ) )
2780 KICAD_FORMAT::FormatBool( m_out, "island", true );
2781
2782 const SHAPE_LINE_CHAIN& chain = fv->COutline( ii );
2783
2785 m_out->Print( ")" );
2786 }
2787 }
2788
2789 m_out->Print( ")" );
2790}
2791
2792
2793void PCB_IO_KICAD_SEXPR::format( const ZONE_LAYER_PROPERTIES& aZoneLayerProperties, int aNestLevel,
2794 PCB_LAYER_ID aLayer ) const
2795{
2796 // Do not store the layer properties if no value is actually set.
2797 if( !aZoneLayerProperties.hatching_offset.has_value() )
2798 return;
2799
2800 m_out->Print( aNestLevel, "(property\n" );
2801 m_out->Print( aNestLevel, "(layer %s)\n", m_out->Quotew( LSET::Name( aLayer ) ).c_str() );
2802
2803 if( aZoneLayerProperties.hatching_offset.has_value() )
2804 {
2805 m_out->Print( aNestLevel, "(hatch_position (xy %s))",
2806 formatInternalUnits( aZoneLayerProperties.hatching_offset.value() ).c_str() );
2807 }
2808
2809 m_out->Print( aNestLevel, ")\n" );
2810}
2811
2812
2813PCB_IO_KICAD_SEXPR::PCB_IO_KICAD_SEXPR( int aControlFlags ) : PCB_IO( wxS( "KiCad" ) ),
2814 m_cache( nullptr ),
2815 m_ctl( aControlFlags ),
2816 m_mapping( new NETINFO_MAPPING() )
2817{
2818 init( nullptr );
2819 m_out = &m_sf;
2820}
2821
2822
2824{
2825 delete m_cache;
2826 delete m_mapping;
2827}
2828
2829
2830BOARD* PCB_IO_KICAD_SEXPR::LoadBoard( const wxString& aFileName, BOARD* aAppendToMe,
2831 const std::map<std::string, UTF8>* aProperties,
2832 PROJECT* aProject )
2833{
2834 FILE_LINE_READER reader( aFileName );
2835
2836 unsigned lineCount = 0;
2837
2839
2840 if( m_progressReporter )
2841 {
2842 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
2843
2844 if( !m_progressReporter->KeepRefreshing() )
2845 THROW_IO_ERROR( _( "Open canceled by user." ) );
2846
2847 while( reader.ReadLine() )
2848 lineCount++;
2849
2850 reader.Rewind();
2851 }
2852
2853 BOARD* board = DoLoad( reader, aAppendToMe, aProperties, m_progressReporter, lineCount );
2854
2855 // Give the filename to the board if it's new
2856 if( !aAppendToMe )
2857 board->SetFileName( aFileName );
2858
2859 return board;
2860}
2861
2862
2864 const std::map<std::string, UTF8>* aProperties,
2865 PROGRESS_REPORTER* aProgressReporter, unsigned aLineCount)
2866{
2867 init( aProperties );
2868
2869 PCB_IO_KICAD_SEXPR_PARSER parser( &aReader, aAppendToMe, m_queryUserCallback,
2870 aProgressReporter, aLineCount );
2871 BOARD* board;
2872
2873 try
2874 {
2875 board = dynamic_cast<BOARD*>( parser.Parse() );
2876 }
2877 catch( const FUTURE_FORMAT_ERROR& )
2878 {
2879 // Don't wrap a FUTURE_FORMAT_ERROR in another
2880 throw;
2881 }
2882 catch( const PARSE_ERROR& parse_error )
2883 {
2884 if( parser.IsTooRecent() )
2885 throw FUTURE_FORMAT_ERROR( parse_error, parser.GetRequiredVersion() );
2886 else
2887 throw;
2888 }
2889
2890 if( !board )
2891 {
2892 // The parser loaded something that was valid, but wasn't a board.
2893 THROW_PARSE_ERROR( _( "This file does not contain a PCB." ), parser.CurSource(),
2894 parser.CurLine(), parser.CurLineNumber(), parser.CurOffset() );
2895 }
2896
2897 return board;
2898}
2899
2900
2901void PCB_IO_KICAD_SEXPR::init( const std::map<std::string, UTF8>* aProperties )
2902{
2903 m_board = nullptr;
2904 m_reader = nullptr;
2905 m_props = aProperties;
2906}
2907
2908
2909void PCB_IO_KICAD_SEXPR::validateCache( const wxString& aLibraryPath, bool checkModified )
2910{
2912
2913 if( !m_cache || !m_cache->IsPath( aLibraryPath ) || ( checkModified && m_cache->IsModified() ) )
2914 {
2915 // a spectacular episode in memory management:
2916 delete m_cache;
2917 m_cache = new FP_CACHE( this, aLibraryPath );
2918 m_cache->Load();
2919 }
2920}
2921
2922
2923void PCB_IO_KICAD_SEXPR::FootprintEnumerate( wxArrayString& aFootprintNames,
2924 const wxString& aLibPath, bool aBestEfforts,
2925 const std::map<std::string, UTF8>* aProperties )
2926{
2927 wxDir dir( aLibPath );
2928 wxString errorMsg;
2929
2930 init( aProperties );
2931
2932 try
2933 {
2934 validateCache( aLibPath );
2935 }
2936 catch( const IO_ERROR& ioe )
2937 {
2938 errorMsg = ioe.What();
2939 }
2940
2941 // Some of the files may have been parsed correctly so we want to add the valid files to
2942 // the library.
2943
2944 for( const auto& footprint : m_cache->GetFootprints() )
2945 aFootprintNames.Add( footprint.first );
2946
2947 if( !errorMsg.IsEmpty() && !aBestEfforts )
2948 THROW_IO_ERROR( errorMsg );
2949}
2950
2951
2952const FOOTPRINT* PCB_IO_KICAD_SEXPR::getFootprint( const wxString& aLibraryPath,
2953 const wxString& aFootprintName,
2954 const std::map<std::string, UTF8>* aProperties,
2955 bool checkModified )
2956{
2957 init( aProperties );
2958
2959 try
2960 {
2961 validateCache( aLibraryPath, checkModified );
2962 }
2963 catch( const IO_ERROR& )
2964 {
2965 // do nothing with the error
2966 }
2967
2968 auto it = m_cache->GetFootprints().find( aFootprintName );
2969
2970 if( it == m_cache->GetFootprints().end() )
2971 return nullptr;
2972
2973 return it->second->GetFootprint().get();
2974}
2975
2976
2977const FOOTPRINT* PCB_IO_KICAD_SEXPR::GetEnumeratedFootprint( const wxString& aLibraryPath,
2978 const wxString& aFootprintName,
2979 const std::map<std::string, UTF8>* aProperties )
2980{
2981 return getFootprint( aLibraryPath, aFootprintName, aProperties, false );
2982}
2983
2984
2985bool PCB_IO_KICAD_SEXPR::FootprintExists( const wxString& aLibraryPath,
2986 const wxString& aFootprintName,
2987 const std::map<std::string, UTF8>* aProperties )
2988{
2989 // Note: checking the cache sounds like a good idea, but won't catch files which differ
2990 // only in case.
2991 //
2992 // Since this goes out to the native filesystem, we get platform differences (ie: MSW's
2993 // case-insensitive filesystem) handled "for free".
2994 // Warning: footprint names frequently contain a point. So be careful when initializing
2995 // wxFileName, and use a CTOR with extension specified
2996 wxFileName footprintFile( aLibraryPath, aFootprintName, FILEEXT::KiCadFootprintFileExtension );
2997
2998 return footprintFile.Exists();
2999}
3000
3001
3002FOOTPRINT* PCB_IO_KICAD_SEXPR::ImportFootprint( const wxString& aFootprintPath,
3003 wxString& aFootprintNameOut,
3004 const std::map<std::string, UTF8>* aProperties )
3005{
3006 wxString fcontents;
3007 wxFFile f( aFootprintPath );
3008
3010
3011 if( !f.IsOpened() )
3012 return nullptr;
3013
3014 f.ReadAll( &fcontents );
3015
3016 aFootprintNameOut = wxFileName( aFootprintPath ).GetName();
3017
3018 return dynamic_cast<FOOTPRINT*>( Parse( fcontents ) );
3019}
3020
3021
3022FOOTPRINT* PCB_IO_KICAD_SEXPR::FootprintLoad( const wxString& aLibraryPath,
3023 const wxString& aFootprintName,
3024 bool aKeepUUID,
3025 const std::map<std::string, UTF8>* aProperties )
3026{
3028
3029 const FOOTPRINT* footprint = getFootprint( aLibraryPath, aFootprintName, aProperties, true );
3030
3031 if( footprint )
3032 {
3033 FOOTPRINT* copy;
3034
3035 if( aKeepUUID )
3036 copy = static_cast<FOOTPRINT*>( footprint->Clone() );
3037 else
3038 copy = static_cast<FOOTPRINT*>( footprint->Duplicate( IGNORE_PARENT_GROUP ) );
3039
3040 copy->SetParent( nullptr );
3041 return copy;
3042 }
3043
3044 return nullptr;
3045}
3046
3047
3048void PCB_IO_KICAD_SEXPR::FootprintSave( const wxString& aLibraryPath, const FOOTPRINT* aFootprint,
3049 const std::map<std::string, UTF8>* aProperties )
3050{
3051 init( aProperties );
3052
3053 // In this public PLUGIN API function, we can safely assume it was
3054 // called for saving into a library path.
3056
3057 validateCache( aLibraryPath, !aProperties || !aProperties->contains( "skip_cache_validation" ) );
3058
3059 if( !m_cache->IsWritable() )
3060 {
3061 if( !m_cache->Exists() )
3062 {
3063 const wxString msg = wxString::Format( _( "Library '%s' does not exist.\n"
3064 "Would you like to create it?"),
3065 aLibraryPath );
3066
3067 if( !Pgm().IsGUI() || wxMessageBox( msg, _( "Library Not Found" ), wxYES_NO | wxICON_QUESTION ) != wxYES )
3068 return;
3069
3070 // Save throws its own IO_ERROR on failure, so no need to recreate here
3071 m_cache->Save( nullptr );
3072 }
3073 else
3074 {
3075 wxString msg = wxString::Format( _( "Library '%s' is read only." ), aLibraryPath );
3076 THROW_IO_ERROR( msg );
3077 }
3078 }
3079
3080 wxString footprintName = aFootprint->GetFPID().GetLibItemName();
3081
3082 wxString fpName = aFootprint->GetFPID().GetLibItemName().wx_str();
3083 ReplaceIllegalFileNameChars( fpName, '_' );
3084
3085 // Quietly overwrite footprint and delete footprint file from path for any by same name.
3086 wxFileName fn( aLibraryPath, fpName, FILEEXT::KiCadFootprintFileExtension );
3087
3088 // Write through symlinks, don't replace them
3090
3091 if( !fn.IsOk() )
3092 {
3093 THROW_IO_ERROR( wxString::Format( _( "Footprint file name '%s' is not valid." ),
3094 fn.GetFullPath() ) );
3095 }
3096
3097 if( fn.FileExists() && !fn.IsFileWritable() )
3098 {
3099 THROW_IO_ERROR( wxString::Format( _( "Insufficient permissions to delete '%s'." ),
3100 fn.GetFullPath() ) );
3101 }
3102
3103 wxString fullPath = fn.GetFullPath();
3104 wxString fullName = fn.GetFullName();
3105 auto it = m_cache->GetFootprints().find( footprintName );
3106
3107 if( it != m_cache->GetFootprints().end() )
3108 {
3109 wxLogTrace( traceKicadPcbPlugin, wxT( "Removing footprint file '%s'." ), fullPath );
3110 m_cache->GetFootprints().erase( footprintName );
3111 wxRemoveFile( fullPath );
3112 }
3113
3114 // I need my own copy for the cache
3115 FOOTPRINT* footprint = static_cast<FOOTPRINT*>( aFootprint->Clone() );
3116
3117 // It's orientation should be zero and it should be on the front layer.
3118 footprint->SetOrientation( ANGLE_0 );
3119
3120 if( footprint->GetLayer() != F_Cu )
3121 {
3122 PCBNEW_SETTINGS* cfg = dynamic_cast<PCBNEW_SETTINGS*>( Kiface().KifaceSettings() );
3123
3124 if( cfg )
3125 footprint->Flip( footprint->GetPosition(), cfg->m_FlipDirection );
3126 else
3127 footprint->Flip( footprint->GetPosition(), FLIP_DIRECTION::TOP_BOTTOM );
3128 }
3129
3130 // Detach it from the board and its group
3131 footprint->SetParent( nullptr );
3132 footprint->SetParentGroup( nullptr );
3133
3134 wxLogTrace( traceKicadPcbPlugin, wxT( "Creating s-expr footprint file '%s'." ), fullPath );
3135 m_cache->GetFootprints().insert( footprintName,
3136 new FP_CACHE_ENTRY( footprint,
3137 WX_FILENAME( fn.GetPath(), fullName ) ) );
3138 m_cache->Save( footprint );
3139}
3140
3141
3142void PCB_IO_KICAD_SEXPR::FootprintDelete( const wxString& aLibraryPath,
3143 const wxString& aFootprintName,
3144 const std::map<std::string, UTF8>* aProperties )
3145{
3146 init( aProperties );
3147
3148 validateCache( aLibraryPath );
3149
3150 if( !m_cache->IsWritable() )
3151 {
3152 THROW_IO_ERROR( wxString::Format( _( "Library '%s' is read only." ),
3153 aLibraryPath.GetData() ) );
3154 }
3155
3156 m_cache->Remove( aFootprintName );
3157}
3158
3159
3160
3161long long PCB_IO_KICAD_SEXPR::GetLibraryTimestamp( const wxString& aLibraryPath ) const
3162{
3163 return FP_CACHE::GetTimestamp( aLibraryPath );
3164}
3165
3166
3167void PCB_IO_KICAD_SEXPR::CreateLibrary( const wxString& aLibraryPath,
3168 const std::map<std::string, UTF8>* aProperties )
3169{
3170 if( wxDir::Exists( aLibraryPath ) )
3171 {
3172 THROW_IO_ERROR( wxString::Format( _( "Cannot overwrite library path '%s'." ),
3173 aLibraryPath.GetData() ) );
3174 }
3175
3176 init( aProperties );
3177
3178 delete m_cache;
3179 m_cache = new FP_CACHE( this, aLibraryPath );
3180 m_cache->Save();
3181}
3182
3183
3184bool PCB_IO_KICAD_SEXPR::DeleteLibrary( const wxString& aLibraryPath,
3185 const std::map<std::string, UTF8>* aProperties )
3186{
3187 wxFileName fn;
3188 fn.SetPath( aLibraryPath );
3189
3190 // Return if there is no library path to delete.
3191 if( !fn.DirExists() )
3192 return false;
3193
3194 if( !fn.IsDirWritable() )
3195 {
3196 THROW_IO_ERROR( wxString::Format( _( "Insufficient permissions to delete folder '%s'." ),
3197 aLibraryPath.GetData() ) );
3198 }
3199
3200 wxDir dir( aLibraryPath );
3201
3202 if( dir.HasSubDirs() )
3203 {
3204 THROW_IO_ERROR( wxString::Format( _( "Library folder '%s' has unexpected sub-folders." ),
3205 aLibraryPath.GetData() ) );
3206 }
3207
3208 // All the footprint files must be deleted before the directory can be deleted.
3209 if( dir.HasFiles() )
3210 {
3211 unsigned i;
3212 wxFileName tmp;
3213 wxArrayString files;
3214
3215 wxDir::GetAllFiles( aLibraryPath, &files );
3216
3217 for( i = 0; i < files.GetCount(); i++ )
3218 {
3219 tmp = files[i];
3220
3221 if( tmp.GetExt() != FILEEXT::KiCadFootprintFileExtension )
3222 {
3223 THROW_IO_ERROR( wxString::Format( _( "Unexpected file '%s' found in library "
3224 "path '%s'." ),
3225 files[i].GetData(),
3226 aLibraryPath.GetData() ) );
3227 }
3228 }
3229
3230 for( i = 0; i < files.GetCount(); i++ )
3231 wxRemoveFile( files[i] );
3232 }
3233
3234 wxLogTrace( traceKicadPcbPlugin, wxT( "Removing footprint library '%s'." ),
3235 aLibraryPath.GetData() );
3236
3237 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
3238 // we don't want that. we want bare metal portability with no UI here.
3239 if( !wxRmdir( aLibraryPath ) )
3240 {
3241 THROW_IO_ERROR( wxString::Format( _( "Footprint library '%s' cannot be deleted." ),
3242 aLibraryPath.GetData() ) );
3243 }
3244
3245 // For some reason removing a directory in Windows is not immediately updated. This delay
3246 // prevents an error when attempting to immediately recreate the same directory when over
3247 // writing an existing library.
3248#ifdef __WINDOWS__
3249 wxMilliSleep( 250L );
3250#endif
3251
3252 if( m_cache && !m_cache->IsPath( aLibraryPath ) )
3253 {
3254 delete m_cache;
3255 m_cache = nullptr;
3256 }
3257
3258 return true;
3259}
3260
3261
3262bool PCB_IO_KICAD_SEXPR::IsLibraryWritable( const wxString& aLibraryPath )
3263{
3264 init( nullptr );
3265
3266 validateCache( aLibraryPath );
3267
3268 return m_cache->IsWritable();
3269}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:112
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
@ LT_FRONT
Definition board.h:187
@ LT_BACK
Definition board.h:188
@ ZLO_FORCE_FLASHED
Definition board_item.h:69
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
bool SaveImageData(wxOutputStream &aOutStream) const
Write the bitmap data to aOutStream.
wxImage * GetImageData()
Definition bitmap_base.h:68
TEARDROP_PARAMETERS & GetTeardropParams()
Container for design settings for a BOARD object.
const VECTOR2I & GetGridOrigin() const
int GetBoardThickness() const
The full thickness of the board including copper and masks.
const VECTOR2I & GetAuxOrigin() const
BOARD_STACKUP & GetStackupDescriptor()
ZONE_SETTINGS & GetDefaultZoneSettings()
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:79
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
Definition board_item.h:232
virtual bool IsKnockout() const
Definition board_item.h:319
bool IsLocked() const override
virtual const BOARD * GetBoard() const
Return the BOARD in which this BOARD_ITEM resides, or NULL if none.
FOOTPRINT * GetParentFootprint() const
VECTOR2I GetFPRelativePosition() const
Manage layers needed to make a physical board.
void FormatBoardStackup(OUTPUTFORMATTER *aFormatter, const BOARD *aBoard) const
Write the stackup info on board file.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:317
EMBEDDED_FILES * GetEmbeddedFiles() override
Definition board.cpp:2710
const GENERATORS & Generators() const
Definition board.h:364
void SetFileName(const wxString &aFileName)
Definition board.h:352
const PCB_POINTS & Points() const
Definition board.h:372
const PAGE_INFO & GetPageSettings() const
Definition board.h:741
const ZONES & Zones() const
Definition board.h:362
const GROUPS & Groups() const
The groups must maintain the following invariants.
Definition board.h:391
LAYER_T GetLayerType(PCB_LAYER_ID aLayer) const
Return the type of the copper layer given by aLayer.
Definition board.cpp:746
TITLE_BLOCK & GetTitleBlock()
Definition board.h:747
int GetCopperLayerCount() const
Definition board.cpp:875
const std::map< wxString, wxString > & GetProperties() const
Definition board.h:395
const FOOTPRINTS & Footprints() const
Definition board.h:358
const TRACKS & Tracks() const
Definition board.h:356
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition board.h:744
bool LegacyTeardrops() const
Definition board.h:1318
wxString GroupsSanityCheck(bool repair=false)
Consistency check of internal m_groups structure.
Definition board.cpp:2918
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition board.cpp:1040
const LSET & GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
Definition board.cpp:923
const DRAWINGS & Drawings() const
Definition board.h:360
A lightweight representation of a component class.
const std::vector< COMPONENT_CLASS * > & GetConstituentClasses() const
Fetches a vector of the constituent classes for this (effective) class.
double AsDegrees() const
Definition eda_angle.h:116
bool IsZero() const
Definition eda_angle.h:136
EDA_ANGLE Normalize720()
Definition eda_angle.h:279
const LIB_ID & GetDesignBlockLibId() const
Definition eda_group.h:73
std::unordered_set< EDA_ITEM * > & GetItems()
Definition eda_group.h:54
wxString GetName() const
Definition eda_group.h:51
bool HasDesignBlockLink() const
Definition eda_group.h:70
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
const KIID m_Uuid
Definition eda_item.h:516
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
virtual void SetParentGroup(EDA_GROUP *aGroup)
Definition eda_item.h:115
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.h:113
const VECTOR2I & GetBezierC2() const
Definition eda_shape.h:258
FILL_T GetFillMode() const
Definition eda_shape.h:142
SHAPE_POLY_SET & GetPolyShape()
Definition eda_shape.h:337
SHAPE_T GetShape() const
Definition eda_shape.h:168
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:215
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:173
wxString SHAPE_T_asString() const
const VECTOR2I & GetBezierC1() const
Definition eda_shape.h:255
int GetCornerRadius() const
bool IsPolyShapeValid() const
VECTOR2I GetArcMid() const
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:79
const VECTOR2I & GetTextPos() const
Definition eda_text.h:272
const EDA_ANGLE & GetTextAngle() const
Definition eda_text.h:146
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:97
bool IsKeepUpright() const
Definition eda_text.h:205
virtual bool IsVisible() const
Definition eda_text.h:186
KIFONT::FONT * GetFont() const
Definition eda_text.h:246
std::vector< std::unique_ptr< KIFONT::GLYPH > > * GetRenderCache(const KIFONT::FONT *aFont, const wxString &forResolvedText, const VECTOR2I &aOffset={ 0, 0 }) const
Definition eda_text.cpp:685
virtual EDA_ANGLE GetDrawRotation() const
Definition eda_text.h:376
virtual wxString GetShownText(bool aAllowExtraText, int aDepth=0) const
Return the string actually shown after processing of the base text.
Definition eda_text.h:108
int GetTextThickness() const
Definition eda_text.h:127
bool IsEmpty() const
void WriteEmbeddedFiles(OUTPUTFORMATTER &aOut, bool aWriteData) const
Output formatter for the embedded files.
void ClearEmbeddedFiles(bool aDeleteFiles=true)
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
const std::map< wxString, EMBEDDED_FILE * > & EmbeddedFileMap() const
bool GetAreFontsEmbedded() const
A LINE_READER that reads from an open file.
Definition richio.h:185
void Rewind()
Rewind the file and resets the line number back to zero.
Definition richio.h:234
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:249
bool GetDuplicatePadNumbersAreJumpers() const
Definition footprint.h:851
bool AllowSolderMaskBridges() const
Definition footprint.h:333
void SetFPID(const LIB_ID &aFPID)
Definition footprint.h:270
wxString GetLibDescription() const
Definition footprint.h:278
ZONE_CONNECTION GetLocalZoneConnection() const
Definition footprint.h:309
EDA_ANGLE GetOrientation() const
Definition footprint.h:248
ZONES & Zones()
Definition footprint.h:230
PCB_POINTS & Points()
Definition footprint.h:236
void SetOrientation(const EDA_ANGLE &aNewAngle)
wxString GetSheetname() const
Definition footprint.h:287
std::optional< int > GetLocalSolderPasteMargin() const
Definition footprint.h:302
EDA_ITEM * Clone() const override
Invoke a function on all children.
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:697
std::optional< int > GetLocalClearance() const
Definition footprint.h:296
std::vector< std::set< wxString > > & JumperPadGroups()
Each jumper pad group is a set of pad numbers that should be treated as internally connected.
Definition footprint.h:858
std::deque< PAD * > & Pads()
Definition footprint.h:224
int GetAttributes() const
Definition footprint.h:327
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition footprint.h:257
LSET GetPrivateLayers() const
Definition footprint.h:164
bool AllowMissingCourtyard() const
Definition footprint.h:330
wxString GetSheetfile() const
Definition footprint.h:290
const std::vector< wxString > & GetNetTiePadGroups() const
Definition footprint.h:382
const LIB_ID & GetFPID() const
Definition footprint.h:269
bool IsLocked() const override
Definition footprint.h:454
const LSET & GetStackupLayers() const
Definition footprint.h:325
PCB_FIELD & Reference()
Definition footprint.h:698
bool IsNetTie() const
Definition footprint.h:340
std::optional< double > GetLocalSolderPasteMarginRatio() const
Definition footprint.h:305
void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection) override
Flip this object, i.e.
GROUPS & Groups()
Definition footprint.h:233
wxString GetFilters() const
Definition footprint.h:293
const wxArrayString * GetInitialComments() const
Return the initial comments block or NULL if none, without transfer of ownership.
Definition footprint.h:977
void GetFields(std::vector< PCB_FIELD * > &aVector, bool aVisibleOnly) const
Populate a std::vector with PCB_TEXTs.
std::vector< FP_3DMODEL > & Models()
Definition footprint.h:241
BOARD_ITEM * Duplicate(bool addToParentGroup, BOARD_COMMIT *aCommit=nullptr) const override
Create a copy of this BOARD_ITEM.
const COMPONENT_CLASS * GetStaticComponentClass() const
Returns the component class for this footprint.
const KIID_PATH & GetPath() const
Definition footprint.h:284
std::optional< int > GetLocalSolderMaskMargin() const
Definition footprint.h:299
wxString GetKeywords() const
Definition footprint.h:281
EMBEDDED_FILES * GetEmbeddedFiles() override
Definition footprint.h:1005
FOOTPRINT_STACKUP GetStackupMode() const
Definition footprint.h:318
bool IsPlaced() const
Definition footprint.h:477
VECTOR2I GetPosition() const override
Definition footprint.h:245
DRAWINGS & GraphicalItems()
Definition footprint.h:227
Helper class for creating a footprint library cache.
std::unique_ptr< FOOTPRINT > m_footprint
WX_FILENAME m_filename
FP_CACHE_ENTRY(FOOTPRINT *aFootprint, const WX_FILENAME &aFileName)
const WX_FILENAME & GetFileName() const
std::unique_ptr< FOOTPRINT > & GetFootprint()
static long long GetTimestamp(const wxString &aLibPath)
Generate a timestamp representing all source files in the cache (including the parent directory).
boost::ptr_map< wxString, FP_CACHE_ENTRY > m_footprints
PCB_IO_KICAD_SEXPR * m_owner
bool IsModified()
Return true if the cache is not up-to-date.
long long m_cache_timestamp
wxString m_lib_raw_path
void SetPath(const wxString &aPath)
wxFileName m_lib_path
bool IsPath(const wxString &aPath) const
Check if aPath is the same as the current cache path.
void Save(FOOTPRINT *aFootprintFilter=nullptr)
Save the footprint cache or a single footprint from it to disk.
FP_CACHE(PCB_IO_KICAD_SEXPR *aOwner, const wxString &aLibraryPath)
boost::ptr_map< wxString, FP_CACHE_ENTRY > & GetFootprints()
void Remove(const wxString &aFootprintName)
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition io_base.h:223
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
APP_SETTINGS_BASE * KifaceSettings() const
Definition kiface_base.h:95
virtual bool IsOutline() const
Definition font.h:139
virtual void SetLineWidth(float aLineWidth)
Set the line width.
virtual wxString GetClass() const =0
Return the class name.
wxString AsString() const
Definition kiid.cpp:356
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:49
UTF8 Format() const
Definition lib_id.cpp:119
const UTF8 & GetLibItemName() const
Definition lib_id.h:102
An abstract class from which implementation specific LINE_READERs may be derived to read single lines...
Definition richio.h:93
LSEQ is a sequence (and therefore also a set) of PCB_LAYER_IDs.
Definition lseq.h:47
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
LSEQ CuStack() const
Return a sequence of copper layers in starting from the front/top and extending to the back/bottom.
Definition lset.cpp:246
LSEQ TechAndUserUIOrder() const
Return the technical and user layers in the order shown in layer widget.
Definition lset.cpp:259
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:296
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:582
static LSET AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:591
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:188
Handle the data for a net.
Definition netinfo.h:54
static const int UNCONNECTED
Constant that holds the "unconnected net" number (typically 0) all items "connected" to this net are ...
Definition netinfo.h:365
A PADSTACK defines the characteristics of a single or multi-layer pad, in the IPC sense of the word.
Definition padstack.h:125
std::optional< int > & Clearance(PCB_LAYER_ID aLayer=F_Cu)
MASK_LAYER_PROPS & FrontOuterLayers()
Definition padstack.h:320
std::optional< int > & ThermalSpokeWidth(PCB_LAYER_ID aLayer=F_Cu)
EDA_ANGLE ThermalSpokeAngle(PCB_LAYER_ID aLayer=F_Cu) const
std::optional< int > & ThermalGap(PCB_LAYER_ID aLayer=F_Cu)
DRILL_PROPS & Drill()
Definition padstack.h:308
const VECTOR2I & Size(PCB_LAYER_ID aLayer) const
@ NORMAL
Shape is the same on all layers.
Definition padstack.h:139
@ FRONT_INNER_BACK
Up to three shapes can be defined (F_Cu, inner copper layers, B_Cu)
Definition padstack.h:140
MODE Mode() const
Definition padstack.h:295
MASK_LAYER_PROPS & BackOuterLayers()
Definition padstack.h:323
static constexpr PCB_LAYER_ID ALL_LAYERS
! Temporary layer identifier to identify code that is not padstack-aware
Definition padstack.h:145
static constexpr PCB_LAYER_ID INNER_LAYERS
! The layer identifier to use for "inner layers" on top/inner/bottom padstacks
Definition padstack.h:148
std::optional< ZONE_CONNECTION > & ZoneConnection(PCB_LAYER_ID aLayer=F_Cu)
Definition pad.h:54
PAD_PROP GetProperty() const
Definition pad.h:443
bool GetRemoveUnconnected() const
Definition pad.h:733
LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition pad.h:437
const std::vector< std::shared_ptr< PCB_SHAPE > > & GetPrimitives(PCB_LAYER_ID aLayer) const
Accessor to the basic shape list for custom-shaped pads.
Definition pad.h:365
const ZONE_LAYER_OVERRIDE & GetZoneLayerOverride(PCB_LAYER_ID aLayer) const
Definition pad.cpp:221
std::optional< double > GetLocalSolderPasteMarginRatio() const
Definition pad.h:475
const wxString & GetPinType() const
Definition pad.h:153
const VECTOR2I & GetDrillSize() const
Definition pad.h:305
PAD_ATTRIB GetAttribute() const
Definition pad.h:440
const wxString & GetPinFunction() const
Definition pad.h:147
const wxString & GetNumber() const
Definition pad.h:136
const VECTOR2I & GetDelta(PCB_LAYER_ID aLayer) const
Definition pad.h:299
EDA_ANGLE GetThermalSpokeAngle() const
Definition pad.h:625
double GetRoundRectRadiusRatio(PCB_LAYER_ID aLayer) const
Definition pad.h:671
PAD_SHAPE GetShape(PCB_LAYER_ID aLayer) const
Definition pad.h:195
bool GetKeepTopBottom() const
Definition pad.h:748
int GetPadToDieDelay() const
Definition pad.h:456
std::optional< int > GetLocalClearance() const override
Return any local clearances set in the "classic" (ie: pre-rule) system.
Definition pad.h:458
const PADSTACK & Padstack() const
Definition pad.h:321
const VECTOR2I & GetOffset(PCB_LAYER_ID aLayer) const
Definition pad.h:317
EDA_ANGLE GetOrientation() const
Return the rotation angle of the pad.
Definition pad.h:408
PADSTACK::CUSTOM_SHAPE_ZONE_MODE GetCustomShapeInZoneOpt() const
Definition pad.h:221
PAD_DRILL_SHAPE GetDrillShape() const
Definition pad.h:422
int GetChamferPositions(PCB_LAYER_ID aLayer) const
Definition pad.h:711
std::optional< int > GetLocalSolderPasteMargin() const
Definition pad.h:468
std::optional< int > GetLocalSolderMaskMargin() const
Definition pad.h:461
double GetChamferRectRatio(PCB_LAYER_ID aLayer) const
Definition pad.h:694
std::optional< int > GetLocalThermalSpokeWidthOverride() const
Definition pad.h:609
ZONE_CONNECTION GetLocalZoneConnection() const
Definition pad.h:486
int GetLocalThermalGapOverride(wxString *aSource) const
Definition pad.cpp:1333
PAD_SHAPE GetAnchorPadShape(PCB_LAYER_ID aLayer) const
Definition pad.h:213
int GetPadToDieLength() const
Definition pad.h:453
const VECTOR2I & GetSize(PCB_LAYER_ID aLayer) const
Definition pad.h:264
void Format(OUTPUTFORMATTER *aFormatter) const
Output the page class to aFormatter in s-expression form.
FLIP_DIRECTION m_FlipDirection
const VECTOR2I & GetMid() const
Definition pcb_track.h:345
Abstract dimension API.
wxString GetOverrideText() const
wxString GetSuffix() const
int GetLineThickness() const
DIM_TEXT_POSITION GetTextPositionMode() const
bool GetKeepTextAligned() const
DIM_PRECISION GetPrecision() const
wxString GetPrefix() const
DIM_UNITS_MODE GetUnitsMode() const
DIM_UNITS_FORMAT GetUnitsFormat() const
virtual const VECTOR2I & GetStart() const
The dimension's origin is the first feature point for the dimension.
DIM_ARROW_DIRECTION GetArrowDirection() const
bool GetSuppressZeroes() const
int GetExtensionOffset() const
int GetArrowLength() const
bool GetOverrideTextEnabled() const
virtual const VECTOR2I & GetEnd() const
For better understanding of the points that make a dimension:
int GetHeight() const
int GetExtensionHeight() const
Mark the center of a circle or arc with a cross shape.
A leader is a dimension-like object pointing to a specific point.
DIM_TEXT_BORDER GetTextBorder() const
An orthogonal dimension is like an aligned dimension, but the extension lines are locked to the X or ...
A radial dimension indicates either the radius or diameter of an arc or circle.
int GetLeaderLength() const
virtual const STRING_ANY_MAP GetProperties() const
virtual wxString GetGeneratorType() const
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:53
Read a Pcbnew s-expression formatted LINE_READER object and returns the appropriate BOARD_ITEM object...
bool IsTooRecent()
Return whether a version number, if any was parsed, was too recent.
bool IsValidBoardHeader()
Partially parse the input and check if it matches expected header.
wxString GetRequiredVersion()
Return a string representing the version of KiCad required to open this file.
A #PLUGIN derivation for saving and loading Pcbnew s-expression formatted files.
BOARD * DoLoad(LINE_READER &aReader, BOARD *aAppendToMe, const std::map< std::string, UTF8 > *aProperties, PROGRESS_REPORTER *aProgressReporter, unsigned aLineCount)
bool CanReadBoard(const wxString &aFileName) const override
Checks if this PCB_IO can read the specified board file.
void formatProperties(const BOARD *aBoard) const
formats the Nets and Netclasses
FOOTPRINT * ImportFootprint(const wxString &aFootprintPath, wxString &aFootprintNameOut, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a single footprint from aFootprintPath and put its name in aFootprintNameOut.
void FootprintDelete(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete aFootprintName from the library at aLibraryPath.
long long GetLibraryTimestamp(const wxString &aLibraryPath) const override
Generate a timestamp representing all the files in the library (including the library directory).
bool IsLibraryWritable(const wxString &aLibraryPath) override
Return true if the library at aLibraryPath is writable.
void formatTeardropParameters(const TEARDROP_PARAMETERS &tdParams) const
bool DeleteLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete an existing library and returns true, or if library does not exist returns false,...
NETINFO_MAPPING * m_mapping
mapping for net codes, so only not empty net codes are stored with consecutive integers as net codes
void formatNetInformation(const BOARD *aBoard) const
formats the Nets and Netclasses
const FOOTPRINT * GetEnumeratedFootprint(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
A version of FootprintLoad() for use after FootprintEnumerate() for more efficient cache management.
void CreateLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Create a new empty library at aLibraryPath empty.
void FootprintEnumerate(wxArrayString &aFootprintNames, const wxString &aLibraryPath, bool aBestEfforts, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Return a list of footprint names contained within the library at aLibraryPath.
void formatPolyPts(const SHAPE_LINE_CHAIN &outline, const FOOTPRINT *aParentFP=nullptr) const
FP_CACHE * m_cache
Footprint library cache.
void formatBoardLayers(const BOARD *aBoard) const
formats the board layer information
FOOTPRINT * FootprintLoad(const wxString &aLibraryPath, const wxString &aFootprintName, bool aKeepUUID=false, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a footprint having aFootprintName from the aLibraryPath containing a library format that this PC...
BOARD * LoadBoard(const wxString &aFileName, BOARD *aAppendToMe, const std::map< std::string, UTF8 > *aProperties=nullptr, PROJECT *aProject=nullptr) override
Load information from some input file format that this PCB_IO implementation knows about into either ...
bool FootprintExists(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Check for the existence of a footprint.
void FootprintSave(const wxString &aLibraryPath, const FOOTPRINT *aFootprint, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aFootprint to an existing library located at aLibraryPath.
void format(const BOARD *aBoard) const
void SaveBoard(const wxString &aFileName, BOARD *aBoard, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aBoard to a storage file in a format that this PCB_IO implementation knows about or it can be u...
void formatLayers(LSET aLayerMask, bool aEnumerateLayers, bool aIsZone=false) const
void formatGeneral(const BOARD *aBoard) const
formats the General section of the file
void formatSetup(const BOARD *aBoard) const
formats the board setup information
std::function< bool(wxString aTitle, int aIcon, wxString aMsg, wxString aAction)> m_queryUserCallback
BOARD_ITEM * Parse(const wxString &aClipboardSourceInput)
void init(const std::map< std::string, UTF8 > *aProperties)
STRING_FORMATTER m_sf
void Format(const BOARD_ITEM *aItem) const
Output aItem to aFormatter in s-expression format.
void formatLayer(PCB_LAYER_ID aLayer, bool aIsKnockout=false) const
void formatHeader(const BOARD *aBoard) const
writes everything that comes before the board_items, like settings and layers etc
const FOOTPRINT * getFootprint(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties, bool checkModified)
PCB_IO_KICAD_SEXPR(int aControlFlags=CTL_FOR_BOARD)
OUTPUTFORMATTER * m_out
output any Format()s to this, no ownership
void validateCache(const wxString &aLibraryPath, bool checkModified=true)
void formatRenderCache(const EDA_TEXT *aText) const
LINE_READER * m_reader
no ownership
BOARD * m_board
The board BOARD being worked on, no ownership here.
Definition pcb_io.h:324
virtual bool CanReadBoard(const wxString &aFileName) const
Checks if this PCB_IO can read the specified board file.
Definition pcb_io.cpp:42
PCB_IO(const wxString &aName)
Definition pcb_io.h:318
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:327
void Format(OUTPUTFORMATTER *aFormatter) const
A PCB_POINT is a 0-dimensional point that is used to mark a position on a PCB, or more usually a foot...
Definition pcb_point.h:43
int GetSize() const
Definition pcb_point.h:62
VECTOR2I GetPosition() const override
Definition pcb_point.h:59
Object to handle a bitmap image that can be inserted in a PCB.
VECTOR2I GetPosition() const override
Get the position of the image (this is the center of the image).
REFERENCE_IMAGE & GetReferenceImage()
std::optional< int > GetLocalSolderMaskMargin() const
Definition pcb_shape.h:198
bool HasSolderMask() const
Definition pcb_shape.h:195
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
STROKE_PARAMS GetStroke() const override
Definition pcb_shape.h:91
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:71
bool StrokeRows() const
Definition pcb_table.h:102
int GetRowCount() const
Definition pcb_table.h:119
bool StrokeHeaderSeparator() const
Definition pcb_table.h:60
bool StrokeColumns() const
Definition pcb_table.h:99
bool StrokeExternal() const
Definition pcb_table.h:57
std::vector< PCB_TABLECELL * > GetCells() const
Definition pcb_table.h:154
int GetColCount() const
Definition pcb_table.h:117
const STROKE_PARAMS & GetSeparatorsStroke() const
Definition pcb_table.h:81
const STROKE_PARAMS & GetBorderStroke() const
Definition pcb_table.h:63
int GetColWidth(int aCol) const
Definition pcb_table.h:126
int GetRowHeight(int aRow) const
Definition pcb_table.h:136
int GetShape() const
Definition pcb_target.h:58
int GetWidth() const
Definition pcb_target.h:64
int GetSize() const
Definition pcb_target.h:61
VECTOR2I GetPosition() const override
Definition pcb_target.h:55
bool IsBorderEnabled() const
Disables the border, this is done by changing the stroke internally.
int GetMarginBottom() const
Definition pcb_textbox.h:92
int GetMarginLeft() const
Definition pcb_textbox.h:89
int GetMarginRight() const
Definition pcb_textbox.h:91
int GetMarginTop() const
Definition pcb_textbox.h:90
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
bool HasSolderMask() const
Definition pcb_track.h:176
std::optional< int > GetLocalSolderMaskMargin() const
Definition pcb_track.h:179
const VECTOR2I & GetStart() const
Definition pcb_track.h:152
const VECTOR2I & GetEnd() const
Definition pcb_track.h:149
virtual int GetWidth() const
Definition pcb_track.h:146
A progress reporter interface for use in multi-threaded environments.
Container for project specific data.
Definition project.h:65
A REFERENCE_IMAGE is a wrapper around a BITMAP_IMAGE that is displayed in an editor as a reference fo...
const BITMAP_BASE & GetImage() const
Get the underlying image.
double GetImageScale() const
const VECTOR2I & GetArcMid() const
Definition shape_arc.h:118
const VECTOR2I & GetP1() const
Definition shape_arc.h:117
const VECTOR2I & GetP0() const
Definition shape_arc.h:116
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
const SHAPE_ARC & Arc(size_t aArc) const
int PointCount() const
Return the number of points (vertices) in this line chain.
ssize_t ArcIndex(size_t aSegment) const
Return the arc index for the given segment index.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
Represent a set of closed polygons.
POLYGON & Polygon(int aIndex)
Return the aIndex-th subpolygon in the set.
std::vector< SHAPE_LINE_CHAIN > POLYGON
represents a single polygon outline with holes.
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
Is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition richio.h:253
void Format(OUTPUTFORMATTER *out, const EDA_IU_SCALE &aIuScale) const
TEARDROP_PARAMETARS is a helper class to handle parameters needed to build teardrops for a board thes...
double m_BestWidthRatio
The height of a teardrop as ratio between height and size of pad/via.
int m_TdMaxLen
max allowed length for teardrops in IU. <= 0 to disable
bool m_AllowUseTwoTracks
True to create teardrops using 2 track segments if the first in too small.
int m_TdMaxWidth
max allowed height for teardrops in IU. <= 0 to disable
double m_BestLengthRatio
The length of a teardrop as ratio between length and size of pad/via.
double m_WidthtoSizeFilterRatio
The ratio (H/D) between the via/pad size and the track width max value to create a teardrop 1....
bool m_TdOnPadsInZones
A filter to exclude pads inside zone fills.
bool m_Enabled
Flag to enable teardrops.
bool m_CurvedEdges
True if the teardrop should be curved.
virtual void Format(OUTPUTFORMATTER *aFormatter) const
Output the object to aFormatter in s-expression form.
const char * c_str() const
Definition utf8.h:109
wxString wx_str() const
Definition utf8.cpp:45
static REPORTER & GetInstance()
Definition reporter.cpp:190
A wrapper around a wxFileName which is much more performant with a subset of the API.
Definition wx_filename.h:50
void SetFullName(const wxString &aFileNameAndExtension)
static void ResolvePossibleSymlinks(wxFileName &aFilename)
wxString GetName() const
wxString GetFullPath() const
long long GetTimestamp()
std::map< PCB_LAYER_ID, ZONE_LAYER_PROPERTIES > m_LayerProperties
Handle a list of polygons defining a copper zone.
Definition zone.h:74
int GetHatchBorderAlgorithm() const
Definition zone.h:328
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:704
std::optional< int > GetLocalClearance() const override
Definition zone.cpp:814
bool GetDoNotAllowVias() const
Definition zone.h:720
ZONE_LAYER_PROPERTIES & LayerProperties(PCB_LAYER_ID aLayer)
Definition zone.h:145
const std::shared_ptr< SHAPE_POLY_SET > & GetFilledPolysList(PCB_LAYER_ID aLayer) const
Definition zone.h:600
wxString GetPlacementAreaSource() const
Definition zone.h:709
bool GetDoNotAllowPads() const
Definition zone.h:722
PLACEMENT_SOURCE_T GetPlacementAreaSourceType() const
Definition zone.h:711
bool GetDoNotAllowTracks() const
Definition zone.h:721
bool IsFilled() const
Definition zone.h:292
ISLAND_REMOVAL_MODE GetIslandRemovalMode() const
Definition zone.h:731
SHAPE_POLY_SET * Outline()
Definition zone.h:335
bool IsIsland(PCB_LAYER_ID aLayer, int aPolyIdx) const
Check if a given filled polygon is an insulated island.
Definition zone.cpp:1318
long long int GetMinIslandArea() const
Definition zone.h:734
const wxString & GetZoneName() const
Definition zone.h:163
int GetMinThickness() const
Definition zone.h:301
ZONE_CONNECTION GetPadConnection() const
Definition zone.h:298
int GetHatchThickness() const
Definition zone.h:310
double GetHatchHoleMinArea() const
Definition zone.h:325
bool GetPlacementAreaEnabled() const
Definition zone.h:706
bool IsTeardropArea() const
Definition zone.h:679
int GetThermalReliefSpokeWidth() const
Definition zone.h:245
int GetBorderHatchPitch() const
HatchBorder related methods.
Definition zone.h:744
ZONE_BORDER_DISPLAY_STYLE GetHatchStyle() const
Definition zone.h:589
EDA_ANGLE GetHatchOrientation() const
Definition zone.h:316
bool GetDoNotAllowFootprints() const
Definition zone.h:723
ZONE_FILL_MODE GetFillMode() const
Definition zone.h:224
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:136
int GetHatchGap() const
Definition zone.h:313
TEARDROP_TYPE GetTeardropAreaType() const
Definition zone.h:690
double GetHatchSmoothingValue() const
Definition zone.h:322
bool GetDoNotAllowZoneFills() const
Definition zone.h:719
int GetHatchSmoothingLevel() const
Definition zone.h:319
unsigned int GetCornerRadius() const
Definition zone.h:650
int GetCornerSmoothingType() const
Definition zone.h:646
bool IsOnCopperLayer() const override
Definition zone.cpp:499
PCB_LAYER_ID GetFirstLayer() const
Definition zone.cpp:481
int GetThermalReliefGap() const
Definition zone.h:234
unsigned GetAssignedPriority() const
Definition zone.h:126
int GetNumCorners(void) const
Access to m_Poly parameters.
Definition zone.h:519
static void SetReporter(REPORTER *aReporter)
Set the reporter to use for reporting font substitution warnings.
long long TimestampDir(const wxString &aDirPath, const wxString &aFilespec)
A copy of ConvertFileTimeToWx() because wxWidgets left it as a static function private to src/common/...
Definition common.cpp:604
This file is part of the common library.
#define CTL_OMIT_HYPERLINK
Omit the hyperlink attribute in .kicad_xxx files.
Definition ctl_flags.h:46
#define CTL_OMIT_UUIDS
Omit component unique ids (useless in library)
Definition ctl_flags.h:30
#define CTL_OMIT_FOOTPRINT_VERSION
Omit the version string from the (footprint) sexpr group.
Definition ctl_flags.h:39
#define CTL_OMIT_INITIAL_COMMENTS
Omit FOOTPRINT initial comments.
Definition ctl_flags.h:43
#define CTL_OMIT_LIBNAME
Omit lib alias when saving (used for board/not library).
Definition ctl_flags.h:37
#define CTL_OMIT_PATH
Omit component sheet time stamp (useless in library).
Definition ctl_flags.h:33
#define CTL_OMIT_AT
Omit position and rotation.
Definition ctl_flags.h:35
#define CTL_OMIT_PAD_NETS
Omit pads net names (useless in library).
Definition ctl_flags.h:29
#define CTL_OMIT_COLOR
Omit the color attribute in .kicad_xxx files.
Definition ctl_flags.h:45
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:411
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:413
static constexpr EDA_ANGLE ANGLE_45
Definition eda_angle.h:412
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
@ SEGMENT
Definition eda_shape.h:45
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:46
@ REVERSE_HATCH
Definition eda_shape.h:62
@ HATCH
Definition eda_shape.h:61
@ FILLED_SHAPE
Fill with object color.
Definition eda_shape.h:58
@ CROSS_HATCH
Definition eda_shape.h:63
@ FP_SMD
Definition footprint.h:82
@ FP_DNP
Definition footprint.h:87
@ FP_EXCLUDE_FROM_POS_FILES
Definition footprint.h:83
@ FP_BOARD_ONLY
Definition footprint.h:85
@ FP_EXCLUDE_FROM_BOM
Definition footprint.h:84
@ FP_THROUGH_HOLE
Definition footprint.h:81
@ EXPAND_INNER_LAYERS
The 'normal' stackup handling, where there is a single inner layer (In1) and rule areas using it expa...
Definition footprint.h:96
static const std::string KiCadFootprintFileExtension
const wxChar *const traceKicadPcbPlugin
Flag to enable GEDA PCB plugin debug output.
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
#define MAX_CU_LAYERS
Definition layer_ids.h:176
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
Definition layer_ids.h:674
bool IsExternalCopperLayer(int aLayerId)
Test whether a layer is an external (F_Cu or B_Cu) copper layer.
Definition layer_ids.h:685
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:60
@ F_CrtYd
Definition layer_ids.h:116
@ B_Adhes
Definition layer_ids.h:103
@ F_Paste
Definition layer_ids.h:104
@ F_Adhes
Definition layer_ids.h:102
@ B_Mask
Definition layer_ids.h:98
@ B_Cu
Definition layer_ids.h:65
@ F_Mask
Definition layer_ids.h:97
@ B_Paste
Definition layer_ids.h:105
@ F_Fab
Definition layer_ids.h:119
@ F_SilkS
Definition layer_ids.h:100
@ B_CrtYd
Definition layer_ids.h:115
@ User_1
Definition layer_ids.h:124
@ B_SilkS
Definition layer_ids.h:101
@ PCB_LAYER_ID_COUNT
Definition layer_ids.h:171
@ F_Cu
Definition layer_ids.h:64
@ B_Fab
Definition layer_ids.h:118
This file contains miscellaneous commonly used macros and functions.
#define UNIMPLEMENTED_FOR(type)
Definition macros.h:96
@ TOP_BOTTOM
Flip top to bottom (around the X axis)
Definition mirror.h:29
KICOMMON_API std::string FormatInternalUnits(const EDA_IU_SCALE &aIuScale, int aValue)
Converts aValue from internal units to a string appropriate for writing to file.
KICOMMON_API std::string FormatAngle(const EDA_ANGLE &aAngle)
Convert aAngle from board units to a string appropriate for writing to file.
void FormatOptBool(OUTPUTFORMATTER *aOut, const wxString &aKey, std::optional< bool > aValue)
Writes an optional boolean to the formatter.
void FormatUuid(OUTPUTFORMATTER *aOut, const KIID &aUuid)
void FormatStreamData(OUTPUTFORMATTER &aOut, const wxStreamBuffer &aStream)
Write binary data to the formatter as base 64 encoded string.
void FormatBool(OUTPUTFORMATTER *aOut, const wxString &aKey, bool aValue)
Writes a boolean to the formatter, in the style (aKey [yes|no])
@ NPTH
like PAD_PTH, but not plated mechanical use only, no connection allowed
Definition padstack.h:87
@ SMD
Smd pad, appears on the solder paste layer (default)
Definition padstack.h:83
@ PTH
Plated through hole pad.
Definition padstack.h:82
@ CONN
Like smd, does not appear on the solder paste layer (default) Note: also has a special attribute in G...
Definition padstack.h:84
@ CHAMFERED_RECT
Definition padstack.h:60
@ ROUNDRECT
Definition padstack.h:57
@ TRAPEZOID
Definition padstack.h:56
@ RECTANGLE
Definition padstack.h:54
@ FIDUCIAL_LOCAL
a fiducial (usually a smd) local to the parent footprint
Definition padstack.h:102
@ FIDUCIAL_GLBL
a fiducial (usually a smd) for the full board
Definition padstack.h:101
@ MECHANICAL
a pad used for mechanical support
Definition padstack.h:106
@ PRESSFIT
a PTH with a hole diameter with tight tolerances for press fit pin
Definition padstack.h:107
@ HEATSINK
a pad used as heat sink, usually in SMD footprints
Definition padstack.h:104
@ NONE
no special fabrication property
Definition padstack.h:99
@ TESTPOINT
a test point pad
Definition padstack.h:103
@ CASTELLATED
a pad with a castellated through hole
Definition padstack.h:105
@ BGA
Smd pad, used in BGA footprints.
Definition padstack.h:100
Class to handle a set of BOARD_ITEMs.
bool isDefaultTeardropParameters(const TEARDROP_PARAMETERS &tdParams)
std::string formatInternalUnits(int aValue)
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
#define CTL_FOR_BOARD
The zero arg constructor when PCB_PLUGIN is used for PLUGIN::Load() and PLUGIN::Save()ing a BOARD fil...
#define CTL_FOR_LIBRARY
Format output for a footprint library instead of clipboard or BOARD.
Pcbnew s-expression file format parser definition.
@ THROUGH
Definition pcb_track.h:67
@ BLIND_BURIED
Definition pcb_track.h:68
@ MICROVIA
Definition pcb_track.h:69
#define UNDEFINED_DRILL_DIAMETER
Definition pcb_track.h:109
PGM_BASE & Pgm()
The global program "get" accessor.
Definition pgm_base.cpp:913
see class PGM_BASE
bool ReplaceIllegalFileNameChars(std::string *aName, int aReplaceChar)
Checks aName for illegal file name characters.
std::string FormatDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 This function is intended in...
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Variant of PARSE_ERROR indicating that a syntax or related error was likely caused by a file generate...
std::optional< bool > is_capped
True if the drill hole should be capped.
Definition padstack.h:251
std::optional< bool > is_filled
True if the drill hole should be filled completely.
Definition padstack.h:250
std::optional< bool > has_covering
True if the pad on this side should have covering.
Definition padstack.h:236
std::optional< bool > has_solder_mask
True if this outer layer has mask (is not tented)
Definition padstack.h:234
std::optional< bool > has_plugging
True if the drill hole should be plugged on this side.
Definition padstack.h:237
A filename or source description, a problem input line, a line number, a byte offset,...
std::optional< VECTOR2I > hatching_offset
VECTOR2I center
const SHAPE_LINE_CHAIN chain
int delta
wxLogTrace helper definitions.
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition trigo.cpp:229
@ PCB_T
Definition typeinfo.h:82
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:88
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition typeinfo.h:105
@ PCB_DIM_LEADER_T
class PCB_DIM_LEADER, a leader dimension (graphic item)
Definition typeinfo.h:102
@ PCB_GENERATOR_T
class PCB_GENERATOR, generator on a layer
Definition typeinfo.h:91
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:97
@ PCB_DIM_CENTER_T
class PCB_DIM_CENTER, a center point marking (graphic item)
Definition typeinfo.h:103
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:110
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition typeinfo.h:93
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:107
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:92
@ PCB_REFERENCE_IMAGE_T
class PCB_REFERENCE_IMAGE, bitmap on a layer
Definition typeinfo.h:89
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:90
@ PCB_TARGET_T
class PCB_TARGET, a target (graphic item)
Definition typeinfo.h:106
@ PCB_TABLECELL_T
class PCB_TABLECELL, PCB_TEXTBOX for use in tables
Definition typeinfo.h:95
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:86
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:101
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:87
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:98
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:94
@ PCB_POINT_T
class PCB_POINT, a 0-dimensional point
Definition typeinfo.h:112
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:96
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:104
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:695
Definition of file extensions used in Kicad.
@ THERMAL
Use thermal relief for pads.
Definition zones.h:50
@ THT_THERMAL
Thermal relief only for THT pads.
Definition zones.h:52
@ NONE
Pads are not covered.
Definition zones.h:49
@ FULL
pads are covered by copper
Definition zones.h:51