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, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <wx/dir.h>
22#include <wx/ffile.h>
23#include <wx/log.h>
24#include <wx/msgdlg.h>
25#include <wx/mstream.h>
26
27#include <board.h>
29#include <callback_gal.h>
31#include <confirm.h>
32#include <core/leak_at_exit.h>
33#include <convert_basic_shapes_to_polygon.h> // for enum RECT_CHAMFER_POSITIONS definition
34#include <fmt/format.h>
35#include <font/fontconfig.h>
36#include <footprint.h>
37#include <gestfich.h>
39#include <kiface_base.h>
40#include <kiplatform/io.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_grid_item.h>
47#include <pcb_group.h>
50#include <pcb_3d_body.h>
52#include <pcb_point.h>
53#include <pcb_reference_image.h>
54#include <pcb_barcode.h>
55#include <pcb_shape.h>
56#include <pcb_drill_chart.h>
57#include <pcb_drill_map.h>
58#include <pcb_table.h>
59#include <pcb_tablecell.h>
60#include <pcb_target.h>
61#include <pcb_text.h>
62#include <pcb_textbox.h>
63#include <pcb_track.h>
64#include <pcbnew_settings.h>
65#include <pgm_base.h>
66#include <progress_reporter.h>
67#include <reporter.h>
68#include <string_utils.h>
69#include <trace_helpers.h>
71#include <zone.h>
72
73#include <build_version.h>
74#include <filter_reader.h>
75#include <ctl_flags.h>
76
77
78using namespace PCB_KEYS_T;
79
80
81FP_CACHE_ENTRY::FP_CACHE_ENTRY( FOOTPRINT* aFootprint, const WX_FILENAME& aFileName ) :
82 m_filename( aFileName ),
83 m_footprint( aFootprint )
84{ }
85
86
87FP_CACHE::FP_CACHE( PCB_IO_KICAD_SEXPR* aOwner, const wxString& aLibraryPath )
88{
89 m_owner = aOwner;
90 m_lib_raw_path = aLibraryPath;
91 m_lib_path.SetPath( aLibraryPath );
93 m_cache_dirty = true;
94}
95
96
97void FP_CACHE::Save( FOOTPRINT* aFootprintFilter )
98{
100
101 if( !m_lib_path.DirExists() && !m_lib_path.Mkdir() )
102 THROW_IO_ERRORF( _( "Cannot create footprint library '%s'." ), m_lib_raw_path );
103
104 if( !m_lib_path.IsDirWritable() )
105 THROW_IO_ERRORF( _( "Footprint library '%s' is read only." ), m_lib_raw_path );
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 WX_FILENAME fn = fpCacheEntry->GetFileName();
116 wxString fileName = fn.GetFullPath();
117
118 // Allow file output stream to go out of scope to close the file stream before
119 // renaming the file.
120 {
121 wxLogTrace( traceKicadPcbPlugin, wxT( "Writing library file '%s'." ), fileName );
122
123 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( fileName );
124
125 m_owner->SetOutputFormatter( &formatter );
126
127 m_owner->FormatFootprintLibFile( footprint.get() );
128 formatter.Finish();
129 }
130
132 }
133
134 if( m_lib_path.IsFileReadable() && m_lib_path.GetModificationTime().IsValid() )
135 m_cache_timestamp += m_lib_path.GetModificationTime().GetValue().GetValue();
136
137 // If we've saved the full cache, we clear the dirty flag.
138 if( !aFootprintFilter )
139 m_cache_dirty = false;
140}
141
142
144{
145 m_cache_dirty = false;
147
148 wxDir dir( m_lib_raw_path );
149
150 if( !dir.IsOpened() )
151 THROW_IO_ERRORF( _( "Footprint library '%s' not found." ), m_lib_raw_path );
152
153 wxString fullName;
154 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadFootprintFileExtension );
155
156 // wxFileName construction is egregiously slow. Construct it once and just swap out
157 // the filename thereafter.
158 WX_FILENAME fn( m_lib_raw_path, wxT( "dummyName" ) );
159
160 if( dir.GetFirst( &fullName, fileSpec ) )
161 {
162 wxString cacheError;
163
164 do
165 {
166 fn.SetFullName( fullName );
167
168 // Queue I/O errors so only files that fail to parse don't get loaded.
169 try
170 {
172 FILE_LINE_READER reader( fn.GetFullPath() );
173 PCB_IO_KICAD_SEXPR_PARSER parser( &reader, nullptr, nullptr );
174
175 parser.ParseFootprintLib( tmp );
176 wxString fpName = fn.GetName();
177
178 if( tmp.empty() )
179 THROW_IO_ERROR( wxEmptyString ); // caught locally, just below...
180
181 // The parser's entry has no file name, and saving uses the one cached here
182 FOOTPRINT* footprint = tmp.release( tmp.begin() )->GetFootprint().release();
183
184 footprint->SetFPID( LIB_ID( wxEmptyString, fpName ) );
185 m_footprints.insert( fpName, new FP_CACHE_ENTRY( footprint, fn ) );
186
187 // A warning leaves the footprint usable, and libraries load on worker threads that have no one to
188 // show a message to, so it is only traced
189 for( const wxString& warning : parser.GetParseWarnings() )
190 {
191 wxLogTrace( traceKicadPcbPlugin, wxT( "Warning in file '%s': %s" ), fn.GetFullPath(), warning );
192 }
193 }
194 catch( const IO_ERROR& ioe )
195 {
196 if( !cacheError.IsEmpty() )
197 cacheError += wxT( "\n\n" );
198
199 cacheError += wxString::Format( _( "Unable to read file '%s'" ) + '\n',
200 fn.GetFullPath() );
201 cacheError += ioe.What();
202 }
203 } while( dir.GetNext( &fullName ) );
204
206
207 if( !cacheError.IsEmpty() )
208 THROW_IO_ERROR( cacheError );
209 }
210}
211
212
213void FP_CACHE::Remove( const wxString& aFootprintName )
214{
215 auto it = m_footprints.find( aFootprintName );
216
217 if( it == m_footprints.end() )
218 {
219 THROW_IO_ERRORF( _( "Library '%s' has no footprint '%s'." ),
221 aFootprintName );
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 KIPLATFORM::IO::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 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( aFileName );
302 FormatBoardToFormatter( &formatter, &aBoard, aProperties );
303 formatter.Finish();
304}
305
306
308 const std::map<std::string, UTF8>* aProperties )
309{
310 init( aProperties );
311
312 m_board = aBoard; // after init()
313
314 // If the user wants fonts embedded, make sure that they are added to the board. Otherwise,
315 // remove any fonts that were previously embedded.
316 if( m_board->GetAreFontsEmbedded() )
317 m_board->EmbedFonts();
318 else
319 m_board->GetEmbeddedFiles()->ClearEmbeddedFonts();
320
321 m_out = aOut;
322
323 m_out->Print( "(kicad_pcb (version %d) (generator \"pcbnew\") (generator_version %s)", SEXPR_BOARD_FILE_VERSION,
324 m_out->Quotew( GetMajorMinorVersion() ).c_str() );
325
326 Format( aBoard );
327
328 m_out->Print( ")" );
329
330 m_out = nullptr;
331}
332
333
334BOARD_ITEM* PCB_IO_KICAD_SEXPR::Parse( const wxString& aClipboardSourceInput )
335{
336 std::string input = TO_UTF8( aClipboardSourceInput );
337
338 STRING_LINE_READER reader( input, wxT( "clipboard" ) );
339 PCB_IO_KICAD_SEXPR_PARSER parser( &reader, nullptr, m_queryUserCallback );
340
341 try
342 {
343 return parser.Parse();
344 }
345 catch( const PARSE_ERROR& parse_error )
346 {
347 if( parser.IsTooRecent() )
348 throw FUTURE_FORMAT_ERROR( parse_error, parser.GetRequiredVersion() );
349 else
350 throw;
351 }
352}
353
354
356{
357 // If we've requested to embed the fonts in the footprint, do so. Otherwise, clear the
358 // embedded fonts from the footprint. Embedded fonts will be used if available.
359 if( aFootprint->GetAreFontsEmbedded() )
360 aFootprint->EmbedFonts();
361 else
362 aFootprint->GetEmbeddedFiles()->ClearEmbeddedFonts();
363
364 formatInitialComments( aFootprint );
365
366 m_out->Print( "(kicad_footprint_lib (version %d) (generator \"kicad_footprint_editor\")"
367 " (generator_version \"%s\")\n",
369 GetMajorMinorVersion().c_str().AsChar() );
370 format( aFootprint, true );
371 m_out->Print( ")\n" );
372}
373
374
375void PCB_IO_KICAD_SEXPR::Format( const BOARD_ITEM* aItem ) const
376{
377 switch( aItem->Type() )
378 {
379 case PCB_T:
380 format( static_cast<const BOARD*>( aItem ) );
381 break;
382
384 case PCB_DIM_CENTER_T:
385 case PCB_DIM_RADIAL_T:
387 case PCB_DIM_LEADER_T:
388 format( static_cast<const PCB_DIMENSION_BASE*>( aItem ) );
389 break;
390
391 case PCB_SHAPE_T:
392 format( static_cast<const PCB_SHAPE*>( aItem ) );
393 break;
394
396 format( static_cast<const PCB_REFERENCE_IMAGE*>( aItem ) );
397 break;
398
399 case PCB_POINT_T:
400 format( static_cast<const PCB_POINT*>( aItem ) );
401 break;
402
403 case PCB_TARGET_T:
404 format( static_cast<const PCB_TARGET*>( aItem ) );
405 break;
406
407 case PCB_GRID_ITEM_T:
408 format( static_cast<const PCB_GRID_ITEM*>( aItem ) );
409 break;
410
411 case PCB_FOOTPRINT_T:
412 format( static_cast<const FOOTPRINT*>( aItem ) );
413 break;
414
415 case PCB_PAD_T:
416 format( static_cast<const PAD*>( aItem ) );
417 break;
418
419 case PCB_FIELD_T:
420 // Handled in the footprint formatter when properties are formatted
421 break;
422
423 case PCB_TEXT_T:
424 format( static_cast<const PCB_TEXT*>( aItem ) );
425 break;
426
427 case PCB_TEXTBOX_T:
428 format( static_cast<const PCB_TEXTBOX*>( aItem ) );
429 break;
430
431 case PCB_BARCODE_T:
432 format( static_cast<const PCB_BARCODE*>( aItem ) );
433 break;
434
435 case PCB_TABLE_T:
436 format( static_cast<const PCB_TABLE*>( aItem ) );
437 break;
438
441 format( static_cast<const PCB_GENERATED_TABLE*>( aItem ) );
442 break;
443
444 case PCB_DRILL_MAP_T:
445 format( static_cast<const PCB_DRILL_MAP*>( aItem ) );
446 break;
447
448 case PCB_GROUP_T:
449 format( static_cast<const PCB_GROUP*>( aItem ) );
450 break;
451
452 case PCB_GENERATOR_T:
453 format( static_cast<const PCB_GENERATOR*>( aItem ) );
454 break;
455
456 case PCB_CONSTRAINT_T:
457 format( static_cast<const PCB_CONSTRAINT*>( aItem ) );
458 break;
459
460 case PCB_TRACE_T:
461 case PCB_ARC_T:
462 case PCB_VIA_T:
463 format( static_cast<const PCB_TRACK*>( aItem ) );
464 break;
465
466 case PCB_ZONE_T:
467 format( static_cast<const ZONE*>( aItem ) );
468 break;
469
470 default:
471 wxFAIL_MSG( wxT( "Cannot format item " ) + aItem->GetClass() );
472 }
473}
474
475
476std::string formatInternalUnits( const int aValue, const EDA_DATA_TYPE aDataType = EDA_DATA_TYPE::DISTANCE )
477{
478 return EDA_UNIT_UTILS::FormatInternalUnits( pcbIUScale, aValue, aDataType );
479}
480
481
482std::string formatInternalUnits( const VECTOR2I& aCoord )
483{
485}
486
487
488std::string formatInternalUnits( const VECTOR2I& aCoord, const FOOTPRINT* aParentFP )
489{
490 if( aParentFP )
491 {
492 return formatInternalUnits( aParentFP->GetTransform().InverseApply( aCoord ) );
493 }
494
495 return formatInternalUnits( aCoord );
496}
497
498
499static VECTOR2I unbakeSize( const VECTOR2I& aSize, const FOOTPRINT* aParentFP )
500{
501 if( !aParentFP )
502 return aSize;
503
504 const TRANSFORM_TRS& xform = aParentFP->GetTransform();
505 return { KiROUND( aSize.x / xform.GetScaleX() ), KiROUND( aSize.y / xform.GetScaleY() ) };
506}
507
508
509static VECTOR2I unbakeSizeUniform( const VECTOR2I& aSize, const FOOTPRINT* aParentFP )
510{
511 if( !aParentFP )
512 return aSize;
513
514 const TRANSFORM_TRS& xform = aParentFP->GetTransform();
515 double avg = ( xform.GetScaleX() + xform.GetScaleY() ) * 0.5;
516 return { KiROUND( aSize.x / avg ), KiROUND( aSize.y / avg ) };
517}
518
519
520static int unbakeLinear( int aValue, const FOOTPRINT* aParentFP )
521{
522 if( !aParentFP )
523 return aValue;
524
525 const TRANSFORM_TRS& xform = aParentFP->GetTransform();
526 double avg = ( xform.GetScaleX() + xform.GetScaleY() ) * 0.5;
527 return KiROUND( aValue / avg );
528}
529
530
531void PCB_IO_KICAD_SEXPR::formatLayer( PCB_LAYER_ID aLayer, bool aIsKnockout ) const
532{
533 m_out->Print( "(layer %s %s)",
534 m_out->Quotew( LSET::Name( aLayer ) ).c_str(),
535 aIsKnockout ? "knockout" : "" );
536}
537
538
540 const FOOTPRINT* aParentFP ) const
541{
542 m_out->Print( "(pts" );
543
544 for( int ii = 0; ii < outline.PointCount(); ++ii )
545 {
546 int ind = outline.ArcIndex( ii );
547
548 if( ind < 0 )
549 {
550 m_out->Print( "(xy %s)",
551 formatInternalUnits( outline.CPoint( ii ), aParentFP ).c_str() );
552 }
553 else
554 {
555 const SHAPE_ARC& arc = outline.Arc( ind );
556 m_out->Print( "(arc (start %s) (mid %s) (end %s))",
557 formatInternalUnits( arc.GetP0(), aParentFP ).c_str(),
558 formatInternalUnits( arc.GetArcMid(), aParentFP ).c_str(),
559 formatInternalUnits( arc.GetP1(), aParentFP ).c_str() );
560
561 do
562 {
563 ++ii;
564 } while( ii < outline.PointCount() && outline.ArcIndex( ii ) == ind );
565
566 --ii;
567 }
568 }
569
570 m_out->Print( ")" );
571}
572
573
575{
576 wxString resolvedText( aText->GetShownText( FOR_CANVAS ) );
577 std::vector<std::unique_ptr<KIFONT::GLYPH>>* cache = aText->GetRenderCache( aText->GetFont(),
578 resolvedText );
579
580 m_out->Print( "(render_cache %s %s",
581 m_out->Quotew( resolvedText ).c_str(),
582 EDA_UNIT_UTILS::FormatAngle( aText->GetDrawRotation() ).c_str() );
583
585
586 CALLBACK_GAL callback_gal( empty_opts,
587 // Polygon callback
588 [&]( const SHAPE_LINE_CHAIN& aPoly )
589 {
590 m_out->Print( "(polygon" );
591 formatPolyPts( aPoly );
592 m_out->Print( ")" );
593 } );
594
595 callback_gal.SetLineWidth( aText->GetTextThickness() );
596 callback_gal.DrawGlyphs( *cache );
597
598 m_out->Print( ")" );
599}
600
601
602void PCB_IO_KICAD_SEXPR::formatSetup( const BOARD* aBoard ) const
603{
604 // Setup
605 m_out->Print( "(setup" );
606
607 // Save the board physical stackup structure
608 const BOARD_DESIGN_SETTINGS& bds = aBoard->GetDesignSettings();
609 const BOARD_STACKUP& stackup = bds.GetStackupDescriptor();
610
611 if( bds.m_HasStackup )
612 stackup.FormatBoardStackup( m_out, aBoard );
613
614 m_out->Print( "(pad_to_mask_clearance %s)", formatInternalUnits( bds.m_SolderMaskExpansion ).c_str() );
615
616 if( bds.m_SolderMaskMinWidth )
617 m_out->Print( "(solder_mask_min_width %s)", formatInternalUnits( bds.m_SolderMaskMinWidth ).c_str() );
618
619 if( bds.m_SolderPasteMargin != 0 )
620 m_out->Print( "(pad_to_paste_clearance %s)", formatInternalUnits( bds.m_SolderPasteMargin ).c_str() );
621
622 if( bds.m_SolderPasteMarginRatio != 0 )
623 m_out->Print( "(pad_to_paste_clearance_ratio %s)", FormatDouble2Str( bds.m_SolderPasteMarginRatio ).c_str() );
624
625 KICAD_FORMAT::FormatBool( m_out, "allow_soldermask_bridges_in_footprints", bds.m_AllowSoldermaskBridgesInFPs );
626
627 m_out->Print( 0, " (tenting " );
630 m_out->Print( 0, ")" );
631
632 m_out->Print( 0, " (covering " );
635 m_out->Print( 0, ")" );
636
637 m_out->Print( 0, " (plugging " );
640 m_out->Print( 0, ")" );
641
642 KICAD_FORMAT::FormatBool( m_out, "capping", bds.m_CapVias );
643
644 KICAD_FORMAT::FormatBool( m_out, "filling", bds.m_FillVias );
645
646 if( !bds.m_ZoneLayerProperties.empty() )
647 {
648 m_out->Print( 0, " (zone_defaults" );
649
650 for( const auto& [layer, properties] : bds.m_ZoneLayerProperties )
651 format( properties, 0, layer );
652
653 m_out->Print( 0, ")\n" );
654 }
655
656 VECTOR2I origin = bds.GetAuxOrigin();
657
658 if( origin != VECTOR2I( 0, 0 ) )
659 {
660 m_out->Print( "(aux_axis_origin %s %s)",
661 formatInternalUnits( origin.x ).c_str(),
662 formatInternalUnits( origin.y ).c_str() );
663 }
664
665 origin = bds.GetGridOrigin();
666
667 if( origin != VECTOR2I( 0, 0 ) )
668 {
669 m_out->Print( "(grid_origin %s %s)",
670 formatInternalUnits( origin.x ).c_str(),
671 formatInternalUnits( origin.y ).c_str() );
672 }
673
675
676 aBoard->GetPlotOptions().Format( m_out );
677
678 m_out->Print( ")" );
679}
680
681
684static void formatDrillSpan( OUTPUTFORMATTER* aOut, const DRILL_SPAN& aSpan )
685{
686 aOut->Print( "%s %s", aOut->Quotew( LSET::Name( aSpan.DrillStartLayer() ) ).c_str(),
687 aOut->Quotew( LSET::Name( aSpan.DrillEndLayer() ) ).c_str() );
688
689 if( aSpan.m_IsBackdrill )
690 aOut->Print( " backdrill" );
691
692 if( aSpan.m_IsNonPlatedFile )
693 aOut->Print( " npth" );
694}
695
696
698{
699 const DRILL_SYMBOL_PROFILE& profile = aSettings.GetDrillSymbolProfile();
700 const DRILL_SYMBOL_PROFILE defaults;
701
702 // A board nobody has configured writes nothing, so existing files keep their bytes
703 if( profile == defaults )
704 {
705 return;
706 }
707
708 m_out->Print( "(drill_symbol_profile" );
709
710 if( !profile.GetName().IsEmpty() )
711 m_out->Print( "(name %s)", m_out->Quotew( profile.GetName() ).c_str() );
712
713 m_out->Print( "(group_by" );
714
715 for( DRILL_GROUP_KEY key : profile.GroupKeys() )
716 m_out->Print( " %s", DrillGroupKeyToken( key ) );
717
718 m_out->Print( ")" );
719
720 m_out->Print( "(default_marks %s)", DrillMarkPolicyToken( profile.GetMarkPolicy() ) );
721 m_out->Print( "(size %s)", formatInternalUnits( profile.GetSymbolSize() ).c_str() );
722 m_out->Print( "(width %s)", formatInternalUnits( profile.GetSymbolWidth() ).c_str() );
723 KICAD_FORMAT::FormatBool( m_out, "freeze_assignments", profile.GetFreezeAssignments() );
724
725
726 for( const auto& [key, assignment] : profile.Assignments() )
727 {
728 m_out->Print( "(assignment (key %s) (mark %s",
729 m_out->Quotew( wxString::FromUTF8( key ) ).c_str(),
730 DrillMarkModeToken( assignment.m_MarkMode ) );
731
732 if( assignment.m_MarkMode == DRILL_MARK_MODE::SHAPE )
733 m_out->Print( " %d", assignment.m_ShapeIndex );
734 else if( assignment.m_MarkMode == DRILL_MARK_MODE::LETTER )
735 m_out->Print( " %s", m_out->Quotew( assignment.m_Letter ).c_str() );
736
737 m_out->Print( ")" );
738
739 if( !assignment.m_Description.IsEmpty() )
740 m_out->Print( "(descr %s)", m_out->Quotew( assignment.m_Description ).c_str() );
741
742 m_out->Print( ")" );
743 }
744
745 m_out->Print( ")" );
746}
747
748
749void PCB_IO_KICAD_SEXPR::formatGeneral( const BOARD* aBoard ) const
750{
751 const BOARD_DESIGN_SETTINGS& bds = aBoard->GetDesignSettings();
752
753 m_out->Print( "(general" );
754
755 m_out->Print( "(thickness %s)", formatInternalUnits( bds.GetBoardThickness() ).c_str() );
756
757 KICAD_FORMAT::FormatBool( m_out, "legacy_teardrops", aBoard->LegacyTeardrops() );
758
759 m_out->Print( ")" );
760
761 aBoard->GetPageSettings().Format( m_out );
762 aBoard->GetTitleBlock().Format( m_out );
763}
764
765
767{
768 m_out->Print( "(layers" );
769
770 // Save only the used copper layers from front to back.
771
772 for( PCB_LAYER_ID layer : aBoard->GetEnabledLayers().CuStack() )
773 {
774 m_out->Print( "(%d %s %s %s)",
775 layer,
776 m_out->Quotew( LSET::Name( layer ) ).c_str(),
777 LAYER::ShowType( aBoard->GetLayerType( layer ) ),
778 LSET::Name( layer ) == aBoard->GetLayerName( layer )
779 ? ""
780 : m_out->Quotew( aBoard->GetLayerName( layer ) ).c_str() );
781
782 }
783
784 // Save used non-copper layers in the order they are defined.
785 LSEQ seq = aBoard->GetEnabledLayers().TechAndUserUIOrder();
786
787 for( PCB_LAYER_ID layer : seq )
788 {
789 bool print_type = false;
790
791 // User layers (layer id >= User_1) have a qualifier
792 // default is "user", but other qualifiers exist
793 if( layer >= User_1 )
794 {
795 if( IsCopperLayer( layer ) )
796 print_type = true;
797
798 if( aBoard->GetLayerType( layer ) == LT_FRONT
799 || aBoard->GetLayerType( layer ) == LT_BACK )
800 print_type = true;
801 }
802
803 m_out->Print( "(%d %s %s %s)",
804 layer,
805 m_out->Quotew( LSET::Name( layer ) ).c_str(),
806 print_type
807 ? LAYER::ShowType( aBoard->GetLayerType( layer ) )
808 : "user",
809 aBoard->GetLayerName( layer ) == LSET::Name( layer )
810 ? ""
811 : m_out->Quotew( aBoard->GetLayerName( layer ) ).c_str() );
812 }
813
814 m_out->Print( ")" );
815}
816
817
819{
820 for( const std::pair<const wxString, wxString>& prop : aBoard->GetProperties() )
821 {
822 m_out->Print( "(property %s %s)",
823 m_out->Quotew( prop.first ).c_str(),
824 m_out->Quotew( prop.second ).c_str() );
825 }
826}
827
828
829void PCB_IO_KICAD_SEXPR::formatVariants( const BOARD* aBoard ) const
830{
831 const std::vector<wxString>& variantNames = aBoard->GetVariantNames();
832
833 if( variantNames.empty() )
834 return;
835
836 m_out->Print( "(variants" );
837
838 for( const wxString& variantName : variantNames )
839 {
840 m_out->Print( "(variant (name %s)", m_out->Quotew( variantName ).c_str() );
841
842 wxString description = aBoard->GetVariantDescription( variantName );
843
844 if( !description.IsEmpty() )
845 m_out->Print( "(description %s)", m_out->Quotew( description ).c_str() );
846
847 m_out->Print( ")" );
848 }
849
850 m_out->Print( ")" );
851}
852
853
854void PCB_IO_KICAD_SEXPR::formatHeader( const BOARD* aBoard ) const
855{
856 formatGeneral( aBoard );
857
858 // Layers list.
859 formatBoardLayers( aBoard );
860
861 // Setup
862 formatSetup( aBoard );
863
864 // Properties
865 formatProperties( aBoard );
866
867 // Variants
868 formatVariants( aBoard );
869}
870
871
873{
874 static const TEARDROP_PARAMETERS defaults;
875
876 return tdParams.m_Enabled == defaults.m_Enabled
877 && tdParams.m_BestLengthRatio == defaults.m_BestLengthRatio
878 && tdParams.m_TdMaxLen == defaults.m_TdMaxLen
879 && tdParams.m_BestWidthRatio == defaults.m_BestWidthRatio
880 && tdParams.m_TdMaxWidth == defaults.m_TdMaxWidth
881 && tdParams.m_CurvedEdges == defaults.m_CurvedEdges
883 && tdParams.m_AllowUseTwoTracks == defaults.m_AllowUseTwoTracks
884 && tdParams.m_TdOnPadsInZones == defaults.m_TdOnPadsInZones;
885}
886
887
889{
890 m_out->Print( "(teardrops (best_length_ratio %s) (max_length %s) (best_width_ratio %s) "
891 "(max_width %s)",
892 FormatDouble2Str( tdParams.m_BestLengthRatio ).c_str(),
893 formatInternalUnits( tdParams.m_TdMaxLen ).c_str(),
894 FormatDouble2Str( tdParams.m_BestWidthRatio ).c_str(),
895 formatInternalUnits( tdParams.m_TdMaxWidth ).c_str() );
896
897 KICAD_FORMAT::FormatBool( m_out, "curved_edges", tdParams.m_CurvedEdges );
898
899 m_out->Print( "(filter_ratio %s)",
900 FormatDouble2Str( tdParams.m_WidthtoSizeFilterRatio ).c_str() );
901
902 KICAD_FORMAT::FormatBool( m_out, "enabled", tdParams.m_Enabled );
903 KICAD_FORMAT::FormatBool( m_out, "allow_two_segments", tdParams.m_AllowUseTwoTracks );
904 KICAD_FORMAT::FormatBool( m_out, "prefer_zone_connections", !tdParams.m_TdOnPadsInZones );
905 m_out->Print( ")" );
906}
907
908
909void PCB_IO_KICAD_SEXPR::format( const BOARD* aBoard ) const
910{
911 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_footprints( aBoard->Footprints().begin(),
912 aBoard->Footprints().end() );
913 std::set<BOARD_ITEM*, BOARD::cmp_drawings> sorted_drawings( aBoard->Drawings().begin(),
914 aBoard->Drawings().end() );
915 std::set<PCB_TRACK*, PCB_TRACK::cmp_tracks> sorted_tracks( aBoard->Tracks().begin(),
916 aBoard->Tracks().end() );
917 std::set<PCB_POINT*, PCB_POINT::cmp_points> sorted_points( aBoard->Points().begin(),
918 aBoard->Points().end() );
919 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_zones( aBoard->Zones().begin(),
920 aBoard->Zones().end() );
921 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_groups( aBoard->Groups().begin(),
922 aBoard->Groups().end() );
923 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_generators( aBoard->Generators().begin(),
924 aBoard->Generators().end() );
925 std::set<BOARD_ITEM*, BOARD_ITEM::ptr_cmp> sorted_constraints( aBoard->Constraints().begin(),
926 aBoard->Constraints().end() );
927 formatHeader( aBoard );
928
929 // Save the footprints.
930 for( BOARD_ITEM* footprint : sorted_footprints )
931 Format( footprint );
932
933 // Save the graphical items on the board (not owned by a footprint)
934 for( BOARD_ITEM* item : sorted_drawings )
935 Format( item );
936
937 // Save the points
938 for( PCB_POINT* point : sorted_points )
939 Format( point );
940
941 // Do not save PCB_MARKERs, they can be regenerated easily.
942
943 // Save the tracks and vias.
944 for( PCB_TRACK* track : sorted_tracks )
945 Format( track );
946
947 // Save the polygon (which are the newer technology) zones.
948 for( auto zone : sorted_zones )
949 Format( zone );
950
951 // Save the groups
952 for( BOARD_ITEM* group : sorted_groups )
953 Format( group );
954
955 // Save the generators
956 for( BOARD_ITEM* gen : sorted_generators )
957 Format( gen );
958
959 // Save the geometric constraints last, after every item they may reference.
960 for( BOARD_ITEM* constraint : sorted_constraints )
961 Format( constraint );
962
963 // After writing all items, write the aggregated net chains section (if any)
964 struct CHAIN_INFO
965 {
966 std::vector<NETINFO_ITEM*> nets;
967 PAD* pads[2] = { nullptr, nullptr };
968 };
969
970 // Simple lexicographic ordering using ValueStringCompare comparator logic
971 auto cmp = []( const wxString& a, const wxString& b )
972 {
973 return ValueStringCompare( a, b ) < 0;
974 };
975
976 std::map<wxString, CHAIN_INFO, decltype( cmp )> chains( cmp );
977
978 for( NETINFO_ITEM* net : aBoard->GetNetInfo() )
979 {
980 if( !net )
981 continue;
982
983 if( net->GetNetChain().IsEmpty() && !net->GetTerminalPad( 0 ) && !net->GetTerminalPad( 1 ) )
984 continue; // nothing to aggregate
985
986 wxString chainName = net->GetNetChain();
987
988 if( chainName.IsEmpty() && ( net->GetTerminalPad( 0 ) || net->GetTerminalPad( 1 ) ) )
989 chainName = net->GetNetname(); // synthetic name for unnamed terminal association
990
991 CHAIN_INFO& info = chains[chainName];
992 info.nets.push_back( net );
993 for( int i = 0; i < 2; ++i )
994 {
995 if( net->GetTerminalPad( i ) && !info.pads[i] )
996 info.pads[i] = net->GetTerminalPad( i );
997 }
998 }
999
1000 size_t count = 0;
1001 for( const auto& kv : chains )
1002 {
1003 const CHAIN_INFO& si = kv.second;
1004 const wxString& chainName = kv.first;
1005 // Persist if: multi-net OR terminal pads OR explicit (non-empty) chain name
1006 if( si.nets.size() > 1 || si.pads[0] || si.pads[1] || !chainName.IsEmpty() )
1007 ++count;
1008 }
1009
1010 if( count )
1011 {
1012 m_out->Print( "(net_chains" );
1013 for( const auto& kv : chains )
1014 {
1015 const wxString& name = kv.first;
1016 const CHAIN_INFO& si = kv.second;
1017
1018 if( si.nets.size() == 1 && !si.pads[0] && !si.pads[1] && name.IsEmpty() )
1019 continue;
1020
1021 m_out->Print( " (net_chain (name %s)", m_out->Quotew( name ).c_str() );
1022 m_out->Print( " (members" );
1023 for( NETINFO_ITEM* n : si.nets )
1024 {
1025 m_out->Print( " (net %s)", m_out->Quotew( n->GetNetname() ).c_str() );
1026 }
1027 m_out->Print( ")" );
1028
1029 for( int i = 0; i < 2; ++i )
1030 {
1031 if( si.pads[i] )
1032 m_out->Print( " (terminal_pad %s)",
1033 m_out->Quotew( si.pads[i]->m_Uuid.AsString() ).c_str() );
1034 }
1035
1036 m_out->Print( ")" );
1037 }
1038 m_out->Print( ")" );
1039 }
1040
1041 // Save any embedded files
1042 // Consolidate the embedded models in footprints into a single map
1043 // to avoid duplicating the same model in the board file.
1044 EMBEDDED_FILES files_to_write;
1045
1046 for( auto& file : aBoard->GetEmbeddedFiles()->EmbeddedFileMap() )
1047 files_to_write.AddFile( file.second );
1048
1049 for( BOARD_ITEM* item : sorted_footprints )
1050 {
1051 FOOTPRINT* fp = static_cast<FOOTPRINT*>( item );
1052
1053 for( auto& file : fp->GetEmbeddedFiles()->EmbeddedFileMap() )
1054 files_to_write.AddFile( file.second );
1055 }
1056
1057 m_out->Print( "(embedded_fonts %s)",
1058 aBoard->GetEmbeddedFiles()->GetAreFontsEmbedded() ? "yes" : "no" );
1059
1060 if( !files_to_write.IsEmpty() )
1061 files_to_write.WriteEmbeddedFiles( *m_out, ( m_ctl & CTL_FOR_BOARD ) );
1062
1063 // Remove the files so that they are not freed in the DTOR
1064 files_to_write.ClearEmbeddedFiles( false );
1065}
1066
1067
1068void PCB_IO_KICAD_SEXPR::format( const PCB_DIMENSION_BASE* aDimension ) const
1069{
1070 const PCB_DIM_ALIGNED* aligned = dynamic_cast<const PCB_DIM_ALIGNED*>( aDimension );
1071 const PCB_DIM_ORTHOGONAL* ortho = dynamic_cast<const PCB_DIM_ORTHOGONAL*>( aDimension );
1072 const PCB_DIM_CENTER* center = dynamic_cast<const PCB_DIM_CENTER*>( aDimension );
1073 const PCB_DIM_RADIAL* radial = dynamic_cast<const PCB_DIM_RADIAL*>( aDimension );
1074 const PCB_DIM_LEADER* leader = dynamic_cast<const PCB_DIM_LEADER*>( aDimension );
1075
1076 m_out->Print( "(dimension" );
1077
1078 if( ortho ) // must be tested before aligned, because ortho is derived from aligned
1079 // and aligned is not null
1080 m_out->Print( "(type orthogonal)" );
1081 else if( aligned )
1082 m_out->Print( "(type aligned)" );
1083 else if( leader )
1084 m_out->Print( "(type leader)" );
1085 else if( center )
1086 m_out->Print( "(type center)" );
1087 else if( radial )
1088 m_out->Print( "(type radial)" );
1089 else
1090 wxFAIL_MSG( wxT( "Cannot format unknown dimension type!" ) );
1091
1092 if( aDimension->IsLocked() )
1093 KICAD_FORMAT::FormatBool( m_out, "locked", aDimension->IsLocked() );
1094
1095 formatLayer( aDimension->GetLayer() );
1096
1097 KICAD_FORMAT::FormatUuid( m_out, aDimension->m_Uuid );
1098
1099 m_out->Print( "(pts (xy %s %s) (xy %s %s))",
1100 formatInternalUnits( aDimension->GetStart().x ).c_str(),
1101 formatInternalUnits( aDimension->GetStart().y ).c_str(),
1102 formatInternalUnits( aDimension->GetEnd().x ).c_str(),
1103 formatInternalUnits( aDimension->GetEnd().y ).c_str() );
1104
1105 if( aligned )
1106 m_out->Print( "(height %s)", formatInternalUnits( aligned->GetHeight() ).c_str() );
1107
1108 if( radial )
1109 {
1110 m_out->Print( "(leader_length %s)",
1111 formatInternalUnits( radial->GetLeaderLength() ).c_str() );
1112 }
1113
1114 if( ortho )
1115 m_out->Print( "(orientation %d)", static_cast<int>( ortho->GetOrientation() ) );
1116
1117 if( !center )
1118 {
1119 m_out->Print( "(format (prefix %s) (suffix %s) (units %d) (units_format %d) (precision %d)",
1120 m_out->Quotew( aDimension->GetPrefix() ).c_str(),
1121 m_out->Quotew( aDimension->GetSuffix() ).c_str(),
1122 static_cast<int>( aDimension->GetUnitsMode() ),
1123 static_cast<int>( aDimension->GetUnitsFormat() ),
1124 static_cast<int>( aDimension->GetPrecision() ) );
1125
1126 if( aDimension->GetOverrideTextEnabled() )
1127 {
1128 m_out->Print( "(override_value %s)",
1129 m_out->Quotew( aDimension->GetOverrideText() ).c_str() );
1130 }
1131
1132 if( aDimension->GetSuppressZeroes() )
1133 KICAD_FORMAT::FormatBool( m_out, "suppress_zeroes", true );
1134
1135 m_out->Print( ")" );
1136 }
1137
1138 m_out->Print( "(style (thickness %s) (arrow_length %s) (text_position_mode %d)",
1139 formatInternalUnits( aDimension->GetLineThickness() ).c_str(),
1140 formatInternalUnits( aDimension->GetArrowLength() ).c_str(),
1141 static_cast<int>( aDimension->GetTextPositionMode() ) );
1142
1143 if( ortho || aligned )
1144 {
1145 switch( aDimension->GetArrowDirection() )
1146 {
1148 m_out->Print( "(arrow_direction outward)" );
1149 break;
1151 m_out->Print( "(arrow_direction inward)" );
1152 break;
1153 // No default, handle all cases
1154 }
1155 }
1156
1157 if( aligned )
1158 {
1159 m_out->Print( "(extension_height %s)",
1160 formatInternalUnits( aligned->GetExtensionHeight() ).c_str() );
1161 }
1162
1163 if( leader )
1164 m_out->Print( "(text_frame %d)", static_cast<int>( leader->GetTextBorder() ) );
1165
1166 m_out->Print( "(extension_offset %s)",
1167 formatInternalUnits( aDimension->GetExtensionOffset() ).c_str() );
1168
1169 if( aDimension->GetKeepTextAligned() )
1170 KICAD_FORMAT::FormatBool( m_out, "keep_text_aligned", true );
1171
1172 m_out->Print( ")" );
1173
1174 // Write dimension text after all other options to be sure the
1175 // text options are known when reading the file
1176 if( !center )
1177 format( static_cast<const PCB_TEXT*>( aDimension ) );
1178
1180 m_out->Print( ")" );
1181}
1182
1183
1184void PCB_IO_KICAD_SEXPR::format( const PCB_SHAPE* aShape ) const
1185{
1186 FOOTPRINT* parentFP = aShape->GetParentFootprint();
1187 std::string prefix = parentFP ? "fp" : "gr";
1188
1189 switch( aShape->GetLibraryShape() )
1190 {
1191 case SHAPE_T::SEGMENT:
1192 m_out->Print( "(%s_line (start %s) (end %s)",
1193 prefix.c_str(),
1194 formatInternalUnits( aShape->GetLibraryStart() ).c_str(),
1195 formatInternalUnits( aShape->GetLibraryEnd() ).c_str() );
1196 break;
1197
1198 case SHAPE_T::RECTANGLE:
1199 m_out->Print( "(%s_rect (start %s) (end %s)", prefix.c_str(),
1200 formatInternalUnits( aShape->GetLibraryStart() ).c_str(),
1201 formatInternalUnits( aShape->GetLibraryEnd() ).c_str() );
1202
1203 if( aShape->GetCornerRadius() > 0 )
1204 m_out->Print( " (radius %s)", formatInternalUnits( aShape->GetLibraryCornerRadius() ).c_str() );
1205
1206 break;
1207
1208 case SHAPE_T::CIRCLE:
1209 m_out->Print( "(%s_circle (center %s) (end %s)", prefix.c_str(),
1210 formatInternalUnits( aShape->GetLibraryStart() ).c_str(),
1211 formatInternalUnits( aShape->GetLibraryEnd() ).c_str() );
1212 break;
1213
1214 case SHAPE_T::ARC:
1215 m_out->Print( "(%s_arc (start %s) (mid %s) (end %s)", prefix.c_str(),
1216 formatInternalUnits( aShape->GetLibraryStart() ).c_str(),
1217 formatInternalUnits( aShape->GetLibraryArcMid() ).c_str(),
1218 formatInternalUnits( aShape->GetLibraryEnd() ).c_str() );
1219 break;
1220
1221 case SHAPE_T::POLY:
1222 if( aShape->IsPolyShapeValid() )
1223 {
1224 const SHAPE_POLY_SET& poly = aShape->GetPolyShape();
1225 const SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
1226
1227 m_out->Print( "(%s_poly", prefix.c_str() );
1228 formatPolyPts( outline, parentFP );
1229 }
1230 else
1231 {
1232 return;
1233 }
1234
1235 break;
1236
1237 case SHAPE_T::BEZIER:
1238 m_out->Print( "(%s_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
1239 prefix.c_str(),
1240 formatInternalUnits( aShape->GetStart(), parentFP ).c_str(),
1241 formatInternalUnits( aShape->GetBezierC1(), parentFP ).c_str(),
1242 formatInternalUnits( aShape->GetBezierC2(), parentFP ).c_str(),
1243 formatInternalUnits( aShape->GetEnd(), parentFP ).c_str() );
1244 break;
1245
1246 case SHAPE_T::ELLIPSE:
1247 m_out->Print( "(%s_ellipse (center %s) (major_radius %s) (minor_radius %s) "
1248 "(rotation_angle %s)",
1249 prefix.c_str(),
1250 formatInternalUnits( aShape->GetLibraryEllipseCenter() ).c_str(),
1254 break;
1255
1257 m_out->Print( "(%s_ellipse_arc (center %s) (major_radius %s) (minor_radius %s) "
1258 "(rotation_angle %s) (start_angle %s) (end_angle %s)",
1259 prefix.c_str(),
1260 formatInternalUnits( aShape->GetLibraryEllipseCenter() ).c_str(),
1266 break;
1267
1268 default:
1270 return;
1271 };
1272
1273 {
1274 STROKE_PARAMS stroke = aShape->GetStroke();
1275 stroke.SetWidth( unbakeLinear( stroke.GetWidth(), parentFP ) );
1276 stroke.Format( m_out, pcbIUScale );
1277 }
1278
1279 aShape->GetStartEnding().Format( m_out, pcbIUScale, "start_shape" );
1280 aShape->GetEndEnding().Format( m_out, pcbIUScale, "end_shape" );
1281
1282 // The filled flag represents if a solid fill is present on circles, rectangles and polygons
1283 if( ( aShape->GetShape() == SHAPE_T::POLY ) || ( aShape->GetShape() == SHAPE_T::RECTANGLE )
1284 || ( aShape->GetShape() == SHAPE_T::CIRCLE ) || ( aShape->GetShape() == SHAPE_T::ELLIPSE ) )
1285 {
1286 switch( aShape->GetFillMode() )
1287 {
1288 case FILL_T::HATCH:
1289 m_out->Print( "(fill hatch)" );
1290 break;
1291
1293 m_out->Print( "(fill reverse_hatch)" );
1294 break;
1295
1297 m_out->Print( "(fill cross_hatch)" );
1298 break;
1299
1301 KICAD_FORMAT::FormatBool( m_out, "fill", true );
1302 break;
1303
1304 default:
1305 KICAD_FORMAT::FormatBool( m_out, "fill", false );
1306 break;
1307 }
1308 }
1309
1310 if( aShape->IsLocked() )
1311 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1312
1313 if( aShape->GetLayerSet().count() > 1 )
1314 formatLayers( aShape->GetLayerSet(), false /* enumerate layers */ );
1315 else
1316 formatLayer( aShape->GetLayer() );
1317
1318 if( aShape->HasSolderMask()
1319 && aShape->GetLocalSolderMaskMargin().has_value()
1320 && IsExternalCopperLayer( aShape->GetLayer() ) )
1321 {
1322 m_out->Print( "(solder_mask_margin %s)",
1323 formatInternalUnits( aShape->GetLocalSolderMaskMargin().value() ).c_str() );
1324 }
1325
1326 if( !( m_ctl & CTL_OMIT_PAD_NETS ) && aShape->GetNetCode() > 0 )
1327 m_out->Print( "(net %s)", m_out->Quotew( aShape->GetNetname() ).c_str() );
1328
1331 m_out->Print( ")" );
1332}
1333
1334
1336{
1337 wxCHECK_RET( aBitmap != nullptr && m_out != nullptr, "" );
1338
1339 const REFERENCE_IMAGE& refImage = aBitmap->GetReferenceImage();
1340
1341 const wxImage* image = refImage.GetImage().GetImageData();
1342
1343 wxCHECK_RET( image != nullptr, "wxImage* is NULL" );
1344
1345 m_out->Print( "(image (at %s %s)",
1346 formatInternalUnits( aBitmap->GetPosition().x ).c_str(),
1347 formatInternalUnits( aBitmap->GetPosition().y ).c_str() );
1348
1349 formatLayer( aBitmap->GetLayer() );
1350
1351 if( !refImage.GetOrientation().IsZero() )
1352 m_out->Print( "(rotate %s)", EDA_UNIT_UTILS::FormatAngle( refImage.GetOrientation() ).c_str() );
1353
1354 if( refImage.GetImageScale() != 1.0 )
1355 m_out->Print( "%s", fmt::format("(scale {:g})", refImage.GetImageScale()).c_str() );
1356
1357 if( refImage.GetOpacity() < 1.0 )
1358 m_out->Print( "%s", fmt::format( "(opacity {:g})", refImage.GetOpacity() ).c_str() );
1359
1360 if( aBitmap->IsLocked() )
1361 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1362
1363 wxMemoryOutputStream ostream;
1364 refImage.GetImage().SaveImageData( ostream );
1365
1366 KICAD_FORMAT::FormatStreamData( *m_out, *ostream.GetOutputStreamBuffer() );
1367
1370 m_out->Print( ")" ); // Closes image token.
1371}
1372
1373
1374void PCB_IO_KICAD_SEXPR::format( const PCB_POINT* aPoint ) const
1375{
1376 m_out->Print( "(point (at %s) (size %s)", formatInternalUnits( aPoint->GetLibraryPosition() ).c_str(),
1377 formatInternalUnits( aPoint->GetSize() ).c_str() );
1378
1379 formatLayer( aPoint->GetLayer() );
1380
1383 m_out->Print( ")" );
1384}
1385
1386
1387void PCB_IO_KICAD_SEXPR::format( const PCB_TARGET* aTarget ) const
1388{
1389 m_out->Print( "(target %s (at %s) (size %s)",
1390 ( aTarget->GetShape() ) ? "x" : "plus",
1391 formatInternalUnits( aTarget->GetPosition() ).c_str(),
1392 formatInternalUnits( aTarget->GetSize() ).c_str() );
1393
1394 if( aTarget->GetWidth() != 0 )
1395 m_out->Print( "(width %s)", formatInternalUnits( aTarget->GetWidth() ).c_str() );
1396
1397 formatLayer( aTarget->GetLayer() );
1400 m_out->Print( ")" );
1401}
1402
1403
1404void PCB_IO_KICAD_SEXPR::format( const PCB_GRID_ITEM* aGridItem ) const
1405{
1406 const bool polar = aGridItem->GetGridItemType() == PCB_GRID_TYPE::POLAR;
1407
1408 // Grid type (polar/xy) must be emitted before extent/spacing: those tokens change
1409 // meaning based on the type (y component = angle for polar, length for cartesian).
1410 m_out->Print( "(grid_item %s (at %s)", polar ? "polar" : "xy",
1411 formatInternalUnits( aGridItem->GetPosition() ).c_str() );
1412
1413 if( polar )
1414 {
1415 // Polar y components are angles; use FormatAngle, not formatInternalUnits.
1416 m_out->Print( " (extent %s %s) (spacing %s %s)", formatInternalUnits( aGridItem->GetRadiusExtent() ).c_str(),
1417 EDA_UNIT_UTILS::FormatAngle( aGridItem->GetPhiExtent() ).c_str(),
1418 formatInternalUnits( aGridItem->GetRadiusSpacing() ).c_str(),
1419 EDA_UNIT_UTILS::FormatAngle( aGridItem->GetPhiSpacing() ).c_str() );
1420 }
1421 else
1422 {
1423 m_out->Print( " (extent %s) (spacing %s)", formatInternalUnits( aGridItem->GetExtent() ).c_str(),
1424 formatInternalUnits( aGridItem->GetSpacing() ).c_str() );
1425 }
1426
1427 if( !aGridItem->GetOrientation().IsZero() )
1428 {
1429 m_out->Print( " (angle %s)", EDA_UNIT_UTILS::FormatAngle( aGridItem->GetOrientation() ).c_str() );
1430 }
1431
1432 // Priority is always set
1433 m_out->Print( " (priority %u)", aGridItem->GetAssignedPriority() );
1434
1435 if( aGridItem->GetTickInterval() > 0 )
1436 m_out->Print( " (tick_interval %u)", aGridItem->GetTickInterval() );
1437
1438 const PCB_GRID_AFFECTS& aff = aGridItem->Affects();
1439 m_out->Print( " (affects (cursor %s) (routing %s) (placement %s))",
1440 aff.cursor ? "yes" : "no",
1441 aff.routing ? "yes" : "no",
1442 aff.placement ? "yes" : "no" );
1443
1444 if( aGridItem->IsLocked() )
1445 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1446
1447 KICAD_FORMAT::FormatUuid( m_out, aGridItem->m_Uuid );
1449 m_out->Print( ")\n" );
1450}
1451
1452
1454{
1455 if( !( m_ctl & CTL_OMIT_INITIAL_COMMENTS ) )
1456 {
1457 const wxArrayString* initial_comments = aFootprint->GetInitialComments();
1458
1459 if( initial_comments )
1460 {
1461 for( unsigned i = 0; i < initial_comments->GetCount(); ++i )
1462 m_out->Print( "%s\n", TO_UTF8( (*initial_comments)[i] ) );
1463 }
1464 }
1465}
1466
1467
1468void PCB_IO_KICAD_SEXPR::format( const FOOTPRINT* aFootprint, bool aInLibFile ) const
1469{
1470 if( !aInLibFile )
1471 formatInitialComments( aFootprint );
1472
1473 if( m_ctl & CTL_OMIT_LIBNAME )
1474 {
1475 m_out->Print( "(footprint %s",
1476 m_out->Quotes( aFootprint->GetFPID().GetLibItemName() ).c_str() );
1477 }
1478 else
1479 {
1480 m_out->Print( "(footprint %s",
1481 m_out->Quotes( aFootprint->GetFPID().Format() ).c_str() );
1482 }
1483
1484 if( !aInLibFile && !( m_ctl & CTL_OMIT_FOOTPRINT_VERSION ) )
1485 {
1486 m_out->Print( "(version %d) (generator \"pcbnew\") (generator_version %s)", SEXPR_BOARD_FILE_VERSION,
1487 m_out->Quotew( GetMajorMinorVersion() ).c_str() );
1488 }
1489
1490 if( aFootprint->IsLocked() )
1491 KICAD_FORMAT::FormatBool( m_out, "locked", true );
1492
1493 if( aFootprint->IsPlaced() )
1494 KICAD_FORMAT::FormatBool( m_out, "placed", true );
1495
1496 formatLayer( aFootprint->GetLayer() );
1497
1498 if( !( m_ctl & CTL_OMIT_UUIDS ) )
1499 KICAD_FORMAT::FormatUuid( m_out, aFootprint->m_Uuid );
1500
1501 if( !( m_ctl & CTL_OMIT_AT ) )
1502 {
1503 m_out->Print( "(transform (translate %s) (rotate %s) (scale %s %s))",
1504 formatInternalUnits( aFootprint->GetPosition() ).c_str(),
1505 EDA_UNIT_UTILS::FormatAngle( aFootprint->GetOrientation() ).c_str(),
1506 FormatDouble2Str( aFootprint->GetTransform().GetScaleX() ).c_str(),
1507 FormatDouble2Str( aFootprint->GetTransform().GetScaleY() ).c_str() );
1508 }
1509
1510 if( !aFootprint->GetLibDescription().IsEmpty() )
1511 m_out->Print( "(descr %s)", m_out->Quotew( aFootprint->GetLibDescription() ).c_str() );
1512
1513 if( !aFootprint->GetKeywords().IsEmpty() )
1514 m_out->Print( "(tags %s)", m_out->Quotew( aFootprint->GetKeywords() ).c_str() );
1515
1516 if( aFootprint->GetHeight() != 0 )
1517 m_out->Print( "(height %s)", formatInternalUnits( aFootprint->GetHeight() ).c_str() );
1518
1519 for( const PCB_FIELD* field : aFootprint->GetFields() )
1520 {
1521 if( !field )
1522 continue;
1523
1524 m_out->Print( "(property %s %s",
1525 m_out->Quotew( field->GetUntranslatedName() ).c_str(),
1526 m_out->Quotew( field->GetText() ).c_str() );
1527
1528 format( field );
1529
1530 m_out->Print( ")" );
1531 }
1532
1533 if( const COMPONENT_CLASS* compClass = aFootprint->GetStaticComponentClass() )
1534 {
1535 if( !compClass->IsEmpty() )
1536 {
1537 m_out->Print( "(component_classes" );
1538
1539 for( const COMPONENT_CLASS* constituent : compClass->GetConstituentClasses() )
1540 m_out->Print( "(class %s)", m_out->Quotew( constituent->GetName() ).c_str() );
1541
1542 m_out->Print( ")" );
1543 }
1544 }
1545
1546 if( !aFootprint->GetFilters().empty() )
1547 {
1548 m_out->Print( "(property ki_fp_filters %s)",
1549 m_out->Quotew( aFootprint->GetFilters() ).c_str() );
1550 }
1551
1552 if( !( m_ctl & CTL_OMIT_PATH ) && !aFootprint->GetPath().empty() )
1553 m_out->Print( "(path %s)", m_out->Quotew( aFootprint->GetPath().AsString() ).c_str() );
1554
1555 if( !aFootprint->GetSheetname().empty() )
1556 m_out->Print( "(sheetname %s)", m_out->Quotew( aFootprint->GetSheetname() ).c_str() );
1557
1558 if( !aFootprint->GetSheetfile().empty() )
1559 m_out->Print( "(sheetfile %s)", m_out->Quotew( aFootprint->GetSheetfile() ).c_str() );
1560
1561 // Emit unit info for gate swapping metadata (flat pin list form)
1562 if( !aFootprint->GetUnitInfo().empty() )
1563 {
1564 m_out->Print( "(units" );
1565
1566 for( const FOOTPRINT::FP_UNIT_INFO& u : aFootprint->GetUnitInfo() )
1567 {
1568 m_out->Print( "(unit (name %s)", m_out->Quotew( u.m_unitName ).c_str() );
1569 m_out->Print( "(pins" );
1570
1571 for( const wxString& n : u.m_pins )
1572 m_out->Print( " %s", m_out->Quotew( n ).c_str() );
1573
1574 m_out->Print( ")" ); // </pins>
1575 m_out->Print( ")" ); // </unit>
1576 }
1577
1578 m_out->Print( ")" ); // </units>
1579 }
1580
1581 if( aFootprint->GetLocalSolderMaskMargin().has_value() )
1582 {
1583 m_out->Print( "(solder_mask_margin %s)",
1584 formatInternalUnits( aFootprint->GetLocalSolderMaskMargin().value() ).c_str() );
1585 }
1586
1587 if( aFootprint->GetLocalSolderPasteMargin().has_value() )
1588 {
1589 m_out->Print( "(solder_paste_margin %s)",
1590 formatInternalUnits( aFootprint->GetLocalSolderPasteMargin().value() ).c_str() );
1591 }
1592
1593 if( aFootprint->GetLocalSolderPasteMarginRatio().has_value() )
1594 {
1595 m_out->Print( "(solder_paste_margin_ratio %s)",
1596 FormatDouble2Str( aFootprint->GetLocalSolderPasteMarginRatio().value() ).c_str() );
1597 }
1598
1599 if( aFootprint->GetLocalClearance().has_value() )
1600 {
1601 m_out->Print( "(clearance %s)",
1602 formatInternalUnits( aFootprint->GetLocalClearance().value() ).c_str() );
1603 }
1604
1606 {
1607 m_out->Print( "(zone_connect %d)",
1608 static_cast<int>( aFootprint->GetLocalZoneConnection() ) );
1609 }
1610
1611 // Attributes
1612 if( aFootprint->GetAttributes()
1613 || aFootprint->AllowMissingCourtyard()
1614 || aFootprint->AllowSolderMaskBridges() )
1615 {
1616 m_out->Print( "(attr" );
1617
1618 if( aFootprint->GetAttributes() & FP_SMD )
1619 m_out->Print( " smd" );
1620
1621 if( aFootprint->GetAttributes() & FP_THROUGH_HOLE )
1622 m_out->Print( " through_hole" );
1623
1624 if( aFootprint->GetAttributes() & FP_BOARD_ONLY )
1625 m_out->Print( " board_only" );
1626
1627 if( aFootprint->GetAttributes() & FP_EXCLUDE_FROM_POS_FILES )
1628 m_out->Print( " exclude_from_pos_files" );
1629
1630 if( aFootprint->GetAttributes() & FP_EXCLUDE_FROM_BOM )
1631 m_out->Print( " exclude_from_bom" );
1632
1633 if( aFootprint->GetAttributes() & FP_EXCLUDE_FROM_SIM )
1634 m_out->Print( " exclude_from_sim" );
1635
1636 if( aFootprint->AllowMissingCourtyard() )
1637 m_out->Print( " allow_missing_courtyard" );
1638
1639 if( aFootprint->GetAttributes() & FP_DNP )
1640 m_out->Print( " dnp" );
1641
1642 if( aFootprint->AllowSolderMaskBridges() )
1643 m_out->Print( " allow_soldermask_bridges" );
1644
1645 m_out->Print( ")" );
1646 }
1647
1648 // Expand inner layers is the default stackup mode
1650 {
1651 m_out->Print( "(stackup" );
1652
1653 const LSET& fpLset = aFootprint->GetStackupLayers();
1654 for( PCB_LAYER_ID layer : fpLset.Seq() )
1655 {
1656 wxString canonicalName( LSET::Name( layer ) );
1657 m_out->Print( "(layer %s)", m_out->Quotew( canonicalName ).c_str() );
1658 }
1659
1660 m_out->Print( ")" );
1661 }
1662
1663 if( aFootprint->GetPrivateLayers().any() )
1664 {
1665 m_out->Print( "(private_layers" );
1666
1667 for( PCB_LAYER_ID layer : aFootprint->GetPrivateLayers().Seq() )
1668 {
1669 wxString canonicalName( LSET::Name( layer ) );
1670 m_out->Print( " %s", m_out->Quotew( canonicalName ).c_str() );
1671 }
1672
1673 m_out->Print( ")" );
1674 }
1675
1676 if( aFootprint->IsNetTie() )
1677 {
1678 m_out->Print( "(net_tie_pad_groups" );
1679
1680 for( const wxString& group : aFootprint->GetNetTiePadGroups() )
1681 m_out->Print( " %s", m_out->Quotew( group ).c_str() );
1682
1683 m_out->Print( ")" );
1684 }
1685
1686 KICAD_FORMAT::FormatBool( m_out, "duplicate_pad_numbers_are_jumpers",
1687 aFootprint->GetDuplicatePadNumbersAreJumpers() );
1688
1689 const JUMPER_GROUP_SET& jumperGroups = aFootprint->JumperPadGroups();
1690
1691 if( !jumperGroups.IsEmpty() )
1692 {
1693 m_out->Print( "(jumper_pad_groups" );
1694
1695 for( const JUMPER_GROUP& group : jumperGroups.GetAll() )
1696 {
1697 m_out->Print( "(" );
1698
1699 for( const wxString& padName : group.GetNames() )
1700 m_out->Print( "%s ", m_out->Quotew( padName ).c_str() );
1701
1702 m_out->Print( ")" );
1703 }
1704
1705 m_out->Print( ")" );
1706 }
1707
1708 Format( &aFootprint->Reference() );
1709 Format( &aFootprint->Value() );
1710
1711 std::set<PAD*, FOOTPRINT::cmp_pads> sorted_pads( aFootprint->Pads().begin(),
1712 aFootprint->Pads().end() );
1713 std::set<BOARD_ITEM*, FOOTPRINT::cmp_drawings> sorted_drawings(
1714 aFootprint->GraphicalItems().begin(),
1715 aFootprint->GraphicalItems().end() );
1716 std::set<PCB_POINT*, PCB_POINT::cmp_points> sorted_points(
1717 aFootprint->Points().begin(),
1718 aFootprint->Points().end() );
1719 std::set<ZONE*, FOOTPRINT::cmp_zones> sorted_zones( aFootprint->Zones().begin(),
1720 aFootprint->Zones().end() );
1721 std::set<BOARD_ITEM*, PCB_GROUP::ptr_cmp> sorted_groups( aFootprint->Groups().begin(),
1722 aFootprint->Groups().end() );
1723 std::set<BOARD_ITEM*, PCB_GROUP::ptr_cmp> sorted_constraints( aFootprint->Constraints().begin(),
1724 aFootprint->Constraints().end() );
1725
1726 // Save drawing elements.
1727
1728 for( BOARD_ITEM* gr : sorted_drawings )
1729 Format( gr );
1730
1731 for( PCB_POINT* point : sorted_points )
1732 Format( point );
1733
1734 // Save pads.
1735 for( PAD* pad : sorted_pads )
1736 Format( pad );
1737
1738 // Save zones.
1739 for( BOARD_ITEM* zone : sorted_zones )
1740 Format( zone );
1741
1742 // Save groups.
1743 for( BOARD_ITEM* group : sorted_groups )
1744 Format( group );
1745
1746 // Save geometric constraints, after the items they reference.
1747 for( BOARD_ITEM* constraint : sorted_constraints )
1748 Format( constraint );
1749
1750 // Save variants.
1751 const bool baseDnp = aFootprint->IsDNP();
1752 const bool baseExcludedFromBOM = aFootprint->IsExcludedFromBOM();
1753 const bool baseExcludedFromSim = aFootprint->IsExcludedFromSim();
1754 const bool baseExcludedFromPosFiles = aFootprint->IsExcludedFromPosFiles();
1755
1756 for( const auto& [variantName, variant] : aFootprint->GetVariants() )
1757 {
1758 m_out->Print( "(variant (name %s)", m_out->Quotew( variantName ).c_str() );
1759
1760 if( variant.GetDNP() != baseDnp )
1761 KICAD_FORMAT::FormatBool( m_out, "dnp", variant.GetDNP() );
1762
1763 if( variant.GetExcludedFromBOM() != baseExcludedFromBOM )
1764 KICAD_FORMAT::FormatBool( m_out, "exclude_from_bom", variant.GetExcludedFromBOM() );
1765
1766 if( variant.GetExcludedFromSim() != baseExcludedFromSim )
1767 KICAD_FORMAT::FormatBool( m_out, "exclude_from_sim", variant.GetExcludedFromSim() );
1768
1769 if( variant.GetExcludedFromPosFiles() != baseExcludedFromPosFiles )
1770 {
1771 KICAD_FORMAT::FormatBool( m_out, "exclude_from_pos_files",
1772 variant.GetExcludedFromPosFiles() );
1773 }
1774
1775 for( const auto& [fieldName, fieldValue] : variant.GetFields() )
1776 {
1777 const PCB_FIELD* baseField = aFootprint->GetField( fieldName );
1778 const wxString baseValue = baseField ? baseField->GetText() : wxString();
1779
1780 if( fieldValue == baseValue )
1781 continue;
1782
1783 m_out->Print( "(field (name %s) (value %s))",
1784 m_out->Quotew( fieldName ).c_str(),
1785 m_out->Quotew( fieldValue ).c_str() );
1786 }
1787
1788 m_out->Print( ")" );
1789 }
1790
1791 KICAD_FORMAT::FormatBool( m_out, "embedded_fonts",
1792 aFootprint->GetEmbeddedFiles()->GetAreFontsEmbedded() );
1793
1794 if( !aFootprint->GetEmbeddedFiles()->IsEmpty() )
1795 aFootprint->WriteEmbeddedFiles( *m_out, !( m_ctl & CTL_FOR_BOARD ) );
1796
1797 // Save extruded 3D body info.
1798 for( const PCB_3D_BODY* bodyItem : aFootprint->Bodies() )
1799 {
1800 if( bodyItem->GetExtruded()->m_height <= 0 )
1801 continue;
1802
1803 const EXTRUDED_3D_BODY* body = bodyItem->GetExtruded();
1804 m_out->Print( "(model" );
1805 m_out->Print( "(type extruded)" );
1806 KICAD_FORMAT::FormatUuid( m_out, bodyItem->m_Uuid );
1807 KICAD_FORMAT::FormatBool( m_out, "hide", !body->m_show );
1808 m_out->Print( "(overall_height %s)", formatInternalUnits( body->m_height ).c_str() );
1809 m_out->Print( "(body_pcb_gap %s)", formatInternalUnits( body->m_standoff ).c_str() );
1810
1811 if( body->m_layer == UNSELECTED_LAYER )
1812 m_out->Print( "(layer pad_bbox)" );
1813 else if( body->m_layer != UNDEFINED_LAYER )
1814 m_out->Print( "(layer %s)", m_out->Quotew( LSET::Name( body->m_layer ) ).c_str() );
1815 else
1816 m_out->Print( "(layer auto)" );
1817
1818 {
1819 static const char* matNames[] = { "plastic", "matte", "metal", "copper" };
1820 m_out->Print( "(material %s)", matNames[static_cast<int>( body->m_material )] );
1821 }
1822
1824 {
1825 m_out->Print( "(color %s %s %s %s)", FormatDouble2Str( body->m_color.r ).c_str(),
1826 FormatDouble2Str( body->m_color.g ).c_str(), FormatDouble2Str( body->m_color.b ).c_str(),
1827 FormatDouble2Str( body->m_color.a ).c_str() );
1828 }
1829 else
1830 {
1831 m_out->Print( "(color unspecified)" );
1832 }
1833
1834 m_out->Print( "(offset (xyz %s %s %s))", FormatDouble2Str( body->m_offset.x ).c_str(),
1835 FormatDouble2Str( body->m_offset.y ).c_str(), FormatDouble2Str( body->m_offset.z ).c_str() );
1836
1837 m_out->Print( "(scale (xyz %s %s %s))", FormatDouble2Str( body->m_scale.x ).c_str(),
1838 FormatDouble2Str( body->m_scale.y ).c_str(), FormatDouble2Str( body->m_scale.z ).c_str() );
1839
1840 m_out->Print( "(rotate (xyz %s %s %s))", FormatDouble2Str( body->m_rotation.x ).c_str(),
1841 FormatDouble2Str( body->m_rotation.y ).c_str(), FormatDouble2Str( body->m_rotation.z ).c_str() );
1842
1843 m_out->Print( ")" );
1844 }
1845
1846 // Save 3D info.
1847 auto bs3D = aFootprint->Models().begin();
1848 auto es3D = aFootprint->Models().end();
1849
1850 while( bs3D != es3D )
1851 {
1852 if( !bs3D->m_Filename.IsEmpty() )
1853 {
1854 m_out->Print( "(model %s", m_out->Quotew( bs3D->m_Filename ).c_str() );
1855
1856 if( !bs3D->m_Show )
1857 KICAD_FORMAT::FormatBool( m_out, "hide", !bs3D->m_Show );
1858
1859 if( bs3D->m_Opacity != 1.0 )
1860 m_out->Print( "%s", fmt::format("(opacity {:.4f})", bs3D->m_Opacity).c_str() );
1861
1862 m_out->Print( "(offset (xyz %s %s %s))",
1863 FormatDouble2Str( bs3D->m_Offset.x ).c_str(),
1864 FormatDouble2Str( bs3D->m_Offset.y ).c_str(),
1865 FormatDouble2Str( bs3D->m_Offset.z ).c_str() );
1866
1867 m_out->Print( "(scale (xyz %s %s %s))",
1868 FormatDouble2Str( bs3D->m_Scale.x ).c_str(),
1869 FormatDouble2Str( bs3D->m_Scale.y ).c_str(),
1870 FormatDouble2Str( bs3D->m_Scale.z ).c_str() );
1871
1872 m_out->Print( "(rotate (xyz %s %s %s))",
1873 FormatDouble2Str( bs3D->m_Rotation.x ).c_str(),
1874 FormatDouble2Str( bs3D->m_Rotation.y ).c_str(),
1875 FormatDouble2Str( bs3D->m_Rotation.z ).c_str() );
1876
1877 m_out->Print( ")" );
1878 }
1879
1880 ++bs3D;
1881 }
1882
1884 m_out->Print( ")" );
1885}
1886
1887
1888void PCB_IO_KICAD_SEXPR::formatLayers( LSET aLayerMask, bool aEnumerateLayers, bool aIsZone ) const
1889{
1890 static const LSET cu_all( LSET::AllCuMask() );
1891 static const LSET fr_bk( { B_Cu, F_Cu } );
1892 static const LSET adhes( { B_Adhes, F_Adhes } );
1893 static const LSET paste( { B_Paste, F_Paste } );
1894 static const LSET silks( { B_SilkS, F_SilkS } );
1895 static const LSET mask( { B_Mask, F_Mask } );
1896 static const LSET crt_yd( { B_CrtYd, F_CrtYd } );
1897 static const LSET fab( { B_Fab, F_Fab } );
1898
1899 LSET cu_board_mask = LSET::AllCuMask( m_board ? m_board->GetCopperLayerCount() : MAX_CU_LAYERS );
1900
1901 std::string output;
1902
1903 if( !aEnumerateLayers )
1904 {
1905 // If all copper layers present on the board are enabled, then output the wildcard
1906 if( ( aLayerMask & cu_board_mask ) == cu_board_mask )
1907 {
1908 output += ' ' + m_out->Quotew( "*.Cu" );
1909
1910 // Clear all copper bits because pads might have internal layers that aren't part of the
1911 // board enabled, and we don't want to output those in the layers listing if we already
1912 // output the wildcard.
1913 aLayerMask &= ~cu_all;
1914 }
1915 else if( ( aLayerMask & cu_board_mask ) == fr_bk )
1916 {
1917 if( aIsZone )
1918 output += ' ' + m_out->Quotew( "F&B.Cu" );
1919 else
1920 output += ' ' + m_out->Quotew( "*.Cu" );
1921
1922 aLayerMask &= ~fr_bk;
1923 }
1924
1925 if( ( aLayerMask & adhes ) == adhes )
1926 {
1927 output += ' ' + m_out->Quotew( "*.Adhes" );
1928 aLayerMask &= ~adhes;
1929 }
1930
1931 if( ( aLayerMask & paste ) == paste )
1932 {
1933 output += ' ' + m_out->Quotew( "*.Paste" );
1934 aLayerMask &= ~paste;
1935 }
1936
1937 if( ( aLayerMask & silks ) == silks )
1938 {
1939 output += ' ' + m_out->Quotew( "*.SilkS" );
1940 aLayerMask &= ~silks;
1941 }
1942
1943 if( ( aLayerMask & mask ) == mask )
1944 {
1945 output += ' ' + m_out->Quotew( "*.Mask" );
1946 aLayerMask &= ~mask;
1947 }
1948
1949 if( ( aLayerMask & crt_yd ) == crt_yd )
1950 {
1951 output += ' ' + m_out->Quotew( "*.CrtYd" );
1952 aLayerMask &= ~crt_yd;
1953 }
1954
1955 if( ( aLayerMask & fab ) == fab )
1956 {
1957 output += ' ' + m_out->Quotew( "*.Fab" );
1958 aLayerMask &= ~fab;
1959 }
1960 }
1961
1962 // output any individual layers not handled in wildcard combos above
1963 for( int layer = 0; layer < PCB_LAYER_ID_COUNT; ++layer )
1964 {
1965 if( aLayerMask[layer] )
1966 output += ' ' + m_out->Quotew( LSET::Name( PCB_LAYER_ID( layer ) ) );
1967 }
1968
1969 m_out->Print( "(layers %s)", output.c_str() );
1970}
1971
1972
1973void PCB_IO_KICAD_SEXPR::format( const PAD* aPad ) const
1974{
1975 const BOARD* board = aPad->GetBoard();
1976 const FOOTPRINT* parentFP = aPad->GetParentFootprint();
1977
1978 auto shapeName =
1979 [&]( PCB_LAYER_ID aLayer )
1980 {
1981 switch( aPad->GetShape( aLayer ) )
1982 {
1983 case PAD_SHAPE::CIRCLE: return "circle";
1984 case PAD_SHAPE::RECTANGLE: return "rect";
1985 case PAD_SHAPE::OVAL: return "oval";
1986 case PAD_SHAPE::TRAPEZOID: return "trapezoid";
1988 case PAD_SHAPE::ROUNDRECT: return "roundrect";
1989 case PAD_SHAPE::CUSTOM: return "custom";
1990
1991 default:
1992 THROW_IO_ERRORF( _( "unknown pad type: %d" ), aPad->GetShape( aLayer ) );
1993 }
1994 };
1995
1996 const char* type = nullptr;
1997
1998 switch( aPad->GetAttribute() )
1999 {
2000 case PAD_ATTRIB::PTH: type = "thru_hole"; break;
2001 case PAD_ATTRIB::SMD: type = "smd"; break;
2002 case PAD_ATTRIB::CONN: type = "connect"; break;
2003 case PAD_ATTRIB::NON_COMPONENT: type = "non_component"; break;
2004 case PAD_ATTRIB::NPTH: type = "np_thru_hole"; break;
2005
2006 default:
2007 THROW_IO_ERRORF( _( "unknown pad attribute: %d" ), aPad->GetAttribute() );
2008 }
2009
2010 const char* property = nullptr;
2011
2012 switch( aPad->GetProperty() )
2013 {
2014 case PAD_PROP::NONE: break; // could be "none"
2015 case PAD_PROP::BGA: property = "pad_prop_bga"; break;
2016 case PAD_PROP::FIDUCIAL_GLBL: property = "pad_prop_fiducial_glob"; break;
2017 case PAD_PROP::FIDUCIAL_LOCAL: property = "pad_prop_fiducial_loc"; break;
2018 case PAD_PROP::TESTPOINT: property = "pad_prop_testpoint"; break;
2019 case PAD_PROP::HEATSINK: property = "pad_prop_heatsink"; break;
2020 case PAD_PROP::CASTELLATED: property = "pad_prop_castellated"; break;
2021 case PAD_PROP::MECHANICAL: property = "pad_prop_mechanical"; break;
2022 case PAD_PROP::PRESSFIT: property = "pad_prop_pressfit"; break;
2023
2024 default:
2025 THROW_IO_ERRORF( _( "unknown pad property: %d" ), aPad->GetProperty() );
2026 }
2027
2028 const char* simElectricalType = nullptr;
2029
2030 switch( aPad->GetSimElectricalType() )
2031 {
2032 case PAD_SIM_ELECTRICAL_TYPE::SOURCE: simElectricalType = "source"; break;
2033 case PAD_SIM_ELECTRICAL_TYPE::SINK: simElectricalType = "sink"; break;
2034 default: simElectricalType = nullptr; break;
2035 }
2036
2037 m_out->Print( "(pad %s %s %s",
2038 m_out->Quotew( aPad->GetNumber() ).c_str(),
2039 type,
2040 shapeName( F_Cu ) );
2041
2042 m_out->Print( "(at %s %s)",
2043 formatInternalUnits( aPad->GetFPRelativePosition() ).c_str(),
2044 aPad->GetOrientation().IsZero() ? ""
2045 : EDA_UNIT_UTILS::FormatAngle( aPad->GetOrientation() ).c_str() );
2046
2047 // Write the stored library size directly: it is the footprint-frame value the parser
2048 // reads back, and avoids a bake/unbake that is not the inverse of GetSize() for a
2049 // pad rotated within the footprint.
2050 m_out->Print( "(size %s)", formatInternalUnits( aPad->Padstack().Size( F_Cu ) ).c_str() );
2051
2052 if( aPad->GetDelta( F_Cu ).x != 0 || aPad->GetDelta( F_Cu ).y != 0 )
2053 m_out->Print( "(rect_delta %s)", formatInternalUnits( aPad->GetDelta( F_Cu ) ).c_str() );
2054
2055 const VECTOR2I drill = aPad->GetDrillShape() == PAD_DRILL_SHAPE::CIRCLE
2056 ? unbakeSizeUniform( aPad->GetDrillSize(), parentFP )
2057 : unbakeSize( aPad->GetDrillSize(), parentFP );
2058 VECTOR2I shapeoffset = aPad->GetOffset( F_Cu );
2059 bool forceShapeOffsetOutput = false;
2060
2062 [&]( PCB_LAYER_ID layer )
2063 {
2064 if( aPad->GetOffset( layer ) != shapeoffset )
2065 forceShapeOffsetOutput = true;
2066 } );
2067
2068 if( drill.x > 0 || drill.y > 0 || shapeoffset.x != 0 || shapeoffset.y != 0 || forceShapeOffsetOutput )
2069 {
2070 m_out->Print( "(drill" );
2071
2072 if( aPad->GetDrillShape() == PAD_DRILL_SHAPE::OBLONG )
2073 m_out->Print( " oval" );
2074
2075 if( drill.x > 0 )
2076 m_out->Print( " %s", formatInternalUnits( drill.x ).c_str() );
2077
2078 if( drill.y > 0 && drill.x != drill.y )
2079 m_out->Print( " %s", formatInternalUnits( drill.y ).c_str() );
2080
2081 // NOTE: Shape offest is a property of the copper shape, not of the drill, but this was put
2082 // in the file format under the drill section. So, it is left here to minimize file format
2083 // changes, but note that the other padstack layers (if present) will have an offset stored
2084 // separately.
2085 if( shapeoffset.x != 0 || shapeoffset.y != 0 || forceShapeOffsetOutput )
2086 m_out->Print( "(offset %s)", formatInternalUnits( aPad->Padstack().Offset( F_Cu ) ).c_str() );
2087
2088 m_out->Print( ")" );
2089 }
2090
2091
2092 if( aPad->Padstack().SecondaryDrill().size.x > 0 && aPad->Padstack().SecondaryDrill().start != UNDEFINED_LAYER )
2093 {
2094 m_out->Print( "(backdrill (size %s) (layers %s %s))",
2095 formatInternalUnits( aPad->Padstack().SecondaryDrill().size.x ).c_str(),
2096 m_out->Quotew( LSET::Name( aPad->Padstack().SecondaryDrill().start ) ).c_str(),
2097 m_out->Quotew( LSET::Name( aPad->Padstack().SecondaryDrill().end ) ).c_str() );
2098 }
2099
2100 if( aPad->Padstack().TertiaryDrill().size.x > 0 && aPad->Padstack().TertiaryDrill().start != UNDEFINED_LAYER )
2101 {
2102 m_out->Print( "(tertiary_drill (size %s) (layers %s %s))",
2103 formatInternalUnits( aPad->Padstack().TertiaryDrill().size.x ).c_str(),
2104 m_out->Quotew( LSET::Name( aPad->Padstack().TertiaryDrill().start ) ).c_str(),
2105 m_out->Quotew( LSET::Name( aPad->Padstack().TertiaryDrill().end ) ).c_str() );
2106 }
2107
2108 auto formatPostMachining =
2109 [&]( const char* aName, const PADSTACK::POST_MACHINING_PROPS& aProps )
2110 {
2111 if( !aProps.mode.has_value() || aProps.mode == PAD_DRILL_POST_MACHINING_MODE::NOT_POST_MACHINED )
2112 return;
2113
2114 m_out->Print( "(%s %s",
2115 aName,
2116 aProps.mode == PAD_DRILL_POST_MACHINING_MODE::COUNTERBORE ? "counterbore"
2117 : "countersink" );
2118
2119 if( aProps.size > 0 )
2120 m_out->Print( " (size %s)", formatInternalUnits( aProps.size ).c_str() );
2121
2122 if( aProps.depth > 0 )
2123 m_out->Print( " (depth %s)", formatInternalUnits( aProps.depth ).c_str() );
2124
2125 if( aProps.angle > 0 )
2126 m_out->Print( " (angle %s)", FormatDouble2Str( aProps.angle / 10.0 ).c_str() );
2127
2128 m_out->Print( ")" );
2129 };
2130
2131 formatPostMachining( "front_post_machining", aPad->Padstack().FrontPostMachining() );
2132 formatPostMachining( "back_post_machining", aPad->Padstack().BackPostMachining() );
2133
2134 // Add pad property, if exists.
2135 if( property )
2136 m_out->Print( "(property %s)", property );
2137
2138 if( simElectricalType )
2139 m_out->Print( "(sim_electrical_type %s)", simElectricalType );
2140
2141 formatLayers( aPad->GetLayerSet(), false /* enumerate layers */ );
2142
2143 if( aPad->GetAttribute() == PAD_ATTRIB::PTH )
2144 {
2145 KICAD_FORMAT::FormatBool( m_out, "remove_unused_layers", aPad->GetRemoveUnconnected() );
2146
2147 if( aPad->GetRemoveUnconnected() )
2148 {
2149 KICAD_FORMAT::FormatBool( m_out, "keep_end_layers", aPad->GetKeepTopBottom() );
2150
2151 if( board ) // Will be nullptr in footprint library
2152 {
2153 m_out->Print( "(zone_layer_connections" );
2154
2155 for( PCB_LAYER_ID layer : board->GetEnabledLayers().CuStack() )
2156 {
2157 if( aPad->GetZoneLayerOverride( layer ) == ZLO_FORCE_FLASHED )
2158 m_out->Print( " %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
2159 }
2160
2161 m_out->Print( ")" );
2162 }
2163 }
2164 }
2165
2166 auto formatCornerProperties =
2167 [&]( PCB_LAYER_ID aLayer )
2168 {
2169 // Output the radius ratio for rounded and chamfered rect pads
2170 if( aPad->GetShape( aLayer ) == PAD_SHAPE::ROUNDRECT
2171 || aPad->GetShape( aLayer ) == PAD_SHAPE::CHAMFERED_RECT)
2172 {
2173 m_out->Print( "(roundrect_rratio %s)",
2174 FormatDouble2Str( aPad->GetRoundRectRadiusRatio( aLayer ) ).c_str() );
2175 }
2176
2177 // Output the chamfer corners for chamfered rect pads
2178 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CHAMFERED_RECT)
2179 {
2180 m_out->Print( "(chamfer_ratio %s)",
2181 FormatDouble2Str( aPad->GetChamferRectRatio( aLayer ) ).c_str() );
2182
2183 m_out->Print( "(chamfer" );
2184
2185 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_TOP_LEFT ) )
2186 m_out->Print( " top_left" );
2187
2188 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_TOP_RIGHT ) )
2189 m_out->Print( " top_right" );
2190
2191 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_BOTTOM_LEFT ) )
2192 m_out->Print( " bottom_left" );
2193
2194 if( ( aPad->GetChamferPositions( aLayer ) & RECT_CHAMFER_BOTTOM_RIGHT ) )
2195 m_out->Print( " bottom_right" );
2196
2197 m_out->Print( ")" );
2198 }
2199
2200 };
2201
2202 // For normal padstacks, this is the one and only set of properties. For complex ones, this
2203 // will represent the front layer properties, and other layers will be formatted below
2204 formatCornerProperties( F_Cu );
2205
2206 // Unconnected pad is default net so don't save it.
2207 if( !( m_ctl & CTL_OMIT_PAD_NETS ) && aPad->GetNetCode() > 0 )
2208 m_out->Print( "(net %s)", m_out->Quotew( aPad->GetNetname() ).c_str() );
2209
2210 // Pin functions and types are closely related to nets, so if CTL_OMIT_NETS is set, omit
2211 // them as well (for instance when saved from library editor).
2212 if( !( m_ctl & CTL_OMIT_PAD_NETS ) )
2213 {
2214 if( !aPad->GetPinFunction().IsEmpty() )
2215 m_out->Print( "(pinfunction %s)", m_out->Quotew( aPad->GetPinFunction() ).c_str() );
2216
2217 if( !aPad->GetPinType().IsEmpty() )
2218 m_out->Print( "(pintype %s)", m_out->Quotew( aPad->GetPinType() ).c_str() );
2219 }
2220
2221 if( aPad->GetPadToDieLength() != 0 )
2222 {
2223 m_out->Print( "(die_length %s)",
2224 formatInternalUnits( aPad->GetPadToDieLength() ).c_str() );
2225 }
2226
2227 if( aPad->GetPadToDieDelay() != 0 )
2228 {
2229 m_out->Print( "(die_delay %s)",
2231 }
2232
2233 if( aPad->GetLocalSolderMaskMargin().has_value() )
2234 {
2235 m_out->Print( "(solder_mask_margin %s)",
2236 formatInternalUnits( aPad->GetLocalSolderMaskMargin().value() ).c_str() );
2237 }
2238
2239 if( aPad->GetLocalSolderPasteMargin().has_value() )
2240 {
2241 m_out->Print( "(solder_paste_margin %s)",
2242 formatInternalUnits( aPad->GetLocalSolderPasteMargin().value() ).c_str() );
2243 }
2244
2245 if( aPad->GetLocalSolderPasteMarginRatio().has_value() )
2246 {
2247 m_out->Print( "(solder_paste_margin_ratio %s)",
2248 FormatDouble2Str( aPad->GetLocalSolderPasteMarginRatio().value() ).c_str() );
2249 }
2250
2251 if( aPad->GetLocalClearance().has_value() )
2252 {
2253 m_out->Print( "(clearance %s)",
2254 formatInternalUnits( aPad->GetLocalClearance().value() ).c_str() );
2255 }
2256
2258 {
2259 m_out->Print( "(zone_connect %d)",
2260 static_cast<int>( aPad->GetLocalZoneConnection() ) );
2261 }
2262
2263 if( aPad->GetLocalThermalSpokeWidthOverride().has_value() )
2264 {
2265 m_out->Print( "(thermal_bridge_width %s)",
2266 formatInternalUnits( aPad->GetLocalThermalSpokeWidthOverride().value() ).c_str() );
2267 }
2268
2270 {
2271 m_out->Print( "(thermal_bridge_angle %s)",
2273 }
2274
2275 if( aPad->GetLocalThermalGapOverride().has_value() )
2276 {
2277 m_out->Print( "(thermal_gap %s)",
2278 formatInternalUnits( aPad->GetLocalThermalGapOverride().value() ).c_str() );
2279 }
2280
2281 auto anchorShape =
2282 [&]( PCB_LAYER_ID aLayer )
2283 {
2284 switch( aPad->GetAnchorPadShape( aLayer ) )
2285 {
2286 case PAD_SHAPE::RECTANGLE: return "rect";
2287 default:
2288 case PAD_SHAPE::CIRCLE: return "circle";
2289 }
2290 };
2291
2292 auto formatPrimitives =
2293 [&]( PCB_LAYER_ID aLayer )
2294 {
2295 m_out->Print( "(primitives" );
2296
2297 // Output all basic shapes
2298 for( const std::shared_ptr<PCB_SHAPE>& primitive : aPad->GetPrimitives( aLayer ) )
2299 {
2300 const SHAPE_T libShape = primitive->GetLibraryShape();
2301
2302 switch( libShape )
2303 {
2304 case SHAPE_T::SEGMENT:
2305 if( primitive->IsProxyItem() )
2306 {
2307 m_out->Print( "(gr_vector (start %s) (end %s)",
2308 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2309 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2310 }
2311 else
2312 {
2313 m_out->Print( "(gr_line (start %s) (end %s)",
2314 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2315 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2316 }
2317 break;
2318
2319 case SHAPE_T::RECTANGLE:
2320 if( primitive->IsProxyItem() )
2321 {
2322 m_out->Print( "(gr_bbox (start %s) (end %s)",
2323 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2324 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2325 }
2326 else
2327 {
2328 m_out->Print( "(gr_rect (start %s) (end %s)",
2329 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2330 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2331
2332 if( primitive->GetCornerRadius() > 0 )
2333 {
2334 m_out->Print( " (radius %s)",
2335 formatInternalUnits( primitive->GetLibraryCornerRadius() ).c_str() );
2336 }
2337 }
2338 break;
2339
2340 case SHAPE_T::ARC:
2341 m_out->Print( "(gr_arc (start %s) (mid %s) (end %s)",
2342 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2343 formatInternalUnits( primitive->GetLibraryArcMid() ).c_str(),
2344 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2345 break;
2346
2347 case SHAPE_T::CIRCLE:
2348 m_out->Print( "(gr_circle (center %s) (end %s)",
2349 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2350 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2351 break;
2352
2353 case SHAPE_T::BEZIER:
2354 // Pad primitives are stored in raw library coordinates and read back
2355 // raw, so emit library coordinates like the other primitive types above.
2356 m_out->Print( "(gr_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
2357 formatInternalUnits( primitive->GetLibraryStart() ).c_str(),
2358 formatInternalUnits( primitive->GetLibraryBezierC1() ).c_str(),
2359 formatInternalUnits( primitive->GetLibraryBezierC2() ).c_str(),
2360 formatInternalUnits( primitive->GetLibraryEnd() ).c_str() );
2361 break;
2362
2363 case SHAPE_T::POLY:
2364 if( primitive->IsPolyShapeValid() )
2365 {
2366 const SHAPE_POLY_SET poly = primitive->GetLibraryPolyShape();
2367 const SHAPE_LINE_CHAIN& outline = poly.Outline( 0 );
2368
2369 m_out->Print( "(gr_poly" );
2370 formatPolyPts( outline );
2371 }
2372 break;
2373
2374 default:
2375 break;
2376 }
2377
2378 if( !primitive->IsProxyItem() )
2379 m_out->Print( "(width %s)", formatInternalUnits( primitive->GetWidth() ).c_str() );
2380
2381 // The filled flag represents if a solid fill is present on circles,
2382 // rectangles and polygons
2383 if( libShape == SHAPE_T::POLY || libShape == SHAPE_T::RECTANGLE || libShape == SHAPE_T::CIRCLE )
2384 {
2385 KICAD_FORMAT::FormatBool( m_out, "fill", primitive->IsSolidFill() );
2386 }
2387
2388 m_out->Print( ")" );
2389 }
2390
2391 m_out->Print( ")" ); // end of (primitives
2392 };
2393
2394 if( aPad->GetShape( F_Cu ) == PAD_SHAPE::CUSTOM )
2395 {
2396 m_out->Print( "(options" );
2397
2399 m_out->Print( "(clearance convexhull)" );
2400 else
2401 m_out->Print( "(clearance outline)" );
2402
2403 // Output the anchor pad shape (circle/rect)
2404 m_out->Print( "(anchor %s)", anchorShape( F_Cu ) );
2405
2406 m_out->Print( ")"); // end of (options ...
2407
2408 // Output graphic primitive of the pad shape
2409 formatPrimitives( F_Cu );
2410 }
2411
2414
2415 if( aPad->Padstack().FrontOuterLayers().has_solder_mask.has_value()
2416 || aPad->Padstack().BackOuterLayers().has_solder_mask.has_value() )
2417 {
2418 m_out->Print( 0, " (tenting " );
2423 m_out->Print( 0, ")" );
2424 }
2425
2427
2428 // TODO: Refactor so that we call formatPadLayer( ALL_LAYERS ) above instead of redundant code
2429 auto formatPadLayer =
2430 [&]( PCB_LAYER_ID aLayer )
2431 {
2432 const PADSTACK& padstack = aPad->Padstack();
2433
2434 m_out->Print( "(shape %s)", shapeName( aLayer ) );
2435
2436 m_out->Print( "(size %s)", formatInternalUnits( padstack.Size( aLayer ) ).c_str() );
2437
2438 const VECTOR2I& delta = aPad->GetDelta( aLayer );
2439
2440 if( delta.x != 0 || delta.y != 0 )
2441 m_out->Print( "(rect_delta %s)", formatInternalUnits( delta ).c_str() );
2442
2443 shapeoffset = aPad->GetOffset( aLayer );
2444
2445 if( shapeoffset.x != 0 || shapeoffset.y != 0 )
2446 m_out->Print( "(offset %s)", formatInternalUnits( padstack.Offset( aLayer ) ).c_str() );
2447
2448 formatCornerProperties( aLayer );
2449
2450 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
2451 {
2452 m_out->Print( "(options" );
2453
2455 m_out->Print( "(clearance convexhull)" );
2456 else
2457 m_out->Print( "(clearance outline)" );
2458
2459 // Output the anchor pad shape (circle/rect)
2460 m_out->Print( "(anchor %s)", anchorShape( aLayer ) );
2461
2462 m_out->Print( ")" ); // end of (options ...
2463
2464 // Output graphic primitive of the pad shape
2465 formatPrimitives( aLayer );
2466 }
2467
2468 EDA_ANGLE defaultLayerAngle = ANGLE_90;
2469
2470 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CIRCLE ||
2471 ( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM
2472 && aPad->GetAnchorPadShape( aLayer ) == PAD_SHAPE::CIRCLE ) )
2473 {
2474 defaultLayerAngle = ANGLE_45;
2475 }
2476
2477 EDA_ANGLE layerSpokeAngle = padstack.ThermalSpokeAngle( aLayer );
2478
2479 if( layerSpokeAngle != defaultLayerAngle )
2480 {
2481 m_out->Print( "(thermal_bridge_angle %s)",
2482 EDA_UNIT_UTILS::FormatAngle( layerSpokeAngle ).c_str() );
2483 }
2484
2485 if( padstack.ThermalGap( aLayer ).has_value() )
2486 {
2487 m_out->Print( "(thermal_gap %s)",
2488 formatInternalUnits( *padstack.ThermalGap( aLayer ) ).c_str() );
2489 }
2490
2491 if( padstack.ThermalSpokeWidth( aLayer ).has_value() )
2492 {
2493 m_out->Print( "(thermal_bridge_width %s)",
2494 formatInternalUnits( *padstack.ThermalSpokeWidth( aLayer ) ).c_str() );
2495 }
2496
2497 if( padstack.Clearance( aLayer ).has_value() )
2498 {
2499 m_out->Print( "(clearance %s)",
2500 formatInternalUnits( *padstack.Clearance( aLayer ) ).c_str() );
2501 }
2502
2503 if( padstack.ZoneConnection( aLayer ).has_value() )
2504 {
2505 m_out->Print( "(zone_connect %d)",
2506 static_cast<int>( *padstack.ZoneConnection( aLayer ) ) );
2507 }
2508 };
2509
2510
2511 if( aPad->Padstack().Mode() != PADSTACK::MODE::NORMAL )
2512 {
2514 {
2515 m_out->Print( "(padstack (mode front_inner_back)" );
2516
2517 m_out->Print( "(layer \"Inner\"" );
2518 formatPadLayer( PADSTACK::INNER_LAYERS );
2519 m_out->Print( ")" );
2520 m_out->Print( "(layer \"B.Cu\"" );
2521 formatPadLayer( B_Cu );
2522 m_out->Print( ")" );
2523 }
2524 else
2525 {
2526 m_out->Print( "(padstack (mode custom)" );
2527
2528 int layerCount = board ? board->GetCopperLayerCount() : MAX_CU_LAYERS;
2529
2530 for( PCB_LAYER_ID layer : LAYER_RANGE( F_Cu, B_Cu, layerCount ) )
2531 {
2532 if( layer == F_Cu )
2533 continue;
2534
2535 // Without a board there is no layer count, so list only the layers the pad defines
2536 if( !board && !aPad->Padstack().HasExplicitDefinitionForLayer( layer ) )
2537 continue;
2538
2539 m_out->Print( "(layer %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
2540 formatPadLayer( layer );
2541 m_out->Print( ")" );
2542 }
2543 }
2544
2545 m_out->Print( ")" );
2546 }
2547
2549 m_out->Print( ")" );
2550}
2551
2552
2553void PCB_IO_KICAD_SEXPR::format( const PCB_BARCODE* aBarcode ) const
2554{
2555 wxCHECK_RET( aBarcode != nullptr && m_out != nullptr, "" );
2556
2557 m_out->Print( "(barcode" );
2558
2559 if( aBarcode->IsLocked() )
2560 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2561
2562 m_out->Print( "(at %s %s)",
2563 formatInternalUnits( aBarcode->GetPosition() ).c_str(),
2564 EDA_UNIT_UTILS::FormatAngle( aBarcode->GetAngle() ).c_str() );
2565
2566 formatLayer( aBarcode->GetLayer() );
2567
2568 m_out->Print( "(size %s %s)",
2569 formatInternalUnits( aBarcode->GetWidth() ).c_str(),
2570 formatInternalUnits( aBarcode->GetHeight() ).c_str() );
2571
2572 m_out->Print( "(text %s)", m_out->Quotew( aBarcode->GetText() ).c_str() );
2573
2574 m_out->Print( "(text_height %s)", formatInternalUnits( aBarcode->GetTextSize() ).c_str() );
2575
2576 const char* typeStr = "code39";
2577
2578 switch( aBarcode->GetKind() )
2579 {
2580 case BARCODE_T::CODE_39: typeStr = "code39"; break;
2581 case BARCODE_T::CODE_128: typeStr = "code128"; break;
2582 case BARCODE_T::DATA_MATRIX: typeStr = "datamatrix"; break;
2583 case BARCODE_T::QR_CODE: typeStr = "qr"; break;
2584 case BARCODE_T::MICRO_QR_CODE: typeStr = "microqr"; break;
2585 }
2586
2587 m_out->Print( "(type %s)", typeStr );
2588
2589 if( aBarcode->GetKind() == BARCODE_T::QR_CODE
2590 || aBarcode->GetKind() == BARCODE_T::MICRO_QR_CODE )
2591 {
2592 const char* eccStr = "L";
2593 switch( aBarcode->GetErrorCorrection() )
2594 {
2595 case BARCODE_ECC_T::L: eccStr = "L"; break;
2596 case BARCODE_ECC_T::M: eccStr = "M"; break;
2597 case BARCODE_ECC_T::Q: eccStr = "Q"; break;
2598 case BARCODE_ECC_T::H: eccStr = "H"; break;
2599 }
2600
2601 m_out->Print( "(ecc_level %s)", eccStr );
2602 }
2603
2604 KICAD_FORMAT::FormatBool( m_out, "hide", !aBarcode->GetShowText() );
2605 KICAD_FORMAT::FormatBool( m_out, "knockout", aBarcode->IsKnockout() );
2606
2607 if( aBarcode->GetMargin().x != 0 || aBarcode->GetMargin().y != 0 )
2608 {
2609 m_out->Print( "(margins %s %s)", formatInternalUnits( aBarcode->GetMargin().x ).c_str(),
2610 formatInternalUnits( aBarcode->GetMargin().y ).c_str() );
2611 }
2612
2614
2616 m_out->Print( ")" );
2617}
2618
2619
2620void PCB_IO_KICAD_SEXPR::format( const PCB_TEXT* aText ) const
2621{
2622 FOOTPRINT* parentFP = aText->GetParentFootprint();
2623 std::string prefix;
2624 std::string type;
2625 VECTOR2I pos = aText->GetTextPos();
2626 // Match the Type() dispatch in Format(); a field body is headerless, so it is only valid
2627 // inside the (property ...) its caller opened
2628 const PCB_FIELD* field = aText->Type() == PCB_FIELD_T ? static_cast<const PCB_FIELD*>( aText )
2629 : nullptr;
2630
2631 // Always format dimension text as gr_text
2632 if( dynamic_cast<const PCB_DIMENSION_BASE*>( aText ) )
2633 parentFP = nullptr;
2634
2635 if( parentFP )
2636 {
2637 prefix = "fp";
2638 type = "user";
2639
2640 pos = parentFP->GetTransform().InverseApply( pos );
2641 }
2642 else
2643 {
2644 prefix = "gr";
2645 }
2646
2647 if( !field )
2648 {
2649 m_out->Print( "(%s_text %s %s",
2650 prefix.c_str(),
2651 type.c_str(),
2652 m_out->Quotew( aText->GetText() ).c_str() );
2653 }
2654
2655 if( aText->IsLocked() )
2656 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2657
2658 m_out->Print( "(at %s %s)",
2659 formatInternalUnits( pos ).c_str(),
2660 EDA_UNIT_UTILS::FormatAngle( aText->GetTextAngle() ).c_str() );
2661
2662 if( parentFP && !aText->IsKeepUpright() )
2663 KICAD_FORMAT::FormatBool( m_out, "unlocked", true );
2664
2665 formatLayer( aText->GetLayer(), aText->IsKnockout() );
2666
2667 if( field && !field->IsVisible() )
2668 KICAD_FORMAT::FormatBool( m_out, "hide", true );
2669
2671
2672 // Currently, texts have no specific color and no hyperlink.
2673 // so ensure they are never written in kicad_pcb file
2674 int ctl_flags = CTL_OMIT_COLOR | CTL_OMIT_HYPERLINK;
2675
2676 if( parentFP )
2677 {
2678 // Footprint text accessors return board-frame sizes, so format the stored library-frame attributes
2679 EDA_TEXT libText( pcbIUScale );
2680 libText.SetAttributes( aText->GetAttributes() );
2681 libText.Format( m_out, ctl_flags );
2682 }
2683 else
2684 {
2685 aText->EDA_TEXT::Format( m_out, ctl_flags );
2686 }
2687
2688 if( aText->GetFont() && aText->GetFont()->IsOutline() )
2689 formatRenderCache( aText );
2690
2692
2693 if( !field )
2694 m_out->Print( ")" );
2695}
2696
2697
2698void PCB_IO_KICAD_SEXPR::format( const PCB_TEXTBOX* aTextBox ) const
2699{
2700 FOOTPRINT* parentFP = aTextBox->GetParentFootprint();
2701
2702 m_out->Print( "(%s %s",
2703 aTextBox->Type() == PCB_TABLECELL_T ? "table_cell"
2704 : parentFP ? "fp_text_box"
2705 : "gr_text_box",
2706 m_out->Quotew( aTextBox->GetText() ).c_str() );
2707
2708 if( aTextBox->IsLocked() )
2709 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2710
2711 // Use the lib-frame shape. The board-frame shape can flip to POLY for
2712 // rendering when the FP rotation is non-cardinal.
2713 SHAPE_T libShape = aTextBox->GetLibraryShape();
2714
2715 if( libShape == SHAPE_T::RECTANGLE )
2716 {
2717 m_out->Print( "(start %s) (end %s)", formatInternalUnits( aTextBox->GetLibraryStart() ).c_str(),
2718 formatInternalUnits( aTextBox->GetLibraryEnd() ).c_str() );
2719 }
2720 else if( libShape == SHAPE_T::POLY )
2721 {
2722 // Fall back to the runtime polygon if the lib copy was never seeded.
2723 const SHAPE_POLY_SET& libPoly = aTextBox->GetLibPoly();
2724 const bool haveLibPoly = libPoly.OutlineCount() > 0;
2725 const SHAPE_POLY_SET& poly = haveLibPoly ? libPoly : aTextBox->GetPolyShape();
2726
2727 if( poly.OutlineCount() > 0 )
2728 formatPolyPts( poly.Outline( 0 ), haveLibPoly ? nullptr : parentFP );
2729 }
2730 else
2731 {
2732 UNIMPLEMENTED_FOR( aTextBox->SHAPE_T_asString() );
2733 }
2734
2735 m_out->Print( "(margins %s %s %s %s)",
2736 formatInternalUnits( aTextBox->GetMarginLeft() ).c_str(),
2737 formatInternalUnits( aTextBox->GetMarginTop() ).c_str(),
2738 formatInternalUnits( aTextBox->GetMarginRight() ).c_str(),
2739 formatInternalUnits( aTextBox->GetMarginBottom() ).c_str() );
2740
2741 if( const PCB_TABLECELL* cell = dynamic_cast<const PCB_TABLECELL*>( aTextBox ) )
2742 m_out->Print( "(span %d %d)", cell->GetColSpan(), cell->GetRowSpan() );
2743
2744 EDA_ANGLE angle = aTextBox->GetTextAngle();
2745
2746 if( parentFP )
2747 {
2748 angle -= parentFP->GetOrientation();
2749 angle.Normalize720();
2750 }
2751
2752 if( !angle.IsZero() )
2753 m_out->Print( "(angle %s)", EDA_UNIT_UTILS::FormatAngle( angle ).c_str() );
2754
2755 formatLayer( aTextBox->GetLayer() );
2756
2758
2759 aTextBox->EDA_TEXT::Format( m_out, 0 );
2760
2761 if( aTextBox->Type() != PCB_TABLECELL_T )
2762 {
2763 KICAD_FORMAT::FormatBool( m_out, "border", aTextBox->IsBorderEnabled() );
2764 aTextBox->GetStroke().Format( m_out, pcbIUScale );
2765 }
2766
2767 KICAD_FORMAT::FormatBool( m_out, "knockout", aTextBox->IsKnockout() );
2768
2769 if( aTextBox->GetFont() && aTextBox->GetFont()->IsOutline() )
2770 formatRenderCache( aTextBox );
2771
2773 m_out->Print( ")" );
2774}
2775
2776
2778{
2779 // Carries geometry and cells only. Identity belongs to whatever encloses this, or a
2780 // drill chart would write its uuid and layer twice and the second copy would win on load
2781 m_out->Print( "(column_count %d)", aTable->GetColCount() );
2782
2783 m_out->Print( "(border" );
2784 KICAD_FORMAT::FormatBool( m_out, "external", aTable->StrokeExternal() );
2786
2787 if( aTable->StrokeExternal() || aTable->StrokeHeaderSeparator() )
2788 aTable->GetBorderStroke().Format( m_out, pcbIUScale );
2789
2790 m_out->Print( ")" ); // Close `border` token.
2791
2792 m_out->Print( "(separators" );
2793 KICAD_FORMAT::FormatBool( m_out, "rows", aTable->StrokeRows() );
2794 KICAD_FORMAT::FormatBool( m_out, "cols", aTable->StrokeColumns() );
2795
2796 if( aTable->StrokeRows() || aTable->StrokeColumns() )
2798
2799 m_out->Print( ")" ); // Close `separators` token.
2800
2801 m_out->Print( "(column_widths" );
2802
2803 for( int col = 0; col < aTable->GetColCount(); ++col )
2804 m_out->Print( " %s", formatInternalUnits( aTable->GetColWidth( col ) ).c_str() );
2805
2806 m_out->Print( ")" );
2807
2808 m_out->Print( "(row_heights" );
2809
2810 for( int row = 0; row < aTable->GetRowCount(); ++row )
2811 m_out->Print( " %s", formatInternalUnits( aTable->GetRowHeight( row ) ).c_str() );
2812
2813 m_out->Print( ")" );
2814
2815 m_out->Print( "(cells" );
2816
2817 for( PCB_TABLECELL* cell : aTable->GetCells() )
2818 format( static_cast<PCB_TEXTBOX*>( cell ) );
2819
2820 m_out->Print( ")" ); // Close `cells` token.
2821
2823}
2824
2825
2827{
2828 wxCHECK_RET( aMap != nullptr && m_out != nullptr, "" );
2829
2830 m_out->Print( "(drill_map " );
2831
2833
2834 if( aMap->IsLocked() )
2835 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2836
2837 formatLayer( aMap->GetLayer() );
2838
2839 // An offset applied to every mark, not a place of its own. Zero puts the marks on their
2840 // holes
2841 m_out->Print( "(offset %s)", formatInternalUnits( aMap->GetOffset() ).c_str() );
2842 m_out->Print( "(size %s)", formatInternalUnits( aMap->GetSymbolSize() ).c_str() );
2843
2844 if( aMap->GetAllSpans() )
2845 {
2846 m_out->Print( "(span all)" );
2847 }
2848 else
2849 {
2850 m_out->Print( "(span " );
2851 formatDrillSpan( m_out, aMap->GetSpan() );
2852 m_out->Print( ")" );
2853 }
2854
2855 KICAD_FORMAT::FormatBool( m_out, "outline_slots", aMap->GetOutlineSlots() );
2856 KICAD_FORMAT::FormatBool( m_out, "guide_cross", aMap->GetGuideCross() );
2858
2859 m_out->Print( ")" ); // Close `drill_map` token.
2860}
2861
2862
2864{
2865 wxCHECK_RET( aTable != nullptr && m_out != nullptr, "" );
2866
2867 switch( aTable->Type() )
2868 {
2869 case PCB_DRILL_CHART_T: m_out->Print( "(drill_chart " ); break;
2870 case PCB_STACKUP_TABLE_T: m_out->Print( "(stackup_table " ); break;
2871
2872 default:
2873 wxFAIL_MSG( wxT( "Unhandled generated table type " ) + aTable->GetClass() );
2874 return;
2875 }
2876
2878
2879 if( aTable->IsLocked() )
2880 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2881
2882 formatLayer( aTable->GetLayer() );
2883
2884 // Anything the reader would arrive at on its own is left out. A table nobody has
2885 // reconfigured is a handful of bytes rather than a page of them
2886 const GENERATED_TABLE_SCHEMA& schema = aTable->Schema();
2887
2888 if( aTable->GetUnits() != schema.DefaultUnits() )
2889 m_out->Print( "(units %s)", GeneratedTableUnitsToken( aTable->GetUnits() ) );
2890
2891 if( aTable->GetPrecision() != schema.DefaultPrecision() )
2892 m_out->Print( "(precision %d)", aTable->GetPrecision() );
2893
2894 for( const GENERATED_TABLE_COLUMN& col : aTable->AllColumns() )
2895 {
2896 const GENERATED_TABLE_COLUMN_DEF* def = schema.Find( col.m_Id );
2897
2898 m_out->Print( "(column (id %s)", schema.Token( col.m_Id ) );
2899
2900 // Compared against the def's own literal, never DefaultColumn()'s translated text, so
2901 // a heading written under one UI language reads back unchanged under another
2902 if( !def || col.m_Heading != wxString( def->m_Heading ) )
2903 m_out->Print( "(name %s)", m_out->Quotew( col.m_Heading ).c_str() );
2904
2905 if( !def || col.m_Align != def->m_Align )
2906 m_out->Print( "(justify %s)", GeneratedTableAlignToken( col.m_Align ) );
2907
2908 if( col.m_Width > 0 )
2909 m_out->Print( "(width %s)", formatInternalUnits( col.m_Width ).c_str() );
2910
2911 if( !col.m_Visible )
2912 KICAD_FORMAT::FormatBool( m_out, "hide", true );
2913
2914 m_out->Print( ")" );
2915 }
2916
2917 if( !aTable->RowKeys().empty() )
2918 {
2919 // What each row reports, so a rebuild after the board has changed can hand a row's
2920 // formatting to the row that still reports the same thing
2921 m_out->Print( "(row_keys" );
2922
2923 for( const auto& [row, key] : aTable->RowKeys() )
2924 m_out->Print( "(key %d %s)", row, m_out->Quotew( wxString::FromUTF8( key ) ).c_str() );
2925
2926 m_out->Print( ")" );
2927 }
2928
2930
2931 // The geometry and cells a generated table shares with any other table, written the same way
2932 formatTableData( aTable );
2933
2934 m_out->Print( ")" ); // Close the table's kind token
2935}
2936
2937
2939{
2940 switch( aTable->Type() )
2941 {
2942 case PCB_DRILL_CHART_T:
2943 {
2944 const PCB_DRILL_CHART* chart = static_cast<const PCB_DRILL_CHART*>( aTable );
2946 const DRILL_CHART_FILTER& filter = chart->Filter();
2947
2948 if( !( filter == DRILL_CHART_FILTER() ) )
2949 {
2950 m_out->Print( "(filter" );
2951 KICAD_FORMAT::FormatBool( m_out, "plated", filter.m_Plated );
2952 KICAD_FORMAT::FormatBool( m_out, "npth", filter.m_NonPlated );
2953 KICAD_FORMAT::FormatBool( m_out, "vias", filter.m_Vias );
2954 KICAD_FORMAT::FormatBool( m_out, "slots", filter.m_Slots );
2955 KICAD_FORMAT::FormatBool( m_out, "backdrill", filter.m_Backdrills );
2956 KICAD_FORMAT::FormatBool( m_out, "castellated", filter.m_Castellated );
2957 m_out->Print( ")" );
2958 }
2959
2960 if( chart->GetShowTotals() != defaults.GetShowTotals() )
2961 KICAD_FORMAT::FormatBool( m_out, "totals", chart->GetShowTotals() );
2962
2963 if( chart->GetSymbolColumn() >= 0 && !chart->RowShapes().empty() )
2964 {
2965 // Generated payload, like the cell text. A shape mark has no text of its own, so
2966 // without this the symbol column comes back blank
2967 m_out->Print( "(row_shapes (column %d)", chart->GetSymbolColumn() );
2968
2969 for( const auto& [row, shapeIndex] : chart->RowShapes() )
2970 m_out->Print( "(shape %d %d)", row, shapeIndex );
2971
2972 m_out->Print( ")" );
2973 }
2974
2975 break;
2976 }
2977
2978 default:
2979 break;
2980 }
2981}
2982
2983
2984void PCB_IO_KICAD_SEXPR::format( const PCB_TABLE* aTable ) const
2985{
2986 wxCHECK_RET( aTable != nullptr && m_out != nullptr, "" );
2987
2988 m_out->Print( "(table " );
2989
2991
2992 if( aTable->IsLocked() )
2993 KICAD_FORMAT::FormatBool( m_out, "locked", true );
2994
2995 formatLayer( aTable->GetLayer() );
2996
2997 formatTableData( aTable );
2998
2999 m_out->Print( ")" ); // Close `table` token.
3000}
3001
3002
3003void PCB_IO_KICAD_SEXPR::format( const PCB_GROUP* aGroup ) const
3004{
3005 wxArrayString memberIds;
3006
3007 // Validate member pointers against the board cache to avoid use-after-free on dangling
3008 // pointers (e.g. when a group held a reference to a deleted item). This validation only
3009 // applies when the group itself is part of m_board; for groups created off-board (e.g. a
3010 // DeepClone() used by the clipboard) the cache contains the originals, not our clones, so
3011 // skip the validation in that case and trust the member pointers.
3012 //
3013 // IsItemIndexedById() is explicitly safe to call on possibly-dangling pointers.
3014 bool validateAgainstBoard = m_board && m_board->IsItemIndexedById( aGroup );
3015
3016 memberIds.Alloc( aGroup->GetItems().size() );
3017
3018 for( EDA_ITEM* member : aGroup->GetItems() )
3019 {
3020 if( !validateAgainstBoard
3021 || m_board->IsItemIndexedById( static_cast<const BOARD_ITEM*>( member ) ) )
3022 {
3023 memberIds.Add( member->m_Uuid.AsString() );
3024 }
3025 }
3026
3027 if( memberIds.empty() )
3028 return;
3029
3030 m_out->Print( "(group %s", m_out->Quotew( aGroup->GetName() ).c_str() );
3031
3033
3034 if( aGroup->IsLocked() )
3035 KICAD_FORMAT::FormatBool( m_out, "locked", true );
3036
3037 if( aGroup->HasDesignBlockLink() )
3038 m_out->Print( "(lib_id \"%s\")", aGroup->GetDesignBlockLibId().Format().c_str() );
3039
3040 memberIds.Sort();
3041
3042 m_out->Print( "(members" );
3043
3044 for( const wxString& memberId : memberIds )
3045 m_out->Print( " %s", m_out->Quotew( memberId ).c_str() );
3046
3047 m_out->Print( ")" ); // Close `members` token.
3048
3050 m_out->Print( ")" ); // Close `group` token.
3051}
3052
3053
3054void PCB_IO_KICAD_SEXPR::format( const PCB_CONSTRAINT* aConstraint ) const
3055{
3056 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
3057
3058 if( members.empty() )
3059 return;
3060
3061 // Members are KIID references (not pointers), so unlike format(PCB_GROUP*) there is no
3062 // use-after-free risk: every member is written verbatim, including one whose item was deleted,
3063 // so the constraint round-trips in its error state rather than silently losing the reference.
3064 m_out->Print( "(constraint (type %s)", ConstraintTypeToken( aConstraint->GetConstraintType() ) );
3065
3066 KICAD_FORMAT::FormatUuid( m_out, aConstraint->m_Uuid );
3067
3068 m_out->Print( "(members" );
3069
3070 for( const CONSTRAINT_MEMBER& member : members )
3071 {
3072 // Only VERTEX carries an ordinal others stay two-token
3073 if( member.m_anchor == CONSTRAINT_ANCHOR::VERTEX )
3074 {
3075 m_out->Print( "(member %s %s %d)", m_out->Quotew( member.m_item.AsString() ).c_str(),
3076 ConstraintAnchorToken( member.m_anchor ), member.m_index );
3077 }
3078 else
3079 {
3080 m_out->Print( "(member %s %s)", m_out->Quotew( member.m_item.AsString() ).c_str(),
3081 ConstraintAnchorToken( member.m_anchor ) );
3082 }
3083 }
3084
3085 m_out->Print( ")" ); // Close `members` token.
3086
3087 if( aConstraint->HasValue() )
3088 {
3089 // Length/radius values are stored in IU but written in mm like every other dimension;
3090 // angle values are written verbatim in degrees.
3091 double value = *aConstraint->GetValue();
3092
3093 if( ConstraintValueIsLength( aConstraint->GetConstraintType() ) )
3094 value /= pcbIUScale.IU_PER_MM;
3095
3096 m_out->Print( "(value %s)", FormatDouble2Str( value ).c_str() );
3097 }
3098
3099 if( !aConstraint->IsDriving() )
3100 KICAD_FORMAT::FormatBool( m_out, "driving", false );
3101
3103 m_out->Print( ")" ); // Close `constraint` token.
3104}
3105
3106
3107void PCB_IO_KICAD_SEXPR::format( const PCB_GENERATOR* aGenerator ) const
3108{
3109 // Some conditions appear to still be creating ghost tuning patterns. Don't save them.
3110 // A microvia stack with no members is the same kind of ghost: it reloads with no size, so
3111 // it can be neither seen nor picked, and with no net to rebuild its vias on.
3112 if( aGenerator->GetItems().empty()
3113 && ( aGenerator->GetGeneratorType() == wxT( "tuning_pattern" )
3114 || aGenerator->GetGeneratorType() == wxT( "via_stack" ) ) )
3115 {
3116 return;
3117 }
3118
3119 m_out->Print( "(generated" );
3120
3121 KICAD_FORMAT::FormatUuid( m_out, aGenerator->m_Uuid );
3122
3123 m_out->Print( "(type %s) (name %s) (layer %s)",
3124 TO_UTF8( aGenerator->GetGeneratorType() ),
3125 m_out->Quotew( aGenerator->GetName() ).c_str(),
3126 m_out->Quotew( LSET::Name( aGenerator->GetLayer() ) ).c_str() );
3127
3128 if( aGenerator->IsLocked() )
3129 KICAD_FORMAT::FormatBool( m_out, "locked", true );
3130
3131 for( const auto& [key, value] : aGenerator->GetProperties() )
3132 {
3133 if( value.CheckType<double>() || value.CheckType<int>() || value.CheckType<long>()
3134 || value.CheckType<long long>() )
3135 {
3136 double val;
3137
3138 if( !value.GetAs( &val ) )
3139 continue;
3140
3141 std::string buf = fmt::format( "{:.10g}", val );
3142
3143 // Don't quote numbers
3144 m_out->Print( "(%s %s)", key.c_str(), buf.c_str() );
3145 }
3146 else if( value.CheckType<bool>() )
3147 {
3148 bool val;
3149 value.GetAs( &val );
3150
3151 KICAD_FORMAT::FormatBool( m_out, key, val );
3152 }
3153 else if( value.CheckType<VECTOR2I>() )
3154 {
3155 VECTOR2I val;
3156 value.GetAs( &val );
3157
3158 m_out->Print( "(%s (xy %s))",
3159 key.c_str(),
3160 formatInternalUnits( val ).c_str() );
3161 }
3162 else if( value.CheckType<SHAPE_LINE_CHAIN>() )
3163 {
3164 SHAPE_LINE_CHAIN val;
3165 value.GetAs( &val );
3166
3167 m_out->Print( "(%s ", key.c_str() );
3168 formatPolyPts( val );
3169 m_out->Print( ")" );
3170 }
3171 else if( value.CheckType<std::vector<VECTOR2I>>() )
3172 {
3173 // Unitless integer pairs
3174 std::vector<VECTOR2I> val;
3175 value.GetAs( &val );
3176
3177 m_out->Print( "(%s (cells", key.c_str() );
3178
3179 for( const VECTOR2I& cell : val )
3180 m_out->Print( "(ij %d %d)", cell.x, cell.y );
3181
3182 m_out->Print( "))" );
3183 }
3184 else
3185 {
3186 wxString val;
3187
3188 if( value.CheckType<wxString>() )
3189 {
3190 value.GetAs( &val );
3191 }
3192 else if( value.CheckType<std::string>() )
3193 {
3194 std::string str;
3195 value.GetAs( &str );
3196
3197 val = wxString::FromUTF8( str );
3198 }
3199
3200 m_out->Print( "(%s %s)", key.c_str(), m_out->Quotew( val ).c_str() );
3201 }
3202 }
3203
3204 std::vector<std::pair<wxString, const BOARD_ITEM*>> templateItems = aGenerator->GetTemplateItems();
3205
3206 if( !templateItems.empty() )
3207 {
3208 m_out->Print( "(templates" );
3209
3210 for( const auto& [name, item] : templateItems )
3211 {
3212 if( !item )
3213 continue;
3214
3215 m_out->Print( "(template (name %s)", m_out->Quotew( name ).c_str() );
3216 Format( item );
3217 m_out->Print( ")" ); // Close `template` token.
3218 }
3219
3220 m_out->Print( ")" ); // Close `templates` token.
3221 }
3222
3223 wxArrayString memberIds;
3224
3225 for( EDA_ITEM* member : aGenerator->GetItems() )
3226 memberIds.Add( member->m_Uuid.AsString() );
3227
3228 memberIds.Sort();
3229
3230 m_out->Print( "(members" );
3231
3232 for( const wxString& memberId : memberIds )
3233 m_out->Print( " %s", m_out->Quotew( memberId ).c_str() );
3234
3235 m_out->Print( ")" ); // Close `members` token.
3236
3238 m_out->Print( ")" ); // Close `generated` token.
3239}
3240
3241
3242void PCB_IO_KICAD_SEXPR::format( const PCB_TRACK* aTrack ) const
3243{
3244 if( aTrack->Type() == PCB_VIA_T )
3245 {
3246 PCB_LAYER_ID layer1, layer2;
3247
3248 const PCB_VIA* via = static_cast<const PCB_VIA*>( aTrack );
3249 const BOARD* board = via->GetBoard();
3250
3251 wxCHECK_RET( board != nullptr, wxT( "Via has no parent." ) );
3252
3253 m_out->Print( "(via" );
3254
3255 via->LayerPair( &layer1, &layer2 );
3256
3257 switch( via->GetViaType() )
3258 {
3259 case VIATYPE::THROUGH: // Default shape not saved.
3260 break;
3261
3262 case VIATYPE::BLIND:
3263 m_out->Print( " blind " );
3264 break;
3265
3266 case VIATYPE::BURIED:
3267 m_out->Print( " buried " );
3268 break;
3269
3270 case VIATYPE::MICROVIA:
3271 m_out->Print( " micro " );
3272 break;
3273
3274 default:
3275 THROW_IO_ERRORF( _( "unknown via type %d" ), via->GetViaType() );
3276 }
3277
3278 m_out->Print( "(at %s) (size %s)",
3279 formatInternalUnits( aTrack->GetStart() ).c_str(),
3280 formatInternalUnits( via->GetWidth( F_Cu ) ).c_str() );
3281
3282 // Old boards were using UNDEFINED_DRILL_DIAMETER value in file for via drill when
3283 // via drill was the netclass value.
3284 // recent boards always set the via drill to the actual value, but now we need to
3285 // always store the drill value, because netclass value is not stored in the board file.
3286 // Otherwise the drill value of some (old) vias can be unknown
3287 if( via->GetDrill() != UNDEFINED_DRILL_DIAMETER )
3288 m_out->Print( "(drill %s)", formatInternalUnits( via->GetDrill() ).c_str() );
3289 else
3290 m_out->Print( "(drill %s)", formatInternalUnits( via->GetDrillValue() ).c_str() );
3291
3292 if( via->Padstack().SecondaryDrill().size.x > 0 && via->Padstack().SecondaryDrill().start != UNDEFINED_LAYER )
3293 {
3294 m_out->Print( "(backdrill (size %s) (layers %s %s))",
3295 formatInternalUnits( via->Padstack().SecondaryDrill().size.x ).c_str(),
3296 m_out->Quotew( LSET::Name( via->Padstack().SecondaryDrill().start ) ).c_str(),
3297 m_out->Quotew( LSET::Name( via->Padstack().SecondaryDrill().end ) ).c_str() );
3298 }
3299
3300 if( via->Padstack().TertiaryDrill().size.x > 0 && via->Padstack().TertiaryDrill().start != UNDEFINED_LAYER )
3301 {
3302 m_out->Print( "(tertiary_drill (size %s) (layers %s %s))",
3303 formatInternalUnits( via->Padstack().TertiaryDrill().size.x ).c_str(),
3304 m_out->Quotew( LSET::Name( via->Padstack().TertiaryDrill().start ) ).c_str(),
3305 m_out->Quotew( LSET::Name( via->Padstack().TertiaryDrill().end ) ).c_str() );
3306 }
3307
3308 auto formatPostMachining = [&]( const char* aName, const PADSTACK::POST_MACHINING_PROPS& aProps )
3309 {
3310 if( !aProps.mode.has_value() || aProps.mode == PAD_DRILL_POST_MACHINING_MODE::NOT_POST_MACHINED )
3311 return;
3312
3313 m_out->Print( "(%s %s", aName,
3314 aProps.mode == PAD_DRILL_POST_MACHINING_MODE::COUNTERBORE ? "counterbore" : "countersink" );
3315
3316 if( aProps.size > 0 )
3317 m_out->Print( " (size %s)", formatInternalUnits( aProps.size ).c_str() );
3318
3319 if( aProps.depth > 0 )
3320 m_out->Print( " (depth %s)", formatInternalUnits( aProps.depth ).c_str() );
3321
3322 if( aProps.angle > 0 )
3323 m_out->Print( " (angle %s)", FormatDouble2Str( aProps.angle / 10.0 ).c_str() );
3324
3325 m_out->Print( ")" );
3326 };
3327
3328 formatPostMachining( "front_post_machining", via->Padstack().FrontPostMachining() );
3329 formatPostMachining( "back_post_machining", via->Padstack().BackPostMachining() );
3330
3331 m_out->Print( "(layers %s %s)",
3332 m_out->Quotew( LSET::Name( layer1 ) ).c_str(),
3333 m_out->Quotew( LSET::Name( layer2 ) ).c_str() );
3334
3335 switch( via->Padstack().UnconnectedLayerMode() )
3336 {
3338 KICAD_FORMAT::FormatBool( m_out, "remove_unused_layers", true );
3339 KICAD_FORMAT::FormatBool( m_out, "keep_end_layers", false );
3340 break;
3341
3343 KICAD_FORMAT::FormatBool( m_out, "remove_unused_layers", true );
3344 KICAD_FORMAT::FormatBool( m_out, "keep_end_layers", true );
3345 break;
3346
3348 KICAD_FORMAT::FormatBool( m_out, "start_end_only", true );
3349 break;
3350
3352 break;
3353 }
3354
3355 if( via->IsLocked() )
3356 KICAD_FORMAT::FormatBool( m_out, "locked", true );
3357
3358 if( via->GetIsFree() )
3359 KICAD_FORMAT::FormatBool( m_out, "free", true );
3360
3361 if( via->GetRemoveUnconnected() )
3362 {
3363 m_out->Print( "(zone_layer_connections" );
3364
3365 for( PCB_LAYER_ID layer : board->GetEnabledLayers().CuStack() )
3366 {
3367 if( via->GetZoneLayerOverride( layer ) == ZLO_FORCE_FLASHED )
3368 m_out->Print( " %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
3369 }
3370
3371 m_out->Print( ")" );
3372 }
3373
3374 const PADSTACK& padstack = via->Padstack();
3375
3376 if( padstack.FrontOuterLayers().has_solder_mask.has_value()
3377 || padstack.BackOuterLayers().has_solder_mask.has_value() )
3378 {
3379 m_out->Print( 0, " (tenting " );
3381 padstack.FrontOuterLayers().has_solder_mask );
3383 padstack.BackOuterLayers().has_solder_mask );
3384 m_out->Print( 0, ")" );
3385 }
3386
3387 if( padstack.Drill().is_capped.has_value() )
3388 KICAD_FORMAT::FormatOptBool( m_out, "capping", padstack.Drill().is_capped );
3389
3390 if( padstack.FrontOuterLayers().has_covering.has_value()
3391 || padstack.BackOuterLayers().has_covering.has_value() )
3392 {
3393 m_out->Print( 0, " (covering " );
3395 padstack.FrontOuterLayers().has_covering );
3397 padstack.BackOuterLayers().has_covering );
3398 m_out->Print( 0, ")" );
3399 }
3400
3401 if( padstack.FrontOuterLayers().has_plugging.has_value()
3402 || padstack.BackOuterLayers().has_plugging.has_value() )
3403 {
3404 m_out->Print( 0, " (plugging " );
3406 padstack.FrontOuterLayers().has_plugging );
3408 padstack.BackOuterLayers().has_plugging );
3409 m_out->Print( 0, ")" );
3410 }
3411
3412 if( padstack.Drill().is_filled.has_value() )
3413 KICAD_FORMAT::FormatOptBool( m_out, "filling", padstack.Drill().is_filled );
3414
3415 if( padstack.Mode() != PADSTACK::MODE::NORMAL )
3416 {
3417 m_out->Print( "(padstack" );
3418
3419 if( padstack.Mode() == PADSTACK::MODE::FRONT_INNER_BACK )
3420 {
3421 m_out->Print( "(mode front_inner_back)" );
3422
3423 m_out->Print( "(layer \"Inner\"" );
3424 m_out->Print( "(size %s)",
3425 formatInternalUnits( padstack.Size( PADSTACK::INNER_LAYERS ).x ).c_str() );
3426 m_out->Print( ")" );
3427 m_out->Print( "(layer \"B.Cu\"" );
3428 m_out->Print( "(size %s)",
3429 formatInternalUnits( padstack.Size( B_Cu ).x ).c_str() );
3430 m_out->Print( ")" );
3431 }
3432 else
3433 {
3434 m_out->Print( "(mode custom)" );
3435
3436 for( PCB_LAYER_ID layer : LAYER_RANGE( F_Cu, B_Cu, board->GetCopperLayerCount() ) )
3437 {
3438 if( layer == F_Cu )
3439 continue;
3440
3441 m_out->Print( "(layer %s", m_out->Quotew( LSET::Name( layer ) ).c_str() );
3442 m_out->Print( "(size %s)",
3443 formatInternalUnits( padstack.Size( layer ).x ).c_str() );
3444 m_out->Print( ")" );
3445 }
3446 }
3447
3448 m_out->Print( ")" );
3449 }
3450
3451 if( !isDefaultTeardropParameters( via->GetTeardropParams() ) )
3452 formatTeardropParameters( via->GetTeardropParams() );
3453 }
3454 else
3455 {
3456 if( aTrack->Type() == PCB_ARC_T )
3457 {
3458 const PCB_ARC* arc = static_cast<const PCB_ARC*>( aTrack );
3459
3460 m_out->Print( "(arc (start %s) (mid %s) (end %s) (width %s)",
3461 formatInternalUnits( arc->GetStart() ).c_str(),
3462 formatInternalUnits( arc->GetMid() ).c_str(),
3463 formatInternalUnits( arc->GetEnd() ).c_str(),
3464 formatInternalUnits( arc->GetWidth() ).c_str() );
3465 }
3466 else
3467 {
3468 m_out->Print( "(segment (start %s) (end %s) (width %s)",
3469 formatInternalUnits( aTrack->GetStart() ).c_str(),
3470 formatInternalUnits( aTrack->GetEnd() ).c_str(),
3471 formatInternalUnits( aTrack->GetWidth() ).c_str() );
3472 }
3473
3474 if( aTrack->IsLocked() )
3475 KICAD_FORMAT::FormatBool( m_out, "locked", true );
3476
3477 if( aTrack->GetLayerSet().count() > 1 )
3478 formatLayers( aTrack->GetLayerSet(), false /* enumerate layers */ );
3479 else
3480 formatLayer( aTrack->GetLayer() );
3481
3482 if( aTrack->HasSolderMask()
3483 && aTrack->GetLocalSolderMaskMargin().has_value()
3484 && IsExternalCopperLayer( aTrack->GetLayer() ) )
3485 {
3486 m_out->Print( "(solder_mask_margin %s)",
3487 formatInternalUnits( aTrack->GetLocalSolderMaskMargin().value() ).c_str() );
3488 }
3489 }
3490
3491 if( !( m_ctl & CTL_OMIT_PAD_NETS ) )
3492 m_out->Print( "(net %s)", m_out->Quotew( aTrack->GetNetname() ).c_str() );
3493
3496 m_out->Print( ")" );
3497}
3498
3499
3500void PCB_IO_KICAD_SEXPR::format( const ZONE* aZone ) const
3501{
3502 m_out->Print( "(zone" );
3503
3504 if( !( m_ctl & CTL_OMIT_PAD_NETS ) && aZone->IsOnCopperLayer() && !aZone->GetIsRuleArea()
3505 && aZone->GetNetCode() > 0 )
3506 {
3507 m_out->Print( "(net %s)", m_out->Quotew( aZone->GetNetname() ).c_str() );
3508 }
3509
3510 if( aZone->IsLocked() )
3511 KICAD_FORMAT::FormatBool( m_out, "locked", true );
3512
3513 // If a zone exists on multiple layers, format accordingly
3514 LSET layers = aZone->GetLayerSet();
3515
3516 if( aZone->GetBoard() )
3517 layers &= aZone->GetBoard()->GetEnabledLayers();
3518
3519 // Always enumerate every layer for a zone on a copper layer
3520 if( layers.count() > 1 )
3521 formatLayers( layers, aZone->IsOnCopperLayer(), true );
3522 else
3523 formatLayer( aZone->GetFirstLayer() );
3524
3525 if( !aZone->IsTeardropArea() )
3527
3528 if( !aZone->GetZoneName().empty() && !aZone->IsTeardropArea() )
3529 m_out->Print( "(name %s)", m_out->Quotew( aZone->GetZoneName() ).c_str() );
3530
3531 // Save the outline aux info
3532 std::string hatch;
3533
3534 switch( aZone->GetHatchStyle() )
3535 {
3536 default:
3537 case ZONE_BORDER_DISPLAY_STYLE::NO_HATCH: hatch = "none"; break;
3538 case ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_EDGE: hatch = "edge"; break;
3539 case ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_FULL: hatch = "full"; break;
3540 }
3541
3542 m_out->Print( "(hatch %s %s)", hatch.c_str(),
3543 formatInternalUnits( aZone->GetBorderHatchPitch() ).c_str() );
3544
3545
3546
3547 if( aZone->GetAssignedPriority() > 0 )
3548 m_out->Print( "(priority %d)", aZone->GetAssignedPriority() );
3549
3550 // Add teardrop keywords in file: (attr (teardrop (type xxx))) where xxx is the teardrop type
3551 if( aZone->IsTeardropArea() )
3552 {
3553 m_out->Print( "(attr (teardrop (type %s)))",
3554 aZone->GetTeardropAreaType() == TEARDROP_TYPE::TD_VIAPAD ? "padvia"
3555 : "track_end" );
3556 }
3557
3558 m_out->Print( "(connect_pads" );
3559
3560 switch( aZone->GetPadConnection() )
3561 {
3562 default:
3563 case ZONE_CONNECTION::THERMAL: // Default option not saved or loaded.
3564 break;
3565
3567 m_out->Print( " thru_hole_only" );
3568 break;
3569
3571 m_out->Print( " yes" );
3572 break;
3573
3575 m_out->Print( " no" );
3576 break;
3577 }
3578
3579 m_out->Print( "(clearance %s)",
3580 formatInternalUnits( aZone->GetLocalClearance().value() ).c_str() );
3581
3582 m_out->Print( ")" );
3583
3584 m_out->Print( "(min_thickness %s)",
3585 formatInternalUnits( aZone->GetMinThickness() ).c_str() );
3586
3587 if( aZone->GetIsRuleArea() )
3588 {
3589 // Keepout settings
3590 m_out->Print( "(keepout (tracks %s) (vias %s) (pads %s) (copperpour %s) (footprints %s))",
3591 aZone->GetDoNotAllowTracks() ? "not_allowed" : "allowed",
3592 aZone->GetDoNotAllowVias() ? "not_allowed" : "allowed",
3593 aZone->GetDoNotAllowPads() ? "not_allowed" : "allowed",
3594 aZone->GetDoNotAllowZoneFills() ? "not_allowed" : "allowed",
3595 aZone->GetDoNotAllowFootprints() ? "not_allowed" : "allowed" );
3596
3597 // Multichannel settings
3598 m_out->Print( "(placement" );
3600
3601 switch( aZone->GetPlacementAreaSourceType() )
3602 {
3604 m_out->Print( "(sheetname %s)", m_out->Quotew( aZone->GetPlacementAreaSource() ).c_str() );
3605 break;
3607 m_out->Print( "(component_class %s)", m_out->Quotew( aZone->GetPlacementAreaSource() ).c_str() );
3608 break;
3610 m_out->Print( "(group %s)", m_out->Quotew( aZone->GetPlacementAreaSource() ).c_str() );
3611 break;
3612 // These are transitory and should not be saved
3614 break;
3615 }
3616
3617 if( aZone->GetLinkSet() != niluuid )
3618 {
3619 const REPEAT_LAYOUT_OPTIONS& opts = aZone->GetRepeatOptions();
3620
3621 m_out->Print( "(link %s", m_out->Quotew( aZone->GetLinkSet().AsString() ).c_str() );
3622 KICAD_FORMAT::FormatBool( m_out, "placement", opts.m_copyPlacement );
3623 KICAD_FORMAT::FormatBool( m_out, "routing", opts.m_copyRouting );
3624 KICAD_FORMAT::FormatBool( m_out, "connected_routing", opts.m_connectedRoutingOnly );
3625 KICAD_FORMAT::FormatBool( m_out, "other_items", opts.m_copyOtherItems );
3626 KICAD_FORMAT::FormatBool( m_out, "group_items", opts.m_groupItems );
3627 KICAD_FORMAT::FormatBool( m_out, "locked_items", opts.m_includeLockedItems );
3628
3629 if( opts.m_anchor != niluuid )
3630 m_out->Print( "(anchor %s)", m_out->Quotew( opts.m_anchor.AsString() ).c_str() );
3631
3632 m_out->Print( ")" );
3633 }
3634
3635 m_out->Print( ")" );
3636 }
3637
3638 m_out->Print( "(fill" );
3639
3640 // Default is not filled.
3641 if( aZone->IsFilled() )
3642 m_out->Print( " yes" );
3643
3644 // Default is polygon filled.
3646 m_out->Print( "(mode hatch)" );
3647 else if( aZone->GetFillMode() == ZONE_FILL_MODE::COPPER_THIEVING )
3648 m_out->Print( "(mode thieving)" );
3649
3650 if( !aZone->IsTeardropArea() )
3651 {
3652 m_out->Print( "(thermal_gap %s) (thermal_bridge_width %s)",
3653 formatInternalUnits( aZone->GetThermalReliefGap() ).c_str(),
3654 formatInternalUnits( aZone->GetThermalReliefSpokeWidth() ).c_str() );
3655 }
3656
3658 {
3659 switch( aZone->GetCornerSmoothingType() )
3660 {
3662 m_out->Print( "(smoothing chamfer)" );
3663 break;
3664
3666 m_out->Print( "(smoothing fillet)" );
3667 break;
3668
3669 default:
3670 THROW_IO_ERRORF( _( "unknown zone corner smoothing type %d" ), aZone->GetCornerSmoothingType() );
3671 }
3672
3673 if( aZone->GetCornerRadius() != 0 )
3674 m_out->Print( "(radius %s)", formatInternalUnits( aZone->GetCornerRadius() ).c_str() );
3675 }
3676
3677 m_out->Print( "(island_removal_mode %d)",
3678 static_cast<int>( aZone->GetIslandRemovalMode() ) );
3679
3681 {
3682 m_out->Print( "(island_area_min %s)",
3683 formatInternalUnits( aZone->GetMinIslandArea() / pcbIUScale.IU_PER_MM ).c_str() );
3684 }
3685
3687 {
3688 m_out->Print( "(hatch_thickness %s) (hatch_gap %s) (hatch_orientation %s)",
3689 formatInternalUnits( aZone->GetHatchThickness() ).c_str(),
3690 formatInternalUnits( aZone->GetHatchGap() ).c_str(),
3691 FormatDouble2Str( aZone->GetHatchOrientation().AsDegrees() ).c_str() );
3692
3693 if( aZone->GetHatchSmoothingLevel() > 0 )
3694 {
3695 m_out->Print( "(hatch_smoothing_level %d) (hatch_smoothing_value %s)",
3696 aZone->GetHatchSmoothingLevel(),
3697 FormatDouble2Str( aZone->GetHatchSmoothingValue() ).c_str() );
3698 }
3699
3700 m_out->Print( "(hatch_border_algorithm %s) (hatch_min_hole_area %s)",
3701 aZone->GetHatchBorderAlgorithm() ? "hatch_thickness" : "min_thickness",
3702 FormatDouble2Str( aZone->GetHatchHoleMinArea() ).c_str() );
3703 }
3704 else if( aZone->GetFillMode() == ZONE_FILL_MODE::COPPER_THIEVING )
3705 {
3706 const THIEVING_SETTINGS& thieving = aZone->GetThievingSettings();
3707 const char* patternStr = "dots";
3708
3709 switch( thieving.pattern )
3710 {
3711 case THIEVING_PATTERN::SQUARES: patternStr = "squares"; break;
3712 case THIEVING_PATTERN::HATCH: patternStr = "hatch"; break;
3714 default: patternStr = "dots"; break;
3715 }
3716
3717 m_out->Print( "(thieving (type %s) (size %s) (gap %s) (width %s) "
3718 "(stagger %s) (orientation %s))",
3719 patternStr,
3720 formatInternalUnits( thieving.element_size ).c_str(),
3721 formatInternalUnits( thieving.gap ).c_str(),
3722 formatInternalUnits( thieving.line_width ).c_str(),
3723 thieving.stagger ? "yes" : "no",
3724 FormatDouble2Str( thieving.orientation.GetAngle().AsDegrees() ).c_str() );
3725 }
3726
3727 m_out->Print( ")" );
3728
3729 for( const auto& [layer, properties] : aZone->LayerProperties() )
3730 {
3731 format( properties, 0, layer );
3732 }
3733
3734 if( aZone->GetNumCorners() )
3735 {
3736 SHAPE_POLY_SET::POLYGON poly = aZone->Outline()->Polygon(0);
3737
3738 for( const SHAPE_LINE_CHAIN& chain : poly )
3739 {
3740 if( chain.PointCount() == 0 )
3741 continue;
3742
3743 m_out->Print( "(polygon" );
3745 m_out->Print( ")" );
3746 }
3747 }
3748
3749 // Save the PolysList (filled areas)
3750 for( PCB_LAYER_ID layer : aZone->GetLayerSet().Seq() )
3751 {
3752 const std::shared_ptr<SHAPE_POLY_SET>& fv = aZone->GetFilledPolysList( layer );
3753
3754 for( int ii = 0; ii < fv->OutlineCount(); ++ii )
3755 {
3756 m_out->Print( "(filled_polygon" );
3757 m_out->Print( "(layer %s)", m_out->Quotew( LSET::Name( layer ) ).c_str() );
3758
3759 if( aZone->IsIsland( layer, ii ) )
3760 KICAD_FORMAT::FormatBool( m_out, "island", true );
3761
3762 const SHAPE_LINE_CHAIN& chain = fv->COutline( ii );
3763
3765 m_out->Print( ")" );
3766 }
3767 }
3768
3770 m_out->Print( ")" );
3771}
3772
3773
3774void PCB_IO_KICAD_SEXPR::format( const ZONE_LAYER_PROPERTIES& aZoneLayerProperties, int aNestLevel,
3775 PCB_LAYER_ID aLayer ) const
3776{
3777 // Do not store the layer properties if no value is actually set.
3778 if( !aZoneLayerProperties.hatching_offset.has_value() )
3779 return;
3780
3781 m_out->Print( aNestLevel, "(property\n" );
3782 m_out->Print( aNestLevel, "(layer %s)\n", m_out->Quotew( LSET::Name( aLayer ) ).c_str() );
3783
3784 if( aZoneLayerProperties.hatching_offset.has_value() )
3785 {
3786 m_out->Print( aNestLevel, "(hatch_position (xy %s))",
3787 formatInternalUnits( aZoneLayerProperties.hatching_offset.value() ).c_str() );
3788 }
3789
3790 m_out->Print( aNestLevel, ")\n" );
3791}
3792
3793
3795 PCB_IO( wxS( "KiCad" ) ),
3796 m_cache( nullptr ),
3797 m_ctl( aControlFlags )
3798{
3799 init( nullptr );
3800 m_out = &m_sf;
3801}
3802
3803
3805{
3806 if( m_leakCacheAtExit )
3808 else
3809 delete m_cache;
3810}
3811
3812
3813void PCB_IO_KICAD_SEXPR::loadBoard( const wxString& aFileName, BOARD& aBoard, bool aIsNewLoad,
3814 const std::map<std::string, UTF8>* aProperties, PROJECT* aProject )
3815{
3816 FILE_LINE_READER reader( aFileName );
3817
3818 unsigned lineCount = 0;
3819
3820 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
3822
3823 if( m_progressReporter )
3824 {
3825 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
3826
3827 if( !m_progressReporter->KeepRefreshing() )
3829
3830 while( reader.ReadLine() )
3831 lineCount++;
3832
3833 reader.Rewind();
3834 }
3835
3836 DoLoad( reader, aBoard, aIsNewLoad, aProperties, m_progressReporter, lineCount );
3837}
3838
3839
3840void PCB_IO_KICAD_SEXPR::DoLoad( LINE_READER& aReader, BOARD& aBoard, bool aIsNewLoad,
3841 const std::map<std::string, UTF8>* aProperties, PROGRESS_REPORTER* aProgressReporter,
3842 unsigned aLineCount )
3843{
3844 init( aProperties );
3845
3846 bool preserveDestinationStackup =
3847 aProperties && aProperties->contains( PCB_IO_LOAD_PROPERTIES::APPEND_PRESERVE_DESTINATION_STACKUP );
3848
3849 PCB_IO_KICAD_SEXPR_PARSER parser( &aReader, &aBoard, m_queryUserCallback, aProgressReporter, aLineCount,
3850 preserveDestinationStackup, !aIsNewLoad );
3851
3853
3854 std::set<BOARD_ITEM*> itemsBefore;
3855 std::set<NETINFO_ITEM*> netsBefore;
3856
3857 if( !aIsNewLoad )
3858 {
3859 for( BOARD_ITEM* item : aBoard.GetItemSet() )
3860 itemsBefore.insert( item );
3861
3862 for( NETINFO_ITEM* net : aBoard.GetNetInfo() )
3863 netsBefore.insert( net );
3864 }
3865
3866 auto revertPartialAppend = [&]()
3867 {
3868 if( aIsNewLoad )
3869 return;
3870
3871 std::vector<BOARD_ITEM*> addedItems;
3872
3873 for( BOARD_ITEM* item : aBoard.GetItemSet() )
3874 {
3875 if( !itemsBefore.contains( item ) )
3876 addedItems.push_back( item );
3877 }
3878
3879 // Remove everything before deleting anything, group member back pointers
3880 // must be unlinked while their groups are still alive
3881 for( BOARD_ITEM* item : addedItems )
3882 aBoard.Remove( item );
3883
3884 for( BOARD_ITEM* item : addedItems )
3885 delete item;
3886
3887 std::vector<NETINFO_ITEM*> addedNets;
3888
3889 for( NETINFO_ITEM* net : aBoard.GetNetInfo() )
3890 {
3891 if( !netsBefore.contains( net ) )
3892 addedNets.push_back( net );
3893 }
3894
3895 for( NETINFO_ITEM* net : addedNets )
3896 {
3897 aBoard.Remove( net );
3898 delete net;
3899 }
3900 };
3901
3902 BOARD* board = nullptr;
3903
3904 try
3905 {
3906 board = dynamic_cast<BOARD*>( parser.Parse() );
3907 }
3908 catch( const FUTURE_FORMAT_ERROR& )
3909 {
3910 revertPartialAppend();
3911
3912 // Don't wrap a FUTURE_FORMAT_ERROR in another
3913 throw;
3914 }
3915 catch( const PARSE_ERROR& parse_error )
3916 {
3917 revertPartialAppend();
3918
3919 if( parser.IsTooRecent() )
3920 throw FUTURE_FORMAT_ERROR( parse_error, parser.GetRequiredVersion() );
3921 else
3922 throw;
3923 }
3924 catch( ... )
3925 {
3926 revertPartialAppend();
3927 throw;
3928 }
3929
3930 if( board != &aBoard )
3931 {
3932 // The parser loaded something that was valid, but wasn't a board.
3933 THROW_PARSE_ERROR( _( "This file does not contain a PCB." ), parser.CurSource(),
3934 parser.CurLine(), parser.CurLineNumber(), parser.CurOffset() );
3935 }
3936
3937 // Report any non-fatal parse warnings to the load info reporter
3938 for( const wxString& warning : parser.GetParseWarnings() )
3940}
3941
3942
3943void PCB_IO_KICAD_SEXPR::init( const std::map<std::string, UTF8>* aProperties )
3944{
3945 m_board = nullptr;
3946 m_reader = nullptr;
3947 m_props = aProperties;
3948}
3949
3950
3951void PCB_IO_KICAD_SEXPR::validateCache( const wxString& aLibraryPath, bool checkModified )
3952{
3953 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
3954 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
3955
3956 if( !m_cache || !m_cache->IsPath( aLibraryPath ) || ( checkModified && m_cache->IsModified() ) )
3957 {
3958 // a spectacular episode in memory management:
3959 delete m_cache;
3960 m_cache = new FP_CACHE( this, aLibraryPath );
3961 m_cache->Load();
3962 }
3963}
3964
3965
3966void PCB_IO_KICAD_SEXPR::FootprintEnumerate( wxArrayString& aFootprintNames,
3967 const wxString& aLibPath, bool aBestEfforts,
3968 const std::map<std::string, UTF8>* aProperties )
3969{
3970 wxDir dir( aLibPath );
3971 wxString errorMsg;
3972
3973 init( aProperties );
3974
3975 try
3976 {
3977 validateCache( aLibPath );
3978
3979 if( !dir.IsOpened() )
3980 THROW_IO_ERRORF( _( "Footprint library '%s' not found." ), aLibPath );
3981 }
3982 catch( const IO_ERROR& ioe )
3983 {
3984 errorMsg = ioe.What();
3985 }
3986
3987 // Some of the files may have been parsed correctly so we want to add the valid files to
3988 // the library.
3989
3990 for( const auto& footprint : m_cache->GetFootprints() )
3991 aFootprintNames.Add( footprint.first );
3992
3993 if( !errorMsg.IsEmpty() && !aBestEfforts )
3994 THROW_IO_ERROR( errorMsg );
3995}
3996
3997
3998const FOOTPRINT* PCB_IO_KICAD_SEXPR::getFootprint( const wxString& aLibraryPath,
3999 const wxString& aFootprintName,
4000 const std::map<std::string, UTF8>* aProperties,
4001 bool checkModified )
4002{
4003 init( aProperties );
4004
4005 try
4006 {
4007 validateCache( aLibraryPath, checkModified );
4008 }
4009 catch( const IO_ERROR& )
4010 {
4011 // do nothing with the error
4012 }
4013
4014 auto it = m_cache->GetFootprints().find( aFootprintName );
4015
4016 if( it == m_cache->GetFootprints().end() )
4017 return nullptr;
4018
4019 return it->second->GetFootprint().get();
4020}
4021
4022
4023const FOOTPRINT* PCB_IO_KICAD_SEXPR::GetEnumeratedFootprint( const wxString& aLibraryPath,
4024 const wxString& aFootprintName,
4025 const std::map<std::string, UTF8>* aProperties )
4026{
4027 return getFootprint( aLibraryPath, aFootprintName, aProperties, false );
4028}
4029
4030
4031bool PCB_IO_KICAD_SEXPR::FootprintExists( const wxString& aLibraryPath,
4032 const wxString& aFootprintName,
4033 const std::map<std::string, UTF8>* aProperties )
4034{
4035 // Note: checking the cache sounds like a good idea, but won't catch files which differ
4036 // only in case.
4037 //
4038 // Since this goes out to the native filesystem, we get platform differences (ie: MSW's
4039 // case-insensitive filesystem) handled "for free".
4040 // Warning: footprint names frequently contain a point. So be careful when initializing
4041 // wxFileName, and use a CTOR with extension specified
4042 wxFileName footprintFile( aLibraryPath, aFootprintName, FILEEXT::KiCadFootprintFileExtension );
4043
4044 return footprintFile.Exists();
4045}
4046
4047
4048std::unique_ptr<FOOTPRINT> PCB_IO_KICAD_SEXPR::ImportFootprint( const wxString& aFootprintPath,
4049 wxString& aFootprintNameOut,
4050 const std::map<std::string, UTF8>* aProperties )
4051{
4053
4054 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
4055 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
4056 FILE_LINE_READER reader( aFootprintPath );
4057 PCB_IO_KICAD_SEXPR_PARSER parser( &reader, nullptr, nullptr );
4058
4059 parser.ParseFootprintLib( footprints );
4060
4061 if( footprints.empty() )
4062 return nullptr;
4063
4064 auto it = footprints.begin();
4065
4066 aFootprintNameOut = wxFileName( aFootprintPath ).GetName();
4067 FOOTPRINT* fp = it->second->GetFootprint().release();
4068 std::unique_ptr<FOOTPRINT> retv;
4069 retv.reset( fp );
4070
4071 return retv;
4072}
4073
4074
4075std::unique_ptr<FOOTPRINT> PCB_IO_KICAD_SEXPR::FootprintLoad( const wxString& aLibraryPath,
4076 const wxString& aFootprintName, bool aKeepUUID,
4077 const std::map<std::string, UTF8>* aProperties )
4078{
4079 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
4080 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
4081
4082 const FOOTPRINT* footprint = getFootprint( aLibraryPath, aFootprintName, aProperties, true );
4083
4084 if( footprint )
4085 {
4086 std::unique_ptr<FOOTPRINT> copy;
4087
4088 if( aKeepUUID )
4089 copy.reset( static_cast<FOOTPRINT*>( footprint->Clone() ) );
4090 else
4091 copy.reset( static_cast<FOOTPRINT*>( footprint->Duplicate( IGNORE_PARENT_GROUP ) ) );
4092
4093 copy->SetParent( nullptr );
4094 return copy;
4095 }
4096
4097 return nullptr;
4098}
4099
4100
4101void PCB_IO_KICAD_SEXPR::FootprintSave( const wxString& aLibraryPath, const FOOTPRINT* aFootprint,
4102 const std::map<std::string, UTF8>* aProperties )
4103{
4104 init( aProperties );
4105
4106 // In this public PLUGIN API function, we can safely assume it was
4107 // called for saving into a library path.
4109
4110 // Support saving to a single-file path like "/tmp/foo.kicad_mod" by treating the directory
4111 // as the library path and the file base-name as the footprint name.
4112 wxString libPath = aLibraryPath;
4113 wxString singleFileBaseName; // without extension
4114 bool saveSingleFile = false;
4115
4116 {
4117 wxFileName asFile( aLibraryPath );
4118
4119 if( asFile.GetExt() == FILEEXT::KiCadFootprintFileExtension )
4120 {
4121 saveSingleFile = true;
4122 libPath = asFile.GetPath();
4123 singleFileBaseName = asFile.GetName();
4124 }
4125 }
4126
4127 validateCache( libPath, !aProperties || !aProperties->contains( "skip_cache_validation" ) );
4128
4129 if( !m_cache->IsWritable() )
4130 {
4131 if( !m_cache->Exists() )
4132 {
4133 const wxString msg = wxString::Format( _( "Library '%s' does not exist.\n"
4134 "Would you like to create it?"),
4135 libPath );
4136
4137 if( !Pgm().IsGUI() || wxMessageBox( msg, _( "Library Not Found" ), wxYES_NO | wxICON_QUESTION ) != wxYES )
4138 return;
4139
4140 // Save throws its own IO_ERROR on failure, so no need to recreate here
4141 m_cache->Save( nullptr );
4142 }
4143 else
4144 {
4145 THROW_IO_ERRORF( _( "Library '%s' is read only." ), libPath );
4146 }
4147 }
4148
4149 // The map key used by the cache and the on-disk filename base.
4150 wxString footprintName = saveSingleFile ? singleFileBaseName
4151 : aFootprint->GetFPID().GetUniStringLibItemName();
4152
4153 wxString fpName = saveSingleFile ? singleFileBaseName
4154 : aFootprint->GetFPID().GetUniStringLibItemName();
4155 ReplaceIllegalFileNameChars( fpName, '_' );
4156
4157 // Quietly overwrite footprint and delete footprint file from path for any by same name.
4158 wxFileName fn( libPath, fpName, FILEEXT::KiCadFootprintFileExtension );
4159
4160 // Write through symlinks, don't replace them
4162
4163 if( !fn.IsOk() )
4164 THROW_IO_ERRORF( _( "Footprint file name '%s' is not valid." ), fn.GetFullPath() );
4165
4166 if( fn.FileExists() && !fn.IsFileWritable() )
4167 THROW_IO_ERRORF( _( "Insufficient permissions to delete '%s'." ), fn.GetFullPath() );
4168
4169 wxString fullPath = fn.GetFullPath();
4170 wxString fullName = fn.GetFullName();
4171 auto it = m_cache->GetFootprints().find( footprintName );
4172
4173 if( it != m_cache->GetFootprints().end() )
4174 {
4175 // Save() below writes atomically via sibling temp + rename, so no pre-delete.
4176 wxLogTrace( traceKicadPcbPlugin, wxT( "Replacing footprint file '%s'." ), fullPath );
4177 m_cache->GetFootprints().erase( footprintName );
4178 }
4179
4180 // I need my own copy for the cache
4181 FOOTPRINT* footprint = static_cast<FOOTPRINT*>( aFootprint->Clone() );
4182
4183 // It's orientation should be zero and it should be on the front layer.
4184 footprint->SetOrientation( ANGLE_0 );
4185
4186 if( footprint->GetLayer() != F_Cu )
4187 {
4188 PCBNEW_SETTINGS* cfg = dynamic_cast<PCBNEW_SETTINGS*>( Kiface().KifaceSettings() );
4189
4190 if( cfg )
4191 footprint->Flip( footprint->GetPosition(), cfg->m_FlipDirection );
4192 else
4193 footprint->Flip( footprint->GetPosition(), FLIP_DIRECTION::TOP_BOTTOM );
4194
4195 // A left-right flip also turns the footprint half a turn
4196 footprint->SetOrientation( ANGLE_0 );
4197 }
4198
4199 // Detach it from the board and its group
4200 footprint->SetParent( nullptr );
4201 footprint->SetParentGroup( nullptr );
4202
4203 // Now that the clone is detached from its parent board, any m_netinfo pointers its
4204 // descendants still carry reference NETINFO_ITEMs owned by that board and may dangle.
4205 // Force them all to the board-independent ORPHANED singleton before serialization.
4206 footprint->ClearAllNets();
4207
4208 wxLogTrace( traceKicadPcbPlugin, wxT( "Creating s-expr footprint file '%s'." ), fullPath );
4209 m_cache->GetFootprints().insert( footprintName,
4210 new FP_CACHE_ENTRY( footprint,
4211 WX_FILENAME( fn.GetPath(), fullName ) ) );
4212 m_cache->Save( footprint );
4213}
4214
4215
4216void PCB_IO_KICAD_SEXPR::FootprintDelete( const wxString& aLibraryPath,
4217 const wxString& aFootprintName,
4218 const std::map<std::string, UTF8>* aProperties )
4219{
4220 init( aProperties );
4221
4222 validateCache( aLibraryPath );
4223
4224 if( !m_cache->IsWritable() )
4225 THROW_IO_ERRORF( _( "Library '%s' is read only." ), aLibraryPath.GetData() );
4226
4227 m_cache->Remove( aFootprintName );
4228}
4229
4230
4231void PCB_IO_KICAD_SEXPR::ClearCachedFootprints( const wxString& aLibraryPath )
4232{
4233 if( m_cache && m_cache->IsPath( aLibraryPath ) )
4234 {
4235 delete m_cache;
4236 m_cache = nullptr;
4237 }
4238}
4239
4240
4241long long PCB_IO_KICAD_SEXPR::GetLibraryTimestamp( const wxString& aLibraryPath ) const
4242{
4243 return FP_CACHE::GetTimestamp( aLibraryPath );
4244}
4245
4246
4247void PCB_IO_KICAD_SEXPR::CreateLibrary( const wxString& aLibraryPath,
4248 const std::map<std::string, UTF8>* aProperties )
4249{
4250 if( wxDir::Exists( aLibraryPath ) )
4251 THROW_IO_ERRORF( _( "Cannot overwrite library path '%s'." ), aLibraryPath.GetData() );
4252
4253 init( aProperties );
4254
4255 delete m_cache;
4256 m_cache = new FP_CACHE( this, aLibraryPath );
4257 m_cache->Save();
4258}
4259
4260
4261bool PCB_IO_KICAD_SEXPR::DeleteLibrary( const wxString& aLibraryPath,
4262 const std::map<std::string, UTF8>* aProperties )
4263{
4264 wxFileName fn;
4265 fn.SetPath( aLibraryPath );
4266
4267 // Return if there is no library path to delete.
4268 if( !fn.DirExists() )
4269 return false;
4270
4271 if( !fn.IsDirWritable() )
4272 THROW_IO_ERRORF( _( "Insufficient permissions to delete folder '%s'." ), aLibraryPath.GetData() );
4273
4274 wxDir dir( aLibraryPath );
4275
4276 if( dir.HasSubDirs() )
4277 THROW_IO_ERRORF( _( "Library folder '%s' has unexpected sub-folders." ), aLibraryPath.GetData() );
4278
4279 // All the footprint files must be deleted before the directory can be deleted.
4280 if( dir.HasFiles() )
4281 {
4282 unsigned i;
4283 wxFileName tmp;
4284 wxArrayString files;
4285
4286 CollectFilesLoopSafe( aLibraryPath, files );
4287
4288 for( i = 0; i < files.GetCount(); i++ )
4289 {
4290 tmp = files[i];
4291
4292 if( tmp.GetExt() != FILEEXT::KiCadFootprintFileExtension )
4293 {
4294 THROW_IO_ERRORF( _( "Unexpected file '%s' found in library path '%s'." ),
4295 files[i].GetData(),
4296 aLibraryPath.GetData() );
4297 }
4298 }
4299
4300 for( i = 0; i < files.GetCount(); i++ )
4301 wxRemoveFile( files[i] );
4302 }
4303
4304 wxLogTrace( traceKicadPcbPlugin, wxT( "Removing footprint library '%s'." ),
4305 aLibraryPath.GetData() );
4306
4307 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
4308 // we don't want that. we want bare metal portability with no UI here.
4309 if( !wxRmdir( aLibraryPath ) )
4310 THROW_IO_ERRORF( _( "Footprint library '%s' cannot be deleted." ), aLibraryPath.GetData() );
4311
4312 // For some reason removing a directory in Windows is not immediately updated. This delay
4313 // prevents an error when attempting to immediately recreate the same directory when over
4314 // writing an existing library.
4315#ifdef __WINDOWS__
4316 wxMilliSleep( 250L );
4317#endif
4318
4319 if( m_cache && !m_cache->IsPath( aLibraryPath ) )
4320 {
4321 delete m_cache;
4322 m_cache = nullptr;
4323 }
4324
4325 return true;
4326}
4327
4328
4329bool PCB_IO_KICAD_SEXPR::IsLibraryWritable( const wxString& aLibraryPath )
4330{
4331 init( nullptr );
4332
4333 validateCache( aLibraryPath );
4334
4335 return m_cache->IsWritable();
4336}
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
@ LT_FRONT
Definition board.h:250
@ LT_BACK
Definition board.h:251
@ ZLO_FORCE_FLASHED
Definition board_item.h:77
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
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:66
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
TEARDROP_PARAMETERS & GetTeardropParams()
Container for design settings for a BOARD object.
std::map< PCB_LAYER_ID, ZONE_LAYER_PROPERTIES > m_ZoneLayerProperties
DRILL_SYMBOL_PROFILE & GetDrillSymbolProfile()
const VECTOR2I & GetGridOrigin() const
int GetBoardThickness() const
The full thickness of the board including copper and masks.
const VECTOR2I & GetAuxOrigin() const
BOARD_STACKUP & GetStackupDescriptor()
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
virtual bool IsKnockout() const
Definition board_item.h:437
bool IsLocked() const override
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
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:411
const NETINFO_LIST & GetNetInfo() const
Definition board.h:1241
EMBEDDED_FILES * GetEmbeddedFiles() override
Definition board.cpp:3709
const std::vector< wxString > & GetVariantNames() const
Definition board.h:533
const GENERATORS & Generators() const
Definition board.h:485
const PCB_POINTS & Points() const
Definition board.h:499
const PAGE_INFO & GetPageSettings() const
Definition board.h:1029
const ZONES & Zones() const
Definition board.h:469
const GROUPS & Groups() const
The groups must maintain the following invariants.
Definition board.h:518
LAYER_T GetLayerType(PCB_LAYER_ID aLayer) const
Return the type of the copper layer given by aLayer.
Definition board.cpp:1019
TITLE_BLOCK & GetTitleBlock()
Definition board.h:1035
int GetCopperLayerCount() const
Definition board.cpp:1155
const std::map< wxString, wxString > & GetProperties() const
Definition board.h:526
const FOOTPRINTS & Footprints() const
Definition board.h:465
const BOARD_ITEM_SET GetItemSet()
Collect every owned item (tracks, zones, generators, footprints, drawings, markers,...
Definition board.cpp:4262
const TRACKS & Tracks() const
Definition board.h:463
const CONSTRAINTS & Constraints() const
Geometric constraints (#2329) owned by this board.
Definition board.h:522
wxString GetVariantDescription(const wxString &aVariantName) const
Definition board.cpp:3172
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition board.h:1032
const wxString GetLayerName(PCB_LAYER_ID aLayer) const
Return the name of a aLayer.
Definition board.cpp:960
bool LegacyTeardrops() const
Definition board.h:1682
wxString GroupsSanityCheck(bool repair=false)
Consistency check of internal m_groups structure.
Definition board.cpp:3965
const LSET & GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
Definition board.cpp:1202
void Remove(BOARD_ITEM *aBoardItem, REMOVE_MODE aMode=REMOVE_MODE::NORMAL) override
Removes an item from the container.
Definition board.cpp:1723
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1318
const DRAWINGS & Drawings() const
Definition board.h:467
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.
The column set and formatting a new chart starts from.
static DRILL_CHART_TEMPLATE MakeDefault()
Grouping rules and symbol assignments, shared by reference so a chart and its map can never disagree ...
const wxString & GetName() const
const std::map< std::string, DRILL_SYMBOL_ASSIGNMENT > & Assignments() const
const std::set< DRILL_GROUP_KEY > & GroupKeys() const
DRILL_MARK_POLICY GetMarkPolicy() const
double AsDegrees() const
Definition eda_angle.h:115
bool IsZero() const
Definition eda_angle.h:135
EDA_ANGLE Normalize720()
Definition eda_angle.h:286
const LIB_ID & GetDesignBlockLibId() const
Definition eda_group.h:102
std::unordered_set< EDA_ITEM * > & GetItems()
Definition eda_group.h:78
wxString GetName() const
Definition eda_group.h:75
bool HasDesignBlockLink() const
Definition eda_group.h:99
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:599
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.cpp:153
EDA_ANGLE GetAngle() const
Definition eda_angle.h:557
const VECTOR2I & GetBezierC2() const
Definition eda_shape.h:377
FILL_T GetFillMode() const
Definition eda_shape.h:151
SHAPE_POLY_SET & GetPolyShape()
SHAPE_T GetShape() const
Definition eda_shape.h:178
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
const LINE_ENDING & GetStartEnding() const
Definition eda_shape.h:180
wxString SHAPE_T_asString() const
const VECTOR2I & GetBezierC1() const
Definition eda_shape.h:374
const LINE_ENDING & GetEndEnding() const
Definition eda_shape.h:186
int GetCornerRadius() const
bool IsPolyShapeValid() const
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
bool IsKeepUpright() const
Definition eda_text.h:245
virtual bool IsVisible() const
Definition eda_text.h:226
KIFONT::FONT * GetFont() const
Definition eda_text.h:286
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:395
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:684
virtual EDA_ANGLE GetDrawRotation() const
Definition eda_text.h:425
virtual wxString GetShownText(RESOLUTION_CONTEXT aContext, int aDepth=0) const
Return the string actually shown after processing of the base text.
Definition eda_text.h:128
virtual void Format(OUTPUTFORMATTER *aFormatter, int aControlBits) const
Output the object to aFormatter in s-expression form.
const TEXT_ATTRIBUTES & GetAttributes() const
Definition eda_text.h:270
virtual int GetTextThickness() const
Definition eda_text.h:159
bool IsEmpty() const
void WriteEmbeddedFiles(OUTPUTFORMATTER &aOut, bool aWriteData) const
Output formatter for the embedded files.
void ClearEmbeddedFiles(bool aDeleteFiles=true)
void ClearEmbeddedFonts()
Remove all embedded fonts from the collection.
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
const std::map< wxString, std::shared_ptr< EMBEDDED_FILE > > & EmbeddedFileMap() const
Provide an iterable view of the file collection.
bool GetAreFontsEmbedded() const
KIGFX::COLOR4D m_color
Definition pcb_3d_body.h:46
VECTOR3D m_offset
Definition pcb_3d_body.h:52
PCB_LAYER_ID m_layer
Definition pcb_3d_body.h:45
VECTOR3D m_rotation
Definition pcb_3d_body.h:51
EXTRUSION_MATERIAL m_material
Definition pcb_3d_body.h:47
A LINE_READER that reads from an open file.
Definition richio.h:157
void Rewind()
Rewind the file and resets the line number back to zero.
Definition richio.h:206
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:202
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:385
bool GetDuplicatePadNumbersAreJumpers() const
Definition footprint.h:1133
const CASE_INSENSITIVE_MAP< FOOTPRINT_VARIANT > & GetVariants() const
Get all variants.
Definition footprint.h:1011
void EmbedFonts() override
bool AllowSolderMaskBridges() const
Definition footprint.h:518
void SetFPID(const LIB_ID &aFPID)
Definition footprint.h:418
wxString GetLibDescription() const
Definition footprint.h:449
ZONE_CONNECTION GetLocalZoneConnection() const
Definition footprint.h:491
bool IsDNP() const
Definition footprint.h:947
EDA_ANGLE GetOrientation() const
Definition footprint.h:382
ZONES & Zones()
Definition footprint.h:361
PCB_POINTS & Points()
Definition footprint.h:370
bool IsExcludedFromBOM() const
Definition footprint.h:929
void SetOrientation(const EDA_ANGLE &aNewAngle)
const TRANSFORM_TRS & GetTransform() const
Definition footprint.h:395
wxString GetSheetname() const
Definition footprint.h:469
const std::vector< FP_UNIT_INFO > & GetUnitInfo() const
Definition footprint.h:909
std::optional< int > GetLocalSolderPasteMargin() const
Definition footprint.h:484
EDA_ITEM * Clone() const override
Create a duplicate of this item with linked list members set to NULL.
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:831
std::optional< int > GetLocalClearance() const
Definition footprint.h:478
CONSTRAINTS & Constraints()
Definition footprint.h:367
PCB_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this footprint.
std::deque< PAD * > & Pads()
Definition footprint.h:355
int GetAttributes() const
Definition footprint.h:509
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition footprint.h:393
LSET GetPrivateLayers() const
Definition footprint.h:295
bool AllowMissingCourtyard() const
Definition footprint.h:515
wxString GetSheetfile() const
Definition footprint.h:472
const std::vector< wxString > & GetNetTiePadGroups() const
Definition footprint.h:567
const LIB_ID & GetFPID() const
Definition footprint.h:417
int GetHeight() const
The overall height of the footprint, or 0 if not specified.
Definition footprint.h:438
bool IsExcludedFromPosFiles() const
Definition footprint.h:920
bool IsExcludedFromSim() const
Definition footprint.h:938
const LSET & GetStackupLayers() const
Definition footprint.h:507
PCB_FIELD & Reference()
Definition footprint.h:832
JUMPER_GROUP_SET & JumperPadGroups()
Each jumper pad group is a set of pad numbers that should be treated as internally connected.
Definition footprint.h:1140
void ClearAllNets()
Clear (i.e.
bool IsNetTie() const
Definition footprint.h:525
std::optional< double > GetLocalSolderPasteMarginRatio() const
Definition footprint.h:487
void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection) override
Flip this object, i.e.
GROUPS & Groups()
Definition footprint.h:364
wxString GetFilters() const
Definition footprint.h:475
const wxArrayString * GetInitialComments() const
Return the initial comments block or NULL if none, without transfer of ownership.
Definition footprint.h:1257
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:375
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:455
std::optional< int > GetLocalSolderMaskMargin() const
Definition footprint.h:481
wxString GetKeywords() const
Definition footprint.h:452
EMBEDDED_FILES * GetEmbeddedFiles() override
Definition footprint.h:1286
std::deque< PCB_3D_BODY * > & Bodies()
Definition footprint.h:422
FOOTPRINT_STACKUP GetStackupMode() const
Definition footprint.h:500
bool IsPlaced() const
Definition footprint.h:656
VECTOR2I GetPosition() const override
Definition footprint.h:379
DRAWINGS & GraphicalItems()
Definition footprint.h:358
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)
The columns one generator (the drill chart, a stackup table, ...) can produce, and the units and prec...
const char * Token(int aId) const
The file token for a known id, or a stable placeholder for one the schema does not recognize,...
const GENERATED_TABLE_COLUMN_DEF * Find(int aId) const
GENERATED_TABLE_UNITS DefaultUnits() const
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition io_base.h:267
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()
Represents an (ordered) list of JUMPER_GROUP objects.
const std::vector< JUMPER_GROUP > & GetAll() const
bool IsEmpty() const
Represents a group of jumper pins or pads, keyed by name.
APP_SETTINGS_BASE * KifaceSettings() const
Definition kiface_base.h:92
virtual bool IsOutline() const
Definition font.h:102
double r
Red component.
Definition color4d.h:391
double g
Green component.
Definition color4d.h:392
double a
Alpha component.
Definition color4d.h:394
static const COLOR4D UNSPECIFIED
For legacy support; used as a value to indicate color hasn't been set yet.
Definition color4d.h:400
double b
Blue component.
Definition color4d.h:393
virtual void SetLineWidth(float aLineWidth)
Set the line width.
virtual wxString GetClass() const =0
Return the class name.
wxString AsString() const
Definition kiid.cpp:423
wxString AsString() const
Definition kiid.cpp:264
LAYER_MAPPING_HANDLER m_layer_mapping_handler
Callback to get layer mapping.
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
UTF8 Format() const
Definition lib_id.cpp:132
const wxString GetUniStringLibItemName() const
Get strings for display messages in dialogs.
Definition lib_id.h:108
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
virtual wxString GetFootprint() const
For items with footprint fields.
void Format(OUTPUTFORMATTER *aOut, const EDA_IU_SCALE &aIuScale, const char *aToken) const
An abstract class from which implementation specific LINE_READERs may be derived to read single lines...
Definition richio.h:65
static LOAD_INFO_REPORTER & GetInstance()
Definition reporter.cpp:351
REPORTER & Report(const wxString &aMsg, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
Definition reporter.cpp:336
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
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:604
LSEQ CuStack() const
Return a sequence of copper layers in starting from the front/top and extending to the back/bottom.
Definition lset.cpp:259
LSEQ TechAndUserUIOrder() const
Return the technical and user layers in the order shown in layer widget.
Definition lset.cpp:272
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
Handle the data for a net.
Definition netinfo.h:50
const wxString & GetNetname() const
Definition netinfo.h:110
An interface used to output 8 bit text in a convenient way.
Definition richio.h:294
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:505
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:432
A PADSTACK defines the characteristics of a single or multi-layer pad, in the IPC sense of the word.
Definition padstack.h:161
std::optional< int > & Clearance(PCB_LAYER_ID aLayer=F_Cu)
MASK_LAYER_PROPS & FrontOuterLayers()
Definition padstack.h:410
void ForEachUniqueLayer(const std::function< void(PCB_LAYER_ID)> &aMethod) const
Runs the given callable for each active unique copper layer in this padstack, meaning F_Cu for MODE::...
bool HasExplicitDefinitionForLayer(PCB_LAYER_ID aLayer) const
Check if the padstack has an explicit definition for the given layer.
std::optional< int > & ThermalSpokeWidth(PCB_LAYER_ID aLayer=F_Cu)
EDA_ANGLE DefaultThermalSpokeAngleForShape(PCB_LAYER_ID aLayer=F_Cu) const
VECTOR2I & Offset(PCB_LAYER_ID aLayer)
Definition padstack.cpp:917
EDA_ANGLE ThermalSpokeAngle(PCB_LAYER_ID aLayer=F_Cu) const
POST_MACHINING_PROPS & FrontPostMachining()
Definition padstack.h:372
std::optional< int > & ThermalGap(PCB_LAYER_ID aLayer=F_Cu)
DRILL_PROPS & TertiaryDrill()
Definition padstack.h:369
DRILL_PROPS & Drill()
Definition padstack.h:363
const VECTOR2I & Size(PCB_LAYER_ID aLayer) const
Definition padstack.cpp:887
@ NORMAL
Shape is the same on all layers.
Definition padstack.h:175
@ FRONT_INNER_BACK
Up to three shapes can be defined (F_Cu, inner copper layers, B_Cu)
Definition padstack.h:176
DRILL_PROPS & SecondaryDrill()
Definition padstack.h:366
POST_MACHINING_PROPS & BackPostMachining()
Definition padstack.h:375
MODE Mode() const
Definition padstack.h:351
MASK_LAYER_PROPS & BackOuterLayers()
Definition padstack.h:413
static constexpr PCB_LAYER_ID INNER_LAYERS
! The layer identifier to use for "inner layers" on top/inner/bottom padstacks
Definition padstack.h:187
std::optional< ZONE_CONNECTION > & ZoneConnection(PCB_LAYER_ID aLayer=F_Cu)
Definition pad.h:61
PAD_PROP GetProperty() const
Definition pad.h:585
bool GetRemoveUnconnected() const
Definition pad.h:900
LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition pad.h:579
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:375
const ZONE_LAYER_OVERRIDE & GetZoneLayerOverride(PCB_LAYER_ID aLayer) const
Definition pad.cpp:521
std::optional< double > GetLocalSolderPasteMarginRatio() const
Definition pad.h:622
const wxString & GetPinType() const
Definition pad.h:160
PAD_ATTRIB GetAttribute() const
Definition pad.h:582
const wxString & GetPinFunction() const
Definition pad.h:154
const wxString & GetNumber() const
Definition pad.h:143
const VECTOR2I & GetDelta(PCB_LAYER_ID aLayer) const
Definition pad.h:307
EDA_ANGLE GetThermalSpokeAngle() const
Definition pad.h:779
VECTOR2I GetOffset(PCB_LAYER_ID aLayer) const
Definition pad.cpp:848
VECTOR2I GetDrillSize() const
Definition pad.h:320
double GetRoundRectRadiusRatio(PCB_LAYER_ID aLayer) const
Definition pad.h:837
PAD_SHAPE GetShape(PCB_LAYER_ID aLayer) const
Definition pad.h:205
bool GetKeepTopBottom() const
Definition pad.h:915
int GetPadToDieDelay() const
Definition pad.h:603
std::optional< int > GetLocalClearance() const override
Return any local clearances set in the "classic" (ie: pre-rule) system.
Definition pad.h:605
const PADSTACK & Padstack() const
Definition pad.h:331
EDA_ANGLE GetOrientation() const
Return the rotation angle of the pad.
Definition pad.cpp:1672
PAD_DRILL_SHAPE GetDrillShape() const
Definition pad.h:438
int GetChamferPositions(PCB_LAYER_ID aLayer) const
Definition pad.h:878
std::optional< int > GetLocalSolderPasteMargin() const
Definition pad.h:615
PAD_SIM_ELECTRICAL_TYPE GetSimElectricalType() const
Definition pad.h:595
std::optional< int > GetLocalSolderMaskMargin() const
Definition pad.h:608
double GetChamferRectRatio(PCB_LAYER_ID aLayer) const
Definition pad.h:860
std::optional< int > GetLocalThermalSpokeWidthOverride() const
Definition pad.h:763
ZONE_CONNECTION GetLocalZoneConnection() const
Definition pad.h:633
CUSTOM_SHAPE_ZONE_MODE GetCustomShapeInZoneOpt() const
Definition pad.h:227
int GetLocalThermalGapOverride(wxString *aSource) const
Definition pad.cpp:2157
PAD_SHAPE GetAnchorPadShape(PCB_LAYER_ID aLayer) const
Definition pad.h:219
int GetPadToDieLength() const
Definition pad.h:600
void Format(OUTPUTFORMATTER *aFormatter) const
Output the page class to aFormatter in s-expression form.
FLIP_DIRECTION m_FlipDirection
A 3D body attached to a footprint (or, later, placed on a board).
Definition pcb_3d_body.h:93
const VECTOR2I & GetMid() const
Definition pcb_track.h:304
const VECTOR2I & GetMargin() const
Get the barcode margin (in internal units).
VECTOR2I GetPosition() const override
Get the position (center) of the barcode in internal units.
wxString GetText() const
int GetTextSize() const
bool IsKnockout() const override
int GetHeight() const
Get the barcode height (in internal units).
BARCODE_ECC_T GetErrorCorrection() const
bool GetShowText() const
EDA_ANGLE GetAngle() const
BARCODE_T GetKind() const
Returns the type of the barcode (QR, CODE_39, etc.).
int GetWidth() const
Get the barcode width (in internal units).
A geometric constraint between board items (issue #2329).
const std::vector< CONSTRAINT_MEMBER > & GetMembers() const
std::optional< double > GetValue() const
bool IsDriving() const
A driving constraint forces its value; a reference (non-driving) one only measures it.
PCB_CONSTRAINT_TYPE GetConstraintType() const
bool HasValue() const
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
DIM_ARROW_DIRECTION GetArrowDirection() const
virtual VECTOR2I GetEnd() const
bool GetSuppressZeroes() const
int GetExtensionOffset() const
virtual VECTOR2I GetStart() const
The dimension's origin is the first feature point for the dimension.
int GetArrowLength() const
bool GetOverrideTextEnabled() 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
A drill chart placed on the board, kept in step with the holes.
const std::map< int, int > & RowShapes() const
Curated shape index for each generated row, by table row.
bool GetShowTotals() const
DRILL_CHART_FILTER & Filter()
int GetSymbolColumn() const
Table column the symbol is drawn in, or -1 when the chart has no symbol column.
Turns on drill symbols at the holes, for one layer.
bool GetAllSpans() const
int GetSymbolSize() const
bool GetGuideCross() const
bool GetOutlineSlots() const
const DRILL_SPAN & GetSpan() const
const VECTOR2I & GetOffset() const
A table whose cell text is derived from the board and rebuilt whenever it goes stale.
std::vector< GENERATED_TABLE_COLUMN > AllColumns() const
Every column the table has been given, in order, with hidden ones marked by m_Visible.
const std::map< int, std::string > & RowKeys() const
What each generated row reports on, by table row.
virtual const GENERATED_TABLE_SCHEMA & Schema() const =0
GENERATED_TABLE_UNITS GetUnits() const
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
virtual std::vector< std::pair< wxString, const BOARD_ITEM * > > GetTemplateItems() const
Named template items used by the generator.
virtual const STRING_ANY_MAP GetProperties() const
virtual wxString GetGeneratorType() const
EDA_ANGLE GetPhiExtent() const
VECTOR2I GetSpacing() const
VECTOR2I GetExtent() const
unsigned GetAssignedPriority() const
unsigned GetTickInterval() const
VECTOR2I GetPosition() const override
int GetRadiusSpacing() const
EDA_ANGLE GetOrientation() const
EDA_ANGLE GetPhiSpacing() const
PCB_GRID_AFFECTS & Affects()
int GetRadiusExtent() const
PCB_GRID_TYPE GetGridItemType() const
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:51
Read a Pcbnew s-expression formatted LINE_READER object and returns the appropriate BOARD_ITEM object...
const std::vector< wxString > & GetParseWarnings() const
Return any non-fatal parse warnings that occurred during parsing.
void SetLayerMappingHandler(LAYER_MAPPING_HANDLER aHandler)
Handler to remap an appended board's layers onto the destination board, used on mismatch.
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.
void ParseFootprintLib(boost::ptr_map< wxString, FP_CACHE_ENTRY, std::less< wxString >, boost::heap_clone_allocator, std::allocator< std::pair< const wxString, void * > > > &aFootprints)
Parse a footprint library file.
wxString GetRequiredVersion()
Return a string representing the version of KiCad required to open this file.
A PCB_IO derivation for saving and loading Pcbnew s-expression formatted files.
bool CanReadBoard(const wxString &aFileName) const override
void loadBoard(const wxString &aFileName, BOARD &aBoard, bool aIsNewLoad, const std::map< std::string, UTF8 > *aProperties=nullptr, PROJECT *aProject=nullptr) override
Parse aFileName into aBoard.
void formatProperties(const BOARD *aBoard) const
formats the Nets and Netclasses
void FootprintDelete(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete aFootprintName from the library at aLibraryPath.
void formatTableData(const PCB_TABLE *aTable) const
Geometry and cells with no identity, so an enclosing form owns uuid/layer/locked.
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,...
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 i...
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 formatDrillSymbolProfile(const BOARD_DESIGN_SETTINGS &aSettings) const
void formatPolyPts(const SHAPE_LINE_CHAIN &outline, const FOOTPRINT *aParentFP=nullptr) const
std::unique_ptr< 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.
FP_CACHE * m_cache
Footprint library cache.
void DoLoad(LINE_READER &aReader, BOARD &aBoard, bool aIsNewLoad, const std::map< std::string, UTF8 > *aProperties, PROGRESS_REPORTER *aProgressReporter, unsigned aLineCount)
void FormatFootprintLibFile(FOOTPRINT *aFootprint) const
Output aFootprint as a complete footprint library file.
void formatBoardLayers(const BOARD *aBoard) const
formats the board layer information
std::unique_ptr< 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...
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 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 format(const BOARD *aBoard) const
void formatLayers(LSET aLayerMask, bool aEnumerateLayers, bool aIsZone=false) const
void formatGeneral(const BOARD *aBoard) const
formats the General section of the file
void formatVariants(const BOARD *aBoard) const
formats the board variant registry
void ClearCachedFootprints(const wxString &aLibraryPath) override
Clear any cached footprint data for the given library path.
void formatSetup(const BOARD *aBoard) const
formats the board setup information
void formatGeneratedTableExtras(const PCB_GENERATED_TABLE *aTable) const
What only one kind of generated table carries, written after the shared settings.
void FormatBoardToFormatter(OUTPUTFORMATTER *aOut, BOARD *aBoard, const std::map< std::string, UTF8 > *aProperties=nullptr)
Serialize a BOARD to an OUTPUTFORMATTER without file I/O or Prettify.
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 formatInitialComments(const FOOTPRINT *aFootprint) const
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:404
virtual bool CanReadBoard(const wxString &aFileName) const
Definition pcb_io.cpp:40
PCB_IO(const wxString &aName)
Definition pcb_io.h:383
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:407
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:39
int GetSize() const
Definition pcb_point.h:69
VECTOR2I GetLibraryPosition() const
Definition pcb_point.h:61
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()
EDA_ANGLE GetLibraryEllipseEndAngle() const
Definition pcb_shape.h:244
std::optional< int > GetLocalSolderMaskMargin() const
Definition pcb_shape.h:352
bool HasSolderMask() const
Definition pcb_shape.h:349
int GetLibraryEllipseMinorRadius() const
Definition pcb_shape.h:241
EDA_ANGLE GetLibraryEllipseStartAngle() const
Definition pcb_shape.h:243
int GetLibraryEllipseMajorRadius() const
Definition pcb_shape.h:240
EDA_ANGLE GetLibraryEllipseRotation() const
Definition pcb_shape.h:242
SHAPE_T GetLibraryShape() const
Definition pcb_shape.h:236
VECTOR2I GetLibraryEllipseCenter() const
Definition pcb_shape.h:239
VECTOR2I GetLibraryEnd() const
Definition pcb_shape.h:235
const SHAPE_POLY_SET & GetLibPoly() const
Definition pcb_shape.h:292
VECTOR2I GetLibraryStart() const
Definition pcb_shape.h:234
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
STROKE_PARAMS GetStroke() const override
VECTOR2I GetLibraryArcMid() const
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:70
int GetLibraryCornerRadius() const
Definition pcb_shape.h:237
bool StrokeRows() const
Definition pcb_table.h:110
int GetRowCount() const
Definition pcb_table.h:128
bool StrokeHeaderSeparator() const
Definition pcb_table.h:68
bool StrokeColumns() const
Definition pcb_table.h:107
bool StrokeExternal() const
Definition pcb_table.h:65
std::vector< PCB_TABLECELL * > GetCells() const
Definition pcb_table.h:165
int GetColCount() const
Definition pcb_table.h:126
const STROKE_PARAMS & GetSeparatorsStroke() const
Definition pcb_table.h:89
const STROKE_PARAMS & GetBorderStroke() const
Definition pcb_table.h:71
int GetColWidth(int aCol) const
Definition pcb_table.h:137
virtual wxString GetClass() const override
Return the class name.
Definition pcb_table.h:54
int GetRowHeight(int aRow) const
Definition pcb_table.h:147
int GetShape() const
Definition pcb_target.h:54
int GetWidth() const
Definition pcb_target.h:60
int GetSize() const
Definition pcb_target.h:57
VECTOR2I GetPosition() const override
Definition pcb_target.h:51
bool IsBorderEnabled() const
Tests whether the border is disabled, as configured by the stroke.
int GetMarginBottom() const
EDA_ANGLE GetTextAngle() const override
int GetMarginLeft() const
int GetMarginRight() const
int GetMarginTop() const
EDA_ANGLE GetTextAngle() const override
Definition pcb_text.cpp:562
VECTOR2I GetTextPos() const override
Definition pcb_text.cpp:463
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:124
std::optional< int > GetLocalSolderMaskMargin() const
Definition pcb_track.h:127
const VECTOR2I & GetStart() const
Definition pcb_track.h:100
const VECTOR2I & GetEnd() const
Definition pcb_track.h:97
virtual int GetWidth() const
Definition pcb_track.h:94
bool Finish() override
Runs prettification over the buffered bytes, writes them to the sibling temp file,...
Definition richio.cpp:710
A progress reporter interface for use in multi-threaded environments.
Container for project specific data.
Definition project.h:63
A REFERENCE_IMAGE is a wrapper around a BITMAP_IMAGE that is displayed in an editor as a reference fo...
EDA_ANGLE GetOrientation() const
double GetOpacity() const
const BITMAP_BASE & GetImage() const
Get the underlying image.
double GetImageScale() const
const VECTOR2I & GetArcMid() const
Definition shape_arc.h:116
const VECTOR2I & GetP1() const
Definition shape_arc.h:115
const VECTOR2I & GetP0() const
Definition shape_arc.h:114
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.
int OutlineCount() const
Return the number of outlines in the set.
Is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition richio.h:225
Simple container to manage line stroke parameters.
int GetWidth() const
void SetWidth(int aWidth)
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.
VECTOR2I InverseApply(const VECTOR2I &aPoint) const
double GetScaleX() const
double GetScaleY() const
const char * c_str() const
Definition utf8.h:104
A wrapper around a wxFileName which is much more performant with a subset of the API.
Definition wx_filename.h:46
void SetFullName(const wxString &aFileNameAndExtension)
static void ResolvePossibleSymlinks(wxFileName &aFilename)
wxString GetName() const
wxString GetFullPath() const
long long GetTimestamp()
Handle a list of polygons defining a copper zone.
Definition zone.h:70
int GetHatchBorderAlgorithm() const
Definition zone.h:343
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:834
std::optional< int > GetLocalClearance() const override
Definition zone.cpp:1099
const THIEVING_SETTINGS & GetThievingSettings() const
Definition zone.h:351
bool GetDoNotAllowVias() const
Definition zone.h:852
const REPEAT_LAYOUT_OPTIONS & GetRepeatOptions() const
Definition zone.h:848
ZONE_LAYER_PROPERTIES & LayerProperties(PCB_LAYER_ID aLayer)
Definition zone.h:146
wxString GetPlacementAreaSource() const
Definition zone.h:839
std::shared_ptr< SHAPE_POLY_SET > GetFilledPolysList(PCB_LAYER_ID aLayer) const
Definition zone.h:701
bool GetDoNotAllowPads() const
Definition zone.h:854
PLACEMENT_SOURCE_T GetPlacementAreaSourceType() const
Definition zone.h:841
bool GetDoNotAllowTracks() const
Definition zone.h:853
bool IsFilled() const
Definition zone.h:306
ISLAND_REMOVAL_MODE GetIslandRemovalMode() const
Definition zone.h:863
SHAPE_POLY_SET * Outline()
Definition zone.h:421
bool IsIsland(PCB_LAYER_ID aLayer, int aPolyIdx) const
Check if a given filled polygon is an insulated island.
Definition zone.cpp:1769
long long int GetMinIslandArea() const
Definition zone.h:866
const wxString & GetZoneName() const
Definition zone.h:160
int GetMinThickness() const
Definition zone.h:315
ZONE_SETTINGS::CORNER_SMOOTHING GetCornerSmoothingType() const
Definition zone.h:773
ZONE_CONNECTION GetPadConnection() const
Definition zone.h:312
int GetHatchThickness() const
Definition zone.h:325
double GetHatchHoleMinArea() const
Definition zone.h:340
bool GetPlacementAreaEnabled() const
Definition zone.h:836
bool IsTeardropArea() const
Definition zone.h:809
int GetThermalReliefSpokeWidth() const
Definition zone.h:259
int GetBorderHatchPitch() const
HatchBorder related methods.
Definition zone.h:876
ZONE_BORDER_DISPLAY_STYLE GetHatchStyle() const
Definition zone.h:689
EDA_ANGLE GetHatchOrientation() const
Definition zone.h:331
bool GetDoNotAllowFootprints() const
Definition zone.h:855
ZONE_FILL_MODE GetFillMode() const
Definition zone.h:238
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
int GetHatchGap() const
Definition zone.h:328
TEARDROP_TYPE GetTeardropAreaType() const
Definition zone.h:820
const KIID & GetLinkSet() const
The set of placement rule areas that share one layout, or niluuid when this one is not linked.
Definition zone.h:845
double GetHatchSmoothingValue() const
Definition zone.h:337
bool GetDoNotAllowZoneFills() const
Definition zone.h:851
int GetHatchSmoothingLevel() const
Definition zone.h:334
unsigned int GetCornerRadius() const
Definition zone.h:777
bool IsOnCopperLayer() const override
Definition zone.cpp:652
PCB_LAYER_ID GetFirstLayer() const
Definition zone.cpp:632
int GetThermalReliefGap() const
Definition zone.h:248
unsigned GetAssignedPriority() const
Definition zone.h:122
int GetNumCorners(void) const
Access to m_Poly parameters.
Definition zone.h:619
@ FOR_CANVAS
Definition common.h:92
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
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition cvpcb.cpp:178
const char * DrillGroupKeyToken(DRILL_GROUP_KEY aKey)
Stable file tokens, deliberately independent of enum ordering so a later insertion into the enum cann...
const char * DrillMarkModeToken(DRILL_MARK_MODE aMode)
const char * DrillMarkPolicyToken(DRILL_MARK_POLICY aPolicy)
DRILL_GROUP_KEY
Which properties split holes into separate chart rows and symbols.
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
static constexpr EDA_ANGLE ANGLE_45
Definition eda_angle.h:473
@ REVERSE_HATCH
Definition eda_fill.h:35
@ HATCH
Definition eda_fill.h:34
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
@ CROSS_HATCH
Definition eda_fill.h:36
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
SHAPE_T
Definition eda_shape.h:55
@ ELLIPSE
Definition eda_shape.h:63
@ SEGMENT
Definition eda_shape.h:57
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
@ ELLIPSE_ARC
Definition eda_shape.h:64
EDA_DATA_TYPE
The type of unit.
Definition eda_units.h:34
@ FP_SMD
Definition footprint.h:87
@ FP_DNP
Definition footprint.h:92
@ FP_EXCLUDE_FROM_POS_FILES
Definition footprint.h:88
@ FP_BOARD_ONLY
Definition footprint.h:90
@ FP_EXCLUDE_FROM_BOM
Definition footprint.h:89
@ FP_EXCLUDE_FROM_SIM
Definition footprint.h:93
@ FP_THROUGH_HOLE
Definition footprint.h:86
@ EXPAND_INNER_LAYERS
The 'normal' stackup handling, where there is a single inner layer (In1) and rule areas using it expa...
Definition footprint.h:111
const char * GeneratedTableUnitsToken(GENERATED_TABLE_UNITS aUnits)
Stable file tokens, independent of enum ordering so inserting a value later cannot change what an exi...
const char * GeneratedTableAlignToken(GENERATED_TABLE_ALIGN aAlign)
void CollectFilesLoopSafe(const wxString &aRoot, wxArrayString &aFiles, const wxString &aFileSpec, int aFlags)
Recursively collect every file under aRoot, deduplicating subdirectories by their resolved path.
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
#define THROW_IO_CANCELLED()
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
static const std::string KiCadFootprintFileExtension
const wxChar *const traceKicadPcbPlugin
Flag to enable KiCad PCB plugin debug output.
KIID niluuid(0)
#define MAX_CU_LAYERS
Definition layer_ids.h:172
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
Definition layer_ids.h:744
bool IsExternalCopperLayer(int aLayerId)
Test whether a layer is an external (F_Cu or B_Cu) copper layer.
Definition layer_ids.h:755
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_CrtYd
Definition layer_ids.h:112
@ B_Adhes
Definition layer_ids.h:99
@ F_Paste
Definition layer_ids.h:100
@ F_Adhes
Definition layer_ids.h:98
@ B_Mask
Definition layer_ids.h:94
@ B_Cu
Definition layer_ids.h:61
@ F_Mask
Definition layer_ids.h:93
@ B_Paste
Definition layer_ids.h:101
@ UNSELECTED_LAYER
Definition layer_ids.h:58
@ F_Fab
Definition layer_ids.h:115
@ F_SilkS
Definition layer_ids.h:96
@ B_CrtYd
Definition layer_ids.h:111
@ UNDEFINED_LAYER
Definition layer_ids.h:57
@ User_1
Definition layer_ids.h:120
@ B_SilkS
Definition layer_ids.h:97
@ PCB_LAYER_ID_COUNT
Definition layer_ids.h:167
@ F_Cu
Definition layer_ids.h:60
@ B_Fab
Definition layer_ids.h:114
Utilities for intentionally "leaking" memory at program exit.
#define LSAN_IGNORE(ptr)
This file contains miscellaneous commonly used macros and functions.
#define UNIMPLEMENTED_FOR(type)
Definition macros.h:92
@ TOP_BOTTOM
Flip top to bottom (around the X axis)
Definition mirror.h:28
KICOMMON_API std::string FormatAngle(const EDA_ANGLE &aAngle)
Convert aAngle from board units to a string appropriate for writing to file.
KICOMMON_API std::string FormatInternalUnits(const EDA_IU_SCALE &aIuScale, int aValue, EDA_DATA_TYPE aDataType=EDA_DATA_TYPE::DISTANCE)
Converts aValue from internal units to a string appropriate for writing to file.
void FormatCustomProperties(OUTPUTFORMATTER *aOut, const EDA_ITEM &aItem)
Writes the item's custom properties as a series of (custom_property "key" "value")
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])
long long TimestampDir(const wxString &aDirPath, const wxString &aFilespec)
Computes a hash of modification times and sizes for files matching a pattern.
Definition unix/io.cpp:123
constexpr char APPEND_PRESERVE_DESTINATION_STACKUP[]
Definition pcb_io.h:46
@ NPTH
like PAD_PTH, but not plated mechanical use only, no connection allowed
Definition padstack.h:104
@ NON_COMPONENT
Pad with no hole that does not connect to a physical component, but rather provides a connection poin...
Definition padstack.h:106
@ SMD
Smd pad, appears on the solder paste layer (default)
Definition padstack.h:100
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ CONN
Like smd, does not appear on the solder paste layer (default) Note: also has a special attribute in G...
Definition padstack.h:101
@ CHAMFERED_RECT
Definition padstack.h:61
@ ROUNDRECT
Definition padstack.h:58
@ TRAPEZOID
Definition padstack.h:57
@ RECTANGLE
Definition padstack.h:55
@ FIDUCIAL_LOCAL
a fiducial (usually a smd) local to the parent footprint
Definition padstack.h:122
@ FIDUCIAL_GLBL
a fiducial (usually a smd) for the full board
Definition padstack.h:121
@ MECHANICAL
a pad used for mechanical support
Definition padstack.h:126
@ PRESSFIT
a PTH with a hole diameter with tight tolerances for press fit pin
Definition padstack.h:127
@ HEATSINK
a pad used as heat sink, usually in SMD footprints
Definition padstack.h:124
@ NONE
no special fabrication property
Definition padstack.h:119
@ TESTPOINT
a test point pad
Definition padstack.h:123
@ CASTELLATED
a pad with a castellated through hole
Definition padstack.h:125
@ BGA
Smd pad, used in BGA footprints.
Definition padstack.h:120
BARCODE class definition.
bool ConstraintValueIsLength(PCB_CONSTRAINT_TYPE aType)
True if this type's value is a length in IU (serialized in mm); false for an angle in degrees.
const char * ConstraintTypeToken(PCB_CONSTRAINT_TYPE aType)
Stable file-format token for a constraint type (e.g. "parallel"). Used by serialization.
const char * ConstraintAnchorToken(CONSTRAINT_ANCHOR aAnchor)
Stable file-format token for a member anchor (e.g. "start").
@ VERTEX
An indexed rectangle corner or polygon outline vertex; pairs with CONSTRAINT_MEMBER::m_index.
Class to handle a set of BOARD_ITEMs.
static void formatDrillSpan(OUTPUTFORMATTER *aOut, const DRILL_SPAN &aSpan)
Layers plus the flags that distinguish a backdrill or non-plated span from the primary one that share...
bool isDefaultTeardropParameters(const TEARDROP_PARAMETERS &tdParams)
static VECTOR2I unbakeSize(const VECTOR2I &aSize, const FOOTPRINT *aParentFP)
std::string formatInternalUnits(const int aValue, const EDA_DATA_TYPE aDataType=EDA_DATA_TYPE::DISTANCE)
static int unbakeLinear(int aValue, const FOOTPRINT *aParentFP)
static VECTOR2I unbakeSizeUniform(const VECTOR2I &aSize, const FOOTPRINT *aParentFP)
#define SEXPR_FOOTPRINT_LIB_FILE_VERSION
#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.
#define UNDEFINED_DRILL_DIAMETER
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
@ RPT_SEVERITY_WARNING
std::string FormatDouble2Str(double aValue)
Print a float number without using scientific notation and no trailing 0 This function is intended in...
bool ReplaceIllegalFileNameChars(std::string &aName, int aReplaceChar)
Checks aName for illegal file name characters.
int ValueStringCompare(const wxString &strFWord, const wxString &strSWord)
Compare strings like the strcmp function but handle numbers and modifiers within the string text corr...
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
One participant in a constraint: a referenced board item plus the feature of that item that participa...
Which holes a chart reports on.
PCB_LAYER_ID DrillEndLayer() const
Definition drill_span.h:88
PCB_LAYER_ID DrillStartLayer() const
Definition drill_span.h:83
bool m_IsNonPlatedFile
Definition drill_span.h:131
bool m_IsBackdrill
Definition drill_span.h:130
Variant of PARSE_ERROR indicating that a syntax or related error was likely caused by a file generate...
The column a schema knows how to build, independent of whether any particular table shows it.
A column as a generated table actually carries it: what a row's cell in that column holds and how it ...
PCB_LAYER_ID start
Definition padstack.h:280
PCB_LAYER_ID end
Definition padstack.h:281
VECTOR2I size
Drill diameter (x == y) or slot dimensions (x != y)
Definition padstack.h:278
std::optional< bool > is_capped
True if the drill hole should be capped.
Definition padstack.h:284
std::optional< bool > is_filled
True if the drill hole should be filled completely.
Definition padstack.h:283
std::optional< bool > has_covering
True if the pad on this side should have covering.
Definition padstack.h:266
std::optional< bool > has_solder_mask
True if this outer layer has mask (is not tented)
Definition padstack.h:264
std::optional< bool > has_plugging
True if the drill hole should be plugged on this side.
Definition padstack.h:267
A filename or source description, a problem input line, a line number, a byte offset,...
bool routing
Used by the router as a local routing frame.
bool cursor
Replace the display grid for cursor snapping inside coverage.
bool placement
Used by edit/move tools for placement snap.
Options for copying a placement rule area onto the others linked to it.
KIID m_anchor
This area's own anchor footprint, or niluuid for the area center.
Parameters that drive copper-thieving fill generation.
THIEVING_PATTERN pattern
EDA_ORIENTATION orientation
std::optional< VECTOR2I > hatching_offset
VECTOR2I center
const SHAPE_LINE_CHAIN chain
int delta
wxLogTrace helper definitions.
#define kv
@ PCB_T
Definition typeinfo.h:74
@ PCB_CONSTRAINT_T
a geometric constraint between board items
Definition typeinfo.h:237
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition typeinfo.h:98
@ PCB_DIM_LEADER_T
class PCB_DIM_LEADER, a leader dimension (graphic item)
Definition typeinfo.h:95
@ PCB_GENERATOR_T
class PCB_GENERATOR, generator on a layer
Definition typeinfo.h:83
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_DRILL_MAP_T
class PCB_DRILL_MAP, drill symbols drawn at the holes
Definition typeinfo.h:240
@ PCB_DIM_CENTER_T
class PCB_DIM_CENTER, a center point marking (graphic item)
Definition typeinfo.h:96
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:103
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition typeinfo.h:85
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:100
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_REFERENCE_IMAGE_T
class PCB_REFERENCE_IMAGE, bitmap on a layer
Definition typeinfo.h:81
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:82
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:93
@ PCB_TARGET_T
class PCB_TARGET, a target (graphic item)
Definition typeinfo.h:99
@ PCB_TABLECELL_T
class PCB_TABLECELL, PCB_TEXTBOX for use in tables
Definition typeinfo.h:87
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:78
@ PCB_GRID_ITEM_T
a subgrid placed on a board
Definition typeinfo.h:238
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:94
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:90
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:86
@ PCB_STACKUP_TABLE_T
class PCB_STACKUP_TABLE, a live stackup table derived from PCB_TABLE
Definition typeinfo.h:242
@ PCB_POINT_T
class PCB_POINT, a 0-dimensional point
Definition typeinfo.h:105
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:97
@ PCB_DRILL_CHART_T
class PCB_DRILL_CHART, a live drill chart derived from PCB_TABLE
Definition typeinfo.h:239
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.
@ THERMAL
Use thermal relief for pads.
Definition zones.h:46
@ THT_THERMAL
Thermal relief only for THT pads.
Definition zones.h:48
@ NONE
Pads are not covered.
Definition zones.h:45
@ FULL
pads are covered by copper
Definition zones.h:47