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