KiCad PCB EDA Suite
Loading...
Searching...
No Matches
test_board_downgrade.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include <boost/test/unit_test.hpp>
21
22#include <algorithm>
23#include <cmath>
24#include <fstream>
25#include <map>
26#include <memory>
27#include <filesystem>
28#include <set>
29
30#include <wx/image.h>
31#include <wx/imagpng.h>
32#include <wx/mstream.h>
33
34#include <base_units.h>
35#include <board.h>
37#include <footprint.h>
38#include <font/font.h>
39#include <gr_text.h>
40#include <pcb_track.h>
45#include <pad.h>
46#include <padstack.h>
47#include <pcb_barcode.h>
48#include <pcb_group.h>
49#include <pcb_dimension.h>
50#include <pcb_drill_chart.h>
51#include <pcb_drill_map.h>
52#include <pcb_grid_item.h>
53#include <pcb_reference_image.h>
54#include <pcb_shape.h>
55#include <pcb_stackup_table.h>
56#include <pcb_table.h>
57#include <pcb_tablecell.h>
58#include <pcb_textbox.h>
60#include <zone.h>
61#include <zone_settings.h>
62#include <nlohmann/json.hpp>
63#include <netinfo.h>
64#include <project.h>
65#include <ki_exception.h>
66
68#include <downgrade_scan.h>
69#include <downgrade_target.h>
70#include <drc_rules_downgrade.h>
71#include <drc/drc_rule.h>
72#include <drc/drc_rule_parser.h>
80#include <qa_utils/file_utils.h>
81
82
83BOOST_AUTO_TEST_SUITE( BoardDowngrade )
84
85static const DOWNGRADE_TARGET& kicad9 = KI_TEST::RequireDowngradeTarget( wxT( "9.0" ) );
86static const DOWNGRADE_TARGET& kicad10 = KI_TEST::RequireDowngradeTarget( wxT( "10.0" ) );
87
88
89// A board with no post-10.0 features exports to 10.0 with nothing lost.
90BOOST_AUTO_TEST_CASE( EmptyBoardIsClean )
91{
92 BOARD board;
93
95
96 BOOST_CHECK( !report.IsLossy() );
97 BOOST_CHECK( !report.IsBlocked() );
98 BOOST_CHECK( report.Entries().empty() );
99}
100
101
102// The ellipse primitive only exists since 20260508, so 10.0 gets an approximation.
103BOOST_AUTO_TEST_CASE( EllipseIsLoweredForKicad10 )
104{
105 BOARD board;
106 board.Add( new PCB_SHAPE( &board, SHAPE_T::ELLIPSE ) );
107
109
110 BOOST_CHECK( report.IsLossy() );
112}
113
114
115// A target that already has the ellipse primitive keeps it. This proves the version gate.
116BOOST_AUTO_TEST_CASE( EllipseKeptForNewerTarget )
117{
118 BOARD board;
119 board.Add( new PCB_SHAPE( &board, SHAPE_T::ELLIPSE ) );
120
121 DOWNGRADE_TARGET future = { wxT( "future" ), wxT( "future" ), 20260623, 20260629, 20260629 };
122 COMPATIBILITY_REPORT report = ClassifyBoardForDowngrade( &board, future );
123
124 BOOST_CHECK( !report.IsLossy() );
125}
126
127
128BOOST_AUTO_TEST_CASE( EllipseTransformedToPolygon )
129{
130 BOARD board;
131 PCB_SHAPE* ellipse = new PCB_SHAPE( &board, SHAPE_T::ELLIPSE );
132 ellipse->SetStart( VECTOR2I( 0, 0 ) );
133 ellipse->SetEnd( VECTOR2I( pcbIUScale.mmToIU( 5 ), 0 ) );
134 board.Add( ellipse );
135
137
138 BOOST_CHECK( ellipse->GetShape() == SHAPE_T::POLY );
139}
140
141
142// An unfilled ellipse must be lowered to its outline polygon, not to stroke debris.
143BOOST_AUTO_TEST_CASE( UnfilledEllipseKeepsOutline )
144{
145 BOARD board;
146 PCB_SHAPE* ellipse = new PCB_SHAPE( &board, SHAPE_T::ELLIPSE );
147 ellipse->SetEllipseCenter( VECTOR2I( 0, 0 ) );
148 ellipse->SetEllipseMajorRadius( pcbIUScale.mmToIU( 5 ) );
149 ellipse->SetEllipseMinorRadius( pcbIUScale.mmToIU( 3 ) );
150 ellipse->SetFillMode( FILL_T::NO_FILL );
151 ellipse->SetWidth( pcbIUScale.mmToIU( 0.2 ) );
152 board.Add( ellipse );
153
155
156 BOOST_REQUIRE( ellipse->GetShape() == SHAPE_T::POLY );
158 BOOST_CHECK( ellipse->GetFillMode() == FILL_T::NO_FILL );
159
160 double areaMM =
161 std::abs( ellipse->GetPolyShape().Outline( 0 ).Area() ) / ( pcbIUScale.IU_PER_MM * pcbIUScale.IU_PER_MM );
162
163 BOOST_CHECK_CLOSE( areaMM, M_PI * 5.0 * 3.0, 2.0 );
164}
165
166
167// An elliptical arc is an open curve, so it is lowered to a filled polygon of its ink.
168BOOST_AUTO_TEST_CASE( EllipseArcKeepsInk )
169{
170 BOARD board;
171 PCB_SHAPE* arc = new PCB_SHAPE( &board, SHAPE_T::ELLIPSE_ARC );
172 arc->SetEllipseCenter( VECTOR2I( 0, 0 ) );
173 arc->SetEllipseMajorRadius( pcbIUScale.mmToIU( 5 ) );
174 arc->SetEllipseMinorRadius( pcbIUScale.mmToIU( 3 ) );
177 arc->SetWidth( pcbIUScale.mmToIU( 0.3 ) );
178 board.Add( arc );
179
181
183
184 // A quarter arc of a 5 mm by 3 mm ellipse is about 6.4 mm of path at 0.3 mm width.
185 double areaMM = std::abs( arc->GetPolyShape().Area() ) / ( pcbIUScale.IU_PER_MM * pcbIUScale.IU_PER_MM );
186
187 BOOST_CHECK_GT( areaMM, 1.5 );
188 BOOST_CHECK_LT( areaMM, 2.6 );
189}
190
191
192// Text box knockout (20250210) postdates 9.0, so the flag is dropped and reported for 9.0.
193BOOST_AUTO_TEST_CASE( KnockoutTextBoxLoweredForKicad9 )
194{
195 BOARD board;
196 PCB_TEXTBOX* textbox = new PCB_TEXTBOX( &board );
197 textbox->SetIsKnockout( true );
198 board.Add( textbox );
199
202
203 DowngradeBoardInPlace( &board, kicad9 );
204
205 BOOST_CHECK( !textbox->IsKnockout() );
206}
207
208
209// Table cell knockout (20260603) postdates both targets, so the flag is dropped for 10.0.
210BOOST_AUTO_TEST_CASE( TableCellKnockoutLoweredForKicad10 )
211{
212 BOARD board;
213 PCB_TABLE* table = new PCB_TABLE( &board, pcbIUScale.mmToIU( 0.1 ) );
214 table->SetColCount( 1 );
215
216 PCB_TABLECELL* cell = new PCB_TABLECELL( table );
217 cell->SetIsKnockout( true );
218 table->AddCell( cell );
219 board.Add( table );
220
221 // A table inside a footprint carries the same flag and must be counted and lowered too.
222 FOOTPRINT* fp = new FOOTPRINT( &board );
223 PCB_TABLE* fpTable = new PCB_TABLE( fp, pcbIUScale.mmToIU( 0.1 ) );
224 fpTable->SetColCount( 1 );
225
226 PCB_TABLECELL* fpCell = new PCB_TABLECELL( fpTable );
227 fpCell->SetIsKnockout( true );
228 fpTable->AddCell( fpCell );
229 fp->Add( fpTable );
230 board.Add( fp );
231
233
235
236 BOOST_CHECK( !cell->IsKnockout() );
237 BOOST_CHECK( !fpCell->IsKnockout() );
238}
239
240
241// A knockout cell in a library footprint goes through the footprint-scoped rule.
242BOOST_AUTO_TEST_CASE( FootprintTableCellKnockoutLowered )
243{
244 FOOTPRINT* fp = new FOOTPRINT( nullptr );
245 PCB_TABLE* table = new PCB_TABLE( fp, pcbIUScale.mmToIU( 0.1 ) );
246 table->SetColCount( 1 );
247
248 PCB_TABLECELL* cell = new PCB_TABLECELL( table );
249 cell->SetIsKnockout( true );
250 table->AddCell( cell );
251 fp->Add( table );
252
254
255 BOOST_CHECK( !cell->IsKnockout() );
256 delete fp;
257}
258
259
260// Rounded rectangles (20250829) postdate 9.0, so 9.0 gets a polygon that keeps the rounding.
261BOOST_AUTO_TEST_CASE( RoundedRectangleLoweredForKicad9 )
262{
263 BOARD board;
264 PCB_SHAPE* rect = new PCB_SHAPE( &board, SHAPE_T::RECTANGLE );
265 rect->SetStart( VECTOR2I( 0, 0 ) );
266 rect->SetEnd( VECTOR2I( pcbIUScale.mmToIU( 10 ), pcbIUScale.mmToIU( 6 ) ) );
267 rect->SetCornerRadius( pcbIUScale.mmToIU( 1 ) );
268 rect->SetFillMode( FILL_T::NO_FILL );
269 rect->SetWidth( pcbIUScale.mmToIU( 0.2 ) );
270 board.Add( rect );
271
274
275 DowngradeBoardInPlace( &board, kicad9 );
276
277 BOOST_REQUIRE( rect->GetShape() == SHAPE_T::POLY );
278 BOOST_REQUIRE_EQUAL( rect->GetPolyShape().OutlineCount(), 1 );
279
280 // A 10 mm by 6 mm rectangle loses ( 4 - pi ) r^2 to the rounded corners.
281 double areaMM =
282 std::abs( rect->GetPolyShape().Outline( 0 ).Area() ) / ( pcbIUScale.IU_PER_MM * pcbIUScale.IU_PER_MM );
283
284 BOOST_CHECK_CLOSE( areaMM, 60.0 - ( 4.0 - M_PI ), 2.0 );
285}
286
287
288// A custom footprint stackup (20250818) remaps inner layers. 9.0 would expand them and change
289// the connectivity, so the export must block.
290BOOST_AUTO_TEST_CASE( CustomFootprintStackupBlocksKicad9 )
291{
292 BOARD board;
293 FOOTPRINT* fp = new FOOTPRINT( &board );
295 board.Add( fp );
296
299}
300
301
302// Non-component pads (20261031) cannot be represented by older writers for now.
303// (Probably they can be approximated, but needs some thought)
304BOOST_AUTO_TEST_CASE( NonComponentPadBlocksOlderTargets )
305{
306 BOARD board;
307 FOOTPRINT* fp = new FOOTPRINT( &board );
308 board.Add( fp );
309
310 PAD* pad = new PAD( fp );
311 pad->SetAttribute( PAD_ATTRIB::NON_COMPONENT );
312 pad->SetLayerSet( LSET( { F_Cu } ) );
313 fp->Add( pad );
314
317}
318
319
320// Per-zone layer properties (20250302) postdate 9.0, so they are dropped like the board-level
321// zone defaults.
322BOOST_AUTO_TEST_CASE( ZoneLayerPropertiesDroppedForKicad9 )
323{
324 BOARD board;
325 ZONE* zone = new ZONE( &board );
326 zone->LayerProperties()[F_Cu].hatching_offset = VECTOR2I( 100, 100 );
327 board.Add( zone );
328
329 // A zone inside a footprint carries the same properties and must be counted and dropped too.
330 FOOTPRINT* fp = new FOOTPRINT( &board );
331 ZONE* fpZone = new ZONE( fp );
332 fpZone->LayerProperties()[F_Cu].hatching_offset = VECTOR2I( 100, 100 );
333 fp->Add( fpZone );
334 board.Add( fp );
335
337
338 DowngradeBoardInPlace( &board, kicad9 );
339
340 BOOST_CHECK( zone->LayerProperties().empty() );
341 BOOST_CHECK( fpZone->LayerProperties().empty() );
342}
343
344
345BOOST_AUTO_TEST_CASE( BoardZoneDefaultsRoundTripAndDowngrade )
346{
347 SETTINGS_MANAGER settingsManager;
348 BOARD board;
349 board.GetDesignSettings().m_ZoneLayerProperties[F_Cu].hatching_offset = VECTOR2I( 100000, 200000 );
350 board.GetDesignSettings().m_ZoneLayerProperties[B_Cu].hatching_offset = VECTOR2I( 300000, 400000 );
351
352 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_board_zone_defaults" );
353 const std::string src = ( tmp.Path() / "source.kicad_pcb" ).string();
355 io.SaveBoard( src, board );
356 const std::string original = KI_TEST::ReadGoldenText( src );
357 std::unique_ptr<BOARD> current( io.LoadBoard( src, nullptr ) );
358 BOOST_REQUIRE( current );
359 const auto& loadedDefaults = current->GetDesignSettings().m_ZoneLayerProperties;
360 BOOST_REQUIRE_EQUAL( loadedDefaults.size(), 2 );
361 BOOST_CHECK( loadedDefaults.at( F_Cu ).hatching_offset == VECTOR2I( 100000, 200000 ) );
362 BOOST_CHECK( loadedDefaults.at( B_Cu ).hatching_offset == VECTOR2I( 300000, 400000 ) );
363 BOOST_CHECK( current->GetDesignSettings().GetDefaultZoneSettings().m_LayerProperties.empty() );
364
365 for( const auto& target : { kicad9, kicad10 } )
366 {
368 const std::string dest = ( tmp.Path() / ( target.m_id.ToStdString() + ".kicad_pcb" ) ).string();
369 BOOST_REQUIRE( ExportBoardToOlderVersion( src, dest, target, report ) );
370 std::unique_ptr<BOARD> reloaded( io.LoadBoard( dest, nullptr ) );
371 BOOST_REQUIRE( reloaded );
372 const auto& defaults = reloaded->GetDesignSettings().m_ZoneLayerProperties;
373
374 if( target.m_id == wxT( "9.0" ) )
375 {
377 BOOST_CHECK( defaults.empty() );
378 BOOST_CHECK( KI_TEST::ReadGoldenText( dest ).find( "zone_defaults" ) == std::string::npos );
379 }
380 else
381 {
382 BOOST_CHECK( !report.IsLossy() );
383 BOOST_REQUIRE_EQUAL( defaults.size(), 2 );
384 BOOST_CHECK( defaults.at( F_Cu ).hatching_offset == loadedDefaults.at( F_Cu ).hatching_offset );
385 BOOST_CHECK( defaults.at( B_Cu ).hatching_offset == loadedDefaults.at( B_Cu ).hatching_offset );
386 }
387
388 BOOST_CHECK( KI_TEST::ReadGoldenText( src ) == original );
389 }
390}
391
392
393// The old (at) header cannot represent a scaled footprint, so the export must block.
394BOOST_AUTO_TEST_CASE( ScaledFootprintBlocksExport )
395{
396 BOARD board;
397 FOOTPRINT* fp = new FOOTPRINT( &board );
398 fp->SetTransformScale( 2.0, 1.0 );
399 board.Add( fp );
400
402
403 BOOST_CHECK( report.IsBlocked() );
405}
406
407
408// IPC-4761 via protection postdates 9.0, so it is dropped and reported for 9.0.
409BOOST_AUTO_TEST_CASE( ViaProtectionDroppedForKicad9 )
410{
411 BOARD board;
412 PCB_VIA* via = new PCB_VIA( &board );
413 via->Padstack().Drill().is_capped = true;
414 board.Add( via );
415
417
418 DowngradeBoardInPlace( &board, kicad9 );
419
420 BOOST_CHECK( !via->Padstack().Drill().is_capped.has_value() );
421}
422
423
424// Frequency-dependent dielectric models postdate both targets, so they are dropped for 10.0.
438
439
440// Group design block links postdate 9.0, so they are dropped and reported for 9.0.
441BOOST_AUTO_TEST_CASE( GroupDesignBlockLinkDroppedForKicad9 )
442{
443 BOARD board;
444 PCB_GROUP* group = new PCB_GROUP( &board );
445 group->SetDesignBlockLibId( LIB_ID( wxT( "Lib" ), wxT( "Block" ) ) );
446 board.Add( group );
447
449
450 DowngradeBoardInPlace( &board, kicad9 );
451
452 BOOST_CHECK( !group->HasDesignBlockLink() );
453}
454
455
456// Extruded 3D bodies (20260410) have no equivalent in 10.0, so they are dropped.
457BOOST_AUTO_TEST_CASE( ExtrudedBodyDroppedForKicad10 )
458{
459 BOARD board;
460 FOOTPRINT* fp = new FOOTPRINT( &board );
461 fp->EnsureBody();
462 board.Add( fp );
463
465
467
468 BOOST_CHECK( !fp->HasBody() );
469}
470
471
472// A refill in the old version would turn a thieving pattern into solid copper, quietly.
473// That is silent corruption, so the export must block.
474BOOST_AUTO_TEST_CASE( ThievingZoneBlocksKicad10 )
475{
476 BOARD board;
477 ZONE* zone = new ZONE( &board );
479 board.Add( zone );
480
482
484
485 BOOST_CHECK( zone->IsCopperThieving() );
486}
487
488
489// Backdrilling changes copper connectivity between layers, so the export must block for 9.0.
490BOOST_AUTO_TEST_CASE( BackdrillBlocksKicad9 )
491{
492 BOARD board;
493 PCB_VIA* via = new PCB_VIA( &board );
494 via->SetSecondaryDrillSize( VECTOR2I( pcbIUScale.mmToIU( 0.3 ), pcbIUScale.mmToIU( 0.3 ) ) );
495 board.Add( via );
496
499}
500
501
502// The headline fail-closed promise: a blocked board export returns failure and writes nothing.
503// The staging name must not be guessable, because the writer resolves symlinks on purpose.
504BOOST_AUTO_TEST_CASE( BoardExportIgnoresAPredictableStagingSymlink )
505{
506 SETTINGS_MANAGER settingsManager;
507
508 const std::string src = KI_TEST::GetPcbnewTestDataDir() + "via_off_center.kicad_pcb";
509
510 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_staging_symlink", "" );
511 const wxString dest = ( tmp.Path() / "out.kicad_pcb" ).wstring();
512 const wxString victim = ( tmp.Path() / "victim.txt" ).wstring();
513
514 {
515 wxFFile file( victim, wxT( "wb" ) );
516 BOOST_REQUIRE( file.IsOpened() );
517 file.Write( wxT( "untouched" ) );
518 }
519
520 const wxString decoy =
521 dest + wxString::Format( wxT( ".downgrade_tmp.%lu" ), (unsigned long) wxGetProcessId() );
522 std::error_code ec;
523 std::filesystem::create_symlink( victim.ToStdString(), decoy.ToStdString(), ec );
524 BOOST_REQUIRE( !ec );
525
527 BOOST_CHECK( ExportBoardToOlderVersion( src, dest, kicad9, report ) );
528
529 wxString after;
530 {
531 wxFFile file( victim, wxT( "rb" ) );
532 BOOST_REQUIRE( file.IsOpened() && file.ReadAll( &after ) );
533 }
534
535 BOOST_CHECK( after == wxT( "untouched" ) );
536
537 // A normal save in the same directory shares this umask, so the modes must agree.
538 const wxString reference = ( tmp.Path() / "reference.kicad_pcb" ).wstring();
540 std::unique_ptr<BOARD> board( io.LoadBoard( dest, nullptr ) );
541 BOOST_REQUIRE( board );
542 io.SaveBoard( reference, *board );
543
544 BOOST_CHECK( std::filesystem::status( dest.ToStdString() ).permissions()
545 == std::filesystem::status( reference.ToStdString() ).permissions() );
546}
547
548
549BOOST_AUTO_TEST_CASE( BlockedBoardExportWritesNothing )
550{
551 SETTINGS_MANAGER settingsManager;
552
553 BOARD board;
554 ZONE* zone = new ZONE( &board );
555 zone->SetLayer( F_Cu );
556 zone->AppendCorner( VECTOR2I( 0, 0 ), -1 );
557 zone->AppendCorner( VECTOR2I( pcbIUScale.mmToIU( 10 ), 0 ), -1 );
558 zone->AppendCorner( VECTOR2I( pcbIUScale.mmToIU( 10 ), pcbIUScale.mmToIU( 10 ) ), -1 );
560 board.Add( zone );
561
562 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_blocked_export", "" );
563 const wxString src = ( tmp.Path() / "src.kicad_pcb" ).wstring();
564 const wxString dest = ( tmp.Path() / "out.kicad_pcb" ).wstring();
565
567 io.SaveBoard( src, board );
568
570 BOOST_CHECK( !ExportBoardToOlderVersion( src, dest, kicad10, report ) );
571 BOOST_CHECK( report.IsBlocked() );
572 BOOST_CHECK( !wxFileExists( dest ) );
573}
574
575
576// Pad simulation electrical types (20260521) are dropped for 10.0.
577BOOST_AUTO_TEST_CASE( PadSimTypeDroppedForKicad10 )
578{
579 BOARD board;
580 FOOTPRINT* fp = new FOOTPRINT( &board );
581 PAD* pad = new PAD( fp );
582 pad->SetSimElectricalType( PAD_SIM_ELECTRICAL_TYPE::SOURCE );
583 fp->Add( pad );
584 board.Add( fp );
585
587
589
590 BOOST_CHECK( pad->GetSimElectricalType() == PAD_SIM_ELECTRICAL_TYPE::NONE );
591}
592
593
594// Counterbore / countersink is a post-9.0 feature 9.0 cannot parse, so it is dropped for 9.0.
595BOOST_AUTO_TEST_CASE( PostMachiningDroppedForKicad9 )
596{
597 BOARD board;
598 FOOTPRINT* fp = new FOOTPRINT( &board );
599 PAD* pad = new PAD( fp );
600 pad->Padstack().FrontPostMachining().mode = PAD_DRILL_POST_MACHINING_MODE::COUNTERBORE;
601 fp->Add( pad );
602 board.Add( fp );
603
605
606 DowngradeBoardInPlace( &board, kicad9 );
607
608 BOOST_CHECK( !pad->Padstack().FrontPostMachining().mode.has_value() );
609}
610
611
612// Press-fit is a post-9.0 pad property 9.0 cannot parse, so it is dropped for 9.0.
613BOOST_AUTO_TEST_CASE( PressFitDroppedForKicad9 )
614{
615 BOARD board;
616 FOOTPRINT* fp = new FOOTPRINT( &board );
617 PAD* pad = new PAD( fp );
618 pad->SetProperty( PAD_PROP::PRESSFIT );
619 fp->Add( pad );
620 board.Add( fp );
621
623
624 DowngradeBoardInPlace( &board, kicad9 );
625
626 BOOST_CHECK( pad->GetProperty() == PAD_PROP::NONE );
627}
628
629
630// Skip vias are post-9.0, so they are approximated by the nearest mode 9.0 understands.
631BOOST_AUTO_TEST_CASE( SkipViaLoweredForKicad9 )
632{
633 BOARD board;
634 PCB_VIA* via = new PCB_VIA( &board );
635 via->Padstack().SetUnconnectedLayerMode( UNCONNECTED_LAYER_MODE::START_END_ONLY );
636 board.Add( via );
637
639
640 DowngradeBoardInPlace( &board, kicad9 );
641
642 BOOST_CHECK( via->Padstack().UnconnectedLayerMode() == UNCONNECTED_LAYER_MODE::REMOVE_EXCEPT_START_AND_END );
643}
644
645
646// The v10 writer must not move anything. Every footprint and pad position in the export must match
647// the source exactly. This guards the extracted writer against silent model drift.
648BOOST_AUTO_TEST_CASE( ExportToKicad10PreservesGeometry )
649{
650 SETTINGS_MANAGER settingsManager;
651
652 const std::string src = KI_TEST::GetPcbnewTestDataDir() + "via_off_center.kicad_pcb";
653
654 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_downgrade_geom", "" );
655 const std::string dest = ( tmp.Path() / "out.kicad_pcb" ).string();
656
658 BOOST_REQUIRE( ExportBoardToOlderVersion( src, dest, kicad10, report ) );
659
661 std::unique_ptr<BOARD> source( io.LoadBoard( src, nullptr ) );
662 std::unique_ptr<BOARD> exported( io.LoadBoard( dest, nullptr ) );
663
664 BOOST_REQUIRE( source && exported );
665 BOOST_REQUIRE_EQUAL( source->Footprints().size(), exported->Footprints().size() );
666
667 for( size_t i = 0; i < source->Footprints().size(); i++ )
668 {
669 FOOTPRINT* a = source->Footprints()[i];
670 FOOTPRINT* b = exported->Footprints()[i];
671
673 BOOST_CHECK( a->GetPosition() == b->GetPosition() );
675
676 BOOST_REQUIRE_EQUAL( a->Pads().size(), b->Pads().size() );
677
678 for( size_t p = 0; p < a->Pads().size(); p++ )
679 BOOST_CHECK( a->Pads()[p]->GetPosition() == b->Pads()[p]->GetPosition() );
680 }
681}
682
683
684// Same geometry guard for the v9 writer.
685BOOST_AUTO_TEST_CASE( ExportToKicad9PreservesGeometry )
686{
687 SETTINGS_MANAGER settingsManager;
688
689 const std::string src = KI_TEST::GetPcbnewTestDataDir() + "via_off_center.kicad_pcb";
690
691 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_downgrade_geom9", "" );
692 const std::string dest = ( tmp.Path() / "out.kicad_pcb" ).string();
693
695 BOOST_REQUIRE( ExportBoardToOlderVersion( src, dest, kicad9, report ) );
696
698 std::unique_ptr<BOARD> source( io.LoadBoard( src, nullptr ) );
699 std::unique_ptr<BOARD> exported( io.LoadBoard( dest, nullptr ) );
700
701 BOOST_REQUIRE( source && exported );
702 BOOST_REQUIRE_EQUAL( source->Footprints().size(), exported->Footprints().size() );
703
704 for( size_t i = 0; i < source->Footprints().size(); i++ )
705 {
706 FOOTPRINT* a = source->Footprints()[i];
707 FOOTPRINT* b = exported->Footprints()[i];
708
709 BOOST_CHECK( a->GetPosition() == b->GetPosition() );
710
711 BOOST_REQUIRE_EQUAL( a->Pads().size(), b->Pads().size() );
712
713 for( size_t pd = 0; pd < a->Pads().size(); pd++ )
714 BOOST_CHECK( a->Pads()[pd]->GetPosition() == b->Pads()[pd]->GetPosition() );
715 }
716}
717
718
719// Buried vias postdate 9.0's blind/buried split, so they are written with the old combined type.
720BOOST_AUTO_TEST_CASE( BuriedViaLoweredForKicad9 )
721{
722 BOARD board;
723 PCB_VIA* via = new PCB_VIA( &board );
724 via->SetViaType( VIATYPE::BURIED );
725 board.Add( via );
726
728
729 DowngradeBoardInPlace( &board, kicad9 );
730
731 BOOST_CHECK( via->GetViaType() == VIATYPE::BLIND );
732}
733
734
735// Per-layer zone defaults are a post-9.0 setup block, so they are dropped for 9.0.
736BOOST_AUTO_TEST_CASE( ZoneDefaultsDroppedForKicad9 )
737{
738 BOARD board;
740
742
743 DowngradeBoardInPlace( &board, kicad9 );
744
746}
747
748
749// A barcode is fabricated ink, so it becomes its rendered polygons instead of vanishing.
750BOOST_AUTO_TEST_CASE( BarcodeLoweredToPolygonsForKicad9 )
751{
752 BOARD board;
753 PCB_BARCODE* barcode = new PCB_BARCODE( &board );
754 barcode->SetLayer( F_SilkS );
755 barcode->SetWidth( pcbIUScale.mmToIU( 10 ) );
756 barcode->SetHeight( pcbIUScale.mmToIU( 10 ) );
757 barcode->SetBarcodeText( wxT( "TEST123" ) );
758 board.Add( barcode );
759
762
763 // The net printed area, holes subtracted. A finder ring must not become a solid square.
765 barcode->TransformShapeToPolygon( expected, barcode->GetLayer(), 0, 0, ERROR_INSIDE );
766 expected.Simplify();
767 expected.Fracture();
768 double expectedMM = expected.Area() / ( pcbIUScale.IU_PER_MM * pcbIUScale.IU_PER_MM );
769
770 DowngradeBoardInPlace( &board, kicad9 );
771
772 int polyCount = 0;
773 double areaMM = 0;
774
775 for( BOARD_ITEM* item : board.Drawings() )
776 {
777 BOOST_REQUIRE( item->Type() != PCB_BARCODE_T );
778
779 if( item->Type() == PCB_SHAPE_T )
780 {
781 PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
782 BOOST_REQUIRE( shape->GetShape() == SHAPE_T::POLY );
783 BOOST_CHECK( shape->GetLayer() == F_SilkS );
784 polyCount++;
785 areaMM += std::abs( shape->GetPolyShape().Area() ) / ( pcbIUScale.IU_PER_MM * pcbIUScale.IU_PER_MM );
786 }
787 }
788
789 // The printed ink survives: many module polygons with a real total area.
790 BOOST_CHECK_GT( polyCount, 1 );
791 BOOST_CHECK_GT( areaMM, 5.0 );
792 BOOST_CHECK_CLOSE( areaMM, expectedMM, 0.1 );
793}
794
795
796BOOST_AUTO_TEST_CASE( BarcodeProjectVariablesResolvedBeforeExport )
797{
798 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_barcode_project" );
799 wxString projectPath = ( tmp.Path() / "source.kicad_pro" ).string();
800 wxString boardPath = ( tmp.Path() / "source.kicad_pcb" ).string();
801 wxString outputPath = ( tmp.Path() / "output.kicad_pcb" ).string();
802
803 {
804 std::ofstream project( projectPath.ToStdString() );
805 project << R"({"meta":{"version":3},"text_variables":{"SERIAL":"SERIAL123"}})";
806 }
807
808 SETTINGS_MANAGER settings;
809 BOOST_REQUIRE( settings.LoadProject( projectPath, false ) );
810 BOARD board;
811 board.SetProject( settings.GetProject( projectPath ), true );
812 PCB_BARCODE* barcode = new PCB_BARCODE( &board );
813 barcode->SetLayer( F_SilkS );
815 barcode->SetWidth( pcbIUScale.mmToIU( 10 ) );
816 barcode->SetHeight( pcbIUScale.mmToIU( 10 ) );
817 barcode->SetBarcodeText( wxT( "${SERIAL}" ) );
818 barcode->SetShowText( false );
819 board.Add( barcode );
820 BOOST_REQUIRE_EQUAL( barcode->GetShownText( FOR_CANVAS ), wxString( "SERIAL123" ) );
821
824 expected.Simplify();
825 expected.Fracture();
826 double expectedArea = expected.Area();
827
829 io.SaveBoard( boardPath, board );
831 BOOST_REQUIRE( ExportBoardToOlderVersion( boardPath, outputPath, kicad9, report ) );
832 std::unique_ptr<BOARD> result( io.LoadBoard( outputPath, nullptr ) );
834 int polygonCount = 0;
835 double resultArea = 0;
836
837 for( BOARD_ITEM* item : result->Drawings() )
838 {
839 BOOST_REQUIRE( item->Type() != PCB_BARCODE_T );
840
841 if( item->Type() == PCB_SHAPE_T )
842 {
843 PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
844 BOOST_REQUIRE( shape->GetShape() == SHAPE_T::POLY );
845 polygonCount++;
846 resultArea += std::abs( shape->GetPolyShape().Area() );
847 }
848 }
849
850 BOOST_CHECK_EQUAL( polygonCount, expected.OutlineCount() );
851 BOOST_CHECK_CLOSE( resultArea, expectedArea, 0.01 );
852}
853
854
855// A barcode inside a footprint takes the same conversion through the footprint path.
856BOOST_AUTO_TEST_CASE( FootprintBarcodeLoweredForKicad9 )
857{
858 BOARD board;
859 FOOTPRINT* fp = new FOOTPRINT( &board );
860 PCB_BARCODE* barcode = new PCB_BARCODE( fp );
861 barcode->SetLayer( F_SilkS );
862 barcode->SetWidth( pcbIUScale.mmToIU( 10 ) );
863 barcode->SetHeight( pcbIUScale.mmToIU( 10 ) );
864 barcode->SetBarcodeText( wxT( "TEST123" ) );
865 fp->Add( barcode );
866 board.Add( fp );
867
869
870 DowngradeBoardInPlace( &board, kicad9 );
871
872 int polyCount = 0;
873
874 for( BOARD_ITEM* item : fp->GraphicalItems() )
875 {
876 BOOST_REQUIRE( item->Type() != PCB_BARCODE_T );
877
878 if( item->Type() == PCB_SHAPE_T && static_cast<PCB_SHAPE*>( item )->GetShape() == SHAPE_T::POLY )
879 polyCount++;
880 }
881
882 BOOST_CHECK_GT( polyCount, 1 );
883}
884
885
886// Exercise the real .kicad_mod write path used to downgrade a footprint library, and confirm the
887// result carries the target stamp and reloads cleanly.
888BOOST_AUTO_TEST_CASE( FootprintFileDowngradeRoundTrips )
889{
890 const std::string src = KI_TEST::GetPcbnewTestDataDir() + "issue24045/QFN-24_L4.0-W4.0-P0.50-BL-EP2.6.kicad_mod";
891
892 PCB_IO_KICAD_SEXPR loader;
893 wxString nameOut;
894 std::unique_ptr<FOOTPRINT> fp( loader.ImportFootprint( src, nameOut ) );
895 BOOST_REQUIRE( fp != nullptr );
896
898
899 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_fp_downgrade", "" );
900 const wxString dest = ( tmp.Path() / "out.kicad_mod" ).wstring();
901
902 SaveFootprintForTarget( fp.get(), dest, kicad9 );
903
904 // The stamp proves the dispatch picked the right writer, not just a parseable one.
905 std::ifstream out( dest.ToStdString() );
906 std::string content( ( std::istreambuf_iterator<char>( out ) ), std::istreambuf_iterator<char>() );
907 BOOST_CHECK( content.find( "(version " + std::to_string( kicad9.m_boardVersion ) + ")" ) != std::string::npos );
908
909 PCB_IO_KICAD_SEXPR reader;
910 wxString reloadName;
911 std::unique_ptr<FOOTPRINT> reloaded( reader.ImportFootprint( dest, reloadName ) );
912 BOOST_CHECK( reloaded != nullptr );
913}
914
915
916// The v10 footprint file path gets the same round-trip check as v9.
917BOOST_AUTO_TEST_CASE( FootprintFileV10RoundTrips )
918{
919 SETTINGS_MANAGER settingsManager;
920
921 const std::string src = KI_TEST::GetPcbnewTestDataDir() + "issue24045/QFN-24_L4.0-W4.0-P0.50-BL-EP2.6.kicad_mod";
922
923 PCB_IO_KICAD_SEXPR loader;
924 wxString nameOut;
925 std::unique_ptr<FOOTPRINT> fp( loader.ImportFootprint( src, nameOut ) );
926 BOOST_REQUIRE( fp != nullptr );
927
929
930 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_fp_downgrade10", "" );
931 const wxString dest = ( tmp.Path() / "out.kicad_mod" ).wstring();
932
933 SaveFootprintForTarget( fp.get(), dest, kicad10 );
934
935 std::ifstream out( dest.ToStdString() );
936 std::string content( ( std::istreambuf_iterator<char>( out ) ), std::istreambuf_iterator<char>() );
937 BOOST_CHECK( content.find( "(version " + std::to_string( kicad10.m_boardVersion ) + ")" ) != std::string::npos );
938
939 PCB_IO_KICAD_SEXPR reader;
940 wxString reloadName;
941 std::unique_ptr<FOOTPRINT> reloaded( reader.ImportFootprint( dest, reloadName ) );
942 BOOST_CHECK( reloaded != nullptr );
943}
944
945
946// A library footprint carries the same features but is downgraded through its own path.
947BOOST_AUTO_TEST_CASE( FootprintPressFitDroppedForKicad9 )
948{
949 BOARD board;
950 FOOTPRINT* fp = new FOOTPRINT( &board );
951 PAD* pad = new PAD( fp );
952 pad->SetProperty( PAD_PROP::PRESSFIT );
953 fp->Add( pad );
954
956
957 BOOST_CHECK( pad->GetProperty() == PAD_PROP::NONE );
958
959 delete fp;
960}
961
962
963// Saving with a target version writes the older stamp, and reloading reads it back.
964BOOST_AUTO_TEST_CASE( SaveWithTargetVersionStampsOlder )
965{
966 SETTINGS_MANAGER settingsManager;
967
968 BOARD board;
969
970 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_downgrade", "" );
971 std::string dest = ( tmp.Path() / "out.kicad_pcb" ).string();
972
973 SaveBoardForTarget( &board, dest, kicad10 );
974
975 PCB_IO_KICAD_SEXPR reader;
976 std::unique_ptr<BOARD> reloaded( reader.LoadBoard( dest, nullptr ) );
977
978 BOOST_REQUIRE( reloaded != nullptr );
979 BOOST_CHECK_EQUAL( reloaded->GetFileFormatVersionAtLoad(), kicad10.m_boardVersion );
980}
981
982
983// The fields deque can hold null slots. The writer must skip them like the current one does.
984BOOST_AUTO_TEST_CASE( NullFieldSlotDoesNotCrashV9Writer )
985{
986 SETTINGS_MANAGER settingsManager;
987
988 std::unique_ptr<FOOTPRINT> fp = std::make_unique<FOOTPRINT>( nullptr );
989 fp->GetFields().push_back( nullptr );
990
991 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_v9_nullfield", "" );
992 const wxString dest = ( tmp.Path() / "out.kicad_mod" ).wstring();
993
994 SaveFootprintForTarget( fp.get(), dest, kicad9 );
995
996 BOOST_CHECK( std::filesystem::exists( dest.ToStdString() ) );
997}
998
999
1000// The 10.0 release writer skips group members that are no longer on the board, so the v10
1001// snapshot must too. The 9.0 release writer had no such check and its snapshot stays faithful.
1002BOOST_AUTO_TEST_CASE( StaleGroupMemberNotWrittenForV10 )
1003{
1004 SETTINGS_MANAGER settingsManager;
1005
1006 BOARD board;
1007 PCB_SHAPE* onBoard = new PCB_SHAPE( &board, SHAPE_T::SEGMENT );
1008 board.Add( onBoard );
1009
1010 PCB_SHAPE* stale = new PCB_SHAPE( &board, SHAPE_T::SEGMENT );
1011
1012 PCB_GROUP* group = new PCB_GROUP( &board );
1013 group->AddItem( onBoard );
1014 group->AddItem( stale );
1015 board.Add( group );
1016
1017 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_v10_stalegroup", "" );
1018 const std::string dest = ( tmp.Path() / "out.kicad_pcb" ).string();
1019
1020 SaveBoardForTarget( &board, dest, kicad10 );
1021
1022 std::ifstream out( dest );
1023 std::string content( ( std::istreambuf_iterator<char>( out ) ), std::istreambuf_iterator<char>() );
1024
1025 BOOST_CHECK( content.find( onBoard->m_Uuid.AsString().ToStdString() ) != std::string::npos );
1026 BOOST_CHECK( content.find( stale->m_Uuid.AsString().ToStdString() ) == std::string::npos );
1027
1028 group->RemoveAll();
1029 delete stale;
1030}
1031
1032
1033// A via mode the era writer predates must be written as the nearest era mode, not silently
1034// fall through to keep-all.
1035BOOST_AUTO_TEST_CASE( SkipViaModeWrittenForV9 )
1036{
1037 SETTINGS_MANAGER settingsManager;
1038
1039 BOARD board;
1040 PCB_VIA* via = new PCB_VIA( &board );
1041 via->Padstack().SetUnconnectedLayerMode( UNCONNECTED_LAYER_MODE::START_END_ONLY );
1042 board.Add( via );
1043
1044 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_v9_skipvia", "" );
1045 const std::string dest = ( tmp.Path() / "out.kicad_pcb" ).string();
1046
1047 SaveBoardForTarget( &board, dest, kicad9 );
1048
1049 std::ifstream out( dest );
1050 std::string content( ( std::istreambuf_iterator<char>( out ) ), std::istreambuf_iterator<char>() );
1051
1052 BOOST_CHECK( content.find( "(remove_unused_layers yes)" ) != std::string::npos );
1053 BOOST_CHECK( content.find( "(keep_end_layers yes)" ) != std::string::npos );
1054
1055 PCB_IO_KICAD_SEXPR reader;
1056 std::unique_ptr<BOARD> reloaded( reader.LoadBoard( dest, nullptr ) );
1057 BOOST_REQUIRE( reloaded );
1058 BOOST_REQUIRE_EQUAL( reloaded->Tracks().size(), 1 );
1059 BOOST_REQUIRE( reloaded->Tracks().front()->Type() == PCB_VIA_T );
1060 const PCB_VIA* reloadedVia = static_cast<const PCB_VIA*>( reloaded->Tracks().front() );
1061 BOOST_CHECK( reloadedVia->Padstack().UnconnectedLayerMode()
1063}
1064
1065
1066// The target computes the image PPI the old truncating way, so the stored scale must be
1067// migrated back or the image renders at the wrong size there.
1068BOOST_AUTO_TEST_CASE( ImageScaleMigratedForV9 )
1069{
1070 SETTINGS_MANAGER settingsManager;
1071
1072 BOARD board;
1073 PCB_REFERENCE_IMAGE* otherImage = new PCB_REFERENCE_IMAGE( &board );
1074 wxMemoryBuffer buf = KI_TEST::MakePngWithFractionalPixelsPerCm();
1075 BOOST_REQUIRE( otherImage->GetReferenceImage().ReadImageFile( buf ) );
1076 otherImage->GetReferenceImage().SetImageScale( 0.5 );
1077 board.Add( otherImage );
1078
1080 REFERENCE_IMAGE& ref = image->GetReferenceImage();
1081
1082 BOOST_REQUIRE( ref.ReadImageFile( buf ) );
1083 ref.SetImageScale( 2.0 );
1084 board.Add( image );
1085
1086 int ppi = ref.GetImage().GetPPI();
1087 int legacyPPI = ref.GetImage().GetLegacyPPI();
1088 BOOST_REQUIRE( legacyPPI > 0 && ppi != legacyPPI );
1089
1090 double originalScale = ref.GetImageScale();
1091
1092 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_v9_imgscale", "" );
1093 const std::string dest = ( tmp.Path() / "out.kicad_pcb" ).string();
1094
1095 DowngradeBoardInPlace( &board, kicad9 );
1096 SaveBoardForTarget( &board, dest, kicad9 );
1097
1098 std::ifstream out( dest );
1099 std::string content( ( std::istreambuf_iterator<char>( out ) ), std::istreambuf_iterator<char>() );
1100
1101 const double written = KI_TEST::SerializedImageScale( content, image->m_Uuid.AsStdString() );
1102 BOOST_CHECK_CLOSE( written, originalScale * legacyPPI / ppi, 0.1 );
1103 BOOST_CHECK_CLOSE( KI_TEST::SerializedImageScale( content, otherImage->m_Uuid.AsStdString() ),
1104 0.5 * legacyPPI / ppi, 0.1 );
1105}
1106
1107
1108// The target has no way to store an image rotation, so an angled image blocks the export.
1109BOOST_AUTO_TEST_CASE( RotatedReferenceImageBlocks )
1110{
1111 BOARD board;
1113 image->GetReferenceImage().SetOrientation( EDA_ANGLE( 45.0, DEGREES_T ) );
1114 board.Add( image );
1115
1117
1118 BOOST_CHECK( report.IsBlocked() );
1120
1121 // An upright image is still exportable.
1122 image->GetReferenceImage().SetOrientation( ANGLE_0 );
1123 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
1124}
1125
1126
1127// The target has no way to store an image opacity, so the export proceeds with full opacity.
1128BOOST_AUTO_TEST_CASE( ReferenceImageOpacityIsDropped )
1129{
1130 BOARD board;
1132 image->GetReferenceImage().SetOpacity( 0.4 );
1133 board.Add( image );
1134
1136
1137 BOOST_CHECK( !report.IsBlocked() );
1139
1140 DowngradeBoardInPlace( &board, kicad10 );
1141
1142 BOOST_CHECK_EQUAL( image->GetReferenceImage().GetOpacity(), 1.0 );
1144}
1145
1146
1147// The fail-closed gate: a post-10.0 token surviving in the output is caught, and lookalikes are not.
1148BOOST_AUTO_TEST_CASE( VerifyGateCatchesUnsupportedTokens )
1149{
1150 // An unstripped feature (e.g. an affine transform) must be caught.
1151 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(footprint (transform (translate 1 2)))" ), kicad10 )
1152 == wxT( "transform" ) );
1153 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(net_chain \"n\")" ), kicad10 ) == wxT( "net_chain" ) );
1154
1155 // A clean board, and lookalike prefixes, must pass.
1156 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(kicad_pcb (net 0 \"n\") (gr_line ...))" ), kicad10 ).IsEmpty() );
1157
1158 // Value tokens the node scan cannot see must still be caught for 9.0, but not inside strings.
1159
1160 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(via buried (at 1 1))" ), kicad9 ) == wxT( "buried" ) );
1161 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(gr_text \"buried treasure\")" ), kicad9 ).IsEmpty() );
1162}
1163
1164
1165// One unknown keyword makes an old KiCad drop the whole rules file, so the export must
1166// comment out rules the target cannot parse and keep the rest byte-identical.
1167BOOST_AUTO_TEST_CASE( DrcRulesFilterForKicad9 )
1168{
1169 const wxString rules = wxT( "(version 2)\n"
1170 "# keep me\n"
1171 "(rule \"clearance_ok\"\n"
1172 " # chamfer runs at 45deg here\n"
1173 " (constraint clearance (min 0.2mm))\n"
1174 " (condition \"A.NetClass == 'HV'\"))\n"
1175 "(rule \"mask_check\"\n"
1176 " (constraint bridged_mask))\n"
1177 "(rule \"chain_check\"\n"
1178 " (condition \"inNetChain('x')\")\n"
1179 " (constraint clearance (min 0.1mm)))\n"
1180 "(rule \"delay_check\"\n"
1181 " (constraint skew (max 5ps)))\n" );
1182
1184
1185 BOOST_REQUIRE_EQUAL( result.m_dropped.size(), 3 );
1186 BOOST_CHECK_EQUAL( result.m_dropped[0], wxString( "mask_check" ) );
1187 BOOST_CHECK_EQUAL( result.m_dropped[1], wxString( "chain_check" ) );
1188 BOOST_CHECK_EQUAL( result.m_dropped[2], wxString( "delay_check" ) );
1189
1190 BOOST_CHECK( result.m_text.Contains( wxT( "(version 1)" ) ) );
1191 BOOST_CHECK( result.m_text.Contains( wxT( "# keep me" ) ) );
1192 BOOST_CHECK( result.m_text.Contains( wxT( "(rule \"clearance_ok\"" ) ) );
1193 BOOST_CHECK( result.m_text.Contains( wxT( "A.NetClass == 'HV'" ) ) );
1194 BOOST_CHECK( result.m_text.Contains( wxT( "# Not supported by KiCad 9.0:\n"
1195 "# (rule \"mask_check\"\n# (constraint bridged_mask))\n" ) ) );
1196 BOOST_CHECK( result.m_text.Contains( wxT( "# (rule \"chain_check\"\n# (condition \"inNetChain('x')\")\n" ) ) );
1197 BOOST_CHECK( result.m_text.Contains( wxT( "# (rule \"delay_check\"\n# (constraint skew (max 5ps)))\n" ) ) );
1198}
1199
1200
1201static size_t ParsedDrcRuleCount( const wxString& aText, const wxString& aSource )
1202{
1203 DRC_RULES_PARSER parser( aText, aSource );
1205 std::vector<std::shared_ptr<DRC_RULE>> rules;
1206 parser.Parse( rules, &reporter );
1207 BOOST_CHECK_MESSAGE( !reporter.HasMessageOfSeverity( RPT_SEVERITY_ERROR ), reporter.GetMessages() );
1208 return rules.size();
1209}
1210
1211
1212BOOST_AUTO_TEST_CASE( DroppedRulesStayInTheFileAsComments )
1213{
1214 const wxString rules = wxT( "(version 2)\n"
1215 "(rule \"keep\" (constraint clearance (min 0.2mm)))\n"
1216 "# why the chain rule exists\n"
1217 "(rule \"chain\"\n"
1218 " (constraint net_chain_length (max 10mm)))\n"
1219 "(rule \"glued\" (constraint net_chain_length (max 1mm)))"
1220 "(rule \"after\" (constraint clearance (min 0.1mm)))\n" );
1221
1222 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1223 {
1225 BOOST_REQUIRE( result.m_error.IsEmpty() );
1226 BOOST_REQUIRE_EQUAL( result.m_dropped.size(), 2 );
1227
1228 const wxString marker = wxT( "# Not supported by " ) + target.m_name + wxT( ":\n" );
1229 const wxString expected = wxT( "(version 1)\n"
1230 "(rule \"keep\" (constraint clearance (min 0.2mm)))\n"
1231 "# why the chain rule exists\n" )
1232 + marker
1233 + wxT( "# (rule \"chain\"\n"
1234 "# (constraint net_chain_length (max 10mm)))\n" )
1235 + marker
1236 + wxT( "# (rule \"glued\" (constraint net_chain_length (max 1mm)))\n"
1237 "(rule \"after\" (constraint clearance (min 0.1mm)))\n" );
1239 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_commented_rules" ) ), 2 );
1240 }
1241}
1242
1243
1244BOOST_AUTO_TEST_CASE( CommentedRuleStartsAndEndsOnItsOwnLine )
1245{
1246 const wxString rules = wxT( "(version 2)"
1247 "(rule \"first\" (constraint net_chain_length (max 1mm)))"
1248 "(rule \"kept\" (constraint clearance (min 0.2mm)))"
1249 "(rule \"last\" (constraint net_chain_length (max 1mm)))" );
1250
1251 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1252 {
1254 BOOST_REQUIRE( result.m_error.IsEmpty() );
1255
1256 const wxString marker = wxT( "# Not supported by " ) + target.m_name + wxT( ":\n" );
1257 const wxString expected = wxT( "(version 1)\n" ) + marker
1258 + wxT( "# (rule \"first\" (constraint net_chain_length (max 1mm)))\n"
1259 "(rule \"kept\" (constraint clearance (min 0.2mm)))\n" )
1260 + marker + wxT( "# (rule \"last\" (constraint net_chain_length (max 1mm)))\n" );
1262 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_glued_rules" ) ), 1 );
1263 }
1264}
1265
1266
1267BOOST_AUTO_TEST_CASE( CommentedRuleKeepsItsOwnCommentsAndLineEndings )
1268{
1269 const wxString rules = wxT( "(version 2)\r\n"
1270 " (rule \"messy\"\r\n"
1271 " # ) \" ( unmatched in a comment\r\n"
1272 " (condition \"A.NetName == 'a'\")\r\n"
1273 " (constraint net_chain_length (max 1mm)))\r\n"
1274 "(rule \"kept\" (constraint clearance (min 0.2mm)))\r\n" );
1275
1276 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1277 {
1279 BOOST_REQUIRE( result.m_error.IsEmpty() );
1280 BOOST_REQUIRE_EQUAL( result.m_dropped.size(), 1 );
1281 BOOST_CHECK( result.m_dropped.front() == wxT( "messy" ) );
1282
1283 const wxString expected = wxT( "(version 1)\r\n # Not supported by " ) + target.m_name
1284 + wxT( ":\r\n"
1285 "# (rule \"messy\"\r\n"
1286 "# # ) \" ( unmatched in a comment\r\n"
1287 "# (condition \"A.NetName == 'a'\")\r\n"
1288 "# (constraint net_chain_length (max 1mm)))\r\n"
1289 "(rule \"kept\" (constraint clearance (min 0.2mm)))\r\n" );
1291 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_crlf_rules" ) ), 1 );
1292 }
1293}
1294
1295
1296BOOST_AUTO_TEST_CASE( UnknownTopLevelBlockIsCommentedOut )
1297{
1298 const wxString rules = wxT( "(version 2)\n"
1299 "(future_block \"x\" (constraint clearance (min 1mm)))\n"
1300 "(rule \"kept\" (constraint clearance (min 0.2mm)))\n" );
1301
1302 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1303 {
1305 BOOST_REQUIRE( result.m_error.IsEmpty() );
1306 BOOST_CHECK_EQUAL( result.m_dropped.size(), 1 );
1307 BOOST_CHECK( result.m_text.Contains( wxT( "# (future_block \"x\" (constraint clearance (min 1mm)))\n"
1308 "(rule \"kept\"" ) ) );
1309 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_unknown_block" ) ), 1 );
1310 }
1311}
1312
1313
1314BOOST_AUTO_TEST_CASE( ExportedRulesFileDowngradesAgainUnchanged )
1315{
1316 const wxString rules = wxT( "(version 2)\n"
1317 "# why the chain rule exists\n"
1318 "(rule \"chain\"\n"
1319 " # ) \" (\n"
1320 " (constraint net_chain_length (max 10mm)))\n"
1321 "(rule \"after\" (constraint clearance (min 0.1mm)))"
1322 "(rule \"last\" (constraint net_chain_length (max 1mm)))\n"
1323 "# trailing note\n" );
1324
1325 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1326 {
1327 DRC_RULES_FILTER_RESULT first = FilterDrcRulesForTarget( rules, target );
1328 BOOST_REQUIRE( first.m_error.IsEmpty() );
1329 BOOST_REQUIRE_EQUAL( first.m_dropped.size(), 2 );
1330 BOOST_CHECK( first.m_text.EndsWith( wxT( "# (rule \"last\" (constraint net_chain_length (max 1mm)))\n"
1331 "# trailing note\n" ) ) );
1332
1333 DRC_RULES_FILTER_RESULT second = FilterDrcRulesForTarget( first.m_text, target );
1334 BOOST_CHECK( second.m_error.IsEmpty() );
1335 BOOST_CHECK( second.m_dropped.empty() );
1336 BOOST_CHECK_EQUAL( second.m_text, first.m_text );
1337 }
1338}
1339
1340
1341BOOST_AUTO_TEST_CASE( DrcRuleNamesAndExpressionLiteralsDoNotTriggerDrops )
1342{
1343 const wxString rules = wxT( "(version 1)\n"
1344 "(rule \"return_path\" (constraint clearance (min 0.2mm)))\n"
1345 "(rule inNetChain (constraint clearance (min 0.2mm)))\n"
1346 "(rule \"literal\" (condition \"A.NetName == 'hasNetChain() 100 ps .Parent.'\")\n"
1347 " (constraint clearance (min 0.2mm)))\n" );
1348
1349 for( const DOWNGRADE_TARGET* target : { &kicad9, &kicad10 } )
1350 {
1352 BOOST_CHECK( result.m_error.IsEmpty() );
1353 BOOST_CHECK( result.m_dropped.empty() );
1354 BOOST_CHECK_EQUAL( result.m_text.Mid( result.m_text.Find( "(rule" ) ), rules.Mid( rules.Find( "(rule" ) ) );
1355 }
1356}
1357
1358
1359BOOST_AUTO_TEST_CASE( SpacedTimeAndAngleUnitsAreDroppedForKicad9 )
1360{
1361 const wxString rules = wxT( "(version 1)\n"
1362 "(rule \"time\" (constraint length (min \"100 ps\")))\n"
1363 "(rule \"femtoseconds\" (constraint length (max \"2 * 100 fs\")))\n"
1364 "(rule \"angle\" (constraint track_angle (max \"90 deg\")))\n"
1365 "(rule \"ordinary\" (constraint clearance (min \"0.2 mm\")))\n" );
1366
1368 BOOST_CHECK( result9.m_error.IsEmpty() );
1369 BOOST_CHECK_EQUAL( result9.m_dropped.size(), 3 );
1370 BOOST_CHECK( result9.m_text.Contains( "ordinary" ) );
1371
1373 BOOST_CHECK( result10.m_error.IsEmpty() );
1374 BOOST_CHECK( result10.m_dropped.empty() );
1375 BOOST_CHECK_EQUAL( result10.m_text.Mid( result10.m_text.Find( "(rule" ) ), rules.Mid( rules.Find( "(rule" ) ) );
1376}
1377
1378
1379// 10.0 knows the mask constraints and time units. Only post-10.0 syntax drops for it.
1380BOOST_AUTO_TEST_CASE( DrcRulesFilterForKicad10 )
1381{
1382 const wxString rules = wxT( "(version 2)\n"
1383 "(rule \"mask_check\" (constraint bridged_mask))\n"
1384 "(rule \"delay_check\" (constraint skew (max 5ps)))\n"
1385 "(rule \"chain_check\" (constraint net_chain_length (max 10mm)))\n" );
1386
1388
1389 BOOST_REQUIRE_EQUAL( result.m_dropped.size(), 1 );
1390 BOOST_CHECK_EQUAL( result.m_dropped[0], wxString( "chain_check" ) );
1391 BOOST_CHECK( result.m_text.Contains( wxT( "bridged_mask" ) ) );
1392 BOOST_CHECK( result.m_text.Contains( wxT( "5ps" ) ) );
1393}
1394
1395
1396// Comment syntax must never participate in balancing a rule. Parentheses or quotes
1397// in a full-line comment used to truncate or swallow otherwise valid rules.
1398BOOST_AUTO_TEST_CASE( DrcRulesWithCommentsRemainIntact )
1399{
1400 const wxString kept = wxT( "(rule \"clearance # literal\"\n"
1401 " # unmatched: ) (( \" \\\n"
1402 " (condition \"A.NetName == 'SIGNAL#1'\")\n"
1403 " # inNetChain('x')\n"
1404 " (constraint clearance (min 0.2mm))\n"
1405 " # ) \" (\n"
1406 ")\n"
1407 "(rule \"second\" (constraint track_width (min 0.25mm)))" );
1408 const wxString input = wxT( "(version 2)\n" ) + kept
1409 + wxT( "\n(rule \"unsupported\"\n # ) \" (\n"
1410 " (constraint net_chain_length (max 10mm)))\n" );
1411
1412 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1413 {
1415 BOOST_REQUIRE( result.m_error.IsEmpty() );
1416 BOOST_REQUIRE_EQUAL( result.m_dropped.size(), 1 );
1417 BOOST_CHECK( result.m_dropped.front() == wxT( "unsupported" ) );
1418 BOOST_CHECK( result.m_text.Contains( kept ) );
1419
1420 DRC_RULES_PARSER parser( result.m_text, wxT( "downgrade_inline_comments" ) );
1422 std::vector<std::shared_ptr<DRC_RULE>> rules;
1423 parser.Parse( rules, &reporter );
1424 BOOST_CHECK_MESSAGE( !reporter.HasMessageOfSeverity( RPT_SEVERITY_ERROR ), reporter.GetMessages() );
1425 BOOST_REQUIRE_EQUAL( rules.size(), 2 );
1426 BOOST_CHECK( rules[0]->FindConstraint( CLEARANCE_CONSTRAINT ).has_value() );
1427 BOOST_CHECK( rules[1]->FindConstraint( TRACK_WIDTH_CONSTRAINT ).has_value() );
1428 }
1429}
1430
1431
1432BOOST_AUTO_TEST_CASE( CommentsAboveTheVersionHeaderAreKept )
1433{
1434 const wxString rules = wxT( "# project rules\n"
1435 "(version 2)\n"
1436 "(rule \"a\" (constraint clearance (min 0.2mm)))\n" );
1437
1439 BOOST_REQUIRE( result.m_error.IsEmpty() );
1440 BOOST_CHECK_EQUAL( result.m_text, wxString( "# project rules\n"
1441 "(version 1)\n"
1442 "(rule \"a\" (constraint clearance (min 0.2mm)))\n" ) );
1443 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_comment_above_header" ) ), 1 );
1444}
1445
1446
1447BOOST_AUTO_TEST_CASE( MissingVersionHeaderIsWrittenOnItsOwnLine )
1448{
1449 const wxString rules = wxT( "# intro\n"
1450 "(rule \"a\" (constraint net_chain_length (max 1mm)))\n" );
1451
1453 BOOST_REQUIRE( result.m_error.IsEmpty() );
1454 BOOST_CHECK_EQUAL( result.m_text, wxString( "(version 1)\n"
1455 "# intro\n"
1456 "# Not supported by KiCad 9.0:\n"
1457 "# (rule \"a\" (constraint net_chain_length (max 1mm)))\n" ) );
1458 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_missing_header" ) ), 0 );
1459}
1460
1461
1462BOOST_AUTO_TEST_CASE( HeaderGluedToTheFirstRuleStaysGlued )
1463{
1464 const wxString rules = wxT( "(version 2)(rule \"kept\" (constraint clearance (min 0.2mm)))" );
1465
1467 BOOST_REQUIRE( result.m_error.IsEmpty() );
1468 BOOST_CHECK_EQUAL( result.m_text, wxString( "(version 1)(rule \"kept\" (constraint clearance (min 0.2mm)))\n" ) );
1469 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_glued_header" ) ), 1 );
1470}
1471
1472
1473BOOST_AUTO_TEST_CASE( InlineCommentBetweenRulesFailsClosed )
1474{
1475 const wxString rules = wxT( "(version 1) # note\n(rule \"a\" (constraint clearance (min 0.2mm)))\n" );
1476
1477 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1478 BOOST_CHECK( !FilterDrcRulesForTarget( rules, target ).m_error.IsEmpty() );
1479}
1480
1481
1482BOOST_AUTO_TEST_CASE( UnitInsideAConditionIsChecked )
1483{
1484 const wxString rules = wxT( "(version 1)(rule \"c\" (condition \"A.Width > 5ps\") "
1485 "(constraint clearance (min 0.2mm)))" );
1486
1487 BOOST_CHECK_EQUAL( FilterDrcRulesForTarget( rules, kicad9 ).m_dropped.size(), 1 );
1488 BOOST_CHECK_EQUAL( FilterDrcRulesForTarget( rules, kicad10 ).m_dropped.size(), 0 );
1489}
1490
1491
1492BOOST_AUTO_TEST_CASE( TextVariableInsideACommentIsIgnored )
1493{
1494 const wxString rules = wxT( "(version 1)\n"
1495 "(rule \"a\"\n"
1496 " # see ${GAP}\n"
1497 " (constraint clearance (min 0.2mm)))\n" );
1498
1499 BOOST_CHECK( FilterDrcRulesForTarget( rules, kicad9 ).m_dropped.empty() );
1500}
1501
1502
1503BOOST_AUTO_TEST_CASE( FunctionNamesAreMatchedWithoutCase )
1504{
1505 const wxString rules = wxT( "(version 1)(rule \"f\" (condition \"A.InsideCourtyard('x')\") "
1506 "(constraint clearance (min 0.2mm)))" );
1507
1508 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1509 BOOST_CHECK( FilterDrcRulesForTarget( rules, target ).m_dropped.empty() );
1510}
1511
1512
1513BOOST_AUTO_TEST_CASE( ComponentClassSelectorIsDroppedForEveryTarget )
1514{
1515 const wxString rules = wxT( "(version 1)(rule \"hv\" (condition \"A.memberOfFootprint('${Class:HV}')\") "
1516 "(constraint clearance (min 1mm)))" );
1517
1518 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1519 BOOST_CHECK_EQUAL( FilterDrcRulesForTarget( rules, target ).m_dropped.size(), 1 );
1520}
1521
1522
1523BOOST_AUTO_TEST_CASE( UnquotedExpressionsAreScanned )
1524{
1525 const wxString parent = wxT( "(version 1)(rule \"x\" (condition A.Parent.Reference==B.Reference) "
1526 "(constraint clearance (min 1mm)))" );
1527 const wxString assertion = wxT( "(version 1)(rule \"x\" (constraint assertion A.Parent.Reference==B.Reference))" );
1528 const wxString plain = wxT( "(version 1)(rule \"x\" (condition A.NetClass=='HV') "
1529 "(constraint clearance (min 1mm)))" );
1530
1531 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1532 {
1533 BOOST_CHECK_EQUAL( FilterDrcRulesForTarget( parent, target ).m_dropped.size(), 1 );
1534 BOOST_CHECK_EQUAL( FilterDrcRulesForTarget( assertion, target ).m_dropped.size(), 1 );
1535 BOOST_CHECK( FilterDrcRulesForTarget( plain, target ).m_dropped.empty() );
1536 }
1537}
1538
1539
1540BOOST_AUTO_TEST_CASE( QuotedConstraintItemsAreChecked )
1541{
1542 const wxString newItem = wxT( "(version 1)(rule \"y\" (constraint disallow \"blind_via\"))" );
1543 const wxString oldItem = wxT( "(version 1)(rule \"y\" (constraint disallow \"via\"))" );
1544 const wxString connection = wxT( "(version 1)(rule \"z\" (constraint zone_connection \"thermal_reliefs\"))" );
1545
1546 BOOST_CHECK_EQUAL( FilterDrcRulesForTarget( newItem, kicad9 ).m_dropped.size(), 1 );
1547 BOOST_CHECK( FilterDrcRulesForTarget( newItem, kicad10 ).m_dropped.empty() );
1548
1549 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1550 {
1551 BOOST_CHECK( FilterDrcRulesForTarget( oldItem, target ).m_dropped.empty() );
1552 BOOST_CHECK( FilterDrcRulesForTarget( connection, target ).m_dropped.empty() );
1553 }
1554}
1555
1556
1557BOOST_AUTO_TEST_CASE( StringSpanningLinesFailsClosed )
1558{
1559 const wxString rules = wxT( "(version 1)\n(rule \"a\" (condition \"A.NetClass ==\n 'HV'\") "
1560 "(constraint clearance (min 0.2mm)))\n" );
1561
1562 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1563 BOOST_CHECK( !FilterDrcRulesForTarget( rules, target ).m_error.IsEmpty() );
1564}
1565
1566
1567BOOST_AUTO_TEST_CASE( CommentBetweenParenthesisAndHeadIsKept )
1568{
1569 const wxString rules = wxT( "(version 1)\n"
1570 "(\n"
1571 "# the head comes after this comment\n"
1572 "rule \"a\" (constraint clearance (min 0.2mm)))\n"
1573 "(\n"
1574 "# so does this one\n"
1575 "rule \"b\" (constraint net_chain_length (max 1mm)))\n" );
1576
1578 BOOST_REQUIRE( result.m_error.IsEmpty() );
1579 BOOST_REQUIRE_EQUAL( result.m_dropped.size(), 1 );
1580 BOOST_CHECK_EQUAL( result.m_dropped.front(), wxString( "b" ) );
1581 BOOST_CHECK( result.m_text.Contains( wxT( "\nrule \"a\"" ) ) );
1582 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_comment_before_head" ) ), 1 );
1583}
1584
1585
1586BOOST_AUTO_TEST_CASE( InvalidDrcCommentAndUnbalancedSyntaxFailClosed )
1587{
1588 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1589 {
1590 for( const wxString& input : { wxT( "(version 1)\n(rule \"inline\" # )\n (constraint clearance (min 0.2mm)))" ),
1591 wxT( "(version 1)\n(rule \"missing_close\" (constraint clearance (min 0.2mm))" ),
1592 wxT( "(version 1)\n(rule \"missing_quote" ) } )
1593 {
1594 BOOST_CHECK( !FilterDrcRulesForTarget( input, target ).m_error.IsEmpty() );
1595 }
1596 }
1597}
1598
1599
1600BOOST_AUTO_TEST_CASE( DrcRulesMatchIndependentOlderReferences )
1601{
1602 const std::string fixture = KI_TEST::GetPcbnewTestDataDir() + "../downgrade/golden/";
1603 const wxString input = wxString::FromUTF8( KI_TEST::ReadGoldenText( fixture + "current/rules.kicad_dru" ) );
1604
1605 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
1606 {
1608 BOOST_REQUIRE( result.m_error.IsEmpty() );
1609 const std::string release = target.m_id == wxT( "9.0" ) ? "v9" : "v10";
1610 BOOST_CHECK_EQUAL( result.m_text.ToStdString(),
1611 KI_TEST::ReadGoldenText( fixture + release + "/rules.kicad_dru" ) );
1612 BOOST_CHECK_EQUAL( result.m_dropped.size(), release == "v9" ? 2 : 1 );
1613 BOOST_CHECK_EQUAL( ParsedDrcRuleCount( result.m_text, wxT( "downgrade_drc_golden" ) ),
1614 release == "v9" ? 1 : 2 );
1615 }
1616}
1617
1618
1619// Flattening bakes the chosen variant's overrides into the base attributes, so the exported
1620// board matches that variant after the registry is dropped.
1621BOOST_AUTO_TEST_CASE( VariantFlattenedIntoBoard )
1622{
1623 BOARD board;
1624 FOOTPRINT* fp = new FOOTPRINT( &board );
1625 fp->SetDNP( false );
1626
1627 FOOTPRINT_VARIANT* variant = fp->AddVariant( wxT( "V1" ) );
1628 variant->SetDNP( true );
1629 variant->SetFieldValue( wxT( "Value" ), wxT( "10k" ) );
1630 board.Add( fp );
1631
1632 FlattenBoardVariant( &board, wxT( "V1" ) );
1633
1634 BOOST_CHECK( fp->IsDNP() );
1635 BOOST_REQUIRE( fp->GetField( wxT( "Value" ) ) != nullptr );
1636 BOOST_CHECK( fp->GetField( wxT( "Value" ) )->GetText() == wxT( "10k" ) );
1637}
1638
1639
1640// The project file is migrated down: newer settings are removed, nested schema versions are
1641// rewound, and meaningful losses are reported.
1642BOOST_AUTO_TEST_CASE( ProjectFileDowngradeForKicad9 )
1643{
1644 nlohmann::json doc = {
1645 { "meta", { { "filename", "p.kicad_pro" }, { "version", 3 } } },
1646 { "board", { { "layer_presets", { { { "name", "P" }, { "renderLayers", { "tracks", "vias" } } } } } } },
1647 { "net_settings",
1648 { { "meta", { { "version", 5 } } },
1649 { "classes", { { { "name", "Default" }, { "priority", 0 }, { "tuning_profile", "tp" } } } },
1650 { "net_chain_classes", { { { "name", "chainA" } } } } } },
1651 { "tuning_profiles",
1652 { { "meta", { { "version", 1 } } },
1653 { "tuning_profiles_impedance_geometric",
1654 { { { "name", "tp" }, { "frequency", 1e9 }, { "model_solder_mask", false } } } } } },
1655 { "component_class_settings", { { "meta", { { "version", 0 } } } } },
1656 { "schematic",
1657 { { "top_level_sheets", { "aaaa" } },
1658 { "bus_aliases", nlohmann::json::array() },
1659 { "variants", nlohmann::json::array() } } },
1660 };
1661
1662 COMPATIBILITY_REPORT report;
1663 DowngradeProjectFileJson( doc, kicad9, report );
1664
1665 // 9.0 shipped project schema 3 and reads render layers by name, skipping names it does
1666 // not know. So the version and the preset strings must pass through untouched.
1667 BOOST_CHECK_EQUAL( doc["meta"]["version"].get<int>(), 3 );
1668
1669 const nlohmann::json& preset = doc["board"]["layer_presets"][0];
1670 BOOST_REQUIRE( preset["renderLayers"].is_array() );
1671 BOOST_REQUIRE_EQUAL( preset["renderLayers"].size(), 2 );
1672 BOOST_CHECK_EQUAL( preset["renderLayers"][0].get<std::string>(), "tracks" );
1673 BOOST_CHECK_EQUAL( preset["renderLayers"][1].get<std::string>(), "vias" );
1674
1675 BOOST_CHECK_EQUAL( doc["net_settings"]["meta"]["version"].get<int>(), 4 );
1676 BOOST_CHECK( !doc["net_settings"]["classes"][0].contains( "tuning_profile" ) );
1677 BOOST_CHECK( doc["net_settings"]["classes"][0].contains( "name" ) );
1678 BOOST_CHECK( !doc["net_settings"].contains( "net_chain_classes" ) );
1679 BOOST_CHECK( !doc.contains( "tuning_profiles" ) );
1680 BOOST_CHECK( !doc.contains( "component_class_settings" ) );
1681 BOOST_CHECK( !doc["schematic"].contains( "top_level_sheets" ) );
1682 BOOST_CHECK( !doc["schematic"].contains( "bus_aliases" ) );
1683 BOOST_CHECK( !doc["schematic"].contains( "variants" ) );
1684
1685 // The meaningful losses show in the report. Hygiene removals stay silent.
1686 BOOST_CHECK( report.IsLossy() );
1688}
1689
1690
1691BOOST_AUTO_TEST_CASE( EmptyNativeProjectSectionsDoNotRequireConsent )
1692{
1693 const nlohmann::json empty = nlohmann::json::array();
1694 const std::vector<nlohmann::json> tuningDefaults = {
1695 nullptr,
1696 nlohmann::json::object(),
1697 { { "meta", { { "version", 2 } } } },
1698 { { "meta", { { "version", 2 } } }, { "tuning_profiles_impedance_geometric", empty } },
1699 };
1700 const std::vector<nlohmann::json> componentDefaults = {
1701 nullptr,
1702 nlohmann::json::object(),
1703 { { "meta", { { "version", 0 } } } },
1704 { { "assignments", empty }, { "sheet_component_classes", nlohmann::json::object() } },
1705 { { "meta", { { "version", 0 } } },
1706 { "assignments", empty },
1707 { "sheet_component_classes", { { "enabled", false } } } },
1708 };
1709
1710 for( const auto& target : { kicad9, kicad10 } )
1711 {
1712 for( const auto& tuning : tuningDefaults )
1713 {
1714 for( const auto& components : componentDefaults )
1715 {
1716 nlohmann::json doc = {
1717 { "meta", { { "version", 4 } } },
1718 { "board", { { "design_settings", { { "meta", { { "version", 3 } } } } } } },
1719 { "erc", { { "meta", { { "version", 1 } } }, { "erc_exclusions", empty } } },
1720 { "net_settings",
1721 { { "meta", { { "version", 5 } } },
1722 { "classes", { { { "name", "Default" }, { "tuning_profile", "" } } } } } },
1723 { "tuning_profiles", tuning },
1724 { "component_class_settings", components },
1725 };
1726
1727 COMPATIBILITY_REPORT report;
1728 DowngradeProjectFileJson( doc, target, report );
1729
1730 BOOST_CHECK( !report.IsBlocked() );
1731 BOOST_CHECK( !report.IsLossy() );
1733 BOOST_CHECK_EQUAL( doc["meta"]["version"].get<int>(), 3 );
1734 BOOST_CHECK_EQUAL( doc["board"]["design_settings"]["meta"]["version"].get<int>(), 2 );
1735 BOOST_CHECK_EQUAL( doc["erc"]["meta"]["version"].get<int>(), 0 );
1736 BOOST_CHECK_EQUAL( doc.contains( "tuning_profiles" ), target.m_id == wxT( "10.0" ) );
1737 BOOST_CHECK_EQUAL( doc.contains( "component_class_settings" ), target.m_id == wxT( "10.0" ) );
1738
1739 const nlohmann::json once = doc;
1740 COMPATIBILITY_REPORT repeated;
1741 DowngradeProjectFileJson( doc, target, repeated );
1742 BOOST_CHECK( doc == once );
1743 BOOST_CHECK( !repeated.IsLossy() );
1744 }
1745 }
1746 }
1747}
1748
1749
1750BOOST_AUTO_TEST_CASE( SavedProjectTuningAndClassChoicesStillRequireConsent )
1751{
1752 const nlohmann::json empty = nlohmann::json::array();
1753 const nlohmann::json profile = {
1754 { "profile_name", "Default" },
1755 { "frequency", 1e9 },
1756 { "model_solder_mask", false },
1757 { "net_chain_bridge_prop_delay", 0 },
1758 };
1759 const std::vector<nlohmann::json> meaningful = {
1760 { { "tuning_profiles", { { "tuning_profiles_impedance_geometric", { profile } } } } },
1761 { { "net_settings", { { "classes", { { { "tuning_profile", "Saved" } } } } } } },
1762 { { "tuning_profiles", { { "tuning_profiles_impedance_geometric", empty } } },
1763 { "net_settings", { { "classes", { { { "tuning_profile", "Saved" } } } } } } },
1764 { { "tuning_profiles", { { "tuning_profiles_impedance_geometric", { profile } } } },
1765 { "net_settings",
1766 { { "classes", { { { "tuning_profile", "Default" } }, { { "tuning_profile", "Default" } } } } } } },
1767 { { "component_class_settings",
1768 { { "assignments",
1769 { { { "component_class", "Fast" }, { "conditions_operator", "ALL" }, { "conditions", empty } } } },
1770 { "sheet_component_classes", { { "enabled", false } } } } } },
1771 { { "component_class_settings",
1772 { { "assignments", empty }, { "sheet_component_classes", { { "enabled", true } } } } } },
1773 };
1774
1775 for( const auto& source : meaningful )
1776 {
1777 for( const auto& target : { kicad9, kicad10 } )
1778 {
1779 nlohmann::json doc = source;
1780 COMPATIBILITY_REPORT report;
1781 DowngradeProjectFileJson( doc, target, report );
1782 BOOST_CHECK( !report.IsBlocked() );
1783 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), target.m_id == wxT( "9.0" ) ? 1 : 0 );
1784 BOOST_CHECK_EQUAL( report.IsLossy(), target.m_id == wxT( "9.0" ) );
1785
1786 const nlohmann::json once = doc;
1787 COMPATIBILITY_REPORT repeated;
1788 DowngradeProjectFileJson( doc, target, repeated );
1789 BOOST_CHECK( doc == once );
1790 BOOST_CHECK( !repeated.IsLossy() );
1791 }
1792 }
1793}
1794
1795
1796BOOST_AUTO_TEST_CASE( FutureComponentClassSchemaBlocksWithoutMutation )
1797{
1798 const nlohmann::json source = {
1799 { "meta", { { "version", 4 } } },
1800 { "component_class_settings", { { "meta", { { "version", 1 } } } } },
1801 };
1802
1803 for( const auto& target : { kicad9, kicad10 } )
1804 {
1805 nlohmann::json doc = source;
1806 COMPATIBILITY_REPORT report;
1807 DowngradeProjectFileJson( doc, target, report );
1808 BOOST_CHECK( report.IsBlocked() );
1809 BOOST_CHECK( doc == source );
1810 }
1811}
1812
1813
1814// A structurally odd but valid-JSON project file must not throw. Classification swallows
1815// exceptions, so a throw here would surface only mid-export and break fail-closed.
1816BOOST_AUTO_TEST_CASE( WrongShapeProjectFileDoesNotThrow )
1817{
1818 nlohmann::json metaIsString = {
1819 { "meta", "not an object" },
1820 { "net_settings", { { "meta", "also a string" }, { "classes", "not an array" } } },
1821 { "schematic", "a string" },
1822 };
1823
1824 nlohmann::json profilesWrong = {
1825 { "tuning_profiles",
1826 { { "meta", 7 }, { "tuning_profiles_impedance_geometric", { "just", "strings" } } } },
1827 };
1828
1829 COMPATIBILITY_REPORT report;
1830 BOOST_CHECK_NO_THROW( DowngradeProjectFileJson( metaIsString, kicad9, report ) );
1831 BOOST_CHECK_NO_THROW( DowngradeProjectFileJson( profilesWrong, kicad10, report ) );
1832}
1833
1834
1835// An empty net chain class array is removed as hygiene, not reported as a loss.
1836BOOST_AUTO_TEST_CASE( EmptyNetChainClassesSilent )
1837{
1838 nlohmann::json doc = {
1839 { "net_settings", { { "net_chain_classes", nlohmann::json::array() } } },
1840 };
1841
1842 COMPATIBILITY_REPORT report;
1843 DowngradeProjectFileJson( doc, kicad10, report );
1844
1845 BOOST_CHECK( !doc["net_settings"].contains( "net_chain_classes" ) );
1847}
1848
1849
1850BOOST_AUTO_TEST_CASE( NonDefaultTuningModelSettingsAreReportedForKicad10 )
1851{
1852 nlohmann::json doc = {
1853 { "tuning_profiles",
1854 { { "meta", { { "version", 1 } } },
1855 { "tuning_profiles_impedance_geometric",
1856 { { { "profile_name", "5 GHz" }, { "frequency", 5e9 }, { "model_solder_mask", true } },
1857 { { "profile_name", "Default" }, { "frequency", 1e9 }, { "model_solder_mask", false } } } } } }
1858 };
1859
1860 COMPATIBILITY_REPORT report;
1861 DowngradeProjectFileJson( doc, kicad10, report );
1862 BOOST_CHECK( report.IsLossy() );
1864
1865 for( const auto& profile : doc["tuning_profiles"]["tuning_profiles_impedance_geometric"] )
1866 {
1867 BOOST_CHECK( !profile.contains( "frequency" ) );
1868 BOOST_CHECK( !profile.contains( "model_solder_mask" ) );
1869 }
1870
1871 COMPATIBILITY_REPORT secondReport;
1872 DowngradeProjectFileJson( doc, kicad10, secondReport );
1873 BOOST_CHECK( !secondReport.IsLossy() );
1874}
1875
1876
1877BOOST_AUTO_TEST_CASE( ProjectFileDowngradeForKicad10 )
1878{
1879 nlohmann::json doc = {
1880 { "meta", { { "version", 3 } } },
1881 { "net_settings",
1882 { { "meta", { { "version", 5 } } },
1883 { "classes", { { { "name", "Default" }, { "priority", 0 }, { "tuning_profile", "tp" } } } },
1884 { "net_chain_classes", { { { "name", "chainA" } } } } } },
1885 { "tuning_profiles",
1886 { { "meta", { { "version", 1 } } },
1887 { "tuning_profiles_impedance_geometric",
1888 { { { "name", "tp" }, { "frequency", 1e9 }, { "model_solder_mask", false } } } } } },
1889 };
1890
1891 COMPATIBILITY_REPORT report;
1892 DowngradeProjectFileJson( doc, kicad10, report );
1893
1894 // 10.0 knows tuning profiles and reads the per-class reference unguarded, so both stay.
1895 BOOST_CHECK_EQUAL( doc["meta"]["version"].get<int>(), 3 );
1896 BOOST_CHECK_EQUAL( doc["net_settings"]["meta"]["version"].get<int>(), 5 );
1897 BOOST_CHECK( doc["net_settings"]["classes"][0].contains( "tuning_profile" ) );
1898 BOOST_CHECK( !doc["net_settings"].contains( "net_chain_classes" ) );
1899
1900 BOOST_CHECK_EQUAL( doc["tuning_profiles"]["meta"]["version"].get<int>(), 0 );
1901 BOOST_CHECK( !doc["tuning_profiles"]["tuning_profiles_impedance_geometric"][0].contains( "frequency" ) );
1902 BOOST_CHECK( !doc["tuning_profiles"]["tuning_profiles_impedance_geometric"][0].contains( "model_solder_mask" ) );
1903
1905}
1906
1907
1908// A near-closed thick elliptical arc strokes to a ring. The writers save one outline per
1909// shape, so the lowered polygon must carry no holes.
1910BOOST_AUTO_TEST_CASE( EllipseArcRingHasNoHoles )
1911{
1912 BOARD board;
1913 PCB_SHAPE* arc = new PCB_SHAPE( &board, SHAPE_T::ELLIPSE_ARC );
1914 arc->SetEllipseCenter( VECTOR2I( 0, 0 ) );
1915 arc->SetEllipseMajorRadius( pcbIUScale.mmToIU( 5 ) );
1916 arc->SetEllipseMinorRadius( pcbIUScale.mmToIU( 3 ) );
1919 arc->SetWidth( pcbIUScale.mmToIU( 0.3 ) );
1920 board.Add( arc );
1921
1922 DowngradeBoardInPlace( &board, kicad10 );
1923
1925
1926 SHAPE_POLY_SET& poly = arc->GetPolyShape();
1927
1928 for( int ii = 0; ii < poly.OutlineCount(); ++ii )
1929 BOOST_CHECK_EQUAL( poly.HoleCount( ii ), 0 );
1930
1931 // The ring's ink, nowhere near the filled disk's 47 square mm.
1932 double areaMM = std::abs( poly.Area() ) / ( pcbIUScale.IU_PER_MM * pcbIUScale.IU_PER_MM );
1933
1934 BOOST_CHECK_GT( areaMM, 4.0 );
1935 BOOST_CHECK_LT( areaMM, 15.0 );
1936}
1937
1938
1939// The scale compensation must reach images inside footprints on the board.
1940BOOST_AUTO_TEST_CASE( FootprintImageScaleCompensatedOnBoard )
1941{
1942 BOARD board;
1943 FOOTPRINT* fp = new FOOTPRINT( &board );
1945 REFERENCE_IMAGE& ref = image->GetReferenceImage();
1946
1947 wxMemoryBuffer buf = KI_TEST::MakePngWithFractionalPixelsPerCm();
1948 BOOST_REQUIRE( ref.ReadImageFile( buf ) );
1949 ref.SetImageScale( 2.0 );
1950 fp->Add( image );
1951 board.Add( fp );
1952
1953 int ppi = ref.GetImage().GetPPI();
1954 int legacyPPI = ref.GetImage().GetLegacyPPI();
1955 BOOST_REQUIRE( legacyPPI > 0 && ppi != legacyPPI );
1956
1957 DowngradeBoardInPlace( &board, kicad9 );
1958
1959 BOOST_CHECK_CLOSE( ref.GetImageScale(), 2.0 * legacyPPI / ppi, 0.1 );
1960}
1961
1962
1963// A library footprint goes through the footprint-scoped path and gets the same compensation.
1964BOOST_AUTO_TEST_CASE( FootprintImageScaleCompensatedInLibrary )
1965{
1966 std::unique_ptr<FOOTPRINT> fp = std::make_unique<FOOTPRINT>( nullptr );
1968 REFERENCE_IMAGE& ref = image->GetReferenceImage();
1969
1970 wxMemoryBuffer buf = KI_TEST::MakePngWithFractionalPixelsPerCm();
1971 BOOST_REQUIRE( ref.ReadImageFile( buf ) );
1972 ref.SetImageScale( 2.0 );
1973 fp->Add( image );
1974
1975 int ppi = ref.GetImage().GetPPI();
1976 int legacyPPI = ref.GetImage().GetLegacyPPI();
1977 BOOST_REQUIRE( legacyPPI > 0 && ppi != legacyPPI );
1978
1979 DowngradeFootprintInPlace( fp.get(), kicad9 );
1980
1981 BOOST_CHECK_CLOSE( ref.GetImageScale(), 2.0 * legacyPPI / ppi, 0.1 );
1982}
1983
1984
1985// The duplicate-pad-numbers jumper flag is jumper data too, so 9.0 must drop and report it.
1986BOOST_AUTO_TEST_CASE( DuplicatePadJumperFlagDroppedForKicad9 )
1987{
1988 BOARD board;
1989 FOOTPRINT* fp = new FOOTPRINT( &board );
1991 board.Add( fp );
1992
1994
1995 DowngradeBoardInPlace( &board, kicad9 );
1996
1998}
1999
2000
2001// Downgrading a library file must not clip zone layers to a scratch board's layer set. The
2002// source file is its own oracle: the layer set must survive the round trip unchanged.
2003BOOST_AUTO_TEST_CASE( FootprintFileKeepsZoneLayers )
2004{
2005 SETTINGS_MANAGER settingsManager;
2006
2007 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_fp_zone_layers", "" );
2008 const wxString src = ( tmp.Path() / "src.kicad_mod" ).wstring();
2009 const wxString dest = ( tmp.Path() / "out.kicad_mod" ).wstring();
2010
2011 {
2012 std::unique_ptr<FOOTPRINT> fp = std::make_unique<FOOTPRINT>( nullptr );
2013 ZONE* zone = new ZONE( fp.get() );
2014
2015 zone->SetLayerSet( LSET::AllCuMask() );
2016 zone->Outline()->NewOutline();
2017 zone->Outline()->Append( 0, 0 );
2018 zone->Outline()->Append( pcbIUScale.mmToIU( 1 ), 0 );
2019 zone->Outline()->Append( pcbIUScale.mmToIU( 1 ), pcbIUScale.mmToIU( 1 ) );
2020 zone->Outline()->Append( 0, pcbIUScale.mmToIU( 1 ) );
2021 fp->Add( zone );
2022
2023 SaveFootprintForTarget( fp.get(), src, kicad10 );
2024 }
2025
2027
2028 PCB_IO_KICAD_SEXPR reader;
2029 wxString nameOut;
2030 std::unique_ptr<FOOTPRINT> srcAgain( reader.ImportFootprint( src, nameOut ) );
2031 std::unique_ptr<FOOTPRINT> converted( reader.ImportFootprint( dest, nameOut ) );
2032
2033 BOOST_REQUIRE( srcAgain && converted );
2034 BOOST_REQUIRE_EQUAL( srcAgain->Zones().size(), 1 );
2035 BOOST_REQUIRE_EQUAL( converted->Zones().size(), 1 );
2036
2037 BOOST_CHECK_EQUAL( converted->Zones()[0]->GetLayerSet().count(), srcAgain->Zones()[0]->GetLayerSet().count() );
2038}
2039
2040
2041// The staged library downgrade converts and verifies every file before any original is
2042// replaced, and a refusal leaves the folder untouched with no temp files behind.
2043BOOST_AUTO_TEST_CASE( LibraryFilesDowngradeFailsClosed )
2044{
2045 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_lib_staged", "" );
2046 const wxString dir = tmp.Path().wstring();
2047
2048 auto writeFile = [&]( const wxString& aName, const wxString& aContent )
2049 {
2050 wxFFile file( dir + wxFileName::GetPathSeparator() + aName, wxT( "wb" ) );
2051 BOOST_REQUIRE( file.IsOpened() );
2052 file.Write( aContent );
2053 };
2054
2055 writeFile( wxT( "a.fake_mod" ), wxT( "old a" ) );
2056 writeFile( wxT( "b.fake_mod" ), wxT( "old b" ) );
2057
2058 auto noForbidden = []( const wxString& )
2059 {
2060 return wxString();
2061 };
2062
2063 auto convertOk = [&]( const wxString& aFile, const wxString& aTmp ) -> DOWNGRADE_FILE_RESULT
2064 {
2065 wxFFile out( aTmp, wxT( "wb" ) );
2066 out.Write( wxT( "(version 123) converted" ) );
2068 };
2069
2070 BOOST_CHECK( DowngradeLibraryFilesInPlace( dir, wxT( "*.fake_mod" ), 123, noForbidden, convertOk ).IsEmpty() );
2071
2072 wxFFile check( dir + wxFileName::GetPathSeparator() + wxT( "a.fake_mod" ), wxT( "rb" ) );
2073 wxString content;
2074 BOOST_REQUIRE( check.IsOpened() && check.ReadAll( &content ) );
2075 BOOST_CHECK( content.Contains( wxT( "converted" ) ) );
2076
2077 // Second pass: the second file refuses, so the first must stay as it is now.
2078 auto convertRefuseB = [&]( const wxString& aFile, const wxString& aTmp ) -> DOWNGRADE_FILE_RESULT
2079 {
2080 if( aFile.Contains( wxT( "b.fake_mod" ) ) )
2082
2083 wxFFile out( aTmp, wxT( "wb" ) );
2084 out.Write( wxT( "(version 123) second pass" ) );
2086 };
2087
2088 wxString bad = DowngradeLibraryFilesInPlace( dir, wxT( "*.fake_mod" ), 123, noForbidden, convertRefuseB );
2089 BOOST_CHECK( bad.Contains( wxT( "b.fake_mod" ) ) );
2090
2091 wxArrayString leftovers;
2092 wxDir::GetAllFiles( dir, &leftovers );
2093 BOOST_CHECK_EQUAL( leftovers.size(), 2 );
2094
2095 wxFFile recheck( dir + wxFileName::GetPathSeparator() + wxT( "a.fake_mod" ), wxT( "rb" ) );
2096 wxString unchanged;
2097 BOOST_REQUIRE( recheck.IsOpened() && recheck.ReadAll( &unchanged ) );
2098 BOOST_CHECK( !unchanged.Contains( wxT( "second pass" ) ) );
2099}
2100
2101
2102// The project export carries design files only. UI state and non-KiCad files stay behind.
2103BOOST_AUTO_TEST_CASE( DesignFileFilter )
2104{
2105 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/proj.kicad_pro" ) ) );
2106 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/sub/sheet.kicad_sch" ) ) );
2107 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/proj.kicad_pcb" ) ) );
2108 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/proj.kicad_dru" ) ) );
2109 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/frame.kicad_wks" ) ) );
2110 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/lib.kicad_sym" ) ) );
2111 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/lib.pretty/fp.kicad_mod" ) ) );
2112 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/sym-lib-table" ) ) );
2113 BOOST_CHECK( IsDowngradeDesignFile( wxT( "proj/fp-lib-table" ) ) );
2114
2115 BOOST_CHECK( !IsDowngradeDesignFile( wxT( "proj/proj.kicad_prl" ) ) );
2116 BOOST_CHECK( !IsDowngradeDesignFile( wxT( "proj/datasheet.pdf" ) ) );
2117 BOOST_CHECK( !IsDowngradeDesignFile( wxT( "proj/out/proj-F_Cu.gbr" ) ) );
2118 BOOST_CHECK( !IsDowngradeDesignFile( wxT( "proj/proj.kicad_jobset" ) ) );
2119 BOOST_CHECK( !IsDowngradeDesignFile( wxT( "proj/notes.txt" ) ) );
2120}
2121
2122
2123// When this fails a format bump happened. Review the new keywords, update the denylist, then bump
2124// BoardDowngradeCoveredVersion.
2129
2130
2131// When this fails the footprint library format moved. Review what it added inside (footprint ...),
2132// then bump FootprintLibDowngradeCoveredVersion.
2137
2138
2139// Every graphical LOWER rule has an omission path, both on boards and in footprints.
2140BOOST_AUTO_TEST_CASE( DropApproximationsOmitsGraphicsWithoutReplacements )
2141{
2142 for( bool footprintOnly : { false, true } )
2143 {
2144 BOARD board;
2145 FOOTPRINT* fp = new FOOTPRINT( &board );
2146 board.Add( fp );
2147 BOARD_ITEM_CONTAINER* parent = footprintOnly ? static_cast<BOARD_ITEM_CONTAINER*>( fp ) : &board;
2148 PCB_GROUP* group = new PCB_GROUP( parent );
2149 parent->Add( group );
2150
2152 {
2153 PCB_SHAPE* shape = new PCB_SHAPE( parent, type );
2154 if( type == SHAPE_T::RECTANGLE )
2155 {
2156 shape->SetEnd( VECTOR2I( pcbIUScale.mmToIU( 10 ), pcbIUScale.mmToIU( 6 ) ) );
2157 shape->SetCornerRadius( pcbIUScale.mmToIU( 1 ) );
2158 }
2159 parent->Add( shape );
2160 group->AddItem( shape );
2161 }
2162
2163 PCB_BARCODE* barcode = new PCB_BARCODE( parent );
2164 parent->Add( barcode );
2165 group->AddItem( barcode );
2166 PCB_TEXTBOX* textbox = new PCB_TEXTBOX( parent );
2167 textbox->SetIsKnockout( true );
2168 textbox->SetText( wxT( "Do not retain as plain text" ) );
2169 parent->Add( textbox );
2170 group->AddItem( textbox );
2171
2172 PCB_SHAPE* supported = new PCB_SHAPE( parent, SHAPE_T::CIRCLE );
2173 parent->Add( supported );
2174 group->AddItem( supported );
2175 const KIID supportedUuid = supported->m_Uuid;
2176 const DOWNGRADE_TARGET& target = kicad9;
2177 auto normal = ClassifyBoardForDowngrade( &board, target );
2178 auto omit = ClassifyBoardForDowngrade( &board, target, true );
2180 BOOST_CHECK_EQUAL( omit.Count( DOWNGRADE_BUCKET::LOWER ), 0 );
2181 BOOST_CHECK_EQUAL( omit.Count( DOWNGRADE_BUCKET::DROP ), 5 );
2182 BOOST_REQUIRE_EQUAL( normal.Entries().size(), omit.Entries().size() );
2183 for( size_t i = 0; i < normal.Entries().size(); ++i )
2184 {
2185 BOOST_CHECK( normal.Entries()[i].m_feature == omit.Entries()[i].m_feature );
2186 BOOST_CHECK_EQUAL( normal.Entries()[i].m_count, omit.Entries()[i].m_count );
2187 BOOST_CHECK( normal.Entries()[i].m_detail != omit.Entries()[i].m_detail );
2188 BOOST_CHECK( !omit.Entries()[i].m_detail.IsEmpty() );
2189 }
2190
2191 // Classification is read-only.
2192 BOOST_CHECK_EQUAL( group->GetItems().size(), 6 );
2193 if( footprintOnly )
2194 DowngradeFootprintInPlace( fp, target, true );
2195 else
2196 DowngradeBoardInPlace( &board, target, true );
2197 BOOST_REQUIRE_EQUAL( group->GetItems().size(), 1 );
2198 BOOST_CHECK( *group->GetItems().begin() == supported );
2199 BOOST_CHECK( supported->m_Uuid == supportedUuid );
2200 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, target, true ).IsLossy() );
2201 }
2202}
2203
2204
2205BOOST_AUTO_TEST_CASE( DropApproximationsOmitsFillAndCellContentsOnly )
2206{
2207 BOARD board;
2208 FOOTPRINT* fp = new FOOTPRINT( &board );
2209 board.Add( fp );
2210 for( BOARD_ITEM_CONTAINER* parent :
2211 { static_cast<BOARD_ITEM_CONTAINER*>( &board ), static_cast<BOARD_ITEM_CONTAINER*>( fp ) } )
2212 {
2213 PCB_SHAPE* hatch = new PCB_SHAPE( parent, SHAPE_T::RECTANGLE );
2214 hatch->SetLayer( F_SilkS );
2215 hatch->SetFillMode( FILL_T::HATCH );
2216 parent->Add( hatch );
2217 PCB_TABLE* table = new PCB_TABLE( parent, pcbIUScale.mmToIU( 0.1 ) );
2218 table->SetColCount( 2 );
2219 PCB_TABLECELL* knockout = new PCB_TABLECELL( table );
2220 knockout->SetIsKnockout( true );
2221 knockout->SetText( wxT( "knockout" ) );
2222 table->AddCell( knockout );
2223 PCB_TABLECELL* plain = new PCB_TABLECELL( table );
2224 plain->SetText( wxT( "supported" ) );
2225 table->AddCell( plain );
2226 parent->Add( table );
2227
2228 if( parent == fp )
2229 DowngradeFootprintInPlace( fp, kicad9, true );
2230 else
2231 DowngradeBoardInPlace( &board, kicad9, true );
2234 BOOST_REQUIRE_EQUAL( table->GetCells().size(), 2 );
2235 BOOST_CHECK( knockout->GetText().IsEmpty() );
2236 BOOST_CHECK( !knockout->IsKnockout() );
2237 BOOST_CHECK( plain->GetText() == wxT( "supported" ) );
2238 }
2239}
2240
2241
2242// Removing a hatch fill on a copper layer would delete copper, and the omission preference is
2243// not an electrical override. Copper keeps a solid fill under both policies. Other layers carry
2244// ink, so there the fill may go.
2245// The report must name the copper case separately. One combined row would label the copper
2246// approximation a drop as soon as the omission preference is set, and hide how many of the
2247// counted shapes are copper.
2248BOOST_AUTO_TEST_CASE( HatchedCopperAndInkFillsAreReportedSeparately )
2249{
2250 BOARD board;
2251
2252 for( int ii = 0; ii < 3; ++ii )
2253 {
2254 PCB_SHAPE* ink = new PCB_SHAPE( &board, SHAPE_T::RECTANGLE );
2255 ink->SetLayer( F_SilkS );
2256 ink->SetFillMode( FILL_T::HATCH );
2257 board.Add( ink );
2258 }
2259
2260 PCB_SHAPE* copper = new PCB_SHAPE( &board, SHAPE_T::RECTANGLE );
2261 copper->SetLayer( F_Cu );
2262 copper->SetFillMode( FILL_T::HATCH );
2263 board.Add( copper );
2264
2265 for( bool drop : { false, true } )
2266 {
2267 BOOST_TEST_CONTEXT( "Drop approximations: " << drop )
2268 {
2269 COMPATIBILITY_REPORT report = ClassifyBoardForDowngrade( &board, kicad9, drop );
2270
2271 BOOST_CHECK_EQUAL( report.Entries().size(), 2 );
2272 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::LOWER ), drop ? 1 : 4 );
2273 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), drop ? 3 : 0 );
2274 }
2275 }
2276}
2277
2278
2279BOOST_AUTO_TEST_CASE( DropApproximationsKeepsHatchedCopperAsSolidFill )
2280{
2281 for( bool drop : { false, true } )
2282 {
2283 BOOST_TEST_CONTEXT( "Drop approximations: " << drop )
2284 {
2285 BOARD board;
2286 FOOTPRINT* fp = new FOOTPRINT( &board );
2287 board.Add( fp );
2288
2289 std::vector<PCB_SHAPE*> copper;
2290 std::vector<PCB_SHAPE*> silk;
2291
2292 for( BOARD_ITEM_CONTAINER* parent : { static_cast<BOARD_ITEM_CONTAINER*>( &board ),
2293 static_cast<BOARD_ITEM_CONTAINER*>( fp ) } )
2294 {
2295 PCB_SHAPE* onCopper = new PCB_SHAPE( parent, SHAPE_T::RECTANGLE );
2296 onCopper->SetLayer( F_Cu );
2297 onCopper->SetFillMode( FILL_T::HATCH );
2298 parent->Add( onCopper );
2299 copper.push_back( onCopper );
2300
2301 PCB_SHAPE* onSilk = new PCB_SHAPE( parent, SHAPE_T::RECTANGLE );
2302 onSilk->SetLayer( F_SilkS );
2303 onSilk->SetFillMode( FILL_T::HATCH );
2304 parent->Add( onSilk );
2305 silk.push_back( onSilk );
2306 }
2307
2308 DowngradeBoardInPlace( &board, kicad9, drop );
2309
2310 for( PCB_SHAPE* shape : copper )
2311 BOOST_CHECK( shape->GetFillMode() == FILL_T::FILLED_SHAPE );
2312
2313 for( PCB_SHAPE* shape : silk )
2314 BOOST_CHECK( shape->GetFillMode() == ( drop ? FILL_T::NO_FILL : FILL_T::FILLED_SHAPE ) );
2315 }
2316 }
2317}
2318
2319
2320BOOST_AUTO_TEST_CASE( DropApproximationsOmitsRoundedPadPrimitives )
2321{
2322 for( bool footprintOnly : { false, true } )
2323 {
2324 BOARD board;
2325 FOOTPRINT* fp = new FOOTPRINT( &board );
2326 board.Add( fp );
2327 PAD* pad = new PAD( fp );
2328 fp->Add( pad );
2329 pad->SetShape( F_Cu, PAD_SHAPE::CUSTOM );
2330 PCB_SHAPE* rounded = new PCB_SHAPE( fp, SHAPE_T::RECTANGLE );
2331 rounded->SetEnd( VECTOR2I( pcbIUScale.mmToIU( 10 ), pcbIUScale.mmToIU( 6 ) ) );
2332 rounded->SetCornerRadius( pcbIUScale.mmToIU( 1 ) );
2333 pad->AddPrimitive( F_Cu, rounded );
2334 PCB_SHAPE* supported = new PCB_SHAPE( fp, SHAPE_T::CIRCLE );
2335 pad->AddPrimitive( F_Cu, supported );
2336 const DOWNGRADE_TARGET& target = kicad9;
2337 BOOST_CHECK_EQUAL( ClassifyBoardForDowngrade( &board, target, true ).Count( DOWNGRADE_BUCKET::DROP ), 1 );
2338 if( footprintOnly )
2339 DowngradeFootprintInPlace( fp, target, true );
2340 else
2341 DowngradeBoardInPlace( &board, target, true );
2342 BOOST_REQUIRE_EQUAL( pad->GetPrimitives( F_Cu ).size(), 1 );
2343 BOOST_CHECK( pad->GetPrimitives( F_Cu ).front()->GetShape() == SHAPE_T::CIRCLE );
2344 BOOST_CHECK_EQUAL( fp->Pads().size(), 1 );
2345 }
2346}
2347
2348
2349// Removing a via deletes copper and splits a net, so the omission preference does not reach it.
2350BOOST_AUTO_TEST_CASE( ViaApproximationsSurviveDropPolicy )
2351{
2352 for( bool drop : { false, true } )
2353 {
2354 BOOST_TEST_CONTEXT( "Drop approximations: " << drop )
2355 {
2356 BOARD board;
2357 PCB_VIA* skip = new PCB_VIA( &board );
2359 board.Add( skip );
2360 PCB_VIA* buried = new PCB_VIA( &board );
2361 buried->SetViaType( VIATYPE::BURIED );
2362 board.Add( buried );
2363 PCB_VIA* supported = new PCB_VIA( &board );
2364 board.Add( supported );
2365
2366 const auto report = ClassifyBoardForDowngrade( &board, kicad9, drop );
2367
2368 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::LOWER ), 2 );
2369 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), 0 );
2370
2371 DowngradeBoardInPlace( &board, kicad9, drop );
2372
2373 BOOST_REQUIRE_EQUAL( board.Tracks().size(), 3 );
2376 BOOST_CHECK( buried->GetViaType() == VIATYPE::BLIND );
2377 BOOST_CHECK( supported->GetViaType() == VIATYPE::THROUGH );
2378 }
2379 }
2380}
2381
2382
2383BOOST_AUTO_TEST_CASE( DropApproximationsKeepsTargetSupportedFeatures )
2384{
2385 BOARD board;
2386 PCB_SHAPE* rect = new PCB_SHAPE( &board, SHAPE_T::RECTANGLE );
2387 rect->SetEnd( VECTOR2I( pcbIUScale.mmToIU( 10 ), pcbIUScale.mmToIU( 6 ) ) );
2388 rect->SetCornerRadius( pcbIUScale.mmToIU( 1 ) );
2389 rect->SetFillMode( FILL_T::HATCH );
2390 board.Add( rect );
2391 PCB_TEXTBOX* textbox = new PCB_TEXTBOX( &board );
2392 textbox->SetIsKnockout( true );
2393 board.Add( textbox );
2394 board.Add( new PCB_BARCODE( &board ) );
2395 PCB_VIA* buried = new PCB_VIA( &board );
2396 buried->SetViaType( VIATYPE::BURIED );
2397 board.Add( buried );
2398 PCB_VIA* skip = new PCB_VIA( &board );
2400 board.Add( skip );
2401 const auto& target = kicad10;
2402 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, target, true ).IsLossy() );
2403 DowngradeBoardInPlace( &board, target, true );
2404 BOOST_CHECK_EQUAL( board.Drawings().size(), 3 );
2405 BOOST_CHECK_EQUAL( board.Tracks().size(), 2 );
2406 BOOST_CHECK_EQUAL( rect->GetCornerRadius(), pcbIUScale.mmToIU( 1 ) );
2407 BOOST_CHECK( rect->GetFillMode() == FILL_T::HATCH );
2408 BOOST_CHECK( textbox->IsKnockout() );
2409 BOOST_CHECK( buried->GetViaType() == VIATYPE::BURIED );
2411}
2412
2413
2414BOOST_AUTO_TEST_CASE( DropApproximationsCannotBypassBlockRules )
2415{
2416 BOARD board;
2417 ZONE* zone = new ZONE( &board );
2419 board.Add( zone );
2420 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, true ).IsBlocked() );
2421}
2422
2423
2424BOOST_AUTO_TEST_CASE( LibraryReplacementsWaitForTheDesignTransaction )
2425{
2426 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_shared_downgrade_transaction" );
2427 const wxString directory = temporary.Path().wstring();
2428 const wxString library = directory + wxT( "/library.fake_mod" );
2429 const wxString board = directory + wxT( "/board.kicad_pcb" );
2430
2431 auto write = []( const wxString& aPath, const wxString& aContent )
2432 {
2433 wxFFile file( aPath, wxT( "wb" ) );
2434 BOOST_REQUIRE( file.IsOpened() && file.Write( aContent ) && file.Close() );
2435 };
2436
2437 auto read = []( const wxString& aPath )
2438 {
2439 wxFFile file( aPath, wxT( "rb" ) );
2440 wxString content;
2441 BOOST_REQUIRE( file.IsOpened() && file.ReadAll( &content ) );
2442 return content;
2443 };
2444
2445 auto noForbidden = []( const wxString& )
2446 {
2447 return wxString();
2448 };
2449 auto convert = [&]( const wxString&, const wxString& aTemporary )
2450 {
2451 write( aTemporary, wxT( "(version 123) converted" ) );
2453 };
2454
2455 write( library, wxT( "original library" ) );
2456 write( board, wxT( "original board" ) );
2457
2458 {
2459 DOWNGRADE_FILE_TRANSACTION transaction;
2461 DowngradeLibraryFilesInPlace( directory, wxT( "*.fake_mod" ), 123, noForbidden, convert, &transaction )
2462 .IsEmpty() );
2463 BOOST_CHECK_EQUAL( read( library ), wxString( wxT( "original library" ) ) );
2464 BOOST_CHECK( transaction.Stage( directory + wxT( "/missing/board.kicad_pcb" ) ).IsEmpty() );
2465 }
2466
2467 BOOST_CHECK_EQUAL( read( library ), wxString( wxT( "original library" ) ) );
2468 BOOST_CHECK_EQUAL( read( board ), wxString( wxT( "original board" ) ) );
2469
2470 {
2471 DOWNGRADE_FILE_TRANSACTION transaction;
2473 DowngradeLibraryFilesInPlace( directory, wxT( "*.fake_mod" ), 123, noForbidden, convert, &transaction )
2474 .IsEmpty() );
2475 wxString stagedBoard = transaction.Stage( board );
2476 BOOST_REQUIRE( !stagedBoard.IsEmpty() );
2477 write( stagedBoard, wxT( "converted board" ) );
2478 BOOST_REQUIRE( transaction.Commit().IsEmpty() );
2479 }
2480
2481 BOOST_CHECK_EQUAL( read( library ), wxString( wxT( "(version 123) converted" ) ) );
2482 BOOST_CHECK_EQUAL( read( board ), wxString( wxT( "converted board" ) ) );
2483 wxArrayString files;
2484 wxDir::GetAllFiles( directory, &files );
2485 BOOST_CHECK_EQUAL( files.size(), 2 );
2486}
2487
2488
2489BOOST_AUTO_TEST_CASE( DirectoryDestinationStopsAllTransactionReplacements )
2490{
2491 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_downgrade_transaction_directory" );
2492 const wxString directory = temporary.Path().wstring();
2493 const wxString first = directory + wxT( "/first.kicad_pcb" );
2494 const wxString second = directory + wxT( "/second.kicad_pcb" );
2495
2496 {
2497 wxFFile file( first, wxT( "wb" ) );
2498 BOOST_REQUIRE( file.IsOpened() && file.Write( wxT( "original" ) ) && file.Close() );
2499 }
2500
2501 {
2502 DOWNGRADE_FILE_TRANSACTION transaction;
2503 wxString stagedFirst = transaction.Stage( first );
2504 wxString stagedSecond = transaction.Stage( second );
2505 BOOST_REQUIRE( !stagedFirst.IsEmpty() && !stagedSecond.IsEmpty() );
2506
2507 for( const wxString& file : { stagedFirst, stagedSecond } )
2508 {
2509 wxFFile output( file, wxT( "wb" ) );
2510 BOOST_REQUIRE( output.IsOpened() && output.Write( wxT( "converted" ) ) && output.Close() );
2511 }
2512
2513 BOOST_REQUIRE( wxMkdir( second ) );
2514 BOOST_CHECK( wxFileName( transaction.Commit() ).SameAs( wxFileName( second ) ) );
2515 BOOST_CHECK( transaction.GetRecoveryError().IsEmpty() );
2516 }
2517
2518 wxFFile input( first, wxT( "rb" ) );
2519 wxString content;
2520 BOOST_REQUIRE( input.IsOpened() && input.ReadAll( &content ) );
2521 BOOST_CHECK_EQUAL( content, wxString( wxT( "original" ) ) );
2522 BOOST_CHECK( wxDirExists( second ) );
2523 wxArrayString files;
2524 wxDir::GetAllFiles( directory, &files );
2525 BOOST_CHECK_EQUAL( files.size(), 1 );
2526}
2527
2528
2529BOOST_AUTO_TEST_CASE( ConcurrentTransactionsUseDifferentOwnedStagingFiles )
2530{
2531 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_downgrade_transaction_unique" );
2532 const wxString destination = temporary.Path().wstring() + wxT( "/board.kicad_pcb" );
2533
2534 {
2537 wxString firstTemporary = first.Stage( destination );
2538 wxString secondTemporary = second.Stage( destination );
2539 BOOST_REQUIRE( !firstTemporary.IsEmpty() && !secondTemporary.IsEmpty() );
2540 BOOST_CHECK( firstTemporary != secondTemporary );
2541 BOOST_CHECK( wxFileExists( firstTemporary ) );
2542 BOOST_CHECK( wxFileExists( secondTemporary ) );
2543 first.Discard( firstTemporary );
2544 BOOST_CHECK( !wxFileExists( firstTemporary ) );
2545 BOOST_CHECK( wxFileExists( secondTemporary ) );
2546 BOOST_CHECK( !wxFileExists( destination ) );
2547 }
2548
2549 BOOST_CHECK( std::filesystem::is_empty( temporary.Path() ) );
2550}
2551
2552
2553BOOST_AUTO_TEST_CASE( TransactionSymlinkReplacementLeavesLinkedSourcesUnchanged )
2554{
2555 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_downgrade_transaction_symlink" );
2556 const auto original = temporary.Path() / u8"original-μ.kicad_mod";
2557 const auto alias = temporary.Path() / "alias.kicad_mod";
2558 const auto danglingAlias = temporary.Path() / "dangling.kicad_mod";
2559
2560 {
2561 wxFFile file( original.wstring(), wxT( "wb" ) );
2562 BOOST_REQUIRE( file.IsOpened() && file.Write( wxT( "original source" ) ) && file.Close() );
2563 }
2564
2565 std::error_code error;
2566 std::filesystem::create_symlink( original.filename(), alias, error );
2567
2568 if( error )
2569 {
2570 BOOST_TEST_MESSAGE( "Symlink creation is unavailable on this system" );
2571 return;
2572 }
2573
2574 std::filesystem::create_symlink( "missing.kicad_mod", danglingAlias, error );
2575 BOOST_REQUIRE( !error );
2576
2577 {
2578 DOWNGRADE_FILE_TRANSACTION transaction;
2579
2580 for( const auto& destination : { alias, danglingAlias } )
2581 {
2582 wxString staged = transaction.Stage( destination.wstring() );
2583 BOOST_REQUIRE( !staged.IsEmpty() );
2584 wxFFile file( staged, wxT( "wb" ) );
2585 BOOST_REQUIRE( file.IsOpened() && file.Write( wxT( "converted output" ) ) && file.Close() );
2586 }
2587
2588 BOOST_REQUIRE( transaction.Commit().IsEmpty() );
2589 }
2590
2591 wxFFile file( original.wstring(), wxT( "rb" ) );
2592 wxString content;
2593 BOOST_REQUIRE( file.IsOpened() && file.ReadAll( &content ) );
2594 BOOST_CHECK_EQUAL( content, wxString( wxT( "original source" ) ) );
2595 BOOST_CHECK( !std::filesystem::is_symlink( alias ) );
2596 BOOST_CHECK( !std::filesystem::is_symlink( danglingAlias ) );
2597 BOOST_CHECK_EQUAL( std::distance( std::filesystem::directory_iterator( temporary.Path() ),
2598 std::filesystem::directory_iterator() ),
2599 3 );
2600}
2601
2602
2603static void checkFeature( const COMPATIBILITY_REPORT& aReport, const wxString& aName, DOWNGRADE_BUCKET aBucket,
2604 int aCount )
2605{
2606 for( const COMPAT_ENTRY& entry : aReport.Entries() )
2607 {
2608 if( entry.m_feature == aName )
2609 {
2610 BOOST_CHECK( entry.m_bucket == aBucket );
2611 BOOST_CHECK_EQUAL( entry.m_count, aCount );
2612 BOOST_CHECK( !entry.m_detail.IsEmpty() );
2613 return;
2614 }
2615 }
2616
2617 BOOST_ERROR( "Missing compatibility feature: " + aName.ToStdString() );
2618}
2619
2620
2621BOOST_AUTO_TEST_CASE( GeometricConstraintsDropWithoutMovingBoardOrFootprintGeometry )
2622{
2623 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
2624 {
2625 for( bool drop : { false, true } )
2626 {
2627 BOARD board;
2628 FOOTPRINT* fp = new FOOTPRINT( &board );
2629 board.Add( fp );
2630
2631 std::vector<PCB_SHAPE*> shapes;
2632
2633 for( BOARD_ITEM_CONTAINER* parent :
2634 { static_cast<BOARD_ITEM_CONTAINER*>( &board ), static_cast<BOARD_ITEM_CONTAINER*>( fp ) } )
2635 {
2636 PCB_SHAPE* shape = new PCB_SHAPE( parent, SHAPE_T::SEGMENT );
2637 shape->SetStart( VECTOR2I( 1000000, 2000000 ) );
2638 shape->SetEnd( VECTOR2I( 7000000, 2000000 ) );
2639 parent->Add( shape );
2640 shapes.push_back( shape );
2642 constraint->AddMember( shape->m_Uuid );
2643 parent->Add( constraint );
2644 }
2645
2646 const auto report = ClassifyBoardForDowngrade( &board, target, drop );
2647 BOOST_CHECK( !report.IsBlocked() );
2648 checkFeature( report, wxT( "Geometric constraints" ), DOWNGRADE_BUCKET::DROP, 2 );
2649 BOOST_CHECK_EQUAL( board.Constraints().size(), 1 );
2650 BOOST_CHECK_EQUAL( fp->Constraints().size(), 1 );
2651 DowngradeBoardInPlace( &board, target, drop );
2652 BOOST_CHECK( board.Constraints().empty() );
2653 BOOST_CHECK( fp->Constraints().empty() );
2654
2655 for( PCB_SHAPE* shape : shapes )
2656 {
2657 BOOST_CHECK( shape->GetStart() == VECTOR2I( 1000000, 2000000 ) );
2658 BOOST_CHECK( shape->GetEnd() == VECTOR2I( 7000000, 2000000 ) );
2659 }
2660 }
2661 }
2662}
2663
2664
2665BOOST_AUTO_TEST_CASE( GridAndDrillDrawingLossesAreReportedBeforeRemoval )
2666{
2667 for( bool drop : { false, true } )
2668 {
2669 BOARD board;
2670 board.Add( new PCB_GRID_ITEM( &board ) );
2671 board.Add( new PCB_DRILL_CHART( &board ) );
2672 board.Add( new PCB_DRILL_MAP( &board ) );
2673 board.GetDesignSettings().GetDrillSymbolProfile().SetName( wxT( "Fabrication symbols" ) );
2674 PCB_VIA* via = new PCB_VIA( &board );
2675 via->SetPosition( VECTOR2I( 1000000, 2000000 ) );
2676 board.Add( via );
2677
2678 const auto report = ClassifyBoardForDowngrade( &board, kicad10, drop );
2679 checkFeature( report, wxT( "Local grids" ), DOWNGRADE_BUCKET::DROP, 1 );
2680 checkFeature( report, wxT( "Drill charts and maps" ), DOWNGRADE_BUCKET::DROP, 2 );
2681 checkFeature( report, wxT( "Drill symbol configuration" ), DOWNGRADE_BUCKET::DROP, 1 );
2682 BOOST_CHECK_EQUAL( board.Drawings().size(), 3 );
2683 DowngradeBoardInPlace( &board, kicad10, drop );
2684 BOOST_CHECK( board.Drawings().empty() );
2685 BOOST_REQUIRE_EQUAL( board.Tracks().size(), 1 );
2686 BOOST_CHECK( via->GetPosition() == VECTOR2I( 1000000, 2000000 ) );
2688 }
2689}
2690
2691
2692BOOST_AUTO_TEST_CASE( StackupTableLowersToAStaticTable )
2693{
2694 for( bool drop : { false, true } )
2695 {
2696 BOARD board;
2697 board.SetCopperLayerCount( 4 );
2698
2699 PCB_STACKUP_TABLE* live = new PCB_STACKUP_TABLE( &board );
2700
2701 // The loader rejects a stackup table anywhere else
2702 live->SetLayer( Dwgs_User );
2703 live->RebuildCells( board );
2704 board.Add( live );
2705
2706 PCB_GROUP* group = new PCB_GROUP( &board );
2707 board.Add( group );
2708 group->AddItem( live );
2709
2710 const auto report = ClassifyBoardForDowngrade( &board, kicad10, drop );
2711 BOOST_CHECK( !report.IsBlocked() );
2712 checkFeature( report, wxT( "Live stackup tables" ), drop ? DOWNGRADE_BUCKET::DROP : DOWNGRADE_BUCKET::LOWER,
2713 1 );
2714
2715 DowngradeBoardInPlace( &board, kicad10, drop );
2716
2717 if( drop )
2718 {
2719 BOOST_CHECK( board.Drawings().empty() );
2720 continue;
2721 }
2722
2723 BOOST_REQUIRE_EQUAL( board.Drawings().size(), 1 );
2724
2725 BOARD_ITEM* item = *board.Drawings().begin();
2726 BOOST_REQUIRE( item->Type() == PCB_TABLE_T );
2727
2728 BOOST_CHECK( item->GetParentGroup() == group );
2729 }
2730}
2731
2732
2733// The frozen writers have no case for a generated table, so the file itself has to carry a plain one.
2734BOOST_AUTO_TEST_CASE( ExportedStackupTableIsAPlainTable )
2735{
2736 SETTINGS_MANAGER settingsManager;
2737
2738 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_downgrade_stackup", "" );
2739 const std::string src = ( tmp.Path() / "stackup.kicad_pcb" ).string();
2740
2741 wxString heading;
2742
2743 {
2744 BOARD board;
2745 board.SetCopperLayerCount( 4 );
2746
2747 PCB_STACKUP_TABLE* live = new PCB_STACKUP_TABLE( &board );
2748
2749 // The loader rejects a stackup table anywhere else
2750 live->SetLayer( Dwgs_User );
2751 live->RebuildCells( board );
2752 board.Add( live );
2753
2754 BOOST_REQUIRE( live->GetRowCount() > 1 );
2755 BOOST_REQUIRE( live->GetCell( 0, 0 ) );
2756 heading = live->GetCell( 0, 0 )->GetText();
2757 BOOST_REQUIRE( !heading.IsEmpty() );
2758
2759 KI_TEST::DumpBoardToFile( board, src );
2760 }
2761
2762 // The source really is a live table, or the export below proves nothing
2763 {
2764 std::ifstream file( src );
2765 std::string content( ( std::istreambuf_iterator<char>( file ) ), std::istreambuf_iterator<char>() );
2766 BOOST_REQUIRE( content.find( "(stackup_table" ) != std::string::npos );
2767 }
2768
2769 for( const DOWNGRADE_TARGET& target : { kicad10, kicad9 } )
2770 {
2771 BOOST_TEST_CONTEXT( "Target " << target.m_id )
2772 {
2773 const std::string dest = ( tmp.Path() / ( "out-" + target.m_id.ToStdString() + ".kicad_pcb" ) ).string();
2774
2775 COMPATIBILITY_REPORT report;
2776 BOOST_REQUIRE( ExportBoardToOlderVersion( src, dest, target, report ) );
2777
2778 std::ifstream file( dest );
2779 std::string content( ( std::istreambuf_iterator<char>( file ) ), std::istreambuf_iterator<char>() );
2780
2781 BOOST_CHECK( content.find( "(stackup_table" ) == std::string::npos );
2782 BOOST_CHECK( content.find( "(table" ) != std::string::npos );
2783
2785 std::unique_ptr<BOARD> exported( io.LoadBoard( dest, nullptr ) );
2786 BOOST_REQUIRE( exported );
2787 BOOST_REQUIRE_EQUAL( exported->Drawings().size(), 1 );
2788
2789 BOARD_ITEM* item = *exported->Drawings().begin();
2790 BOOST_REQUIRE( item->Type() == PCB_TABLE_T );
2791
2792 PCB_TABLE* flat = static_cast<PCB_TABLE*>( item );
2793 BOOST_REQUIRE( flat->GetCell( 0, 0 ) );
2794 BOOST_CHECK( flat->GetCell( 0, 0 )->GetText() == heading );
2795 }
2796 }
2797}
2798
2799
2800BOOST_AUTO_TEST_CASE( NewGeneratorsLoseEditabilityAndKeepCopperAndOuterGroups )
2801{
2802 for( bool drop : { false, true } )
2803 {
2804 BOARD board;
2805 PCB_GROUP* outer = new PCB_GROUP( &board );
2806 board.Add( outer );
2807 PCB_VIA_STITCH* stitch = new PCB_VIA_STITCH( &board );
2808 PCB_VIA_STACK* stack = new PCB_VIA_STACK( &board );
2809 board.Add( stitch );
2810 board.Add( stack );
2811 outer->AddItem( stitch );
2812 outer->AddItem( stack );
2813 std::vector<PCB_VIA*> vias;
2814
2815 for( PCB_GENERATOR* generator :
2816 { static_cast<PCB_GENERATOR*>( stitch ), static_cast<PCB_GENERATOR*>( stack ) } )
2817 {
2818 PCB_VIA* via = new PCB_VIA( &board );
2819 via->SetPosition( VECTOR2I( 1000000 * ( vias.size() + 1 ), 2000000 ) );
2820 via->SetWidth( F_Cu, 600000 );
2821 via->SetDrill( 300000 );
2822 board.Add( via );
2823 generator->AddItem( via );
2824 vias.push_back( via );
2825 }
2826
2827 const auto report = ClassifyBoardForDowngrade( &board, kicad10, drop );
2828 checkFeature( report, wxT( "Via stitching and guarding" ), DOWNGRADE_BUCKET::DROP, 1 );
2829 checkFeature( report, wxT( "Microvia stack generators" ), DOWNGRADE_BUCKET::DROP, 1 );
2830 DowngradeBoardInPlace( &board, kicad10, drop );
2831 BOOST_CHECK( board.Generators().empty() );
2832 BOOST_REQUIRE_EQUAL( board.Tracks().size(), 2 );
2833 BOOST_REQUIRE_EQUAL( outer->GetItems().size(), 2 );
2834
2835 for( size_t ii = 0; ii < vias.size(); ++ii )
2836 {
2837 BOOST_CHECK( vias[ii]->GetPosition() == VECTOR2I( 1000000 * ( ii + 1 ), 2000000 ) );
2838 BOOST_CHECK_EQUAL( vias[ii]->GetWidth( F_Cu ), 600000 );
2839 BOOST_CHECK_EQUAL( vias[ii]->GetDrill(), 300000 );
2840 BOOST_CHECK( vias[ii]->GetParentGroup() == outer );
2841 }
2842 }
2843}
2844
2845
2846BOOST_AUTO_TEST_CASE( NativeViaGeneratorFixtureExportsCopperAndOwnershipForBothTargetsAndPolicies )
2847{
2848 SETTINGS_MANAGER settingsManager;
2849 const std::string src =
2850 KI_TEST::GetPcbnewTestDataDir() + "../downgrade/regressions/via_generators/via_generators.kicad_pcb";
2851 const std::string originalBytes = KI_TEST::ReadGoldenText( src );
2853 std::unique_ptr<BOARD> source( io.LoadBoard( src, nullptr ) );
2855 BOOST_REQUIRE_EQUAL( source->GetCopperLayerCount(), 6 );
2856 BOOST_REQUIRE_EQUAL( source->Zones().size(), 3u );
2857 BOOST_REQUIRE_EQUAL( source->Generators().size(), 3u );
2858 BOOST_REQUIRE_EQUAL( source->Groups().size(), 1u );
2859 BOOST_REQUIRE( source->GroupsSanityCheck().IsEmpty() );
2860
2861 const auto copperById = []( const BOARD& aBoard )
2862 {
2863 std::map<KIID, const PCB_TRACK*> items;
2864
2865 for( const PCB_TRACK* item : aBoard.Tracks() )
2866 BOOST_REQUIRE( items.emplace( item->m_Uuid, item ).second );
2867
2868 return items;
2869 };
2870 const auto memberIds = []( const PCB_GROUP& aGroup )
2871 {
2872 std::set<KIID> ids;
2873
2874 for( const EDA_ITEM* member : aGroup.GetItems() )
2875 BOOST_REQUIRE( ids.insert( member->m_Uuid ).second );
2876
2877 return ids;
2878 };
2879 const auto serializeNative = []( BOARD* aBoard )
2880 {
2881 STRING_FORMATTER formatter;
2882 PCB_IO_KICAD_SEXPR serializer;
2883 serializer.FormatBoardToFormatter( &formatter, aBoard );
2884 return formatter.GetString();
2885 };
2886
2887 const auto sourceCopper = copperById( *source );
2888 BOOST_REQUIRE_EQUAL( sourceCopper.size(), 83u );
2889 std::set<KIID> plainVias;
2890 std::set<KIID> generatedVias;
2891 size_t sourceVias = 0;
2892 size_t sourceSegments = 0;
2893 size_t sourceMicrovias = 0;
2894
2895 for( const auto& [id, item] : sourceCopper )
2896 {
2897 if( const PCB_VIA* via = dynamic_cast<const PCB_VIA*>( item ) )
2898 {
2899 ++sourceVias;
2900
2901 if( via->GetViaType() == VIATYPE::MICROVIA )
2902 {
2903 ++sourceMicrovias;
2904 BOOST_REQUIRE( via->Padstack().Drill().is_filled.value_or( false ) );
2905 }
2906
2907 if( !via->GetParentGroup() )
2908 plainVias.insert( id );
2909 }
2910 else
2911 {
2912 BOOST_REQUIRE( item->Type() == PCB_TRACE_T );
2913 ++sourceSegments;
2914 }
2915 }
2916
2917 BOOST_REQUIRE_EQUAL( sourceVias, 80u );
2918 BOOST_REQUIRE_EQUAL( sourceSegments, 3u );
2919 BOOST_REQUIRE_EQUAL( sourceMicrovias, 2u );
2920 BOOST_REQUIRE_EQUAL( plainVias.size(), 3u );
2921
2922 PCB_VIA_STITCH* stitch = nullptr;
2923 PCB_VIA_STITCH* guard = nullptr;
2924 PCB_VIA_STACK* stack = nullptr;
2925
2926 for( PCB_GENERATOR* generator : source->Generators() )
2927 {
2928 if( PCB_VIA_STITCH* viaStitch = dynamic_cast<PCB_VIA_STITCH*>( generator ) )
2929 {
2930 BOOST_REQUIRE( source->FindNet( viaStitch->GetNetCode() ) );
2931 BOOST_REQUIRE( source->FindNet( viaStitch->GetNetCode() )->GetNetname() == wxT( "GND" ) );
2932
2933 if( viaStitch->GetMode() == PCB_VIA_STITCH_MODE::STITCH )
2934 {
2935 BOOST_REQUIRE( !stitch );
2936 stitch = viaStitch;
2937 }
2938 else
2939 {
2940 BOOST_REQUIRE( viaStitch->GetMode() == PCB_VIA_STITCH_MODE::GUARD );
2941 BOOST_REQUIRE( !guard );
2942 guard = viaStitch;
2943 BOOST_REQUIRE( source->FindNet( guard->GetGuardedNetCode() ) );
2944 BOOST_REQUIRE( source->FindNet( guard->GetGuardedNetCode() )->GetNetname() == wxT( "SIGNAL" ) );
2945 }
2946 }
2947 else
2948 {
2949 BOOST_REQUIRE( !stack );
2950 stack = dynamic_cast<PCB_VIA_STACK*>( generator );
2951 BOOST_REQUIRE( stack );
2953 BOOST_REQUIRE( stack->GetStartLayer() == F_Cu );
2954 BOOST_REQUIRE( stack->GetEndLayer() == In2_Cu );
2955 }
2956
2957 for( BOARD_ITEM* member : generator->GetBoardItems() )
2958 {
2959 BOOST_REQUIRE( member->Type() == PCB_VIA_T );
2960 BOOST_REQUIRE( member->GetParentGroup() == static_cast<EDA_GROUP*>( generator ) );
2961 BOOST_REQUIRE( sourceCopper.count( member->m_Uuid ) == 1u );
2962 BOOST_REQUIRE( generatedVias.insert( member->m_Uuid ).second );
2963 }
2964 }
2965
2966 BOOST_REQUIRE( stitch && guard && stack );
2967 BOOST_REQUIRE_EQUAL( stitch->GetItems().size(), 49u );
2968 BOOST_REQUIRE_EQUAL( guard->GetItems().size(), 26u );
2969 BOOST_REQUIRE_EQUAL( stack->GetItems().size(), 2u );
2970 BOOST_REQUIRE_EQUAL( generatedVias.size(), 77u );
2971 const auto stitchMembers = memberIds( *stitch );
2972 PCB_GROUP* outer = *source->Groups().begin();
2973 const KIID outerId = outer->m_Uuid;
2974 const wxString outerName = outer->GetName();
2975 BOOST_REQUIRE( stitch->GetParentGroup() == static_cast<EDA_GROUP*>( outer ) );
2976 BOOST_REQUIRE( !guard->GetParentGroup() && !stack->GetParentGroup() );
2977 BOOST_REQUIRE( memberIds( *outer ) == std::set<KIID>{ stitch->m_Uuid } );
2978
2979 const std::string sourceModel = serializeNative( source.get() );
2980 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_native_via_generators", "" );
2981
2982 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
2983 {
2984 const bool preTen = target.m_boardVersion == kicad9.m_boardVersion;
2985
2986 for( bool drop : { false, true } )
2987 {
2988 BOOST_TEST_CONTEXT( target.m_id.ToStdString() << " drop=" << drop )
2989 {
2990 const COMPATIBILITY_REPORT preview = ClassifyBoardForDowngrade( source.get(), target, drop );
2991 BOOST_CHECK( !preview.IsBlocked() );
2993 BOOST_CHECK_EQUAL( preview.Count( DOWNGRADE_BUCKET::DROP ), preTen ? 5 : 3 );
2994 BOOST_CHECK_EQUAL( serializeNative( source.get() ), sourceModel );
2995 const std::string dest =
2996 ( tmp.Path()
2997 / ( target.m_id.ToStdString() + ( drop ? "-drop.kicad_pcb" : "-lower.kicad_pcb" ) ) )
2998 .string();
2999 COMPATIBILITY_REPORT report;
3000 wxString unsupportedToken;
3001 BOOST_REQUIRE( ExportBoardToOlderVersion( src, dest, target, report, &unsupportedToken, wxEmptyString,
3002 drop ) );
3003 BOOST_CHECK( unsupportedToken.IsEmpty() );
3004 BOOST_CHECK( !report.IsBlocked() );
3006 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), preTen ? 5 : 3 );
3007 BOOST_REQUIRE_EQUAL( report.Entries().size(), preTen ? 3u : 2u );
3008 checkFeature( report, wxT( "Via stitching and guarding" ), DOWNGRADE_BUCKET::DROP, 2 );
3009 checkFeature( report, wxT( "Microvia stack generators" ), DOWNGRADE_BUCKET::DROP, 1 );
3010
3011 if( preTen )
3012 checkFeature( report, wxT( "Via protection" ), DOWNGRADE_BUCKET::DROP, 2 );
3013
3014 BOOST_REQUIRE_EQUAL( report.Entries().size(), preview.Entries().size() );
3015
3016 for( size_t ii = 0; ii < preview.Entries().size(); ++ii )
3017 {
3018 BOOST_CHECK( report.Entries()[ii].m_bucket == preview.Entries()[ii].m_bucket );
3019 BOOST_CHECK( report.Entries()[ii].m_feature == preview.Entries()[ii].m_feature );
3020 BOOST_CHECK_EQUAL( report.Entries()[ii].m_count, preview.Entries()[ii].m_count );
3021 }
3022
3023 const std::string outputBytes = KI_TEST::ReadGoldenText( dest );
3024 BOOST_CHECK( FindUnsupportedBoardToken( wxString::FromUTF8( outputBytes ), target ).IsEmpty() );
3025 BOOST_CHECK( outputBytes.find( "(generated" ) == std::string::npos );
3026
3027 if( preTen )
3028 {
3029 for( const char* token : { "(filling", "(capping", "(covering", "(plugging" } )
3030 BOOST_CHECK( outputBytes.find( token ) == std::string::npos );
3031 }
3032
3033 std::unique_ptr<BOARD> exported( io.LoadBoard( dest, nullptr ) );
3034 BOOST_REQUIRE( exported );
3035 BOOST_CHECK_EQUAL( exported->GetFileFormatVersionAtLoad(), target.m_boardVersion );
3036 BOOST_CHECK_EQUAL( exported->GetCopperLayerCount(), 6 );
3037 BOOST_CHECK_EQUAL( exported->Zones().size(), 3u );
3038 BOOST_CHECK( exported->Generators().empty() );
3039 BOOST_REQUIRE_EQUAL( exported->Groups().size(), 1u );
3040 BOOST_CHECK( exported->GroupsSanityCheck().IsEmpty() );
3041
3042 const auto exportedCopper = copperById( *exported );
3043 BOOST_REQUIRE_EQUAL( exportedCopper.size(), sourceCopper.size() );
3044 PCB_GROUP* exportedOuter = *exported->Groups().begin();
3045 BOOST_CHECK( exportedOuter->m_Uuid == outerId );
3046 BOOST_CHECK( exportedOuter->GetName() == outerName );
3047 BOOST_CHECK( memberIds( *exportedOuter ) == stitchMembers );
3048
3049 for( const auto& [id, original] : sourceCopper )
3050 {
3051 const auto found = exportedCopper.find( id );
3052 BOOST_REQUIRE( found != exportedCopper.end() );
3053 const PCB_TRACK* item = found->second;
3054 BOOST_CHECK( item->Type() == original->Type() );
3055 BOOST_CHECK( item->GetStart() == original->GetStart() );
3056 BOOST_CHECK( item->GetEnd() == original->GetEnd() );
3057 BOOST_CHECK( item->GetLayerSet() == original->GetLayerSet() );
3058 BOOST_CHECK_EQUAL( item->GetNetname().ToStdString(), original->GetNetname().ToStdString() );
3059
3060 if( const PCB_VIA* originalVia = dynamic_cast<const PCB_VIA*>( original ) )
3061 {
3062 const PCB_VIA* via = dynamic_cast<const PCB_VIA*>( item );
3063 BOOST_REQUIRE( via );
3064 BOOST_CHECK( via->GetPosition() == originalVia->GetPosition() );
3065 BOOST_CHECK( via->GetViaType() == originalVia->GetViaType() );
3066 BOOST_CHECK( via->TopLayer() == originalVia->TopLayer() );
3067 BOOST_CHECK( via->BottomLayer() == originalVia->BottomLayer() );
3068 BOOST_CHECK_EQUAL( via->GetDrillValue(), originalVia->GetDrillValue() );
3069
3070 for( PCB_LAYER_ID layer : LSET::AllCuMask( 6 ) )
3071 BOOST_CHECK_EQUAL( via->GetWidth( layer ), originalVia->GetWidth( layer ) );
3072
3073 const PADSTACK& padstack = via->Padstack();
3074
3075 if( preTen )
3076 {
3077 // The current reader resolves omitted legacy fields to board defaults.
3078 BOOST_CHECK( !padstack.Drill().is_filled.value_or( false ) );
3079 BOOST_CHECK( !padstack.Drill().is_capped.value_or( false ) );
3080 BOOST_CHECK( !padstack.FrontOuterLayers().has_covering.value_or( false ) );
3081 BOOST_CHECK( !padstack.BackOuterLayers().has_covering.value_or( false ) );
3082 BOOST_CHECK( !padstack.FrontOuterLayers().has_plugging.value_or( false ) );
3083 BOOST_CHECK( !padstack.BackOuterLayers().has_plugging.value_or( false ) );
3084 }
3085 else
3086 {
3087 const PADSTACK& originalStack = originalVia->Padstack();
3088 BOOST_CHECK( padstack.Drill().is_filled == originalStack.Drill().is_filled );
3089 BOOST_CHECK( padstack.Drill().is_capped == originalStack.Drill().is_capped );
3091 == originalStack.FrontOuterLayers().has_covering );
3093 == originalStack.BackOuterLayers().has_covering );
3095 == originalStack.FrontOuterLayers().has_plugging );
3097 == originalStack.BackOuterLayers().has_plugging );
3098 }
3099
3100 if( plainVias.count( id ) )
3101 BOOST_CHECK( !via->GetParentGroup() );
3102 }
3103 else
3104 {
3105 BOOST_CHECK( item->GetLayer() == original->GetLayer() );
3106 BOOST_CHECK_EQUAL( item->GetWidth(), original->GetWidth() );
3107 }
3108
3109 if( stitchMembers.count( id ) )
3110 BOOST_CHECK( item->GetParentGroup() == static_cast<EDA_GROUP*>( exportedOuter ) );
3111 else
3112 BOOST_CHECK( !item->GetParentGroup() );
3113 }
3114
3115 for( BOARD_ITEM* drawing : source->Drawings() )
3116 {
3117 if( const EDA_TEXT* text = dynamic_cast<const EDA_TEXT*>( drawing ) )
3118 {
3119 const auto found = std::find_if( exported->Drawings().begin(), exported->Drawings().end(),
3120 [&]( const BOARD_ITEM* aItem )
3121 {
3122 return aItem->m_Uuid == drawing->m_Uuid;
3123 } );
3124 BOOST_REQUIRE( found != exported->Drawings().end() );
3125 const EDA_TEXT* exportedText = dynamic_cast<const EDA_TEXT*>( *found );
3126 BOOST_REQUIRE( exportedText );
3127 BOOST_CHECK( exportedText->GetText() == text->GetText() );
3128 }
3129 }
3130
3131 BOOST_CHECK_EQUAL( serializeNative( source.get() ), sourceModel );
3132 BOOST_CHECK_EQUAL( KI_TEST::ReadGoldenText( src ), originalBytes );
3133 }
3134 }
3135 }
3136}
3137
3138
3139BOOST_AUTO_TEST_CASE( NativeTuningFixturesPreserveCopperAndEraEditabilityForBothPolicies )
3140{
3141 SETTINGS_MANAGER settingsManager;
3143 const std::string lengthPath = KI_TEST::GetPcbnewTestDataDir() + "tuning_generators_load_save.kicad_pcb";
3144 const std::string timePath = KI_TEST::GetPcbnewTestDataDir() + "issue24772/fw16_MCIO8i.kicad_pcb";
3145 const std::string lengthBytes = KI_TEST::ReadGoldenText( lengthPath );
3146 const std::string timeBytes = KI_TEST::ReadGoldenText( timePath );
3147 std::unique_ptr<BOARD> lengthFixture( io.LoadBoard( lengthPath, nullptr ) );
3148 std::unique_ptr<BOARD> timeFixture( io.LoadBoard( timePath, nullptr ) );
3149 BOOST_REQUIRE( lengthFixture && timeFixture );
3150 BOOST_REQUIRE_EQUAL( lengthFixture->Generators().size(), 1u );
3151 BOOST_REQUIRE_EQUAL( timeFixture->Generators().size(), 16u );
3152 PCB_TUNING_PATTERN* originalTime = nullptr;
3153
3154 for( PCB_GENERATOR* generator : timeFixture->Generators() )
3155 {
3156 if( generator->m_Uuid == KIID( "2acf841f-25ce-450c-b8df-dbbc34cc96ac" ) )
3157 originalTime = dynamic_cast<PCB_TUNING_PATTERN*>( generator );
3158 }
3159
3160 BOOST_REQUIRE( originalTime );
3161 BOOST_REQUIRE( originalTime->GetSettings().m_isTimeDomain );
3162 BOOST_REQUIRE_EQUAL( originalTime->GetItems().size(), 1u );
3163 BOARD board;
3164 board.SetCopperLayerCount( timeFixture->GetCopperLayerCount() );
3165 board.SetEnabledLayers( timeFixture->GetEnabledLayers() );
3166 auto length = dynamic_cast<PCB_TUNING_PATTERN*>( ( *lengthFixture->Generators().begin() )->DeepClone() );
3167 auto time = dynamic_cast<PCB_TUNING_PATTERN*>( originalTime->DeepClone() );
3168 BOOST_REQUIRE( length && time );
3169 BOOST_REQUIRE( !length->GetSettings().m_isTimeDomain );
3170 BOOST_REQUIRE_GT( length->GetItems().size(), 1u );
3171
3172 const auto addCopper = [&]( PCB_TRACK* aTrack )
3173 {
3174 NETINFO_ITEM* net = board.FindNet( aTrack->GetNetname() );
3175
3176 if( !net )
3177 {
3178 net = new NETINFO_ITEM( &board, aTrack->GetNetname() );
3179 board.Add( net );
3180 }
3181
3182 aTrack->SetParent( &board );
3183 aTrack->SetNetCode( net->GetNetCode() );
3184 board.Add( aTrack );
3185 };
3186
3187 for( PCB_TUNING_PATTERN* pattern : { length, time } )
3188 {
3189 for( BOARD_ITEM* member : pattern->GetBoardItems() )
3190 {
3191 PCB_TRACK* track = dynamic_cast<PCB_TRACK*>( member );
3192 BOOST_REQUIRE( track );
3193 addCopper( track );
3194 }
3195
3196 board.Add( pattern );
3197 }
3198
3199 PCB_TRACK* originalControl = nullptr;
3200
3201 for( PCB_TRACK* track : timeFixture->Tracks() )
3202 {
3203 if( track->Type() == PCB_TRACE_T && !dynamic_cast<PCB_GENERATOR*>( track->GetParentGroup() ) )
3204 {
3205 originalControl = track;
3206 break;
3207 }
3208 }
3209
3210 BOOST_REQUIRE( originalControl );
3211 auto control = static_cast<PCB_TRACK*>( originalControl->Clone() );
3212 control->SetParentGroup( nullptr );
3213 addCopper( control );
3214 PCB_GROUP* outer = new PCB_GROUP( &board );
3215 outer->SetName( wxT( "Native tuning ownership" ) );
3216 board.Add( outer );
3217 outer->AddItem( length );
3218 outer->AddItem( time );
3219
3220 // Populate the numeric cache through native APIs without changing fixture copper.
3221 double patternLength = 0;
3222
3223 for( BOARD_ITEM* member : length->GetBoardItems() )
3224 patternLength += static_cast<PCB_TRACK*>( member )->GetLength();
3225
3226 STRING_ANY_MAP lengthProperties = length->GetProperties();
3227
3228 // The native setter expects wxString values for these serialized string enums.
3229 for( const char* key : { "tuning_mode", "initial_side", "last_status" } )
3230 {
3231 std::string value;
3232 BOOST_REQUIRE( lengthProperties.get_to( key, value ) );
3233 lengthProperties[key] = wxAny( wxString::FromUTF8( value ) );
3234 }
3235
3236 lengthProperties["last_tuning_length"] = wxAny( patternLength / pcbIUScale.IU_PER_MM );
3237 length->SetProperties( lengthProperties );
3238 const wxString tuningInfo = length->GetRowData().back().second.GetString();
3239 BOOST_REQUIRE( !tuningInfo.IsEmpty() );
3240 const auto memberIds = []( const PCB_GROUP& aGroup )
3241 {
3242 std::set<KIID> ids;
3243
3244 for( const EDA_ITEM* member : aGroup.GetItems() )
3245 BOOST_REQUIRE( ids.insert( member->m_Uuid ).second );
3246
3247 return ids;
3248 };
3249 const auto serializeNative = []( BOARD* aBoard )
3250 {
3251 STRING_FORMATTER formatter;
3252 PCB_IO_KICAD_SEXPR serializer;
3253 serializer.FormatBoardToFormatter( &formatter, aBoard );
3254 return formatter.GetString();
3255 };
3256 std::map<KIID, const PCB_TRACK*> copper;
3257
3258 for( const PCB_TRACK* track : board.Tracks() )
3259 BOOST_REQUIRE( copper.emplace( track->m_Uuid, track ).second );
3260
3261 const auto lengthMembers = memberIds( *length );
3262 const auto timeMembers = memberIds( *time );
3263 BOOST_REQUIRE_EQUAL( copper.size(), lengthMembers.size() + timeMembers.size() + 1u );
3264 BOOST_REQUIRE( board.GroupsSanityCheck().IsEmpty() );
3265 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_native_tuning_boundaries" );
3266 const std::string src = ( tmp.Path() / "native-source.kicad_pcb" ).string();
3267 io.SaveBoard( src, board );
3268 const std::string sourceBytes = KI_TEST::ReadGoldenText( src );
3269 const std::string sourceModel = serializeNative( &board );
3270
3271 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
3272 {
3273 const bool preTen = target.m_boardVersion == kicad9.m_boardVersion;
3274
3275 for( bool drop : { false, true } )
3276 {
3277 BOOST_TEST_CONTEXT( target.m_id.ToStdString() << " drop=" << drop )
3278 {
3279 const auto preview = ClassifyBoardForDowngrade( &board, target, drop );
3280 BOOST_CHECK( !preview.IsBlocked() );
3281 BOOST_CHECK_EQUAL( preview.Count( DOWNGRADE_BUCKET::LOWER ), 0 );
3282 BOOST_CHECK_EQUAL( preview.Count( DOWNGRADE_BUCKET::DROP ), preTen ? 1 : 0 );
3283 BOOST_CHECK_EQUAL( serializeNative( &board ), sourceModel );
3284 const std::string dest =
3285 ( tmp.Path()
3286 / ( target.m_id.ToStdString() + ( drop ? "-drop.kicad_pcb" : "-lower.kicad_pcb" ) ) )
3287 .string();
3288 COMPATIBILITY_REPORT report;
3289 wxString unsupported;
3291 ExportBoardToOlderVersion( src, dest, target, report, &unsupported, wxEmptyString, drop ) );
3292 BOOST_CHECK( unsupported.IsEmpty() );
3293 BOOST_CHECK( !report.IsBlocked() );
3295 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), preTen ? 1 : 0 );
3296 BOOST_REQUIRE_EQUAL( report.Entries().size(), preTen ? 1u : 0u );
3297
3298 if( preTen )
3299 checkFeature( report, wxT( "Time-domain tuning patterns" ), DOWNGRADE_BUCKET::DROP, 1 );
3300
3301 const std::string outputBytes = KI_TEST::ReadGoldenText( dest );
3302 BOOST_CHECK( FindUnsupportedBoardToken( wxString::FromUTF8( outputBytes ), target ).IsEmpty() );
3303
3304 if( preTen )
3305 {
3306 for( const char* token : { "(is_time_domain", "(target_delay", "(last_tuning_length" } )
3307 BOOST_CHECK( outputBytes.find( token ) == std::string::npos );
3308
3309 STRING_FORMATTER quoting;
3310 BOOST_CHECK( outputBytes.find( "(last_tuning " + quoting.Quotew( tuningInfo ) + ")" )
3311 != std::string::npos );
3312 }
3313 else
3314 {
3315 BOOST_CHECK( outputBytes.find( "(is_time_domain yes)" ) != std::string::npos );
3316 BOOST_CHECK( outputBytes.find( "(last_tuning_length " ) != std::string::npos );
3317 BOOST_CHECK( outputBytes.find( "(last_tuning " ) == std::string::npos );
3318 }
3319
3320 std::unique_ptr<BOARD> exported( io.LoadBoard( dest, nullptr ) );
3321 BOOST_REQUIRE( exported );
3322 BOOST_CHECK_EQUAL( exported->GetFileFormatVersionAtLoad(), target.m_boardVersion );
3323 BOOST_REQUIRE_EQUAL( exported->Generators().size(), preTen ? 1u : 2u );
3324 BOOST_REQUIRE_EQUAL( exported->Groups().size(), 1u );
3325 BOOST_CHECK( exported->GroupsSanityCheck().IsEmpty() );
3326 PCB_GROUP* exportedOuter = *exported->Groups().begin();
3327 BOOST_CHECK( exportedOuter->m_Uuid == outer->m_Uuid );
3328 std::set<KIID> expectedOuter{ length->m_Uuid };
3329
3330 if( preTen )
3331 expectedOuter.insert( timeMembers.begin(), timeMembers.end() );
3332 else
3333 expectedOuter.insert( time->m_Uuid );
3334
3335 BOOST_CHECK( memberIds( *exportedOuter ) == expectedOuter );
3336 BOOST_REQUIRE_EQUAL( exported->Tracks().size(), copper.size() );
3337
3338 for( const PCB_TRACK* track : exported->Tracks() )
3339 {
3340 const auto found = copper.find( track->m_Uuid );
3341 BOOST_REQUIRE( found != copper.end() );
3342 const PCB_TRACK* original = found->second;
3343 BOOST_CHECK( track->Type() == original->Type() );
3344 BOOST_CHECK( track->GetStart() == original->GetStart() );
3345 BOOST_CHECK( track->GetEnd() == original->GetEnd() );
3346 BOOST_CHECK( track->GetLayerSet() == original->GetLayerSet() );
3347 BOOST_CHECK_EQUAL( track->GetWidth(), original->GetWidth() );
3348 BOOST_CHECK_EQUAL( track->GetNetname().ToStdString(), original->GetNetname().ToStdString() );
3349
3350 if( const PCB_ARC* arc = dynamic_cast<const PCB_ARC*>( original ) )
3351 {
3352 const PCB_ARC* exportedArc = dynamic_cast<const PCB_ARC*>( track );
3353 BOOST_REQUIRE( exportedArc );
3354 BOOST_CHECK( exportedArc->GetMid() == arc->GetMid() );
3355 }
3356
3357 if( timeMembers.count( track->m_Uuid ) && preTen )
3358 BOOST_CHECK( track->GetParentGroup() == static_cast<EDA_GROUP*>( exportedOuter ) );
3359 else if( track->m_Uuid == control->m_Uuid )
3360 BOOST_CHECK( !track->GetParentGroup() );
3361 }
3362
3363 for( PCB_GENERATOR* generator : exported->Generators() )
3364 {
3365 auto pattern = dynamic_cast<PCB_TUNING_PATTERN*>( generator );
3366 BOOST_REQUIRE( pattern );
3367 BOOST_CHECK( pattern->GetParentGroup() == static_cast<EDA_GROUP*>( exportedOuter ) );
3368 BOOST_CHECK( pattern->m_Uuid == length->m_Uuid || ( !preTen && pattern->m_Uuid == time->m_Uuid ) );
3369 const bool isTime = pattern->m_Uuid == time->m_Uuid;
3370 BOOST_CHECK( pattern->GetSettings().m_isTimeDomain == isTime );
3371 BOOST_CHECK( memberIds( *pattern ) == ( isTime ? timeMembers : lengthMembers ) );
3372 const PCB_TUNING_PATTERN* original = isTime ? time : length;
3373 const auto properties = pattern->GetProperties();
3374 const auto originalProperties = original->GetProperties();
3375
3376 for( const char* key :
3377 { "target_length", "target_length_min", "target_length_max", "target_skew", "target_skew_min",
3378 "target_skew_max", "min_spacing", "max_amplitude", "min_amplitude" } )
3379 {
3380 double value = 0;
3381 double originalValue = 0;
3382 BOOST_REQUIRE( properties.get_to( key, value ) );
3383 BOOST_REQUIRE( originalProperties.get_to( key, originalValue ) );
3384 BOOST_CHECK_EQUAL( value, originalValue );
3385 }
3386
3387 if( !preTen )
3388 {
3389 for( const char* key :
3390 { "target_delay", "target_delay_min", "target_delay_max", "last_tuning_length" } )
3391 {
3392 double value = 0;
3393 double originalValue = 0;
3394 BOOST_REQUIRE( properties.get_to( key, value ) );
3395 BOOST_REQUIRE( originalProperties.get_to( key, originalValue ) );
3396 BOOST_CHECK_EQUAL( value, originalValue );
3397 }
3398 }
3399 }
3400
3401 BOOST_CHECK_EQUAL( serializeNative( &board ), sourceModel );
3402 BOOST_CHECK_EQUAL( KI_TEST::ReadGoldenText( src ), sourceBytes );
3403 BOOST_CHECK_EQUAL( KI_TEST::ReadGoldenText( lengthPath ), lengthBytes );
3404 BOOST_CHECK_EQUAL( KI_TEST::ReadGoldenText( timePath ), timeBytes );
3405 }
3406 }
3407 }
3408}
3409
3410
3411BOOST_AUTO_TEST_CASE( UnreviewedTuningPropertiesBlockBothTargetsAndPolicies )
3412{
3413 class UNREVIEWED_TUNING_PATTERN : public PCB_TUNING_PATTERN
3414 {
3415 public:
3417
3418 const STRING_ANY_MAP GetProperties() const override
3419 {
3421 properties.set( "future_tuning_setting", true );
3422 return properties;
3423 }
3424 };
3425
3426 BOARD board;
3427 auto pattern = new UNREVIEWED_TUNING_PATTERN( &board );
3428 auto track = new PCB_TRACK( &board );
3429 track->SetStart( VECTOR2I( 1000000, 2000000 ) );
3430 track->SetEnd( VECTOR2I( 3000000, 2000000 ) );
3431 board.Add( track );
3432 board.Add( pattern );
3433 pattern->AddItem( track );
3434
3435 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
3436 {
3437 for( bool drop : { false, true } )
3438 {
3439 const auto report = ClassifyBoardForDowngrade( &board, target, drop );
3440 checkFeature( report, wxT( "Unreviewed tuning properties" ), DOWNGRADE_BUCKET::BLOCK, 1 );
3441 BOOST_REQUIRE_EQUAL( board.Generators().size(), 1u );
3442 BOOST_CHECK( track->GetParentGroup() == static_cast<EDA_GROUP*>( pattern ) );
3443 }
3444 }
3445
3446 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_unreviewed_tuning" );
3447
3448 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
3449 {
3450 const wxString path = ( tmp.Path() / ( target.m_id.ToStdString() + ".kicad_pcb" ) ).wstring();
3451 BOOST_CHECK_THROW( SaveBoardForTarget( &board, path, target ), IO_ERROR );
3452 }
3453}
3454
3455
3456BOOST_AUTO_TEST_CASE( HistoricalTuningWritersRejectUnsafeDirectSerialization )
3457{
3458 BOARD board;
3459 auto pattern = new PCB_TUNING_PATTERN( &board );
3460 pattern->SetTargetDelay( 100000 );
3461 auto track = new PCB_TRACK( &board );
3462 track->SetStart( VECTOR2I( 1000000, 2000000 ) );
3463 track->SetEnd( VECTOR2I( 3000000, 2000000 ) );
3464 board.Add( track );
3465 board.Add( pattern );
3466 pattern->AddItem( track );
3467 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_direct_time_tuning" );
3468 BOOST_CHECK_THROW( SaveBoardForTarget( &board, ( tmp.Path() / "unsafe.kicad_pcb" ).wstring(), kicad9 ), IO_ERROR );
3469
3470 for( const char* token :
3471 { "is_time_domain", "target_delay", "target_delay_min", "target_delay_max", "last_tuning_length" } )
3472 {
3473 const wxString value = wxString::FromUTF8( "(kicad_pcb (generated (" + std::string( token ) + " 0)))" );
3474 BOOST_CHECK_EQUAL( FindUnsupportedBoardToken( value, kicad9 ), wxString::FromUTF8( token ) );
3475 BOOST_CHECK( FindUnsupportedBoardToken( value, kicad10 ).IsEmpty() );
3476 }
3477}
3478
3479
3480BOOST_AUTO_TEST_CASE( HistoricalWritersRejectDirectViaGeneratorsAtomically )
3481{
3482 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_direct_via_generators" );
3483
3484 for( bool stack : { false, true } )
3485 {
3486 BOARD board;
3487
3488 if( stack )
3489 board.Add( new PCB_VIA_STACK( &board ) );
3490 else
3491 board.Add( new PCB_VIA_STITCH( &board ) );
3492
3493 const std::string kind = stack ? "via-stack" : "via-stitch";
3494
3495 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
3496 {
3497 BOOST_TEST_CONTEXT( kind << " target=" << target.m_id.ToStdString() )
3498 {
3499 const auto absent = tmp.Path() / ( kind + "-" + target.m_id.ToStdString() + "-absent.kicad_pcb" );
3500 BOOST_CHECK_THROW( SaveBoardForTarget( &board, absent.wstring(), target ), IO_ERROR );
3501 BOOST_CHECK( !wxFileExists( absent.wstring() ) );
3502
3503 const auto existing = tmp.Path() / ( kind + "-" + target.m_id.ToStdString() + "-existing.kicad_pcb" );
3504
3505 {
3506 std::ofstream sentinel( existing, std::ios::binary );
3507 sentinel << "existing destination";
3508 BOOST_REQUIRE( sentinel.good() );
3509 }
3510
3511 BOOST_CHECK_THROW( SaveBoardForTarget( &board, existing.wstring(), target ), IO_ERROR );
3512 BOOST_CHECK_EQUAL( KI_TEST::ReadGoldenText( existing.string() ), "existing destination" );
3513 }
3514 }
3515 }
3516}
3517
3518
3519BOOST_AUTO_TEST_CASE( NativeGroupPlacementFixtureKeepsGeometryAndOwnershipForBothPolicies )
3520{
3521 SETTINGS_MANAGER settingsManager;
3522 const std::string src =
3523 KI_TEST::GetPcbnewTestDataDir() + "../downgrade/regressions/group_placement/group_placement.kicad_pcb";
3524 wxFileName projectFile( wxString::FromUTF8( src ) );
3525 projectFile.SetExt( wxT( "kicad_pro" ) );
3526 BOOST_REQUIRE( wxFileExists( projectFile.GetFullPath() ) );
3527 BOOST_REQUIRE( settingsManager.LoadProject( projectFile.GetFullPath(), false ) );
3528 const std::string sourceBytes = KI_TEST::ReadGoldenText( src );
3530 std::unique_ptr<BOARD> source( io.LoadBoard( src, nullptr ) );
3532 BOOST_REQUIRE_EQUAL( source->Zones().size(), 7u );
3533 BOOST_REQUIRE_EQUAL( source->Groups().size(), 4u );
3534 BOOST_REQUIRE_EQUAL( source->Footprints().size(), 4u );
3535 BOOST_REQUIRE( source->GroupsSanityCheck().IsEmpty() );
3536 std::map<KIID, const PCB_TEXT*> sourceNotes;
3537
3538 for( const BOARD_ITEM* drawing : source->Drawings() )
3539 {
3540 if( const PCB_TEXT* note = dynamic_cast<const PCB_TEXT*>( drawing ) )
3541 BOOST_REQUIRE( sourceNotes.emplace( note->m_Uuid, note ).second );
3542 }
3543
3544 BOOST_REQUIRE_EQUAL( sourceNotes.size(), 1u );
3545 std::map<KIID, const ZONE*> sourceZones;
3546 int placementAreas = 0;
3547 int filledOutlines = 0;
3548
3549 for( const ZONE* zone : source->Zones() )
3550 {
3551 BOOST_REQUIRE( sourceZones.emplace( zone->m_Uuid, zone ).second );
3552
3553 if( zone->GetPlacementAreaSourceType() == PLACEMENT_SOURCE_T::GROUP_PLACEMENT )
3554 {
3555 ++placementAreas;
3556 BOOST_REQUIRE( zone->GetPlacementAreaEnabled() );
3557 BOOST_REQUIRE( !zone->GetPlacementAreaSource().IsEmpty() );
3558 }
3559
3560 for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
3561 filledOutlines += zone->GetFilledPolysList( layer )->OutlineCount();
3562 }
3563
3564 BOOST_REQUIRE_EQUAL( placementAreas, 4 );
3565 BOOST_REQUIRE_GT( filledOutlines, 0 );
3566 const auto memberIds = []( const PCB_GROUP& aGroup )
3567 {
3568 std::set<KIID> ids;
3569
3570 for( const EDA_ITEM* member : aGroup.GetItems() )
3571 BOOST_REQUIRE( ids.insert( member->m_Uuid ).second );
3572
3573 return ids;
3574 };
3575 const auto checkPolygons = []( const SHAPE_POLY_SET& aOriginal, const SHAPE_POLY_SET& aExported )
3576 {
3577 BOOST_REQUIRE_EQUAL( aExported.OutlineCount(), aOriginal.OutlineCount() );
3578
3579 for( int outline = 0; outline < aOriginal.OutlineCount(); ++outline )
3580 {
3581 BOOST_CHECK( aExported.COutline( outline ).CompareGeometry( aOriginal.COutline( outline ) ) );
3582 BOOST_REQUIRE_EQUAL( aExported.HoleCount( outline ), aOriginal.HoleCount( outline ) );
3583
3584 for( int hole = 0; hole < aOriginal.HoleCount( outline ); ++hole )
3585 BOOST_CHECK( aExported.CHole( outline, hole ).CompareGeometry( aOriginal.CHole( outline, hole ) ) );
3586 }
3587 };
3588 const auto serializeNative = []( BOARD* aBoard )
3589 {
3590 STRING_FORMATTER formatter;
3591 PCB_IO_KICAD_SEXPR serializer;
3592 serializer.FormatBoardToFormatter( &formatter, aBoard );
3593 return formatter.GetString();
3594 };
3595 const std::string sourceModel = serializeNative( source.get() );
3596 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_native_group_placement" );
3597 BOOST_CHECK_THROW( SaveBoardForTarget( source.get(), ( tmp.Path() / "unsafe.kicad_pcb" ).wstring(), kicad9 ),
3598 IO_ERROR );
3599 BOOST_CHECK_EQUAL( serializeNative( source.get() ), sourceModel );
3600
3601 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
3602 {
3603 const bool preTen = target.m_boardVersion == kicad9.m_boardVersion;
3604
3605 for( bool drop : { false, true } )
3606 {
3607 BOOST_TEST_CONTEXT( target.m_id.ToStdString() << " drop=" << drop )
3608 {
3609 const auto preview = ClassifyBoardForDowngrade( source.get(), target, drop );
3610 BOOST_CHECK( !preview.IsBlocked() );
3611 BOOST_CHECK_EQUAL( preview.Count( DOWNGRADE_BUCKET::DROP ), preTen ? 4 : 0 );
3612 BOOST_CHECK_EQUAL( preview.Count( DOWNGRADE_BUCKET::LOWER ), 0 );
3613 BOOST_CHECK_EQUAL( serializeNative( source.get() ), sourceModel );
3614 const std::string dest =
3615 ( tmp.Path()
3616 / ( target.m_id.ToStdString() + ( drop ? "-drop.kicad_pcb" : "-lower.kicad_pcb" ) ) )
3617 .string();
3618 COMPATIBILITY_REPORT report;
3619 wxString unsupported;
3621 ExportBoardToOlderVersion( src, dest, target, report, &unsupported, wxEmptyString, drop ) );
3622 BOOST_CHECK( unsupported.IsEmpty() );
3623 BOOST_CHECK( !report.IsBlocked() );
3624 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), preTen ? 4 : 0 );
3626 BOOST_REQUIRE_EQUAL( report.Entries().size(), preTen ? 1u : 0u );
3627
3628 if( preTen )
3629 checkFeature( report, wxT( "Group placement areas" ), DOWNGRADE_BUCKET::DROP, 4 );
3630
3631 const std::string outputBytes = KI_TEST::ReadGoldenText( dest );
3632 BOOST_CHECK( FindUnsupportedBoardToken( wxString::FromUTF8( outputBytes ), target ).IsEmpty() );
3633 std::unique_ptr<BOARD> exported( io.LoadBoard( dest, nullptr ) );
3634 BOOST_REQUIRE( exported );
3635 BOOST_CHECK_EQUAL( exported->GetFileFormatVersionAtLoad(), target.m_boardVersion );
3636 BOOST_REQUIRE_EQUAL( exported->Zones().size(), source->Zones().size() );
3637 BOOST_REQUIRE_EQUAL( exported->Groups().size(), source->Groups().size() );
3638 BOOST_REQUIRE_EQUAL( exported->Footprints().size(), source->Footprints().size() );
3639 BOOST_CHECK( exported->GroupsSanityCheck().IsEmpty() );
3640
3641 for( const auto& [id, original] : sourceNotes )
3642 {
3643 const auto found = std::find_if( exported->Drawings().begin(), exported->Drawings().end(),
3644 [&]( const BOARD_ITEM* aItem )
3645 {
3646 return aItem->m_Uuid == id;
3647 } );
3648 BOOST_REQUIRE( found != exported->Drawings().end() );
3649 const PCB_TEXT* note = dynamic_cast<const PCB_TEXT*>( *found );
3650 BOOST_REQUIRE( note );
3651 BOOST_CHECK( note->GetText() == original->GetText() );
3652 BOOST_CHECK( note->GetPosition() == original->GetPosition() );
3653 BOOST_CHECK( note->GetLayer() == original->GetLayer() );
3654 }
3655
3656 for( const ZONE* zone : exported->Zones() )
3657 {
3658 const auto found = sourceZones.find( zone->m_Uuid );
3659 BOOST_REQUIRE( found != sourceZones.end() );
3660 const ZONE* original = found->second;
3661 BOOST_CHECK( zone->GetZoneName() == original->GetZoneName() );
3662 BOOST_CHECK( zone->GetLayerSet() == original->GetLayerSet() );
3663 BOOST_CHECK( zone->GetIsRuleArea() == original->GetIsRuleArea() );
3664 BOOST_CHECK( zone->GetDoNotAllowTracks() == original->GetDoNotAllowTracks() );
3665 BOOST_CHECK( zone->GetDoNotAllowVias() == original->GetDoNotAllowVias() );
3666 BOOST_CHECK( zone->GetDoNotAllowPads() == original->GetDoNotAllowPads() );
3667 BOOST_CHECK( zone->GetDoNotAllowZoneFills() == original->GetDoNotAllowZoneFills() );
3668 BOOST_CHECK( zone->GetDoNotAllowFootprints() == original->GetDoNotAllowFootprints() );
3669 BOOST_CHECK( zone->GetNetname() == original->GetNetname() );
3670 BOOST_CHECK( zone->IsFilled() == original->IsFilled() );
3671 checkPolygons( original->GetBoardOutline(), zone->GetBoardOutline() );
3672
3673 for( PCB_LAYER_ID layer : original->GetLayerSet().Seq() )
3674 {
3675 const auto originalFill = original->GetFilledPolysList( layer );
3676 const auto exportedFill = zone->GetFilledPolysList( layer );
3677 checkPolygons( *originalFill, *exportedFill );
3678
3679 for( int outline = 0; outline < originalFill->OutlineCount(); ++outline )
3680 BOOST_CHECK( zone->IsIsland( layer, outline ) == original->IsIsland( layer, outline ) );
3681 }
3682
3684 {
3685 BOOST_CHECK( !zone->GetPlacementAreaEnabled() );
3686 BOOST_CHECK( zone->GetPlacementAreaSource().IsEmpty() );
3687 BOOST_CHECK( zone->GetPlacementAreaSourceType() == PLACEMENT_SOURCE_T::SHEETNAME );
3688 }
3689 else
3690 {
3691 BOOST_CHECK( zone->GetPlacementAreaEnabled() == original->GetPlacementAreaEnabled() );
3692 BOOST_CHECK( zone->GetPlacementAreaSource() == original->GetPlacementAreaSource() );
3693 BOOST_CHECK( zone->GetPlacementAreaSourceType() == original->GetPlacementAreaSourceType() );
3694 }
3695 }
3696
3697 for( const PCB_GROUP* group : exported->Groups() )
3698 {
3699 const auto original = std::find_if( source->Groups().begin(), source->Groups().end(),
3700 [&]( const PCB_GROUP* aGroup )
3701 {
3702 return aGroup->m_Uuid == group->m_Uuid;
3703 } );
3704 BOOST_REQUIRE( original != source->Groups().end() );
3705 BOOST_CHECK( group->GetName() == ( *original )->GetName() );
3706 BOOST_CHECK( memberIds( *group ) == memberIds( **original ) );
3707 }
3708
3709 std::map<KIID, const PAD*> sourcePads;
3710
3711 for( const PAD* pad : source->GetPads() )
3712 BOOST_REQUIRE( sourcePads.emplace( pad->m_Uuid, pad ).second );
3713
3714 BOOST_REQUIRE_EQUAL( sourcePads.size(), 8u );
3715 BOOST_REQUIRE_EQUAL( exported->GetPads().size(), sourcePads.size() );
3716
3717 for( const PAD* pad : exported->GetPads() )
3718 {
3719 const auto found = sourcePads.find( pad->m_Uuid );
3720 BOOST_REQUIRE( found != sourcePads.end() );
3721 const PAD* original = found->second;
3722 BOOST_CHECK( pad->GetPosition() == original->GetPosition() );
3723 BOOST_CHECK( pad->GetOrientation() == original->GetOrientation() );
3724 BOOST_CHECK( pad->GetLayerSet() == original->GetLayerSet() );
3725 BOOST_CHECK( pad->GetNetname() == original->GetNetname() );
3726 BOOST_CHECK( pad->GetShape( F_Cu ) == original->GetShape( F_Cu ) );
3727 BOOST_CHECK( pad->GetSize( F_Cu ) == original->GetSize( F_Cu ) );
3728 BOOST_CHECK_EQUAL( pad->GetRoundRectRadiusRatio( F_Cu ),
3729 original->GetRoundRectRadiusRatio( F_Cu ) );
3730 }
3731
3732 BOOST_CHECK_EQUAL( serializeNative( source.get() ), sourceModel );
3733 BOOST_CHECK_EQUAL( KI_TEST::ReadGoldenText( src ), sourceBytes );
3734 }
3735 }
3736 }
3737}
3738
3739
3740BOOST_AUTO_TEST_CASE( GroupPlacementLinkageUsesTheSameFootprintPolicy )
3741{
3742 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
3743 {
3744 for( bool drop : { false, true } )
3745 {
3746 BOARD board;
3747 auto footprint = new FOOTPRINT( &board );
3748 auto zone = new ZONE( footprint );
3749 zone->SetIsRuleArea( true );
3750 zone->SetPlacementAreaEnabled( true );
3751 zone->SetPlacementAreaSourceType( PLACEMENT_SOURCE_T::GROUP_PLACEMENT );
3752 zone->SetPlacementAreaSource( wxT( "Repeated group" ) );
3753 zone->SetDoNotAllowTracks( true );
3754 footprint->Add( zone );
3755 board.Add( footprint );
3756 const auto report = ClassifyBoardForDowngrade( &board, target, drop );
3757 BOOST_CHECK_EQUAL( report.Count( DOWNGRADE_BUCKET::DROP ), target.m_id == kicad9.m_id ? 1 : 0 );
3758 BOOST_CHECK( zone->GetPlacementAreaEnabled() );
3759 DowngradeFootprintInPlace( footprint, target, drop );
3760 BOOST_CHECK( zone->GetIsRuleArea() );
3761 BOOST_CHECK( zone->GetDoNotAllowTracks() );
3762 BOOST_CHECK( zone->GetPlacementAreaEnabled() == ( target.m_id == kicad10.m_id ) );
3763 BOOST_CHECK( zone->GetPlacementAreaSource()
3764 == ( target.m_id == kicad10.m_id ? wxT( "Repeated group" ) : wxEmptyString ) );
3765 }
3766 }
3767}
3768
3769
3770BOOST_AUTO_TEST_CASE( GroupPlacementGuardIgnoresOrdinaryGroupsAndQuotedText )
3771{
3772 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(zone (placement (group \"SourceA\")))" ), kicad9 )
3773 == wxT( "placement/group" ) );
3774 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(zone (placement (group \"SourceA\")))" ), kicad10 ).IsEmpty() );
3775 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(group \"Ordinary\" (members \"uuid\"))" ), kicad9 ).IsEmpty() );
3776 BOOST_CHECK( FindUnsupportedBoardToken( wxT( "(gr_text \"(zone (placement (group foo)))\")" ), kicad9 ).IsEmpty() );
3777}
3778
3779
3780BOOST_AUTO_TEST_CASE( InertGroupPlacementMetadataDoesNotRequireConsent )
3781{
3782 for( bool drop : { false, true } )
3783 {
3784 BOARD board;
3785 auto emptyRuleArea = new ZONE( &board );
3786 emptyRuleArea->SetIsRuleArea( true );
3787 emptyRuleArea->SetPlacementAreaSourceType( PLACEMENT_SOURCE_T::GROUP_PLACEMENT );
3788 board.Add( emptyRuleArea );
3789 auto ordinaryZone = new ZONE( &board );
3790 ordinaryZone->SetPlacementAreaSourceType( PLACEMENT_SOURCE_T::GROUP_PLACEMENT );
3791 ordinaryZone->SetPlacementAreaEnabled( true );
3792 ordinaryZone->SetPlacementAreaSource( wxT( "Unused by ordinary copper zones" ) );
3793 board.Add( ordinaryZone );
3794 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad9, drop ).IsLossy() );
3795 DowngradeBoardInPlace( &board, kicad9, drop );
3796 BOOST_CHECK( emptyRuleArea->GetIsRuleArea() );
3797 BOOST_CHECK( !ordinaryZone->GetIsRuleArea() );
3798 BOOST_CHECK( emptyRuleArea->GetPlacementAreaSourceType() == PLACEMENT_SOURCE_T::SHEETNAME );
3799 BOOST_CHECK( ordinaryZone->GetPlacementAreaSourceType() == PLACEMENT_SOURCE_T::SHEETNAME );
3800 }
3801}
3802
3803
3804BOOST_AUTO_TEST_CASE( UnreviewedGeneratorKindBlocksBothPolicies )
3805{
3806 class FUTURE_GENERATOR : public PCB_VIA_STITCH
3807 {
3808 public:
3809 explicit FUTURE_GENERATOR( BOARD* aBoard ) :
3810 PCB_VIA_STITCH( aBoard )
3811 {
3812 }
3813 wxString GetGeneratorType() const override { return wxT( "future_generator" ); }
3814 };
3815
3816 BOARD board;
3817 board.Add( new FUTURE_GENERATOR( &board ) );
3818
3819 for( bool drop : { false, true } )
3820 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, drop ).IsBlocked() );
3821}
3822
3823
3824BOOST_AUTO_TEST_CASE( LineEndingsLowerPrintedInkOrDropOnlyEmbellishments )
3825{
3826 for( bool drop : { false, true } )
3827 {
3828 BOARD board;
3829 FOOTPRINT* fp = new FOOTPRINT( &board );
3830 board.Add( fp );
3831 std::vector<PCB_SHAPE*> shapes;
3832 double expectedArea = 0;
3833
3834 for( BOARD_ITEM_CONTAINER* parent :
3835 { static_cast<BOARD_ITEM_CONTAINER*>( &board ), static_cast<BOARD_ITEM_CONTAINER*>( fp ) } )
3836 {
3837 PCB_SHAPE* shape = new PCB_SHAPE( parent, SHAPE_T::SEGMENT );
3838 shape->SetStart( VECTOR2I( 0, 0 ) );
3839 shape->SetEnd( VECTOR2I( 10000000, 0 ) );
3840 shape->SetWidth( 200000 );
3841 shape->SetLayer( F_SilkS );
3842 shape->SetEndEnding( LINE_ENDING( LINE_ENDING_STYLE::ARROW, 2000000, 1000000 ) );
3843 parent->Add( shape );
3844 shapes.push_back( shape );
3845 SHAPE_POLY_SET ink;
3846 shape->TransformWithLineEndingsToPolygon( ink, 0, 5000, ERROR_INSIDE );
3847 ink.Simplify();
3848 expectedArea += ink.Area();
3849 }
3850
3851 const auto report = ClassifyBoardForDowngrade( &board, kicad10, drop );
3852 checkFeature( report, wxT( "Graphic line endings" ), drop ? DOWNGRADE_BUCKET::DROP : DOWNGRADE_BUCKET::LOWER,
3853 2 );
3854 DowngradeBoardInPlace( &board, kicad10, drop );
3855
3856 if( drop )
3857 {
3858 for( PCB_SHAPE* shape : shapes )
3859 {
3860 BOOST_CHECK( shape->GetShape() == SHAPE_T::SEGMENT );
3861 BOOST_CHECK( shape->GetEnd() == VECTOR2I( 10000000, 0 ) );
3862 BOOST_CHECK( shape->GetEndEndingStyle() == LINE_ENDING_STYLE::NONE );
3863 }
3864 }
3865 else
3866 {
3867 double area = 0;
3868
3869 for( BOARD_ITEM* item : board.Drawings() )
3870 area += static_cast<PCB_SHAPE*>( item )->GetPolyShape().Area();
3871
3872 for( BOARD_ITEM* item : fp->GraphicalItems() )
3873 area += static_cast<PCB_SHAPE*>( item )->GetPolyShape().Area();
3874
3875 BOOST_CHECK_CLOSE( area, expectedArea, 0.05 );
3876 }
3877 }
3878}
3879
3880
3881BOOST_AUTO_TEST_CASE( DashedEndedLinesBlockApproximationButAllowDroppingEndings )
3882{
3883 BOARD board;
3884 PCB_SHAPE* line = new PCB_SHAPE( &board, SHAPE_T::SEGMENT );
3885 line->SetStart( VECTOR2I( 0, 0 ) );
3886 line->SetEnd( VECTOR2I( 10000000, 0 ) );
3887 line->SetWidth( 200000 );
3890 board.Add( line );
3891 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
3892 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10, true ).IsBlocked() );
3893 DowngradeBoardInPlace( &board, kicad10, true );
3896}
3897
3898
3899BOOST_AUTO_TEST_CASE( CustomPropertiesBakeOnlyAffectedVariablesBeforeRemoval )
3900{
3901 for( bool footprintOnly : { false, true } )
3902 {
3903 BOARD board;
3904 FOOTPRINT* fp = new FOOTPRINT( &board );
3905 fp->SetReference( wxT( "42" ) );
3906 fp->SetCustomProperty( wxT( "Serial" ), wxT( "42" ) );
3907 fp->Value().SetText( wxT( "${PROPERTY.Reference}/${REFERENCE}" ) );
3908 fp->Reference().SetCustomProperty( wxT( "Owner" ), wxT( "Engineering" ) );
3909 PCB_TEXT* escaped = new PCB_TEXT( fp );
3910 escaped->SetText( wxT( "\\${PROPERTY.Serial}" ) );
3911 fp->Add( escaped );
3912 PCB_TEXT* expression = new PCB_TEXT( fp );
3913 expression->SetText( wxT( "@{${PROPERTY.Reference}+1}/${REFERENCE}" ) );
3914 fp->Add( expression );
3915 board.Add( fp );
3916 const auto report = ClassifyBoardForDowngrade( &board, kicad10 );
3917 checkFeature( report, wxT( "Custom properties" ), DOWNGRADE_BUCKET::DROP, 2 );
3918 BOOST_CHECK( !report.IsBlocked() );
3919
3920 if( footprintOnly )
3922 else
3923 DowngradeBoardInPlace( &board, kicad10 );
3924
3927 BOOST_CHECK_EQUAL( fp->Value().GetText(), wxString( "42/${REFERENCE}" ) );
3928 BOOST_CHECK_EQUAL( expression->GetText(), wxString( "43/${REFERENCE}" ) );
3929 BOOST_CHECK_EQUAL( escaped->GetText(), wxString( "\\${PROPERTY.Serial}" ) );
3930 }
3931}
3932
3933
3934BOOST_AUTO_TEST_CASE( UnresolvedPropertyVariablesBlockBothPolicies )
3935{
3936 BOARD board;
3937 FOOTPRINT* fp = new FOOTPRINT( &board );
3938 fp->Value().SetText( wxT( "${PROPERTY.Missing}" ) );
3939 board.Add( fp );
3940
3941 for( bool drop : { false, true } )
3942 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, drop ).IsBlocked() );
3943}
3944
3945
3946BOOST_AUTO_TEST_CASE( UsedProjectVariablesBakeInFootprintContextAndUnusedDefinitionsDoNotBlock )
3947{
3948 KI_TEST::SCOPED_TEMP_DIR tmp( "kicad_qa_property_dependencies" );
3949 const wxString projectPath = ( tmp.Path() / "source.kicad_pro" ).string();
3950
3951 {
3952 std::ofstream project( projectPath.ToStdString() );
3953 project << R"({"meta":{"version":4},"text_variables":{"SERIAL":"${PROPERTY.Reference}","ALIAS":"${SERIAL}","UNUSED":"${PROPERTY.Missing}"}})";
3954 }
3955
3956 SETTINGS_MANAGER settings;
3957 BOOST_REQUIRE( settings.LoadProject( projectPath, false ) );
3958 BOARD board;
3959 board.SetProject( settings.GetProject( projectPath ), true );
3960
3961 std::vector<FOOTPRINT*> footprints;
3962
3963 for( const wxString& serial : { wxT( "42" ), wxT( "73" ) } )
3964 {
3965 FOOTPRINT* fp = new FOOTPRINT( &board );
3966 fp->SetReference( serial );
3967 fp->SetCustomProperty( wxT( "Serial" ), serial );
3968 fp->Value().SetText( wxT( "${ALIAS}/${REFERENCE}" ) );
3969 board.Add( fp );
3970 footprints.push_back( fp );
3971 }
3972
3973 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
3974 DowngradeBoardInPlace( &board, kicad10 );
3975 BOOST_CHECK_EQUAL( footprints[0]->Value().GetText(), wxString( "42/${REFERENCE}" ) );
3976 BOOST_CHECK_EQUAL( footprints[1]->Value().GetText(), wxString( "73/${REFERENCE}" ) );
3977
3978 footprints[0]->Value().SetText( wxT( "${UNUSED}" ) );
3979 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
3980 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, true ).IsBlocked() );
3981}
3982
3983
3984BOOST_AUTO_TEST_CASE( CachedBoardVariableDependenciesBakeInFootprintContext )
3985{
3986 BOARD board;
3987 board.SetProperties( { { wxT( "SERIAL" ), wxT( "${PROPERTY.Reference}" ) },
3988 { wxT( "UNUSED" ), wxT( "${PROPERTY.Missing}" ) } } );
3989 FOOTPRINT* fp = new FOOTPRINT( &board );
3990 fp->SetReference( wxT( "42" ) );
3991 fp->Value().SetText( wxT( "${SERIAL}/${REFERENCE}" ) );
3992 board.Add( fp );
3993 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
3994 DowngradeBoardInPlace( &board, kicad10 );
3995 BOOST_CHECK_EQUAL( fp->Value().GetText(), wxString( "42/${REFERENCE}" ) );
3996}
3997
3998
3999BOOST_AUTO_TEST_CASE( MixedPropertyTextKeepsEscapedLiteralsAndSupportedVariables )
4000{
4001 BOARD board;
4002 FOOTPRINT* fp = new FOOTPRINT( &board );
4003 fp->SetReference( wxT( "42" ) );
4004 fp->SetCustomProperty( wxT( "Serial" ), wxT( "42" ) );
4005 fp->SetKeywords( wxT( "\\${REFERENCE}/\\@{1+2}" ) );
4006 fp->Value().SetText( wxT( "${PROPERTY.Reference}/\\${U1:PROPERTY.Missing}/${REFERENCE}" ) );
4007 PCB_TEXT* text = new PCB_TEXT( fp );
4008 text->SetText( wxT( "${PROPERTY.Keywords}/${REFERENCE}" ) );
4009 fp->Add( text );
4010 board.Add( fp );
4011 const wxString shown = text->GetShownText( FOR_CANVAS );
4012 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
4013 DowngradeBoardInPlace( &board, kicad10 );
4014 BOOST_CHECK_EQUAL( fp->Value().GetText(), wxString( "42/\\${U1:PROPERTY.Missing}/${REFERENCE}" ) );
4015 BOOST_CHECK( !text->GetText().Contains( wxT( "PROPERTY." ) ) );
4016 BOOST_CHECK_EQUAL( text->GetShownText( FOR_CANVAS ), shown );
4017}
4018
4019
4020BOOST_AUTO_TEST_CASE( NewExpressionUnitAliasIsBakedWithoutFreezingOtherVariables )
4021{
4022 BOARD board;
4023 FOOTPRINT* fp = new FOOTPRINT( &board );
4024 fp->SetReference( wxT( "U1" ) );
4025 fp->Value().SetText( wxT( "@{1000mils}/${REFERENCE}" ) );
4026 board.Add( fp );
4027 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
4028 DowngradeBoardInPlace( &board, kicad10 );
4029 BOOST_CHECK_EQUAL( fp->Value().GetText(), wxString( "25.4/${REFERENCE}" ) );
4030}
4031
4032
4033BOOST_AUTO_TEST_CASE( UnresolvedAffectedExpressionsBlockBothPolicies )
4034{
4035 for( const wxString& raw :
4036 { wxT( "@{${PROPERTY.Reference}+${MISSING}}" ), wxT( "@{unknown_function(${PROPERTY.Reference})}" ) } )
4037 {
4038 BOARD board;
4039 FOOTPRINT* fp = new FOOTPRINT( &board );
4040 fp->SetReference( wxT( "42" ) );
4041 fp->SetCustomProperty( wxT( "Serial" ), wxT( "42" ) );
4042 fp->Value().SetText( raw );
4043 board.Add( fp );
4044
4045 for( bool drop : { false, true } )
4046 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, drop ).IsBlocked() );
4047 }
4048}
4049
4050
4051BOOST_AUTO_TEST_CASE( EscapedTextControlsBlockKicad9AndRemainLiteralInKicad10 )
4052{
4053 for( bool inProperty : { false, true } )
4054 {
4055 BOARD board;
4056 FOOTPRINT* fp = new FOOTPRINT( &board );
4057 fp->SetReference( wxT( "U1" ) );
4058 const wxString literal = wxT( "\\${REFERENCE}/\\@{1+2}" );
4059 fp->SetKeywords( literal );
4060 fp->Value().SetText( inProperty ? wxString( wxT( "${PROPERTY.Keywords}" ) ) : literal );
4061 board.Add( fp );
4062 const wxString shown = fp->Value().GetShownText( FOR_CANVAS );
4063
4064 for( bool drop : { false, true } )
4065 {
4066 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad9, drop ).IsBlocked() );
4067 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10, drop ).IsBlocked() );
4068 }
4069
4070 DowngradeBoardInPlace( &board, kicad10 );
4072 }
4073}
4074
4075
4076BOOST_AUTO_TEST_CASE( TitleBlockExpressionsBakeBeforeDependentFootprintText )
4077{
4078 for( bool drop : { false, true } )
4079 {
4080 BOARD board;
4081 board.GetTitleBlock().SetTitle( wxT( "@{1000mils}" ) );
4082 FOOTPRINT* fp = new FOOTPRINT( &board );
4083 fp->SetReference( wxT( "U1" ) );
4084 fp->Value().SetText( wxT( "${TITLE}/${REFERENCE}" ) );
4085 board.Add( fp );
4086 const auto report = ClassifyBoardForDowngrade( &board, kicad10, drop );
4087 BOOST_CHECK( !report.IsBlocked() );
4088 checkFeature( report, wxT( "Post-target text variables" ), DOWNGRADE_BUCKET::DROP, 2 );
4089 DowngradeBoardInPlace( &board, kicad10, drop );
4090 BOOST_CHECK_EQUAL( board.GetTitleBlock().GetTitle(), wxString( "25.4" ) );
4091 BOOST_CHECK_EQUAL( fp->Value().GetText(), wxString( "25.4/${REFERENCE}" ) );
4092 }
4093}
4094
4095
4096BOOST_AUTO_TEST_CASE( TitleBlockUnresolvablePropertyContextBlocksBothPolicies )
4097{
4098 BOARD board;
4099 board.GetTitleBlock().SetComment( 0, wxT( "${PROPERTY.Reference}" ) );
4100
4101 for( bool drop : { false, true } )
4102 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, drop ).IsBlocked() );
4103}
4104
4105
4106BOOST_AUTO_TEST_CASE( TitleBlockSelfReferenceDoesNotHideUsedProjectDependencies )
4107{
4108 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_title_dependencies" );
4109 const wxString projectPath = ( temporary.Path() / "source.kicad_pro" ).string();
4110
4111 {
4112 std::ofstream project( projectPath.ToStdString() );
4113 project << R"({"meta":{"version":4},"text_variables":{"TITLE":"${PROPERTY.Reference}"}})";
4114 }
4115
4116 SETTINGS_MANAGER settings;
4117 BOOST_REQUIRE( settings.LoadProject( projectPath, false ) );
4118 BOARD board;
4119 board.SetProject( settings.GetProject( projectPath ), true );
4120 board.GetTitleBlock().SetTitle( wxT( "${TITLE}" ) );
4121 FOOTPRINT* fp = new FOOTPRINT( &board );
4122 fp->SetReference( wxT( "42" ) );
4123 fp->Value().SetText( wxT( "${TITLE}" ) );
4124 board.Add( fp );
4125 BOOST_CHECK_EQUAL( fp->Value().GetShownText( FOR_CANVAS ), wxString( "42" ) );
4126
4127 for( bool drop : { false, true } )
4128 BOOST_CHECK( ClassifyBoardForDowngrade( &board, kicad10, drop ).IsBlocked() );
4129
4130 board.GetTitleBlock().SetTitle( wxT( "Ordinary title" ) );
4131 const auto report = ClassifyBoardForDowngrade( &board, kicad10 );
4132 BOOST_CHECK( !report.IsBlocked() );
4133 BOOST_CHECK( !report.IsLossy() );
4134}
4135
4136
4137BOOST_AUTO_TEST_CASE( AffectedTableExpressionsUseNativeCellCoordinates )
4138{
4139 BOARD board;
4140 FOOTPRINT* fp = new FOOTPRINT( &board );
4141 fp->SetReference( wxT( "42" ) );
4142 board.Add( fp );
4143 PCB_TABLE* table = new PCB_TABLE( fp );
4144 table->SetColCount( 1 );
4145 table->SetColWidth( 0, 10000000 );
4146 table->SetRowHeight( 0, 6000000 );
4147 PCB_TABLECELL* cell = new PCB_TABLECELL( table );
4148 cell->SetText( wxT( "@{${PROPERTY.Reference}+${ROW}}/${COL}/${REFERENCE}" ) );
4149 table->AddCell( cell );
4150 fp->Add( table );
4151 BOOST_CHECK( !ClassifyBoardForDowngrade( &board, kicad10 ).IsBlocked() );
4152 DowngradeBoardInPlace( &board, kicad10 );
4153 BOOST_CHECK_EQUAL( cell->GetText(), wxString( "43/${COL}/${REFERENCE}" ) );
4154}
4155
4156
4157BOOST_AUTO_TEST_CASE( FootprintFileUsesTheSamePostMasterPoliciesAsBoardFootprints )
4158{
4159 SETTINGS_MANAGER settingsManager;
4160 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_fp_post_master" );
4161 const wxString source = ( temporary.Path() / "source.kicad_mod" ).string();
4162 FOOTPRINT footprint( nullptr );
4163 footprint.SetReference( wxT( "42" ) );
4164 footprint.Value().SetText( wxT( "${PROPERTY.Reference}/${REFERENCE}" ) );
4165 footprint.SetCustomProperty( wxT( "Owner" ), wxT( "QA" ) );
4166 footprint.SetExcludedFromSim( true );
4167 PCB_SHAPE* line = new PCB_SHAPE( &footprint, SHAPE_T::SEGMENT );
4168 line->SetStart( VECTOR2I( 0, 0 ) );
4169 line->SetEnd( VECTOR2I( 10000000, 0 ) );
4170 line->SetWidth( 200000 );
4171 line->SetLayer( F_SilkS );
4173 footprint.Add( line );
4174 PCB_CONSTRAINT* constraint = new PCB_CONSTRAINT( &footprint, PCB_CONSTRAINT_TYPE::HORIZONTAL );
4175 constraint->AddMember( line->m_Uuid );
4176 footprint.Add( constraint );
4178 io.FootprintSave( source, &footprint );
4179
4180 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4181 {
4182 for( bool drop : { false, true } )
4183 {
4184 const wxString destination = ( temporary.Path() / "out.kicad_mod" ).string();
4185 BOOST_REQUIRE( DowngradeFootprintFileToTemp( source, destination, target, drop )
4187 wxString name;
4188 auto converted = io.ImportFootprint( destination, name );
4189 BOOST_REQUIRE( converted );
4190 BOOST_CHECK( converted->Constraints().empty() );
4191 BOOST_CHECK( !converted->HasCustomProperties() );
4192 BOOST_CHECK( !converted->IsExcludedFromSim() );
4193 BOOST_CHECK_EQUAL( converted->Value().GetText(), wxString( "42/${REFERENCE}" ) );
4194 BOOST_REQUIRE( !converted->GraphicalItems().empty() );
4195
4196 for( BOARD_ITEM* item : converted->GraphicalItems() )
4197 {
4198 BOOST_REQUIRE( item->Type() == PCB_SHAPE_T );
4199 const PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
4201 BOOST_CHECK( shape->GetShape() == ( drop ? SHAPE_T::SEGMENT : SHAPE_T::POLY ) );
4202 }
4203 }
4204 }
4205}
4206
4207
4208BOOST_AUTO_TEST_CASE( SimulationExclusionsFollowSelectedVariantAndReportTheirLoss )
4209{
4210 for( bool drop : { false, true } )
4211 {
4212 BOARD board;
4213 FOOTPRINT* fp = new FOOTPRINT( &board );
4214 fp->SetExcludedFromSim( false );
4215 fp->AddVariant( wxT( "selected" ) )->SetExcludedFromSim( true );
4216 board.Add( fp );
4217 FlattenBoardVariant( &board, wxT( "selected" ) );
4219 const auto report = ClassifyBoardForDowngrade( &board, kicad10, drop );
4220 checkFeature( report, wxT( "Footprint simulation exclusions" ), DOWNGRADE_BUCKET::DROP, 1 );
4221 DowngradeBoardInPlace( &board, kicad10, drop );
4223 for( const auto& [name, variant] : fp->GetVariants() )
4224 BOOST_CHECK( !variant.GetExcludedFromSim() );
4225 }
4226}
4227
4228
4229BOOST_AUTO_TEST_CASE( LegacyBoldWidthsPreserveNestedTextAndDoNotMutateSource )
4230{
4231 SETTINGS_MANAGER settingsManager;
4232 BOARD board;
4233 FOOTPRINT* fp = new FOOTPRINT( &board );
4234 board.Add( fp );
4235 std::vector<EDA_TEXT*> bold;
4236 PCB_TEXT* text = new PCB_TEXT( &board );
4237 text->SetText( wxT( "board bold" ) );
4238 board.Add( text );
4239 bold.push_back( text );
4240 fp->Value().SetText( wxT( "footprint bold" ) );
4241 bold.push_back( &fp->Value() );
4242 PCB_TEXT* fpText = new PCB_TEXT( fp );
4243 fpText->SetText( wxT( "graphic bold" ) );
4244 fp->Add( fpText );
4245 bold.push_back( fpText );
4246 PCB_TABLE* table = new PCB_TABLE( fp, 100000 );
4247 table->SetColCount( 1 );
4248 table->SetColWidth( 0, 10000000 );
4249 table->SetRowHeight( 0, 5000000 );
4250 PCB_TABLECELL* cell = new PCB_TABLECELL( table );
4251 cell->SetText( wxT( "cell bold" ) );
4252 table->AddCell( cell );
4253 fp->Add( table );
4254 bold.push_back( cell );
4255 PCB_DIM_ALIGNED* dimension = new PCB_DIM_ALIGNED( &board );
4256 dimension->SetStart( VECTOR2I( 0, 0 ) );
4257 dimension->SetEnd( VECTOR2I( 10000000, 0 ) );
4258 dimension->SetHeight( 2000000 );
4259 dimension->ChangeOverrideText( wxT( "dimension bold" ) );
4260 board.Add( dimension );
4261 bold.push_back( dimension );
4262
4263 for( EDA_TEXT* item : bold )
4264 {
4265 item->SetBold( true );
4266 item->SetTextThickness( 100000 );
4267 }
4268
4269 PCB_TEXT* automatic = new PCB_TEXT( &board );
4270 automatic->SetText( wxT( "auto bold" ) );
4271 automatic->SetBold( true );
4272 automatic->SetTextThickness( 0 );
4273 board.Add( automatic );
4274 PCB_TEXT* outline = new PCB_TEXT( &board );
4275 outline->SetText( wxT( "outline bold" ) );
4276 outline->SetFont( KIFONT::FONT::GetFont( wxT( "DejaVu Sans" ), true ) );
4277 outline->SetBold( true );
4278 outline->SetTextThickness( 100000 );
4279 board.Add( outline );
4280 const bool outlineAvailable = outline->GetFont() && outline->GetFont()->IsOutline();
4281 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_legacy_bold_widths" );
4282
4283 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4284 {
4285 const std::string first = ( temporary.Path() / ( target.m_id.ToStdString() + "-first.kicad_pcb" ) ).string();
4286 const std::string second = ( temporary.Path() / ( target.m_id.ToStdString() + "-second.kicad_pcb" ) ).string();
4287 SaveBoardForTarget( &board, first, target );
4288 SaveBoardForTarget( &board, second, target );
4289 const std::string content = KI_TEST::ReadGoldenText( first );
4290 BOOST_CHECK( content.find( "(thickness 0.16)" ) != std::string::npos );
4291 BOOST_CHECK( content == KI_TEST::ReadGoldenText( second ) );
4292
4293 for( EDA_TEXT* item : bold )
4294 BOOST_CHECK_EQUAL( item->GetTextThickness(), 100000 );
4295
4296 BOOST_CHECK_EQUAL( automatic->GetTextThickness(), 0 );
4297 BOOST_CHECK_EQUAL( outline->GetTextThickness(), 100000 );
4299 auto reloaded = io.LoadBoard( first );
4300 BOOST_REQUIRE( reloaded );
4301 size_t checked = 0;
4302 reloaded->RunOnChildren(
4303 [&]( BOARD_ITEM* item )
4304 {
4305 EDA_TEXT* reloadedText = dynamic_cast<EDA_TEXT*>( item );
4306
4307 if( !reloadedText || !reloadedText->IsBold() )
4308 return;
4309
4310 if( reloadedText->GetText() == wxT( "auto bold" ) )
4311 BOOST_CHECK_EQUAL( reloadedText->GetTextThickness(), 0 );
4312 else if( reloadedText->GetText() != wxT( "outline bold" ) || outlineAvailable )
4313 BOOST_CHECK_EQUAL( reloadedText->GetTextThickness(), 100000 );
4314
4315 ++checked;
4316 },
4318 BOOST_CHECK_EQUAL( checked, bold.size() + 2 );
4319 }
4320}
4321
4322
4323BOOST_AUTO_TEST_CASE( ComplexPadstackFrontAndInnerCustomOptionsRoundTripToKicad10 )
4324{
4325 SETTINGS_MANAGER settingsManager;
4326 BOARD board;
4327 board.SetCopperLayerCount( 4 );
4328 FOOTPRINT* fp = new FOOTPRINT( &board );
4329 PAD* pad = new PAD( fp );
4330 pad->SetAttribute( PAD_ATTRIB::PTH );
4331 pad->SetLayerSet( LSET::AllCuMask() );
4332 pad->Padstack().SetMode( PADSTACK::MODE::CUSTOM );
4333 pad->SetShape( F_Cu, PAD_SHAPE::OVAL );
4334 pad->SetSize( F_Cu, VECTOR2I( 2000000, 1000000 ) );
4335 pad->SetShape( In1_Cu, PAD_SHAPE::CUSTOM );
4336 pad->SetSize( In1_Cu, VECTOR2I( 500000, 500000 ) );
4337 pad->SetCustomShapeInZoneOpt( CUSTOM_SHAPE_ZONE_MODE::CONVEXHULL );
4338 PCB_SHAPE* primitive = new PCB_SHAPE( pad, SHAPE_T::SEGMENT );
4339 primitive->SetStart( VECTOR2I( -1000000, 0 ) );
4340 primitive->SetEnd( VECTOR2I( 1000000, 0 ) );
4341 primitive->SetWidth( 200000 );
4342 pad->AddPrimitive( In1_Cu, primitive );
4343 pad->SetDrillSize( VECTOR2I( 300000, 300000 ) );
4344 fp->Add( pad );
4345 board.Add( fp );
4346 KI_TEST::SCOPED_TEMP_DIR temporary( "kicad_qa_complex_pad_front" );
4347 const std::string path = ( temporary.Path() / "out.kicad_pcb" ).string();
4348 SaveBoardForTarget( &board, path, kicad10 );
4350 auto reloaded = io.LoadBoard( path );
4351 BOOST_REQUIRE( reloaded && reloaded->Footprints().size() == 1 );
4352 BOOST_REQUIRE_EQUAL( reloaded->Footprints()[0]->Pads().size(), 1 );
4353 const PAD* result = reloaded->Footprints()[0]->Pads()[0];
4354 BOOST_CHECK( result->GetShape( F_Cu ) == PAD_SHAPE::OVAL );
4355 BOOST_CHECK( result->GetSize( F_Cu ) == VECTOR2I( 2000000, 1000000 ) );
4356 BOOST_CHECK( result->GetShape( In1_Cu ) == PAD_SHAPE::CUSTOM );
4357 BOOST_REQUIRE_EQUAL( result->GetPrimitives( In1_Cu ).size(), 1 );
4358 BOOST_CHECK( result->GetCustomShapeInZoneOpt() == CUSTOM_SHAPE_ZONE_MODE::CONVEXHULL );
4359}
4360
4361
4362BOOST_AUTO_TEST_CASE( CurrentProjectSchemasAndSupportedDrcExclusionsMigrateForBothTargets )
4363{
4364 const nlohmann::json exclusion = { { "marker",
4365 { { "error_type", "DRCET_CLEARANCE" },
4366 { "position", { { "x_nm", "123" }, { "y_nm", "-456" } } },
4367 { "items",
4368 { { { "value", "11111111-1111-1111-1111-111111111111" } },
4369 { { "value", "22222222-2222-2222-2222-222222222222" } } } } } },
4370 { "comment", "accepted" } };
4371
4372 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4373 {
4374 nlohmann::json doc = {
4375 { "meta", { { "version", 4 } } },
4376 { "board",
4377 { { "design_settings", { { "meta", { { "version", 3 } } }, { "drc_exclusions", { exclusion } } } } } }
4378 };
4379 COMPATIBILITY_REPORT report;
4380 DowngradeProjectFileJson( doc, target, report );
4381 BOOST_CHECK_EQUAL( doc["meta"]["version"].get<int>(), 3 );
4382 const auto& settings = doc["board"]["design_settings"];
4383 BOOST_CHECK_EQUAL( settings["meta"]["version"].get<int>(), 2 );
4384 BOOST_REQUIRE_EQUAL( settings["drc_exclusions"].size(), 1 );
4386 settings["drc_exclusions"][0][0].get<std::string>(),
4387 "clearance|123|-456|11111111-1111-1111-1111-111111111111|22222222-2222-2222-2222-222222222222" );
4388 BOOST_CHECK_EQUAL( settings["drc_exclusions"][0][1].get<std::string>(), "accepted" );
4389 BOOST_CHECK( !report.IsLossy() );
4390 const auto migrated = doc;
4391 COMPATIBILITY_REPORT second;
4392 DowngradeProjectFileJson( doc, target, second );
4393 BOOST_CHECK( doc == migrated );
4394 BOOST_CHECK( !second.IsLossy() );
4395 }
4396}
4397
4398
4399BOOST_AUTO_TEST_CASE( UnrepresentableDrcExclusionsDropWithReports )
4400{
4401 nlohmann::json multiple = { { "marker",
4402 { { "error_type", "DRCET_CLEARANCE" },
4403 { "position", { { "x_nm", "123" }, { "y_nm", "-456" } } },
4404 { "items",
4405 { { { "value", "11111111-1111-1111-1111-111111111111" } },
4406 { { "value", "22222222-2222-2222-2222-222222222222" } },
4407 { { "value", "33333333-3333-3333-3333-333333333333" } } } } } },
4408 { "comment", "three items" } };
4409 nlohmann::json unknown = multiple;
4410 unknown["marker"]["error_type"] = "DRCET_MICROVIA_STACK_DEPTH";
4411 unknown["marker"]["items"].erase( 2 );
4412
4413 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4414 {
4415 nlohmann::json doc = {
4416 { "board",
4417 { { "design_settings",
4418 { { "meta", { { "version", 3 } } }, { "drc_exclusions", { multiple, unknown, "malformed" } } } } } }
4419 };
4420 COMPATIBILITY_REPORT report;
4421 DowngradeProjectFileJson( doc, target, report );
4422 BOOST_CHECK( doc["board"]["design_settings"]["drc_exclusions"].empty() );
4424 }
4425}
4426
4427
4428BOOST_AUTO_TEST_CASE( PostMasterProjectSettingsReportOnlyMeaningfulLosses )
4429{
4430 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4431 {
4432 nlohmann::json doc;
4433 doc["net_settings"]["net_chain_netclasses"] = { { { "name", "fast" } } };
4434 doc["board"]["design_settings"]["via_stack_presets"] = { { { "name", "fanout" } } };
4435 doc["board"]["design_settings"]["teardrop_parameters"] = {
4436 { { "td_target_name", "td_track_end" }, { "td_enabled", true }, { "td_max_len", 1.0 } },
4437 { { "td_enabled", false } }
4438 };
4439 COMPATIBILITY_REPORT report;
4440 DowngradeProjectFileJson( doc, target, report );
4441 BOOST_CHECK( !doc["net_settings"].contains( "net_chain_netclasses" ) );
4442 const auto& settings = doc["board"]["design_settings"];
4443 BOOST_CHECK( !settings.contains( "via_stack_presets" ) );
4444 BOOST_CHECK( !settings["teardrop_parameters"][0].contains( "td_enabled" ) );
4445 BOOST_CHECK( !settings["teardrop_parameters"][1].contains( "td_enabled" ) );
4446 BOOST_CHECK_EQUAL( settings["teardrop_parameters"][0]["td_max_len"].get<double>(), 1.0 );
4448 COMPATIBILITY_REPORT second;
4449 DowngradeProjectFileJson( doc, target, second );
4450 BOOST_CHECK( !second.IsLossy() );
4451
4452 nlohmann::json defaults;
4453 defaults["net_settings"]["net_chain_netclasses"] = nlohmann::json::array();
4454 defaults["board"]["design_settings"]["via_stack_presets"] = nlohmann::json::array();
4455 defaults["board"]["design_settings"]["teardrop_parameters"] = { { { "td_enabled", false } } };
4456 COMPATIBILITY_REPORT silent;
4457 DowngradeProjectFileJson( defaults, target, silent );
4458 BOOST_CHECK( !silent.IsLossy() );
4459 }
4460}
4461
4462
4463BOOST_AUTO_TEST_CASE( NewTuningBridgeDelayIsRemovedAndReportedForKicad10 )
4464{
4465 nlohmann::json doc = {
4466 { "tuning_profiles",
4467 { { "meta", { { "version", 2 } } },
4468 { "tuning_profiles_impedance_geometric",
4469 { { { "net_chain_bridge_prop_delay", 25 } }, { { "net_chain_bridge_prop_delay", 0 } } } } } }
4470 };
4471 COMPATIBILITY_REPORT report;
4472 DowngradeProjectFileJson( doc, kicad10, report );
4473 BOOST_CHECK_EQUAL( doc["tuning_profiles"]["meta"]["version"].get<int>(), 0 );
4475
4476 for( const auto& profile : doc["tuning_profiles"]["tuning_profiles_impedance_geometric"] )
4477 BOOST_CHECK( !profile.contains( "net_chain_bridge_prop_delay" ) );
4478}
4479
4480
4481BOOST_AUTO_TEST_CASE( NativeNetChainClassMapReportsOnlyNonemptyMappings )
4482{
4483 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4484 {
4485 nlohmann::json doc;
4486 doc["net_settings"]["net_chain_classes"] = { { "clock", "Fast" } };
4487 COMPATIBILITY_REPORT report;
4488 DowngradeProjectFileJson( doc, target, report );
4489 BOOST_CHECK( !doc["net_settings"].contains( "net_chain_classes" ) );
4491 COMPATIBILITY_REPORT second;
4492 DowngradeProjectFileJson( doc, target, second );
4493 BOOST_CHECK( !second.IsLossy() );
4494 doc["net_settings"]["net_chain_classes"] = nlohmann::json::object();
4496 DowngradeProjectFileJson( doc, target, empty );
4497 BOOST_CHECK( !empty.IsLossy() );
4498 }
4499}
4500
4501
4502// A word the generated vocabulary lists must never be the reason a rule is dropped. That is the
4503// direction a generator mistake would take, silently losing a rule the target can read.
4504BOOST_AUTO_TEST_CASE( ReleaseVocabularyKeepsEveryRuleTheReleaseCouldRead )
4505{
4506 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4507 {
4508 const DRC_RULE_VOCABULARY* vocabulary = FindDrcRuleVocabulary( target );
4509 BOOST_REQUIRE( vocabulary );
4510
4511 for( size_t i = 0; i < vocabulary->m_functionCount; i++ )
4512 {
4513 const wxString name = wxString::FromUTF8( vocabulary->m_functions[i] );
4514
4515 if( std::any_of( std::begin( DRC_RULE_SEMANTIC_BREAKS ), std::end( DRC_RULE_SEMANTIC_BREAKS ),
4516 [&]( const char* aBreak )
4517 {
4518 return name == aBreak;
4519 } ) )
4520 continue;
4521
4522 const wxString rule = wxT( "(version 1)(rule \"f\" (condition \"A." ) + name
4523 + wxT( "('x')\") (constraint clearance (min 0.2mm)))" );
4524
4525 BOOST_CHECK_MESSAGE( FilterDrcRulesForTarget( rule, target ).m_dropped.empty(),
4526 target.m_id + " dropped a rule calling " + name );
4527 }
4528
4529 for( size_t i = 0; i < vocabulary->m_propertyCount; i++ )
4530 {
4531 const wxString name = wxString::FromUTF8( vocabulary->m_properties[i] );
4532 const wxString rule = wxT( "(version 1)(rule \"p\" (condition \"A." ) + name
4533 + wxT( " == 1\") (constraint clearance (min 0.2mm)))" );
4534
4535 BOOST_CHECK_MESSAGE( FilterDrcRulesForTarget( rule, target ).m_dropped.empty(),
4536 target.m_id + " dropped a rule reading " + name );
4537 }
4538 }
4539}
4540
4541
4542// Adding a downgrade target without rerunning tools/generate_drc_rules_vocabulary.py must fail here.
4543BOOST_AUTO_TEST_CASE( EveryDowngradeTargetHasARuleVocabulary )
4544{
4545 for( const DOWNGRADE_TARGET& target : GetDowngradeTargets() )
4546 {
4547 BOOST_CHECK_MESSAGE( FindDrcRuleVocabulary( target ),
4548 target.m_name + " has no entry in include/drc_rules_release_vocabulary.h" );
4549 }
4550}
4551
4552
4553// A registered property is only usable if the release's evaluator can read its type. Priority
4554// is unsigned and Hatch Orientation an angle, neither readable before 11, while an enum always is.
4555BOOST_AUTO_TEST_CASE( PropertiesTheReleaseCannotEvaluateAreDropped )
4556{
4557 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4558 {
4559 for( const wxString& property : { wxT( "A.Priority > 1" ), wxT( "A.Hatch_Orientation == 0" ),
4560 wxT( "A.Line_Color == 'red'" ) } )
4561 {
4562 const auto result = FilterDrcRulesForTarget( wxT( "(version 1)(rule \"typed\" (condition \"" ) + property
4563 + wxT( "\") (constraint clearance (min 0.2mm)))" ),
4564 target );
4565 BOOST_CHECK_MESSAGE( result.m_dropped.size() == 1, target.m_id + " kept " + property );
4566 }
4567
4568 const auto kept = FilterDrcRulesForTarget( wxT( "(version 1)(rule \"enum\" (condition \"A.Pad_Type == 'PTH'\") "
4569 "(constraint clearance (min 0.2mm)))" ),
4570 target );
4571 BOOST_CHECK( kept.m_dropped.empty() );
4572 }
4573}
4574
4575
4576// A unit may stand apart from its number. That is a value, not a keyword the target lacks.
4577BOOST_AUTO_TEST_CASE( SpacedUnitsAreNotMistakenForKeywords )
4578{
4579 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4580 {
4581 const auto kept = FilterDrcRulesForTarget(
4582 wxT( "(version 1)(rule \"spaced\" (constraint clearance (min 0.2 mm) (opt 0.3 mil) (max 1 in)))" ),
4583 target );
4584 BOOST_CHECK_MESSAGE( kept.m_dropped.empty(), target.m_id + " dropped a rule with a spaced unit" );
4585
4586 // A unit the target cannot read is still caught when it stands apart.
4587 const auto dropped = FilterDrcRulesForTarget(
4588 wxT( "(version 1)(rule \"delay\" (constraint skew (max 5 ps)))" ), target );
4589 BOOST_CHECK_EQUAL( dropped.m_dropped.size(), target.m_id == wxT( "9.0" ) ? 1 : 0 );
4590 }
4591}
4592
4593
4594// 9.0 reads neither degrees nor picoseconds, and knows nothing of text variables. 10.0 has all three.
4595BOOST_AUTO_TEST_CASE( UnitsAndTextVariablesFollowWhatTheReleaseParses )
4596{
4597 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4598 {
4599 const bool old = target.m_id == wxT( "9.0" );
4600
4601 auto angle = FilterDrcRulesForTarget(
4602 wxT( "(version 1)(rule \"a\" (constraint track_angle (max 45deg)))" ), target );
4603 BOOST_CHECK_EQUAL( angle.m_dropped.size(), old ? 1 : 0 );
4604
4605 auto delay = FilterDrcRulesForTarget( wxT( "(version 1)(rule \"d\" (constraint skew (max 5ps)))" ), target );
4606 BOOST_CHECK_EQUAL( delay.m_dropped.size(), old ? 1 : 0 );
4607
4608 for( const wxString& rule : { wxT( "(rule \"v\" (constraint clearance (min ${GAP})))" ),
4609 wxT( "(rule \"c\" (condition \"A.NetName == '${NET}'\") "
4610 "(constraint clearance (min 0.2mm)))" ) } )
4611 {
4612 auto variable = FilterDrcRulesForTarget( wxT( "(version 1)" ) + rule, target );
4613 BOOST_CHECK_EQUAL( variable.m_dropped.size(), old ? 1 : 0 );
4614 }
4615 }
4616}
4617
4618
4619BOOST_AUTO_TEST_CASE( WordsAddedInAPointReleaseAreNotInTheSeriesVocabulary )
4620{
4621 for( const wxString& expression : { wxT( "A.hasExactNetclass('x')" ), wxT( "A.Column_Width == 1" ),
4622 wxT( "A.Visible == 1" ) } )
4623 {
4624 const wxString rule = wxT( "(version 1)(rule \"r\" (condition \"" ) + expression
4625 + wxT( "\") (constraint clearance (min 0.2mm)))" );
4626 BOOST_CHECK_MESSAGE( FilterDrcRulesForTarget( rule, kicad9 ).m_dropped.size() == 1,
4627 "9.0 kept " + expression + " which not every 9.0.x release reads" );
4628 }
4629
4630 for( const wxString& expression : { wxT( "A.intersectsKeepout('x')" ), wxT( "A.Origin_X == 1" ) } )
4631 {
4632 const wxString rule = wxT( "(version 1)(rule \"r\" (condition \"" ) + expression
4633 + wxT( "\") (constraint clearance (min 0.2mm)))" );
4634 BOOST_CHECK_MESSAGE( FilterDrcRulesForTarget( rule, kicad10 ).m_dropped.size() == 1,
4635 "10.0 kept " + expression + " which not every 10.0.x release reads" );
4636 }
4637}
4638
4639
4640// A layer may be given unquoted, and a user layer name is not a grammar keyword.
4641BOOST_AUTO_TEST_CASE( UnquotedLayerNamesAreNotMistakenForKeywords )
4642{
4643 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4644 {
4645 for( const wxString& layer : { wxT( "MyCustomLayer" ), wxT( "F.Cu" ), wxT( "\"In1.Cu\"" ), wxT( "outer" ) } )
4646 {
4647 const auto result = FilterDrcRulesForTarget( wxT( "(version 1)(rule \"on layer\" (layer " ) + layer
4648 + wxT( ") (constraint clearance (min 0.2mm)))" ),
4649 target );
4650 BOOST_CHECK_MESSAGE( result.m_dropped.empty(), target.m_id + " dropped a rule on layer " + layer );
4651 }
4652 }
4653}
4654
4655
4656BOOST_AUTO_TEST_CASE( MissingRuleVocabularyFailsClosed )
4657{
4659 unknown.m_id = wxT( "0.0" );
4660 unknown.m_name = wxT( "KiCad 0.0" );
4661
4662 const auto result =
4663 FilterDrcRulesForTarget( wxT( "(version 1)(rule \"r\" (constraint clearance (min 0.2mm)))" ), unknown );
4664
4665 BOOST_CHECK( !result.m_error.IsEmpty() );
4666 BOOST_CHECK( result.m_text.IsEmpty() );
4667}
4668
4669
4670BOOST_AUTO_TEST_CASE( NewDrcConstraintsAndFunctionsAreFilteredWithoutLiteralFalsePositives )
4671{
4672 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4673 {
4674 for( const wxString& keyword : { wxT( "hole_aspect_ratio" ), wxT( "microvia_stack_depth" ) } )
4675 {
4676 const wxString rule = "(version 1)(rule \"new\" (constraint " + keyword + " (max 2)))";
4677 const auto result = FilterDrcRulesForTarget( rule, target );
4678 BOOST_CHECK( result.m_error.IsEmpty() );
4679 BOOST_CHECK_EQUAL( result.m_dropped.size(), 1 );
4680 }
4681
4682 for( const wxString& call :
4683 { wxT( "A.intersectsKeepout('x')" ), wxT( "A.intersectsArea('x')" ), wxT( "A.isStackedVia()" ),
4684 wxT( "A.ISSTACKEDVIA()" ), wxT( "A.customProperty('Owner') == 'Team'" ),
4685 wxT( "A.hasCustomProperty('Owner')" ) } )
4686 {
4687 for( const wxString& expression : { wxT( "condition" ), wxT( "assertion" ) } )
4688 {
4689 const wxString rule =
4690 expression == wxT( "condition" )
4691 ? "(rule \"new\" (condition \"" + call + "\") (constraint clearance (min 0.2mm)))"
4692 : "(rule \"new\" (constraint assertion \"" + call + "\"))";
4693 const auto result = FilterDrcRulesForTarget( wxT( "(version 1)" ) + rule, target );
4694 BOOST_CHECK( result.m_error.IsEmpty() );
4695 BOOST_CHECK_EQUAL( result.m_dropped.size(), 1 );
4696 }
4697 }
4698
4699 const wxString kept = wxT( "(rule \"customProperty\" (condition \"A.NetName == 'isStackedVia()'\") "
4700 "(constraint clearance (min 0.2mm)))\n"
4701 "(rule \"literal\" (condition \"A.NetName == 'intersectsArea()'\") "
4702 "(constraint clearance (min 0.2mm)))\n"
4703 "(rule \"uppercase literal\" (condition \"A.NetName == 'ISSTACKEDVIA()'\") "
4704 "(constraint clearance (min 0.2mm)))\n"
4705 "(rule \"legacy\" (condition \"A.insideArea('x')\") "
4706 "(constraint clearance (min 0.2mm)))\n"
4707 "(rule \"position\" (condition \"A.Start_X > 1mm && A.Start_Y > 1mm\") "
4708 "(constraint clearance (min 0.2mm)))" );
4709 const auto result = FilterDrcRulesForTarget( wxT( "(version 1)\n" ) + kept, target );
4710 BOOST_CHECK( result.m_error.IsEmpty() );
4711 BOOST_CHECK( result.m_dropped.empty() );
4712 BOOST_CHECK( result.m_text.Contains( kept ) );
4713 }
4714}
4715
4716
4717BOOST_AUTO_TEST_CASE( DrcPostTargetPropertiesAreGuardedInConditionsAndAssertions )
4718{
4719 for( const DOWNGRADE_TARGET& target : { kicad9, kicad10 } )
4720 {
4721 for( const wxString& kind : { wxT( "condition" ), wxT( "assertion" ) } )
4722 {
4723 const wxString expression = wxT( "A.Parent == A.Parent && A.NetName != 'A.parent.Reference'" );
4724 const wxString body =
4725 kind == wxT( "condition" )
4726 ? wxT( "(condition \"" ) + expression + wxT( "\") (constraint clearance (min 0.2mm))" )
4727 : wxT( "(constraint assertion \"" ) + expression + wxT( "\")" );
4728 const auto parent =
4729 FilterDrcRulesForTarget( wxT( "(version 1)(rule \"parent property\" " ) + body + ")", target );
4730 BOOST_CHECK( parent.m_error.IsEmpty() );
4731 BOOST_CHECK( parent.m_dropped.empty() );
4732 }
4733
4734 for( const wxString& property :
4735 { wxT( "A.Start_Shape" ), wxT( "A.start_shape" ), wxT( "B.End_Width" ), wxT( "AB.Scale_X" ),
4736 wxT( "A.parent.Reference" ), wxT( "A . PARENT . Reference" ), wxT( "A.Major_Radius" ),
4737 wxT( "A.Exclude_From_Simulation" ), wxT( "A.Automatically_Update_Net" ), wxT( "A.Grid_Type" ) } )
4738 {
4739 for( const wxString& kind : { wxT( "condition" ), wxT( "assertion" ) } )
4740 {
4741 const wxString expression =
4742 property + ( property.Contains( wxT( "Reference" ) ) ? wxT( " == 'U1'" ) : wxT( " == 1" ) );
4743 const wxString body =
4744 kind == wxT( "condition" )
4745 ? wxT( "(condition \"" ) + expression + wxT( "\") (constraint clearance (min 0.2mm))" )
4746 : wxT( "(constraint assertion \"" ) + expression + wxT( "\")" );
4747 const auto result =
4748 FilterDrcRulesForTarget( wxT( "(version 1)(rule \"props\" " ) + body + ")", target );
4749 BOOST_CHECK( result.m_error.IsEmpty() );
4750 BOOST_CHECK_EQUAL( result.m_dropped.size(), 1 );
4751 }
4752 }
4753
4754 for( const wxString& property :
4755 { wxT( "A.Corner_Radius" ), wxT( "A.Auto_Thickness" ), wxT( "A.Target_Delay" ) } )
4756 {
4757 for( const wxString& kind : { wxT( "condition" ), wxT( "assertion" ) } )
4758 {
4759 const wxString expression = property + wxT( " == 1" );
4760 const wxString body =
4761 kind == wxT( "condition" )
4762 ? wxT( "(condition \"" ) + expression + wxT( "\") (constraint clearance (min 0.2mm))" )
4763 : wxT( "(constraint assertion \"" ) + expression + wxT( "\")" );
4764 const auto result =
4765 FilterDrcRulesForTarget( wxT( "(version 1)(rule \"older\" " ) + body + ")", target );
4766 BOOST_CHECK( result.m_error.IsEmpty() );
4767 BOOST_CHECK_EQUAL( result.m_dropped.size(), target.m_boardVersion == kicad9.m_boardVersion ? 1 : 0 );
4768 }
4769 }
4770
4771 const wxString kept = wxT( "(rule \"literal\" (condition \"A.NetName == 'A.Start_Shape' && A.Start_X > 1mm "
4772 "&& A.End_Y > 1mm && A.Radius > 1mm\") (constraint clearance (min 0.2mm)))" );
4773 const auto result = FilterDrcRulesForTarget( wxT( "(version 1)" ) + kept, target );
4774 BOOST_CHECK( result.m_error.IsEmpty() );
4775 BOOST_CHECK( result.m_dropped.empty() );
4776 BOOST_CHECK( result.m_text.Contains( kept ) );
4777 }
4778}
4779
4780
const char * name
@ ERROR_INSIDE
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
COMPATIBILITY_REPORT ClassifyBoardForDowngrade(const BOARD *aBoard, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Report what a board would lose if exported to an older KiCad.
void SaveFootprintForTarget(FOOTPRINT *aFootprint, const wxString &aPath, const DOWNGRADE_TARGET &aTarget)
Save a single .kicad_mod footprint file for the target.
int BoardDowngradeCoveredVersion()
The format the denylist was generated against. A format bump forces a review.
void SaveBoardForTarget(BOARD *aBoard, const wxString &aPath, const DOWNGRADE_TARGET &aTarget)
Save a board stamped for the target, using the writer for that version.
void FlattenBoardVariant(BOARD *aBoard, const wxString &aVariantName)
Bake a variant's overrides into the base footprint attributes.
int FootprintLibDowngradeCoveredVersion()
The footprint library format the rules were reviewed against. Moves independently of the board.
bool ExportBoardToOlderVersion(const wxString &aSrcFile, const wxString &aDestFile, const DOWNGRADE_TARGET &aTarget, COMPATIBILITY_REPORT &aReport, wxString *aUnsupportedToken, const wxString &aVariant, bool aDropInsteadOfApproximate)
Load a board, downgrade the copy, and write it stamped for the target.
DOWNGRADE_FILE_RESULT DowngradeFootprintFileToTemp(const wxString &aSrcFile, const wxString &aTmpFile, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Load one .kicad_mod, classify it against the rule table, and write the downgraded copy to aTmpFile.
void DowngradeBoardInPlace(BOARD *aBoard, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Approximate or remove, in place, what the target cannot represent.
void DowngradeFootprintInPlace(FOOTPRINT *aFootprint, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Footprint-scoped downgrade for standalone .kicad_mod files the board pass never sees.
wxString FindUnsupportedBoardToken(const wxString &aSerialized, const DOWNGRADE_TARGET &aTarget)
Scan serialized board text for tokens the target cannot parse.
General utilities for PCB file IO for QA programs.
@ BS_ITEM_TYPE_DIELECTRIC
int GetPPI() const
int GetLegacyPPI() const
Recompute the PPI the way it was computed before the pixels/cm truncation fix.
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
std::map< PCB_LAYER_ID, ZONE_LAYER_PROPERTIES > m_ZoneLayerProperties
DRILL_SYMBOL_PROFILE & GetDrillSymbolProfile()
BOARD_STACKUP & GetStackupDescriptor()
Abstract interface for BOARD_ITEMs capable of storing other items inside.
virtual void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false)=0
Adds an item to the container.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:98
virtual bool IsKnockout() const
Definition board_item.h:436
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
virtual void SetIsKnockout(bool aKnockout)
Definition board_item.h:437
Manage one layer needed to make a physical board.
DIELECTRIC_MODEL GetDielectricModel(int aDielectricSubLayer=0) const
void SetDielectricModel(DIELECTRIC_MODEL aModel, int aDielectricSubLayer=0)
void Add(BOARD_STACKUP_ITEM *aItem)
Add a new item in stackup layer.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Removes an item from the container.
Definition board.cpp:1520
const GENERATORS & Generators() const
Definition board.h:485
void SetProperties(const std::map< wxString, wxString > &aProps)
Definition board.h:527
NETINFO_ITEM * FindNet(int aNetcode) const
Search for a net with the given netcode.
Definition board.cpp:2805
TITLE_BLOCK & GetTitleBlock()
Definition board.h:1026
const TRACKS & Tracks() const
Definition board.h:463
const CONSTRAINTS & Constraints() const
Geometric constraints (#2329) owned by this board.
Definition board.h:522
void SetCopperLayerCount(int aCount)
Definition board.cpp:1133
void SetProject(PROJECT *aProject, bool aReferenceOnly=false)
Link a board to a given project.
Definition board.cpp:379
wxString GroupsSanityCheck(bool repair=false)
Consistency check of internal m_groups structure.
Definition board.cpp:3937
void SetEnabledLayers(const LSET &aLayerMask)
A proxy function that calls the correspondent function in m_BoardSettings.
Definition board.cpp:1194
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1290
const DRAWINGS & Drawings() const
Definition board.h:467
What an export to a given target will keep, approximate, drop, or block.
bool IsLossy() const
True if anything is approximated or dropped. This is what triggers the lossy warning.
bool IsBlocked() const
True if some feature makes the target impossible. The user cannot export anyway.
int Count(DOWNGRADE_BUCKET aBucket) const
const std::vector< COMPAT_ENTRY > & Entries() const
Stage related design and library files together, retaining originals until every write is ready.
const wxString & GetRecoveryError() const
Recovery details are nonempty only if restoring an original or removing a new output failed.
wxString Commit()
Replace all destinations, rolling back earlier replacements if a rename fails.
wxString Stage(const wxString &aDestination)
Return an exclusively-created sibling staging file, or empty if it cannot be created.
void Discard(const wxString &aTemporary)
Forget a skipped conversion without exposing its empty staging file as an output.
void Parse(std::vector< std::shared_ptr< DRC_RULE > > &aRules, REPORTER *aReporter)
Grouping rules and symbol assignments, shared by reference so a chart and its map can never disagree ...
void SetName(const wxString &aName)
A set of EDA_ITEMs (i.e., without duplicates).
Definition eda_group.h:43
std::unordered_set< EDA_ITEM * > & GetItems()
Definition eda_group.h:78
wxString GetName() const
Definition eda_group.h:75
void AddItem(EDA_ITEM *aItem)
Add item to group.
Definition eda_group.cpp:58
void SetName(const wxString &aName)
Definition eda_group.h:76
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
virtual EDA_GROUP * GetParentGroup() const
Definition eda_item.h:116
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
bool HasCustomProperties() const
Definition eda_item.h:269
void SetCustomProperty(const wxString &aKey, const wxString &aValue)
Definition eda_item.h:255
void SetEndEnding(const LINE_ENDING &aEnding)
Definition eda_shape.h:190
FILL_T GetFillMode() const
Definition eda_shape.h:151
void TransformWithLineEndingsToPolygon(SHAPE_POLY_SET &aBuffer, int aClearance, int aError, ERROR_LOC aErrorLoc, bool ignoreLineWidth=false) const
Convert the shape body shortened for line endings plus line-ending geometry to polygons.
void SetLineStyle(const LINE_STYLE aStyle)
SHAPE_POLY_SET & GetPolyShape()
void SetEndEndingStyle(LINE_ENDING_STYLE aStyle)
Definition eda_shape.h:196
SHAPE_T GetShape() const
Definition eda_shape.h:178
LINE_STYLE GetLineStyle() const
LINE_ENDING_STYLE GetEndEndingStyle() const
Definition eda_shape.h:195
void SetFillMode(FILL_T aFill)
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
KIFONT::FONT * GetFont() const
Definition eda_text.h:286
void SetBold(bool aBold)
Set the text to be bold - this will also update the font if needed.
Definition eda_text.cpp:311
bool IsBold() const
Definition eda_text.h:215
virtual int GetTextThickness() const
Definition eda_text.h:159
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
void SetFont(KIFONT::FONT *aFont)
Definition eda_text.cpp:472
Variant information for a footprint.
Definition footprint.h:178
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
bool GetDuplicatePadNumbersAreJumpers() const
Definition footprint.h:1133
const CASE_INSENSITIVE_MAP< FOOTPRINT_VARIANT > & GetVariants() const
Get all variants.
Definition footprint.h:1011
bool IsDNP() const
Definition footprint.h:947
EDA_ANGLE GetOrientation() const
Definition footprint.h:382
PCB_3D_BODY & EnsureBody()
void SetDNP(bool aDNP=true)
Definition footprint.h:948
void SetStackupMode(FOOTPRINT_STACKUP aMode)
Set the stackup mode for this footprint.
void SetExcludedFromSim(bool aExclude=true)
Definition footprint.h:939
void SetKeywords(const wxString &aKeywords)
Definition footprint.h:453
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:831
void SetDuplicatePadNumbersAreJumpers(bool aEnabled)
Definition footprint.h:1134
CONSTRAINTS & Constraints()
Definition footprint.h:367
PCB_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this footprint.
std::deque< PAD * > & Pads()
Definition footprint.h:355
void SetReference(const wxString &aReference)
Definition footprint.h:799
bool IsExcludedFromSim() const
Definition footprint.h:938
void SetTransformScale(double aScaleX, double aScaleY)
PCB_FIELD & Reference()
Definition footprint.h:832
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Adds an item to the container.
FOOTPRINT_VARIANT * AddVariant(const wxString &aVariantName)
Add a new variant with the given name.
bool HasBody() const
Convenience accessors for now while we restrict to only one body per footprint.
Definition footprint.h:426
const wxString & GetReference() const
Definition footprint.h:793
VECTOR2I GetPosition() const override
Definition footprint.h:379
DRAWINGS & GraphicalItems()
Definition footprint.h:358
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
static FONT * GetFont(const wxString &aFontName=wxEmptyString, bool aBold=false, bool aItalic=false, const std::vector< wxString > *aEmbeddedFiles=nullptr, bool aForDrawingSheet=false)
Definition font.cpp:144
virtual bool IsOutline() const
Definition font.h:102
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
std::string AsStdString() const
Definition kiid.cpp:270
const std::filesystem::path & Path() const
Get the path to the temporary directory as a std::filesystem::path.
Definition file_utils.h:61
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
Decorative shape (arrowhead, circle, square) at the start or end of a graphic line,...
Definition line_ending.h:62
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
Handle the data for a net.
Definition netinfo.h:50
int GetNetCode() const
Definition netinfo.h:104
void SetParent(BOARD *aParent)
Definition netinfo.h:176
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:505
A PADSTACK defines the characteristics of a single or multi-layer pad, in the IPC sense of the word.
Definition padstack.h:161
MASK_LAYER_PROPS & FrontOuterLayers()
Definition padstack.h:410
void SetUnconnectedLayerMode(UNCONNECTED_LAYER_MODE aMode)
Definition padstack.h:405
UNCONNECTED_LAYER_MODE UnconnectedLayerMode() const
Definition padstack.h:404
DRILL_PROPS & Drill()
Definition padstack.h:363
@ CUSTOM
Shapes can be defined on arbitrary layers.
Definition padstack.h:177
MASK_LAYER_PROPS & BackOuterLayers()
Definition padstack.h:413
Definition pad.h:61
LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition pad.h:579
VECTOR2I GetPosition() const override
Definition pad.cpp:255
double GetRoundRectRadiusRatio(PCB_LAYER_ID aLayer) const
Definition pad.h:837
PAD_SHAPE GetShape(PCB_LAYER_ID aLayer) const
Definition pad.h:205
VECTOR2I GetSize(PCB_LAYER_ID aLayer) const
Definition pad.cpp:297
EDA_ANGLE GetOrientation() const
Return the rotation angle of the pad.
Definition pad.cpp:1672
const VECTOR2I & GetMid() const
Definition pcb_track.h:304
wxString GetShownText(RESOLUTION_CONTEXT aContext) const
void SetShowText(bool aShow)
void SetBarcodeText(const wxString &aText)
void SetWidth(int aWidth)
void SetBarcodeKind(BARCODE_T aKind)
void SetHeight(int aHeight)
void SetLayer(PCB_LAYER_ID aLayer) override
Set the drawing layer for the barcode and its text.
void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aMaxError, ERROR_LOC aErrorLoc=ERROR_INSIDE, bool ignoreLineWidth=false) const override
Convert the barcode (text + symbol shapes) to polygonal geometry suitable for filling/collision tests...
A geometric constraint between board items (issue #2329).
void AddMember(const KIID &aItem, CONSTRAINT_ANCHOR aAnchor=CONSTRAINT_ANCHOR::WHOLE, int aIndex=-1)
virtual void SetEnd(const VECTOR2I &aPoint)
virtual void SetStart(const VECTOR2I &aPoint)
void ChangeOverrideText(const wxString &aValue)
For better understanding of the points that make a dimension:
void SetHeight(int aHeight)
Set the distance from the feature points to the crossbar line.
A drill chart placed on the board, kept in step with the holes.
Turns on drill symbols at the holes, for one layer.
wxString GetShownText(RESOLUTION_CONTEXT aContext, int aDepth=0) const override
Return the string actually shown after processing of the base text.
void RebuildCells(const BOARD &aBoard, GENERATED_TABLE_REFRESH *aRefresh=nullptr)
Regenerate the cells from the board.
PCB_GENERATOR * DeepClone() const
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:51
A PCB_IO derivation for saving and loading Pcbnew s-expression formatted files.
std::unique_ptr< FOOTPRINT > ImportFootprint(const wxString &aFootprintPath, wxString &aFootprintNameOut, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a single footprint from aFootprintPath and put its name in aFootprintNameOut.
void FootprintSave(const wxString &aLibraryPath, const FOOTPRINT *aFootprint, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aFootprint to an existing library located at aLibraryPath.
void SaveBoard(const wxString &aFileName, BOARD &aBoard, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aBoard to a storage file in a format that this PCB_IO implementation knows about or it can be u...
void FormatBoardToFormatter(OUTPUTFORMATTER *aOut, BOARD *aBoard, const std::map< std::string, UTF8 > *aProperties=nullptr)
Serialize a BOARD to an OUTPUTFORMATTER without file I/O or Prettify.
std::unique_ptr< BOARD > LoadBoard(const wxString &aFileName, const std::map< std::string, UTF8 > *aProperties=nullptr, PROJECT *aProject=nullptr)
Load information from some input file format that this PCB_IO implementation knows about into new BOA...
Definition pcb_io.cpp:72
Object to handle a bitmap image that can be inserted in a PCB.
REFERENCE_IMAGE & GetReferenceImage()
void SetEllipseCenter(const VECTOR2I &aPt) override
void SetCornerRadius(int aCornerRadius) override
void SetWidth(int aWidth) override
void SetEllipseStartAngle(const EDA_ANGLE &aA) override
void SetEllipseEndAngle(const EDA_ANGLE &aA) override
void SetEnd(const VECTOR2I &aEnd) override
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
void SetEllipseMinorRadius(int aR) override
void SetStart(const VECTOR2I &aStart) override
void SetEllipseMajorRadius(int aR) override
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:70
A board stackup table placed on the board, kept in step with the stackup.
int GetRowCount() const
Definition pcb_table.h:128
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
PCB_TABLECELL * GetCell(int aRow, int aCol) const
Definition pcb_table.h:155
void AddCell(PCB_TABLECELL *aCell)
Definition pcb_table.h:170
void SetColCount(int aCount)
Definition pcb_table.h:125
void SetTextThickness(int aWidth) override
The TextThickness is that set by the user.
Definition pcb_text.cpp:514
VECTOR2I GetPosition() const override
Definition pcb_text.h:101
int GetTextThickness() const override
Definition pcb_text.cpp:499
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
EDA_ITEM * Clone() const override
Create a duplicate of this item with linked list members set to NULL.
Definition pcb_track.cpp:73
const VECTOR2I & GetStart() const
Definition pcb_track.h:100
const VECTOR2I & GetEnd() const
Definition pcb_track.h:97
virtual int GetWidth() const
Definition pcb_track.h:94
const STRING_ANY_MAP GetProperties() const override
PCB_TUNING_PATTERN(BOARD_ITEM *aParent=nullptr, PCB_LAYER_ID aLayer=F_Cu, LENGTH_TUNING_MODE aMode=LENGTH_TUNING_MODE::SINGLE)
PNS::MEANDER_SETTINGS & GetSettings()
A microvia stack: several single hop microvias, plus connecting traces for staggered stacks,...
VIA_STACK_STYLE GetStyle() const
PCB_LAYER_ID GetStartLayer() const
PCB_LAYER_ID GetEndLayer() const
wxString GetGeneratorType() const override
PCB_VIA_STITCH(BOARD_ITEM *aParent=nullptr)
int GetGuardedNetCode() const
Net being guarded in GUARD mode.
const PADSTACK & Padstack() const
Definition pcb_track.h:435
void SetViaType(VIATYPE aViaType)
Definition pcb_track.h:427
VIATYPE GetViaType() const
Definition pcb_track.h:426
bool m_isTimeDomain
Calculate tuning in the time domain.
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.
const BITMAP_BASE & GetImage() const
Get the underlying image.
double GetImageScale() const
void SetImageScale(double aScale)
Set the image "zoom" value.
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load a project or sets up a new project with a specified path.
double Area(bool aAbsolute=true) const
Return the area of this chain.
Represent a set of closed polygons.
double Area()
Return the area of this poly set.
int HoleCount(int aOutline) const
Returns the number of holes in a given outline.
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void Simplify()
Simplify the polyset (merges overlapping polys, eliminates degeneracy/self-intersections)
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.
const SHAPE_LINE_CHAIN & CHole(int aOutline, int aHole) const
int OutlineCount() const
Return the number of outlines in the set.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
A name/value tuple with unique names and wxAny values.
bool get_to(const std::string &aKey, T &aVar) const
void set(const std::string &aKey, const T &aVar)
Implement an OUTPUTFORMATTER to a memory buffer.
Definition richio.h:430
const std::string & GetString()
Definition richio.h:453
void SetComment(int aIdx, const wxString &aComment)
Definition title_block.h:98
void SetTitle(const wxString &aTitle)
Definition title_block.h:55
const wxString & GetTitle() const
Definition title_block.h:60
A wrapper for reporting to a wxString object.
Definition reporter.h:242
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:834
bool GetDoNotAllowVias() const
Definition zone.h:852
bool AppendCorner(const VECTOR2I &aPosition, int aHoleIdx, bool aAllowDuplication=false)
Add a new corner to the zone outline (to the main outline or a hole)
Definition zone.cpp:1519
ZONE_LAYER_PROPERTIES & LayerProperties(PCB_LAYER_ID aLayer)
Definition zone.h:146
wxString GetPlacementAreaSource() const
Definition zone.h:839
std::shared_ptr< SHAPE_POLY_SET > GetFilledPolysList(PCB_LAYER_ID aLayer) const
Definition zone.h:701
bool GetDoNotAllowPads() const
Definition zone.h:854
PLACEMENT_SOURCE_T GetPlacementAreaSourceType() const
Definition zone.h:841
bool GetDoNotAllowTracks() const
Definition zone.h:853
bool IsFilled() const
Definition zone.h:306
virtual void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
Definition zone.cpp:677
SHAPE_POLY_SET * Outline()
Definition zone.h:421
bool IsIsland(PCB_LAYER_ID aLayer, int aPolyIdx) const
Check if a given filled polygon is an insulated island.
Definition zone.cpp:1769
bool IsCopperThieving() const
Definition zone.h:349
const wxString & GetZoneName() const
Definition zone.h:160
SHAPE_POLY_SET GetBoardOutline() const
Definition zone.cpp:953
void SetFillMode(ZONE_FILL_MODE aFillMode)
Definition zone.cpp:683
void SetLayerSet(const LSET &aLayerSet) override
Definition zone.cpp:702
bool GetPlacementAreaEnabled() const
Definition zone.h:836
bool GetDoNotAllowFootprints() const
Definition zone.h:855
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
bool GetDoNotAllowZoneFills() const
Definition zone.h:851
@ FOR_CANVAS
Definition common.h:92
DOWNGRADE_BUCKET
What happens to a feature when we export to an older KiCad.
@ BLOCK
Cannot be represented at all, export to this target is not possible.
@ LOWER
Approximated down to a simpler equivalent.
@ DROP
No equivalent, left out.
static bool empty(const wxTextEntryBase *aCtrl)
wxString DowngradeLibraryFilesInPlace(const wxString &aDir, const wxString &aGlob, int aStampVersion, const std::function< wxString(const wxString &)> &aFindForbidden, const std::function< DOWNGRADE_FILE_RESULT(const wxString &, const wxString &)> &aConvert, DOWNGRADE_FILE_TRANSACTION *aTransaction=nullptr, wxString *aRecoveryError=nullptr)
Downgrade every library file matching aGlob under aDir in place.
bool IsDowngradeDesignFile(const wxString &aPath)
Files the project export carries over.
DOWNGRADE_FILE_RESULT
What a per-file converter did with one library file.
@ REFUSED
The target cannot represent this file.
@ CONVERTED
The temp file holds the downgraded copy.
const std::vector< DOWNGRADE_TARGET > & GetDowngradeTargets()
Supported downgrade targets, newest first.
@ TRACK_WIDTH_CONSTRAINT
@ CLEARANCE_CONSTRAINT
constexpr const char * DRC_RULE_SEMANTIC_BREAKS[]
A function a release parses but answers differently, which the vocabulary cannot say.
const DRC_RULE_VOCABULARY * FindDrcRuleVocabulary(const DOWNGRADE_TARGET &aTarget)
The vocabulary a target release could parse, generated from its release tags by tools/generate_drc_ru...
DRC_RULES_FILTER_RESULT FilterDrcRulesForTarget(const wxString &aRulesText, const DOWNGRADE_TARGET &aTarget)
Filter a .kicad_dru file for the target.
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_360
Definition eda_angle.h:478
@ NO_FILL
Definition eda_fill.h:30
@ HATCH
Definition eda_fill.h:34
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
@ RECURSE
Definition eda_item.h:51
SHAPE_T
Definition eda_shape.h:55
@ ELLIPSE
Definition eda_shape.h:63
@ SEGMENT
Definition eda_shape.h:57
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
@ ELLIPSE_ARC
Definition eda_shape.h:64
@ CUSTOM_LAYERS
Stackup handling where the footprint can have any number of copper layers, and objects on those layer...
Definition footprint.h:116
std::string source
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ Dwgs_User
Definition layer_ids.h:103
@ B_Cu
Definition layer_ids.h:61
@ In2_Cu
Definition layer_ids.h:63
@ F_SilkS
Definition layer_ids.h:96
@ In1_Cu
Definition layer_ids.h:62
@ F_Cu
Definition layer_ids.h:60
Test utilities for timestamps.
std::string GetPcbnewTestDataDir()
Utility which returns a path to the data directory where the test board files are stored.
std::string ReadGoldenText(const std::string &aPath)
wxMemoryBuffer MakePngWithFractionalPixelsPerCm()
A tiny PNG whose embedded resolution gives a fractional pixels/cm, so the legacy truncating PPI diffe...
void DumpBoardToFile(BOARD &board, const std::filesystem::path &aFilename)
Utility function to simply write a Board out to a file.
double SerializedImageScale(const std::string &aContent, const std::string &aUuid)
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
@ NON_COMPONENT
Pad with no hole that does not connect to a physical component, but rather provides a connection poin...
Definition padstack.h:106
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ PRESSFIT
a PTH with a hole diameter with tight tolerances for press fit pin
Definition padstack.h:127
@ NONE
no special fabrication property
Definition padstack.h:119
BARCODE class definition.
@ HORIZONTAL
A segment (or two points) is horizontal.
Class to handle a set of BOARD_ITEMs.
#define SEXPR_FOOTPRINT_LIB_FILE_VERSION
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
@ STITCH
Fill the outline with vias with a pattern.
@ GUARD
Place vias to guard a net contained within.
void DowngradeProjectFileJson(nlohmann::json &aDoc, const DOWNGRADE_TARGET &aTarget, COMPATIBILITY_REPORT &aReport)
Migrate a .kicad_pro document down to what the target release expects.
@ RPT_SEVERITY_ERROR
One line in the compatibility report.
An older KiCad release we can export a project back to.
wxString m_text
The filtered rules file text.
wxString m_error
Invalid source syntax, do not write m_text.
std::vector< wxString > m_dropped
Names of the rules the target cannot parse.
Everything a rules file could name in one release.
std::optional< bool > is_capped
True if the drill hole should be capped.
Definition padstack.h:284
std::optional< bool > is_filled
True if the drill hole should be filled completely.
Definition padstack.h:283
std::optional< bool > has_covering
True if the pad on this side should have covering.
Definition padstack.h:266
std::optional< bool > has_plugging
True if the drill hole should be plugged on this side.
Definition padstack.h:267
std::optional< VECTOR2I > hatching_offset
BOOST_AUTO_TEST_CASE(HorizontalAlignment)
BOOST_AUTO_TEST_CASE(EmptyBoardIsClean)
static size_t ParsedDrcRuleCount(const wxString &aText, const wxString &aSource)
static void checkFeature(const COMPATIBILITY_REPORT &aReport, const wxString &aName, DOWNGRADE_BUCKET aBucket, int aCount)
BOOST_AUTO_TEST_SUITE(CadstarPartParser)
BOOST_CHECK(res.column_datatype(0)==SQL_NUMERIC||res.column_datatype(0)==SQL_DECIMAL)
const std::string table
BOOST_REQUIRE_EQUAL(rows.size(), 1)
BOOST_CHECK_EQUAL(std::any_cast< std::string >(rows[0].at("val")), "12345678901234567.89")
BOOST_REQUIRE(res.columns()==1)
BOOST_AUTO_TEST_SUITE_END()
std::string path
IbisParser parser & reporter
VECTOR3I expected(15, 30, 45)
static const DOWNGRADE_TARGET & kicad10
static const DOWNGRADE_TARGET & kicad9
BOOST_TEST_CONTEXT("Test Clearance")
BOOST_TEST_MESSAGE("Polyline has "<< chain.PointCount()<< " points")
wxString result
Test unit parsing edge cases and error handling.
#define M_PI
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:93
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:86
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)
Class ZONE_SETTINGS used to handle zones parameters in dialogs.