KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pcb_io_kicad_sexpr_parser.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2012 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
25
26#include "layer_ids.h"
27#include "pcb_lexer.h"
28#include <cerrno>
29#include <charconv>
30#include <cmath>
31#include <confirm.h>
32#include <macros.h>
33#include <fmt/format.h>
34#include <title_block.h>
35#include <trigo.h>
36
37#include <board.h>
43#include <font/fontconfig.h>
44#include <magic_enum.hpp>
45#include <pcb_dimension.h>
46#include <pcb_shape.h>
47#include <pcb_reference_image.h>
48#include <pcb_barcode.h>
49#include <pcb_group.h>
50#include <pcb_generator.h>
51#include <pcb_point.h>
52#include <pcb_target.h>
53#include <pcb_grid_item.h>
54#include <pcb_track.h>
55#include <pcb_textbox.h>
56#include <pcb_drill_chart.h>
57#include <pcb_stackup_table.h>
58#include <pcb_drill_map.h>
59#include <pcb_table.h>
60#include <pad.h>
61#include <generators_mgr.h>
62#include <zone.h>
63#include <footprint.h>
64#include <pcb_3d_body.h>
66#include <font/font.h>
67#include <core/ignore.h>
68#include <netclass.h>
69#include <netinfo.h>
72#include <pcb_plot_params.h>
73#include <zones.h>
75#include <convert_basic_shapes_to_polygon.h> // for RECT_CHAMFER_POSITIONS definition
76#include <math/util.h> // KiROUND, Clamp
77#include <string_utils.h>
79#include <wx/log.h>
80#include <progress_reporter.h>
82#include <pgm_base.h>
83#include <trace_helpers.h>
84
85// For some reason wxWidgets is built with wxUSE_BASE64 unset so expose the wxWidgets
86// base64 code. Needed for PCB_REFERENCE_IMAGE
87#define wxUSE_BASE64 1
88#include <wx/base64.h>
89#include <wx/log.h>
90#include <wx/mstream.h>
91
92// We currently represent board units as integers. Any values that are
93// larger or smaller than those board units represent undefined behavior for
94// the system. We limit values to the largest usable
95// i.e. std::numeric_limits<int>::max().
96// However to avoid issues in comparisons, use a slightly smaller value
97// Note also the usable limits are much smaller to avoid overflows in intermediate
98// calculations.
99constexpr double INT_LIMIT = std::numeric_limits<int>::max() - 10;
100
101using namespace PCB_KEYS_T;
102
103
105{
108 m_tooRecent = false;
110 m_layerIndices.clear();
111 m_layerMasks.clear();
112 m_resetKIIDMap.clear();
113 m_linkedZones.clear();
114
115 // Add untranslated default (i.e. English) layernames.
116 // Some may be overridden later if parsing a board rather than a footprint.
117 // The English name will survive if parsing only a footprint.
118 for( int layer = 0; layer < PCB_LAYER_ID_COUNT; ++layer )
119 {
120 std::string untranslated = TO_UTF8( LSET::Name( PCB_LAYER_ID( layer ) ) );
121
122 m_layerIndices[untranslated] = PCB_LAYER_ID( layer );
123 m_layerMasks[untranslated] = LSET( { PCB_LAYER_ID( layer ) } );
124 }
125
126 m_layerMasks[ "*.Cu" ] = LSET::AllCuMask();
127 m_layerMasks[ "*In.Cu" ] = LSET::InternalCuMask();
128 m_layerMasks[ "F&B.Cu" ] = LSET( { F_Cu, B_Cu } );
129 m_layerMasks[ "*.Adhes" ] = LSET( { B_Adhes, F_Adhes } );
130 m_layerMasks[ "*.Paste" ] = LSET( { B_Paste, F_Paste } );
131 m_layerMasks[ "*.Mask" ] = LSET( { B_Mask, F_Mask } );
132 m_layerMasks[ "*.SilkS" ] = LSET( { B_SilkS, F_SilkS } );
133 m_layerMasks[ "*.Fab" ] = LSET( { B_Fab, F_Fab } );
134 m_layerMasks[ "*.CrtYd" ] = LSET( { B_CrtYd, F_CrtYd } );
135
136 // This is for the first pretty & *.kicad_pcb formats, which had
137 // Inner1_Cu - Inner14_Cu with the numbering sequence
138 // reversed from the subsequent format's In1_Cu - In30_Cu numbering scheme.
139 // The newer format brought in an additional 16 Cu layers and flipped the cu stack but
140 // kept the gap between one of the outside layers and the last cu internal.
141
142 for( int i=1; i<=14; ++i )
143 {
144 std::string key = fmt::format( "Inner{}.Cu", i );
145
146 m_layerMasks[key] = LSET( { PCB_LAYER_ID( In15_Cu - 2 * i ) } );
147 }
148}
149
150
152{
154 {
155 TIME_PT curTime = CLOCK::now();
156 unsigned curLine = reader->LineNumber();
157 auto delta = std::chrono::duration_cast<TIMEOUT>( curTime - m_lastProgressTime );
158
159 if( delta > std::chrono::milliseconds( 250 ) )
160 {
161 m_progressReporter->SetCurrentProgress( ( (double) curLine )
162 / std::max( 1U, m_lineCount ) );
163
164 if( !m_progressReporter->KeepRefreshing() )
166
167 m_lastProgressTime = curTime;
168 }
169 }
170}
171
172
174{
175 int curr_level = 0;
176 T token;
177
178 while( ( token = NextTok() ) != T_EOF )
179 {
180 if( token == T_LEFT )
181 curr_level--;
182
183 if( token == T_RIGHT )
184 {
185 curr_level++;
186
187 if( curr_level > 0 )
188 return;
189 }
190 }
191}
192
193
195{
196 // Add aValue in netcode mapping (m_netCodes) at index aNetCode
197 // ensure there is room in m_netCodes for that, and add room if needed.
198
199 if( (int)m_netCodes.size() <= aIndex )
200 m_netCodes.resize( static_cast<std::size_t>( aIndex ) + 1 );
201
202 m_netCodes[aIndex] = aValue;
203}
204
205
207{
208 // There should be no major rounding issues here, since the values in
209 // the file are in mm and get converted to nano-meters.
210 // See test program tools/test-nm-biu-to-ascii-mm-round-tripping.cpp
211 // to confirm or experiment. Use a similar strategy in both places, here
212 // and in the test program. Make that program with:
213 // $ make test-nm-biu-to-ascii-mm-round-tripping
214 auto retval = parseDouble() * pcbIUScale.IU_PER_MM;
215
216 // N.B. we currently represent board units as integers. Any values that are
217 // larger or smaller than those board units represent undefined behavior for
218 // the system. We limit values to the largest that is visible on the screen
219 return KiROUND( std::clamp( retval, -INT_LIMIT, INT_LIMIT ) );
220}
221
222
224 const EDA_DATA_TYPE aDataType = EDA_DATA_TYPE::DISTANCE )
225{
227 auto retval = parseDouble( aExpected ) * scale;
228
229 // N.B. we currently represent board units as integers. Any values that are
230 // larger or smaller than those board units represent undefined behavior for
231 // the system. We limit values to the largest that is visible on the screen
232 return KiROUND( std::clamp( retval, -INT_LIMIT, INT_LIMIT ) );
233}
234
235
237{
238 T token = NextTok();
239
240 if( token == T_yes )
241 return true;
242 else if( token == T_no )
243 return false;
244 else
245 Expecting( "yes or no" );
246
247 return false;
248}
249
250
252{
253 T token = NextTok();
254
255 if( token == T_yes )
256 return true;
257 else if( token == T_no )
258 return false;
259 else if( token == T_none )
260 return std::nullopt;
261 else
262 Expecting( "yes, no or none" );
263
264 return false;
265}
266
267
268/*
269 * e.g. "hide", "hide)", "(hide yes)"
270 */
272{
273 bool ret = aDefaultValue;
274
275 if( PrevTok() == T_LEFT )
276 {
277 T token = NextTok();
278
279 // "hide)"
280 if( static_cast<int>( token ) == DSN_RIGHT )
281 return aDefaultValue;
282
283 if( token == T_yes || token == T_true )
284 ret = true;
285 else if( token == T_no || token == T_false )
286 ret = false;
287 else
288 Expecting( "yes or no" );
289
290 NeedRIGHT();
291 }
292 else
293 {
294 // "hide"
295 return aDefaultValue;
296 }
297
298 return ret;
299}
300
301
303{
304 int token = NextTok();
305
306 // Legacy files (pre-10.0) will have a netcode instead of a netname. This netcode
307 // is authoratative (though may be mapped by getNetCode() to prevent collisions).
308 if( IsNumber( token ) )
309 {
310 if( !aItem->SetNetCode( std::max( 0, getNetCode( parseInt() ) ), /* aNoAssert */ true ) )
311 {
312 wxLogTrace( traceKicadPcbPlugin,
313 _( "Invalid net ID in\nfile: %s;\nline: %d\noffset: %d." ),
314 CurSource(), CurLineNumber(), CurOffset() );
315 }
316
317 NeedRIGHT();
318 return;
319 }
320
321 if( !IsSymbol( token ) )
322 {
323 Expecting( "net name" );
324 return;
325 }
326
327 if( m_board )
328 {
329 wxString netName( FromUTF8() );
330
331 // Convert overbar syntax from `~...~` to `~{...}`. These were left out of the
332 // first merge so the version is a bit later.
333 if( m_requiredVersion < 20210606 )
334 netName = ConvertToNewOverbarNotation( netName );
335
336 NETINFO_ITEM* netinfo = m_board->FindNet( netName );
337
338 if( !netinfo )
339 {
340 netinfo = new NETINFO_ITEM( m_board, netName );
341 m_board->Add( netinfo, ADD_MODE::INSERT, true );
342 }
343
344 aItem->SetNet( netinfo );
345 }
346
347 NeedRIGHT();
348}
349
350
352{
353 int year, month, day;
354
355 year = m_requiredVersion / 10000;
356 month = ( m_requiredVersion / 100 ) - ( year * 100 );
357 day = m_requiredVersion - ( year * 10000 ) - ( month * 100 );
358
359 // wx throws an assertion, not a catchable exception, when the date is invalid.
360 // User input shouldn't give wx asserts, so check manually and throw a proper
361 // error instead
362 if( day <= 0 || month <= 0 || month > 12 ||
363 day > wxDateTime::GetNumberOfDays( (wxDateTime::Month)( month - 1 ), year ) )
364 {
365 wxString err;
366 err.Printf( _( "Cannot interpret date code %d" ), m_requiredVersion );
367 THROW_PARSE_ERROR( err, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
368 }
369
370 wxDateTime date( day, (wxDateTime::Month)( month - 1 ), year, 0, 0, 0, 0 );
371 return date.FormatDate();
372}
373
374
376{
377 if( CurTok() != T_LEFT )
378 NeedLEFT();
379
380 VECTOR2I pt;
381 T token = NextTok();
382
383 if( token != T_xy )
384 Expecting( T_xy );
385
386 pt.x = parseBoardUnits( "X coordinate" );
387 pt.y = parseBoardUnits( "Y coordinate" );
388
389 NeedRIGHT();
390
391 return pt;
392}
393
394
396{
397 if( CurTok() != T_LEFT )
398 NeedLEFT();
399
400 T token = NextTok();
401
402 switch( token )
403 {
404 case T_xy:
405 {
406 int x = parseBoardUnits( "X coordinate" );
407 int y = parseBoardUnits( "Y coordinate" );
408
409 NeedRIGHT();
410
411 aPoly.Append( x, y );
412 break;
413 }
414 case T_arc:
415 {
416 bool has_start = false;
417 bool has_mid = false;
418 bool has_end = false;
419
420 VECTOR2I arc_start, arc_mid, arc_end;
421
422 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
423 {
424 if( token != T_LEFT )
425 Expecting( T_LEFT );
426
427 token = NextTok();
428
429 switch( token )
430 {
431 case T_start:
432 arc_start.x = parseBoardUnits( "start x" );
433 arc_start.y = parseBoardUnits( "start y" );
434 has_start = true;
435 break;
436
437 case T_mid:
438 arc_mid.x = parseBoardUnits( "mid x" );
439 arc_mid.y = parseBoardUnits( "mid y" );
440 has_mid = true;
441 break;
442
443 case T_end:
444 arc_end.x = parseBoardUnits( "end x" );
445 arc_end.y = parseBoardUnits( "end y" );
446 has_end = true;
447 break;
448
449 default:
450 Expecting( "start, mid or end" );
451 }
452
453 NeedRIGHT();
454 }
455
456 if( !has_start )
457 Expecting( "start" );
458
459 if( !has_mid )
460 Expecting( "mid" );
461
462 if( !has_end )
463 Expecting( "end" );
464
465 SHAPE_ARC arc( arc_start, arc_mid, arc_end, 0 );
466
467 aPoly.Append( arc );
468
469 if( token != T_RIGHT )
470 Expecting( T_RIGHT );
471
472 break;
473 }
474 default:
475 Expecting( "xy or arc" );
476 }
477}
478
479
481{
482 VECTOR2I pt = parseXY();
483
484 if( aX )
485 *aX = pt.x;
486
487 if( aY )
488 *aY = pt.y;
489}
490
491
492void PCB_IO_KICAD_SEXPR_PARSER::parseMargins( int& aLeft, int& aTop, int& aRight, int& aBottom )
493{
494 aLeft = parseBoardUnits( "left margin" );
495 aTop = parseBoardUnits( "top margin" );
496 aRight = parseBoardUnits( "right margin" );
497 aBottom = parseBoardUnits( "bottom margin" );
498}
499
500
502{
503 wxString pName;
504 wxString pValue;
505
506 NeedSYMBOL();
507 pName = FromUTF8();
508 NeedSYMBOL();
509 pValue = FromUTF8();
510 NeedRIGHT();
511
512 return { pName, pValue };
513}
514
515
517{
518 NeedSYMBOL();
519 wxString key = FromUTF8();
520 NeedSYMBOL();
521 wxString value = FromUTF8();
522 aItem->SetCustomProperty( key, value );
523 NeedRIGHT();
524}
525
526
527void PCB_IO_KICAD_SEXPR_PARSER::parseCustomProperty( std::map<wxString, wxString>& aProps )
528{
529 NeedSYMBOL();
530 wxString key = FromUTF8();
531 NeedSYMBOL();
532 wxString value = FromUTF8();
533 aProps[key] = value;
534 NeedRIGHT();
535}
536
537
539{
540 // (variants
541 // (variant (name "VariantA") (description "Description A"))
542 // (variant (name "VariantB") (description "Description B"))
543 // )
544 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
545 {
546 if( token == T_LEFT )
547 token = NextTok();
548
549 if( token == T_variant )
550 {
551 wxString variantName;
552 wxString description;
553
554 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
555 {
556 if( token == T_LEFT )
557 token = NextTok();
558
559 switch( token )
560 {
561 case T_name:
562 NeedSYMBOL();
563 variantName = FromUTF8();
564 NeedRIGHT();
565 break;
566
567 case T_description:
568 NeedSYMBOL();
569 description = FromUTF8();
570 NeedRIGHT();
571 break;
572
573 default:
574 Expecting( "name or description" );
575 }
576 }
577
578 if( !variantName.IsEmpty() )
579 {
580 m_board->AddVariant( variantName );
581
582 if( !description.IsEmpty() )
583 m_board->SetVariantDescription( variantName, description );
584 }
585 }
586 else
587 {
588 Expecting( T_variant );
589 }
590 }
591}
592
593
595{
596 // (variant (name "VariantA") (dnp yes) (exclude_from_bom yes) (exclude_from_sim yes)
597 // (exclude_from_pos_files yes)
598 // (field (name "Value") (value "100nF")))
599 wxString variantName;
600 bool hasDnp = false;
601 bool dnp = false;
602 bool hasExcludeFromBOM = false;
603 bool excludeFromBOM = false;
604 bool hasExcludeFromSim = false;
605 bool excludeFromSim = false;
606 bool hasExcludeFromPosFiles = false;
607 bool excludeFromPosFiles = false;
608 std::vector<std::pair<wxString, wxString>> fields;
609
610 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
611 {
612 if( token == T_LEFT )
613 token = NextTok();
614
615 switch( token )
616 {
617 case T_name:
618 NeedSYMBOL();
619 variantName = FromUTF8();
620 NeedRIGHT();
621 break;
622
623 case T_dnp:
624 dnp = parseMaybeAbsentBool( true );
625 hasDnp = true;
626 break;
627
628 case T_exclude_from_bom:
629 excludeFromBOM = parseMaybeAbsentBool( true );
630 hasExcludeFromBOM = true;
631 break;
632
633 case T_exclude_from_sim:
634 excludeFromSim = parseMaybeAbsentBool( true );
635 hasExcludeFromSim = true;
636 break;
637
638 case T_exclude_from_pos_files:
639 excludeFromPosFiles = parseMaybeAbsentBool( true );
640 hasExcludeFromPosFiles = true;
641 break;
642
643 case T_field:
644 {
645 wxString fieldName;
646 wxString fieldValue;
647
648 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
649 {
650 if( token == T_LEFT )
651 token = NextTok();
652
653 if( token == T_name )
654 {
655 NeedSYMBOL();
656 fieldName = FromUTF8();
657 NeedRIGHT();
658 }
659 else if( token == T_value )
660 {
661 NeedSYMBOL();
662 fieldValue = FromUTF8();
663 NeedRIGHT();
664 }
665 else
666 {
667 Expecting( "name or value" );
668 }
669 }
670
671 if( !fieldName.IsEmpty() )
672 fields.emplace_back( fieldName, fieldValue );
673
674 break;
675 }
676
677 default:
678 Expecting( "name, dnp, exclude_from_bom, exclude_from_sim, exclude_from_pos_files, or field" );
679 }
680 }
681
682 if( variantName.IsEmpty() )
683 return;
684
685 FOOTPRINT_VARIANT* variant = aFootprint->AddVariant( variantName );
686
687 if( !variant )
688 return;
689
690 if( hasDnp )
691 variant->SetDNP( dnp );
692
693 if( hasExcludeFromBOM )
694 variant->SetExcludedFromBOM( excludeFromBOM );
695
696 if( hasExcludeFromSim )
697 variant->SetExcludedFromSim( excludeFromSim );
698
699 if( hasExcludeFromPosFiles )
700 variant->SetExcludedFromPosFiles( excludeFromPosFiles );
701
702 for( const auto& [fieldName, fieldValue] : fields )
703 variant->SetFieldValue( fieldName, fieldValue );
704}
705
706
708{
709 tdParams->m_Enabled = false;
710 tdParams->m_AllowUseTwoTracks = false;
711 tdParams->m_TdOnPadsInZones = true;
712
713 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
714 {
715 if( token == T_LEFT )
716 token = NextTok();
717
718 switch( token )
719 {
720 case T_enabled:
721 tdParams->m_Enabled = parseMaybeAbsentBool( true );
722 break;
723
724 case T_allow_two_segments:
725 tdParams->m_AllowUseTwoTracks = parseMaybeAbsentBool( true );
726 break;
727
728 case T_prefer_zone_connections:
729 tdParams->m_TdOnPadsInZones = !parseMaybeAbsentBool( false );
730 break;
731
732 case T_best_length_ratio:
733 tdParams->m_BestLengthRatio = parseDouble( "teardrop best length ratio" );
734 NeedRIGHT();
735 break;
736
737 case T_max_length:
738 tdParams->m_TdMaxLen = parseBoardUnits( "teardrop max length" );
739 NeedRIGHT();
740 break;
741
742 case T_best_width_ratio:
743 tdParams->m_BestWidthRatio = parseDouble( "teardrop best width ratio" );
744 NeedRIGHT();
745 break;
746
747 case T_max_width:
748 tdParams->m_TdMaxWidth = parseBoardUnits( "teardrop max width" );
749 NeedRIGHT();
750 break;
751
752 // Legacy token
753 case T_curve_points:
754 tdParams->m_CurvedEdges = parseInt( "teardrop curve points count" ) > 0;
755 NeedRIGHT();
756 break;
757
758 case T_curved_edges:
759 tdParams->m_CurvedEdges = parseMaybeAbsentBool( true );
760 break;
761
762 case T_filter_ratio:
763 tdParams->m_WidthtoSizeFilterRatio = parseDouble( "teardrop filter ratio" );
764 NeedRIGHT();
765 break;
766
767 default:
768 Expecting( "enabled, allow_two_segments, prefer_zone_connections, best_length_ratio, "
769 "max_length, best_width_ratio, max_width, curve_points or filter_ratio" );
770 }
771 }
772}
773
774
776{
777 wxCHECK_RET( CurTok() == T_effects,
778 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as EDA_TEXT." ) );
779
780 // These are not written out if center/center and/or no mirror,
781 // so we have to make sure we start that way.
782 // (these parameters will be set in T_justify section, when existing)
785 aText->SetMirrored( false );
786
787 // In version 20210606 the notation for overbars was changed from `~...~` to `~{...}`.
788 // We need to convert the old syntax to the new one.
789 if( m_requiredVersion < 20210606 )
790 aText->SetText( ConvertToNewOverbarNotation( aText->GetText() ) );
791
792 T token;
793
794 // Prior to v5.0 text size was omitted from file format if equal to 60mils
795 // Now, it is always explicitly written to file
796 bool foundTextSize = false;
797
798 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
799 {
800 if( token == T_LEFT )
801 token = NextTok();
802
803 switch( token )
804 {
805 case T_font:
806 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
807 {
808 if( token == T_LEFT )
809 continue;
810
811 switch( token )
812 {
813 case T_face:
814 NeedSYMBOL();
815 aText->SetUnresolvedFontName( FromUTF8() );
816 NeedRIGHT();
817 break;
818
819 case T_size:
820 {
821 VECTOR2I sz;
822 sz.y = parseBoardUnits( "text height" );
823 sz.x = parseBoardUnits( "text width" );
824 aText->SetTextSize( sz );
825 NeedRIGHT();
826
827 foundTextSize = true;
828 break;
829 }
830
831 case T_line_spacing:
832 aText->SetLineSpacing( parseDouble( "line spacing" ) );
833 NeedRIGHT();
834 break;
835
836 case T_thickness:
837 aText->SetTextThickness( parseBoardUnits( "text thickness" ) );
838 NeedRIGHT();
839 break;
840
841 case T_bold:
842 aText->SetBoldFlag( parseMaybeAbsentBool( true ) );
843 break;
844
845 case T_italic:
846 aText->SetItalicFlag( parseMaybeAbsentBool( true ) );
847 break;
848
849 default:
850 Expecting( "face, size, line_spacing, thickness, bold, or italic" );
851 }
852 }
853
854 break;
855
856 case T_justify:
857 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
858 {
859 if( token == T_LEFT )
860 continue;
861
862 switch( token )
863 {
864 case T_left: aText->SetHorizJustify( GR_TEXT_H_ALIGN_LEFT ); break;
865 case T_right: aText->SetHorizJustify( GR_TEXT_H_ALIGN_RIGHT ); break;
866 case T_top: aText->SetVertJustify( GR_TEXT_V_ALIGN_TOP ); break;
867 case T_bottom: aText->SetVertJustify( GR_TEXT_V_ALIGN_BOTTOM ); break;
868 case T_mirror: aText->SetMirrored( true ); break;
869 default: Expecting( "left, right, top, bottom, or mirror" );
870 }
871
872 }
873
874 break;
875
876 case T_hide:
877 {
878 // In older files, the hide token appears bare, and indicates hide==true.
879 // In newer files, it will be an explicit bool in a list like (hide yes)
880 bool hide = parseMaybeAbsentBool( true );
881 aText->SetVisible( !hide );
882 break;
883 }
884
885 default:
886 Expecting( "font, justify, or hide" );
887 }
888 }
889
890 // Text size was not specified in file, force legacy default units
891 // 60mils is 1.524mm
892 if( !foundTextSize )
893 {
894 const double defaultTextSize = 1.524 * pcbIUScale.IU_PER_MM;
895
896 aText->SetTextSize( VECTOR2I( defaultTextSize, defaultTextSize ) );
897 }
898
899 if( m_requiredVersion < 20260826 )
901}
902
903
905{
906 T token;
907
908 NeedSYMBOLorNUMBER();
909 wxString cacheText = From_UTF8( CurText() );
910 EDA_ANGLE cacheAngle( parseDouble( "render cache angle" ), DEGREES_T );
911
912 text->SetupRenderCache( cacheText, text->GetFont(), cacheAngle, { 0, 0 } );
913
914 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
915 {
916 if( token != T_LEFT )
917 Expecting( T_LEFT );
918
919 token = NextTok();
920
921 if( token != T_polygon )
922 Expecting( T_polygon );
923
924 SHAPE_POLY_SET poly;
925
926 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
927 {
928 if( token != T_LEFT )
929 Expecting( T_LEFT );
930
931 token = NextTok();
932
933 if( token != T_pts )
934 Expecting( T_pts );
935
936 SHAPE_LINE_CHAIN lineChain;
937
938 while( (token = NextTok() ) != T_RIGHT )
939 parseOutlinePoints( lineChain );
940
941 lineChain.SetClosed( true );
942
943 if( poly.OutlineCount() == 0 )
944 poly.AddOutline( lineChain );
945 else
946 poly.AddHole( lineChain );
947 }
948
949 text->AddRenderCacheGlyph( poly );
950 }
951}
952
953
955{
956 if( !aFileNameAlreadyParsed )
957 {
958 wxCHECK_MSG( CurTok() == T_model, nullptr,
959 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as FP_3DMODEL." ) );
960
961 NeedSYMBOLorNUMBER();
962 }
963
964 T token;
965
966 FP_3DMODEL* n3D = new FP_3DMODEL;
967 n3D->m_Filename = FromUTF8();
968
969 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
970 {
971 if( token == T_LEFT )
972 token = NextTok();
973
974 switch( token )
975 {
976 case T_at:
977 NeedLEFT();
978 token = NextTok();
979
980 if( token != T_xyz )
981 Expecting( T_xyz );
982
983 /* Note:
984 * Prior to KiCad v5, model offset was designated by "at",
985 * and the units were in inches.
986 * Now we use mm, but support reading of legacy files
987 */
988
989 n3D->m_Offset.x = parseDouble( "x value" ) * 25.4f;
990 n3D->m_Offset.y = parseDouble( "y value" ) * 25.4f;
991 n3D->m_Offset.z = parseDouble( "z value" ) * 25.4f;
992
993 NeedRIGHT(); // xyz
994 NeedRIGHT(); // at
995 break;
996
997 case T_hide:
998 {
999 // In older files, the hide token appears bare, and indicates hide==true.
1000 // In newer files, it will be an explicit bool in a list like (hide yes)
1001 bool hide = parseMaybeAbsentBool( true );
1002 n3D->m_Show = !hide;
1003 break;
1004 }
1005
1006 case T_opacity:
1007 n3D->m_Opacity = parseDouble( "opacity value" );
1008 NeedRIGHT();
1009 break;
1010
1011 case T_offset:
1012 NeedLEFT();
1013 token = NextTok();
1014
1015 if( token != T_xyz )
1016 Expecting( T_xyz );
1017
1018 /*
1019 * 3D model offset is in mm
1020 */
1021 n3D->m_Offset.x = parseDouble( "x value" );
1022 n3D->m_Offset.y = parseDouble( "y value" );
1023 n3D->m_Offset.z = parseDouble( "z value" );
1024
1025 NeedRIGHT(); // xyz
1026 NeedRIGHT(); // offset
1027 break;
1028
1029 case T_scale:
1030 NeedLEFT();
1031 token = NextTok();
1032
1033 if( token != T_xyz )
1034 Expecting( T_xyz );
1035
1036 n3D->m_Scale.x = parseDouble( "x value" );
1037 n3D->m_Scale.y = parseDouble( "y value" );
1038 n3D->m_Scale.z = parseDouble( "z value" );
1039
1040 NeedRIGHT(); // xyz
1041 NeedRIGHT(); // scale
1042 break;
1043
1044 case T_rotate:
1045 NeedLEFT();
1046 token = NextTok();
1047
1048 if( token != T_xyz )
1049 Expecting( T_xyz );
1050
1051 n3D->m_Rotation.x = parseDouble( "x value" );
1052 n3D->m_Rotation.y = parseDouble( "y value" );
1053 n3D->m_Rotation.z = parseDouble( "z value" );
1054
1055 NeedRIGHT(); // xyz
1056 NeedRIGHT(); // rotate
1057 break;
1058
1059 default:
1060 Expecting( "at, hide, opacity, offset, scale, or rotate" );
1061 }
1062
1063 }
1064
1065 return n3D;
1066}
1067
1068
1070{
1071 m_groupInfos.clear();
1072 m_constraintInfos.clear();
1073
1074 // See Parse() - FOOTPRINTS can be prefixed with an initial block of single line comments,
1075 // eventually BOARD might be the same
1076 ReadCommentLines();
1077
1078 if( CurTok() != T_LEFT )
1079 return false;
1080
1081 if( NextTok() != T_kicad_pcb)
1082 return false;
1083
1084 return true;
1085}
1086
1087
1089{
1090 T token;
1091 BOARD_ITEM* item;
1092
1093 m_groupInfos.clear();
1094 m_constraintInfos.clear();
1095
1096 // FOOTPRINTS can be prefixed with an initial block of single line comments and these are
1097 // kept for Format() so they round trip in s-expression form. BOARDs might eventually do
1098 // the same, but currently do not.
1099 std::unique_ptr<wxArrayString> initial_comments( ReadCommentLines() );
1100
1101 token = CurTok();
1102
1103 if( token == -1 ) // EOF
1104 Unexpected( token );
1105
1106 if( token != T_LEFT )
1107 Expecting( T_LEFT );
1108
1109 switch( NextTok() )
1110 {
1111 case T_kicad_pcb:
1112 if( m_board == nullptr )
1113 m_board = new BOARD();
1114
1115 item = parseBOARD();
1116 break;
1117
1118 case T_module: // legacy token
1119 case T_footprint:
1120 item = parseFOOTPRINT( initial_comments.release() );
1121
1122 // Locking a footprint has no meaning outside of a board.
1123 item->SetLocked( false );
1124 break;
1125
1126 default:
1127 wxString err;
1128 err.Printf( _( "Unknown token '%s'" ), FromUTF8() );
1129 THROW_PARSE_ERROR( err, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
1130 }
1131
1132 finishItem( item );
1133
1134 return item;
1135}
1136
1137
1139{
1140 const std::vector<wxString>* embeddedFonts = aItem->GetEmbeddedFiles()->UpdateFontFiles();
1141
1142 aItem->RunOnChildren(
1143 [&]( BOARD_ITEM* aChild )
1144 {
1145 if( EDA_TEXT* textItem = dynamic_cast<EDA_TEXT*>( aChild ) )
1146 textItem->ResolveFont( embeddedFonts );
1147 },
1149
1150 resolveGroups( aItem );
1151 resolveConstraints( aItem );
1152
1153 // The next footprint in a file must not resolve against these
1154 m_groupInfos.clear();
1155 m_generatorInfos.clear();
1156 m_constraintInfos.clear();
1157}
1158
1159
1161 boost::ptr_map<wxString, FP_CACHE_ENTRY, std::less<wxString>,
1162 boost::heap_clone_allocator,
1163 std::allocator<std::pair<const wxString, void*>>>& aFootprints )
1164{
1165 T token;
1166
1167 std::unique_ptr<wxArrayString> initial_comments( ReadCommentLines() );
1168
1169 auto parseFp = [&]()
1170 {
1171 std::unique_ptr<FOOTPRINT> footprint( parseFOOTPRINT( initial_comments.release() ) );
1172
1173 if( footprint )
1174 {
1175 wxString fpName = footprint->GetFPID().GetLibItemName();
1176 footprint->SetFPID( LIB_ID( wxEmptyString, fpName ) );
1177
1178 // Locking a footprint has no meaning outside of a board
1179 footprint->SetLocked( false );
1180 footprint->SetFileFormatVersionAtLoad( m_requiredVersion );
1181
1182 finishItem( footprint.get() );
1183
1184 WX_FILENAME fn( wxEmptyString, fpName );
1185 aFootprints.insert( fpName, new FP_CACHE_ENTRY( footprint.release(), fn ) );
1186 }
1187 };
1188
1189 for( token = CurTok(); token != T_RIGHT; token = NextTok() )
1190 {
1191 if( token != T_LEFT )
1192 Expecting( T_LEFT );
1193
1194 token = NextTok();
1195
1196 switch( token )
1197 {
1198 case T_module: // legacy token
1199 case T_footprint: // This is a footprint file prior to the header addition.
1200 parseFp(); // There is only a single footprint so the closing ')' has already been parsed.
1201 return;
1202
1203 case T_kicad_footprint_lib:
1204 {
1205 bool hasVersion = false;
1206
1207 // Version gates in the footprint parser need this before they run
1208 auto checkVersion =
1209 [&]()
1210 {
1211 if( !hasVersion )
1212 Expecting( "version" );
1213
1214 if( m_tooRecent )
1215 throw FUTURE_FORMAT_ERROR( fmt::format( "{}", m_requiredVersion ), m_generatorVersion );
1216 };
1217
1218 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
1219 {
1220 if( token != T_LEFT )
1221 Expecting( T_LEFT );
1222
1223 token = NextTok();
1224
1225 switch( token )
1226 {
1227 case T_version:
1228 {
1229 if( hasVersion )
1230 Unexpected( token );
1231
1232 hasVersion = true;
1233
1234 int versionNumber = parseInt( "version" );
1235
1236 m_requiredVersion = versionNumber;
1237 m_tooRecent = ( versionNumber > SEXPR_FOOTPRINT_LIB_FILE_VERSION );
1238 SetKnowsBar( m_requiredVersion >= 20240706 ); // Bar token is known from this version
1239 NeedRIGHT();
1240 break;
1241 }
1242
1243 case T_generator:
1244 NeedSYMBOL();
1245 NeedRIGHT();
1246 break;
1247
1248 case T_generator_version:
1249 NeedSYMBOL();
1250 m_generatorVersion = FromUTF8();
1251 NeedRIGHT();
1252 break;
1253
1254 case T_footprint:
1255 checkVersion();
1256 parseFp();
1257 break;
1258
1259 default:
1260 checkVersion();
1261 Expecting( "footprint, generator, generator_version, or version" );
1262 }
1263 }
1264
1265 checkVersion();
1266
1267 return;
1268 }
1269
1270 default:
1271 Expecting( "footprint or kicad_footprint_lib" );
1272 }
1273 }
1274}
1275
1276
1278{
1279 try
1280 {
1281 return parseBOARD_unchecked();
1282 }
1283 catch( const PARSE_ERROR& parse_error )
1284 {
1285 if( m_tooRecent )
1286 throw FUTURE_FORMAT_ERROR( parse_error, GetRequiredVersion() );
1287 else
1288 throw;
1289 }
1290}
1291
1292
1294{
1295 T token;
1296 std::map<wxString, wxString> properties;
1297
1298 parseHeader();
1299
1300 auto checkVersion =
1301 [&]()
1302 {
1304 {
1305 throw FUTURE_FORMAT_ERROR( fmt::format( "{}", m_requiredVersion ),
1307 }
1308 };
1309
1310 std::vector<BOARD_ITEM*> bulkAddedItems;
1311 BOARD_ITEM* item = nullptr;
1312
1313 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
1314 {
1315 checkpoint();
1316
1317 if( token != T_LEFT )
1318 Expecting( T_LEFT );
1319
1320 token = NextTok();
1321
1322 if( token == T_page && m_requiredVersion <= 20200119 )
1323 token = T_paper;
1324
1325 switch( token )
1326 {
1327 case T_host: // legacy token
1328 NeedSYMBOL();
1329 m_board->SetGenerator( FromUTF8() );
1330
1331 // Older formats included build data
1333 NeedSYMBOL();
1334
1335 NeedRIGHT();
1336 break;
1337
1338 case T_generator:
1339 NeedSYMBOL();
1340 m_board->SetGenerator( FromUTF8() );
1341 NeedRIGHT();
1342 break;
1343
1344 case T_generator_version:
1345 {
1346 NeedSYMBOL();
1347 m_generatorVersion = FromUTF8();
1348 NeedRIGHT();
1349
1350 // If the format includes a generator version, by this point we have enough info to
1351 // do the version check here
1352 checkVersion();
1353
1354 break;
1355 }
1356
1357 case T_general:
1358 // Do another version check here, for older files that do not include generator_version
1359 checkVersion();
1360
1362 break;
1363
1364 case T_paper:
1366 break;
1367
1368 case T_title_block:
1370 break;
1371
1372 case T_layers:
1373 parseLayers();
1374 break;
1375
1376 case T_setup:
1377 parseSetup();
1378 break;
1379
1380 case T_property:
1381 properties.insert( parseBoardProperty() );
1382 break;
1383
1384 case T_variants:
1385 parseVariants();
1386 break;
1387
1388 case T_net:
1390 break;
1391
1392 case T_net_chains:
1394 break;
1395
1396 case T_net_class:
1397 parseNETCLASS();
1398 m_board->m_LegacyNetclassesLoaded = true;
1399 break;
1400
1401 case T_gr_arc:
1402 case T_gr_curve:
1403 case T_gr_line:
1404 case T_gr_poly:
1405 case T_gr_circle:
1406 case T_gr_rect:
1407 case T_gr_ellipse:
1408 case T_gr_ellipse_arc:
1409 item = parsePCB_SHAPE( m_board );
1410 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1411 bulkAddedItems.push_back( item );
1412 break;
1413
1414 case T_image:
1416 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1417 bulkAddedItems.push_back( item );
1418 break;
1419
1420 case T_barcode:
1421 item = parsePCB_BARCODE( m_board );
1422 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1423 bulkAddedItems.push_back( item );
1424 break;
1425
1426 case T_gr_text:
1427 item = parsePCB_TEXT( m_board );
1428 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1429 bulkAddedItems.push_back( item );
1430 break;
1431
1432 case T_gr_text_box:
1433 item = parsePCB_TEXTBOX( m_board );
1434 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1435 bulkAddedItems.push_back( item );
1436 break;
1437
1438 case T_drill_chart:
1439 item = parseGeneratedTable( std::make_unique<PCB_DRILL_CHART>( m_board ) );
1440 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1441 bulkAddedItems.push_back( item );
1442 break;
1443
1444 case T_stackup_table:
1445 item = parseGeneratedTable( std::make_unique<PCB_STACKUP_TABLE>( m_board ) );
1446 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1447 bulkAddedItems.push_back( item );
1448 break;
1449
1450 case T_drill_map:
1451 item = parsePCB_DRILL_MAP( m_board );
1452 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1453 bulkAddedItems.push_back( item );
1454 break;
1455
1456 case T_table:
1457 item = parsePCB_TABLE( m_board );
1458 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1459 bulkAddedItems.push_back( item );
1460 break;
1461
1462 case T_dimension:
1463 item = parseDIMENSION( m_board );
1464 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1465 bulkAddedItems.push_back( item );
1466 break;
1467
1468 case T_module: // legacy token
1469 case T_footprint:
1470 item = parseFOOTPRINT();
1471 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1472 bulkAddedItems.push_back( item );
1473 break;
1474
1475 case T_segment:
1476 if( PCB_TRACK* track = parsePCB_TRACK() )
1477 {
1478 m_board->Add( track, ADD_MODE::BULK_APPEND, true );
1479 bulkAddedItems.push_back( track );
1480 }
1481
1482 break;
1483
1484 case T_arc:
1485 if( PCB_TRACK* arc = parseARC() )
1486 {
1487 m_board->Add( arc, ADD_MODE::BULK_APPEND, true );
1488 bulkAddedItems.push_back( arc );
1489 }
1490
1491 break;
1492
1493 case T_group:
1495 break;
1496
1497 case T_constraint:
1499 break;
1500
1501 case T_generated:
1503 break;
1504
1505 case T_via:
1506 item = parsePCB_VIA();
1507 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1508 bulkAddedItems.push_back( item );
1509 break;
1510
1511 case T_zone:
1512 {
1513 ZONE* zone = parseZONE( m_board );
1514
1515 if( zone->GetNumCorners() == 0 )
1516 {
1517 // Zones with no outline vertices are degenerate and can cause crashes
1518 // elsewhere. Silently discard them.
1519 delete zone;
1520 break;
1521 }
1522
1523 item = zone;
1524 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1525 bulkAddedItems.push_back( item );
1526 break;
1527 }
1528
1529 case T_target:
1530 item = parsePCB_TARGET();
1531 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1532 bulkAddedItems.push_back( item );
1533 break;
1534
1535 case T_point:
1536 item = parsePCB_POINT();
1537 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1538 bulkAddedItems.push_back( item );
1539 break;
1540
1541 case T_grid_item:
1542 item = parsePCB_GRID_ITEM();
1543 m_board->Add( item, ADD_MODE::BULK_APPEND, true );
1544 bulkAddedItems.push_back( item );
1545 break;
1546
1547 case T_embedded_fonts:
1548 {
1549 bool embedFonts = parseBool();
1550
1551 // An append must not clear the destination's flag; saving with it off deletes the
1552 // fonts the destination already embedded
1553 if( m_appendToExisting )
1554 embedFonts = embedFonts || m_board->GetEmbeddedFiles()->GetAreFontsEmbedded();
1555
1556 m_board->GetEmbeddedFiles()->SetAreFontsEmbedded( embedFonts );
1557 NeedRIGHT();
1558 break;
1559 }
1560
1561 case T_embedded_files:
1562 {
1563 EMBEDDED_FILES_PARSER embeddedFilesParser( reader );
1564 embeddedFilesParser.SyncLineReaderWith( *this );
1565
1566 try
1567 {
1568 embeddedFilesParser.ParseEmbedded( m_board->GetEmbeddedFiles() );
1569 }
1570 catch( const PARSE_ERROR& e )
1571 {
1572 m_parseWarnings.push_back( e.What() );
1573
1574 // ParseEmbedded may have stopped mid-section. Skip remaining
1575 // tokens so the board parser doesn't see them at the top level.
1576 int depth = 0;
1577
1578 for( int tok = embeddedFilesParser.NextTok();
1579 tok != DSN_EOF;
1580 tok = embeddedFilesParser.NextTok() )
1581 {
1582 if( tok == DSN_LEFT )
1583 depth++;
1584 else if( tok == DSN_RIGHT && --depth < 0 )
1585 break;
1586 }
1587 }
1588
1589 SyncLineReaderWith( embeddedFilesParser );
1590 break;
1591 }
1592
1593 default:
1594 wxString err;
1595 err.Printf( _( "Unknown token '%s'" ), FromUTF8() );
1596 THROW_PARSE_ERROR( err, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
1597 }
1598 }
1599
1600 if( bulkAddedItems.size() > 0 )
1601 m_board->FinalizeBulkAdd( bulkAddedItems );
1602
1603 m_board->SetProperties( properties );
1604
1605 // Re-assemble any barcodes now that board properties (text variables) are available.
1606 // When barcodes are parsed, AssembleBarcode() is called before board properties are set,
1607 // so text variables in human-readable text remain unexpanded. Re-assembling now ensures
1608 // variables like ${PART_NUMBER} are properly expanded in the displayed text.
1609 for( BOARD_ITEM* bc_item : m_board->Drawings() )
1610 {
1611 if( bc_item->Type() == PCB_BARCODE_T )
1612 static_cast<PCB_BARCODE*>( bc_item )->AssembleBarcode();
1613 }
1614
1615 for( FOOTPRINT* fp : m_board->Footprints() )
1616 {
1617 for( BOARD_ITEM* bc_item : fp->GraphicalItems() )
1618 {
1619 if( bc_item->Type() == PCB_BARCODE_T )
1620 static_cast<PCB_BARCODE*>( bc_item )->AssembleBarcode();
1621 }
1622 }
1623
1624 if( m_undefinedLayers.size() > 0 )
1625 {
1626 PCB_LAYER_ID destLayer = Cmts_User;
1627 wxString msg, undefinedLayerNames, destLayerName;
1628
1629 for( const wxString& layerName : m_undefinedLayers )
1630 {
1631 if( !undefinedLayerNames.IsEmpty() )
1632 undefinedLayerNames += wxT( ", " );
1633
1634 undefinedLayerNames += layerName;
1635 }
1636
1637 destLayerName = m_board->GetLayerName( destLayer );
1638
1639 if( Pgm().IsGUI() && m_queryUserCallback )
1640 {
1641 msg.Printf( _( "Items found on undefined layers (%s).\n"
1642 "Do you wish to rescue them to the %s layer?\n"
1643 "\n"
1644 "Zones will need to be refilled." ),
1645 undefinedLayerNames, destLayerName );
1646
1647 if( !m_queryUserCallback( _( "Undefined Layers Warning" ), wxICON_WARNING, msg,
1648 _( "Rescue" ) ) )
1649 {
1651 }
1652
1653 // Make sure the destination layer is enabled, even if not in the file
1654 m_board->SetEnabledLayers( LSET( m_board->GetEnabledLayers() ).set( destLayer ) );
1655
1656 const auto visitItem = [&]( BOARD_ITEM& curr_item )
1657 {
1658 LSET layers = curr_item.GetLayerSet();
1659
1660 if( !layers.test( Rescue ) )
1661 return;
1662
1663 layers.set( destLayer );
1664 layers.reset( Rescue );
1665
1666 // Single-layer items (shapes, text) ignore non-copper layers in SetLayerSet, so
1667 // move them with SetLayer. Multi-layer items keep their full set.
1668 if( layers.count() == 1 )
1669 curr_item.SetLayer( destLayer );
1670 else
1671 curr_item.SetLayerSet( layers );
1672 };
1673
1674 for( PCB_TRACK* track : m_board->Tracks() )
1675 {
1676 if( track->Type() == PCB_VIA_T )
1677 {
1678 PCB_VIA* via = static_cast<PCB_VIA*>( track );
1679 PCB_LAYER_ID top_layer, bottom_layer;
1680
1681 if( via->GetViaType() == VIATYPE::THROUGH )
1682 continue;
1683
1684 via->LayerPair( &top_layer, &bottom_layer );
1685
1686 if( top_layer == Rescue || bottom_layer == Rescue )
1687 {
1688 if( top_layer == Rescue )
1689 top_layer = F_Cu;
1690
1691 if( bottom_layer == Rescue )
1692 bottom_layer = B_Cu;
1693
1694 via->SetLayerPair( top_layer, bottom_layer );
1695 }
1696 }
1697 else
1698 {
1699 visitItem( *track );
1700 }
1701 }
1702
1703 for( BOARD_ITEM* zone : m_board->Zones() )
1704 visitItem( *zone );
1705
1706 for( BOARD_ITEM* drawing : m_board->Drawings() )
1707 visitItem( *drawing );
1708
1709 for( FOOTPRINT* fp : m_board->Footprints() )
1710 {
1711 for( BOARD_ITEM* drawing : fp->GraphicalItems() )
1712 visitItem( *drawing );
1713
1714 for( BOARD_ITEM* zone : fp->Zones() )
1715 visitItem( *zone );
1716
1717 for( PCB_FIELD* field : fp->GetFields() )
1718 visitItem( *field );
1719 }
1720
1721 m_undefinedLayers.clear();
1722
1723 // Rescued items make the board differ from disk. Mark modified so it gets re-saved.
1724 m_board->SetModified();
1725 }
1726 else
1727 {
1728 THROW_IO_ERRORF( _( "One or more items were found on undefined layers (%s). Open the board in the "
1729 "PCB Editor to resolve." ),
1730 undefinedLayerNames );
1731 }
1732 }
1733
1734 // Clear unused zone data
1735 {
1736 LSET layers = m_board->GetEnabledLayers();
1737
1738 for( BOARD_ITEM* zone : m_board->Zones() )
1739 {
1740 ZONE* z = static_cast<ZONE*>( zone );
1741
1742 z->SetLayerSetAndRemoveUnusedFills( z->GetLayerSet() & layers );
1743 }
1744 }
1745
1746 // Appended items get fresh UUIDs, so remap the links read in this parse and leave existing zones alone
1747 // A link set is no item, so appended copies of one set get a set of their own
1748 std::map<KIID, KIID> appendedSets;
1749
1750 for( ZONE* z : m_board->Zones() )
1751 {
1752 if( !m_linkedZones.contains( z->m_Uuid ) )
1753 continue;
1754
1755 if( m_appendToExisting && z->GetLinkSet() != niluuid )
1756 z->SetLinkSet( appendedSets.try_emplace( z->GetLinkSet(), KIID() ).first->second );
1757
1758 REPEAT_LAYOUT_OPTIONS opts = z->GetRepeatOptions();
1759
1760 if( auto it = m_resetKIIDMap.find( opts.m_anchor.AsString() ); it != m_resetKIIDMap.end() )
1761 {
1762 opts.m_anchor = it->second;
1763 z->SetRepeatOptions( opts );
1764 }
1765 }
1766
1767 // Ensure all footprints have their embedded data from the board
1768 m_board->FixupEmbeddedData();
1769
1770 for( NETINFO_ITEM* net : m_board->GetNetInfo() )
1771 {
1772 // Remap terminal pad UUIDs through reset map if needed before resolving
1773 for( int i = 0; i < 2; ++i )
1774 {
1775 const KIID& original = net->GetTerminalPadUuid( i );
1776 if( original != niluuid )
1777 {
1778 auto it = m_resetKIIDMap.find( original.AsString() );
1779 if( it != m_resetKIIDMap.end() )
1780 {
1781 // Replace with canonical UUID after reset
1782 net->SetTerminalPadUuid( i, it->second );
1783 }
1784 }
1785 }
1786
1787 net->ResolveTerminalPads( m_board );
1788 }
1789
1790 // Pads and vias read this from ViewGetLayers(), so a loaded map draws nothing until it
1791 // is populated
1792 m_board->RefreshDrillSymbolLayers();
1793
1794 return m_board;
1795}
1796
1797
1799{
1800 BOARD* board = dynamic_cast<BOARD*>( aParent );
1801 FOOTPRINT* footprint = board ? nullptr : dynamic_cast<FOOTPRINT*>( aParent );
1802
1803 // For footprint parents, build a one-time lookup map instead of scanning children
1804 // on every call. For board parents, resolve using BOARD::ResolveItem(), which
1805 // goes to the board's item index cache and re-binds stale entries.
1806 std::unordered_map<KIID, BOARD_ITEM*> fpItemMap;
1807
1808 if( footprint )
1809 {
1810 footprint->RunOnChildren(
1811 [&]( BOARD_ITEM* child )
1812 {
1813 fpItemMap.insert( { child->m_Uuid, child } );
1814 },
1816 }
1817
1818 auto getItem =
1819 [&]( const KIID& aId ) -> BOARD_ITEM*
1820 {
1821 if( board )
1822 {
1823 return board->ResolveItem( aId, true );
1824 }
1825 else if( footprint )
1826 {
1827 auto it = fpItemMap.find( aId );
1828
1829 return it != fpItemMap.end() ? it->second : nullptr;
1830 }
1831
1832 return nullptr;
1833 };
1834
1835 // Now that we've parsed the other Uuids in the file we can resolve the uuids referred
1836 // to in the group declarations we saw.
1837 //
1838 // First add all group objects so subsequent getItem() calls for nested groups work.
1839
1840 std::vector<GROUP_INFO*> groupTypeObjects;
1841
1842 for( GROUP_INFO& groupInfo : m_groupInfos )
1843 groupTypeObjects.emplace_back( &groupInfo );
1844
1845 for( GENERATOR_INFO& genInfo : m_generatorInfos )
1846 groupTypeObjects.emplace_back( &genInfo );
1847
1848 for( GROUP_INFO* groupInfo : groupTypeObjects )
1849 {
1850 PCB_GROUP* group = nullptr;
1851
1852 if( GENERATOR_INFO* genInfo = dynamic_cast<GENERATOR_INFO*>( groupInfo ) )
1853 {
1855
1856 PCB_GENERATOR* gen;
1857 group = gen = mgr.CreateFromType( genInfo->genType );
1858
1859 if( !gen )
1860 THROW_IO_ERRORF( _( "Cannot create generated object of type '%s'" ), genInfo->genType );
1861
1862 gen->SetLayer( genInfo->layer );
1863 gen->SetProperties( genInfo->properties );
1864
1865 for( auto& [name, item] : genInfo->templates )
1866 gen->SetTemplateItem( name, std::move( item ) );
1867 }
1868 else
1869 {
1870 group = new PCB_GROUP( groupInfo->parent );
1871 group->SetName( groupInfo->name );
1872 }
1873
1874 group->SetUuidDirect( groupInfo->uuid );
1875 group->SetCustomProperties( groupInfo->customProperties );
1876
1877 if( groupInfo->libId.IsValid() )
1878 group->SetDesignBlockLibId( groupInfo->libId );
1879
1880 if( groupInfo->locked )
1881 group->SetLocked( true );
1882
1883 if( groupInfo->parent->Type() == PCB_FOOTPRINT_T )
1884 {
1885 static_cast<FOOTPRINT*>( groupInfo->parent )->Add( group, ADD_MODE::INSERT, true );
1886
1887 // Keep the footprint lookup map in sync with newly added groups
1888 if( footprint )
1889 fpItemMap.insert( { group->m_Uuid, group } );
1890 }
1891 else
1892 {
1893 static_cast<BOARD*>( groupInfo->parent )->Add( group, ADD_MODE::INSERT, true );
1894 }
1895 }
1896
1897 for( GROUP_INFO* groupInfo : groupTypeObjects )
1898 {
1899 if( PCB_GROUP* group = dynamic_cast<PCB_GROUP*>( getItem( groupInfo->uuid ) ) )
1900 {
1901 for( const KIID& aUuid : groupInfo->memberUuids )
1902 {
1903 BOARD_ITEM* item = nullptr;
1904
1905 if( m_appendToExisting )
1906 item = getItem( m_resetKIIDMap[ aUuid.AsString() ] );
1907 else
1908 item = getItem( aUuid );
1909
1910 // We used to allow fp items in non-footprint groups. It was a mistake. Check
1911 // to make sure they the item and group are owned by the same parent (will both
1912 // be nullptr in the board case).
1913 if( item && item->GetParentFootprint() == group->GetParentFootprint() )
1914 group->AddItem( item );
1915 }
1916
1917 // For generators, set the layer to match the layer of the contained tracks.
1918 // GetBoardItems() is unordered, so this may only be done for a generator whose
1919 // members all share one layer; one that spans layers keeps its own.
1920 if( PCB_GENERATOR* gen = dynamic_cast<PCB_GENERATOR*>( group ); gen && gen->LayerFollowsMembers() )
1921 {
1922 for( BOARD_ITEM* item : gen->GetBoardItems() )
1923 {
1924 if( PCB_TRACK* track = dynamic_cast<PCB_TRACK*>( item ) )
1925 {
1926 gen->SetLayer( track->GetLayer() );
1927 break;
1928 }
1929 }
1930 }
1931 }
1932 }
1933
1934 // Don't allow group cycles
1935 if( m_board )
1936 m_board->GroupsSanityCheck( true );
1937}
1938
1939
1941{
1942 wxCHECK_RET( CurTok() == T_kicad_pcb,
1943 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a header." ) );
1944
1945 NeedLEFT();
1946
1947 T tok = NextTok();
1948
1949 if( tok == T_version )
1950 {
1951 m_requiredVersion = parseInt( FromUTF8().mb_str( wxConvUTF8 ) );
1952 NeedRIGHT();
1953 }
1954 else
1955 {
1956 m_requiredVersion = 20201115; // Last version before we started writing version #s
1957 // in footprint files as well as board files.
1958 }
1959
1961
1962 // Prior to this, bar was a valid string char for unquoted strings.
1963 SetKnowsBar( m_requiredVersion >= 20240706 );
1964
1965 m_board->SetFileFormatVersionAtLoad( m_requiredVersion );
1966}
1967
1968
1970{
1971 wxCHECK_RET( CurTok() == T_general,
1972 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a general section." ) );
1973
1974 T token;
1975
1976 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
1977 {
1978 if( token != T_LEFT )
1979 Expecting( T_LEFT );
1980
1981 token = NextTok();
1982
1983 switch( token )
1984 {
1985 case T_thickness:
1986 m_board->GetDesignSettings().SetBoardThickness( parseBoardUnits( T_thickness ) );
1987 NeedRIGHT();
1988 break;
1989
1990 case T_legacy_teardrops:
1991 m_board->SetLegacyTeardrops( parseMaybeAbsentBool( true ) );
1992 break;
1993
1994 default: // Skip everything else.
1995 while( ( token = NextTok() ) != T_RIGHT )
1996 {
1997 if( !IsSymbol( token ) && token != T_NUMBER )
1998 Expecting( "symbol or number" );
1999 }
2000 }
2001 }
2002}
2003
2004
2006{
2007 wxCHECK_RET( ( CurTok() == T_page && m_requiredVersion <= 20200119 ) || CurTok() == T_paper,
2008 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a PAGE_INFO." ) );
2009
2010 T token;
2011 PAGE_INFO pageInfo;
2012
2013 NeedSYMBOL();
2014
2015 wxString pageType = FromUTF8();
2016
2017 if( !pageInfo.SetType( pageType ) )
2018 {
2019 wxString err;
2020 err.Printf( _( "Page type '%s' is not valid." ), FromUTF8() );
2021 THROW_PARSE_ERROR( err, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
2022 }
2023
2024 if( pageInfo.GetType() == PAGE_SIZE_TYPE::User )
2025 {
2026 double width = parseDouble( "width" ); // width in mm
2027
2028 // Perform some controls to avoid crashes if the size is edited by hands
2029 if( width < MIN_PAGE_SIZE_MM )
2030 width = MIN_PAGE_SIZE_MM;
2031 else if( width > MAX_PAGE_SIZE_PCBNEW_MM )
2033
2034 double height = parseDouble( "height" ); // height in mm
2035
2036 if( height < MIN_PAGE_SIZE_MM )
2037 height = MIN_PAGE_SIZE_MM;
2038 else if( height > MAX_PAGE_SIZE_PCBNEW_MM )
2039 height = MAX_PAGE_SIZE_PCBNEW_MM;
2040
2041 pageInfo.SetWidthMM( width );
2042 pageInfo.SetHeightMM( height );
2043 }
2044
2045 token = NextTok();
2046
2047 if( token == T_portrait )
2048 {
2049 pageInfo.SetPortrait( true );
2050 NeedRIGHT();
2051 }
2052 else if( token != T_RIGHT )
2053 {
2054 Expecting( "portrait|)" );
2055 }
2056
2057 m_board->SetPageSettings( pageInfo );
2058}
2059
2060
2062{
2063 wxCHECK_RET( CurTok() == T_title_block,
2064 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as TITLE_BLOCK." ) );
2065
2066 T token;
2067 TITLE_BLOCK titleBlock;
2068
2069 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
2070 {
2071 if( token != T_LEFT )
2072 Expecting( T_LEFT );
2073
2074 token = NextTok();
2075
2076 switch( token )
2077 {
2078 case T_title:
2079 NextTok();
2080 titleBlock.SetTitle( FromUTF8() );
2081 break;
2082
2083 case T_date:
2084 NextTok();
2085 titleBlock.SetDate( FromUTF8() );
2086 break;
2087
2088 case T_rev:
2089 NextTok();
2090 titleBlock.SetRevision( FromUTF8() );
2091 break;
2092
2093 case T_company:
2094 NextTok();
2095 titleBlock.SetCompany( FromUTF8() );
2096 break;
2097
2098 case T_comment:
2099 {
2100 int commentNumber = parseInt( "comment" );
2101
2102 switch( commentNumber )
2103 {
2104 case 1:
2105 NextTok();
2106 titleBlock.SetComment( 0, FromUTF8() );
2107 break;
2108
2109 case 2:
2110 NextTok();
2111 titleBlock.SetComment( 1, FromUTF8() );
2112 break;
2113
2114 case 3:
2115 NextTok();
2116 titleBlock.SetComment( 2, FromUTF8() );
2117 break;
2118
2119 case 4:
2120 NextTok();
2121 titleBlock.SetComment( 3, FromUTF8() );
2122 break;
2123
2124 case 5:
2125 NextTok();
2126 titleBlock.SetComment( 4, FromUTF8() );
2127 break;
2128
2129 case 6:
2130 NextTok();
2131 titleBlock.SetComment( 5, FromUTF8() );
2132 break;
2133
2134 case 7:
2135 NextTok();
2136 titleBlock.SetComment( 6, FromUTF8() );
2137 break;
2138
2139 case 8:
2140 NextTok();
2141 titleBlock.SetComment( 7, FromUTF8() );
2142 break;
2143
2144 case 9:
2145 NextTok();
2146 titleBlock.SetComment( 8, FromUTF8() );
2147 break;
2148
2149 default:
2150 wxString err;
2151 err.Printf( wxT( "%d is not a valid title block comment number" ), commentNumber );
2152 THROW_PARSE_ERROR( err, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
2153 }
2154
2155 break;
2156 }
2157
2158 default:
2159 Expecting( "title, date, rev, company, or comment" );
2160 }
2161
2162 NeedRIGHT();
2163 }
2164
2165 m_board->SetTitleBlock( titleBlock );
2166}
2167
2168
2170{
2171 T token;
2172
2173 std::string name;
2174 std::string userName;
2175 std::string type;
2176 bool isVisible = true;
2177
2178 aLayer->clear();
2179
2180 if( CurTok() != T_LEFT )
2181 Expecting( T_LEFT );
2182
2183 // this layer_num is not used, we DO depend on LAYER_T however.
2184 int layer_num = parseInt( "layer index" );
2185
2186 NeedSYMBOLorNUMBER();
2187 name = CurText();
2188
2189 NeedSYMBOL();
2190 type = CurText();
2191
2192 token = NextTok();
2193
2194 // @todo Figure out why we are looking for a hide token in the layer definition.
2195 if( token == T_hide )
2196 {
2197 isVisible = false;
2198 NeedRIGHT();
2199 }
2200 else if( token == T_STRING )
2201 {
2202 userName = CurText();
2203 NeedRIGHT();
2204 }
2205 else if( token != T_RIGHT )
2206 {
2207 Expecting( "hide, user defined name, or )" );
2208 }
2209
2210 aLayer->m_type = LAYER::ParseType( type.c_str() );
2211 aLayer->m_number = layer_num;
2212 aLayer->m_visible = isVisible;
2213
2214 if( m_requiredVersion >= 20200922 )
2215 {
2216 aLayer->m_userName = From_UTF8( userName.c_str() );
2217 aLayer->m_name = From_UTF8( name.c_str() );
2218 }
2219 else // Older versions didn't have a dedicated user name field
2220 {
2221 aLayer->m_name = aLayer->m_userName = From_UTF8( name.c_str() );
2222 }
2223}
2224
2225
2227{
2228 T token;
2229 wxString name;
2230 int dielectric_idx = 1; // the index of dielectric layers
2231 BOARD_STACKUP& stackup = m_board->GetDesignSettings().GetStackupDescriptor();
2232
2233 // Remove existing stack or we end up just appending to the existing stackup
2234 stackup.RemoveAll();
2235
2236 // Board appends in older versions could duplicate the whole stackup. Stop adding items once
2237 // a board layer id repeats; still parse the duplicates to keep the token stream consistent.
2238 std::set<PCB_LAYER_ID> seenBrdLayers;
2239 bool duplicatedStackup = false;
2240
2241 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
2242 {
2243 if( CurTok() != T_LEFT )
2244 Expecting( T_LEFT );
2245
2246 token = NextTok();
2247
2248 if( token != T_layer )
2249 {
2250 switch( token )
2251 {
2252 case T_copper_finish:
2253 NeedSYMBOL();
2254 stackup.m_FinishType = FromUTF8();
2255 NeedRIGHT();
2256 break;
2257
2258 case T_edge_plating:
2259 token = NextTok();
2260 stackup.m_EdgePlating = token == T_yes;
2261 NeedRIGHT();
2262 break;
2263
2264 case T_dielectric_constraints:
2265 token = NextTok();
2266 stackup.m_HasDielectricConstrains = token == T_yes;
2267 NeedRIGHT();
2268 break;
2269
2270 case T_edge_connector:
2271 token = NextTok();
2273
2274 if( token == T_yes )
2276 else if( token == T_bevelled )
2278
2279 NeedRIGHT();
2280 break;
2281
2282 case T_castellated_pads: // Legacy compatibility. just skip it
2283 token = NextTok();
2284 NeedRIGHT();
2285 break;
2286
2287 default:
2288 // Currently, skip this item if not defined, because the stackup def
2289 // is a moving target
2290 //Expecting( "copper_finish, edge_plating, dielectric_constrains,
2291 // edge_connector, castellated_pads" );
2292 skipCurrent();
2293 break;
2294 }
2295
2296 continue;
2297 }
2298
2299 NeedSYMBOL();
2300 name = FromUTF8();
2301
2302 // Match the canonical names that we write, not GetLayerID() because the user-name matching
2303 // could end up being the same as a canonical name and corrupt the stack.
2304 PCB_LAYER_ID layerId = UNDEFINED_LAYER;
2305
2306 for( PCB_LAYER_ID candidate : LSET::AllLayersMask() )
2307 {
2308 if( LSET::Name( candidate ) == name )
2309 {
2310 layerId = candidate;
2311 break;
2312 }
2313 }
2314
2315 // Init the type
2317
2318 if( layerId == F_SilkS || layerId == B_SilkS )
2320 else if( layerId == F_Mask || layerId == B_Mask )
2322 else if( layerId == F_Paste || layerId == B_Paste )
2324 else if( layerId == UNDEFINED_LAYER )
2326 else if( !( layerId & 1 ) )
2327 type = BS_ITEM_TYPE_COPPER;
2328
2329 std::unique_ptr<BOARD_STACKUP_ITEM> itemOwner;
2330 BOARD_STACKUP_ITEM* item = nullptr;
2331
2332 if( layerId != UNDEFINED_LAYER && !seenBrdLayers.insert( layerId ).second )
2333 duplicatedStackup = true;
2334
2335 if( type != BS_ITEM_TYPE_UNDEFINED )
2336 {
2337 // A 32-copper-layer board has at most 69 stackup items (32 copper +
2338 // 31 dielectric + 6 mask/paste/silk). Anything far beyond that
2339 // indicates a corrupted file. Parse the item so tokens are consumed
2340 // correctly, but don't keep it.
2341 static constexpr int MAX_STACKUP_ITEMS = 128;
2342
2343 itemOwner = std::make_unique<BOARD_STACKUP_ITEM>( type );
2344 item = itemOwner.get();
2345 item->SetBrdLayerId( layerId );
2346
2347 if( type == BS_ITEM_TYPE_DIELECTRIC )
2348 item->SetDielectricLayerId( dielectric_idx++ );
2349
2350 if( !duplicatedStackup && stackup.GetCount() < MAX_STACKUP_ITEMS )
2351 stackup.Add( itemOwner.release() );
2352 }
2353 else
2354 {
2355 Expecting( "layer_name" );
2356 }
2357
2358 bool has_next_sublayer = true;
2359 int sublayer_idx = 0; // the index of dielectric sub layers
2360 // sublayer 0 is always existing (main sublayer)
2361 wxString specFreqUnits;
2362 wxString dielectricModel;
2363
2364 while( has_next_sublayer )
2365 {
2366 has_next_sublayer = false;
2367
2368 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
2369 {
2370 if( token == T_addsublayer )
2371 {
2372 has_next_sublayer = true;
2373 break;
2374 }
2375
2376 if( token == T_LEFT )
2377 {
2378 token = NextTok();
2379
2380 switch( token )
2381 {
2382 case T_type:
2383 NeedSYMBOL();
2384 item->SetTypeName( FromUTF8() );
2385 NeedRIGHT();
2386 break;
2387
2388 case T_thickness:
2389 item->SetThickness( parseBoardUnits( T_thickness ), sublayer_idx );
2390 token = NextTok();
2391
2392 if( token == T_LEFT )
2393 break;
2394
2395 if( token == T_locked )
2396 {
2397 // Dielectric thickness can be locked (for impedance controlled layers)
2398 if( type == BS_ITEM_TYPE_DIELECTRIC )
2399 item->SetThicknessLocked( true, sublayer_idx );
2400
2401 NeedRIGHT();
2402 }
2403
2404 break;
2405
2406 case T_material:
2407 NeedSYMBOL();
2408 item->SetMaterial( FromUTF8(), sublayer_idx );
2409 NeedRIGHT();
2410 break;
2411
2412 case T_epsilon_r:
2413 NextTok();
2414 item->SetEpsilonR( parseDouble(), sublayer_idx );
2415 NeedRIGHT();
2416 break;
2417
2418 case T_loss_tangent:
2419 NextTok();
2420 item->SetLossTangent( parseDouble(), sublayer_idx );
2421 NeedRIGHT();
2422 break;
2423
2424 case T_spec_frequency:
2425 NextTok();
2426 item->SetSpecFreq( parseDouble(), sublayer_idx );
2427 NeedRIGHT();
2428 break;
2429
2430 case T_dielectric_model:
2431 token = NextTok();
2432
2433 switch( token )
2434 {
2435 case T_constant:
2436 item->SetDielectricModel( DIELECTRIC_MODEL::CONSTANT, sublayer_idx );
2437 break;
2438
2439 case T_djordjevic_sarkar:
2441 break;
2442
2443 default:
2444 Expecting( "constant or djordjevic_sarkar" );
2445 break;
2446 }
2447
2448 NeedRIGHT();
2449 break;
2450
2451 case T_color:
2452 NeedSYMBOL();
2453 name = FromUTF8();
2454
2455 // Older versions didn't store opacity with custom colors
2456 if( name.StartsWith( wxT( "#" ) ) && m_requiredVersion < 20210824 )
2457 {
2458 KIGFX::COLOR4D color( name );
2459
2460 if( item->GetType() == BS_ITEM_TYPE_SOLDERMASK )
2461 color = color.WithAlpha( DEFAULT_SOLDERMASK_OPACITY );
2462 else
2463 color = color.WithAlpha( 1.0 );
2464
2465 wxColour wx_color = color.ToColour();
2466
2467 // Open-code wxColour::GetAsString() because 3.0 doesn't handle rgba
2468 name.Printf( wxT("#%02X%02X%02X%02X" ),
2469 wx_color.Red(),
2470 wx_color.Green(),
2471 wx_color.Blue(),
2472 wx_color.Alpha() );
2473 }
2474
2475 item->SetColor( name, sublayer_idx );
2476 NeedRIGHT();
2477 break;
2478
2479 default:
2480 // Currently, skip this item if not defined, because the stackup def
2481 // is a moving target
2482 //Expecting( "type, thickness, material, epsilon_r, loss_tangent, color" );
2483 skipCurrent();
2484 }
2485 }
2486 }
2487
2488 if( has_next_sublayer ) // Prepare reading the next sublayer description
2489 {
2490 sublayer_idx++;
2491 item->AddDielectricPrms( sublayer_idx );
2492 }
2493 }
2494 }
2495
2496 if( token != T_RIGHT )
2497 {
2498 Expecting( ")" );
2499 }
2500
2501 // Success:
2502 m_board->GetDesignSettings().m_HasStackup = true;
2503}
2504
2505
2506void PCB_IO_KICAD_SEXPR_PARSER::createOldLayerMapping( std::unordered_map< std::string, std::string >& aMap )
2507{
2508 // N.B. This mapping only includes Italian, Polish and French as they were the only languages
2509 // that mapped the layer names as of cc2022b1ac739aa673d2a0b7a2047638aa7a47b3 (kicad-i18n)
2510 // when the bug was fixed in KiCad source.
2511
2512 // Italian
2513 aMap["Adesivo.Retro"] = "B.Adhes";
2514 aMap["Adesivo.Fronte"] = "F.Adhes";
2515 aMap["Pasta.Retro"] = "B.Paste";
2516 aMap["Pasta.Fronte"] = "F.Paste";
2517 aMap["Serigrafia.Retro"] = "B.SilkS";
2518 aMap["Serigrafia.Fronte"] = "F.SilkS";
2519 aMap["Maschera.Retro"] = "B.Mask";
2520 aMap["Maschera.Fronte"] = "F.Mask";
2521 aMap["Grafica"] = "Dwgs.User";
2522 aMap["Commenti"] = "Cmts.User";
2523 aMap["Eco1"] = "Eco1.User";
2524 aMap["Eco2"] = "Eco2.User";
2525 aMap["Contorno.scheda"] = "Edge.Cuts";
2526
2527 // Polish
2528 aMap["Kleju_Dolna"] = "B.Adhes";
2529 aMap["Kleju_Gorna"] = "F.Adhes";
2530 aMap["Pasty_Dolna"] = "B.Paste";
2531 aMap["Pasty_Gorna"] = "F.Paste";
2532 aMap["Opisowa_Dolna"] = "B.SilkS";
2533 aMap["Opisowa_Gorna"] = "F.SilkS";
2534 aMap["Maski_Dolna"] = "B.Mask";
2535 aMap["Maski_Gorna"] = "F.Mask";
2536 aMap["Rysunkowa"] = "Dwgs.User";
2537 aMap["Komentarzy"] = "Cmts.User";
2538 aMap["ECO1"] = "Eco1.User";
2539 aMap["ECO2"] = "Eco2.User";
2540 aMap["Krawedziowa"] = "Edge.Cuts";
2541
2542 // French
2543 aMap["Dessous.Adhes"] = "B.Adhes";
2544 aMap["Dessus.Adhes"] = "F.Adhes";
2545 aMap["Dessous.Pate"] = "B.Paste";
2546 aMap["Dessus.Pate"] = "F.Paste";
2547 aMap["Dessous.SilkS"] = "B.SilkS";
2548 aMap["Dessus.SilkS"] = "F.SilkS";
2549 aMap["Dessous.Masque"] = "B.Mask";
2550 aMap["Dessus.Masque"] = "F.Mask";
2551 aMap["Dessin.User"] = "Dwgs.User";
2552 aMap["Contours.Ci"] = "Edge.Cuts";
2553}
2554
2555
2557{
2558 wxCHECK_RET( CurTok() == T_layers,
2559 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as layers." ) );
2560
2561 T token;
2562 LSET visibleLayers;
2563 LSET enabledLayers;
2564 int copperLayerCount = 0;
2565 LAYER layer;
2566 bool anyHidden = false;
2567
2568 std::unordered_map< std::string, std::string > v3_layer_names;
2569 std::vector<LAYER> cu;
2570
2571 // Destination layers before the appended board is applied, used to detect a remap need
2572 const LSET destInitialEnabled = m_appendToExisting ? m_board->GetEnabledLayers() : LSET();
2573 const int destInitialCopperCount = m_appendToExisting ? m_board->GetCopperLayerCount() : 0;
2574 std::vector<LAYER> appendedLayers;
2575
2576 createOldLayerMapping( v3_layer_names );
2577
2578 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
2579 {
2580 parseLayer( &layer );
2581
2582 if( layer.m_type == LT_UNDEFINED ) // it's a non-copper layer
2583 break;
2584
2585 cu.push_back( layer ); // it's copper
2586 }
2587
2588 // All Cu layers are parsed, but not the non-cu layers here.
2589
2590 // The original *.kicad_pcb file format and the inverted
2591 // Cu stack format both have all the Cu layers first, so use this
2592 // trick to handle either. The layer number in the (layers ..)
2593 // s-expression element are ignored.
2594 if( cu.size() )
2595 {
2596 // Rework the layer numbers, which changed when the Cu stack
2597 // was flipped. So we instead use position in the list.
2598 for( size_t i = 1; i < cu.size() - 1; i++ )
2599 {
2600 int tmpLayer = LSET::NameToLayer( cu[i].m_name );
2601
2602 if( tmpLayer < 0 )
2603 tmpLayer = ( i + 1 ) * 2;
2604
2605 cu[i].m_number = tmpLayer;
2606 }
2607
2608 cu[0].m_number = F_Cu;
2609 cu[cu.size()-1].m_number = B_Cu;
2610
2611 for( auto& cu_layer : cu )
2612 {
2613 enabledLayers.set( cu_layer.m_number );
2614
2615 if( cu_layer.m_visible )
2616 visibleLayers.set( cu_layer.m_number );
2617 else
2618 anyHidden = true;
2619
2620 if( !m_preserveDestinationStackup || !m_board->IsLayerEnabled( PCB_LAYER_ID( cu_layer.m_number ) ) )
2621 {
2622 m_board->SetLayerDescr( PCB_LAYER_ID( cu_layer.m_number ), cu_layer );
2623 }
2624
2625 UTF8 name = cu_layer.m_name;
2626
2627 m_layerIndices[ name ] = PCB_LAYER_ID( cu_layer.m_number );
2628 m_layerMasks[ name ] = LSET( { PCB_LAYER_ID( cu_layer.m_number ) } );
2629
2630 appendedLayers.push_back( cu_layer );
2631 }
2632
2633 copperLayerCount = cu.size();
2634 }
2635
2636 // process non-copper layers
2637 while( token != T_RIGHT )
2638 {
2639 LAYER_ID_MAP::const_iterator it = m_layerIndices.find( UTF8( layer.m_name ) );
2640
2641 if( it == m_layerIndices.end() )
2642 {
2643 auto new_layer_it = v3_layer_names.find( layer.m_name.ToStdString() );
2644
2645 if( new_layer_it != v3_layer_names.end() )
2646 it = m_layerIndices.find( new_layer_it->second );
2647
2648 if( it == m_layerIndices.end() )
2649 {
2650 THROW_IO_ERRORF( _( "Layer '%s' in file '%s' at line %d is not in fixed layer hash." ),
2651 layer.m_name, CurSource(), CurLineNumber(), CurOffset() );
2652 }
2653
2654 // If we are here, then we have found a translated layer name. Put it in the maps
2655 // so that items on this layer get the appropriate layer ID number.
2656 m_layerIndices[ UTF8( layer.m_name ) ] = it->second;
2657 m_layerMasks[ UTF8( layer.m_name ) ] = LSET( { it->second } );
2658 layer.m_name = it->first;
2659 }
2660
2661 layer.m_number = it->second;
2662 enabledLayers.set( layer.m_number );
2663
2664 if( layer.m_visible )
2665 visibleLayers.set( layer.m_number );
2666 else
2667 anyHidden = true;
2668
2669 if( !m_preserveDestinationStackup || !m_board->IsLayerEnabled( it->second ) )
2670 m_board->SetLayerDescr( it->second, layer );
2671
2672 appendedLayers.push_back( layer );
2673
2674 token = NextTok();
2675
2676 if( token != T_LEFT )
2677 break;
2678
2679 parseLayer( &layer );
2680 }
2681
2682 // We need at least 2 copper layers and there must be an even number of them.
2683 if( copperLayerCount < 2 || (copperLayerCount % 2) != 0 )
2684 {
2685 wxString err = wxString::Format( _( "%d is not a valid layer count" ), copperLayerCount );
2686
2687 THROW_PARSE_ERROR( err, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
2688 }
2689
2691 {
2692 m_board->SetCopperLayerCount( std::max( copperLayerCount, m_board->GetCopperLayerCount() ) );
2693 m_board->SetEnabledLayers( enabledLayers | m_board->GetEnabledLayers() );
2694 }
2695 else
2696 {
2697 m_board->SetCopperLayerCount( copperLayerCount );
2698 m_board->SetEnabledLayers( enabledLayers );
2699
2700 // Only set this if any layers were explicitly marked as hidden. Otherwise, we want to leave
2701 // this alone; default visibility will show everything
2702 if( anyHidden )
2703 m_board->m_LegacyVisibleLayers = visibleLayers;
2704 }
2705
2707 remapAppendedLayers( appendedLayers, destInitialEnabled, destInitialCopperCount );
2708}
2709
2710
2711void PCB_IO_KICAD_SEXPR_PARSER::remapAppendedLayers( const std::vector<LAYER>& aSourceLayers,
2712 const LSET& aDestInitialEnabled, int aDestInitialCopperCount )
2713{
2714 // Only prompt when an appended layer is new to the destination or a named appended layer would
2715 // land on a differently-named destination layer
2716 int srcCopperCount = 0;
2717 bool mismatch = false;
2718
2719 for( const LAYER& src : aSourceLayers )
2720 {
2721 PCB_LAYER_ID id = PCB_LAYER_ID( src.m_number );
2722
2723 if( IsCopperLayer( src.m_number ) )
2724 srcCopperCount++;
2725
2726 if( !aDestInitialEnabled.Contains( id ) )
2727 mismatch = true;
2728 else if( !src.m_userName.IsEmpty() && src.m_userName != m_board->GetLayerName( id ) )
2729 mismatch = true;
2730 }
2731
2732 if( !mismatch )
2733 return;
2734
2735 std::vector<INPUT_LAYER_DESC> descs;
2736
2737 for( const LAYER& src : aSourceLayers )
2738 {
2739 INPUT_LAYER_DESC desc;
2740 desc.Name = src.m_userName.IsEmpty() ? src.m_name : src.m_userName;
2741 desc.AutoMapLayer = PCB_LAYER_ID( src.m_number );
2742 desc.Required = false;
2743
2744 if( IsCopperLayer( src.m_number ) )
2745 desc.PermittedLayers = LSET::AllCuMask( std::max( srcCopperCount, aDestInitialCopperCount ) );
2746 else
2747 desc.PermittedLayers = LSET( { PCB_LAYER_ID( src.m_number ) } );
2748
2749 // Prefer a destination layer with the same name as the auto-map suggestion
2750 for( PCB_LAYER_ID hid : aDestInitialEnabled.Seq() )
2751 {
2752 if( m_board->GetLayerName( hid ) == desc.Name )
2753 {
2754 desc.AutoMapLayer = hid;
2755 break;
2756 }
2757 }
2758
2759 descs.push_back( desc );
2760 }
2761
2762 // Hide the load progress reporter while the (modal) mapping dialog is up
2763 wxWindow* progressWindow = dynamic_cast<wxWindow*>( m_progressReporter );
2764
2765 if( progressWindow )
2766 progressWindow->Hide();
2767
2768 std::map<wxString, PCB_LAYER_ID> remap = m_layerMappingHandler( descs );
2769
2770 if( progressWindow )
2771 progressWindow->Show();
2772
2773 LSET enabled = m_board->GetEnabledLayers();
2774
2775 for( const LAYER& src : aSourceLayers )
2776 {
2777 wxString key = src.m_userName.IsEmpty() ? src.m_name : src.m_userName;
2778 auto it = remap.find( key );
2779 PCB_LAYER_ID target = ( it != remap.end() ) ? it->second : PCB_LAYER_ID( src.m_number );
2780
2781 UTF8 name = src.m_name;
2782
2783 if( target == UNDEFINED_LAYER )
2784 {
2785 // Not imported, items on it fall through to Rescue
2786 m_layerIndices.erase( name );
2787 m_layerMasks.erase( name );
2788 continue;
2789 }
2790
2791 m_layerIndices[name] = target;
2792 m_layerMasks[name] = LSET( { target } );
2793
2794 // New layer on the destination keeps the appended descriptor
2795 if( !aDestInitialEnabled.Contains( target ) )
2796 {
2797 LAYER descr = src;
2798 descr.m_number = target;
2799 m_board->SetLayerDescr( target, descr );
2800 }
2801
2802 enabled.set( target );
2803 }
2804
2805 m_board->SetEnabledLayers( enabled );
2806}
2807
2808
2810{
2811 LSET_MAP::const_iterator it = aMap.find( curText );
2812
2813 if( it == aMap.end() )
2814 return LSET( { Rescue } );
2815
2816 return it->second;
2817}
2818
2819
2821{
2822 // avoid constructing another std::string, use lexer's directly
2823 LAYER_ID_MAP::const_iterator it = aMap.find( curText );
2824
2825 if( it == aMap.end() )
2826 {
2827 if( curText == "UNDEFINED" && aAllowUndefined )
2828 return UNDEFINED_LAYER;
2829
2830 m_undefinedLayers.insert( curText );
2831 return Rescue;
2832 }
2833
2834 // Some files may have saved items to the Rescue Layer due to an issue in v5
2835 if( it->second == Rescue )
2836 m_undefinedLayers.insert( curText );
2837
2838 return it->second;
2839}
2840
2841
2843{
2844 wxCHECK_MSG( CurTok() == T_layer, UNDEFINED_LAYER,
2845 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as layer." ) );
2846
2847 NextTok();
2848
2849 PCB_LAYER_ID layerIndex = lookUpLayer( m_layerIndices );
2850
2851 // Handle closing ) in object parser.
2852
2853 return layerIndex;
2854}
2855
2856
2858{
2859 wxCHECK_MSG( CurTok() == T_layers, LSET(),
2860 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as item layers." ) );
2861
2862 LSET layerMask;
2863
2864 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
2865 {
2866 layerMask |= lookUpLayerSet( m_layerMasks );
2867 }
2868
2869 return layerMask;
2870}
2871
2872
2874{
2875 LSET layerMask = parseBoardItemLayersAsMask();
2876
2877 if( ( layerMask & LSET::AllCuMask() ).count() != 1 )
2878 Expecting( "single copper layer" );
2879
2880 if( ( layerMask & LSET( { F_Mask, B_Mask } ) ).count() > 1 )
2881 Expecting( "max one soldermask layer" );
2882
2883 if( ( ( layerMask & LSET::InternalCuMask() ).any()
2884 && ( layerMask & LSET( { F_Mask, B_Mask } ) ).any() ) )
2885 {
2886 Expecting( "no mask layer when track is on internal layer" );
2887 }
2888
2889 if( ( layerMask & LSET( { F_Cu, B_Mask } ) ).count() > 1 )
2890 Expecting( "copper and mask on the same side" );
2891
2892 if( ( layerMask & LSET( { B_Cu, F_Mask } ) ).count() > 1 )
2893 Expecting( "copper and mask on the same side" );
2894
2895 return layerMask;
2896}
2897
2898
2900{
2901 wxCHECK_RET( CurTok() == T_drill_symbol_profile,
2902 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a drill symbol profile." ) );
2903
2904 DRILL_SYMBOL_PROFILE& profile = m_board->GetDesignSettings().GetDrillSymbolProfile();
2905
2911 {
2912 profile.SetGroupedBy( key, false );
2913 }
2914
2915 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
2916 {
2917 if( token != T_LEFT )
2918 Expecting( T_LEFT );
2919
2920 token = NextTok();
2921
2922 switch( token )
2923 {
2924 case T_name:
2925 NeedSYMBOLorNUMBER();
2926 profile.SetName( FromUTF8() );
2927 NeedRIGHT();
2928 break;
2929
2930 case T_group_by:
2931 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
2932 {
2933 DRILL_GROUP_KEY key;
2934
2935 if( DrillGroupKeyFromToken( FromUTF8(), key ) )
2936 profile.SetGroupedBy( key, true );
2937 }
2938
2939 break;
2940
2941 case T_default_marks:
2942 {
2943 NeedSYMBOLorNUMBER();
2944 DRILL_MARK_POLICY policy;
2945
2946 if( DrillMarkPolicyFromToken( FromUTF8(), policy ) )
2947 profile.SetMarkPolicy( policy );
2948
2949 NeedRIGHT();
2950 break;
2951 }
2952
2953 case T_size:
2954 profile.SetSymbolSize( parseBoardUnits( "drill symbol size" ) );
2955 NeedRIGHT();
2956 break;
2957
2958 case T_width:
2959 profile.SetSymbolWidth( parseBoardUnits( "drill symbol line width" ) );
2960 NeedRIGHT();
2961 break;
2962
2963 case T_freeze_assignments:
2964 profile.SetFreezeAssignments( parseBool() );
2965 NeedRIGHT();
2966 break;
2967
2968 case T_assignment:
2969 {
2970 std::string key;
2971 DRILL_SYMBOL_ASSIGNMENT assignment;
2972
2973 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
2974 {
2975 if( token != T_LEFT )
2976 Expecting( T_LEFT );
2977
2978 token = NextTok();
2979
2980 switch( token )
2981 {
2982 case T_key:
2983 NeedSYMBOLorNUMBER();
2984 key = CurStr();
2985 NeedRIGHT();
2986 break;
2987
2988 case T_mark:
2989 {
2990 NeedSYMBOLorNUMBER();
2991 DrillMarkModeFromToken( FromUTF8(), assignment.m_MarkMode );
2992
2993 if( assignment.m_MarkMode == DRILL_MARK_MODE::SHAPE )
2994 {
2995 assignment.m_ShapeIndex = parseInt( "drill symbol shape" );
2996 }
2997 else if( assignment.m_MarkMode == DRILL_MARK_MODE::LETTER )
2998 {
2999 NeedSYMBOLorNUMBER();
3000 assignment.m_Letter = FromUTF8();
3001 }
3002
3003 NeedRIGHT();
3004 break;
3005 }
3006
3007 case T_descr:
3008 NeedSYMBOLorNUMBER();
3009 assignment.m_Description = FromUTF8();
3010 NeedRIGHT();
3011 break;
3012
3013 default:
3014 skipCurrent();
3015 break;
3016 }
3017 }
3018
3019 if( !key.empty() )
3020 profile.SetAssignment( key, assignment );
3021
3022 break;
3023 }
3024
3025 default:
3026 skipCurrent();
3027 break;
3028 }
3029 }
3030}
3031
3032
3034{
3035 wxCHECK_RET( CurTok() == T_setup,
3036 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as setup." ) );
3037
3038 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
3039 const std::shared_ptr<NETCLASS>& defaultNetClass = bds.m_NetSettings->GetDefaultNetclass();
3040 ZONE_SETTINGS& zoneSettings = bds.GetDefaultZoneSettings();
3041
3042 // Missing soldermask min width value means that the user has set the value to 0 and
3043 // not the default value (0.25mm)
3044 bds.m_SolderMaskMinWidth = 0;
3045
3046 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
3047 {
3048 if( token != T_LEFT )
3049 Expecting( T_LEFT );
3050
3051 token = NextTok();
3052
3053 switch( token )
3054 {
3055 case T_drill_symbol_profile:
3057 break;
3058
3059 case T_stackup:
3061 skipCurrent();
3062 else
3064 break;
3065
3066 case T_last_trace_width: // not used now
3067 /* lastTraceWidth =*/ parseBoardUnits( T_last_trace_width );
3068 NeedRIGHT();
3069 break;
3070
3071 case T_user_trace_width:
3072 {
3073 // Make room for the netclass value
3074 if( bds.m_TrackWidthList.empty() )
3075 bds.m_TrackWidthList.emplace_back( 0 );
3076
3077 int trackWidth = parseBoardUnits( T_user_trace_width );
3078
3079 if( !m_appendToExisting || !alg::contains( bds.m_TrackWidthList, trackWidth ) )
3080 bds.m_TrackWidthList.push_back( trackWidth );
3081
3082 m_board->m_LegacyDesignSettingsLoaded = true;
3083 NeedRIGHT();
3084 break;
3085 }
3086
3087 case T_trace_clearance:
3088 defaultNetClass->SetClearance( parseBoardUnits( T_trace_clearance ) );
3089 m_board->m_LegacyDesignSettingsLoaded = true;
3090 NeedRIGHT();
3091 break;
3092
3093 case T_zone_clearance:
3094 zoneSettings.m_ZoneClearance = parseBoardUnits( T_zone_clearance );
3095 m_board->m_LegacyDesignSettingsLoaded = true;
3096 NeedRIGHT();
3097 break;
3098
3099 case T_zone_45_only: // legacy setting
3100 /* zoneSettings.m_Zone_45_Only = */ parseBool();
3101 m_board->m_LegacyDesignSettingsLoaded = true;
3102 NeedRIGHT();
3103 break;
3104
3105 case T_clearance_min:
3106 bds.m_MinClearance = parseBoardUnits( T_clearance_min );
3107 m_board->m_LegacyDesignSettingsLoaded = true;
3108 NeedRIGHT();
3109 break;
3110
3111 case T_trace_min:
3112 bds.m_TrackMinWidth = parseBoardUnits( T_trace_min );
3113 m_board->m_LegacyDesignSettingsLoaded = true;
3114 NeedRIGHT();
3115 break;
3116
3117 case T_via_size:
3118 defaultNetClass->SetViaDiameter( parseBoardUnits( T_via_size ) );
3119 m_board->m_LegacyDesignSettingsLoaded = true;
3120 NeedRIGHT();
3121 break;
3122
3123 case T_via_drill:
3124 defaultNetClass->SetViaDrill( parseBoardUnits( T_via_drill ) );
3125 m_board->m_LegacyDesignSettingsLoaded = true;
3126 NeedRIGHT();
3127 break;
3128
3129 case T_via_min_annulus:
3130 bds.m_ViasMinAnnularWidth = parseBoardUnits( T_via_min_annulus );
3131 m_board->m_LegacyDesignSettingsLoaded = true;
3132 NeedRIGHT();
3133 break;
3134
3135 case T_via_min_size:
3136 bds.m_ViasMinSize = parseBoardUnits( T_via_min_size );
3137 m_board->m_LegacyDesignSettingsLoaded = true;
3138 NeedRIGHT();
3139 break;
3140
3141 case T_through_hole_min:
3142 bds.m_MinThroughDrill = parseBoardUnits( T_through_hole_min );
3143 m_board->m_LegacyDesignSettingsLoaded = true;
3144 NeedRIGHT();
3145 break;
3146
3147 // Legacy token for T_through_hole_min
3148 case T_via_min_drill:
3149 bds.m_MinThroughDrill = parseBoardUnits( T_via_min_drill );
3150 m_board->m_LegacyDesignSettingsLoaded = true;
3151 NeedRIGHT();
3152 break;
3153
3154 case T_hole_to_hole_min:
3155 bds.m_HoleToHoleMin = parseBoardUnits( T_hole_to_hole_min );
3156 m_board->m_LegacyDesignSettingsLoaded = true;
3157 NeedRIGHT();
3158 break;
3159
3160 case T_user_via:
3161 {
3162 int viaSize = parseBoardUnits( "user via size" );
3163 int viaDrill = parseBoardUnits( "user via drill" );
3164 VIA_DIMENSION via( viaSize, viaDrill );
3165
3166 // Make room for the netclass value
3167 if( bds.m_ViasDimensionsList.empty() )
3168 bds.m_ViasDimensionsList.emplace_back( VIA_DIMENSION( 0, 0 ) );
3169
3171 bds.m_ViasDimensionsList.emplace_back( via );
3172
3173 m_board->m_LegacyDesignSettingsLoaded = true;
3174 NeedRIGHT();
3175 break;
3176 }
3177
3178 case T_uvia_size:
3179 defaultNetClass->SetuViaDiameter( parseBoardUnits( T_uvia_size ) );
3180 m_board->m_LegacyDesignSettingsLoaded = true;
3181 NeedRIGHT();
3182 break;
3183
3184 case T_uvia_drill:
3185 defaultNetClass->SetuViaDrill( parseBoardUnits( T_uvia_drill ) );
3186 m_board->m_LegacyDesignSettingsLoaded = true;
3187 NeedRIGHT();
3188 break;
3189
3190 case T_uvias_allowed:
3191 parseBool();
3192 m_board->m_LegacyDesignSettingsLoaded = true;
3193 NeedRIGHT();
3194 break;
3195
3196 case T_blind_buried_vias_allowed:
3197 parseBool();
3198 m_board->m_LegacyDesignSettingsLoaded = true;
3199 NeedRIGHT();
3200 break;
3201
3202 case T_uvia_min_size:
3203 bds.m_MicroViasMinSize = parseBoardUnits( T_uvia_min_size );
3204 m_board->m_LegacyDesignSettingsLoaded = true;
3205 NeedRIGHT();
3206 break;
3207
3208 case T_uvia_min_drill:
3209 bds.m_MicroViasMinDrill = parseBoardUnits( T_uvia_min_drill );
3210 m_board->m_LegacyDesignSettingsLoaded = true;
3211 NeedRIGHT();
3212 break;
3213
3214 case T_user_diff_pair:
3215 {
3216 int width = parseBoardUnits( "user diff-pair width" );
3217 int gap = parseBoardUnits( "user diff-pair gap" );
3218 int viaGap = parseBoardUnits( "user diff-pair via gap" );
3219 DIFF_PAIR_DIMENSION diffPair( width, gap, viaGap );
3220
3222 bds.m_DiffPairDimensionsList.emplace_back( diffPair );
3223
3224 m_board->m_LegacyDesignSettingsLoaded = true;
3225 NeedRIGHT();
3226 break;
3227 }
3228
3229 case T_segment_width: // note: legacy (pre-6.0) token
3230 bds.m_LineThickness[ LAYER_CLASS_COPPER ] = parseBoardUnits( T_segment_width );
3231 m_board->m_LegacyDesignSettingsLoaded = true;
3232 NeedRIGHT();
3233 break;
3234
3235 case T_edge_width: // note: legacy (pre-6.0) token
3236 bds.m_LineThickness[ LAYER_CLASS_EDGES ] = parseBoardUnits( T_edge_width );
3237 m_board->m_LegacyDesignSettingsLoaded = true;
3238 NeedRIGHT();
3239 break;
3240
3241 case T_mod_edge_width: // note: legacy (pre-6.0) token
3242 bds.m_LineThickness[ LAYER_CLASS_SILK ] = parseBoardUnits( T_mod_edge_width );
3243 m_board->m_LegacyDesignSettingsLoaded = true;
3244 NeedRIGHT();
3245 break;
3246
3247 case T_pcb_text_width: // note: legacy (pre-6.0) token
3248 bds.m_TextThickness[ LAYER_CLASS_COPPER ] = parseBoardUnits( T_pcb_text_width );
3249 m_board->m_LegacyDesignSettingsLoaded = true;
3250 NeedRIGHT();
3251 break;
3252
3253 case T_mod_text_width: // note: legacy (pre-6.0) token
3254 bds.m_TextThickness[ LAYER_CLASS_SILK ] = parseBoardUnits( T_mod_text_width );
3255 m_board->m_LegacyDesignSettingsLoaded = true;
3256 NeedRIGHT();
3257 break;
3258
3259 case T_pcb_text_size: // note: legacy (pre-6.0) token
3260 bds.m_TextSize[ LAYER_CLASS_COPPER ].x = parseBoardUnits( "pcb text width" );
3261 bds.m_TextSize[ LAYER_CLASS_COPPER ].y = parseBoardUnits( "pcb text height" );
3262 m_board->m_LegacyDesignSettingsLoaded = true;
3263 NeedRIGHT();
3264 break;
3265
3266 case T_mod_text_size: // note: legacy (pre-6.0) token
3267 bds.m_TextSize[ LAYER_CLASS_SILK ].x = parseBoardUnits( "footprint text width" );
3268 bds.m_TextSize[ LAYER_CLASS_SILK ].y = parseBoardUnits( "footprint text height" );
3269 m_board->m_LegacyDesignSettingsLoaded = true;
3270 NeedRIGHT();
3271 break;
3272
3273 case T_defaults:
3274 parseDefaults( bds );
3275 m_board->m_LegacyDesignSettingsLoaded = true;
3276 break;
3277
3278 case T_pad_size:
3279 {
3280 // master pad size no longer read
3281 parseBoardUnits( "master pad width" ); // x
3282 parseBoardUnits( "master pad height" ); // y
3283 m_board->m_LegacyDesignSettingsLoaded = true;
3284 NeedRIGHT();
3285 break;
3286 }
3287
3288 case T_pad_drill:
3289 {
3290 // master pad drill size no longer read
3291 parseBoardUnits( T_pad_drill ); // drill size
3292 m_board->m_LegacyDesignSettingsLoaded = true;
3293 NeedRIGHT();
3294 break;
3295 }
3296
3297 case T_pad_to_mask_clearance:
3298 bds.m_SolderMaskExpansion = parseBoardUnits( T_pad_to_mask_clearance );
3299 NeedRIGHT();
3300 break;
3301
3302 case T_solder_mask_min_width:
3303 bds.m_SolderMaskMinWidth = parseBoardUnits( T_solder_mask_min_width );
3304 NeedRIGHT();
3305 break;
3306
3307 case T_pad_to_paste_clearance:
3308 bds.m_SolderPasteMargin = parseBoardUnits( T_pad_to_paste_clearance );
3309 NeedRIGHT();
3310 break;
3311
3312 case T_pad_to_paste_clearance_ratio:
3313 bds.m_SolderPasteMarginRatio = parseDouble( T_pad_to_paste_clearance_ratio );
3314 NeedRIGHT();
3315 break;
3316
3317 case T_allow_soldermask_bridges_in_footprints:
3319 NeedRIGHT();
3320 break;
3321
3322 case T_tenting:
3323 {
3324 auto [front, back] = parseFrontBackOptBool( true );
3325 bds.m_TentViasFront = front.value_or( false );
3326 bds.m_TentViasBack = back.value_or( false );
3327 break;
3328 }
3329
3330 case T_covering:
3331 {
3332 auto [front, back] = parseFrontBackOptBool();
3333 bds.m_CoverViasFront = front.value_or( false );
3334 bds.m_CoverViasBack = back.value_or( false );
3335 break;
3336 }
3337
3338 case T_plugging:
3339 {
3340 auto [front, back] = parseFrontBackOptBool();
3341 bds.m_PlugViasFront = front.value_or( false );
3342 bds.m_PlugViasBack = back.value_or( false );
3343 break;
3344 }
3345
3346 case T_capping:
3347 {
3348 bds.m_CapVias = parseBool();
3349 NeedRIGHT();
3350 break;
3351 }
3352
3353 case T_filling:
3354 {
3355 bds.m_FillVias = parseBool();
3356 NeedRIGHT();
3357 break;
3358 }
3359
3360 case T_aux_axis_origin:
3361 {
3362 int x = parseBoardUnits( "auxiliary origin X" );
3363 int y = parseBoardUnits( "auxiliary origin Y" );
3364 bds.SetAuxOrigin( VECTOR2I( x, y ) );
3365
3366 // Aux origin still stored in board for the moment
3367 //m_board->m_LegacyDesignSettingsLoaded = true;
3368 NeedRIGHT();
3369 break;
3370 }
3371
3372 case T_grid_origin:
3373 {
3374 int x = parseBoardUnits( "grid origin X" );
3375 int y = parseBoardUnits( "grid origin Y" );
3376 bds.SetGridOrigin( VECTOR2I( x, y ) );
3377 // Grid origin still stored in board for the moment
3378 //m_board->m_LegacyDesignSettingsLoaded = true;
3379 NeedRIGHT();
3380 break;
3381 }
3382
3383 // Stored in board prior to 6.0
3384 case T_visible_elements:
3385 {
3386 // Make sure to start with DefaultVisible so all new layers are set
3387 m_board->m_LegacyVisibleItems = GAL_SET::DefaultVisible();
3388
3389 int visible = parseHex() | MIN_VISIBILITY_MASK;
3390
3391 for( size_t i = 0; i < sizeof( int ) * CHAR_BIT; i++ )
3392 m_board->m_LegacyVisibleItems.set( i, visible & ( 1u << i ) );
3393
3394 NeedRIGHT();
3395 break;
3396 }
3397
3398 case T_max_error:
3399 bds.m_MaxError = parseBoardUnits( T_max_error );
3400 m_board->m_LegacyDesignSettingsLoaded = true;
3401 NeedRIGHT();
3402 break;
3403
3404 case T_filled_areas_thickness:
3405 // Ignore this value, it is not used anymore
3406 parseBool();
3407 NeedRIGHT();
3408 break;
3409
3410 case T_pcbplotparams:
3411 {
3412 PCB_PLOT_PARAMS plotParams;
3413 PCB_PLOT_PARAMS_PARSER parser( reader, m_requiredVersion );
3414 // parser must share the same current line as our current PCB parser
3415 // synchronize it.
3416 parser.SyncLineReaderWith( *this );
3417
3418 plotParams.Parse( &parser );
3419 SyncLineReaderWith( parser );
3420
3421 m_board->SetPlotOptions( plotParams );
3422
3423 if( plotParams.GetLegacyPlotViaOnMaskLayer().has_value() )
3424 {
3425 bool tent = !( *plotParams.GetLegacyPlotViaOnMaskLayer() );
3426 bds.m_TentViasFront = tent;
3427 bds.m_TentViasBack = tent;
3428 }
3429
3430 break;
3431 }
3432 case T_zone_defaults: parseZoneDefaults( bds.m_ZoneLayerProperties ); break;
3433
3434 default:
3435 Unexpected( CurText() );
3436 }
3437 }
3438
3439 // Set up a default stackup in case the file doesn't define one, and now we know
3440 // the enabled layers
3442 {
3443 BOARD_STACKUP& stackup = bds.GetStackupDescriptor();
3444 stackup.RemoveAll();
3445 stackup.BuildDefaultStackupList( &bds, m_board->GetCopperLayerCount() );
3446 }
3447}
3448
3449
3450void PCB_IO_KICAD_SEXPR_PARSER::parseZoneDefaults( std::map<PCB_LAYER_ID, ZONE_LAYER_PROPERTIES>& aProperties )
3451{
3452 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
3453 {
3454 if( token != T_LEFT )
3455 Expecting( T_LEFT );
3456
3457 token = NextTok();
3458
3459 switch( token )
3460 {
3461 case T_property: parseZoneLayerProperty( aProperties ); break;
3462 default:
3463 Unexpected( CurText() );
3464 }
3465 }
3466}
3467
3468
3470 std::map<PCB_LAYER_ID, ZONE_LAYER_PROPERTIES>& aProperties )
3471{
3473 ZONE_LAYER_PROPERTIES properties;
3474
3475 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
3476 {
3477 if( token != T_LEFT )
3478 Expecting( T_LEFT );
3479
3480 token = NextTok();
3481
3482 switch( token )
3483 {
3484 case T_layer:
3485 layer = parseBoardItemLayer();
3486 NeedRIGHT();
3487 break;
3488 case T_hatch_position:
3489 {
3490 properties.hatching_offset = parseXY();
3491 NeedRIGHT();
3492 break;
3493 }
3494 default:
3495 Unexpected( CurText() );
3496 break;
3497 }
3498 }
3499
3500 aProperties.emplace( layer, properties );
3501}
3502
3503
3505{
3506 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
3507 {
3508 if( token != T_LEFT )
3509 Expecting( T_LEFT );
3510
3511 token = NextTok();
3512
3513 switch( token )
3514 {
3515 case T_edge_clearance:
3516 aSettings.m_CopperEdgeClearance = parseBoardUnits( T_edge_clearance );
3517 m_board->m_LegacyCopperEdgeClearanceLoaded = true;
3518 NeedRIGHT();
3519 break;
3520
3521 case T_copper_line_width:
3522 aSettings.m_LineThickness[ LAYER_CLASS_COPPER ] = parseBoardUnits( token );
3523 NeedRIGHT();
3524 break;
3525
3526 case T_copper_text_dims:
3528 break;
3529
3530 case T_courtyard_line_width:
3532 NeedRIGHT();
3533 break;
3534
3535 case T_edge_cuts_line_width:
3536 aSettings.m_LineThickness[ LAYER_CLASS_EDGES ] = parseBoardUnits( token );
3537 NeedRIGHT();
3538 break;
3539
3540 case T_silk_line_width:
3541 aSettings.m_LineThickness[ LAYER_CLASS_SILK ] = parseBoardUnits( token );
3542 NeedRIGHT();
3543 break;
3544
3545 case T_silk_text_dims:
3547 break;
3548
3549 case T_fab_layers_line_width:
3550 aSettings.m_LineThickness[ LAYER_CLASS_FAB ] = parseBoardUnits( token );
3551 NeedRIGHT();
3552 break;
3553
3554 case T_fab_layers_text_dims:
3556 break;
3557
3558 case T_other_layers_line_width:
3559 aSettings.m_LineThickness[ LAYER_CLASS_OTHERS ] = parseBoardUnits( token );
3560 NeedRIGHT();
3561 break;
3562
3563 case T_other_layers_text_dims:
3565 break;
3566
3567 case T_dimension_units:
3568 aSettings.m_DimensionUnitsMode = static_cast<DIM_UNITS_MODE>( parseInt( "dimension units" ) );
3569 NeedRIGHT();
3570 break;
3571
3572 case T_dimension_precision:
3573 aSettings.m_DimensionPrecision = static_cast<DIM_PRECISION>( parseInt( "dimension precision" ) );
3574 NeedRIGHT();
3575 break;
3576
3577 default:
3578 Unexpected( CurText() );
3579 }
3580 }
3581}
3582
3583
3585{
3586 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
3587 {
3588 if( token == T_LEFT )
3589 token = NextTok();
3590
3591 switch( token )
3592 {
3593 case T_size:
3594 aSettings.m_TextSize[ aLayer ].x = parseBoardUnits( "default text size X" );
3595 aSettings.m_TextSize[ aLayer ].y = parseBoardUnits( "default text size Y" );
3596 NeedRIGHT();
3597 break;
3598
3599 case T_thickness:
3600 aSettings.m_TextThickness[ aLayer ] = parseBoardUnits( "default text width" );
3601 NeedRIGHT();
3602 break;
3603
3604 case T_italic:
3605 aSettings.m_TextItalic[ aLayer ] = true;
3606 break;
3607
3608 case T_keep_upright:
3609 aSettings.m_TextUpright[ aLayer ] = true;
3610 break;
3611
3612 default:
3613 Expecting( "size, thickness, italic or keep_upright" );
3614 }
3615 }
3616}
3617
3618
3620{
3621 wxCHECK_RET( CurTok() == T_net, wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as net." ) );
3622
3623 int netCode = parseInt( "net number" );
3624
3625 NeedSYMBOLorNUMBER();
3626 wxString name = FromUTF8();
3627
3628 // Convert overbar syntax from `~...~` to `~{...}`. These were left out of the first merge
3629 // so the version is a bit later.
3630 if( m_requiredVersion < 20210606 )
3632
3633 NeedRIGHT();
3634
3635 // net 0 should be already in list, so store this net
3636 // if it is not the net 0, or if the net 0 does not exists.
3637 // (TODO: a better test.)
3638 if( netCode > NETINFO_LIST::UNCONNECTED || !m_board->FindNet( NETINFO_LIST::UNCONNECTED ) )
3639 {
3640 NETINFO_ITEM* net = m_board->FindOrAddNet( name, netCode, ADD_MODE::INSERT, true );
3641
3642 // Store the new code mapping
3643 pushValueIntoMap( netCode, net->GetNetCode() );
3644 }
3645}
3646
3647// Parse the (net_chains ...) aggregation block providing chain names, member nets and optional terminal pads.
3649{
3650 // Tokens inside section: (net_chain (name <str>) (members (member (net <code>))...) (terminal_pad <uuid>) (terminal_pad <uuid>))
3651 for( T token = NextTok(); token != T_EOF; token = NextTok() )
3652 {
3653 if( token == T_RIGHT )
3654 break; // end of (net_chains ...)
3655 else if( token == T_LEFT )
3656 token = NextTok();
3657
3658 if( token != T_net_chain )
3659 {
3660 skipCurrent();
3661 continue;
3662 }
3663
3664 wxString name;
3665 std::vector<int> netCodes;
3666 std::vector<wxString> netNames;
3667 KIID padUuids[2];
3668 int padCount = 0;
3669
3670 for( T t = NextTok(); t != T_EOF; t = NextTok() )
3671 {
3672 if( t == T_RIGHT )
3673 break; // end chain
3674 else if( t == T_LEFT )
3675 t = NextTok();
3676
3677 switch( t )
3678 {
3679 case T_name:
3680 NeedSYMBOLorNUMBER();
3681 name = FromUTF8();
3682 NeedRIGHT();
3683 break;
3684
3685 case T_members:
3686 {
3687 for( T mt = NextTok(); mt != T_RIGHT; mt = NextTok() )
3688 {
3689 if( mt == T_LEFT )
3690 mt = NextTok();
3691
3692 if( mt == T_net )
3693 {
3694 // Accept either a net code (legacy) or a net name (current).
3695 T tok = NextTok();
3696
3697 if( tok == T_NUMBER )
3698 netCodes.push_back( (int) strtol( CurText(), nullptr, 10 ) );
3699 else
3700 netNames.push_back( FromUTF8() );
3701
3702 NeedRIGHT();
3703 }
3704 else if( mt == T_member )
3705 {
3706 // legacy style (member (net <code>)) wrapper
3707 T inner = NextTok();
3708
3709 if( inner == T_LEFT )
3710 inner = NextTok();
3711
3712 if( inner == T_net )
3713 {
3714 T tok2 = NextTok();
3715
3716 if( tok2 == T_NUMBER )
3717 netCodes.push_back( (int) strtol( CurText(), nullptr, 10 ) );
3718 else
3719 netNames.push_back( FromUTF8() );
3720
3721 NeedRIGHT();
3722 }
3723
3724 NeedRIGHT();
3725 }
3726 else
3727 {
3728 skipCurrent();
3729 }
3730 }
3731 break;
3732 }
3733
3734 case T_terminal_pad:
3735 if( padCount < 2 )
3736 {
3737 NeedSYMBOLorNUMBER();
3738 padUuids[padCount++] = KIID( FromUTF8() );
3739 NeedRIGHT();
3740 }
3741 else
3742 {
3743 skipCurrent();
3744 }
3745 break;
3746
3747 default:
3748 skipCurrent();
3749 break;
3750 }
3751 }
3752
3753 std::vector<NETINFO_ITEM*> resolvedNets;
3754
3755 for( int code : netCodes )
3756 {
3757 int internalCode = code;
3758
3759 if( code >= 0 && code < (int) m_netCodes.size() && m_netCodes[code] != 0 )
3760 internalCode = m_netCodes[code];
3761
3762 if( NETINFO_ITEM* net = m_board->FindNet( internalCode ) )
3763 resolvedNets.push_back( net );
3764 }
3765
3766 for( const wxString& netName : netNames )
3767 {
3768 if( NETINFO_ITEM* net = m_board->FindNet( netName ) )
3769 resolvedNets.push_back( net );
3770 }
3771
3772 for( NETINFO_ITEM* net : resolvedNets )
3773 {
3774 net->SetNetChain( name );
3775
3776 for( int i = 0; i < padCount && i < 2; ++i )
3777 {
3778 net->SetTerminalPadUuid( i, padUuids[i] );
3779
3780 if( PAD* pad = m_board->FindPadByUuid( padUuids[i] ) )
3781 net->SetTerminalPad( i, pad );
3782 }
3783 }
3784 }
3785}
3786
3787
3789{
3790 wxCHECK_RET( CurTok() == T_net_class,
3791 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as net class." ) );
3792
3793 std::shared_ptr<NETCLASS> nc = std::make_shared<NETCLASS>( wxEmptyString );
3794
3795 // Read netclass name (can be a name or just a number like track width)
3796 NeedSYMBOLorNUMBER();
3797 nc->SetName( FromUTF8() );
3798 NeedSYMBOL();
3799 nc->SetDescription( FromUTF8() );
3800
3801 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
3802 {
3803 if( token != T_LEFT )
3804 Expecting( T_LEFT );
3805
3806 token = NextTok();
3807
3808 switch( token )
3809 {
3810 case T_clearance:
3811 nc->SetClearance( parseBoardUnits( T_clearance ) );
3812 break;
3813
3814 case T_trace_width:
3815 nc->SetTrackWidth( parseBoardUnits( T_trace_width ) );
3816 break;
3817
3818 case T_via_dia:
3819 nc->SetViaDiameter( parseBoardUnits( T_via_dia ) );
3820 break;
3821
3822 case T_via_drill:
3823 nc->SetViaDrill( parseBoardUnits( T_via_drill ) );
3824 break;
3825
3826 case T_uvia_dia:
3827 nc->SetuViaDiameter( parseBoardUnits( T_uvia_dia ) );
3828 break;
3829
3830 case T_uvia_drill:
3831 nc->SetuViaDrill( parseBoardUnits( T_uvia_drill ) );
3832 break;
3833
3834 case T_diff_pair_width:
3835 nc->SetDiffPairWidth( parseBoardUnits( T_diff_pair_width ) );
3836 break;
3837
3838 case T_diff_pair_gap:
3839 nc->SetDiffPairGap( parseBoardUnits( T_diff_pair_gap ) );
3840 break;
3841
3842 case T_add_net:
3843 {
3844 NeedSYMBOLorNUMBER();
3845
3846 wxString netName = FromUTF8();
3847
3848 // Convert overbar syntax from `~...~` to `~{...}`. These were left out of the
3849 // first merge so the version is a bit later.
3850 if( m_requiredVersion < 20210606 )
3851 netName = ConvertToNewOverbarNotation( FromUTF8() );
3852
3853 m_board->GetDesignSettings().m_NetSettings->SetNetclassPatternAssignment( netName, nc->GetName() );
3854
3855 break;
3856 }
3857
3858 default:
3859 Expecting( "clearance, trace_width, via_dia, via_drill, uvia_dia, uvia_drill, "
3860 "diff_pair_width, diff_pair_gap or add_net" );
3861 }
3862
3863 NeedRIGHT();
3864 }
3865
3866 std::shared_ptr<NET_SETTINGS>& netSettings = m_board->GetDesignSettings().m_NetSettings;
3867
3868 if( netSettings->HasNetclass( nc->GetName() ) )
3869 {
3870 // Must have been a name conflict, this is a bad board file.
3871 // User may have done a hand edit to the file.
3872 THROW_IO_ERRORF( _( "Duplicate NETCLASS name '%s' in file '%s' at line %d, offset %d." ),
3873 nc->GetName().GetData(), CurSource().GetData(), CurLineNumber(), CurOffset() );
3874 }
3875 else if( nc->GetName() == netSettings->GetDefaultNetclass()->GetName() )
3876 {
3877 netSettings->SetDefaultNetclass( nc );
3878 }
3879 else
3880 {
3881 netSettings->SetNetclass( nc->GetName(), nc );
3882 }
3883}
3884
3885
3887{
3888 // Current token is T_start_shape or T_end_shape. Next token is the style.
3889 T token = NextTok();
3890
3891 switch( token )
3892 {
3893 case T_arrow: aEnding.SetStyle( LINE_ENDING_STYLE::ARROW ); break;
3894 case T_circle: aEnding.SetStyle( LINE_ENDING_STYLE::CIRCLE ); break;
3895 case T_square: aEnding.SetStyle( LINE_ENDING_STYLE::SQUARE ); break;
3896 case T_arrow_open: aEnding.SetStyle( LINE_ENDING_STYLE::ARROW_OPEN ); break;
3897 case T_none: aEnding.SetStyle( LINE_ENDING_STYLE::NONE ); break;
3898 default: Expecting( "arrow, circle, square, arrow_open, or none" );
3899 }
3900
3901 // Parse optional sub-tokens
3902 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
3903 {
3904 if( token != T_LEFT )
3905 Expecting( T_LEFT );
3906
3907 token = NextTok();
3908
3909 switch( token )
3910 {
3911 case T_length:
3912 aEnding.SetLength( parseBoardUnits( "length" ) );
3913 NeedRIGHT();
3914 break;
3915
3916 case T_width:
3917 aEnding.SetWidth( parseBoardUnits( "width" ) );
3918 NeedRIGHT();
3919 break;
3920
3921 case T_stroke:
3922 {
3923 STROKE_PARAMS stroke;
3924 STROKE_PARAMS_PARSER strokeParser( reader, pcbIUScale.IU_PER_MM );
3925 strokeParser.SyncLineReaderWith( *this );
3926
3927 strokeParser.ParseStroke( stroke );
3928 SyncLineReaderWith( strokeParser );
3929
3930 aEnding.SetStroke( stroke );
3931 break;
3932 }
3933
3934 default: Expecting( "length, width, or stroke" );
3935 }
3936 }
3937}
3938
3939
3941{
3942 wxCHECK_MSG( CurTok() == T_fp_arc || CurTok() == T_fp_circle || CurTok() == T_fp_curve || CurTok() == T_fp_rect
3943 || CurTok() == T_fp_line || CurTok() == T_fp_poly || CurTok() == T_fp_ellipse
3944 || CurTok() == T_fp_ellipse_arc || CurTok() == T_gr_arc || CurTok() == T_gr_circle
3945 || CurTok() == T_gr_curve || CurTok() == T_gr_rect || CurTok() == T_gr_bbox
3946 || CurTok() == T_gr_line || CurTok() == T_gr_poly || CurTok() == T_gr_vector
3947 || CurTok() == T_gr_ellipse || CurTok() == T_gr_ellipse_arc,
3948 nullptr, wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_SHAPE." ) );
3949
3950 T token;
3951 VECTOR2I pt;
3952 STROKE_PARAMS stroke( 0, LINE_STYLE::SOLID );
3953 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( aParent );
3954
3955 VECTOR2I ellipseCenter( 0, 0 );
3956 int ellipseMajor = 0;
3957 int ellipseMinor = 0;
3958 EDA_ANGLE ellipseRotation = ANGLE_0;
3959 EDA_ANGLE ellipseStart = ANGLE_0;
3960 EDA_ANGLE ellipseEnd = ANGLE_0;
3961
3962 switch( CurTok() )
3963 {
3964 case T_gr_arc:
3965 case T_fp_arc:
3966 shape->SetShape( SHAPE_T::ARC );
3967 token = NextTok();
3968
3969 if( token == T_locked )
3970 {
3971 shape->SetLocked( true );
3972 token = NextTok();
3973 }
3974
3975 if( token != T_LEFT )
3976 Expecting( T_LEFT );
3977
3978 token = NextTok();
3979
3981 {
3982 // In legacy files the start keyword actually gives the arc center...
3983 if( token != T_start )
3984 Expecting( T_start );
3985
3986 pt.x = parseBoardUnits( "X coordinate" );
3987 pt.y = parseBoardUnits( "Y coordinate" );
3988 shape->SetCenter( pt );
3989 NeedRIGHT();
3990 NeedLEFT();
3991 token = NextTok();
3992
3993 // ... and the end keyword gives the start point of the arc
3994 if( token != T_end )
3995 Expecting( T_end );
3996
3997 pt.x = parseBoardUnits( "X coordinate" );
3998 pt.y = parseBoardUnits( "Y coordinate" );
3999 shape->SetStart( pt );
4000 NeedRIGHT();
4001 NeedLEFT();
4002 token = NextTok();
4003
4004 if( token != T_angle )
4005 Expecting( T_angle );
4006
4007 shape->SetArcAngleAndEnd( EDA_ANGLE( parseDouble( "arc angle" ), DEGREES_T ), true );
4008 NeedRIGHT();
4009 }
4010 else
4011 {
4012 VECTOR2I arc_start, arc_mid, arc_end;
4013
4014 if( token != T_start )
4015 Expecting( T_start );
4016
4017 arc_start.x = parseBoardUnits( "X coordinate" );
4018 arc_start.y = parseBoardUnits( "Y coordinate" );
4019 NeedRIGHT();
4020 NeedLEFT();
4021 token = NextTok();
4022
4023 if( token != T_mid )
4024 Expecting( T_mid );
4025
4026 arc_mid.x = parseBoardUnits( "X coordinate" );
4027 arc_mid.y = parseBoardUnits( "Y coordinate" );
4028 NeedRIGHT();
4029 NeedLEFT();
4030 token = NextTok();
4031
4032 if( token != T_end )
4033 Expecting( T_end );
4034
4035 arc_end.x = parseBoardUnits( "X coordinate" );
4036 arc_end.y = parseBoardUnits( "Y coordinate" );
4037 NeedRIGHT();
4038
4039 shape->SetArcOrSegment( arc_start, arc_mid, arc_end );
4040 }
4041
4042 break;
4043
4044 case T_gr_circle:
4045 case T_fp_circle:
4046 shape->SetShape( SHAPE_T::CIRCLE );
4047 token = NextTok();
4048
4049 if( token == T_locked )
4050 {
4051 shape->SetLocked( true );
4052 token = NextTok();
4053 }
4054
4055 if( token != T_LEFT )
4056 Expecting( T_LEFT );
4057
4058 token = NextTok();
4059
4060 if( token != T_center )
4061 Expecting( T_center );
4062
4063 pt.x = parseBoardUnits( "X coordinate" );
4064 pt.y = parseBoardUnits( "Y coordinate" );
4065 shape->SetStart( pt );
4066 NeedRIGHT();
4067 NeedLEFT();
4068
4069 token = NextTok();
4070
4071 if( token != T_end )
4072 Expecting( T_end );
4073
4074 pt.x = parseBoardUnits( "X coordinate" );
4075 pt.y = parseBoardUnits( "Y coordinate" );
4076 shape->SetEnd( pt );
4077 NeedRIGHT();
4078 break;
4079
4080 case T_gr_curve:
4081 case T_fp_curve:
4082 shape->SetShape( SHAPE_T::BEZIER );
4083 token = NextTok();
4084
4085 if( token == T_locked )
4086 {
4087 shape->SetLocked( true );
4088 token = NextTok();
4089 }
4090
4091 if( token != T_LEFT )
4092 Expecting( T_LEFT );
4093
4094 token = NextTok();
4095
4096 if( token != T_pts )
4097 Expecting( T_pts );
4098
4099 shape->SetStart( parseXY() );
4100 shape->SetBezierC1( parseXY());
4101 shape->SetBezierC2( parseXY());
4102 shape->SetEnd( parseXY() );
4103
4104 if( m_board )
4105 shape->RebuildBezierToSegmentsPointsList( m_board->GetDesignSettings().m_MaxError );
4106 else
4107 shape->RebuildBezierToSegmentsPointsList( ARC_HIGH_DEF );
4108
4109 NeedRIGHT();
4110 break;
4111
4112 case T_gr_bbox:
4113 case T_gr_rect:
4114 case T_fp_rect:
4115 shape->SetShape( SHAPE_T::RECTANGLE );
4116 token = NextTok();
4117
4118 if( token == T_locked )
4119 {
4120 shape->SetLocked( true );
4121 token = NextTok();
4122 }
4123
4124 if( token != T_LEFT )
4125 Expecting( T_LEFT );
4126
4127 token = NextTok();
4128
4129 if( token != T_start )
4130 Expecting( T_start );
4131
4132 pt.x = parseBoardUnits( "X coordinate" );
4133 pt.y = parseBoardUnits( "Y coordinate" );
4134 shape->SetStart( pt );
4135 NeedRIGHT();
4136 NeedLEFT();
4137 token = NextTok();
4138
4139 if( token != T_end )
4140 Expecting( T_end );
4141
4142 pt.x = parseBoardUnits( "X coordinate" );
4143 pt.y = parseBoardUnits( "Y coordinate" );
4144 shape->SetEnd( pt );
4145
4146 if( aParent && aParent->Type() == PCB_FOOTPRINT_T )
4147 {
4148 // Footprint shapes are stored in board-relative coordinates, but we want the
4149 // normalization to remain in footprint-relative coordinates.
4150 }
4151 else
4152 {
4153 shape->Normalize();
4154 }
4155
4156 NeedRIGHT();
4157 break;
4158
4159 case T_gr_vector:
4160 case T_gr_line:
4161 case T_fp_line:
4162 shape->SetShape( SHAPE_T::SEGMENT );
4163 token = NextTok();
4164
4165 if( token == T_locked )
4166 {
4167 shape->SetLocked( true );
4168 token = NextTok();
4169 }
4170
4171 if( token != T_LEFT )
4172 Expecting( T_LEFT );
4173
4174 token = NextTok();
4175
4176 if( token != T_start )
4177 Expecting( T_start );
4178
4179 pt.x = parseBoardUnits( "X coordinate" );
4180 pt.y = parseBoardUnits( "Y coordinate" );
4181 shape->SetStart( pt );
4182 NeedRIGHT();
4183 NeedLEFT();
4184 token = NextTok();
4185
4186 if( token != T_end )
4187 Expecting( T_end );
4188
4189 pt.x = parseBoardUnits( "X coordinate" );
4190 pt.y = parseBoardUnits( "Y coordinate" );
4191 shape->SetEnd( pt );
4192 NeedRIGHT();
4193 break;
4194
4195 case T_gr_poly:
4196 case T_fp_poly:
4197 {
4198 shape->SetShape( SHAPE_T::POLY );
4199 shape->SetPolyPoints( {} );
4200
4201 SHAPE_LINE_CHAIN& outline = shape->GetPolyShape().Outline( 0 );
4202
4203 token = NextTok();
4204
4205 if( token == T_locked )
4206 {
4207 shape->SetLocked( true );
4208 token = NextTok();
4209 }
4210
4211 if( token != T_LEFT )
4212 Expecting( T_LEFT );
4213
4214 token = NextTok();
4215
4216 if( token != T_pts )
4217 Expecting( T_pts );
4218
4219 while( (token = NextTok() ) != T_RIGHT )
4220 parseOutlinePoints( outline );
4221
4222 break;
4223 }
4224
4225 case T_gr_ellipse:
4226 case T_fp_ellipse: shape->SetShape( SHAPE_T::ELLIPSE ); break;
4227
4228 case T_gr_ellipse_arc:
4229 case T_fp_ellipse_arc: shape->SetShape( SHAPE_T::ELLIPSE_ARC ); break;
4230
4231 default:
4232 if( aParent && aParent->Type() == PCB_FOOTPRINT_T )
4233 {
4234 Expecting( "fp_arc, fp_circle, fp_curve, fp_ellipse, fp_ellipse_arc, "
4235 "fp_line, fp_poly or fp_rect" );
4236 }
4237 else
4238 {
4239 Expecting( "gr_arc, gr_circle, gr_curve, gr_ellipse, gr_ellipse_arc, "
4240 "gr_vector, gr_line, gr_poly, gr_rect or gr_bbox" );
4241 }
4242 }
4243
4244 bool foundFill = false;
4245
4246 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
4247 {
4248 if( token != T_LEFT )
4249 Expecting( T_LEFT );
4250
4251 token = NextTok();
4252
4253 switch( token )
4254 {
4255 case T_angle: // legacy token; ignore value
4256 parseDouble( "arc angle" );
4257 NeedRIGHT();
4258 break;
4259
4260 case T_layer:
4261 shape->SetLayer( parseBoardItemLayer() );
4262 NeedRIGHT();
4263 break;
4264
4265 case T_layers:
4266 shape->SetLayerSet( parseBoardItemLayersAsMask() );
4267 break;
4268
4269 case T_solder_mask_margin:
4270 shape->SetLocalSolderMaskMargin( parseBoardUnits( "local solder mask margin value" ) );
4271 NeedRIGHT();
4272 break;
4273
4274 case T_width: // legacy token
4275 stroke.SetWidth( parseBoardUnits( T_width ) );
4276 NeedRIGHT();
4277 break;
4278
4279 case T_radius:
4280 shape->SetCornerRadius( parseBoardUnits( "corner radius" ) );
4281 NeedRIGHT();
4282 break;
4283
4284 case T_stroke:
4285 {
4286 STROKE_PARAMS_PARSER strokeParser( reader, pcbIUScale.IU_PER_MM );
4287 strokeParser.SyncLineReaderWith( *this );
4288
4289 strokeParser.ParseStroke( stroke );
4290 SyncLineReaderWith( strokeParser );
4291 break;
4292 }
4293
4294 case T_tstamp:
4295 case T_uuid:
4296 NextTok();
4297 shape->SetUuidDirect( CurStrToKIID() );
4298 NeedRIGHT();
4299 break;
4300
4301 case T_fill:
4302 foundFill = true;
4303
4304 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
4305 {
4306 if( token == T_LEFT )
4307 token = NextTok();
4308
4309 switch( token )
4310 {
4311 // T_yes was used to indicate filling when first introduced, so treat it like a
4312 // solid fill since that was the only fill available at the time.
4313 case T_yes:
4314 case T_solid: shape->SetFillMode( FILL_T::FILLED_SHAPE ); break;
4315
4316 case T_none:
4317 case T_no: shape->SetFillMode( FILL_T::NO_FILL ); break;
4318
4319 case T_hatch: shape->SetFillMode( FILL_T::HATCH ); break;
4320 case T_reverse_hatch: shape->SetFillMode( FILL_T::REVERSE_HATCH ); break;
4321 case T_cross_hatch: shape->SetFillMode( FILL_T::CROSS_HATCH ); break;
4322
4323 default: Expecting( "yes, no, solid, none, hatch, reverse_hatch or cross_hatch" );
4324 }
4325 }
4326
4327 break;
4328
4329 case T_status: // legacy token; ignore value
4330 parseHex();
4331 NeedRIGHT();
4332 break;
4333
4334 // Handle "(locked)" from 5.99 development, and "(locked yes)" from modern times
4335 case T_locked:
4336 shape->SetLocked( parseMaybeAbsentBool( true ) );
4337 break;
4338
4339 case T_net:
4340 parseNet( shape.get() );
4341 break;
4342
4343 case T_center:
4344 ellipseCenter.x = parseBoardUnits( "X coordinate" );
4345 ellipseCenter.y = parseBoardUnits( "Y coordinate" );
4346 NeedRIGHT();
4347 break;
4348
4349 case T_major_radius:
4350 ellipseMajor = parseBoardUnits( "major radius" );
4351 NeedRIGHT();
4352 break;
4353
4354 case T_minor_radius:
4355 ellipseMinor = parseBoardUnits( "minor radius" );
4356 NeedRIGHT();
4357 break;
4358
4359 case T_rotation_angle:
4360 ellipseRotation = EDA_ANGLE( parseDouble( "rotation angle" ), DEGREES_T );
4361 NeedRIGHT();
4362 break;
4363
4364 case T_start_angle:
4365 ellipseStart = EDA_ANGLE( parseDouble( "start angle" ), DEGREES_T );
4366 NeedRIGHT();
4367 break;
4368
4369 case T_end_angle:
4370 ellipseEnd = EDA_ANGLE( parseDouble( "end angle" ), DEGREES_T );
4371 NeedRIGHT();
4372 break;
4373
4374 case T_start_shape:
4375 {
4376 LINE_ENDING ending;
4377 parseLineEnding( ending );
4378 shape->SetStartEnding( ending );
4379 break;
4380 }
4381
4382 case T_end_shape:
4383 {
4384 LINE_ENDING ending;
4385 parseLineEnding( ending );
4386 shape->SetEndEnding( ending );
4387 break;
4388 }
4389
4390 case T_custom_property:
4391 parseCustomProperty( shape.get() );
4392 break;
4393
4394 default:
4395 Expecting( "layer, width, fill, tstamp, uuid, locked, net, status, solder_mask_margin, center, "
4396 "major_radius, minor_radius, rotation_angle, start_angle, end_angle, start_shape, "
4397 "end_shape, or custom_property" );
4398 }
4399 }
4400
4401 if( !foundFill )
4402 {
4403 // Legacy versions didn't have a filled flag but allowed some shapes to indicate they
4404 // should be filled by specifying a 0 stroke-width.
4405 if( stroke.GetWidth() == 0
4406 && ( shape->GetShape() == SHAPE_T::RECTANGLE || shape->GetShape() == SHAPE_T::CIRCLE ) )
4407 {
4408 shape->SetFilled( true );
4409 }
4410 else if( shape->GetShape() == SHAPE_T::POLY && shape->GetLayer() != Edge_Cuts )
4411 {
4412 // Polygons on non-Edge_Cuts layers were always filled.
4413 shape->SetFilled( true );
4414 }
4415 }
4416
4417 // Only filled shapes may have a zero line-width. This is not permitted in KiCad but some
4418 // external tools can generate invalid files.
4419 if( stroke.GetWidth() <= 0 && !shape->IsAnyFill() )
4420 stroke.SetWidth( pcbIUScale.mmToIU( DEFAULT_LINE_WIDTH ) );
4421
4422 shape->SetStroke( stroke );
4423
4424 if( shape->GetParentFootprint() )
4425 shape->SetLibStrokeWidth( stroke.GetWidth() );
4426
4427 if( shape->GetShape() == SHAPE_T::ELLIPSE || shape->GetShape() == SHAPE_T::ELLIPSE_ARC )
4428 {
4429 shape->SetLibraryEllipse( ellipseCenter, ellipseMajor, ellipseMinor, ellipseRotation, ellipseStart,
4430 ellipseEnd );
4431
4432 if( shape->GetParentFootprint() )
4433 shape->RebakeFromLib();
4434 }
4435 else if( shape->GetParentFootprint() )
4436 {
4437 const VECTOR2I libStart = shape->GetStart();
4438 const VECTOR2I libEnd = shape->GetEnd();
4439 const VECTOR2I libArcMid = shape->GetShape() == SHAPE_T::ARC ? shape->GetArcMid() : VECTOR2I( 0, 0 );
4440
4441 shape->OverrideLibCoords( libStart, libEnd, libArcMid );
4442
4443 if( shape->GetShape() == SHAPE_T::RECTANGLE )
4444 shape->OverrideLibCornerRadius( shape->GetCornerRadius() );
4445
4446 if( shape->GetShape() == SHAPE_T::BEZIER )
4447 shape->OverrideLibBezier( shape->GetBezierC1(), shape->GetBezierC2() );
4448
4449 if( shape->GetShape() == SHAPE_T::POLY )
4450 shape->OverrideLibPoly( shape->GetPolyShape() );
4451
4452 shape->RebakeFromLib();
4453 }
4454
4455 return shape.release();
4456}
4457
4458
4460{
4461 wxCHECK_MSG( CurTok() == T_image, nullptr,
4462 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a reference image." ) );
4463
4464 std::unique_ptr<PCB_REFERENCE_IMAGE> bitmap = std::make_unique<PCB_REFERENCE_IMAGE>( aParent );
4465
4466 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
4467 {
4468 if( token != T_LEFT )
4469 Expecting( T_LEFT );
4470
4471 token = NextTok();
4472
4473 switch( token )
4474 {
4475 case T_at:
4476 {
4477 VECTOR2I pos;
4478 pos.x = parseBoardUnits( "X coordinate" );
4479 pos.y = parseBoardUnits( "Y coordinate" );
4480 bitmap->SetPosition( pos );
4481 NeedRIGHT();
4482 break;
4483 }
4484
4485 case T_layer:
4486 bitmap->SetLayer( parseBoardItemLayer() );
4487 NeedRIGHT();
4488 break;
4489
4490 case T_rotate:
4491 {
4492 REFERENCE_IMAGE& refImage = bitmap->GetReferenceImage();
4493 refImage.SetOrientation( EDA_ANGLE( parseDouble( "image rotation" ), DEGREES_T ) );
4494 NeedRIGHT();
4495 break;
4496 }
4497
4498 case T_opacity:
4499 {
4500 REFERENCE_IMAGE& refImage = bitmap->GetReferenceImage();
4501 refImage.SetOpacity( parseDouble( "image opacity" ) );
4502 NeedRIGHT();
4503 break;
4504 }
4505
4506 case T_scale:
4507 {
4508 REFERENCE_IMAGE& refImage = bitmap->GetReferenceImage();
4509 refImage.SetImageScale( parseDouble( "image scale factor" ) );
4510
4511 if( !std::isnormal( refImage.GetImageScale() ) )
4512 refImage.SetImageScale( 1.0 );
4513
4514 NeedRIGHT();
4515 break;
4516 }
4517 case T_data:
4518 {
4519 token = NextTok();
4520
4521 wxString data;
4522
4523 // Reserve 512K because most image files are going to be larger than the default
4524 // 1K that wxString reserves.
4525 data.reserve( 1 << 19 );
4526
4527 while( token != T_RIGHT )
4528 {
4529 if( !IsSymbol( token ) )
4530 Expecting( "base64 image data" );
4531
4532 data += FromUTF8();
4533 token = NextTok();
4534 }
4535
4536 wxMemoryBuffer buffer = wxBase64Decode( data );
4537
4538 REFERENCE_IMAGE& refImage = bitmap->GetReferenceImage();
4539
4540 if( !refImage.ReadImageFile( buffer ) )
4541 THROW_IO_ERROR( _( "Failed to read image data." ) );
4542
4543 break;
4544 }
4545
4546 case T_locked:
4547 {
4548 // This has only ever been (locked yes) format
4549 const bool locked = parseBool();
4550 bitmap->SetLocked( locked );
4551
4552 NeedRIGHT();
4553 break;
4554 }
4555
4556 case T_uuid:
4557 NextTok();
4558 bitmap->SetUuidDirect( CurStrToKIID() );
4559 NeedRIGHT();
4560 break;
4561
4562 case T_custom_property:
4563 parseCustomProperty( bitmap.get() );
4564 break;
4565
4566 default: Expecting( "at, layer, rotate, opacity, scale, data, locked, uuid, or custom_property" );
4567 }
4568 }
4569
4570 // Before 20260623 the PPI was computed from the embedded resolution but pixels/cm was
4571 // truncated to an integer, so the stored scale compensated for the wrong PPI. Re-scale
4572 // to the corrected PPI to preserve the rendered size of existing boards.
4573 if( m_requiredVersion < 20260623 )
4574 {
4575 REFERENCE_IMAGE& refImage = bitmap->GetReferenceImage();
4576 const BITMAP_BASE& image = refImage.GetImage();
4577 int legacyPPI = image.GetLegacyPPI();
4578
4579 if( legacyPPI > 0 && image.GetPPI() != legacyPPI )
4580 refImage.SetImageScale( refImage.GetImageScale() * image.GetPPI() / legacyPPI );
4581 }
4582
4583 return bitmap.release();
4584}
4585
4586
4588{
4589 std::unique_ptr<PCB_TEXT> text( aBaseText );
4590
4591 wxCHECK_MSG( CurTok() == T_gr_text || CurTok() == T_fp_text, nullptr,
4592 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_TEXT." ) );
4593
4594 FOOTPRINT* parentFP = dynamic_cast<FOOTPRINT*>( aParent );
4595
4596 T token = NextTok();
4597
4598 if( !text && parentFP )
4599 {
4600 switch( token )
4601 {
4602 case T_reference:
4603 text = std::make_unique<PCB_FIELD>( parentFP, FIELD_T::REFERENCE );
4604 break;
4605
4606 case T_value:
4607 text = std::make_unique<PCB_FIELD>( parentFP, FIELD_T::VALUE );
4608 break;
4609
4610 case T_user:
4611 text = std::make_unique<PCB_TEXT>( parentFP );
4612 break;
4613
4614 default:
4615 THROW_IO_ERRORF( _( "Cannot handle footprint text type %s" ), FromUTF8() );
4616 }
4617
4618 token = NextTok();
4619 }
4620 else if( !text )
4621 {
4622 text = std::make_unique<PCB_TEXT>( aParent );
4623 }
4624
4625 // Legacy bare locked token
4626 if( token == T_locked )
4627 {
4628 text->SetLocked( true );
4629 token = NextTok();
4630 }
4631
4632 if( !IsSymbol( token ) && (int) token != DSN_NUMBER )
4633 Expecting( "text value" );
4634
4635 wxString value = FromUTF8();
4636 value.Replace( wxT( "%V" ), wxT( "${VALUE}" ) );
4637 value.Replace( wxT( "%R" ), wxT( "${REFERENCE}" ) );
4638 text->SetText( value );
4639
4640 NeedLEFT();
4641
4642 parsePCB_TEXT_effects( text.get(), aBaseText );
4643
4644 if( parentFP )
4645 {
4646 // Convert hidden footprint text (which is no longer supported) into a hidden field
4647 if( !text->IsVisible() && text->Type() == PCB_TEXT_T )
4648 {
4649 wxString fieldName = GetUserFieldName( parentFP->GetFields().size(), UNTRANSLATED );
4650 return new PCB_FIELD( *text.get(), FIELD_T::USER, fieldName );
4651 }
4652 }
4653 else
4654 {
4655 // Hidden PCB text is no longer supported
4656 text->SetVisible( true );
4657 }
4658
4659 return text.release();
4660}
4661
4662
4664{
4665 FOOTPRINT* parentFP = dynamic_cast<FOOTPRINT*>( aText->GetParent() );
4666 bool sawEffects = false;
4667 bool hasAngle = false; // Old files do not have a angle specified.
4668 // in this case it is 0 expected to be 0
4669 bool hasPos = false;
4670
4671 // By default, texts in footprints have a locked rotation (i.e. rot = -90 ... 90 deg)
4672 if( parentFP )
4673 aText->SetKeepUpright( true );
4674
4675 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
4676 {
4677 if( token == T_LEFT )
4678 token = NextTok();
4679
4680 switch( token )
4681 {
4682 case T_at:
4683 {
4684 VECTOR2I pt;
4685
4686 hasPos = true;
4687 pt.x = parseBoardUnits( "X coordinate" );
4688 pt.y = parseBoardUnits( "Y coordinate" );
4689
4690 if( parentFP && m_requiredVersion >= FIRST_FP_AFFINE_TRANSFORM )
4691 aText->SetLibTextPos( pt );
4692 else
4693 aText->SetTextPos( pt );
4694 token = NextTok();
4695
4696 if( CurTok() == T_NUMBER )
4697 {
4699 hasAngle = true;
4700 token = NextTok();
4701 }
4702
4703 // Legacy location of this token; presence implies true
4704 if( parentFP && CurTok() == T_unlocked )
4705 {
4706 aText->SetKeepUpright( false );
4707 token = NextTok();
4708 }
4709
4710 if( (int) token != DSN_RIGHT )
4711 Expecting( DSN_RIGHT );
4712
4713 break;
4714 }
4715
4716 case T_layer:
4717 aText->SetLayer( parseBoardItemLayer() );
4718
4719 token = NextTok();
4720
4721 if( token == T_knockout )
4722 {
4723 aText->SetIsKnockout( true );
4724 token = NextTok();
4725 }
4726
4727 if( (int) token != DSN_RIGHT )
4728 Expecting( DSN_RIGHT );
4729
4730 break;
4731
4732 case T_tstamp:
4733 case T_uuid:
4734 NextTok();
4735 aText->SetUuidDirect( CurStrToKIID() );
4736 NeedRIGHT();
4737 break;
4738
4739 case T_hide:
4740 {
4741 // In older files, the hide token appears bare, and indicates hide==true.
4742 // In newer files, it will be an explicit bool in a list like (hide yes)
4743 bool hide = parseMaybeAbsentBool( true );
4744
4745 if( parentFP )
4746 aText->SetVisible( !hide );
4747 else
4748 Expecting( "layer, effects, locked, render_cache, uuid or tstamp" );
4749
4750 break;
4751 }
4752
4753 case T_locked:
4754 // Newer list-enclosed locked
4755 aText->SetLocked( parseBool() );
4756 NeedRIGHT();
4757 break;
4758
4759 // Confusingly, "unlocked" is not the opposite of "locked", but refers to "keep upright"
4760 case T_unlocked:
4761 if( parentFP )
4762 aText->SetKeepUpright( !parseBool() );
4763 else
4764 Expecting( "layer, effects, locked, render_cache or tstamp" );
4765
4766 NeedRIGHT();
4767 break;
4768
4769 case T_effects:
4770 sawEffects = true;
4771 parseEDA_TEXT( static_cast<EDA_TEXT*>( aText ) );
4772 break;
4773
4774 case T_render_cache:
4775 parseRenderCache( static_cast<EDA_TEXT*>( aText ) );
4776 break;
4777
4778 case T_custom_property:
4779 parseCustomProperty( aText );
4780 break;
4781
4782 default:
4783 if( parentFP )
4784 Expecting( "layer, hide, effects, locked, render_cache, tstamp, uuid, or custom_property" );
4785 else
4786 Expecting( "layer, effects, locked, render_cache, tstamp, uuid, or custom_property" );
4787 }
4788 }
4789
4790 // If there is no orientation defined, then it is the default value of 0 degrees.
4791 if( !hasAngle )
4792 aText->SetTextAngle( ANGLE_0 );
4793
4794 if( parentFP && !dynamic_cast<PCB_DIMENSION_BASE*>( aBaseText ) && m_requiredVersion < FIRST_FP_AFFINE_TRANSFORM )
4795 {
4796 // Legacy files stored an absolute board-frame angle and an FP-relative
4797 // position with the parent FP transform un-applied. Rotate and move
4798 // the text into board coordinates.
4799 aText->SetTextAngle( aText->GetTextAngle() - parentFP->GetOrientation() );
4800 aText->Rotate( { 0, 0 }, parentFP->GetOrientation() );
4801
4802 // Only move offset from parent position if we read a position from the file.
4803 // These positions are relative to the parent footprint. If we don't have a position
4804 // then the text defaults to the parent position and moving again will double it.
4805 if( hasPos )
4806 aText->Move( parentFP->GetPosition() );
4807 }
4808
4809 if( parentFP && !dynamic_cast<PCB_DIMENSION_BASE*>( aBaseText ) && m_requiredVersion >= FIRST_FP_AFFINE_TRANSFORM )
4810 {
4811 aText->SetLibTextSize( aText->GetTextSize() );
4812
4813 if( !aText->GetAutoThickness() )
4814 aText->SetLibTextThickness( aText->GetTextThickness() );
4815 }
4816
4817 return sawEffects;
4818}
4819
4820
4822{
4823 wxCHECK_MSG( CurTok() == T_barcode, nullptr,
4824 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_BARCODE." ) );
4825
4826 std::unique_ptr<PCB_BARCODE> barcode = std::make_unique<PCB_BARCODE>( aParent );
4827
4828 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
4829 {
4830 if( token != T_LEFT )
4831 Expecting( T_LEFT );
4832
4833 token = NextTok();
4834
4835 switch( token )
4836 {
4837 case T_at:
4838 {
4839 VECTOR2I pos;
4840 pos.x = parseBoardUnits( "X coordinate" );
4841 pos.y = parseBoardUnits( "Y coordinate" );
4842 barcode->SetPosition( pos );
4843 token = NextTok();
4844
4845 if( CurTok() == T_NUMBER )
4846 barcode->SetOrientation( parseDouble() );
4847
4848 NeedRIGHT();
4849 break;
4850 }
4851
4852 case T_layer:
4853 barcode->SetLayer( parseBoardItemLayer() );
4854 NeedRIGHT();
4855 break;
4856
4857 case T_size:
4858 {
4859 int w = parseBoardUnits( "barcode width" );
4860 int h = parseBoardUnits( "barcode height" );
4861 barcode->SetWidth( w );
4862 barcode->SetHeight( h );
4863 NeedRIGHT();
4864 break;
4865 }
4866
4867 case T_text:
4868 if( NextTok() != T_STRING )
4869 Expecting( T_STRING );
4870
4871 barcode->SetText( FromUTF8() );
4872 NeedRIGHT();
4873 break;
4874
4875 case T_text_height:
4876 {
4877 int h = parseBoardUnits( "barcode text height" );
4878 barcode->SetTextSize( h );
4879 NeedRIGHT();
4880 break;
4881 }
4882
4883 case T_type:
4884 NeedSYMBOL();
4885 {
4886 std::string kind = CurText();
4887 if( kind == "code39" )
4888 barcode->SetKind( BARCODE_T::CODE_39 );
4889 else if( kind == "code128" )
4890 barcode->SetKind( BARCODE_T::CODE_128 );
4891 else if( kind == "datamatrix" || kind == "data_matrix" )
4892 barcode->SetKind( BARCODE_T::DATA_MATRIX );
4893 else if( kind == "qr" || kind == "qrcode" )
4894 barcode->SetKind( BARCODE_T::QR_CODE );
4895 else if( kind == "microqr" || kind == "micro_qr" )
4896 barcode->SetKind( BARCODE_T::MICRO_QR_CODE );
4897 else
4898 Expecting( "barcode type" );
4899 }
4900 NeedRIGHT();
4901 break;
4902
4903 case T_ecc_level:
4904 NeedSYMBOL();
4905 {
4906 std::string ecc = CurText();
4907 if( ecc == "L" || ecc == "l" )
4908 barcode->SetErrorCorrection( BARCODE_ECC_T::L );
4909 else if( ecc == "M" || ecc == "m" )
4910 barcode->SetErrorCorrection( BARCODE_ECC_T::M );
4911 else if( ecc == "Q" || ecc == "q" )
4912 barcode->SetErrorCorrection( BARCODE_ECC_T::Q );
4913 else if( ecc == "H" || ecc == "h" )
4914 barcode->SetErrorCorrection( BARCODE_ECC_T::H );
4915 else
4916 Expecting( "ecc level" );
4917 }
4918 NeedRIGHT();
4919 break;
4920
4921
4922 case T_locked:
4923 barcode->SetLocked( parseMaybeAbsentBool( true ) );
4924 break;
4925
4926 case T_tstamp:
4927 case T_uuid:
4928 NextTok();
4929 barcode->SetUuidDirect( CurStrToKIID() );
4930 NeedRIGHT();
4931 break;
4932
4933 case T_hide:
4934 barcode->SetShowText( !parseBool() );
4935 NeedRIGHT();
4936 break;
4937
4938 case T_knockout:
4939 barcode->SetIsKnockout( parseBool() );
4940 NeedRIGHT();
4941 break;
4942
4943 case T_margins:
4944 {
4945 int marginX = parseBoardUnits( "margin X" );
4946 int marginY = parseBoardUnits( "margin Y" );
4947 barcode->SetMargin( VECTOR2I( marginX, marginY ) );
4948 NeedRIGHT();
4949 break;
4950 }
4951
4952 case T_custom_property:
4953 parseCustomProperty( barcode.get() );
4954 break;
4955
4956 default:
4957 Expecting( "at, layer, size, text, text_height, type, ecc_level, locked, hide, knockout, margins, "
4958 "uuid, or custom_property" );
4959 }
4960 }
4961
4962 barcode->AssembleBarcode();
4963
4964 return barcode.release();
4965}
4966
4967
4973{
4974 aTextBox->SetLibTextAngle( aTextBox->EDA_TEXT::GetTextAngle() );
4975
4976 if( aTextBox->GetShape() == SHAPE_T::RECTANGLE )
4977 aTextBox->OverrideLibCoords( aTextBox->GetStart(), aTextBox->GetEnd() );
4978 else if( aTextBox->GetShape() == SHAPE_T::POLY )
4979 aTextBox->OverrideLibPoly( aTextBox->GetPolyShape() );
4980
4981 if( aTextBox->GetParentFootprint() )
4982 aTextBox->OnFootprintTransformed();
4983
4984 // Sync the EDA_TEXT angle cache to the absolute board angle.
4985 aTextBox->EDA_TEXT::SetTextAngle( aTextBox->GetTextAngle() );
4986}
4987
4988
4990{
4991 wxCHECK_MSG( CurTok() == T_gr_text_box || CurTok() == T_fp_text_box, nullptr,
4992 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_TEXTBOX." ) );
4993
4994 std::unique_ptr<PCB_TEXTBOX> textbox = std::make_unique<PCB_TEXTBOX>( aParent );
4995
4996 parseTextBoxContent( textbox.get() );
4997 bakeTextBoxLib( textbox.get() );
4998
4999 return textbox.release();
5000}
5001
5002
5004{
5005 wxCHECK_MSG( CurTok() == T_table_cell, nullptr,
5006 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a table cell." ) );
5007
5008 std::unique_ptr<PCB_TABLECELL> cell = std::make_unique<PCB_TABLECELL>( aParent );
5009
5010 parseTextBoxContent( cell.get() );
5011 bakeTextBoxLib( cell.get() );
5012
5013 return cell.release();
5014}
5015
5016
5018{
5019 int left;
5020 int top;
5021 int right;
5022 int bottom;
5023 STROKE_PARAMS stroke( -1, LINE_STYLE::SOLID );
5024 bool foundMargins = false;
5025
5026 T token = NextTok();
5027
5028 // Legacy locked
5029 if( token == T_locked )
5030 {
5031 aTextBox->SetLocked( true );
5032 token = NextTok();
5033 }
5034
5035 if( !IsSymbol( token ) && (int) token != DSN_NUMBER )
5036 Expecting( "text value" );
5037
5038 aTextBox->SetText( FromUTF8() );
5039
5040 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5041 {
5042 if( token != T_LEFT )
5043 Expecting( T_LEFT );
5044
5045 token = NextTok();
5046
5047 switch( token )
5048 {
5049 case T_locked:
5050 aTextBox->SetLocked( parseMaybeAbsentBool( true ) );
5051 break;
5052
5053 case T_start:
5054 {
5055 int x = parseBoardUnits( "X coordinate" );
5056 int y = parseBoardUnits( "Y coordinate" );
5057 aTextBox->SetStart( VECTOR2I( x, y ) );
5058 NeedRIGHT();
5059
5060 NeedLEFT();
5061 token = NextTok();
5062
5063 if( token != T_end )
5064 Expecting( T_end );
5065
5066 x = parseBoardUnits( "X coordinate" );
5067 y = parseBoardUnits( "Y coordinate" );
5068 aTextBox->SetEnd( VECTOR2I( x, y ) );
5069 NeedRIGHT();
5070 break;
5071 }
5072
5073 case T_pts:
5074 aTextBox->SetShape( SHAPE_T::POLY );
5075 aTextBox->GetPolyShape().RemoveAllContours();
5076 aTextBox->GetPolyShape().NewOutline();
5077
5078 while( (token = NextTok() ) != T_RIGHT )
5079 parseOutlinePoints( aTextBox->GetPolyShape().Outline( 0 ) );
5080
5081 break;
5082
5083 case T_angle:
5084 // Set the angle of the text only, the coordinates of the box (a polygon) are
5085 // already at the right position, and must not be rotated
5086 aTextBox->EDA_TEXT::SetTextAngle( EDA_ANGLE( parseDouble( "text box angle" ), DEGREES_T ) );
5087 NeedRIGHT();
5088 break;
5089
5090 case T_stroke:
5091 {
5092 STROKE_PARAMS_PARSER strokeParser( reader, pcbIUScale.IU_PER_MM );
5093 strokeParser.SyncLineReaderWith( *this );
5094
5095 strokeParser.ParseStroke( stroke );
5096 SyncLineReaderWith( strokeParser );
5097 break;
5098 }
5099
5100 case T_border:
5101 aTextBox->SetBorderEnabled( parseBool() );
5102 NeedRIGHT();
5103 break;
5104
5105 case T_margins:
5106 parseMargins( left, top, right, bottom );
5107 aTextBox->SetMarginLeft( left );
5108 aTextBox->SetMarginTop( top );
5109 aTextBox->SetMarginRight( right );
5110 aTextBox->SetMarginBottom( bottom );
5111 foundMargins = true;
5112 NeedRIGHT();
5113 break;
5114
5115 case T_layer:
5116 aTextBox->SetLayer( parseBoardItemLayer() );
5117 NeedRIGHT();
5118 break;
5119
5120 case T_knockout:
5121 aTextBox->SetIsKnockout( parseBool() );
5122 NeedRIGHT();
5123 break;
5124
5125 case T_span:
5126 if( PCB_TABLECELL* cell = dynamic_cast<PCB_TABLECELL*>( aTextBox ) )
5127 {
5128 cell->SetColSpan( parseInt( "column span" ) );
5129 cell->SetRowSpan( parseInt( "row span" ) );
5130 }
5131 else
5132 {
5133 Expecting( "locked, start, pts, angle, width, stroke, border, margins, knockout, "
5134 "layer, effects, render_cache, uuid or tstamp" );
5135 }
5136
5137 NeedRIGHT();
5138 break;
5139
5140 case T_tstamp:
5141 case T_uuid:
5142 NextTok();
5143 aTextBox->SetUuidDirect( CurStrToKIID() );
5144 NeedRIGHT();
5145 break;
5146
5147 case T_effects:
5148 parseEDA_TEXT( static_cast<EDA_TEXT*>( aTextBox ) );
5149 break;
5150
5151 case T_render_cache:
5152 parseRenderCache( static_cast<EDA_TEXT*>( aTextBox ) );
5153 break;
5154
5155 case T_custom_property:
5156 parseCustomProperty( aTextBox );
5157 break;
5158
5159 default:
5160 if( dynamic_cast<PCB_TABLECELL*>( aTextBox ) != nullptr )
5161 {
5162 Expecting( "locked, start, pts, angle, width, margins, knockout, layer, effects, "
5163 "span, render_cache, uuid, tstamp, or custom_property" );
5164 }
5165 else
5166 {
5167 Expecting( "locked, start, pts, angle, width, stroke, border, margins, knockout,"
5168 "layer, effects, render_cache, uuid, tstamp, or custom_property" );
5169 }
5170 }
5171 }
5172
5173 aTextBox->SetStroke( stroke );
5174
5175 if( m_requiredVersion < 20230825 ) // compat, we move to an explicit flag
5176 aTextBox->SetBorderEnabled( stroke.GetWidth() >= 0 );
5177
5178 if( !foundMargins )
5179 {
5180 int margin = aTextBox->GetLegacyTextMargin();
5181 aTextBox->SetMarginLeft( margin );
5182 aTextBox->SetMarginTop( margin );
5183 aTextBox->SetMarginRight( margin );
5184 aTextBox->SetMarginBottom( margin );
5185 }
5186}
5187
5188
5189// A drill chart offers its own tokens first and shares the rest, so identity is accepted
5190// only for the plain table form
5191bool PCB_IO_KICAD_SEXPR_PARSER::parseTableBodyToken( PCB_TABLE* aTable, T aToken, bool aAllowIdentity )
5192{
5193 PCB_TABLE* table = aTable;
5194 T token = aToken;
5195
5196 switch( aToken )
5197 {
5198 case T_column_count:
5199 table->SetColCount( parseInt( "column count" ) );
5200 NeedRIGHT();
5201 return true;
5202
5203 case T_uuid:
5204 if( !aAllowIdentity )
5205 Expecting( "table geometry without identity" );
5206
5207 NextTok();
5208 table->SetUuidDirect( CurStrToKIID() );
5209 NeedRIGHT();
5210 return true;
5211
5212 case T_locked:
5213 if( !aAllowIdentity )
5214 Expecting( "table geometry without identity" );
5215
5216 table->SetLocked( parseBool() );
5217 NeedRIGHT();
5218 return true;
5219
5220 case T_angle: // legacy token no longer used
5221 NeedRIGHT();
5222 return true;
5223
5224 case T_layer:
5225 if( !aAllowIdentity )
5226 Expecting( "table geometry without identity" );
5227
5228 table->SetLayer( parseBoardItemLayer() );
5229 NeedRIGHT();
5230 return true;
5231
5232 case T_column_widths:
5233 {
5234 int col = 0;
5235
5236 while( ( token = NextTok() ) != T_RIGHT )
5237 table->SetColWidth( col++, parseBoardUnits() );
5238
5239 return true;
5240 }
5241
5242 case T_row_heights:
5243 {
5244 int row = 0;
5245
5246 while( ( token = NextTok() ) != T_RIGHT )
5247 table->SetRowHeight( row++, parseBoardUnits() );
5248
5249 return true;
5250 }
5251
5252 case T_cells:
5253 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5254 {
5255 if( token != T_LEFT )
5256 Expecting( T_LEFT );
5257
5258 token = NextTok();
5259
5260 if( token != T_table_cell )
5261 Expecting( "table_cell" );
5262
5263 table->AddCell( parsePCB_TABLECELL( table ) );
5264 }
5265
5266 return true;
5267
5268 case T_border:
5269 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5270 {
5271 if( token != T_LEFT )
5272 Expecting( T_LEFT );
5273
5274 token = NextTok();
5275
5276 switch( token )
5277 {
5278 case T_external:
5279 table->SetStrokeExternal( parseBool() );
5280 NeedRIGHT();
5281 break;
5282
5283 case T_header:
5284 table->SetStrokeHeaderSeparator( parseBool() );
5285 NeedRIGHT();
5286 break;
5287
5288 case T_stroke:
5289 {
5290 STROKE_PARAMS_PARSER strokeParser( reader, pcbIUScale.IU_PER_MM );
5291 strokeParser.SyncLineReaderWith( *this );
5292
5293 STROKE_PARAMS borderStroke( -1, LINE_STYLE::SOLID );
5294 strokeParser.ParseStroke( borderStroke );
5295 SyncLineReaderWith( strokeParser );
5296
5297 table->SetBorderStroke( borderStroke );
5298 break;
5299 }
5300
5301 default:
5302 Expecting( "external, header or stroke" );
5303 break;
5304 }
5305 }
5306
5307 return true;
5308
5309 case T_separators:
5310 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5311 {
5312 if( token != T_LEFT )
5313 Expecting( T_LEFT );
5314
5315 token = NextTok();
5316
5317 switch( token )
5318 {
5319 case T_rows:
5320 table->SetStrokeRows( parseBool() );
5321 NeedRIGHT();
5322 break;
5323
5324 case T_cols:
5325 table->SetStrokeColumns( parseBool() );
5326 NeedRIGHT();
5327 break;
5328
5329 case T_stroke:
5330 {
5331 STROKE_PARAMS_PARSER strokeParser( reader, pcbIUScale.IU_PER_MM );
5332 strokeParser.SyncLineReaderWith( *this );
5333
5334 STROKE_PARAMS separatorsStroke( -1, LINE_STYLE::SOLID );
5335 strokeParser.ParseStroke( separatorsStroke );
5336 SyncLineReaderWith( strokeParser );
5337
5338 table->SetSeparatorsStroke( separatorsStroke );
5339 break;
5340 }
5341
5342 default:
5343 Expecting( "rows, cols, or stroke" );
5344 break;
5345 }
5346 }
5347
5348 return true;
5349
5350 case T_custom_property:
5352 return true;
5353
5354 default:
5355 return false;
5356 }
5357}
5358
5359
5360void PCB_IO_KICAD_SEXPR_PARSER::parseTableBody( PCB_TABLE* aTable, bool aAllowIdentity )
5361{
5362 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
5363 {
5364 if( token != T_LEFT )
5365 Expecting( T_LEFT );
5366
5367 token = NextTok();
5368
5369 if( !parseTableBodyToken( aTable, token, aAllowIdentity ) )
5370 Expecting( "columns, layer, col_widths, row_heights, border, separators, header or cells" );
5371 }
5372}
5373
5374
5376{
5377 wxString name = FromUTF8();
5378 const PCB_LAYER_ID startLayer = static_cast<PCB_LAYER_ID>( LSET::NameToLayer( name ) );
5379
5380 NeedSYMBOLorNUMBER();
5381 name = FromUTF8();
5382 const PCB_LAYER_ID endLayer = static_cast<PCB_LAYER_ID>( LSET::NameToLayer( name ) );
5383
5384 bool backdrill = false;
5385 bool nonPlated = false;
5386
5387 // The flags are what tell a backdrill span apart from the primary span sharing its layer
5388 // pair, so a map without them comes back pointing at the wrong holes
5389 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
5390 {
5391 if( token == T_backdrill )
5392 backdrill = true;
5393 else if( token == T_npth )
5394 nonPlated = true;
5395 }
5396
5397 return DRILL_SPAN( startLayer, endLayer, backdrill, nonPlated );
5398}
5399
5400
5402{
5403 wxCHECK_MSG( CurTok() == T_drill_map, nullptr,
5404 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a drill map." ) );
5405
5406 std::unique_ptr<PCB_DRILL_MAP> map = std::make_unique<PCB_DRILL_MAP>( aParent );
5407
5408 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
5409 {
5410 if( token != T_LEFT )
5411 Expecting( T_LEFT );
5412
5413 token = NextTok();
5414
5415 switch( token )
5416 {
5417 case T_uuid:
5418 NextTok();
5419 map->SetUuidDirect( CurStrToKIID() );
5420 NeedRIGHT();
5421 break;
5422
5423 case T_locked:
5424 map->SetLocked( parseBool() );
5425 NeedRIGHT();
5426 break;
5427
5428 case T_layer:
5429 map->SetLayer( parseBoardItemLayer() );
5430 NeedRIGHT();
5431 break;
5432
5433 case T_offset:
5434 {
5435 VECTOR2I offset;
5436 offset.x = parseBoardUnits( "drill map x offset" );
5437 offset.y = parseBoardUnits( "drill map y offset" );
5438 map->SetOffset( offset );
5439 NeedRIGHT();
5440 break;
5441 }
5442
5443 case T_size:
5444 map->SetSymbolSize( parseBoardUnits( "drill map symbol size" ) );
5445 NeedRIGHT();
5446 break;
5447
5448 case T_span:
5449 {
5450 NextTok();
5451
5452 if( CurTok() == T_all )
5453 {
5454 map->SetAllSpans( true );
5455 NeedRIGHT();
5456 }
5457 else
5458 {
5459 map->SetAllSpans( false );
5460 map->SetSpan( parseDrillSpanBody() );
5461 }
5462
5463 break;
5464 }
5465
5466 case T_outline_slots:
5467 map->SetOutlineSlots( parseBool() );
5468 NeedRIGHT();
5469 break;
5470
5471 case T_guide_cross:
5472 map->SetGuideCross( parseBool() );
5473 NeedRIGHT();
5474 break;
5475
5476 case T_custom_property:
5477 parseCustomProperty( map.get() );
5478 break;
5479
5480 default:
5481 skipCurrent();
5482 break;
5483 }
5484 }
5485
5486 if( !DocumentationLayers().Contains( map->GetLayer() ) )
5487 {
5488 THROW_IO_ERROR( _( "Invalid drill map: not on a documentation layer" ) );
5489 }
5490
5491 return map.release();
5492}
5493
5494
5495PCB_GENERATED_TABLE* PCB_IO_KICAD_SEXPR_PARSER::parseGeneratedTable( std::unique_ptr<PCB_GENERATED_TABLE> aTable )
5496{
5497 const GENERATED_TABLE_SCHEMA& schema = aTable->Schema();
5498
5499 // The file's columns replace the defaults a new table starts with rather than adding to them
5500 std::vector<GENERATED_TABLE_COLUMN> columns;
5501
5502 // The writer omits units and precision equal to these, whatever the constructor chose
5503 aTable->SetUnits( schema.DefaultUnits() );
5504 aTable->SetPrecision( schema.DefaultPrecision() );
5505
5506 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
5507 {
5508 if( token != T_LEFT )
5509 Expecting( T_LEFT );
5510
5511 token = NextTok();
5512
5513 switch( token )
5514 {
5515 case T_uuid:
5516 NextTok();
5517 aTable->SetUuidDirect( CurStrToKIID() );
5518 NeedRIGHT();
5519 break;
5520
5521 case T_locked:
5522 aTable->SetLocked( parseBool() );
5523 NeedRIGHT();
5524 break;
5525
5526 case T_layer:
5527 aTable->SetLayer( parseBoardItemLayer() );
5528 NeedRIGHT();
5529 break;
5530
5531 case T_units:
5532 {
5533 NeedSYMBOLorNUMBER();
5535
5536 if( GeneratedTableUnitsFromToken( FromUTF8(), units ) )
5537 aTable->SetUnits( units );
5538
5539 NeedRIGHT();
5540 break;
5541 }
5542
5543 case T_precision:
5544 aTable->SetPrecision( parseInt( "generated table precision" ) );
5545 NeedRIGHT();
5546 break;
5547
5548 case T_column:
5549 {
5551
5552 // Not GENERATED_TABLE_COLUMN's default 0 (a schema's first id), or an unrecognized
5553 // id token that never sets it would silently become a real column instead of being
5554 // dropped by Validate() below as the unknown id it actually is
5555 col.m_Id = -1;
5556
5557 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5558 {
5559 if( token != T_LEFT )
5560 Expecting( T_LEFT );
5561
5562 token = NextTok();
5563
5564 switch( token )
5565 {
5566 case T_id:
5567 NeedSYMBOLorNUMBER();
5568
5569 if( const GENERATED_TABLE_COLUMN_DEF* def = schema.FindToken( FromUTF8() ) )
5570 {
5571 // The writer's own default is this literal, never DefaultColumn()'s
5572 // translated text, so a heading it left out reads back the same
5573 // regardless of which locale is active now
5574 col.m_Id = def->m_Id;
5575 col.m_Heading = wxString( def->m_Heading );
5576 col.m_Align = def->m_Align;
5577 }
5578
5579 NeedRIGHT();
5580 break;
5581
5582 case T_name:
5583 NeedSYMBOLorNUMBER();
5584 col.m_Heading = FromUTF8();
5585 NeedRIGHT();
5586 break;
5587
5588 case T_justify:
5589 NeedSYMBOLorNUMBER();
5590 GeneratedTableAlignFromToken( FromUTF8(), col.m_Align );
5591 NeedRIGHT();
5592 break;
5593
5594 case T_width:
5595 col.m_Width = parseBoardUnits( "generated table column width" );
5596 NeedRIGHT();
5597 break;
5598
5599 case T_hide:
5600 col.m_Visible = !parseBool();
5601 NeedRIGHT();
5602 break;
5603
5604 default:
5605 skipCurrent();
5606 break;
5607 }
5608 }
5609
5610 columns.push_back( col );
5611 break;
5612 }
5613
5614 case T_row_keys:
5615 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5616 {
5617 if( token != T_LEFT )
5618 Expecting( T_LEFT );
5619
5620 token = NextTok();
5621
5622 if( token == T_key )
5623 {
5624 const int row = parseInt( "row key row" );
5625
5626 NeedSYMBOLorNUMBER();
5627 aTable->RowKeys()[row] = curText;
5628 }
5629
5630 NeedRIGHT();
5631 }
5632
5633 break;
5634
5635 default:
5636 if( parseGeneratedTableExtra( aTable.get(), token ) )
5637 break;
5638
5639 // A generated table is a table, so whatever is left is the geometry and cells it
5640 // shares with one rather than something to skip
5641 if( !parseTableBodyToken( aTable.get(), token, false ) )
5642 skipCurrent();
5643
5644 break;
5645 }
5646 }
5647
5648 if( columns.empty() )
5649 columns = schema.Defaults();
5650
5651 const auto anyShown =
5652 []( const std::vector<GENERATED_TABLE_COLUMN>& aColumns )
5653 {
5654 return std::any_of( aColumns.begin(), aColumns.end(),
5655 []( const GENERATED_TABLE_COLUMN& aCol )
5656 {
5657 return aCol.m_Visible;
5658 } );
5659 };
5660
5661 // No columns leaves every later consumer dividing by the column count. Repeats and
5662 // implausible widths reach table geometry
5663 if( aTable->GetColCount() < 1 || !schema.Validate( columns ) || !anyShown( columns ) )
5664 {
5665 THROW_IO_ERROR( wxString::Format( _( "Invalid %s: bad column set" ), aTable->GetFriendlyName() ) );
5666 }
5667
5668 aTable->RestoreColumns( columns );
5669
5670 // Copper, silkscreen, mask, paste, adhesive, Edge.Cuts, Margin and courtyard are all
5671 // manufacturing inputs that table artwork would corrupt rather than document
5672 if( !DocumentationLayers().Contains( aTable->GetLayer() ) )
5673 {
5674 THROW_IO_ERROR( wxString::Format( _( "Invalid %s: not on a documentation layer" ),
5675 aTable->GetFriendlyName() ) );
5676 }
5677
5678 return aTable.release();
5679}
5680
5681
5683{
5684 switch( aTable->Type() )
5685 {
5686 case PCB_DRILL_CHART_T:
5687 {
5688 PCB_DRILL_CHART* chart = static_cast<PCB_DRILL_CHART*>( aTable );
5689
5690 switch( aToken )
5691 {
5692 case T_filter:
5693 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
5694 {
5695 if( token != T_LEFT )
5696 Expecting( T_LEFT );
5697
5698 token = NextTok();
5699
5700 switch( token )
5701 {
5702 case T_plated: chart->Filter().m_Plated = parseBool(); NeedRIGHT(); break;
5703 case T_npth: chart->Filter().m_NonPlated = parseBool(); NeedRIGHT(); break;
5704 case T_vias: chart->Filter().m_Vias = parseBool(); NeedRIGHT(); break;
5705 case T_slots: chart->Filter().m_Slots = parseBool(); NeedRIGHT(); break;
5706 case T_backdrill: chart->Filter().m_Backdrills = parseBool(); NeedRIGHT(); break;
5707 case T_castellated: chart->Filter().m_Castellated = parseBool(); NeedRIGHT(); break;
5708 default: skipCurrent(); break;
5709 }
5710 }
5711
5712 return true;
5713
5714 case T_totals:
5715 chart->RestoreShowTotals( parseBool() );
5716 NeedRIGHT();
5717 return true;
5718
5719 case T_row_shapes:
5720 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
5721 {
5722 if( token != T_LEFT )
5723 Expecting( T_LEFT );
5724
5725 token = NextTok();
5726
5727 if( token == T_column )
5728 {
5729 chart->SetSymbolColumn( parseInt( "symbol column" ) );
5730 }
5731 else if( token == T_shape )
5732 {
5733 const int row = parseInt( "row shape row" );
5734 chart->RowShapes()[row] = parseInt( "row shape index" );
5735 }
5736
5737 NeedRIGHT();
5738 }
5739
5740 return true;
5741
5742 default:
5743 return false;
5744 }
5745 }
5746
5747 default:
5748 return false;
5749 }
5750}
5751
5752
5754{
5755 wxCHECK_MSG( CurTok() == T_table, nullptr,
5756 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as a table." ) );
5757
5758 std::unique_ptr<PCB_TABLE> table = std::make_unique<PCB_TABLE>( aParent, -1 );
5759
5760 parseTableBody( table.get(), true );
5761
5762 return table.release();
5763}
5764
5765
5767{
5768 wxCHECK_MSG( CurTok() == T_dimension, nullptr,
5769 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as DIMENSION." ) );
5770
5771 T token;
5772 bool locked = false;
5773 std::unique_ptr<PCB_DIMENSION_BASE> dim;
5774
5775 token = NextTok();
5776
5777 // Free 'locked' token from 6.0/7.0 formats
5778 if( token == T_locked )
5779 {
5780 locked = true;
5781 token = NextTok();
5782 }
5783
5784 // skip value that used to be saved
5785 if( token != T_LEFT )
5786 NeedLEFT();
5787
5788 token = NextTok();
5789
5790 bool isLegacyDimension = false;
5791 bool isStyleKnown = false;
5792
5793 // Old format
5794 if( token == T_width )
5795 {
5796 isLegacyDimension = true;
5797 dim = std::make_unique<PCB_DIM_ALIGNED>( aParent );
5798 dim->SetLineThickness( parseBoardUnits( "dimension width value" ) );
5799 NeedRIGHT();
5800 }
5801 else
5802 {
5803 if( token != T_type )
5804 Expecting( T_type );
5805
5806 switch( NextTok() )
5807 {
5808 case T_aligned: dim = std::make_unique<PCB_DIM_ALIGNED>( aParent ); break;
5809 case T_orthogonal: dim = std::make_unique<PCB_DIM_ORTHOGONAL>( aParent ); break;
5810 case T_leader: dim = std::make_unique<PCB_DIM_LEADER>( aParent ); break;
5811 case T_center: dim = std::make_unique<PCB_DIM_CENTER>( aParent ); break;
5812 case T_radial: dim = std::make_unique<PCB_DIM_RADIAL>( aParent ); break;
5813 default: wxFAIL_MSG( wxT( "Cannot parse unknown dimension type " ) + GetTokenString( CurTok() ) );
5814 }
5815
5816 NeedRIGHT();
5817
5818 // Before parsing further, set default properites for old KiCad file
5819 // versions that didnt have these properties:
5820 dim->SetArrowDirection( DIM_ARROW_DIRECTION::OUTWARD );
5821 }
5822
5823 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5824 {
5825 if( token != T_LEFT )
5826 Expecting( T_LEFT );
5827
5828 token = NextTok();
5829
5830 switch( token )
5831 {
5832 case T_layer:
5833 dim->SetLayer( parseBoardItemLayer() );
5834 NeedRIGHT();
5835 break;
5836
5837 case T_tstamp:
5838 case T_uuid:
5839 NextTok();
5840 dim->SetUuidDirect( CurStrToKIID() );
5841 NeedRIGHT();
5842 break;
5843
5844 case T_gr_text:
5845 {
5846 // In old pcb files, when parsing the text we do not yet know
5847 // if the text is kept aligned or not, and its DIM_TEXT_POSITION option.
5848 // Leave the text not aligned for now to read the text angle, and no
5849 // constraint for DIM_TEXT_POSITION in this case.
5850 // It will be set aligned (or not) later
5851 bool is_aligned = dim->GetKeepTextAligned();
5852 DIM_TEXT_POSITION t_dim_pos = dim->GetTextPositionMode();
5853
5854 if( !isStyleKnown )
5855 {
5856 dim->SetTextPositionMode( DIM_TEXT_POSITION::MANUAL );
5857 dim->SetKeepTextAligned( false );
5858 }
5859
5860 dim.reset( static_cast<PCB_DIMENSION_BASE*>( parsePCB_TEXT( m_board, dim.release() ) ) );
5861
5862 if( isLegacyDimension )
5863 {
5864 EDA_UNITS units = EDA_UNITS::MM;
5865
5866 if( !EDA_UNIT_UTILS::FetchUnitsFromString( dim->GetText(), units ) )
5867 dim->SetAutoUnits( true ); //Not determined => use automatic units
5868
5869 dim->SetUnits( units );
5870 }
5871
5872 if( !isStyleKnown )
5873 {
5874 dim->SetKeepTextAligned( is_aligned );
5875 dim->SetTextPositionMode( t_dim_pos );
5876 }
5877 break;
5878 }
5879
5880 // New format: feature points
5881 case T_pts:
5882 {
5883 VECTOR2I point;
5884
5885 parseXY( &point.x, &point.y );
5886 dim->SetStart( point );
5887 parseXY( &point.x, &point.y );
5888 dim->SetEnd( point );
5889
5890 NeedRIGHT();
5891 break;
5892 }
5893
5894 case T_height:
5895 {
5896 int height = parseBoardUnits( "dimension height value" );
5897 NeedRIGHT();
5898
5899 if( dim->Type() == PCB_DIM_ORTHOGONAL_T || dim->Type() == PCB_DIM_ALIGNED_T )
5900 {
5901 PCB_DIM_ALIGNED* aligned = static_cast<PCB_DIM_ALIGNED*>( dim.get() );
5902 aligned->SetHeight( height );
5903 }
5904
5905 break;
5906 }
5907
5908 case T_leader_length:
5909 {
5910 int length = parseBoardUnits( "leader length value" );
5911 NeedRIGHT();
5912
5913 if( dim->Type() == PCB_DIM_RADIAL_T )
5914 {
5915 PCB_DIM_RADIAL* radial = static_cast<PCB_DIM_RADIAL*>( dim.get() );
5916 radial->SetLeaderLength( length );
5917 }
5918
5919 break;
5920 }
5921
5922 case T_orientation:
5923 {
5924 int orientation = parseInt( "orthogonal dimension orientation" );
5925 NeedRIGHT();
5926
5927 if( dim->Type() == PCB_DIM_ORTHOGONAL_T )
5928 {
5929 PCB_DIM_ORTHOGONAL* ortho = static_cast<PCB_DIM_ORTHOGONAL*>( dim.get() );
5930 orientation = std::clamp( orientation, 0, 1 );
5931 ortho->SetOrientation( static_cast<PCB_DIM_ORTHOGONAL::DIR>( orientation ) );
5932 }
5933
5934 break;
5935 }
5936
5937 case T_format:
5938 {
5939 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
5940 {
5941 switch( token )
5942 {
5943 case T_LEFT:
5944 continue;
5945
5946 case T_prefix:
5947 NeedSYMBOLorNUMBER();
5948 dim->SetPrefix( FromUTF8() );
5949 NeedRIGHT();
5950 break;
5951
5952 case T_suffix:
5953 NeedSYMBOLorNUMBER();
5954 dim->SetSuffix( FromUTF8() );
5955 NeedRIGHT();
5956 break;
5957
5958 case T_units:
5959 {
5960 int mode = parseInt( "dimension units mode" );
5961 mode = std::max( 0, std::min( 4, mode ) );
5962 dim->SetUnitsMode( static_cast<DIM_UNITS_MODE>( mode ) );
5963 NeedRIGHT();
5964 break;
5965 }
5966
5967 case T_units_format:
5968 {
5969 int format = parseInt( "dimension units format" );
5970 format = std::clamp( format, 0, 3 );
5971 dim->SetUnitsFormat( static_cast<DIM_UNITS_FORMAT>( format ) );
5972 NeedRIGHT();
5973 break;
5974 }
5975
5976 case T_precision:
5977 dim->SetPrecision( static_cast<DIM_PRECISION>( parseInt( "dimension precision" ) ) );
5978 NeedRIGHT();
5979 break;
5980
5981 case T_override_value:
5982 NeedSYMBOLorNUMBER();
5983 dim->SetOverrideTextEnabled( true );
5984 dim->SetOverrideText( FromUTF8() );
5985 NeedRIGHT();
5986 break;
5987
5988 case T_suppress_zeroes:
5989 dim->SetSuppressZeroes( parseMaybeAbsentBool( true ) );
5990 break;
5991
5992 default:
5993 std::cerr << "Unknown format token: " << GetTokenString( token ) << std::endl;
5994 Expecting( "prefix, suffix, units, units_format, precision, override_value, suppress_zeroes" );
5995 }
5996 }
5997 break;
5998 }
5999
6000 case T_style:
6001 {
6002 isStyleKnown = true;
6003
6004 // new format: default to keep text aligned off unless token is present
6005 dim->SetKeepTextAligned( false );
6006
6007 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6008 {
6009 switch( token )
6010 {
6011 case T_LEFT:
6012 continue;
6013
6014 case T_thickness:
6015 dim->SetLineThickness( parseBoardUnits( "extension line thickness value" ) );
6016 NeedRIGHT();
6017 break;
6018
6019 case T_arrow_direction:
6020 token = NextTok();
6021
6022 if( token == T_inward )
6023 dim->ChangeArrowDirection( DIM_ARROW_DIRECTION::INWARD );
6024 else if( token == T_outward )
6025 dim->ChangeArrowDirection( DIM_ARROW_DIRECTION::OUTWARD );
6026 else
6027 Expecting( "inward or outward" );
6028
6029 NeedRIGHT();
6030 break;
6031
6032 case T_arrow_length:
6033
6034 dim->SetArrowLength( parseBoardUnits( "arrow length value" ) );
6035 NeedRIGHT();
6036 break;
6037
6038 case T_text_position_mode:
6039 {
6040 int mode = parseInt( "text position mode" );
6041 mode = std::max( 0, std::min( 3, mode ) );
6042 dim->SetTextPositionMode( static_cast<DIM_TEXT_POSITION>( mode ) );
6043 NeedRIGHT();
6044 break;
6045 }
6046
6047 case T_extension_height:
6048 {
6049 PCB_DIM_ALIGNED* aligned = dynamic_cast<PCB_DIM_ALIGNED*>( dim.get() );
6050 wxCHECK_MSG( aligned, nullptr, wxT( "Invalid extension_height token" ) );
6051 aligned->SetExtensionHeight( parseBoardUnits( "extension height value" ) );
6052 NeedRIGHT();
6053 break;
6054 }
6055
6056 case T_extension_offset:
6057 dim->SetExtensionOffset( parseBoardUnits( "extension offset value" ) );
6058 NeedRIGHT();
6059 break;
6060
6061 case T_keep_text_aligned:
6062 dim->SetKeepTextAligned( parseMaybeAbsentBool( true ) );
6063 break;
6064
6065 case T_text_frame:
6066 {
6067 wxCHECK_MSG( dim->Type() == PCB_DIM_LEADER_T, nullptr, wxT( "Invalid text_frame token" ) );
6068
6069 PCB_DIM_LEADER* leader = static_cast<PCB_DIM_LEADER*>( dim.get() );
6070
6071 int textFrame = parseInt( "text frame mode" );
6072 textFrame = std::clamp( textFrame, 0, 3 );
6073 leader->SetTextBorder( static_cast<DIM_TEXT_BORDER>( textFrame ));
6074 NeedRIGHT();
6075 break;
6076 }
6077
6078 default:
6079 Expecting( "thickness, arrow_length, arrow_direction, text_position_mode, "
6080 "extension_height, extension_offset" );
6081 }
6082 }
6083
6084 break;
6085 }
6086
6087 // Old format: feature1 stores a feature line. We only care about the origin.
6088 case T_feature1:
6089 {
6090 NeedLEFT();
6091 token = NextTok();
6092
6093 if( token != T_pts )
6094 Expecting( T_pts );
6095
6096 VECTOR2I point;
6097
6098 parseXY( &point.x, &point.y );
6099 dim->SetStart( point );
6100
6101 parseXY( nullptr, nullptr ); // Ignore second point
6102 NeedRIGHT();
6103 NeedRIGHT();
6104 break;
6105 }
6106
6107 // Old format: feature2 stores a feature line. We only care about the end point.
6108 case T_feature2:
6109 {
6110 NeedLEFT();
6111 token = NextTok();
6112
6113 if( token != T_pts )
6114 Expecting( T_pts );
6115
6116 VECTOR2I point;
6117
6118 parseXY( &point.x, &point.y );
6119 dim->SetEnd( point );
6120
6121 parseXY( nullptr, nullptr ); // Ignore second point
6122
6123 NeedRIGHT();
6124 NeedRIGHT();
6125 break;
6126 }
6127
6128 case T_crossbar:
6129 {
6130 NeedLEFT();
6131 token = NextTok();
6132
6133 if( token == T_pts )
6134 {
6135 // If we have a crossbar, we know we're an old aligned dim
6136 PCB_DIM_ALIGNED* aligned = static_cast<PCB_DIM_ALIGNED*>( dim.get() );
6137
6138 // Old style: calculate height from crossbar
6139 VECTOR2I point1, point2;
6140 parseXY( &point1.x, &point1.y );
6141 parseXY( &point2.x, &point2.y );
6142 aligned->UpdateHeight( point2, point1 ); // Yes, backwards intentionally
6143 NeedRIGHT();
6144 }
6145
6146 NeedRIGHT();
6147 break;
6148 }
6149
6150 // Arrow: no longer saved; no-op
6151 case T_arrow1a:
6152 NeedLEFT();
6153 token = NextTok();
6154
6155 if( token != T_pts )
6156 Expecting( T_pts );
6157
6158 parseXY( nullptr, nullptr );
6159 parseXY( nullptr, nullptr );
6160 NeedRIGHT();
6161 NeedRIGHT();
6162 break;
6163
6164 // Arrow: no longer saved; no-op
6165 case T_arrow1b:
6166 NeedLEFT();
6167 token = NextTok();
6168
6169 if( token != T_pts )
6170 Expecting( T_pts );
6171
6172 parseXY( nullptr, nullptr );
6173 parseXY( nullptr, nullptr );
6174 NeedRIGHT();
6175 NeedRIGHT();
6176 break;
6177
6178 // Arrow: no longer saved; no-op
6179 case T_arrow2a:
6180 NeedLEFT();
6181 token = NextTok();
6182
6183 if( token != T_pts )
6184 Expecting( T_pts );
6185
6186 parseXY( nullptr, nullptr );
6187 parseXY( nullptr, nullptr );
6188 NeedRIGHT();
6189 NeedRIGHT();
6190 break;
6191
6192 // Arrow: no longer saved; no-op
6193 case T_arrow2b:
6194 NeedLEFT();
6195 token = NextTok();
6196
6197 if( token != T_pts )
6198 Expecting( T_pts );
6199
6200 parseXY( nullptr, nullptr );
6201 parseXY( nullptr, nullptr );
6202 NeedRIGHT();
6203 NeedRIGHT();
6204 break;
6205
6206 // Handle (locked yes) from modern times
6207 case T_locked:
6208 {
6209 // Unsure if we ever wrote out (locked) for dimensions, so use maybeAbsent just in case
6210 bool isLocked = parseMaybeAbsentBool( true );
6211 dim->SetLocked( isLocked );
6212 break;
6213 }
6214
6215 case T_custom_property:
6216 parseCustomProperty( dim.get() );
6217 break;
6218
6219 default:
6220 Expecting( "layer, tstamp, uuid, gr_text, feature1, feature2, crossbar, arrow1a, "
6221 "arrow1b, arrow2a, arrow2b, locked, or custom_property" );
6222 }
6223 }
6224
6225 if( locked )
6226 dim->SetLocked( true );
6227
6228 dim->Update();
6229
6230 return dim.release();
6231}
6232
6233
6234FOOTPRINT* PCB_IO_KICAD_SEXPR_PARSER::parseFOOTPRINT( wxArrayString* aInitialComments )
6235{
6236 try
6237 {
6238 return parseFOOTPRINT_unchecked( aInitialComments );
6239 }
6240 catch( const PARSE_ERROR& parse_error )
6241 {
6242 if( m_tooRecent )
6243 throw FUTURE_FORMAT_ERROR( parse_error, GetRequiredVersion() );
6244 else
6245 throw;
6246 }
6247}
6248
6249
6251{
6252 wxCHECK_MSG( CurTok() == T_module || CurTok() == T_footprint, nullptr,
6253 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as FOOTPRINT." ) );
6254
6255 wxString name;
6256 VECTOR2I pt;
6257 T token;
6258 LIB_ID fpid;
6259 int attributes = 0;
6260 double parsedScaleX = 1.0;
6261 double parsedScaleY = 1.0;
6262
6263 std::unique_ptr<FOOTPRINT> footprint = std::make_unique<FOOTPRINT>( m_board );
6264
6265 footprint->SetInitialComments( aInitialComments );
6266
6267 if( m_board )
6268 footprint->SetStaticComponentClass( m_board->GetComponentClassManager().GetNoneComponentClass() );
6269
6270 token = NextTok();
6271
6272 if( !IsSymbol( token ) && token != T_NUMBER )
6273 Expecting( "symbol|number" );
6274
6275 name = FromUTF8();
6276
6277 if( !name.IsEmpty() && fpid.Parse( name, true ) >= 0 )
6278 {
6279 THROW_IO_ERRORF( _( "Invalid footprint ID in\nfile: %s\nline: %d\noffset: %d." ),
6280 CurSource(), CurLineNumber(), CurOffset() );
6281 }
6282
6283 auto checkVersion =
6284 [&]()
6285 {
6287 throw FUTURE_FORMAT_ERROR( fmt::format( "{}", m_requiredVersion ), m_generatorVersion );
6288 };
6289
6290 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6291 {
6292 if( token == T_LEFT )
6293 token = NextTok();
6294
6295 switch( token )
6296 {
6297 case T_version:
6298 {
6299 // Theoretically a footprint nested in a PCB could declare its own version, though
6300 // as of writing this comment we don't do that. Just in case, take the greater
6301 // version.
6302 int this_version = parseInt( FromUTF8().mb_str( wxConvUTF8 ) );
6303 NeedRIGHT();
6304 m_requiredVersion = std::max( m_requiredVersion, this_version );
6306 SetKnowsBar( m_requiredVersion >= 20240706 ); // Bar token is known from this version
6307 footprint->SetFileFormatVersionAtLoad( this_version );
6308 break;
6309 }
6310
6311 case T_generator:
6312 // We currently ignore the generator when parsing. It is included in the file for manual
6313 // indication of where the footprint came from.
6314 NeedSYMBOL();
6315 NeedRIGHT();
6316 break;
6317
6318 case T_generator_version:
6319 NeedSYMBOL();
6320 m_generatorVersion = FromUTF8();
6321 NeedRIGHT();
6322
6323 // If the format includes a generator version, by this point we have enough info to
6324 // do the version check here
6325 checkVersion();
6326
6327 break;
6328
6329 case T_locked:
6330 footprint->SetLocked( parseMaybeAbsentBool( true ) );
6331 break;
6332
6333 case T_placed:
6334 footprint->SetIsPlaced( parseMaybeAbsentBool( true ) );
6335 break;
6336
6337 case T_layer:
6338 {
6339 // Footprints can be only on the front side or the back side.
6340 // but because we can find some stupid layer in file, ensure a
6341 // acceptable layer is set for the footprint
6343 footprint->SetLayer( layer == B_Cu ? B_Cu : F_Cu );
6344 NeedRIGHT();
6345 break;
6346 }
6347
6348 case T_stackup:
6349 parseFootprintStackup( *footprint );
6350 break;
6351
6352 case T_tedit:
6353 parseHex();
6354 NeedRIGHT();
6355 break;
6356
6357 case T_tstamp:
6358 case T_uuid:
6359 NextTok();
6360 footprint->SetUuidDirect( CurStrToKIID() );
6361 NeedRIGHT();
6362 break;
6363
6364 case T_at:
6365 pt.x = parseBoardUnits( "X coordinate" );
6366 pt.y = parseBoardUnits( "Y coordinate" );
6367 footprint->SetPosition( pt );
6368 token = NextTok();
6369
6370 if( token == T_NUMBER )
6371 {
6372 footprint->SetOrientation( EDA_ANGLE( parseDouble(), DEGREES_T ) );
6373 NeedRIGHT();
6374 }
6375 else if( token != T_RIGHT )
6376 {
6377 Expecting( T_RIGHT );
6378 }
6379
6380 break;
6381
6382 case T_transform:
6383 {
6384 VECTOR2I trsTranslate( 0, 0 );
6385 EDA_ANGLE trsRotate = ANGLE_0;
6386
6387 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6388 {
6389 if( token != T_LEFT )
6390 Expecting( T_LEFT );
6391
6392 token = NextTok();
6393
6394 switch( token )
6395 {
6396 case T_translate:
6397 trsTranslate.x = parseBoardUnits( "translate X" );
6398 trsTranslate.y = parseBoardUnits( "translate Y" );
6399 NeedRIGHT();
6400 break;
6401
6402 case T_rotate:
6403 trsRotate = EDA_ANGLE( parseDouble( "rotate angle" ), DEGREES_T );
6404 NeedRIGHT();
6405 break;
6406
6407 case T_scale:
6408 parsedScaleX = parseDouble( "scale X" );
6409 parsedScaleY = parseDouble( "scale Y" );
6410
6411 // Guard against corrupt files: a zero, negative, or non-finite
6412 // scale would make the footprint transform degenerate.
6413 if( !std::isfinite( parsedScaleX ) || parsedScaleX <= 0.0 )
6414 parsedScaleX = 1.0;
6415
6416 if( !std::isfinite( parsedScaleY ) || parsedScaleY <= 0.0 )
6417 parsedScaleY = 1.0;
6418
6419 NeedRIGHT();
6420 break;
6421
6422 default:
6423 Expecting( "translate, rotate, or scale" );
6424 }
6425 }
6426
6427 footprint->SetPosition( trsTranslate );
6428 footprint->SetOrientation( trsRotate );
6429 footprint->SetTransformScale( parsedScaleX, parsedScaleY );
6430 break;
6431 }
6432
6433 case T_descr:
6434 NeedSYMBOLorNUMBER(); // some symbols can be 0508, so a number is also a symbol here
6435 footprint->SetLibDescription( FromUTF8() );
6436 NeedRIGHT();
6437 break;
6438
6439 case T_tags:
6440 NeedSYMBOLorNUMBER(); // some symbols can be 0508, so a number is also a symbol here
6441 footprint->SetKeywords( FromUTF8() );
6442 NeedRIGHT();
6443 break;
6444
6445 case T_height:
6446 footprint->SetHeight( parseBoardUnits( "footprint height" ) );
6447 NeedRIGHT();
6448 break;
6449
6450 case T_property:
6451 {
6452 NeedSYMBOL();
6453 wxString pName = FromUTF8();
6454 NeedSYMBOL();
6455 wxString pValue = FromUTF8();
6456
6457 // Prior to PCB fields, we used to use properties for special values instead of
6458 // using (keyword_example "value")
6459 if( m_requiredVersion < 20230620 )
6460 {
6461 // Skip legacy non-field properties sent from symbols that should not be kept
6462 // in footprints.
6463 if( pName == "ki_keywords" || pName == "ki_locked" )
6464 {
6465 NeedRIGHT();
6466 break;
6467 }
6468
6469 // Description from symbol (not the fooprint library description stored in (descr) )
6470 // used to be stored as a reserved key value
6471 if( pName == "ki_description" )
6472 {
6473 footprint->GetField( FIELD_T::DESCRIPTION )->SetText( pValue );
6474 NeedRIGHT();
6475 break;
6476 }
6477
6478 // Sheet file and name used to be stored as properties invisible to the user
6479 if( pName == "Sheetfile" || pName == "Sheet file" )
6480 {
6481 footprint->SetSheetfile( pValue );
6482 NeedRIGHT();
6483 break;
6484 }
6485
6486 if( pName == "Sheetname" || pName == "Sheet name" )
6487 {
6488 footprint->SetSheetname( pValue );
6489 NeedRIGHT();
6490 break;
6491 }
6492 }
6493
6494 PCB_FIELD* field = nullptr;
6495 std::unique_ptr<PCB_FIELD> unusedField;
6496 bool newField = false;
6497
6498 // 8.0.0rc3 had a bug where these properties were mistakenly added to the footprint as
6499 // fields, this will remove them as fields but still correctly set the footprint filters
6500 if( pName == "ki_fp_filters" )
6501 {
6502 footprint->SetFilters( pValue );
6503
6504 // Use the text effect parsing function because it will handle ki_fp_filters as a
6505 // property with no text effects, but will also handle parsing the text effects.
6506 // We just drop the effects if they're present.
6507 unusedField = std::make_unique<PCB_FIELD>( footprint.get(), FIELD_T::USER );
6508 field = unusedField.get();
6509 }
6510 else if( pName == "Footprint" )
6511 {
6512 // Until V9, footprints had a Footprint field that usually (but not always)
6513 // duplicated the footprint's LIB_ID. In V9 this was removed. Parse it
6514 // like any other, but don't add it to anything.
6515 unusedField = std::make_unique<PCB_FIELD>( footprint.get(), FIELD_T::FOOTPRINT );
6516 field = unusedField.get();
6517 }
6518 else if( footprint->HasField( pName ) )
6519 {
6520 field = footprint->GetField( pName );
6521 field->SetText( pValue );
6522 }
6523 else
6524 {
6525 field = new PCB_FIELD( footprint.get(), FIELD_T::USER, pName );
6526 footprint->Add( field );
6527
6528 field->SetText( pValue );
6529 field->SetLayer( footprint->GetLayer() == F_Cu ? F_Fab : B_Fab );
6530
6531 newField = true;
6532 }
6533
6534 // Hide the field by default if it is a legacy field that did not have
6535 // text effects applied, since hide is a negative effect
6536 if( m_requiredVersion < 20230620 )
6537 field->SetVisible( false );
6538 else
6539 field->SetVisible( true );
6540
6541 bool sawEffects = parsePCB_TEXT_effects( field );
6542
6543 // Fields too old to carry effects have no style of their own, so give them the
6544 // board's. A file that did carry effects has said all it means to say.
6545 if( newField && !sawEffects && m_board ) // m_board is null when reading a lib
6546 field->StyleFromSettings( m_board->GetDesignSettings(), true );
6547 }
6548 break;
6549
6550 case T_path:
6551 NeedSYMBOLorNUMBER(); // Paths can be numerical so a number is also a symbol here
6552 footprint->SetPath( KIID_PATH( FromUTF8() ) );
6553 NeedRIGHT();
6554 break;
6555
6556 case T_sheetname:
6557 NeedSYMBOL();
6558 footprint->SetSheetname( FromUTF8() );
6559 NeedRIGHT();
6560 break;
6561
6562 case T_sheetfile:
6563 NeedSYMBOL();
6564 footprint->SetSheetfile( FromUTF8() );
6565 NeedRIGHT();
6566 break;
6567
6568 case T_units:
6569 {
6570 std::vector<FOOTPRINT::FP_UNIT_INFO> unitInfos;
6571
6572 // (units (unit (name "A") (pins "1" "2" ...)) ...)
6573 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6574 {
6575 if( token == T_LEFT )
6576 token = NextTok();
6577
6578 if( token == T_unit )
6579 {
6581
6582 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6583 {
6584 if( token == T_LEFT )
6585 token = NextTok();
6586
6587 if( token == T_name )
6588 {
6589 NeedSYMBOLorNUMBER();
6590 info.m_unitName = FromUTF8();
6591 NeedRIGHT();
6592 }
6593 else if( token == T_pins )
6594 {
6595 // Parse a flat list of quoted numbers or symbols until ')'
6596 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6597 {
6598 if( token == T_STRING || token == T_NUMBER )
6599 {
6600 info.m_pins.emplace_back( FromUTF8() );
6601 }
6602 else
6603 {
6604 Expecting( "pin number" );
6605 }
6606 }
6607 }
6608 else
6609 {
6610 // Unknown sub-token inside unit; skip its list if any
6611 skipCurrent();
6612 }
6613 }
6614
6615 unitInfos.push_back( info );
6616 }
6617 else
6618 {
6619 // Unknown entry under units; skip
6620 skipCurrent();
6621 }
6622 }
6623
6624 if( !unitInfos.empty() )
6625 footprint->SetUnitInfo( unitInfos );
6626
6627 break;
6628 }
6629
6630 case T_autoplace_cost90:
6631 case T_autoplace_cost180:
6632 parseInt( "legacy auto-place cost" );
6633 NeedRIGHT();
6634 break;
6635
6636 case T_private_layers:
6637 {
6638 LSET privateLayers;
6639
6640 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6641 {
6642 auto it = m_layerIndices.find( CurStr() );
6643
6644 if( it != m_layerIndices.end() )
6645 privateLayers.set( it->second );
6646 else
6647 Expecting( "layer name" );
6648 }
6649
6650 if( m_requiredVersion < 20220427 )
6651 {
6652 privateLayers.set( Edge_Cuts, false );
6653 privateLayers.set( Margin, false );
6654 }
6655
6656 footprint->SetPrivateLayers( privateLayers );
6657 break;
6658 }
6659
6660 case T_net_tie_pad_groups:
6661 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6662 footprint->AddNetTiePadGroup( CurStr() );
6663
6664 break;
6665
6666 case T_duplicate_pad_numbers_are_jumpers:
6667 footprint->SetDuplicatePadNumbersAreJumpers( parseBool() );
6668 NeedRIGHT();
6669 break;
6670
6671 case T_jumper_pad_groups:
6672 {
6673 JUMPER_GROUP_SET& groups = footprint->JumperPadGroups();
6674 std::set<wxString> names;
6675 bool inGroup = false;
6676
6677 for( token = NextTok(); inGroup || token != T_RIGHT; token = NextTok() )
6678 {
6679 switch( static_cast<int>( token ) )
6680 {
6681 case T_LEFT:
6682 if( inGroup )
6683 Expecting( "list of pad names" );
6684
6685 inGroup = true;
6686 break;
6687
6688 case DSN_STRING:
6689 if( !inGroup )
6690 Expecting( "list of pad names" );
6691
6692 names.insert( FromUTF8() );
6693 break;
6694
6695 case T_RIGHT:
6696 if( std::optional<JUMPER_GROUP> group = JUMPER_GROUP::Make( std::move( names ) ) )
6697 groups.Add( std::move( *group ) );
6698
6699 names.clear();
6700 inGroup = false;
6701 break;
6702
6703 default:
6704 Expecting( "list of pad names" );
6705 }
6706 }
6707
6708 break;
6709 }
6710
6711 case T_solder_mask_margin:
6712 footprint->SetLocalSolderMaskMargin( parseBoardUnits( "local solder mask margin value" ) );
6713 NeedRIGHT();
6714
6715 // In pre-9.0 files "0" meant inherit.
6716 if( m_requiredVersion <= 20240201 && footprint->GetLocalSolderMaskMargin() == 0 )
6717 footprint->SetLocalSolderMaskMargin( {} );
6718
6719 break;
6720
6721 case T_solder_paste_margin:
6722 footprint->SetLocalSolderPasteMargin( parseBoardUnits( "local solder paste margin value" ) );
6723 NeedRIGHT();
6724
6725 // In pre-9.0 files "0" meant inherit.
6726 if( m_requiredVersion <= 20240201 && footprint->GetLocalSolderPasteMargin() == 0 )
6727 footprint->SetLocalSolderPasteMargin( {} );
6728
6729 break;
6730
6731 case T_solder_paste_ratio: // legacy token
6732 case T_solder_paste_margin_ratio:
6733 footprint->SetLocalSolderPasteMarginRatio( parseDouble( "local solder paste margin ratio value" ) );
6734 NeedRIGHT();
6735
6736 // In pre-9.0 files "0" meant inherit.
6737 if( m_requiredVersion <= 20240201 && footprint->GetLocalSolderPasteMarginRatio() == 0 )
6738 footprint->SetLocalSolderPasteMarginRatio( {} );
6739
6740 break;
6741
6742 case T_clearance:
6743 footprint->SetLocalClearance( parseBoardUnits( "local clearance value" ) );
6744 NeedRIGHT();
6745
6746 // In pre-9.0 files "0" meant inherit.
6747 if( m_requiredVersion <= 20240201 && footprint->GetLocalClearance() == 0 )
6748 footprint->SetLocalClearance( {} );
6749
6750 break;
6751
6752 case T_zone_connect:
6753 footprint->SetLocalZoneConnection((ZONE_CONNECTION) parseInt( "zone connection value" ) );
6754 NeedRIGHT();
6755 break;
6756
6757 case T_thermal_width:
6758 case T_thermal_gap:
6759 // Interestingly, these have never been exposed in the GUI
6760 parseBoardUnits( token );
6761 NeedRIGHT();
6762 break;
6763
6764 case T_attr:
6765 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6766 {
6767 switch( token )
6768 {
6769 case T_virtual: // legacy token prior to version 20200826
6771 break;
6772
6773 case T_through_hole:
6774 attributes |= FP_THROUGH_HOLE;
6775 break;
6776
6777 case T_smd:
6778 attributes |= FP_SMD;
6779 break;
6780
6781 case T_board_only:
6782 attributes |= FP_BOARD_ONLY;
6783 break;
6784
6785 case T_exclude_from_pos_files:
6786 attributes |= FP_EXCLUDE_FROM_POS_FILES;
6787 break;
6788
6789 case T_exclude_from_bom:
6790 attributes |= FP_EXCLUDE_FROM_BOM;
6791 break;
6792
6793 case T_exclude_from_sim:
6794 attributes |= FP_EXCLUDE_FROM_SIM;
6795 break;
6796
6797 case T_allow_missing_courtyard:
6798 footprint->SetAllowMissingCourtyard( true );
6799 break;
6800
6801 case T_dnp:
6802 attributes |= FP_DNP;
6803 break;
6804
6805 case T_allow_soldermask_bridges:
6806 footprint->SetAllowSolderMaskBridges( true );
6807 break;
6808
6809 default:
6810 Expecting( "through_hole, smd, virtual, board_only, exclude_from_pos_files, "
6811 "exclude_from_bom, exclude_from_sim or allow_solder_mask_bridges" );
6812 }
6813 }
6814 footprint->SetAttributes( attributes );
6815 break;
6816
6817 case T_fp_text:
6818 {
6819 PCB_TEXT* text = parsePCB_TEXT( footprint.get() );
6820
6821 if( PCB_FIELD* field = dynamic_cast<PCB_FIELD*>( text ) )
6822 {
6823 switch( field->GetId() )
6824 {
6825 case FIELD_T::REFERENCE:
6826 footprint->Reference() = PCB_FIELD( *text, FIELD_T::REFERENCE );
6827 footprint->Reference().SetUuidDirect( text->m_Uuid );
6828 delete text;
6829 break;
6830
6831 case FIELD_T::VALUE:
6832 footprint->Value() = PCB_FIELD( *text, FIELD_T::VALUE );
6833 footprint->Value().SetUuidDirect( text->m_Uuid );
6834 delete text;
6835 break;
6836
6837 default:
6838 // Fields other than reference and value aren't treated specially,
6839 // and can be created if the fp_text was hidden on the board,
6840 // so just add those to the footprint as normal.
6841 footprint->Add(text, ADD_MODE::APPEND, true );
6842 break;
6843 }
6844 }
6845 else
6846 {
6847 footprint->Add( text, ADD_MODE::APPEND, true );
6848 }
6849
6850 break;
6851 }
6852
6853 case T_fp_text_box:
6854 {
6855 PCB_TEXTBOX* textbox = parsePCB_TEXTBOX( footprint.get() );
6856 footprint->Add( textbox, ADD_MODE::APPEND, true );
6857 break;
6858 }
6859
6860 case T_table:
6861 {
6862 PCB_TABLE* table = parsePCB_TABLE( footprint.get() );
6863 footprint->Add( table, ADD_MODE::APPEND, true );
6864 break;
6865 }
6866
6867 case T_fp_arc:
6868 case T_fp_circle:
6869 case T_fp_curve:
6870 case T_fp_rect:
6871 case T_fp_line:
6872 case T_fp_poly:
6873 case T_fp_ellipse:
6874 case T_fp_ellipse_arc:
6875 {
6876 PCB_SHAPE* shape = parsePCB_SHAPE( footprint.get() );
6877 footprint->Add( shape, ADD_MODE::APPEND, true );
6878 break;
6879 }
6880
6881 case T_image:
6882 {
6884 footprint->Add( image, ADD_MODE::APPEND, true );
6885 break;
6886 }
6887
6888 case T_barcode:
6889 {
6890 PCB_BARCODE* barcode = parsePCB_BARCODE( footprint.get() );
6891 footprint->Add( barcode, ADD_MODE::APPEND, true );
6892 break;
6893 }
6894
6895 case T_dimension:
6896 {
6897 PCB_DIMENSION_BASE* dimension = parseDIMENSION( footprint.get() );
6898 footprint->Add( dimension, ADD_MODE::APPEND, true );
6899 break;
6900 }
6901
6902 case T_pad:
6903 {
6904 PAD* pad = parsePAD( footprint.get() );
6905 footprint->Add( pad, ADD_MODE::APPEND, true );
6906 break;
6907 }
6908
6909 case T_model:
6910 token = NextTok();
6911
6912 if( token == T_LEFT )
6913 {
6914 // Typed model (model (type extruded) ...)
6915 token = NextTok();
6916
6917 if( token != T_type )
6918 Expecting( T_type );
6919
6920 NeedSYMBOL();
6921
6922 if( CurTok() == T_extruded )
6923 {
6924 NeedRIGHT(); // close (type extruded)
6925
6926 PCB_3D_BODY* bodyItem = footprint->GetBody();
6927
6928 if( !bodyItem )
6929 bodyItem = &footprint->EnsureBody();
6930
6931 EXTRUDED_3D_BODY& body = *bodyItem->MutableExtruded();
6932
6933 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
6934 {
6935 if( token != T_LEFT )
6936 Expecting( T_LEFT );
6937
6938 token = NextTok();
6939
6940 switch( token )
6941 {
6942 case T_hide:
6943 {
6944 bool hide = parseMaybeAbsentBool( true );
6945 body.m_show = !hide;
6946 break;
6947 }
6948
6949 case T_uuid:
6950 NextTok();
6951 bodyItem->SetUuidDirect( CurStrToKIID() );
6952 NeedRIGHT();
6953 break;
6954
6955 case T_overall_height:
6956 body.m_height = parseBoardUnits( "overall height" );
6957 NeedRIGHT();
6958 break;
6959
6960 case T_body_pcb_gap:
6961 body.m_standoff = parseBoardUnits( "body pcb gap" );
6962 NeedRIGHT();
6963 break;
6964
6965 case T_layer:
6966 {
6967 NeedSYMBOL();
6968 wxString layerName = From_UTF8( CurText() );
6969
6970 if( layerName == wxT( "auto" ) )
6971 {
6972 body.m_layer = UNDEFINED_LAYER;
6973 }
6974 else if( layerName == wxT( "pad_bbox" ) )
6975 {
6977 }
6978 else
6979 {
6980 int layer = LSET::NameToLayer( layerName );
6981
6982 if( layer >= 0 )
6983 body.m_layer = static_cast<PCB_LAYER_ID>( layer );
6984 }
6985
6986 NeedRIGHT();
6987 break;
6988 }
6989
6990 case T_material:
6991 {
6992 NeedSYMBOL();
6993 wxString matName = From_UTF8( CurText() );
6994
6995 if( matName == wxT( "matte" ) )
6997 else if( matName == wxT( "metal" ) )
6999 else if( matName == wxT( "copper" ) )
7001 else
7003
7004 NeedRIGHT();
7005 break;
7006 }
7007
7008 case T_color:
7009 {
7010 NeedSYMBOLorNUMBER();
7011 wxString first = From_UTF8( CurText() );
7012
7013 if( first == wxT( "unspecified" ) )
7014 {
7016 }
7017 else
7018 {
7019 body.m_color.r = parseDouble();
7020 body.m_color.g = parseDouble( "green" );
7021 body.m_color.b = parseDouble( "blue" );
7022 body.m_color.a = parseDouble( "alpha" );
7023 }
7024
7025 NeedRIGHT();
7026 break;
7027 }
7028
7029 case T_offset:
7030 NeedLEFT();
7031 token = NextTok();
7032
7033 if( token != T_xyz )
7034 Expecting( T_xyz );
7035
7036 body.m_offset.x = parseDouble( "x value" );
7037 body.m_offset.y = parseDouble( "y value" );
7038 body.m_offset.z = parseDouble( "z value" );
7039 NeedRIGHT();
7040 NeedRIGHT();
7041 break;
7042
7043 case T_scale:
7044 NeedLEFT();
7045 token = NextTok();
7046
7047 if( token != T_xyz )
7048 Expecting( T_xyz );
7049
7050 body.m_scale.x = parseDouble( "x value" );
7051 body.m_scale.y = parseDouble( "y value" );
7052 body.m_scale.z = parseDouble( "z value" );
7053 NeedRIGHT();
7054 NeedRIGHT();
7055 break;
7056
7057 case T_rotate:
7058 NeedLEFT();
7059 token = NextTok();
7060
7061 if( token != T_xyz )
7062 Expecting( T_xyz );
7063
7064 body.m_rotation.x = parseDouble( "x value" );
7065 body.m_rotation.y = parseDouble( "y value" );
7066 body.m_rotation.z = parseDouble( "z value" );
7067 NeedRIGHT();
7068 NeedRIGHT();
7069 break;
7070
7071 default:
7072 Expecting( "hide, uuid, overall_height, body_pcb_gap, layer, material, "
7073 "color, offset, scale, or rotate" );
7074 }
7075 }
7076 }
7077 else
7078 {
7079 Expecting( "extruded" );
7080 }
7081 }
7082 else
7083 {
7084 // Reference model (model "filename" ...)
7085 FP_3DMODEL* model = parse3DModel( true );
7086 footprint->Add3DModel( model );
7087 delete model;
7088 }
7089
7090 break;
7091
7092 case T_zone:
7093 {
7094 ZONE* zone = parseZONE( footprint.get() );
7095
7096 if( zone->GetNumCorners() == 0 )
7097 {
7098 delete zone;
7099 break;
7100 }
7101
7102 // Legacy footprint zone outlines were in board frame. Convert to lib.
7104 {
7105 const TRANSFORM_TRS& xform = footprint->GetTransform();
7106 SHAPE_POLY_SET& poly = *zone->Outline();
7107
7108 for( auto it = poly.IterateWithHoles(); it; it++ )
7109 poly.SetVertex( it.GetIndex(), xform.InverseApply( *it ) );
7110
7111 // Hatch lines were cached in board frame; rebuild in lib frame so the
7112 // footprint transform is not applied to them twice on render.
7113 zone->HatchBorder();
7114 }
7115
7116 footprint->Add( zone, ADD_MODE::APPEND, true );
7117 break;
7118 }
7119
7120 case T_group:
7121 parseGROUP( footprint.get() );
7122 break;
7123
7124 case T_constraint:
7125 parseCONSTRAINT( footprint.get() );
7126 break;
7127
7128 case T_point:
7129 {
7130 PCB_POINT* point = parsePCB_POINT();
7131 const VECTOR2I filePos = point->GetPosition();
7132
7133 footprint->Add( point, ADD_MODE::APPEND, true );
7134
7135 // Legacy files stored footprint points in board frame
7137 point->SetPosition( filePos );
7138
7139 break;
7140 }
7141
7142 case T_embedded_fonts:
7143 {
7144 footprint->GetEmbeddedFiles()->SetAreFontsEmbedded( parseBool() );
7145 NeedRIGHT();
7146 break;
7147 }
7148
7149 case T_embedded_files:
7150 {
7151 EMBEDDED_FILES_PARSER embeddedFilesParser( reader );
7152 embeddedFilesParser.SyncLineReaderWith( *this );
7153
7154 try
7155 {
7156 embeddedFilesParser.ParseEmbedded( footprint->GetEmbeddedFiles() );
7157 }
7158 catch( const PARSE_ERROR& e )
7159 {
7160 m_parseWarnings.push_back( e.What() );
7161
7162 int depth = 0;
7163
7164 for( int tok = embeddedFilesParser.NextTok(); tok != DSN_EOF; tok = embeddedFilesParser.NextTok() )
7165 {
7166 if( tok == DSN_LEFT )
7167 depth++;
7168 else if( tok == DSN_RIGHT && --depth < 0 )
7169 break;
7170 }
7171 }
7172
7173 SyncLineReaderWith( embeddedFilesParser );
7174 break;
7175 }
7176
7177 case T_component_classes:
7178 {
7179 std::unordered_set<wxString> componentClassNames;
7180
7181 while( ( token = NextTok() ) != T_RIGHT )
7182 {
7183 if( token != T_LEFT )
7184 Expecting( T_LEFT );
7185
7186 if( ( token = NextTok() ) != T_class )
7187 Expecting( T_class );
7188
7189 NeedSYMBOLorNUMBER();
7190 componentClassNames.insert( From_UTF8( CurText() ) );
7191 NeedRIGHT();
7192 }
7193
7194 footprint->SetTransientComponentClassNames( componentClassNames );
7195
7196 if( m_board )
7197 footprint->ResolveComponentClassNames( m_board, componentClassNames );
7198
7199 break;
7200 }
7201
7202 case T_variant:
7203 parseFootprintVariant( footprint.get() );
7204 break;
7205
7206 case T_custom_property:
7207 parseCustomProperty( footprint.get() );
7208 break;
7209
7210 default:
7211 Expecting( "at, descr, locked, placed, tedit, tstamp, uuid, variant, autoplace_cost90, "
7212 "autoplace_cost180, attr, clearance, embedded_files, fp_arc, fp_circle, fp_curve, "
7213 "fp_line, fp_poly, fp_rect, fp_text, pad, group, generator, model, path, "
7214 "solder_mask_margin, solder_paste_margin, solder_paste_margin_ratio, tags, "
7215 "thermal_gap, version, zone, zone_connect, component_classes, or custom_property" );
7216 }
7217 }
7218
7219 footprint->FixUpPadsForBoard( m_board );
7220
7221 // In legacy files the lack of attributes indicated a through-hole component which was by
7222 // default excluded from pos files. However there was a hack to look for SMD pads and
7223 // consider those "mislabeled through-hole components" and therefore include them in place
7224 // files. We probably don't want to get into that game so we'll just include them by
7225 // default and let the user change it if required.
7226 if( m_requiredVersion < 20200826 && attributes == 0 )
7227 attributes |= FP_THROUGH_HOLE;
7228
7230 {
7231 if( footprint->GetKeywords().StartsWith( wxT( "net tie" ) ) )
7232 {
7233 wxString padGroup;
7234
7235 for( PAD* pad : footprint->Pads() )
7236 {
7237 if( !padGroup.IsEmpty() )
7238 padGroup += wxS( ", " );
7239
7240 padGroup += pad->GetNumber();
7241 }
7242
7243 if( !padGroup.IsEmpty() )
7244 footprint->AddNetTiePadGroup( padGroup );
7245 }
7246 }
7247
7248 footprint->SetAttributes( attributes );
7249
7250 footprint->SetFPID( fpid );
7251
7252 return footprint.release();
7253}
7254
7255
7257{
7258 wxCHECK_RET( CurTok() == T_stackup, "Expected stackup token" );
7259
7260 // If we have a stackup list at all, we must be in custom layer mode
7262 LSET layers = LSET{};
7263
7264 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
7265 {
7266 if( CurTok() != T_LEFT )
7267 Expecting( T_LEFT );
7268
7269 token = NextTok();
7270
7271 switch( token )
7272 {
7273 case T_layer:
7274 {
7275 NeedSYMBOLorNUMBER();
7276
7277 const auto it = m_layerIndices.find( CurStr() );
7278
7279 if( it == m_layerIndices.end() )
7280 Expecting( "layer name" );
7281 else
7282 layers.set( it->second );
7283
7284 NeedRIGHT();
7285 break;
7286 }
7287 default:
7288 Expecting( "layer" );
7289 }
7290 }
7291
7292 // Check that the copper layers are sensible and contiguous
7293 const LSET gotCuLayers = layers & LSET::AllCuMask();
7294
7295 // Remove this check when we support odd copper layer stackups
7296 if( gotCuLayers.count() % 2 != 0 )
7297 {
7298 THROW_IO_ERRORF( _( "Invalid stackup in footprint: odd number of copper layers (%d)." ),
7299 gotCuLayers.count() );
7300 }
7301
7302 const LSET expectedCuLayers = LSET::AllCuMask( gotCuLayers.count() );
7303 if( gotCuLayers != expectedCuLayers )
7304 {
7305 THROW_IO_ERROR( _( "Invalid stackup in footprint: copper layers are not contiguous." ) );
7306 }
7307
7308 if( ( layers & LSET::AllTechMask() ).count() > 0 )
7309 {
7310 THROW_IO_ERROR( _( "Invalid stackup in footprint: technology layers are implicit in footprints and "
7311 "should not be specified in the stackup." ) );
7312 }
7313
7314 // Set the mode first, so that the layer count is unlocked if needed
7315 aFootprint.SetStackupMode( stackupMode );
7316 aFootprint.SetStackupLayers( std::move( layers ) );
7317}
7318
7319
7321{
7322 wxCHECK_MSG( CurTok() == T_pad, nullptr, wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PAD." ) );
7323
7324 VECTOR2I sz;
7325 VECTOR2I pt;
7326 bool foundNet = false;
7327 bool foundNetcode = false;
7328
7329 std::unique_ptr<PAD> pad = std::make_unique<PAD>( aParent );
7330
7331 NeedSYMBOLorNUMBER();
7332 pad->SetNumber( FromUTF8() );
7333
7334 T token = NextTok();
7335
7336 // NB: all pre-padstack tokens are stored into the F_Cu layer. For PADSTACK::MODE::NORMAL
7337 // this will be all there is. For complex padstacks, the other values will get loaded from the
7338 // T_padstack record.
7339
7340 switch( token )
7341 {
7342 case T_thru_hole:
7343 pad->SetAttribute( PAD_ATTRIB::PTH );
7344
7345 // The drill token is usually missing if 0 drill size is specified.
7346 // Emulate it using 1 nm drill size to avoid errors.
7347 // Drill size cannot be set to 0 in newer versions.
7348 pad->SetDrillSize( VECTOR2I( 1, 1 ) );
7349 break;
7350
7351 case T_smd:
7352 pad->SetAttribute( PAD_ATTRIB::SMD );
7353 break;
7354
7355 case T_connect:
7356 pad->SetAttribute( PAD_ATTRIB::CONN );
7357 break;
7358
7359 case T_non_component:
7360 pad->SetAttribute( PAD_ATTRIB::NON_COMPONENT );
7361 break;
7362
7363 case T_np_thru_hole:
7364 pad->SetAttribute( PAD_ATTRIB::NPTH );
7365 break;
7366
7367 default:
7368 Expecting( "thru_hole, smd, connect, non_component, or np_thru_hole" );
7369 }
7370
7371 token = NextTok();
7372
7373 switch( token )
7374 {
7375 case T_circle:
7376 pad->SetShape( F_Cu, PAD_SHAPE::CIRCLE );
7377 break;
7378
7379 case T_rect:
7380 pad->SetShape( F_Cu, PAD_SHAPE::RECTANGLE );
7381 break;
7382
7383 case T_oval:
7384 pad->SetShape( F_Cu, PAD_SHAPE::OVAL );
7385 break;
7386
7387 case T_trapezoid:
7388 pad->SetShape( F_Cu, PAD_SHAPE::TRAPEZOID );
7389 break;
7390
7391 case T_roundrect:
7392 // Note: the shape can be PAD_SHAPE::ROUNDRECT or PAD_SHAPE::CHAMFERED_RECT
7393 // (if chamfer parameters are found later in pad descr.)
7394 pad->SetShape( F_Cu, PAD_SHAPE::ROUNDRECT );
7395 break;
7396
7397 case T_custom:
7398 pad->SetShape( F_Cu, PAD_SHAPE::CUSTOM );
7399 break;
7400
7401 default:
7402 Expecting( "circle, rectangle, roundrect, oval, trapezoid or custom" );
7403 }
7404
7405 std::optional<EDA_ANGLE> thermalBrAngleOverride;
7406
7407 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
7408 {
7409 if( token == T_locked )
7410 {
7411 // Pad locking is now a session preference
7412 token = NextTok();
7413 }
7414
7415 if( token != T_LEFT )
7416 Expecting( T_LEFT );
7417
7418 token = NextTok();
7419
7420 switch( token )
7421 {
7422 case T_size:
7423 sz.x = parseBoardUnits( "width value" );
7424 sz.y = parseBoardUnits( "height value" );
7425 pad->SetLibSize( F_Cu, sz );
7426 NeedRIGHT();
7427 break;
7428
7429 case T_at:
7430 pt.x = parseBoardUnits( "X coordinate" );
7431 pt.y = parseBoardUnits( "Y coordinate" );
7432 pad->SetFPRelativePosition( pt );
7433 token = NextTok();
7434
7435 // The pad angle in the file is a board frame absolute value. If it is
7436 // missing, the pad is axis aligned regardless of the parent footprint
7437 // orientation, matching the pre affine transform behavior.
7438 if( token == T_NUMBER )
7439 {
7440 pad->SetOrientation( EDA_ANGLE( parseDouble(), DEGREES_T ) );
7441 NeedRIGHT();
7442 }
7443 else if( token == T_RIGHT )
7444 {
7445 pad->SetOrientation( ANGLE_0 );
7446 }
7447 else
7448 {
7449 Expecting( ") or angle value" );
7450 }
7451
7452 break;
7453
7454 case T_rect_delta:
7455 {
7457 delta.x = parseBoardUnits( "rectangle delta width" );
7458 delta.y = parseBoardUnits( "rectangle delta height" );
7459 pad->SetDelta( F_Cu, delta );
7460 NeedRIGHT();
7461 break;
7462 }
7463
7464 case T_drill:
7465 {
7466 bool haveWidth = false;
7467 VECTOR2I drillSize = pad->GetDrillSize();
7468
7469 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
7470 {
7471 if( token == T_LEFT )
7472 token = NextTok();
7473
7474 switch( token )
7475 {
7476 case T_oval: pad->SetDrillShape( PAD_DRILL_SHAPE::OBLONG ); break;
7477
7478 case T_NUMBER:
7479 {
7480 if( !haveWidth )
7481 {
7482 drillSize.x = parseBoardUnits();
7483
7484 // If height is not defined the width and height are the same.
7485 drillSize.y = drillSize.x;
7486 haveWidth = true;
7487 }
7488 else
7489 {
7490 drillSize.y = parseBoardUnits();
7491 }
7492 }
7493
7494 break;
7495
7496 case T_offset:
7497 pt.x = parseBoardUnits( "drill offset x" );
7498 pt.y = parseBoardUnits( "drill offset y" );
7499 pad->SetLibOffset( F_Cu, pt );
7500 NeedRIGHT();
7501 break;
7502
7503 default:
7504 Expecting( "oval, size, or offset" );
7505 }
7506 }
7507
7508 // This fixes a bug caused by setting the default PAD drill size to a value other
7509 // than 0 used to fix a bunch of debug assertions even though it is defined as a
7510 // through hole pad. Wouldn't a though hole pad with no drill be a surface mount
7511 // pad (or a conn pad which is a smd pad with no solder paste)?
7512 if( pad->GetAttribute() == PAD_ATTRIB::SMD
7513 || pad->GetAttribute() == PAD_ATTRIB::CONN
7514 || pad->GetAttribute() == PAD_ATTRIB::NON_COMPONENT )
7515 {
7516 pad->SetLibDrillSize( VECTOR2I( 0, 0 ) );
7517 }
7518 else
7519 {
7520 pad->SetLibDrillSize( drillSize );
7521 }
7522
7523 break;
7524 }
7525
7526 case T_backdrill:
7527 {
7528 // Parse: (backdrill (size ...) (layers start end))
7529 PADSTACK::DRILL_PROPS& secondary = pad->Padstack().SecondaryDrill();
7530
7531 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
7532 {
7533 if( token != T_LEFT )
7534 Expecting( T_LEFT );
7535
7536 token = NextTok();
7537
7538 switch( token )
7539 {
7540 case T_size:
7541 {
7542 int size = parseBoardUnits( "backdrill size" );
7543 secondary.size = VECTOR2I( size, size );
7544 NeedRIGHT();
7545 break;
7546 }
7547
7548 case T_layers:
7549 {
7550 NextTok();
7551 secondary.start = lookUpLayer( m_layerIndices, true );
7552 NextTok();
7553 secondary.end = lookUpLayer( m_layerIndices, true );
7554 NeedRIGHT();
7555 break;
7556 }
7557
7558 default:
7559 Expecting( "size or layers" );
7560 }
7561 }
7562
7563 if( secondary.start == UNDEFINED_LAYER )
7564 secondary.size = VECTOR2I( 0, 0 );
7565
7566 break;
7567 }
7568
7569 case T_tertiary_drill:
7570 {
7571 // Parse: (tertiary_drill (size ...) (layers start end))
7572 PADSTACK::DRILL_PROPS& tertiary = pad->Padstack().TertiaryDrill();
7573
7574 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
7575 {
7576 if( token != T_LEFT )
7577 Expecting( T_LEFT );
7578
7579 token = NextTok();
7580
7581 switch( token )
7582 {
7583 case T_size:
7584 {
7585 int size = parseBoardUnits( "tertiary drill size" );
7586 tertiary.size = VECTOR2I( size, size );
7587 NeedRIGHT();
7588 break;
7589 }
7590
7591 case T_layers:
7592 {
7593 NextTok();
7594 tertiary.start = lookUpLayer( m_layerIndices, true );
7595 NextTok();
7596 tertiary.end = lookUpLayer( m_layerIndices, true );
7597 NeedRIGHT();
7598 break;
7599 }
7600
7601 default:
7602 Expecting( "size or layers" );
7603 }
7604 }
7605
7606 if( tertiary.start == UNDEFINED_LAYER )
7607 tertiary.size = VECTOR2I( 0, 0 );
7608
7609 break;
7610 }
7611
7612 case T_layers:
7613 {
7614 LSET layerMask = parseBoardItemLayersAsMask();
7615
7616 pad->SetLayerSet( layerMask );
7617 break;
7618 }
7619
7620 case T_net:
7621 foundNet = true;
7622
7623 token = NextTok();
7624
7625 // Legacy files (pre-10.0) will have a netcode written before the netname. This netcode
7626 // is authoratative (though may be mapped by getNetCode() to prevent collisions).
7627 if( IsNumber( token ) )
7628 {
7629 if( !pad->SetNetCode( getNetCode( parseInt() ), /* aNoAssert */ true ) )
7630 {
7631 wxLogTrace( traceKicadPcbPlugin, _( "Invalid net ID in\nfile: %s\nline: %d offset: %d" ),
7632 CurSource(), CurLineNumber(), CurOffset() );
7633 }
7634 else
7635 {
7636 foundNetcode = true;
7637 }
7638
7639 token = NextTok();
7640 }
7641
7642 if( !IsSymbol( token ) )
7643 {
7644 Expecting( "net name" );
7645 break;
7646 }
7647
7648 if( m_board )
7649 {
7650 wxString netName( FromUTF8() );
7651
7652 // Convert overbar syntax from `~...~` to `~{...}`. These were left out of the
7653 // first merge so the version is a bit later.
7654 if( m_requiredVersion < 20210606 )
7655 netName = ConvertToNewOverbarNotation( netName );
7656
7657 if( foundNetcode )
7658 {
7659 if( netName != m_board->FindNet( pad->GetNetCode() )->GetNetname() )
7660 {
7661 pad->SetNetCode( NETINFO_LIST::ORPHANED, /* aNoAssert */ true );
7662 wxLogTrace( traceKicadPcbPlugin,
7663 _( "Net name doesn't match ID in\nfile: %s\nline: %d offset: %d" ),
7664 CurSource(), CurLineNumber(), CurOffset() );
7665 }
7666 }
7667 else
7668 {
7669 NETINFO_ITEM* netinfo = m_board->FindNet( netName );
7670
7671 if( !netinfo )
7672 {
7673 netinfo = new NETINFO_ITEM( m_board, netName );
7674 m_board->Add( netinfo, ADD_MODE::INSERT, true );
7675 }
7676
7677 pad->SetNet( netinfo );
7678 }
7679 }
7680
7681 NeedRIGHT();
7682 break;
7683
7684 case T_pinfunction:
7685 NeedSYMBOLorNUMBER();
7686 pad->SetPinFunction( FromUTF8() );
7687 NeedRIGHT();
7688 break;
7689
7690 case T_pintype:
7691 NeedSYMBOLorNUMBER();
7692 pad->SetPinType( FromUTF8() );
7693 NeedRIGHT();
7694 break;
7695
7696 case T_sim_electrical_type:
7697 {
7698 token = NextTok();
7699
7700 switch( token )
7701 {
7702 case T_source: pad->SetSimElectricalType( PAD_SIM_ELECTRICAL_TYPE::SOURCE ); break;
7703 case T_sink: pad->SetSimElectricalType( PAD_SIM_ELECTRICAL_TYPE::SINK ); break;
7704 default: Expecting( "sink or source" );
7705 }
7706
7707 NeedRIGHT();
7708 break;
7709 }
7710
7711 case T_die_length:
7712 pad->SetPadToDieLength( parseBoardUnits( T_die_length ) );
7713 NeedRIGHT();
7714 break;
7715
7716 case T_die_delay:
7717 if( m_requiredVersion <= 20250926 )
7718 pad->SetPadToDieDelay( parseBoardUnits( T_die_delay ) );
7719 else
7720 pad->SetPadToDieDelay( parseBoardUnits( T_die_delay, EDA_DATA_TYPE::TIME ) );
7721
7722 NeedRIGHT();
7723 break;
7724
7725 case T_solder_mask_margin:
7726 pad->SetLocalSolderMaskMargin( parseBoardUnits( "local solder mask margin value" ) );
7727 NeedRIGHT();
7728
7729 // In pre-9.0 files "0" meant inherit.
7730 if( m_requiredVersion <= 20240201 && pad->GetLocalSolderMaskMargin() == 0 )
7731 pad->SetLocalSolderMaskMargin( {} );
7732
7733 break;
7734
7735 case T_solder_paste_margin:
7736 pad->SetLocalSolderPasteMargin( parseBoardUnits( "local solder paste margin value" ) );
7737 NeedRIGHT();
7738
7739 // In pre-9.0 files "0" meant inherit.
7740 if( m_requiredVersion <= 20240201 && pad->GetLocalSolderPasteMargin() == 0 )
7741 pad->SetLocalSolderPasteMargin( {} );
7742
7743 break;
7744
7745 case T_solder_paste_margin_ratio:
7746 pad->SetLocalSolderPasteMarginRatio( parseDouble( "local solder paste margin ratio value" ) );
7747 NeedRIGHT();
7748
7749 // In pre-9.0 files "0" meant inherit.
7750 if( m_requiredVersion <= 20240201 && pad->GetLocalSolderPasteMarginRatio() == 0 )
7751 pad->SetLocalSolderPasteMarginRatio( {} );
7752
7753 break;
7754
7755 case T_clearance:
7756 pad->SetLocalClearance( parseBoardUnits( "local clearance value" ) );
7757 NeedRIGHT();
7758
7759 // In pre-9.0 files "0" meant inherit.
7760 if( m_requiredVersion <= 20240201 && pad->GetLocalClearance() == 0 )
7761 pad->SetLocalClearance( {} );
7762
7763 break;
7764
7765 case T_teardrops:
7766 parseTEARDROP_PARAMETERS( &pad->GetTeardropParams() );
7767 break;
7768
7769 case T_zone_connect:
7770 pad->SetLocalZoneConnection( (ZONE_CONNECTION) parseInt( "zone connection value" ) );
7771 NeedRIGHT();
7772 break;
7773
7774 case T_thermal_width: // legacy token
7775 case T_thermal_bridge_width:
7776 pad->SetLocalThermalSpokeWidthOverride( parseBoardUnits( token ) );
7777 NeedRIGHT();
7778 break;
7779
7780 case T_thermal_bridge_angle:
7781 thermalBrAngleOverride = EDA_ANGLE( parseDouble( "thermal spoke angle" ), DEGREES_T );
7782 NeedRIGHT();
7783 break;
7784
7785
7786 case T_thermal_gap:
7787 pad->SetThermalGap( parseBoardUnits( "thermal relief gap value" ) );
7788 NeedRIGHT();
7789 break;
7790
7791 case T_roundrect_rratio:
7792 pad->SetRoundRectRadiusRatio( F_Cu, parseDouble( "roundrect radius ratio" ) );
7793 NeedRIGHT();
7794 break;
7795
7796 case T_chamfer_ratio:
7797 pad->SetChamferRectRatio( F_Cu, parseDouble( "chamfer ratio" ) );
7798
7799 if( pad->GetChamferRectRatio( F_Cu ) > 0 )
7800 pad->SetShape( F_Cu, PAD_SHAPE::CHAMFERED_RECT );
7801
7802 NeedRIGHT();
7803 break;
7804
7805 case T_chamfer:
7806 {
7807 int chamfers = 0;
7808 bool end_list = false;
7809
7810 while( !end_list )
7811 {
7812 token = NextTok();
7813
7814 switch( token )
7815 {
7816 case T_top_left:
7817 chamfers |= RECT_CHAMFER_TOP_LEFT;
7818 break;
7819
7820 case T_top_right:
7821 chamfers |= RECT_CHAMFER_TOP_RIGHT;
7822 break;
7823
7824 case T_bottom_left:
7825 chamfers |= RECT_CHAMFER_BOTTOM_LEFT;
7826 break;
7827
7828 case T_bottom_right:
7829 chamfers |= RECT_CHAMFER_BOTTOM_RIGHT;
7830 break;
7831
7832 case T_RIGHT:
7833 pad->SetChamferPositions( F_Cu, chamfers );
7834 end_list = true;
7835 break;
7836
7837 default:
7838 Expecting( "chamfer_top_left chamfer_top_right chamfer_bottom_left or chamfer_bottom_right" );
7839 }
7840 }
7841
7842 if( pad->GetChamferPositions( F_Cu ) != RECT_NO_CHAMFER )
7843 pad->SetShape( F_Cu, PAD_SHAPE::CHAMFERED_RECT );
7844
7845 break;
7846 }
7847
7848 case T_property:
7849 while( token != T_RIGHT )
7850 {
7851 token = NextTok();
7852
7853 switch( token )
7854 {
7855 case T_pad_prop_bga: pad->SetProperty( PAD_PROP::BGA ); break;
7856 case T_pad_prop_fiducial_glob: pad->SetProperty( PAD_PROP::FIDUCIAL_GLBL ); break;
7857 case T_pad_prop_fiducial_loc: pad->SetProperty( PAD_PROP::FIDUCIAL_LOCAL ); break;
7858 case T_pad_prop_testpoint: pad->SetProperty( PAD_PROP::TESTPOINT ); break;
7859 case T_pad_prop_castellated: pad->SetProperty( PAD_PROP::CASTELLATED ); break;
7860 case T_pad_prop_heatsink: pad->SetProperty( PAD_PROP::HEATSINK ); break;
7861 case T_pad_prop_mechanical: pad->SetProperty( PAD_PROP::MECHANICAL ); break;
7862 case T_pad_prop_pressfit: pad->SetProperty( PAD_PROP::PRESSFIT ); break;
7863 case T_none: pad->SetProperty( PAD_PROP::NONE ); break;
7864 case T_RIGHT: break;
7865
7866 default:
7867#if 0 // Currently: skip unknown property
7868 Expecting( "pad_prop_bga pad_prop_fiducial_glob pad_prop_fiducial_loc"
7869 " pad_prop_heatsink or pad_prop_castellated" );
7870#endif
7871 break;
7872 }
7873 }
7874
7875 break;
7876
7877 case T_options:
7878 parsePAD_option( pad.get(), F_Cu );
7879 break;
7880
7881 case T_padstack:
7882 parsePadstack( pad.get() );
7883 break;
7884
7885 case T_primitives:
7886 // Primitives at the top level are put in the padstack's F_Cu; other layers will be parsed
7887 // in parsePadstack().
7888 parsePAD_primitives( pad.get(), F_Cu );
7889 break;
7890
7891 case T_remove_unused_layers:
7892 {
7893 bool remove = parseMaybeAbsentBool( true );
7894 pad->SetRemoveUnconnected( remove );
7895 break;
7896 }
7897
7898 case T_keep_end_layers:
7899 {
7900 bool keep = parseMaybeAbsentBool( true );
7901 pad->SetKeepTopBottom( keep );
7902 break;
7903 }
7904
7905 case T_tenting:
7906 {
7907 auto [front, back] = parseFrontBackOptBool( true );
7908 pad->Padstack().FrontOuterLayers().has_solder_mask = front;
7909 pad->Padstack().BackOuterLayers().has_solder_mask = back;
7910 break;
7911 }
7912
7913 case T_zone_layer_connections:
7914 {
7915 LSET cuLayers = pad->GetLayerSet() & LSET::AllCuMask();
7916
7917 for( PCB_LAYER_ID layer : cuLayers )
7918 pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
7919
7920 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
7921 {
7923
7924 if( !IsCopperLayer( layer ) )
7925 Expecting( "copper layer name" );
7926
7927 pad->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
7928 }
7929
7930 break;
7931 }
7932
7933 // Continue to process "(locked)" format which was output during 5.99 development
7934 case T_locked:
7935 // Pad locking is now a session preference
7936 parseMaybeAbsentBool( true );
7937 break;
7938
7939 case T_tstamp:
7940 case T_uuid:
7941 NextTok();
7942 pad->SetUuidDirect( CurStrToKIID() );
7943 NeedRIGHT();
7944 break;
7945
7946 case T_front_post_machining:
7947 parsePostMachining( pad->Padstack().FrontPostMachining() );
7948 break;
7949
7950 case T_back_post_machining:
7951 parsePostMachining( pad->Padstack().BackPostMachining() );
7952 break;
7953
7954 case T_custom_property:
7955 parseCustomProperty( pad.get() );
7956 break;
7957
7958 default:
7959 Expecting( "at, locked, drill, layers, net, die_length, roundrect_rratio, "
7960 "solder_mask_margin, solder_paste_margin, solder_paste_margin_ratio, uuid, "
7961 "clearance, tstamp, primitives, remove_unused_layers, keep_end_layers, "
7962 "pinfunction, pintype, zone_connect, thermal_width, thermal_gap, padstack, "
7963 "teardrops, front_post_machining, back_post_machining, or custom_property" );
7964 }
7965 }
7966
7967 if( !foundNet )
7968 {
7969 // Make sure default netclass is correctly assigned to pads that don't define a net.
7970 pad->SetNetCode( 0, /* aNoAssert */ true );
7971 }
7972
7973 if( thermalBrAngleOverride )
7974 {
7975 pad->SetThermalSpokeAngle( *thermalBrAngleOverride );
7976 }
7977 else
7978 {
7979 // This is here because custom pad anchor shape isn't known before reading (options
7980 if( pad->GetShape( F_Cu ) == PAD_SHAPE::CIRCLE )
7981 {
7982 pad->SetThermalSpokeAngle( ANGLE_45 );
7983 }
7984 else if( pad->GetShape( F_Cu ) == PAD_SHAPE::CUSTOM && pad->GetAnchorPadShape( F_Cu ) == PAD_SHAPE::CIRCLE )
7985 {
7986 if( m_requiredVersion <= 20211014 ) // 6.0
7987 pad->SetThermalSpokeAngle( ANGLE_90 );
7988 else
7989 pad->SetThermalSpokeAngle( ANGLE_45 );
7990 }
7991 else
7992 {
7993 pad->SetThermalSpokeAngle( ANGLE_90 );
7994 }
7995 }
7996
7997 if( !pad->CanHaveNumber() )
7998 {
7999 // At some point it was possible to assign a number to aperture pads so we need to clean
8000 // those out here.
8001 pad->SetNumber( wxEmptyString );
8002 }
8003
8004 // Zero-sized pads are likely algorithmically unsafe.
8005 pad->Padstack().ForEachUniqueLayer(
8006 [&]( PCB_LAYER_ID aLayer )
8007 {
8008 VECTOR2I padSize = pad->GetSize( aLayer );
8009
8010 if( padSize.x <= 0 || padSize.y <= 0 )
8011 {
8012 pad->SetSize( aLayer, VECTOR2I( pcbIUScale.mmToIU( 0.001 ), pcbIUScale.mmToIU( 0.001 ) ) );
8013
8014 m_parseWarnings.push_back( wxString::Format( _( "Invalid zero-sized pad pinned to %s in\n"
8015 "file: %s\n"
8016 "line: %d\n"
8017 "offset: %d" ),
8018 wxT( "1µm" ),
8019 CurSource(), CurLineNumber(), CurOffset() ) );
8020 }
8021 } );
8022
8023 return pad.release();
8024}
8025
8026
8028{
8029 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
8030 {
8031 if( token == T_LEFT )
8032 token = NextTok();
8033
8034 switch( token )
8035 {
8036 case T_gr_arc:
8037 case T_gr_line:
8038 case T_gr_circle:
8039 case T_gr_rect:
8040 case T_gr_poly:
8041 case T_gr_curve:
8042 aPad->AddPrimitive( aLayer, parsePCB_SHAPE( nullptr ) );
8043 break;
8044
8045 case T_gr_bbox:
8046 {
8047 PCB_SHAPE* numberBox = parsePCB_SHAPE( nullptr );
8048 numberBox->SetIsProxyItem();
8049 aPad->AddPrimitive( aLayer, numberBox );
8050 break;
8051 }
8052
8053 case T_gr_vector:
8054 {
8055 PCB_SHAPE* spokeTemplate = parsePCB_SHAPE( nullptr );
8056 spokeTemplate->SetIsProxyItem();
8057 aPad->AddPrimitive( aLayer, spokeTemplate );
8058 break;
8059 }
8060
8061 default:
8062 Expecting( "gr_line, gr_arc, gr_circle, gr_curve, gr_rect, gr_bbox or gr_poly" );
8063 break;
8064 }
8065 }
8066}
8067
8068
8070{
8071 // Parse only the (option ...) inside a pad description
8072 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
8073 {
8074 if( token != T_LEFT )
8075 Expecting( T_LEFT );
8076
8077 token = NextTok();
8078
8079 switch( token )
8080 {
8081 case T_anchor:
8082 token = NextTok();
8083
8084 // Custom shaped pads have a "anchor pad", which is the reference for connection calculations.
8085 // Because this is an anchor, only the 2 very basic shapes are managed: circle and rect.
8086 switch( token )
8087 {
8088 case T_circle: aPad->SetAnchorPadShape( aLayer, PAD_SHAPE::CIRCLE ); break;
8089 case T_rect: aPad->SetAnchorPadShape( aLayer, PAD_SHAPE::RECTANGLE ); break;
8090 default: Expecting( "circle or rect" );
8091 }
8092
8093 NeedRIGHT();
8094 break;
8095
8096 case T_clearance:
8097 token = NextTok();
8098
8099 // TODO: m_customShapeInZoneMode is not per-layer at the moment
8100 if( aLayer == F_Cu )
8101 {
8102 // Custom shaped pads have a clearance area that is the pad shape (like usual pads) or the
8103 // convex hull of the pad shape.
8104 switch( token )
8105 {
8106 case T_outline: aPad->SetCustomShapeInZoneOpt( CUSTOM_SHAPE_ZONE_MODE::OUTLINE ); break;
8107 case T_convexhull: aPad->SetCustomShapeInZoneOpt( CUSTOM_SHAPE_ZONE_MODE::CONVEXHULL ); break;
8108 default: Expecting( "outline or convexhull" );
8109 }
8110 }
8111
8112 NeedRIGHT();
8113 break;
8114
8115 default:
8116 Expecting( "anchor or clearance" );
8117 break;
8118 }
8119 }
8120}
8121
8122
8124{
8125 // Parse: (front_post_machining counterbore (size ...) (depth ...) (angle ...))
8126 // or: (back_post_machining countersink (size ...) (depth ...) (angle ...))
8127 // The mode token (counterbore/countersink) comes first
8128 T token = NextTok();
8129
8130 switch( token )
8131 {
8132 case T_counterbore: aProps.mode = PAD_DRILL_POST_MACHINING_MODE::COUNTERBORE; break;
8133 case T_countersink: aProps.mode = PAD_DRILL_POST_MACHINING_MODE::COUNTERSINK; break;
8134 default: Expecting( "counterbore or countersink" );
8135 }
8136
8137 // Parse optional properties
8138 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
8139 {
8140 if( token != T_LEFT )
8141 Expecting( T_LEFT );
8142
8143 token = NextTok();
8144
8145 switch( token )
8146 {
8147 case T_size:
8148 aProps.size = parseBoardUnits( "post machining size" );
8149 NeedRIGHT();
8150 break;
8151
8152 case T_depth:
8153 aProps.depth = parseBoardUnits( "post machining depth" );
8154 NeedRIGHT();
8155 break;
8156
8157 case T_angle:
8158 aProps.angle = KiROUND( parseDouble( "post machining angle" ) * 10.0 );
8159 NeedRIGHT();
8160 break;
8161
8162 default:
8163 Expecting( "size, depth, or angle" );
8164 }
8165 }
8166}
8167
8168
8170{
8171 PADSTACK& padstack = aPad->Padstack();
8172
8173 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
8174 {
8175 if( token != T_LEFT )
8176 Expecting( T_LEFT );
8177
8178 token = NextTok();
8179
8180 switch( token )
8181 {
8182 case T_mode:
8183 token = NextTok();
8184
8185 switch( token )
8186 {
8187 case T_front_inner_back:
8189 break;
8190
8191 case T_custom:
8192 padstack.SetMode( PADSTACK::MODE::CUSTOM );
8193 break;
8194
8195 default:
8196 Expecting( "front_inner_back or custom" );
8197 }
8198
8199 NeedRIGHT();
8200 break;
8201
8202 case T_layer:
8203 {
8204 NextTok();
8205 PCB_LAYER_ID curLayer = UNDEFINED_LAYER;
8206
8207 if( curText == "Inner" )
8208 {
8209 if( padstack.Mode() != PADSTACK::MODE::FRONT_INNER_BACK )
8210 {
8211 THROW_IO_ERRORF( _( "Invalid padstack layer in\nfile: %s\nline: %d\noffset: %d." ),
8212 CurSource(), CurLineNumber(), CurOffset() );
8213 }
8214
8215 curLayer = PADSTACK::INNER_LAYERS;
8216 }
8217 else
8218 {
8219 curLayer = lookUpLayer( m_layerIndices );
8220 }
8221
8222 if( !IsCopperLayer( curLayer ) )
8223 {
8224 THROW_IO_ERRORF( _( "Invalid padstack layer '%s' in file '%s' at line %d, offset %d." ),
8225 curText, CurSource().GetData(), CurLineNumber(), CurOffset() );
8226 }
8227
8228 // Reset layer properties to default that are omitted when default in the formatter
8229 aPad->SetLibOffset( curLayer, VECTOR2I( 0, 0 ) );
8230 aPad->SetDelta( curLayer, VECTOR2I( 0, 0 ) );
8231
8232 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
8233 {
8234 if( token != T_LEFT )
8235 Expecting( T_LEFT );
8236
8237 token = NextTok();
8238
8239 switch( token )
8240 {
8241 case T_shape:
8242 token = NextTok();
8243
8244 switch( token )
8245 {
8246 case T_circle:
8247 aPad->SetShape( curLayer, PAD_SHAPE::CIRCLE );
8248 break;
8249
8250 case T_rect:
8251 aPad->SetShape( curLayer, PAD_SHAPE::RECTANGLE );
8252 break;
8253
8254 case T_oval:
8255 aPad->SetShape( curLayer, PAD_SHAPE::OVAL );
8256 break;
8257
8258 case T_trapezoid:
8259 aPad->SetShape( curLayer, PAD_SHAPE::TRAPEZOID );
8260 break;
8261
8262 case T_roundrect:
8263 // Note: the shape can be PAD_SHAPE::ROUNDRECT or PAD_SHAPE::CHAMFERED_RECT
8264 // (if chamfer parameters are found later in pad descr.)
8265 aPad->SetShape( curLayer, PAD_SHAPE::ROUNDRECT );
8266 break;
8267
8268 case T_custom:
8269 aPad->SetShape( curLayer, PAD_SHAPE::CUSTOM );
8270 break;
8271
8272 default:
8273 Expecting( "circle, rectangle, roundrect, oval, trapezoid or custom" );
8274 }
8275
8276 NeedRIGHT();
8277 break;
8278
8279 case T_size:
8280 {
8281 VECTOR2I sz;
8282 sz.x = parseBoardUnits( "width value" );
8283 sz.y = parseBoardUnits( "height value" );
8284 aPad->SetLibSize( curLayer, sz );
8285 NeedRIGHT();
8286 break;
8287 }
8288
8289 case T_offset:
8290 {
8291 VECTOR2I pt;
8292 pt.x = parseBoardUnits( "drill offset x" );
8293 pt.y = parseBoardUnits( "drill offset y" );
8294 aPad->SetLibOffset( curLayer, pt );
8295 NeedRIGHT();
8296 break;
8297 }
8298
8299 case T_rect_delta:
8300 {
8302 delta.x = parseBoardUnits( "rectangle delta width" );
8303 delta.y = parseBoardUnits( "rectangle delta height" );
8304 aPad->SetDelta( curLayer, delta );
8305 NeedRIGHT();
8306 break;
8307 }
8308
8309 case T_roundrect_rratio:
8310 aPad->SetRoundRectRadiusRatio( curLayer, parseDouble( "roundrect radius ratio" ) );
8311 NeedRIGHT();
8312 break;
8313
8314 case T_chamfer_ratio:
8315 {
8316 double ratio = parseDouble( "chamfer ratio" );
8317 aPad->SetChamferRectRatio( curLayer, ratio );
8318
8319 if( ratio > 0 )
8320 aPad->SetShape( curLayer, PAD_SHAPE::CHAMFERED_RECT );
8321
8322 NeedRIGHT();
8323 break;
8324 }
8325
8326 case T_chamfer:
8327 {
8328 int chamfers = 0;
8329 bool end_list = false;
8330
8331 while( !end_list )
8332 {
8333 token = NextTok();
8334
8335 switch( token )
8336 {
8337 case T_top_left:
8338 chamfers |= RECT_CHAMFER_TOP_LEFT;
8339 break;
8340
8341 case T_top_right:
8342 chamfers |= RECT_CHAMFER_TOP_RIGHT;
8343 break;
8344
8345 case T_bottom_left:
8346 chamfers |= RECT_CHAMFER_BOTTOM_LEFT;
8347 break;
8348
8349 case T_bottom_right:
8350 chamfers |= RECT_CHAMFER_BOTTOM_RIGHT;
8351 break;
8352
8353 case T_RIGHT:
8354 aPad->SetChamferPositions( curLayer, chamfers );
8355 end_list = true;
8356 break;
8357
8358 default:
8359 Expecting( "chamfer_top_left chamfer_top_right chamfer_bottom_left or "
8360 "chamfer_bottom_right" );
8361 }
8362 }
8363
8364 if( end_list && chamfers != RECT_NO_CHAMFER )
8365 aPad->SetShape( curLayer, PAD_SHAPE::CHAMFERED_RECT );
8366
8367 break;
8368 }
8369
8370 case T_thermal_bridge_width:
8371 padstack.ThermalSpokeWidth( curLayer ) = parseBoardUnits( "thermal relief spoke width" );
8372 NeedRIGHT();
8373 break;
8374
8375 case T_thermal_gap:
8376 padstack.ThermalGap( curLayer ) = parseBoardUnits( "thermal relief gap value" );
8377 NeedRIGHT();
8378 break;
8379
8380 case T_thermal_bridge_angle:
8381 padstack.SetThermalSpokeAngle( EDA_ANGLE( parseDouble( "thermal spoke angle" ), DEGREES_T ) );
8382 NeedRIGHT();
8383 break;
8384
8385 case T_zone_connect:
8386 padstack.ZoneConnection( curLayer ) =
8387 magic_enum::enum_cast<ZONE_CONNECTION>( parseInt( "zone connection value" ) );
8388 NeedRIGHT();
8389 break;
8390
8391 case T_clearance:
8392 padstack.Clearance( curLayer ) = parseBoardUnits( "local clearance value" );
8393 NeedRIGHT();
8394 break;
8395
8396 case T_tenting:
8397 {
8398 auto [front, back] = parseFrontBackOptBool( true );
8399 padstack.FrontOuterLayers().has_solder_mask = front;
8400 padstack.BackOuterLayers().has_solder_mask = back;
8401 break;
8402 }
8403
8404 case T_options:
8405 parsePAD_option( aPad, curLayer );
8406 break;
8407
8408 case T_primitives:
8409 // the file lists every primitive of the layer, so none inherited from another layer stay
8410 aPad->DeletePrimitivesList( curLayer );
8411 parsePAD_primitives( aPad, curLayer );
8412 break;
8413
8414 default:
8415 // Not strict-parsing padstack layers yet
8416 continue;
8417 }
8418 }
8419
8420 break;
8421 }
8422
8423 default:
8424 Expecting( "mode or layer" );
8425 break;
8426 }
8427 }
8428}
8429
8430
8432{
8433 while( NextTok() != T_RIGHT )
8434 {
8435 // This token is the Uuid of the item in the group.
8436 // Since groups are serialized at the end of the file/footprint, the Uuid should already
8437 // have been seen and exist in the board.
8438 KIID uuid( CurStr() );
8439 aGroupInfo.memberUuids.push_back( uuid );
8440 }
8441}
8442
8443
8445{
8446 for( T tok = NextTok(); tok != T_RIGHT; tok = NextTok() )
8447 {
8448 if( tok != T_LEFT )
8449 Expecting( T_LEFT );
8450
8451 if( NextTok() != T_template )
8452 Expecting( T_template );
8453
8454 wxString templateName;
8455 std::unique_ptr<BOARD_ITEM> parsed;
8456
8457 // Parse (template ...
8458 for( T innerTok = NextTok(); innerTok != T_RIGHT; innerTok = NextTok() )
8459 {
8460 if( innerTok != T_LEFT )
8461 Expecting( T_LEFT );
8462
8463 T inner = NextTok();
8464
8465 switch( inner )
8466 {
8467 case T_name:
8468 NeedSYMBOLorNUMBER();
8469 templateName = FromUTF8();
8470 NeedRIGHT();
8471 break;
8472
8473 case T_via:
8474 // A duplicate item in the same (template …) block replaces the previous one.
8475 parsed.reset( parsePCB_VIA() );
8476 // parsePCB_VIA consumes the closing T_RIGHT itself.
8477 break;
8478
8479 default: Expecting( "name or via" );
8480 }
8481 }
8482
8483 if( parsed )
8484 aGenInfo.templates.emplace_back( templateName, std::move( parsed ) );
8485 }
8486}
8487
8488
8490{
8491 wxCHECK_RET( CurTok() == T_group, wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_GROUP." ) );
8492
8493 T token;
8494
8495 m_groupInfos.push_back( GROUP_INFO() );
8496 GROUP_INFO& groupInfo = m_groupInfos.back();
8497 groupInfo.parent = aParent;
8498
8499 while( ( token = NextTok() ) != T_LEFT )
8500 {
8501 if( token == T_STRING )
8502 groupInfo.name = FromUTF8();
8503 else if( token == T_locked )
8504 groupInfo.locked = true;
8505 else
8506 Expecting( "group name or locked" );
8507 }
8508
8509 for( ; token != T_RIGHT; token = NextTok() )
8510 {
8511 if( token != T_LEFT )
8512 Expecting( T_LEFT );
8513
8514 token = NextTok();
8515
8516 switch( token )
8517 {
8518 // From formats [20200811, 20231215), 'id' was used instead of 'uuid'
8519 case T_id:
8520 case T_uuid:
8521 NextTok();
8522 groupInfo.uuid = CurStrToKIID();
8523 NeedRIGHT();
8524 break;
8525
8526 case T_lib_id:
8527 {
8528 token = NextTok();
8529
8530 if( !IsSymbol( token ) && token != T_NUMBER )
8531 Expecting( "symbol|number" );
8532
8533 wxString name = FromUTF8();
8534 // Some symbol LIB_IDs have the '/' character escaped which can break
8535 // symbol links. The '/' character is no longer an illegal LIB_ID character so
8536 // it doesn't need to be escaped.
8537 name.Replace( "{slash}", "/" );
8538
8539 int bad_pos = groupInfo.libId.Parse( name );
8540
8541 if( bad_pos >= 0 )
8542 {
8543 if( static_cast<int>( name.size() ) > bad_pos )
8544 {
8545 wxString msg = wxString::Format( _( "Group library link %s contains invalid character '%c'" ),
8546 name,
8547 name[bad_pos] );
8548
8549 THROW_PARSE_ERROR( msg, CurSource(), CurLine(), CurLineNumber(), CurOffset() );
8550 }
8551
8552 THROW_PARSE_ERROR( _( "Invalid library ID" ), CurSource(), CurLine(), CurLineNumber(), CurOffset() );
8553 }
8554
8555 NeedRIGHT();
8556 break;
8557 }
8558
8559 case T_locked:
8560 groupInfo.locked = parseBool();
8561 NeedRIGHT();
8562 break;
8563
8564 case T_members:
8565 parseGROUP_members( groupInfo );
8566 break;
8567
8568 case T_custom_property:
8570 break;
8571
8572 default:
8573 Expecting( "uuid, locked, lib_id, or members" );
8574 }
8575 }
8576}
8577
8578
8580{
8581 wxCHECK_RET( CurTok() == T_constraint,
8582 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_CONSTRAINT." ) );
8583
8584 m_constraintInfos.push_back( CONSTRAINT_INFO() );
8586 info.parent = aParent;
8587
8588 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
8589 {
8590 if( token != T_LEFT )
8591 Expecting( T_LEFT );
8592
8593 token = NextTok();
8594
8595 switch( token )
8596 {
8597 case T_type:
8598 NextTok();
8599 info.type = ConstraintTypeFromToken( FromUTF8() );
8600 NeedRIGHT();
8601 break;
8602
8603 case T_uuid:
8604 NextTok();
8605 info.uuid = CurStrToKIID();
8606 NeedRIGHT();
8607 break;
8608
8609 case T_members:
8610 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
8611 {
8612 if( token != T_LEFT )
8613 Expecting( T_LEFT );
8614
8615 if( NextTok() != T_member )
8616 Expecting( "member" );
8617
8618 NextTok(); // member uuid; resolved (and remapped on append) in resolveConstraints
8619 KIID memberId( CurStr() );
8620
8621 NextTok(); // anchor token
8623
8624 // Only VERTEX may carry an ordinal and even then optional
8625 // writer never emits one elsewhere so accepting one there breaks round-trip
8626 int index = -1;
8627
8629 {
8630 token = NextTok();
8631
8632 if( token != T_RIGHT )
8633 {
8634 if( token != T_NUMBER )
8635 Expecting( "vertex index" );
8636
8637 index = parseInt();
8638 NeedRIGHT();
8639 }
8640 }
8641 else
8642 {
8643 NeedRIGHT();
8644 }
8645
8646 info.members.emplace_back( memberId, anchor, index );
8647 }
8648
8649 break;
8650
8651 case T_value:
8652 NextTok();
8653 info.value = parseDouble();
8654 NeedRIGHT();
8655 break;
8656
8657 case T_driving:
8658 info.driving = parseBool();
8659 NeedRIGHT();
8660 break;
8661
8662 case T_custom_property:
8663 parseCustomProperty( info.customProperties );
8664 break;
8665
8666 default:
8667 Expecting( "type, uuid, members, value, or driving" );
8668 }
8669 }
8670
8671 // The value is written in mm for length/radius types; convert back to IU now that the type is
8672 // known (independent of token order within the block).
8673 if( info.value.has_value() && ConstraintValueIsLength( info.type ) )
8674 info.value = *info.value * pcbIUScale.IU_PER_MM;
8675}
8676
8677
8679{
8680 // Mirror resolveGroups: resolve every deferred constraint against the parsed items, adding
8681 // each to its own recorded parent (a board parse also sees footprint-scoped constraints, so
8682 // the resolution must not assume aParent owns them).
8683 BOARD* board = dynamic_cast<BOARD*>( aParent );
8684 FOOTPRINT* footprint = board ? nullptr : dynamic_cast<FOOTPRINT*>( aParent );
8685
8686 std::unordered_map<KIID, BOARD_ITEM*> fpItemMap;
8687
8688 if( footprint )
8689 {
8690 footprint->RunOnChildren(
8691 [&]( BOARD_ITEM* child )
8692 {
8693 fpItemMap.insert( { child->m_Uuid, child } );
8694 },
8696 }
8697
8698 auto getItem =
8699 [&]( const KIID& aId ) -> BOARD_ITEM*
8700 {
8701 if( board )
8702 {
8703 return board->ResolveItem( aId, true );
8704 }
8705 else if( footprint )
8706 {
8707 auto it = fpItemMap.find( aId );
8708
8709 return it != fpItemMap.end() ? it->second : nullptr;
8710 }
8711
8712 return nullptr;
8713 };
8714
8715 for( const CONSTRAINT_INFO& info : m_constraintInfos )
8716 {
8717 std::unique_ptr<PCB_CONSTRAINT> constraint = std::make_unique<PCB_CONSTRAINT>( info.parent, info.type );
8718
8719 constraint->SetUuidDirect( info.uuid );
8720 constraint->SetValue( info.value );
8721 constraint->SetDriving( info.driving );
8722 constraint->SetCustomProperties( info.customProperties );
8723
8724 for( const CONSTRAINT_MEMBER& member : info.members )
8725 {
8726 KIID resolvedId = member.m_item;
8727
8728 if( m_appendToExisting )
8729 {
8730 // Use the remapped uuid if this member's item was part of the appended content;
8731 // otherwise keep the original (it will dangle as an error state). find(), not
8732 // operator[], so a miss does not pollute the remap with a nil entry.
8733 auto remap = m_resetKIIDMap.find( member.m_item.AsString() );
8734
8735 if( remap != m_resetKIIDMap.end() )
8736 resolvedId = remap->second;
8737 }
8738
8739 BOARD_ITEM* item = getItem( resolvedId );
8740
8741 // A member that resolves to an item in a different footprint scope is genuinely
8742 // invalid and dropped. A member that does not resolve at all (its item was deleted)
8743 // is kept as a dangling reference: the constraint persists in an error state for the
8744 // user to repair, rather than silently losing it (Zulip "Geometry Constraint Solver",
8745 // 2026-06-18; supersedes the plan's drop-on-missing rule).
8746 if( item )
8747 {
8748 if( item->GetParentFootprint() == constraint->GetParentFootprint() )
8749 constraint->AddMember( item->m_Uuid, member.m_anchor, member.m_index );
8750 }
8751 else
8752 {
8753 constraint->AddMember( resolvedId, member.m_anchor, member.m_index );
8754 }
8755 }
8756
8757 if( info.parent->Type() == PCB_FOOTPRINT_T )
8758 static_cast<FOOTPRINT*>( info.parent )->Add( constraint.release(), ADD_MODE::INSERT, true );
8759 else
8760 static_cast<BOARD*>( info.parent )->Add( constraint.release(), ADD_MODE::INSERT, true );
8761 }
8762}
8763
8764
8766{
8767 wxCHECK_RET( CurTok() == T_generated,
8768 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_GENERATOR." ) );
8769
8770 T token;
8771
8772 m_generatorInfos.push_back( GENERATOR_INFO() );
8773 GENERATOR_INFO& genInfo = m_generatorInfos.back();
8774
8775 genInfo.layer = F_Cu;
8776 genInfo.parent = aParent;
8777 genInfo.properties = STRING_ANY_MAP( pcbIUScale.IU_PER_MM );
8778
8779 NeedLEFT();
8780 token = NextTok();
8781
8782 // For formats [20231007, 20231215), 'id' was used instead of 'uuid'
8783 if( token != T_uuid && token != T_id )
8784 Expecting( T_uuid );
8785
8786 NextTok();
8787 genInfo.uuid = CurStrToKIID();
8788 NeedRIGHT();
8789
8790 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
8791 {
8792 if( token != T_LEFT )
8793 Expecting( T_LEFT );
8794
8795 token = NextTok();
8796
8797 switch( token )
8798 {
8799 case T_type:
8800 NeedSYMBOL();
8801 genInfo.genType = FromUTF8();
8802 NeedRIGHT();
8803 break;
8804
8805 case T_name:
8806 NeedSYMBOL();
8807 genInfo.name = FromUTF8();
8808 NeedRIGHT();
8809 break;
8810
8811 case T_locked:
8812 token = NextTok();
8813 genInfo.locked = token == T_yes;
8814 NeedRIGHT();
8815 break;
8816
8817 case T_layer:
8818 genInfo.layer = parseBoardItemLayer();
8819 NeedRIGHT();
8820 break;
8821
8822 case T_members:
8823 parseGROUP_members( genInfo );
8824 break;
8825
8826 case T_templates:
8827 parseGENERATOR_templates( genInfo );
8828 break;
8829
8830 case T_custom_property:
8832 break;
8833
8834 default:
8835 {
8836 wxString pName = FromUTF8();
8837 T tok1 = NextTok();
8838
8839 switch( tok1 )
8840 {
8841 case T_yes:
8842 genInfo.properties.emplace( pName, wxAny( true ) );
8843 NeedRIGHT();
8844 break;
8845
8846 case T_no:
8847 genInfo.properties.emplace( pName, wxAny( false ) );
8848 NeedRIGHT();
8849 break;
8850
8851 case T_NUMBER:
8852 {
8853 double pValue = parseDouble();
8854 genInfo.properties.emplace( pName, wxAny( pValue ) );
8855 NeedRIGHT();
8856 break;
8857 }
8858
8859 case T_STRING: // Quoted string
8860 {
8861 wxString pValue = FromUTF8();
8862 genInfo.properties.emplace( pName, pValue );
8863 NeedRIGHT();
8864 break;
8865 }
8866
8867 case T_LEFT:
8868 {
8869 NeedSYMBOL();
8870 T tok2 = CurTok();
8871
8872 switch( tok2 )
8873 {
8874 case T_xy:
8875 {
8876 VECTOR2I pt;
8877
8878 pt.x = parseBoardUnits( "X coordinate" );
8879 pt.y = parseBoardUnits( "Y coordinate" );
8880
8881 genInfo.properties.emplace( pName, wxAny( pt ) );
8882 NeedRIGHT();
8883 NeedRIGHT();
8884 break;
8885 }
8886
8887 case T_pts:
8888 {
8890
8891 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
8893
8894 NeedRIGHT();
8895 genInfo.properties.emplace( pName, wxAny( chain ) );
8896 break;
8897 }
8898
8899 case T_cells:
8900 {
8901 std::vector<VECTOR2I> cells;
8902
8903 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
8904 {
8905 if( token != T_LEFT )
8906 Expecting( T_LEFT );
8907
8908 if( NextTok() != T_ij )
8909 Expecting( T_ij );
8910
8911 VECTOR2I cell;
8912
8913 cell.x = parseInt( "column index" );
8914 cell.y = parseInt( "row index" );
8915
8916 NeedRIGHT();
8917 cells.push_back( cell );
8918 }
8919
8920 NeedRIGHT();
8921 genInfo.properties.emplace( pName, wxAny( cells ) );
8922 break;
8923 }
8924
8925 default:
8926 Expecting( "xy, pts or cells" );
8927 }
8928
8929 break;
8930 }
8931
8932 default:
8933 Expecting( "a number, symbol, string or (" );
8934 }
8935
8936 break;
8937 }
8938 }
8939 }
8940
8941 // Previous versions had bugs which could save ghost tuning patterns. Ignore them, and
8942 // ignore member-less microvia stacks already sitting in files for the same reason.
8943 if( genInfo.memberUuids.empty()
8944 && ( genInfo.genType == wxT( "tuning_pattern" ) || genInfo.genType == wxT( "via_stack" ) ) )
8945 {
8946 m_generatorInfos.pop_back();
8947 }
8948}
8949
8950
8952{
8953 wxCHECK_MSG( CurTok() == T_arc, nullptr, wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as ARC." ) );
8954
8955 VECTOR2I pt;
8956 std::unique_ptr<PCB_ARC> arc = std::make_unique<PCB_ARC>( m_board );
8957
8958 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
8959 {
8960 // Legacy locked
8961 if( token == T_locked )
8962 {
8963 arc->SetLocked( true );
8964 token = NextTok();
8965 }
8966
8967 if( token != T_LEFT )
8968 Expecting( T_LEFT );
8969
8970 token = NextTok();
8971
8972 switch( token )
8973 {
8974 case T_start:
8975 pt.x = parseBoardUnits( "start x" );
8976 pt.y = parseBoardUnits( "start y" );
8977 arc->SetStart( pt );
8978 NeedRIGHT();
8979 break;
8980
8981 case T_mid:
8982 pt.x = parseBoardUnits( "mid x" );
8983 pt.y = parseBoardUnits( "mid y" );
8984 arc->SetMid( pt );
8985 NeedRIGHT();
8986 break;
8987
8988 case T_end:
8989 pt.x = parseBoardUnits( "end x" );
8990 pt.y = parseBoardUnits( "end y" );
8991 arc->SetEnd( pt );
8992 NeedRIGHT();
8993 break;
8994
8995 case T_width:
8996 arc->SetWidth( parseBoardUnits( "width" ) );
8997 NeedRIGHT();
8998 break;
8999
9000 case T_layer:
9001 arc->SetLayer( parseBoardItemLayer() );
9002 NeedRIGHT();
9003 break;
9004
9005 case T_layers:
9006 arc->SetLayerSet( parseLayersForCuItemWithSoldermask() );
9007 break;
9008
9009 case T_solder_mask_margin:
9010 arc->SetLocalSolderMaskMargin( parseBoardUnits( "local solder mask margin value" ) );
9011 NeedRIGHT();
9012 break;
9013
9014 case T_net:
9015 parseNet( arc.get() );
9016 break;
9017
9018 case T_tstamp:
9019 case T_uuid:
9020 NextTok();
9021 arc->SetUuidDirect( CurStrToKIID() );
9022 NeedRIGHT();
9023 break;
9024
9025 // We continue to parse the status field but it is no longer written
9026 case T_status:
9027 parseHex();
9028 NeedRIGHT();
9029 break;
9030
9031 case T_locked:
9032 arc->SetLocked( parseMaybeAbsentBool( true ) );
9033 break;
9034
9035 case T_custom_property:
9036 parseCustomProperty( arc.get() );
9037 break;
9038
9039 default:
9040 Expecting( "start, mid, end, width, layer, solder_mask_margin, net, tstamp, uuid or status" );
9041 }
9042 }
9043
9044 if( !IsCopperLayer( arc->GetLayer() ) )
9045 {
9046 // No point in asserting; these usually come from hand-edited boards
9047 return nullptr;
9048 }
9049
9050 // Collinear points have no arc center, so load them as the straight track they describe
9051 if( IsStraightArc( arc->GetStart(), arc->GetMid(), arc->GetEnd() ) )
9052 {
9053 std::unique_ptr<PCB_TRACK> track = std::make_unique<PCB_TRACK>( m_board );
9054
9055 // Base assignment copies every track property except the item type and UUID
9056 static_cast<PCB_TRACK&>( *track ) = *arc;
9057 track->SetUuidDirect( arc->m_Uuid );
9058 return track.release();
9059 }
9060
9061 return arc.release();
9062}
9063
9064
9066{
9067 wxCHECK_MSG( CurTok() == T_segment, nullptr,
9068 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_TRACK." ) );
9069
9070 VECTOR2I pt;
9071 std::unique_ptr<PCB_TRACK> track = std::make_unique<PCB_TRACK>( m_board );
9072
9073 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
9074 {
9075 // Legacy locked flag
9076 if( token == T_locked )
9077 {
9078 track->SetLocked( true );
9079 token = NextTok();
9080 }
9081
9082 if( token != T_LEFT )
9083 Expecting( T_LEFT );
9084
9085 token = NextTok();
9086
9087 switch( token )
9088 {
9089 case T_start:
9090 pt.x = parseBoardUnits( "start x" );
9091 pt.y = parseBoardUnits( "start y" );
9092 track->SetStart( pt );
9093 NeedRIGHT();
9094 break;
9095
9096 case T_end:
9097 pt.x = parseBoardUnits( "end x" );
9098 pt.y = parseBoardUnits( "end y" );
9099 track->SetEnd( pt );
9100 NeedRIGHT();
9101 break;
9102
9103 case T_width:
9104 track->SetWidth( parseBoardUnits( "width" ) );
9105 NeedRIGHT();
9106 break;
9107
9108 case T_layer:
9109 track->SetLayer( parseBoardItemLayer() );
9110 NeedRIGHT();
9111 break;
9112
9113 case T_layers:
9114 track->SetLayerSet( parseLayersForCuItemWithSoldermask() );
9115 break;
9116
9117 case T_solder_mask_margin:
9118 track->SetLocalSolderMaskMargin( parseBoardUnits( "local solder mask margin value" ) );
9119 NeedRIGHT();
9120 break;
9121
9122 case T_net:
9123 parseNet( track.get() );
9124 break;
9125
9126 case T_tstamp:
9127 case T_uuid:
9128 NextTok();
9129 track->SetUuidDirect( CurStrToKIID() );
9130 NeedRIGHT();
9131 break;
9132
9133 // We continue to parse the status field but it is no longer written
9134 case T_status:
9135 parseHex();
9136 NeedRIGHT();
9137 break;
9138
9139 case T_locked:
9140 track->SetLocked( parseMaybeAbsentBool( true ) );
9141 break;
9142
9143 case T_custom_property:
9144 parseCustomProperty( track.get() );
9145 break;
9146
9147 default:
9148 Expecting( "start, end, width, layer, solder_mask_margin, net, tstamp, uuid or locked" );
9149 }
9150 }
9151
9152 if( !IsCopperLayer( track->GetLayer() ) )
9153 {
9154 // No point in asserting; these usually come from hand-edited boards
9155 return nullptr;
9156 }
9157
9158 return track.release();
9159}
9160
9161
9163{
9164 wxCHECK_MSG( CurTok() == T_via, nullptr,
9165 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_VIA." ) );
9166
9167 VECTOR2I pt;
9168 std::unique_ptr<PCB_VIA> via = std::make_unique<PCB_VIA>( m_board );
9169
9170 // NB: all pre-padstack tokens are stored into the F_Cu layer. For PADSTACK::MODE::NORMAL
9171 // this will be all there is. For complex padstacks, the other values will get loaded from the
9172 // T_padstack record.
9173
9174 // File format default is no-token == no-feature.
9175 via->Padstack().SetUnconnectedLayerMode( UNCONNECTED_LAYER_MODE::KEEP_ALL );
9176
9177 // Versions before 10.0 had no protection features other than tenting, so those features must
9178 // be interpreted as OFF in legacy boards, not as unspecified (aka: inherit from board stackup)
9179 if( m_requiredVersion < 20250228 )
9180 {
9181 via->Padstack().FrontOuterLayers().has_covering = false;
9182 via->Padstack().BackOuterLayers().has_covering = false;
9183 via->Padstack().FrontOuterLayers().has_plugging = false;
9184 via->Padstack().BackOuterLayers().has_plugging = false;
9185 via->Padstack().Drill().is_filled = false;
9186 via->Padstack().Drill().is_capped = false;
9187 }
9188
9189 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
9190 {
9191 // Legacy locked
9192 if( token == T_locked )
9193 {
9194 via->SetLocked( true );
9195 token = NextTok();
9196 }
9197
9198 if( token == T_LEFT )
9199 token = NextTok();
9200
9201 switch( token )
9202 {
9203 case T_blind:
9204 via->SetViaType( VIATYPE::BLIND );
9205 break;
9206
9207 case T_buried:
9208 via->SetViaType( VIATYPE::BURIED );
9209 break;
9210
9211 case T_micro:
9212 via->SetViaType( VIATYPE::MICROVIA );
9213 break;
9214
9215 case T_at:
9216 pt.x = parseBoardUnits( "start x" );
9217 pt.y = parseBoardUnits( "start y" );
9218 via->SetStart( pt );
9219 via->SetEnd( pt );
9220 NeedRIGHT();
9221 break;
9222
9223 case T_size:
9224 via->SetWidth( F_Cu, parseBoardUnits( "via width" ) );
9225 NeedRIGHT();
9226 break;
9227
9228 case T_drill:
9229 via->SetDrill( parseBoardUnits( "drill diameter" ) );
9230 NeedRIGHT();
9231 break;
9232
9233 case T_layers:
9234 {
9235 PCB_LAYER_ID layer1, layer2;
9236 NextTok();
9237 layer1 = lookUpLayer( m_layerIndices );
9238 NextTok();
9239 layer2 = lookUpLayer( m_layerIndices );
9240 via->SetLayerPair( layer1, layer2 );
9241
9242 if( layer1 == UNDEFINED_LAYER || layer2 == UNDEFINED_LAYER )
9243 Expecting( "layer name" );
9244
9245 NeedRIGHT();
9246 break;
9247 }
9248
9249 case T_net:
9250 parseNet( via.get() );
9251 break;
9252
9253 case T_remove_unused_layers:
9254 if( parseMaybeAbsentBool( true ) )
9255 via->SetRemoveUnconnected( true );
9256
9257 break;
9258
9259 case T_keep_end_layers:
9260 if( parseMaybeAbsentBool( true ) )
9261 via->SetKeepStartEnd( true );
9262
9263 break;
9264
9265 case T_start_end_only:
9266 if( parseMaybeAbsentBool( true ) )
9267 via->Padstack().SetUnconnectedLayerMode( UNCONNECTED_LAYER_MODE::START_END_ONLY );
9268
9269 break;
9270
9271 case T_zone_layer_connections:
9272 {
9273 // Ensure only copper layers are stored int ZoneLayerOverride array
9274 LSET cuLayers = via->GetLayerSet() & LSET::AllCuMask();
9275
9276 for( PCB_LAYER_ID layer : cuLayers )
9277 via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
9278
9279 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9280 {
9282
9283 if( !IsCopperLayer( layer ) )
9284 Expecting( "copper layer name" );
9285
9286 via->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
9287 }
9288
9289 break;
9290 }
9291
9292 case T_padstack:
9293 parseViastack( via.get() );
9294 break;
9295
9296 case T_teardrops:
9297 parseTEARDROP_PARAMETERS( &via->GetTeardropParams() );
9298 break;
9299
9300 case T_tenting:
9301 {
9302 auto [front, back] = parseFrontBackOptBool( true );
9303 via->Padstack().FrontOuterLayers().has_solder_mask = front;
9304 via->Padstack().BackOuterLayers().has_solder_mask = back;
9305 break;
9306 }
9307
9308 case T_covering:
9309 {
9310 auto [front, back] = parseFrontBackOptBool();
9311 via->Padstack().FrontOuterLayers().has_covering = front;
9312 via->Padstack().BackOuterLayers().has_covering = back;
9313 break;
9314 }
9315
9316 case T_plugging:
9317 {
9318 auto [front, back] = parseFrontBackOptBool();
9319 via->Padstack().FrontOuterLayers().has_plugging = front;
9320 via->Padstack().BackOuterLayers().has_plugging = back;
9321 break;
9322 }
9323
9324 case T_filling:
9325 via->Padstack().Drill().is_filled = parseOptBool();
9326 NeedRIGHT();
9327 break;
9328
9329 case T_capping:
9330 via->Padstack().Drill().is_capped = parseOptBool();
9331 NeedRIGHT();
9332 break;
9333
9334 case T_tstamp:
9335 case T_uuid:
9336 NextTok();
9337 via->SetUuidDirect( CurStrToKIID() );
9338 NeedRIGHT();
9339 break;
9340
9341 // We continue to parse the status field but it is no longer written
9342 case T_status:
9343 parseHex();
9344 NeedRIGHT();
9345 break;
9346
9347 case T_locked:
9348 via->SetLocked( parseMaybeAbsentBool( true ) );
9349 break;
9350
9351 case T_free:
9352 via->SetIsFree( parseMaybeAbsentBool( true ) );
9353 break;
9354
9355 case T_backdrill:
9356 {
9357 // Parse: (backdrill (size ...) (layers start end))
9358 PADSTACK::DRILL_PROPS& secondary = via->Padstack().SecondaryDrill();
9359
9360 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9361 {
9362 if( token != T_LEFT )
9363 Expecting( T_LEFT );
9364
9365 token = NextTok();
9366
9367 switch( token )
9368 {
9369 case T_size:
9370 {
9371 int size = parseBoardUnits( "backdrill size" );
9372 secondary.size = VECTOR2I( size, size );
9373 NeedRIGHT();
9374 break;
9375 }
9376
9377 case T_layers:
9378 {
9379 NextTok();
9380 secondary.start = lookUpLayer( m_layerIndices, true );
9381 NextTok();
9382 secondary.end = lookUpLayer( m_layerIndices, true );
9383 NeedRIGHT();
9384 break;
9385 }
9386
9387 default:
9388 Expecting( "size or layers" );
9389 }
9390 }
9391
9392 if( secondary.start == UNDEFINED_LAYER )
9393 secondary.size = VECTOR2I( 0, 0 );
9394
9395 break;
9396 }
9397
9398 case T_tertiary_drill:
9399 {
9400 // Parse: (tertiary_drill (size ...) (layers start end))
9401 PADSTACK::DRILL_PROPS& tertiary = via->Padstack().TertiaryDrill();
9402
9403 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9404 {
9405 if( token != T_LEFT )
9406 Expecting( T_LEFT );
9407
9408 token = NextTok();
9409
9410 switch( token )
9411 {
9412 case T_size:
9413 {
9414 int size = parseBoardUnits( "tertiary drill size" );
9415 tertiary.size = VECTOR2I( size, size );
9416 NeedRIGHT();
9417 break;
9418 }
9419
9420 case T_layers:
9421 {
9422 NextTok();
9423 tertiary.start = lookUpLayer( m_layerIndices, true );
9424 NextTok();
9425 tertiary.end = lookUpLayer( m_layerIndices, true );
9426 NeedRIGHT();
9427 break;
9428 }
9429
9430 default:
9431 Expecting( "size or layers" );
9432 }
9433 }
9434
9435 if( tertiary.start == UNDEFINED_LAYER )
9436 tertiary.size = VECTOR2I( 0, 0 );
9437
9438 break;
9439 }
9440
9441 case T_front_post_machining:
9442 parsePostMachining( via->Padstack().FrontPostMachining() );
9443 break;
9444
9445 case T_back_post_machining:
9446 parsePostMachining( via->Padstack().BackPostMachining() );
9447 break;
9448
9449 case T_custom_property:
9450 parseCustomProperty( via.get() );
9451 break;
9452
9453 default:
9454 Expecting( "blind, micro, at, size, drill, layers, net, free, tstamp, uuid, status, "
9455 "teardrops, backdrill, tertiary_drill, front_post_machining, or back_post_machining" );
9456 }
9457 }
9458
9459 return via.release();
9460}
9461
9462
9463std::pair<std::optional<bool>, std::optional<bool>>
9465{
9466 T token = NextTok();
9467
9468 std::pair<std::optional<bool>, std::optional<bool>> result;
9469 auto& [front, back] = result;
9470
9471 if( token != T_LEFT && aAllowLegacyFormat )
9472 {
9473 // legacy format for tenting.
9474 while( token != T_RIGHT )
9475 {
9476 if( token == T_front )
9477 {
9478 front = true;
9479 }
9480 else if( token == T_back )
9481 {
9482 back = true;
9483 }
9484 else if( token == T_none )
9485 {
9486 front.reset();
9487 back.reset();
9488 }
9489 else
9490 {
9491 Expecting( "front, back or none" );
9492 }
9493
9494 token = NextTok();
9495 }
9496
9497 return result;
9498 }
9499
9500 while( token != T_RIGHT )
9501 {
9502 if( token != T_LEFT )
9503 Expecting( "(" );
9504
9505 token = NextTok();
9506
9507 if( token == T_front )
9508 front = parseOptBool();
9509 else if( token == T_back )
9510 back = parseOptBool();
9511 else
9512 Expecting( "front or back" );
9513
9514 NeedRIGHT();
9515
9516 token = NextTok();
9517 }
9518
9519 return result;
9520}
9521
9522
9524{
9525 PADSTACK& padstack = aVia->Padstack();
9526
9527 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
9528 {
9529 if( token != T_LEFT )
9530 Expecting( T_LEFT );
9531
9532 token = NextTok();
9533
9534 switch( token )
9535 {
9536 case T_mode:
9537 token = NextTok();
9538
9539 switch( token )
9540 {
9541 case T_front_inner_back: padstack.SetMode( PADSTACK::MODE::FRONT_INNER_BACK ); break;
9542 case T_custom: padstack.SetMode( PADSTACK::MODE::CUSTOM ); break;
9543 default: Expecting( "front_inner_back or custom" );
9544 }
9545
9546 NeedRIGHT();
9547 break;
9548
9549 case T_layer:
9550 {
9551 NextTok();
9552 PCB_LAYER_ID curLayer = UNDEFINED_LAYER;
9553
9554 if( curText == "Inner" )
9555 {
9556 if( padstack.Mode() != PADSTACK::MODE::FRONT_INNER_BACK )
9557 {
9558 THROW_IO_ERRORF( _( "Invalid padstack layer in\nfile: %s\nline: %d\noffset: %d." ),
9559 CurSource(), CurLineNumber(), CurOffset() );
9560 }
9561
9562 curLayer = PADSTACK::INNER_LAYERS;
9563 }
9564 else
9565 {
9566 curLayer = lookUpLayer( m_layerIndices );
9567 }
9568
9569 if( !IsCopperLayer( curLayer ) )
9570 {
9571 THROW_IO_ERRORF( _( "Invalid padstack layer '%s' in file '%s' at line %d, offset %d." ),
9572 curText, CurSource().GetData(), CurLineNumber(), CurOffset() );
9573 }
9574
9575 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9576 {
9577 if( token != T_LEFT )
9578 Expecting( T_LEFT );
9579
9580 token = NextTok();
9581
9582 switch( token )
9583 {
9584
9585 case T_size:
9586 {
9587 int diameter = parseBoardUnits( "via width" );
9588 padstack.SetSize( { diameter, diameter }, curLayer );
9589 NeedRIGHT();
9590 break;
9591 }
9592
9593 default:
9594 // Currently only supporting custom via diameter per layer, not other properties
9595 Expecting( "size" );
9596 }
9597 }
9598
9599 break;
9600 }
9601
9602 default:
9603 Expecting( "mode or layer" );
9604 break;
9605 }
9606 }
9607}
9608
9609
9611{
9612 wxCHECK_MSG( CurTok() == T_zone, nullptr,
9613 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as ZONE." ) );
9614
9616
9617 int hatchPitch = ZONE::GetDefaultHatchPitch();
9618 int tmp;
9619 wxString legacyNetnameFromFile; // the (non-authoratative) zone net name found in a legacy file
9620
9621 // bigger scope since each filled_polygon is concatenated in here
9622 std::map<PCB_LAYER_ID, SHAPE_POLY_SET> pts;
9623 std::map<PCB_LAYER_ID, std::vector<SEG>> legacySegs;
9624 PCB_LAYER_ID filledLayer;
9625 bool addedFilledPolygons = false;
9626
9627 // This hasn't been supported since V6 or so, but we only stopped writing out the token
9628 // in V10.
9629 bool isStrokedFill = m_requiredVersion < 20250210;
9630
9631 std::unique_ptr<ZONE> zone = std::make_unique<ZONE>( aParent );
9632
9633 zone->SetAssignedPriority( 0 );
9634
9635 // This is the default for board files:
9636 zone->SetIslandRemovalMode( ISLAND_REMOVAL_MODE::ALWAYS );
9637
9638 // The ZONE ctor copies the board's default zone settings, but these tokens are
9639 // omitted from the file when at their defaults. Reset them so appending into a
9640 // live board (design block, paste) doesn't pick up its session defaults.
9641 zone->SetPadConnection( ZONE_CONNECTION::THERMAL );
9642 zone->SetFillMode( ZONE_FILL_MODE::POLYGONS );
9643 zone->SetCornerSmoothingType( ZONE_SETTINGS::CORNER_SMOOTHING::NO_SMOOTHING );
9644 zone->SetCornerRadius( 0 );
9645 zone->SetHatchSmoothingLevel( 0 );
9646 zone->SetLocked( false );
9647
9648 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
9649 {
9650 // legacy locked
9651 if( token == T_locked )
9652 {
9653 zone->SetLocked( true );
9654 token = NextTok();
9655 }
9656
9657 if( token == T_LEFT )
9658 token = NextTok();
9659
9660 switch( token )
9661 {
9662 case T_net:
9663 parseNet( zone.get() );
9664 break;
9665
9666 case T_net_name:
9667 NeedSYMBOLorNUMBER();
9668 legacyNetnameFromFile = FromUTF8();
9669 NeedRIGHT();
9670 break;
9671
9672 case T_layer: // keyword for zones that are on only one layer
9673 zone->SetLayer( parseBoardItemLayer() );
9674 NeedRIGHT();
9675 break;
9676
9677 case T_layers: // keyword for zones that can live on a set of layers
9678 zone->SetLayerSet( parseBoardItemLayersAsMask() );
9679 break;
9680
9681 case T_property:
9682 parseZoneLayerProperty( zone->LayerProperties() );
9683 break;
9684
9685 case T_tstamp:
9686 case T_uuid:
9687 NextTok();
9688 zone->SetUuidDirect( CurStrToKIID() );
9689 NeedRIGHT();
9690 break;
9691
9692 case T_hatch:
9693 token = NextTok();
9694
9695 if( token != T_none && token != T_edge && token != T_full )
9696 Expecting( "none, edge, or full" );
9697
9698 switch( token )
9699 {
9700 default:
9701 case T_none: hatchStyle = ZONE_BORDER_DISPLAY_STYLE::NO_HATCH; break;
9702 case T_edge: hatchStyle = ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_EDGE; break;
9703 case T_full: hatchStyle = ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_FULL; break;
9704 }
9705
9706 hatchPitch = parseBoardUnits( "hatch pitch" );
9707 NeedRIGHT();
9708 break;
9709
9710 case T_priority:
9711 zone->SetAssignedPriority( parseInt( "zone priority" ) );
9712 NeedRIGHT();
9713 break;
9714
9715 case T_connect_pads:
9716 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9717 {
9718 if( token == T_LEFT )
9719 token = NextTok();
9720
9721 switch( token )
9722 {
9723 case T_yes:
9724 zone->SetPadConnection( ZONE_CONNECTION::FULL );
9725 break;
9726
9727 case T_no:
9728 zone->SetPadConnection( ZONE_CONNECTION::NONE );
9729 break;
9730
9731 case T_thru_hole_only:
9732 zone->SetPadConnection( ZONE_CONNECTION::THT_THERMAL );
9733 break;
9734
9735 case T_clearance:
9736 zone->SetLocalClearance( parseBoardUnits( "zone clearance" ) );
9737 NeedRIGHT();
9738 break;
9739
9740 default:
9741 Expecting( "yes, no, or clearance" );
9742 }
9743 }
9744
9745 break;
9746
9747 case T_min_thickness:
9748 zone->SetMinThickness( parseBoardUnits( T_min_thickness ) );
9749 NeedRIGHT();
9750 break;
9751
9752 case T_filled_areas_thickness:
9753 // A new zone fill strategy was added in v6, so we need to know if we're parsing
9754 // a zone that was filled before that. Note that the change was implemented as
9755 // a new parameter, so we need to check for the presence of filled_areas_thickness
9756 // instead of just its value.
9757
9758 if( !parseBool() )
9759 isStrokedFill = false;
9760
9761 NeedRIGHT();
9762 break;
9763
9764 case T_fill:
9765 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9766 {
9767 if( token == T_LEFT )
9768 token = NextTok();
9769
9770 switch( token )
9771 {
9772 case T_yes:
9773 zone->SetIsFilled( true );
9774 break;
9775
9776 case T_mode:
9777 token = NextTok();
9778
9779 if( token != T_segment && token != T_hatch && token != T_polygon
9780 && token != T_thieving )
9781 {
9782 Expecting( "segment, hatch, polygon or thieving" );
9783 }
9784
9785 switch( token )
9786 {
9787 case T_hatch:
9788 zone->SetFillMode( ZONE_FILL_MODE::HATCH_PATTERN );
9789 break;
9790
9791 case T_thieving:
9792 if( m_requiredVersion < 20260513 )
9793 {
9794 Expecting( "segment, hatch or polygon "
9795 "(thieving requires file version >= 20260513)" );
9796 }
9797
9798 zone->SetFillMode( ZONE_FILL_MODE::COPPER_THIEVING );
9799 break;
9800
9801 case T_segment: // deprecated, convert to polygons
9802 case T_polygon:
9803 default:
9804 zone->SetFillMode( ZONE_FILL_MODE::POLYGONS );
9805 break;
9806 }
9807
9808 NeedRIGHT();
9809 break;
9810
9811 case T_hatch_thickness:
9812 zone->SetHatchThickness( parseBoardUnits( T_hatch_thickness ) );
9813 NeedRIGHT();
9814 break;
9815
9816 case T_hatch_gap:
9817 zone->SetHatchGap( parseBoardUnits( T_hatch_gap ) );
9818 NeedRIGHT();
9819 break;
9820
9821 case T_hatch_orientation:
9822 {
9823 EDA_ANGLE orientation( parseDouble( T_hatch_orientation ), DEGREES_T );
9824 zone->SetHatchOrientation( orientation );
9825 NeedRIGHT();
9826 break;
9827 }
9828
9829 case T_hatch_smoothing_level:
9830 zone->SetHatchSmoothingLevel( parseDouble( T_hatch_smoothing_level ) );
9831 NeedRIGHT();
9832 break;
9833
9834 case T_hatch_smoothing_value:
9835 zone->SetHatchSmoothingValue( parseDouble( T_hatch_smoothing_value ) );
9836 NeedRIGHT();
9837 break;
9838
9839 case T_hatch_border_algorithm:
9840 token = NextTok();
9841
9842 if( token != T_hatch_thickness && token != T_min_thickness )
9843 Expecting( "hatch_thickness or min_thickness" );
9844
9845 zone->SetHatchBorderAlgorithm( token == T_hatch_thickness ? 1 : 0 );
9846 NeedRIGHT();
9847 break;
9848
9849 case T_hatch_min_hole_area:
9850 zone->SetHatchHoleMinArea( parseDouble( T_hatch_min_hole_area ) );
9851 NeedRIGHT();
9852 break;
9853
9854 case T_thieving:
9855 {
9856 if( m_requiredVersion < 20260513 )
9857 {
9858 Expecting( "thieving requires file version >= 20260513" );
9859 }
9860
9861 THIEVING_SETTINGS thieving = zone->GetThievingSettings();
9862
9863 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
9864 {
9865 if( token == T_LEFT )
9866 token = NextTok();
9867
9868 switch( token )
9869 {
9870 case T_type:
9871 token = NextTok();
9872
9873 switch( token )
9874 {
9875 case T_dots: thieving.pattern = THIEVING_PATTERN::DOTS; break;
9876 case T_squares: thieving.pattern = THIEVING_PATTERN::SQUARES; break;
9877 case T_hatch: thieving.pattern = THIEVING_PATTERN::HATCH; break;
9878 default: Expecting( "dots, squares or hatch" );
9879 }
9880
9881 NeedRIGHT();
9882 break;
9883
9884 // Reject non-positive geometry inline. Zero size would emit
9885 // zero-area stamps and zero gap would deadlock the filler grid
9886 // loop. The zone's existing setting (constructor defaults)
9887 // stays in place for any malformed field.
9888 case T_size:
9889 {
9890 int val = parseBoardUnits( T_size );
9891
9892 if( val > 0 )
9893 thieving.element_size = val;
9894
9895 NeedRIGHT();
9896 break;
9897 }
9898
9899 case T_gap:
9900 {
9901 int val = parseBoardUnits( T_gap );
9902
9903 if( val > 0 )
9904 thieving.gap = val;
9905
9906 NeedRIGHT();
9907 break;
9908 }
9909
9910 case T_width:
9911 {
9912 int val = parseBoardUnits( T_width );
9913
9914 if( val > 0 )
9915 thieving.line_width = val;
9916
9917 NeedRIGHT();
9918 break;
9919 }
9920
9921 case T_stagger:
9922 thieving.stagger = parseBool();
9923 NeedRIGHT();
9924 break;
9925
9926 case T_orientation:
9927 thieving.orientation = EDA_ANGLE( parseDouble( T_orientation ),
9928 DEGREES_T );
9929 NeedRIGHT();
9930 break;
9931
9932 default:
9933 Expecting( "type, size, gap, width, stagger or orientation" );
9934 }
9935 }
9936
9937 zone->SetThievingSettings( thieving );
9938 break;
9939 }
9940
9941 case T_arc_segments:
9942 ignore_unused( parseInt( "arc segment count" ) );
9943 NeedRIGHT();
9944 break;
9945
9946 case T_thermal_gap:
9947 zone->SetThermalReliefGap( parseBoardUnits( T_thermal_gap ) );
9948 NeedRIGHT();
9949 break;
9950
9951 case T_thermal_bridge_width:
9952 zone->SetThermalReliefSpokeWidth( parseBoardUnits( T_thermal_bridge_width ) );
9953 NeedRIGHT();
9954 break;
9955
9956 case T_smoothing:
9957 switch( NextTok() )
9958 {
9959 case T_none:
9960 zone->SetCornerSmoothingType( ZONE_SETTINGS::CORNER_SMOOTHING::NO_SMOOTHING );
9961 break;
9962
9963 case T_chamfer:
9964 if( !zone->GetIsRuleArea() ) // smoothing has meaning only for filled zones
9965 zone->SetCornerSmoothingType( ZONE_SETTINGS::CORNER_SMOOTHING::CHAMFER );
9966
9967 break;
9968
9969 case T_fillet:
9970 if( !zone->GetIsRuleArea() ) // smoothing has meaning only for filled zones
9971 zone->SetCornerSmoothingType( ZONE_SETTINGS::CORNER_SMOOTHING::FILLET );
9972
9973 break;
9974
9975 default:
9976 Expecting( "none, chamfer, or fillet" );
9977 }
9978
9979 NeedRIGHT();
9980 break;
9981
9982 case T_radius:
9983 tmp = parseBoardUnits( "corner radius" );
9984
9985 if( !zone->GetIsRuleArea() ) // smoothing has meaning only for filled zones
9986 zone->SetCornerRadius( tmp );
9987
9988 NeedRIGHT();
9989 break;
9990
9991 case T_island_removal_mode:
9992 tmp = parseInt( "island_removal_mode" );
9993
9994 if( tmp >= 0 && tmp <= 2 )
9995 zone->SetIslandRemovalMode( static_cast<ISLAND_REMOVAL_MODE>( tmp ) );
9996
9997 NeedRIGHT();
9998 break;
9999
10000 case T_island_area_min:
10001 {
10002 int area = parseBoardUnits( T_island_area_min );
10003 zone->SetMinIslandArea( area * pcbIUScale.IU_PER_MM );
10004 NeedRIGHT();
10005 break;
10006 }
10007
10008 default:
10009 Expecting( "mode, arc_segments, thermal_gap, thermal_bridge_width, "
10010 "hatch_thickness, hatch_gap, hatch_orientation, "
10011 "hatch_smoothing_level, hatch_smoothing_value, "
10012 "hatch_border_algorithm, hatch_min_hole_area, thieving, "
10013 "smoothing, radius, island_removal_mode, or island_area_min" );
10014 }
10015 }
10016
10017 break;
10018
10019 case T_placement:
10020 zone->SetIsRuleArea( true );
10021
10022 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10023 {
10024 if( token == T_LEFT )
10025 token = NextTok();
10026
10027 switch( token )
10028 {
10029 case T_sheetname:
10030 {
10031 zone->SetPlacementAreaSourceType( PLACEMENT_SOURCE_T::SHEETNAME );
10032 NeedSYMBOL();
10033 zone->SetPlacementAreaSource( FromUTF8() );
10034 break;
10035 }
10036 case T_component_class:
10037 {
10038 zone->SetPlacementAreaSourceType( PLACEMENT_SOURCE_T::COMPONENT_CLASS );
10039 NeedSYMBOL();
10040 zone->SetPlacementAreaSource( FromUTF8() );
10041 break;
10042 }
10043 case T_group:
10044 {
10045 zone->SetPlacementAreaSourceType( PLACEMENT_SOURCE_T::GROUP_PLACEMENT );
10046 NeedSYMBOL();
10047 zone->SetPlacementAreaSource( FromUTF8() );
10048 break;
10049 }
10050 case T_enabled:
10051 {
10052 token = NextTok();
10053
10054 if( token == T_yes )
10055 zone->SetPlacementAreaEnabled( true );
10056 else if( token == T_no )
10057 zone->SetPlacementAreaEnabled( false );
10058 else
10059 Expecting( "yes or no" );
10060
10061 break;
10062 }
10063 case T_link:
10064 {
10066
10067 NeedSYMBOL();
10068 zone->SetLinkSet( KIID( CurStr() ) );
10069
10070 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10071 {
10072 if( token == T_LEFT )
10073 token = NextTok();
10074
10075 switch( token )
10076 {
10077 case T_placement: opts.m_copyPlacement = parseBool(); break;
10078 case T_routing: opts.m_copyRouting = parseBool(); break;
10079 case T_connected_routing: opts.m_connectedRoutingOnly = parseBool(); break;
10080 case T_other_items: opts.m_copyOtherItems = parseBool(); break;
10081 case T_group_items: opts.m_groupItems = parseBool(); break;
10082 case T_locked_items: opts.m_includeLockedItems = parseBool(); break;
10083 case T_anchor:
10084 NeedSYMBOL();
10085 opts.m_anchor = KIID( CurStr() );
10086 break;
10087 default:
10088 Expecting( "placement, routing, connected_routing, other_items, group_items, "
10089 "locked_items or anchor" );
10090 }
10091
10092 NeedRIGHT();
10093 }
10094
10095 zone->SetRepeatOptions( opts );
10096
10097 // The loop already consumed the closing paren
10098 continue;
10099 }
10100 default:
10101 {
10102 Expecting( "enabled, sheetname, component_class, group or link" );
10103 break;
10104 }
10105 }
10106
10107 NeedRIGHT();
10108 }
10109
10110 break;
10111
10112 case T_keepout:
10113 // "keepout" now means rule area, but the file token stays the same
10114 zone->SetIsRuleArea( true );
10115
10116 // Initialize these two because their tokens won't appear in older files:
10117 zone->SetDoNotAllowPads( false );
10118 zone->SetDoNotAllowFootprints( false );
10119
10120 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10121 {
10122 if( token == T_LEFT )
10123 token = NextTok();
10124
10125 switch( token )
10126 {
10127 case T_tracks:
10128 token = NextTok();
10129
10130 if( token != T_allowed && token != T_not_allowed )
10131 Expecting( "allowed or not_allowed" );
10132
10133 zone->SetDoNotAllowTracks( token == T_not_allowed );
10134 break;
10135
10136 case T_vias:
10137 token = NextTok();
10138
10139 if( token != T_allowed && token != T_not_allowed )
10140 Expecting( "allowed or not_allowed" );
10141
10142 zone->SetDoNotAllowVias( token == T_not_allowed );
10143 break;
10144
10145 case T_copperpour:
10146 token = NextTok();
10147
10148 if( token != T_allowed && token != T_not_allowed )
10149 Expecting( "allowed or not_allowed" );
10150
10151 zone->SetDoNotAllowZoneFills( token == T_not_allowed );
10152 break;
10153
10154 case T_pads:
10155 token = NextTok();
10156
10157 if( token != T_allowed && token != T_not_allowed )
10158 Expecting( "allowed or not_allowed" );
10159
10160 zone->SetDoNotAllowPads( token == T_not_allowed );
10161 break;
10162
10163 case T_footprints:
10164 token = NextTok();
10165
10166 if( token != T_allowed && token != T_not_allowed )
10167 Expecting( "allowed or not_allowed" );
10168
10169 zone->SetDoNotAllowFootprints( token == T_not_allowed );
10170 break;
10171
10172 default:
10173 Expecting( "tracks, vias or copperpour" );
10174 }
10175
10176 NeedRIGHT();
10177 }
10178
10179 break;
10180
10181 case T_polygon:
10182 {
10183 SHAPE_LINE_CHAIN outline;
10184
10185 NeedLEFT();
10186 token = NextTok();
10187
10188 if( token != T_pts )
10189 Expecting( T_pts );
10190
10191 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10192 parseOutlinePoints( outline );
10193
10194 NeedRIGHT();
10195
10196 outline.SetClosed( true );
10197
10198 if( outline.PointCount() == 0 )
10199 break;
10200
10201 // Remark: The first polygon is the main outline.
10202 // Others are holes inside the main outline.
10203 zone->AddPolygon( outline );
10204 break;
10205 }
10206
10207 case T_filled_polygon:
10208 {
10209 // "(filled_polygon (pts"
10210 NeedLEFT();
10211 token = NextTok();
10212
10213 if( token == T_layer )
10214 {
10215 filledLayer = parseBoardItemLayer();
10216 NeedRIGHT();
10217 token = NextTok();
10218
10219 if( token != T_LEFT )
10220 Expecting( T_LEFT );
10221
10222 token = NextTok();
10223 }
10224 else
10225 {
10226 // for legacy, single-layer zones
10227 filledLayer = zone->GetFirstLayer();
10228 }
10229
10230 bool island = false;
10231
10232 if( token == T_island )
10233 {
10234 island = parseMaybeAbsentBool( true );
10235 NeedLEFT();
10236 token = NextTok();
10237 }
10238
10239 if( token != T_pts )
10240 Expecting( T_pts );
10241
10242 if( !pts.count( filledLayer ) )
10243 pts[filledLayer] = SHAPE_POLY_SET();
10244
10245 SHAPE_POLY_SET& poly = pts.at( filledLayer );
10246
10247 int idx = poly.NewOutline();
10248 SHAPE_LINE_CHAIN& chain = poly.Outline( idx );
10249
10250 if( island )
10251 zone->SetIsIsland( filledLayer, idx );
10252
10253 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10255
10256 NeedRIGHT();
10257
10258 addedFilledPolygons |= !poly.IsEmpty();
10259 }
10260
10261 break;
10262
10263 case T_fill_segments:
10264 {
10265 // Legacy segment fill
10266
10267 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10268 {
10269 if( token != T_LEFT )
10270 Expecting( T_LEFT );
10271
10272 token = NextTok();
10273
10274 if( token != T_pts )
10275 Expecting( T_pts );
10276
10277 // Legacy zones only had one layer
10278 filledLayer = zone->GetFirstLayer();
10279
10280 SEG fillSegment;
10281
10282 fillSegment.A = parseXY();
10283 fillSegment.B = parseXY();
10284
10285 legacySegs[filledLayer].push_back( fillSegment );
10286
10287 NeedRIGHT();
10288 }
10289
10290 break;
10291 }
10292
10293 case T_name:
10294 NextTok();
10295 zone->SetZoneName( FromUTF8() );
10296 NeedRIGHT();
10297 break;
10298
10299 case T_attr:
10300 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10301 {
10302 if( token == T_LEFT )
10303 token = NextTok();
10304
10305 switch( token )
10306 {
10307 case T_teardrop:
10308 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10309 {
10310 if( token == T_LEFT )
10311 token = NextTok();
10312
10313 switch( token )
10314 {
10315 case T_type:
10316 token = NextTok();
10317
10318 if( token == T_padvia )
10319 zone->SetTeardropAreaType( TEARDROP_TYPE::TD_VIAPAD );
10320 else if( token == T_track_end )
10321 zone->SetTeardropAreaType( TEARDROP_TYPE::TD_TRACKEND );
10322 else
10323 Expecting( "padvia or track_end" );
10324
10325 NeedRIGHT();
10326 break;
10327
10328 default:
10329 Expecting( "type" );
10330 }
10331 }
10332
10333 break;
10334
10335 default:
10336 Expecting( "teardrop" );
10337 }
10338 }
10339 break;
10340
10341 case T_locked:
10342 zone->SetLocked( parseBool() );
10343 NeedRIGHT();
10344 break;
10345
10346 case T_custom_property:
10347 parseCustomProperty( zone.get() );
10348 break;
10349
10350 default:
10351 Expecting( "net, layer/layers, tstamp, hatch, priority, connect_pads, min_thickness, "
10352 "fill, polygon, filled_polygon, fill_segments, attr, locked, uuid, or name" );
10353 }
10354 }
10355
10356 if( zone->GetNumCorners() > 2 )
10357 {
10358 if( !zone->IsOnCopperLayer() )
10359 {
10360 //zone->SetFillMode( ZONE_FILL_MODE::POLYGONS );
10361 zone->SetNetCode( NETINFO_LIST::UNCONNECTED );
10362 }
10363
10364 // Set hatch here, after outlines corners are read
10365 zone->SetBorderDisplayStyle( hatchStyle, hatchPitch, true );
10366 }
10367
10368 if( addedFilledPolygons )
10369 {
10370 if( isStrokedFill && !zone->GetIsRuleArea() )
10371 {
10373 {
10374 m_parseWarnings.push_back( _( "Legacy zone fill strategy is not supported anymore.\n"
10375 "Zone fills will be converted on best-effort basis." ) );
10376
10378 }
10379
10380 if( zone->GetMinThickness() > 0 )
10381 {
10382 for( auto& [layer, polyset] : pts )
10383 {
10384 polyset.InflateWithLinkedHoles( zone->GetMinThickness() / 2,
10386 ARC_HIGH_DEF / 2 );
10387 }
10388 }
10389 }
10390
10391 for( auto& [layer, polyset] : pts )
10392 zone->SetFilledPolysList( layer, polyset );
10393
10394 zone->CalculateFilledArea();
10395 }
10396 else if( legacySegs.size() > 0 )
10397 {
10398 // No polygons, just segment fill?
10399 // Note RFB: This code might be removed if turns out this never existed for sexpr file
10400 // format or otherwise we should add a test case to the qa folder
10401
10403 {
10404 m_parseWarnings.push_back( _( "The legacy segment zone fill mode is no longer supported.\n"
10405 "Zone fills will be converted on a best-effort basis." ) );
10406
10408 }
10409
10410
10411 for( const auto& [layer, segments] : legacySegs )
10412 {
10413 SHAPE_POLY_SET layerFill;
10414
10415 if( zone->HasFilledPolysForLayer( layer ) )
10416 layerFill = SHAPE_POLY_SET( *zone->GetFill( layer ) );
10417
10418 for( const auto& seg : segments )
10419 {
10420 SHAPE_POLY_SET segPolygon;
10421
10422 TransformOvalToPolygon( segPolygon, seg.A, seg.B, zone->GetMinThickness(),
10424
10425 layerFill.BooleanAdd( segPolygon );
10426 }
10427
10428
10429 zone->SetFilledPolysList( layer, layerFill );
10430 zone->CalculateFilledArea();
10431 }
10432 }
10433
10434
10435 // Ensure keepout and non copper zones do not have a net
10436 // (which have no sense for these zones)
10437 // the netcode 0 is used for these zones
10438 bool zone_has_net = zone->IsOnCopperLayer() && !zone->GetIsRuleArea();
10439
10440 if( !zone_has_net )
10441 zone->SetNetCode( NETINFO_LIST::UNCONNECTED );
10442
10443 // In legacy files, ensure the zone net name is valid, and matches the net code
10444 if( m_board && !legacyNetnameFromFile.IsEmpty() && zone->GetNetname() != legacyNetnameFromFile )
10445 {
10446 // Can happens which old boards, with nonexistent nets ...
10447 // or after being edited by hand
10448 // We try to fix the mismatch.
10449 NETINFO_ITEM* net = m_board->FindNet( legacyNetnameFromFile );
10450
10451 if( net ) // An existing net has the same net name. use it for the zone
10452 {
10453 zone->SetNetCode( net->GetNetCode() );
10454 }
10455 else // Not existing net: add a new net to keep track of the zone netname
10456 {
10457 int newnetcode = m_board->GetNetCount();
10458 net = new NETINFO_ITEM( m_board, legacyNetnameFromFile, newnetcode );
10459 m_board->Add( net, ADD_MODE::INSERT, true );
10460
10461 // Store the new code mapping
10462 pushValueIntoMap( newnetcode, net->GetNetCode() );
10463
10464 // and update the zone netcode
10465 zone->SetNetCode( net->GetNetCode() );
10466 }
10467 }
10468
10469 if( m_board && zone->IsTeardropArea() && m_requiredVersion < 20230517 )
10470 m_board->SetLegacyTeardrops( true );
10471
10472 // Clear flags used in zone edition:
10473 zone->SetNeedRefill( false );
10474
10475 // By UUID, since the caller may still discard the zone
10476 if( zone->GetLinkSet() != niluuid || zone->GetRepeatOptions().m_anchor != niluuid )
10477 m_linkedZones.insert( zone->m_Uuid );
10478
10479 return zone.release();
10480}
10481
10482
10484{
10485 wxCHECK_MSG( CurTok() == T_point, nullptr,
10486 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_POINT." ) );
10487
10488 std::unique_ptr<PCB_POINT> point = std::make_unique<PCB_POINT>( nullptr );
10489
10490 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
10491 {
10492 if( token == T_LEFT )
10493 token = NextTok();
10494
10495 switch( token )
10496 {
10497 case T_at:
10498 {
10499 VECTOR2I pt;
10500 pt.x = parseBoardUnits( "point x position" );
10501 pt.y = parseBoardUnits( "point y position" );
10502 point->SetPosition( pt );
10503 NeedRIGHT();
10504 break;
10505 }
10506 case T_size:
10507 {
10508 point->SetSize( parseBoardUnits( "point size" ) );
10509 NeedRIGHT();
10510 break;
10511 }
10512 case T_layer:
10513 {
10514 point->SetLayer( parseBoardItemLayer() );
10515 NeedRIGHT();
10516 break;
10517 }
10518 case T_uuid:
10519 {
10520 NextTok();
10521 point->SetUuidDirect( CurStrToKIID() );
10522 NeedRIGHT();
10523 break;
10524 }
10525 case T_custom_property:
10526 parseCustomProperty( point.get() );
10527 break;
10528 default: Expecting( "at, size, layer or uuid" );
10529 }
10530 }
10531
10532 return point.release();
10533}
10534
10535
10537{
10538 wxCHECK_MSG( CurTok() == T_target, nullptr,
10539 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_TARGET." ) );
10540
10541 VECTOR2I pt;
10542 T token;
10543
10544 std::unique_ptr<PCB_TARGET> target = std::make_unique<PCB_TARGET>( nullptr );
10545
10546 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10547 {
10548 if( token == T_LEFT )
10549 token = NextTok();
10550
10551 switch( token )
10552 {
10553 case T_x:
10554 target->SetShape( 1 );
10555 break;
10556
10557 case T_plus:
10558 target->SetShape( 0 );
10559 break;
10560
10561 case T_at:
10562 pt.x = parseBoardUnits( "target x position" );
10563 pt.y = parseBoardUnits( "target y position" );
10564 target->SetPosition( pt );
10565 NeedRIGHT();
10566 break;
10567
10568 case T_size:
10569 target->SetSize( parseBoardUnits( "target size" ) );
10570 NeedRIGHT();
10571 break;
10572
10573 case T_width:
10574 target->SetWidth( parseBoardUnits( "target thickness" ) );
10575 NeedRIGHT();
10576 break;
10577
10578 case T_layer:
10579 target->SetLayer( parseBoardItemLayer() );
10580 NeedRIGHT();
10581 break;
10582
10583 case T_tstamp:
10584 case T_uuid:
10585 NextTok();
10586 target->SetUuidDirect( CurStrToKIID() );
10587 NeedRIGHT();
10588 break;
10589
10590 case T_custom_property:
10591 parseCustomProperty( target.get() );
10592 break;
10593
10594 default:
10595 Expecting( "x, plus, at, size, width, layer, uuid, or tstamp" );
10596 }
10597 }
10598
10599 return target.release();
10600}
10601
10602
10604{
10605 wxCHECK_MSG( CurTok() == T_grid_item, nullptr,
10606 wxT( "Cannot parse " ) + GetTokenString( CurTok() ) + wxT( " as PCB_GRID_ITEM." ) );
10607
10608 VECTOR2I pt;
10609 T token;
10610
10611 std::unique_ptr<PCB_GRID_ITEM> griditem = std::make_unique<PCB_GRID_ITEM>( nullptr );
10612
10613 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10614 {
10615 if( token == T_LEFT )
10616 token = NextTok();
10617
10618 switch( token )
10619 {
10620 case T_xy:
10621 griditem->SetGridItemType( PCB_GRID_TYPE::CARTESIAN );
10622 break;
10623
10624 case T_polar:
10625 griditem->SetGridItemType( PCB_GRID_TYPE::POLAR );
10626 break;
10627
10628 case T_at:
10629 pt.x = parseBoardUnits( "grid_item x position" );
10630 pt.y = parseBoardUnits( "grid_item y position" );
10631 griditem->SetPosition( pt );
10632 NeedRIGHT();
10633 break;
10634
10635 case T_spacing:
10636 // Writer emits the grid type before extent/spacing, so the type is set here.
10637 // Polar y is an angle; cartesian y is a length.
10638 if( griditem->GetGridItemType() == PCB_GRID_TYPE::POLAR )
10639 {
10640 griditem->SetRadiusSpacing( parseBoardUnits( "grid_item radius spacing" ) );
10641 griditem->SetPhiSpacingDegrees( parseDouble( "grid_item phi spacing" ) );
10642 }
10643 else
10644 {
10645 pt.x = parseBoardUnits( "grid_item x spacing" );
10646 pt.y = parseBoardUnits( "grid_item y spacing" );
10647 griditem->SetSpacing( pt );
10648 }
10649 NeedRIGHT();
10650 break;
10651
10652 case T_extent:
10653 if( griditem->GetGridItemType() == PCB_GRID_TYPE::POLAR )
10654 {
10655 griditem->SetRadiusExtent( parseBoardUnits( "grid_item radius extent" ) );
10656 griditem->SetPhiExtentDegrees( parseDouble( "grid_item phi extent" ) );
10657 }
10658 else
10659 {
10660 pt.x = parseBoardUnits( "grid_item x extent" );
10661 pt.y = parseBoardUnits( "grid_item y extent" );
10662 griditem->SetExtent( pt );
10663 }
10664 NeedRIGHT();
10665 break;
10666
10667 case T_angle:
10668 griditem->SetOrientationDegrees( parseDouble( "grid_item orientation" ) );
10669 NeedRIGHT();
10670 break;
10671
10672 case T_priority:
10673 griditem->SetAssignedPriority( static_cast<unsigned>( parseInt( "grid_item priority" ) ) );
10674 NeedRIGHT();
10675 break;
10676
10677 case T_tick_interval:
10678 griditem->SetTickInterval( static_cast<unsigned>( parseInt( "grid_item tick_interval" ) ) );
10679 NeedRIGHT();
10680 break;
10681
10682 case T_affects:
10683 {
10684 // (affects (cursor yes|no) (routing yes|no) (placement yes|no))
10685 PCB_GRID_AFFECTS aff;
10686 aff.SetAll( false );
10687
10688 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
10689 {
10690 if( token != T_LEFT )
10691 Expecting( "cursor, routing or placement" );
10692
10693 token = NextTok();
10694 bool* target = nullptr;
10695
10696 switch( token )
10697 {
10698 case T_cursor: target = &aff.cursor; break;
10699 case T_routing: target = &aff.routing; break;
10700 case T_placement: target = &aff.placement; break;
10701 default: Expecting( "cursor, routing or placement" );
10702 }
10703
10704 *target = parseBool();
10705 NeedRIGHT();
10706 }
10707
10708 griditem->Affects() = aff;
10709 break;
10710 }
10711
10712 case T_locked:
10713 griditem->SetLocked( parseBool() );
10714 NeedRIGHT();
10715 break;
10716
10717 case T_uuid:
10718 NextTok();
10719 const_cast<KIID&>( griditem->m_Uuid ) = CurStrToKIID();
10720 NeedRIGHT();
10721 break;
10722
10723 case T_custom_property:
10724 parseCustomProperty( griditem.get() );
10725 break;
10726
10727 default:
10728 Expecting( "xy, polar, at, spacing, extent, angle, priority, tick_interval, "
10729 "affects, locked or uuid" );
10730 }
10731 }
10732
10733 return griditem.release();
10734}
10735
10736
10738{
10739 KIID aId;
10740 std::string idStr( CurStr() );
10741
10742 // Older files did not quote UUIDs
10743 if( *idStr.begin() == '"' && *idStr.rbegin() == '"' )
10744 idStr = idStr.substr( 1, idStr.length() - 1 );
10745
10746 if( m_appendToExisting )
10747 {
10748 aId = KIID();
10749 m_resetKIIDMap.insert( std::make_pair( idStr, aId ) );
10750 }
10751 else
10752 {
10753 aId = KIID( idStr );
10754 }
10755
10756 return aId;
10757}
int index
const char * name
@ ERROR_OUTSIDE
constexpr int ARC_HIGH_DEF
Definition base_units.h:144
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
@ LT_UNDEFINED
Definition board.h:244
@ LAYER_CLASS_OTHERS
@ LAYER_CLASS_FAB
@ LAYER_CLASS_COURTYARD
@ LAYER_CLASS_SILK
@ LAYER_CLASS_COPPER
@ LAYER_CLASS_EDGES
#define DEFAULT_LINE_WIDTH
@ ZLO_FORCE_NO_ZONE_CONNECTION
Definition board_item.h:78
@ ZLO_FORCE_FLASHED
Definition board_item.h:77
@ BS_EDGE_CONNECTOR_BEVELLED
@ BS_EDGE_CONNECTOR_NONE
@ BS_EDGE_CONNECTOR_IN_USE
BOARD_STACKUP_ITEM_TYPE
@ BS_ITEM_TYPE_UNDEFINED
@ BS_ITEM_TYPE_COPPER
@ BS_ITEM_TYPE_SILKSCREEN
@ BS_ITEM_TYPE_DIELECTRIC
@ BS_ITEM_TYPE_SOLDERPASTE
@ BS_ITEM_TYPE_SOLDERMASK
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
BASE_SET & reset(size_t pos)
Definition base_set.h:153
BASE_SET & set(size_t pos)
Definition base_set.h:126
This class handle bitmap images in KiCad.
Definition bitmap_base.h:47
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
virtual bool SetNetCode(int aNetCode, bool aNoAssert)
Set net using a net code.
virtual void SetNet(NETINFO_ITEM *aNetInfo)
Set a NET_INFO object for the item.
Container for design settings for a BOARD object.
DIM_PRECISION m_DimensionPrecision
Number of digits after the decimal.
std::shared_ptr< NET_SETTINGS > m_NetSettings
std::map< PCB_LAYER_ID, ZONE_LAYER_PROPERTIES > m_ZoneLayerProperties
void SetGridOrigin(const VECTOR2I &aOrigin)
bool m_TextUpright[LAYER_CLASS_COUNT]
std::vector< DIFF_PAIR_DIMENSION > m_DiffPairDimensionsList
void SetAuxOrigin(const VECTOR2I &aOrigin)
BOARD_STACKUP & GetStackupDescriptor()
int m_TextThickness[LAYER_CLASS_COUNT]
std::vector< int > m_TrackWidthList
int m_LineThickness[LAYER_CLASS_COUNT]
ZONE_SETTINGS & GetDefaultZoneSettings()
VECTOR2I m_TextSize[LAYER_CLASS_COUNT]
bool m_TextItalic[LAYER_CLASS_COUNT]
std::vector< VIA_DIMENSION > m_ViasDimensionsList
Abstract interface for BOARD_ITEMs capable of storing other items inside.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
void SetUuidDirect(const KIID &aUuid)
Raw UUID assignment.
void SetLocked(bool aLocked) override
Definition board_item.h:441
virtual void SetIsKnockout(bool aKnockout)
Definition board_item.h:438
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition board_item.h:397
FOOTPRINT * GetParentFootprint() const
virtual void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const
Invoke a function on all children.
Definition board_item.h:279
BOARD_ITEM_CONTAINER * GetParent() const
Definition board_item.h:281
Manage one layer needed to make a physical board.
void AddDielectricPrms(int aDielectricPrmsIdx)
Add (insert) a DIELECTRIC_PRMS item to m_DielectricPrmsList all values are set to default.
void SetDielectricLayerId(int aLayerId)
void SetThickness(int aThickness, int aDielectricSubLayer=0)
void SetDielectricModel(DIELECTRIC_MODEL aModel, int aDielectricSubLayer=0)
void SetThicknessLocked(bool aLocked, int aDielectricSubLayer=0)
void SetSpecFreq(double aSpecFreq, int aDielectricSubLayer=0)
void SetMaterial(const wxString &aName, int aDielectricSubLayer=0)
void SetLossTangent(double aTg, int aDielectricSubLayer=0)
BOARD_STACKUP_ITEM_TYPE GetType() const
void SetBrdLayerId(PCB_LAYER_ID aBrdLayerId)
void SetTypeName(const wxString &aName)
void SetColor(const wxString &aColorName, int aDielectricSubLayer=0)
void SetEpsilonR(double aEpsilon, int aDielectricSubLayer=0)
Manage layers needed to make a physical board.
void RemoveAll()
Delete all items in list and clear the list.
int GetCount() const
bool m_HasDielectricConstrains
True if some layers have impedance controlled tracks or have specific constrains for micro-wave appli...
void Add(BOARD_STACKUP_ITEM *aItem)
Add a new item in stackup layer.
void BuildDefaultStackupList(const BOARD_DESIGN_SETTINGS *aSettings, int aActiveCopperLayersCount=0)
Create a default stackup, according to the current BOARD_DESIGN_SETTINGS settings.
bool m_EdgePlating
True if the edge board is plated.
BS_EDGE_CONNECTOR_CONSTRAINTS m_EdgeConnectorConstraints
If the board has edge connector cards, some constrains can be specified in job file: BS_EDGE_CONNECTO...
wxString m_FinishType
The name of external copper finish.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
BOARD_ITEM * ResolveItem(const KIID &aID, bool aAllowNullptrReturn=false) const
Definition board.cpp:2176
Grouping rules and symbol assignments, shared by reference so a chart and its map can never disagree ...
void SetSymbolWidth(int aWidth)
void SetName(const wxString &aName)
void SetFreezeAssignments(bool aFreeze)
void SetGroupedBy(DRILL_GROUP_KEY aKey, bool aOn)
void SetMarkPolicy(DRILL_MARK_POLICY aPolicy)
void SetAssignment(const std::string &aKey, const DRILL_SYMBOL_ASSIGNMENT &aAssignment)
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void SetCustomProperty(const wxString &aKey, const wxString &aValue)
Definition eda_item.h:255
virtual EMBEDDED_FILES * GetEmbeddedFiles()
Definition eda_item.h:551
SHAPE_POLY_SET & GetPolyShape()
SHAPE_T GetShape() const
Definition eda_shape.h:178
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
virtual void SetTextSize(VECTOR2I aNewSize, bool aEnforceMinTextSize=true)
Definition eda_text.cpp:513
void SetUnresolvedFontName(const wxString &aFontName)
Definition eda_text.h:288
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
virtual void SetTextPos(const VECTOR2I &aPoint)
Definition eda_text.cpp:557
void SetMirrored(bool isMirrored)
Definition eda_text.cpp:355
void SetVertJustify(GR_TEXT_V_ALIGN_T aType)
Definition eda_text.cpp:379
void SetBoldFlag(bool aBold)
Set only the bold flag, without changing the font.
Definition eda_text.cpp:325
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
void MigrateLegacyBoldStrokeWidth()
Migrate a pre-v11 bold stroke text so its stored thickness holds the base (non-bold) width.
Definition eda_text.cpp:333
bool GetAutoThickness() const
Definition eda_text.h:170
void SetLineSpacing(double aLineSpacing)
Definition eda_text.cpp:505
virtual void SetTextThickness(int aWidth)
The TextThickness is that set by the user.
Definition eda_text.cpp:251
void SetItalicFlag(bool aItalic)
Set only the italic flag, without changing the font.
Definition eda_text.cpp:303
void SetKeepUpright(bool aKeepUpright)
Definition eda_text.cpp:387
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
void SetHorizJustify(GR_TEXT_H_ALIGN_T aType)
Definition eda_text.cpp:371
void ParseEmbedded(EMBEDDED_FILES *aFiles)
const std::vector< wxString > * UpdateFontFiles()
Helper function to get a list of fonts for fontconfig to add to the library.
KIGFX::COLOR4D m_color
Definition pcb_3d_body.h:46
VECTOR3D m_offset
Definition pcb_3d_body.h:52
PCB_LAYER_ID m_layer
Definition pcb_3d_body.h:45
VECTOR3D m_rotation
Definition pcb_3d_body.h:51
EXTRUSION_MATERIAL m_material
Definition pcb_3d_body.h:47
Variant information for a footprint.
Definition footprint.h:178
void SetExcludedFromPosFiles(bool aExclude)
Definition footprint.h:202
void SetExcludedFromSim(bool aExclude)
Definition footprint.h:199
void SetDNP(bool aDNP)
Definition footprint.h:193
void SetFieldValue(const wxString &aFieldName, const wxString &aValue)
Set a field value override for this variant.
Definition footprint.h:224
void SetExcludedFromBOM(bool aExclude)
Definition footprint.h:196
void SetStackupLayers(LSET aLayers)
If the footprint has a non-default stackup, set the layers that should be used for the stackup.
EDA_ANGLE GetOrientation() const
Definition footprint.h:382
void SetStackupMode(FOOTPRINT_STACKUP aMode)
Set the stackup mode for this footprint.
void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const override
Invoke a function on all children.
void GetFields(std::vector< PCB_FIELD * > &aVector, bool aVisibleOnly) const
Populate a std::vector with PCB_TEXTs.
FOOTPRINT_VARIANT * AddVariant(const wxString &aVariantName)
Add a new variant with the given name.
VECTOR2I GetPosition() const override
Definition footprint.h:379
VECTOR3D m_Offset
3D model offset (mm)
Definition footprint.h:134
double m_Opacity
Definition footprint.h:135
VECTOR3D m_Rotation
3D model rotation (degrees)
Definition footprint.h:133
VECTOR3D m_Scale
3D model scaling factor (dimensionless)
Definition footprint.h:132
wxString m_Filename
The 3D shape filename in 3D library.
Definition footprint.h:136
bool m_Show
Include model in rendering.
Definition footprint.h:137
Helper class for creating a footprint library cache.
static GAL_SET DefaultVisible()
Definition lset.cpp:782
The columns one generator (the drill chart, a stackup table, ...) can produce, and the units and prec...
std::vector< GENERATED_TABLE_COLUMN > Defaults() const
const GENERATED_TABLE_COLUMN_DEF * FindToken(const wxString &aToken) const
GENERATED_TABLE_UNITS DefaultUnits() const
bool Validate(std::vector< GENERATED_TABLE_COLUMN > &aColumns) const
Drop a column whose id the schema does not know and a column that repeats an id already kept,...
A factory which returns an instance of a PCB_GENERATOR.
PCB_GENERATOR * CreateFromType(const wxString &aTypeStr)
static GENERATORS_MGR & Instance()
virtual const wxString What() const
A composite of Problem() and Where()
Represents an (ordered) list of JUMPER_GROUP objects.
void Add(JUMPER_GROUP aGroup)
Add a JUMPER_GROUP to the set.
static std::optional< JUMPER_GROUP > Make(std::set< wxString > aNames)
Factory method to create a JUMPER_GROUP from a set of names.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
double r
Red component.
Definition color4d.h:391
double g
Green component.
Definition color4d.h:392
COLOR4D WithAlpha(double aAlpha) const
Return a color with the same color, but the given alpha.
Definition color4d.h:309
double a
Alpha component.
Definition color4d.h:394
wxColour ToColour() const
Definition color4d.cpp:221
static const COLOR4D UNSPECIFIED
For legacy support; used as a value to indicate color hasn't been set yet.
Definition color4d.h:400
double b
Blue component.
Definition color4d.h:393
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:65
Decorative shape (arrowhead, circle, square) at the start or end of a graphic line,...
Definition line_ending.h:62
void SetStroke(const STROKE_PARAMS &aStroke)
void SetLength(int aLength)
Definition line_ending.h:85
void SetStyle(LINE_ENDING_STYLE aStyle)
Definition line_ending.h:82
void SetWidth(int aWidth)
Definition line_ending.h:88
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:604
static int NameToLayer(wxString &aName)
Return the layer number from a layer name.
Definition lset.cpp:113
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static const LSET & AllTechMask()
Return a mask holding all technical layers (no CU layer) on both side.
Definition lset.cpp:672
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
static const LSET & AllLayersMask()
Definition lset.cpp:637
static const LSET & InternalCuMask()
Return a complete set of internal copper layers which is all Cu layers except F_Cu and B_Cu.
Definition lset.cpp:573
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
Definition lset.h:63
Handle the data for a net.
Definition netinfo.h:50
int GetNetCode() const
Definition netinfo.h:104
static const int UNCONNECTED
Constant that holds the "unconnected net" number (typically 0) all items "connected" to this net are ...
Definition netinfo.h:281
static const int ORPHANED
Constant that forces initialization of a netinfo item to the NETINFO_ITEM ORPHANED (typically -1) whe...
Definition netinfo.h:285
std::shared_ptr< NETCLASS > GetDefaultNetclass() const
Gets the default netclass for the project.
A PADSTACK defines the characteristics of a single or multi-layer pad, in the IPC sense of the word.
Definition padstack.h:161
std::optional< int > & Clearance(PCB_LAYER_ID aLayer=F_Cu)
MASK_LAYER_PROPS & FrontOuterLayers()
Definition padstack.h:410
void SetThermalSpokeAngle(EDA_ANGLE aAngle, PCB_LAYER_ID aLayer=F_Cu)
void SetMode(MODE aMode)
std::optional< int > & ThermalSpokeWidth(PCB_LAYER_ID aLayer=F_Cu)
std::optional< int > & ThermalGap(PCB_LAYER_ID aLayer=F_Cu)
@ CUSTOM
Shapes can be defined on arbitrary layers.
Definition padstack.h:177
@ FRONT_INNER_BACK
Up to three shapes can be defined (F_Cu, inner copper layers, B_Cu)
Definition padstack.h:176
MODE Mode() const
Definition padstack.h:351
MASK_LAYER_PROPS & BackOuterLayers()
Definition padstack.h:413
void SetSize(const VECTOR2I &aSize, PCB_LAYER_ID aLayer)
Definition padstack.cpp:873
static constexpr PCB_LAYER_ID INNER_LAYERS
! The layer identifier to use for "inner layers" on top/inner/bottom padstacks
Definition padstack.h:187
std::optional< ZONE_CONNECTION > & ZoneConnection(PCB_LAYER_ID aLayer=F_Cu)
Definition pad.h:61
void SetAnchorPadShape(PCB_LAYER_ID aLayer, PAD_SHAPE aShape)
Set the shape of the anchor pad for custom shaped pads.
Definition pad.h:249
void SetShape(PCB_LAYER_ID aLayer, PAD_SHAPE aShape)
Set the new shape of this pad.
Definition pad.h:196
void SetDelta(PCB_LAYER_ID aLayer, const VECTOR2I &aSize)
Definition pad.h:301
void DeletePrimitivesList(PCB_LAYER_ID aLayer=UNDEFINED_LAYER)
Clear the basic shapes list.
Definition pad.cpp:3456
void AddPrimitive(PCB_LAYER_ID aLayer, PCB_SHAPE *aPrimitive)
Add item to the custom shape primitives list.
Definition pad.cpp:3431
void SetCustomShapeInZoneOpt(CUSTOM_SHAPE_ZONE_MODE aOption)
Set the option for the custom pad shape to use as clearance area in copper zones.
Definition pad.h:237
void SetChamferRectRatio(PCB_LAYER_ID aLayer, double aChamferScale)
Has meaning only for chamfered rectangular pads.
Definition pad.cpp:1103
const PADSTACK & Padstack() const
Definition pad.h:331
void SetLibOffset(PCB_LAYER_ID aLayer, const VECTOR2I &aOffset)
Definition pad.cpp:290
void SetLibSize(PCB_LAYER_ID aLayer, const VECTOR2I &aSize)
Definition pad.cpp:276
void SetChamferPositions(PCB_LAYER_ID aLayer, int aPositions)
Has meaning only for chamfered rectangular pads.
Definition pad.h:873
void SetRoundRectRadiusRatio(PCB_LAYER_ID aLayer, double aRadiusScale)
Has meaning only for rounded rectangle pads.
Definition pad.cpp:1065
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
void SetPortrait(bool aIsPortrait)
Rotate the paper page 90 degrees.
bool SetType(PAGE_SIZE_TYPE aPageSize, bool aIsPortrait=false)
Set the name of the page type and also the sizes and margins commonly associated with that type name.
void SetWidthMM(double aWidthInMM)
Definition page_info.h:135
void SetHeightMM(double aHeightInMM)
Definition page_info.h:140
const PAGE_SIZE_TYPE & GetType() const
Definition page_info.h:97
A 3D body attached to a footprint (or, later, placed on a board).
Definition pcb_3d_body.h:93
EXTRUDED_3D_BODY * MutableExtruded()
Abstract dimension API.
For better understanding of the points that make a dimension:
void SetExtensionHeight(int aHeight)
void UpdateHeight(const VECTOR2I &aCrossbarStart, const VECTOR2I &aCrossbarEnd)
Update the stored height basing on points coordinates.
void SetHeight(int aHeight)
Set the distance from the feature points to the crossbar line.
A leader is a dimension-like object pointing to a specific point.
void SetTextBorder(DIM_TEXT_BORDER aBorder)
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.
void SetLeaderLength(int aLength)
A drill chart placed on the board, kept in step with the holes.
void SetSymbolColumn(int aCol)
const std::map< int, int > & RowShapes() const
Curated shape index for each generated row, by table row.
DRILL_CHART_FILTER & Filter()
void RestoreShowTotals(bool aShow)
Set it without that, for a loader whose cells were laid out with this setting.
Turns on drill symbols at the holes, for one layer.
A table whose cell text is derived from the board and rebuilt whenever it goes stale.
virtual void SetProperties(const STRING_ANY_MAP &aProps)
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
virtual bool LayerFollowsMembers() const
virtual void SetTemplateItem(const wxString &aName, std::unique_ptr< BOARD_ITEM > aItem)
Insert a template item (from board file loading)
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:51
void parseCONSTRAINT(BOARD_ITEM *aParent)
wxString m_generatorVersion
Set to the generator version this board requires.
PCB_TABLECELL * parsePCB_TABLECELL(BOARD_ITEM *aParent)
void parseGENERATOR_templates(GENERATOR_INFO &aGenInfo)
std::unordered_map< std::string, PCB_LAYER_ID > LAYER_ID_MAP
std::vector< int > m_netCodes
net codes mapping for boards being loaded
void parseOutlinePoints(SHAPE_LINE_CHAIN &aPoly)
Parses possible outline points and stores them into aPoly.
std::set< wxString > m_undefinedLayers
set of layers not defined in layers section
LAYER_MAPPING_HANDLER m_layerMappingHandler
optional remap of appended layers onto dest
std::vector< CONSTRAINT_INFO > m_constraintInfos
void parseZoneLayerProperty(std::map< PCB_LAYER_ID, ZONE_LAYER_PROPERTIES > &aProperties)
PROGRESS_REPORTER * m_progressReporter
optional; may be nullptr
int getNetCode(int aNetCode)
Convert net code using the mapping table if available, otherwise returns unchanged net code if < 0 or...
void parseFootprintStackup(FOOTPRINT &aFootprint)
PCB_GENERATED_TABLE * parseGeneratedTable(std::unique_ptr< PCB_GENERATED_TABLE > aTable)
The body every generated table shares.
void createOldLayerMapping(std::unordered_map< std::string, std::string > &aMap)
Create a mapping from the (short-lived) bug where layer names were translated.
bool parseTableBodyToken(PCB_TABLE *aTable, PCB_KEYS_T::T aToken, bool aAllowIdentity)
aAllowIdentity is false inside a drill chart's table_data, where the enclosing form owns uuid,...
void parseZoneDefaults(std::map< PCB_LAYER_ID, ZONE_LAYER_PROPERTIES > &aProperties)
std::unordered_map< std::string, LSET > LSET_MAP
void parseEDA_TEXT(EDA_TEXT *aText)
Parse the common settings for any object derived from EDA_TEXT.
bool m_tooRecent
true if version parses as later than supported
void remapAppendedLayers(const std::vector< LAYER > &aSourceLayers, const LSET &aDestInitialEnabled, int aDestInitialCopperCount)
Remap the appended layers onto the destination using m_layerMappingHandler, on mismatch.
PCB_REFERENCE_IMAGE * parsePCB_REFERENCE_IMAGE(BOARD_ITEM *aParent)
LAYER_ID_MAP m_layerIndices
map layer name to it's index
void parsePostMachining(PADSTACK::POST_MACHINING_PROPS &aProps)
void parseTableBody(PCB_TABLE *aTable, bool aAllowIdentity)
FP_3DMODEL * parse3DModel(bool aFileNameAlreadyParsed=false)
void parseTextBoxContent(PCB_TEXTBOX *aTextBox)
FOOTPRINT * parseFOOTPRINT(wxArrayString *aInitialComments=nullptr)
void parseLineEnding(LINE_ENDING &aEnding)
Parse a line ending definition from the token stream.
void pushValueIntoMap(int aIndex, int aValue)
Add aValue value in netcode mapping (m_netCodes) at aIndex.
void parseRenderCache(EDA_TEXT *aText)
Parse the render cache for any object derived from EDA_TEXT.
bool m_preserveDestinationStackup
append keeps destination stackup
std::set< KIID > m_linkedZones
Zones read with a link set or anchor.
void init()
Clear and re-establish m_layerMap with the default layer names.
std::pair< std::optional< bool >, std::optional< bool > > parseFrontBackOptBool(bool aAllowLegacyFormat=false)
void skipCurrent()
Skip the current token level, i.e search for the RIGHT parenthesis which closes the current descripti...
void parseMargins(int &aLeft, int &aTop, int &aRight, int &aBottom)
PCB_LAYER_ID parseBoardItemLayer()
Parse the layer definition of a BOARD_ITEM object.
LSET parseLayersForCuItemWithSoldermask()
Parse the layers definition of a BOARD_ITEM object that has a single copper layer and optional solder...
void parseGENERATOR(BOARD_ITEM *aParent)
PCB_LAYER_ID lookUpLayer(const LAYER_ID_MAP &aMap, bool aAllowUndefined=false)
Parse the current token for the layer definition of a BOARD_ITEM object.
void parsePAD_option(PAD *aPad, PCB_LAYER_ID aLayer)
LSET parseBoardItemLayersAsMask()
Parse the layers definition of a BOARD_ITEM object.
void finishItem(BOARD_ITEM *aItem)
Resolve the fonts, groups and constraints of a fully parsed board or footprint.
void resolveGroups(BOARD_ITEM *aParent)
Called after parsing a footprint definition or board to build the group membership lists.
void parseDefaultTextDims(BOARD_DESIGN_SETTINGS &aSettings, int aLayer)
std::vector< GROUP_INFO > m_groupInfos
ZONE * parseZONE(BOARD_ITEM_CONTAINER *aParent)
PCB_TABLE * parsePCB_TABLE(BOARD_ITEM *aParent)
std::vector< GENERATOR_INFO > m_generatorInfos
PCB_TEXTBOX * parsePCB_TEXTBOX(BOARD_ITEM *aParent)
std::chrono::time_point< CLOCK > TIME_PT
The type of the time stamps.
PCB_TEXT * parsePCB_TEXT(BOARD_ITEM *aParent, PCB_TEXT *aBaseText=nullptr)
unsigned m_lineCount
for progress reporting
VECTOR2I parseXY()
Parse a coordinate pair (xy X Y) in board units (mm).
void parseTEARDROP_PARAMETERS(TEARDROP_PARAMETERS *tdParams)
int m_requiredVersion
set to the KiCad format version this board requires
PAD * parsePAD(FOOTPRINT *aParent=nullptr)
void resolveConstraints(BOARD_ITEM *aParent)
std::function< bool(wxString aTitle, int aIcon, wxString aMsg, wxString aAction)> m_queryUserCallback
void parseNet(BOARD_CONNECTED_ITEM *aItem)
FOOTPRINT * parseFOOTPRINT_unchecked(wxArrayString *aInitialComments=nullptr)
PCB_DRILL_MAP * parsePCB_DRILL_MAP(BOARD_ITEM *aParent)
TIME_PT m_lastProgressTime
for progress reporting
void parseGROUP_members(GROUP_INFO &aGroupInfo)
bool IsValidBoardHeader()
Partially parse the input and check if it matches expected header.
void parseFootprintVariant(FOOTPRINT *aFootprint)
void ParseFootprintLib(boost::ptr_map< wxString, FP_CACHE_ENTRY, std::less< wxString >, boost::heap_clone_allocator, std::allocator< std::pair< const wxString, void * > > > &aFootprints)
Parse a footprint library file.
std::pair< wxString, wxString > parseBoardProperty()
LSET_MAP m_layerMasks
map layer names to their masks
bool parseMaybeAbsentBool(bool aDefaultValue)
Parses a boolean flag inside a list that existed before boolean normalization.
int parseBoardUnits()
Parse the current token as an ASCII numeric string with possible leading whitespace into a double pre...
bool parsePCB_TEXT_effects(PCB_TEXT *aText, PCB_TEXT *aBaseText=nullptr)
KIID_MAP m_resetKIIDMap
if resetting UUIDs, record new ones to update groups with.
void bakeTextBoxLib(PCB_TEXTBOX *aTextBox)
Lift disk-parsed values into PCB_TEXTBOX lib storage for new format files.
PCB_DIMENSION_BASE * parseDIMENSION(BOARD_ITEM *aParent)
LSET lookUpLayerSet(const LSET_MAP &aMap)
std::vector< wxString > m_parseWarnings
Non-fatal warnings collected during parsing.
bool m_appendToExisting
reading into an existing board; reset UUIDs
bool parseGeneratedTableExtra(PCB_GENERATED_TABLE *aTable, PCB_KEYS_T::T aToken)
One token only aTable's kind carries.
void parsePAD_primitives(PAD *aPad, PCB_LAYER_ID aLayer)
PCB_SHAPE * parsePCB_SHAPE(BOARD_ITEM *aParent)
void parseDefaults(BOARD_DESIGN_SETTINGS &aSettings)
wxString GetRequiredVersion()
Return a string representing the version of KiCad required to open this file.
PCB_BARCODE * parsePCB_BARCODE(BOARD_ITEM *aParent)
The parser for PCB_PLOT_PARAMS.
Parameters and options when plotting/printing a board.
std::optional< bool > GetLegacyPlotViaOnMaskLayer() const
void Parse(PCB_PLOT_PARAMS_PARSER *aParser)
A PCB_POINT is a 0-dimensional point that is used to mark a position on a PCB, or more usually a foot...
Definition pcb_point.h:39
void SetPosition(const VECTOR2I &aPos) override
Definition pcb_point.cpp:76
VECTOR2I GetPosition() const override
Definition pcb_point.h:60
Object to handle a bitmap image that can be inserted in a PCB.
void OverrideLibPoly(const SHAPE_POLY_SET &aPoly)
Definition pcb_shape.h:290
void SetEnd(const VECTOR2I &aEnd) override
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
void OverrideLibCoords(const VECTOR2I &aStart, const VECTOR2I &aEnd, const VECTOR2I &aArcMid=VECTOR2I(0, 0))
Definition pcb_shape.h:273
void SetIsProxyItem(bool aIsProxy=true) override
void SetStart(const VECTOR2I &aStart) override
void SetStroke(const STROKE_PARAMS &aStroke) override
void SetLibTextAngle(const EDA_ANGLE &aAngle)
EDA_ANGLE GetTextAngle() const override
void SetBorderEnabled(bool enabled)
Disables the border, this is done by changing the stroke internally.
void OnFootprintTransformed() override
Hook for items inside a footprint to refresh after the FP transform changes (translate,...
void SetShape(SHAPE_T aShape) override
void SetMarginTop(int aTop)
void SetMarginLeft(int aLeft)
void SetMarginBottom(int aBottom)
void SetMarginRight(int aRight)
int GetLegacyTextMargin() const
void StyleFromSettings(const BOARD_DESIGN_SETTINGS &aSettings, bool aCheckSide) override
Definition pcb_text.cpp:373
EDA_ANGLE GetTextAngle() const override
Definition pcb_text.cpp:562
void SetLibTextThickness(int aWidth)
Definition pcb_text.cpp:556
void SetLibTextSize(const VECTOR2I &aSize)
Definition pcb_text.cpp:550
void Move(const VECTOR2I &aMoveVector) override
Move this object.
Definition pcb_text.h:105
int GetTextThickness() const override
Definition pcb_text.cpp:499
void SetTextAngle(const EDA_ANGLE &aAngle) override
Definition pcb_text.cpp:574
VECTOR2I GetTextSize() const override
Definition pcb_text.cpp:472
void Rotate(const VECTOR2I &aRotCentre, const EDA_ANGLE &aAngle) override
Rotate this object.
Definition pcb_text.cpp:585
void SetLibTextPos(const VECTOR2I &aPos)
Definition pcb_text.cpp:544
const PADSTACK & Padstack() const
Definition pcb_track.h:435
A REFERENCE_IMAGE is a wrapper around a BITMAP_IMAGE that is displayed in an editor as a reference fo...
bool ReadImageFile(const wxString &aFullFilename)
Read and store an image file.
void SetOrientation(const EDA_ANGLE &aAngle)
Set the rotation of the image content relative to the stored raster.
void SetOpacity(double aOpacity)
const BITMAP_BASE & GetImage() const
Get the underlying image.
double GetImageScale() const
void SetImageScale(double aScale)
Set the image "zoom" value.
Definition seg.h:38
VECTOR2I A
Definition seg.h:45
VECTOR2I B
Definition seg.h:46
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
int PointCount() const
Return the number of points (vertices) in this line chain.
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
Represent a set of closed polygons.
void RemoveAllContours()
Remove all outlines & holes (clears) the polygon set.
void BooleanAdd(const SHAPE_POLY_SET &b)
Perform boolean polyset union.
ITERATOR IterateWithHoles(int aOutline)
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index.
void SetVertex(const VERTEX_INDEX &aIndex, const VECTOR2I &aPos)
Accessor function to set the position of a specific point.
bool IsEmpty() const
Return true if the set is empty (no polygons at all)
int AddHole(const SHAPE_LINE_CHAIN &aHole, int aOutline=-1)
Adds a new hole to the given outline (default: last) and returns its index.
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
int NewOutline()
Creates a new empty polygon in the set and returns its index.
int OutlineCount() const
Return the number of outlines in the set.
A name/value tuple with unique names and wxAny values.
void ParseStroke(STROKE_PARAMS &aStroke)
Simple container to manage line stroke parameters.
int GetWidth() const
void SetWidth(int aWidth)
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.
Hold the information shown in the lower right corner of a plot, printout, or editing view.
Definition title_block.h:38
void SetRevision(const wxString &aRevision)
Definition title_block.h:78
void SetComment(int aIdx, const wxString &aComment)
Definition title_block.h:98
void SetTitle(const wxString &aTitle)
Definition title_block.h:55
void SetCompany(const wxString &aCompany)
Definition title_block.h:88
void SetDate(const wxString &aDate)
Set the date field, and defaults to the current time and date.
Definition title_block.h:68
VECTOR2I InverseApply(const VECTOR2I &aPoint) const
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
A wrapper around a wxFileName which is much more performant with a subset of the API.
Definition wx_filename.h:46
Handle zones parameters.
Handle a list of polygons defining a copper zone.
Definition zone.h:70
void HatchBorder()
Compute the hatch lines depending on the hatch parameters and stores it in the zone's attribute m_bor...
Definition zone.cpp:1637
SHAPE_POLY_SET * Outline()
Definition zone.h:421
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
void SetLayerSetAndRemoveUnusedFills(const LSET &aLayerSet)
Set the zone to be on the aLayerSet layers and only remove the fill polygons from the unused layers,...
Definition zone.cpp:2142
static int GetDefaultHatchPitch()
Definition zone.cpp:1695
int GetNumCorners(void) const
Access to m_Poly parameters.
Definition zone.h:619
A type-safe container of any type.
Definition ki_any.h:92
constexpr any() noexcept
Default constructor, creates an empty object.
Definition ki_any.h:155
This file is part of the common library.
void TransformOvalToPolygon(SHAPE_POLY_SET &aBuffer, const VECTOR2I &aStart, const VECTOR2I &aEnd, int aWidth, int aError, ERROR_LOC aErrorLoc, int aMinSegCount=0)
Convert a oblong shape to a polygon, using multiple segments.
@ ROUND_ALL_CORNERS
All angles are rounded.
bool DrillMarkModeFromToken(const wxString &aToken, DRILL_MARK_MODE &aMode)
bool DrillMarkPolicyFromToken(const wxString &aToken, DRILL_MARK_POLICY &aPolicy)
bool DrillGroupKeyFromToken(const wxString &aToken, DRILL_GROUP_KEY &aKey)
DRILL_MARK_POLICY
DRILL_GROUP_KEY
Which properties split holes into separate chart rows and symbols.
@ DSN_LEFT
Definition dsnlexer.h:63
@ DSN_RIGHT
Definition dsnlexer.h:62
@ DSN_NUMBER
Definition dsnlexer.h:61
@ DSN_STRING
Definition dsnlexer.h:64
@ DSN_EOF
Definition dsnlexer.h:65
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
@ DEGREES_T
Definition eda_angle.h:30
static constexpr EDA_ANGLE ANGLE_45
Definition eda_angle.h:473
@ NO_FILL
Definition eda_fill.h:30
@ REVERSE_HATCH
Definition eda_fill.h:35
@ HATCH
Definition eda_fill.h:34
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
@ CROSS_HATCH
Definition eda_fill.h:36
@ RECURSE
Definition eda_item.h:51
@ NO_RECURSE
Definition eda_item.h:52
@ ELLIPSE
Definition eda_shape.h:63
@ SEGMENT
Definition eda_shape.h:57
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
@ ELLIPSE_ARC
Definition eda_shape.h:64
EDA_DATA_TYPE
The type of unit.
Definition eda_units.h:34
EDA_UNITS
Definition eda_units.h:45
@ FP_SMD
Definition footprint.h:87
@ FP_DNP
Definition footprint.h:92
@ FP_EXCLUDE_FROM_POS_FILES
Definition footprint.h:88
@ FP_BOARD_ONLY
Definition footprint.h:90
@ FP_EXCLUDE_FROM_BOM
Definition footprint.h:89
@ FP_EXCLUDE_FROM_SIM
Definition footprint.h:93
@ FP_THROUGH_HOLE
Definition footprint.h:86
FOOTPRINT_STACKUP
Definition footprint.h:106
@ CUSTOM_LAYERS
Stackup handling where the footprint can have any number of copper layers, and objects on those layer...
Definition footprint.h:116
bool GeneratedTableUnitsFromToken(const wxString &aToken, GENERATED_TABLE_UNITS &aUnits)
LSET DocumentationLayers()
Layers a generated table or drill map may live on.
bool GeneratedTableAlignFromToken(const wxString &aToken, GENERATED_TABLE_ALIGN &aAlign)
GENERATED_TABLE_UNITS
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
#define THROW_IO_CANCELLED()
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
const wxChar *const traceKicadPcbPlugin
Flag to enable KiCad PCB plugin debug output.
void ignore_unused(const T &)
Definition ignore.h:20
KIID niluuid(0)
#define MIN_VISIBILITY_MASK
Definition layer_ids.h:708
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
Definition layer_ids.h:744
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_CrtYd
Definition layer_ids.h:112
@ B_Adhes
Definition layer_ids.h:99
@ Edge_Cuts
Definition layer_ids.h:108
@ F_Paste
Definition layer_ids.h:100
@ Cmts_User
Definition layer_ids.h:104
@ F_Adhes
Definition layer_ids.h:98
@ B_Mask
Definition layer_ids.h:94
@ B_Cu
Definition layer_ids.h:61
@ F_Mask
Definition layer_ids.h:93
@ B_Paste
Definition layer_ids.h:101
@ In15_Cu
Definition layer_ids.h:76
@ UNSELECTED_LAYER
Definition layer_ids.h:58
@ F_Fab
Definition layer_ids.h:115
@ Margin
Definition layer_ids.h:109
@ F_SilkS
Definition layer_ids.h:96
@ B_CrtYd
Definition layer_ids.h:111
@ UNDEFINED_LAYER
Definition layer_ids.h:57
@ Rescue
Definition layer_ids.h:117
@ B_SilkS
Definition layer_ids.h:97
@ PCB_LAYER_ID_COUNT
Definition layer_ids.h:167
@ F_Cu
Definition layer_ids.h:60
@ B_Fab
Definition layer_ids.h:114
This file contains miscellaneous commonly used macros and functions.
KICOMMON_API bool FetchUnitsFromString(const wxString &aTextValue, EDA_UNITS &aUnits)
Write any unit info found in the string to aUnits.
Definition eda_units.cpp:84
KICOMMON_API double GetScaleForInternalUnitType(const EDA_IU_SCALE &aIuScale, EDA_DATA_TYPE aDataType)
Returns the scaling parameter for the given units data type.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
@ NPTH
like PAD_PTH, but not plated mechanical use only, no connection allowed
Definition padstack.h:104
@ NON_COMPONENT
Pad with no hole that does not connect to a physical component, but rather provides a connection poin...
Definition padstack.h:106
@ SMD
Smd pad, appears on the solder paste layer (default)
Definition padstack.h:100
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ CONN
Like smd, does not appear on the solder paste layer (default) Note: also has a special attribute in G...
Definition padstack.h:101
@ CHAMFERED_RECT
Definition padstack.h:61
@ ROUNDRECT
Definition padstack.h:58
@ TRAPEZOID
Definition padstack.h:57
@ RECTANGLE
Definition padstack.h:55
@ FIDUCIAL_LOCAL
a fiducial (usually a smd) local to the parent footprint
Definition padstack.h:122
@ FIDUCIAL_GLBL
a fiducial (usually a smd) for the full board
Definition padstack.h:121
@ MECHANICAL
a pad used for mechanical support
Definition padstack.h:126
@ PRESSFIT
a PTH with a hole diameter with tight tolerances for press fit pin
Definition padstack.h:127
@ HEATSINK
a pad used as heat sink, usually in SMD footprints
Definition padstack.h:124
@ NONE
no special fabrication property
Definition padstack.h:119
@ TESTPOINT
a test point pad
Definition padstack.h:123
@ CASTELLATED
a pad with a castellated through hole
Definition padstack.h:125
@ BGA
Smd pad, used in BGA footprints.
Definition padstack.h:120
#define MAX_PAGE_SIZE_PCBNEW_MM
Definition page_info.h:36
#define MIN_PAGE_SIZE_MM
Min and max page sizes for clamping, in mm.
Definition page_info.h:35
BARCODE class definition.
PCB_CONSTRAINT_TYPE ConstraintTypeFromToken(const wxString &aToken)
Parse a constraint-type token; returns UNDEFINED for an unknown token.
bool ConstraintValueIsLength(PCB_CONSTRAINT_TYPE aType)
True if this type's value is a length in IU (serialized in mm); false for an angle in degrees.
CONSTRAINT_ANCHOR ConstraintAnchorFromToken(const wxString &aToken)
Parse an anchor token; returns WHOLE for an unknown token.
CONSTRAINT_ANCHOR
Which feature of a referenced board item participates in a constraint.
@ VERTEX
An indexed rectangle corner or polygon outline vertex; pairs with CONSTRAINT_MEMBER::m_index.
DIM_TEXT_POSITION
Where to place the text on a dimension.
@ MANUAL
Text placement is manually set by the user.
DIM_UNITS_FORMAT
How to display the units in a dimension's text.
DIM_UNITS_MODE
Used for storing the units selection in the file because EDA_UNITS alone doesn't cut it.
DIM_TEXT_BORDER
Frame to show around dimension text.
DIM_PRECISION
Class to handle a set of BOARD_ITEMs.
#define SEXPR_FOOTPRINT_LIB_FILE_VERSION
#define FIRST_FP_AFFINE_TRANSFORM
First version that stores footprint children in library frame.
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
#define LEGACY_ARC_FORMATTING
These were the last to use old arc formatting.
#define LEGACY_NET_TIES
These were the last to use the keywords field to indicate a net-tie.
#define BOARD_FILE_HOST_VERSION
Earlier files than this include the host tag.
constexpr double INT_LIMIT
Pcbnew s-expression file format parser definition.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
static bool IsNumber(char x)
double parseDouble(LINE_READER &aReader, const char *aLine, const char **aOutput)
Parses an ASCII point string with possible leading whitespace into a double precision floating point ...
const int scale
#define DEFAULT_SOLDERMASK_OPACITY
wxString ConvertToNewOverbarNotation(const wxString &aOldStr)
Convert the old ~...~ overbar notation to the new ~{...} one.
wxString From_UTF8(const char *cstring)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
One participant in a constraint: a referenced board item plus the feature of that item that participa...
KIID m_item
Referenced board item, usually a PCB_SHAPE.
CONSTRAINT_ANCHOR m_anchor
Which feature of that item participates.
int m_index
Vertex ordinal; only meaningful for the VERTEX anchor.
Container to handle a stock of specific differential pairs each with unique track width,...
Variant of PARSE_ERROR indicating that a syntax or related error was likely caused by a file generate...
The column a schema knows how to build, independent of whether any particular table shows it.
A column as a generated table actually carries it: what a row's cell in that column holds and how it ...
GENERATED_TABLE_ALIGN m_Align
Describes an imported layer and how it could be mapped to KiCad Layers.
PCB_LAYER_ID AutoMapLayer
Best guess as to what the equivalent KiCad layer might be.
bool Required
Should we require the layer to be assigned?
LSET PermittedLayers
KiCad layers that the imported layer can be mapped onto.
wxString Name
Imported layer name as displayed in original application.
Container to hold information pertinent to a layer of a BOARD.
Definition board.h:259
void clear()
Definition board.h:265
LAYER_T m_type
The type of the layer.
Definition board.h:288
wxString m_name
The canonical name of the layer.
Definition board.h:286
wxString m_userName
The user defined name of the layer.
Definition board.h:287
bool m_visible
Definition board.h:289
int m_number
The layer ID.
Definition board.h:290
The properties of a padstack drill.
Definition padstack.h:277
PCB_LAYER_ID start
Definition padstack.h:280
PCB_LAYER_ID end
Definition padstack.h:281
VECTOR2I size
Drill diameter (x == y) or slot dimensions (x != y)
Definition padstack.h:278
std::optional< bool > has_solder_mask
True if this outer layer has mask (is not tented)
Definition padstack.h:264
std::optional< PAD_DRILL_POST_MACHINING_MODE > mode
Definition padstack.h:292
A filename or source description, a problem input line, a line number, a byte offset,...
bool routing
Used by the router as a local routing frame.
bool cursor
Replace the display grid for cursor snapping inside coverage.
void SetAll(bool aState)
bool placement
Used by edit/move tools for placement snap.
Deferred constraint, resolved against the parsed items once the whole file is read,...
std::vector< std::pair< wxString, std::unique_ptr< BOARD_ITEM > > > templates
Named template items parsed from the generator's (templates …) section.
std::map< wxString, wxString > customProperties
Options for copying a placement rule area onto the others linked to it.
KIID m_anchor
This area's own anchor footprint, or niluuid for the area center.
Parameters that drive copper-thieving fill generation.
THIEVING_PATTERN pattern
EDA_ORIENTATION orientation
Container to handle a stock of specific vias each with unique diameter and drill sizes in the BOARD c...
std::optional< VECTOR2I > hatching_offset
wxString GetUserFieldName(int aFieldNdx, TRANSLATION aTranslation)
@ USER
The field ID hasn't been set yet; field is invalid.
@ DESCRIPTION
Field Description of part, i.e. "1/4W 1% Metal Film Resistor".
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
@ UNTRANSLATED
const std::string table
static EDA_ORIENTATION orientation(double d)
KIBIS top(path, &reporter)
KIBIS_MODEL * model
const SHAPE_LINE_CHAIN chain
wxString result
Test unit parsing edge cases and error handling.
int delta
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
wxLogTrace helper definitions.
bool IsStraightArc(const VECTOR2I &aStart, const VECTOR2I &aMid, const VECTOR2I &aEnd)
Definition trigo.cpp:549
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition typeinfo.h:98
@ PCB_DIM_LEADER_T
class PCB_DIM_LEADER, a leader dimension (graphic item)
Definition typeinfo.h:95
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:93
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:78
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:94
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:97
@ PCB_DRILL_CHART_T
class PCB_DRILL_CHART, a live drill chart derived from PCB_TABLE
Definition typeinfo.h:239
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
ISLAND_REMOVAL_MODE
Whether or not to remove isolated islands from a zone.
ZONE_BORDER_DISPLAY_STYLE
Zone border styles.
ZONE_CONNECTION
How pads are covered by copper in zone.
Definition zones.h:43
@ THERMAL
Use thermal relief for pads.
Definition zones.h:46
@ THT_THERMAL
Thermal relief only for THT pads.
Definition zones.h:48
@ NONE
Pads are not covered.
Definition zones.h:45
@ FULL
pads are covered by copper
Definition zones.h:47