KiCad PCB EDA Suite
Loading...
Searching...
No Matches
test_specctra_export.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
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU 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 <filesystem>
23#include <fstream>
24#include <memory>
25#include <sstream>
26#include <string>
27#include <system_error>
28
29#include <board.h>
30#include <board_commit.h>
31#include <footprint.h>
32#include <layer_ids.h>
33#include <locale_io.h>
34#include <pcb_shape.h>
35#include <pcb_track.h>
36#include <zone.h>
40#include <tool/tool_manager.h>
41#include <reporter.h>
42#include <ranges>
43
44#include <wx/filename.h>
45#include <wx/string.h>
46
47using namespace DSN;
48
49
50namespace
51{
52// Unique per-test scratch file that survives BOOST_REQUIRE early-outs and cleans up on scope exit.
53class TEMP_FILE
54{
55public:
56 explicit TEMP_FILE( const wxString& aPrefix ) :
57 m_path( std::string( wxFileName::CreateTempFileName( aPrefix ).ToUTF8() ) )
58 {
59 }
60
61 ~TEMP_FILE()
62 {
63 std::error_code ec;
64 std::filesystem::remove( m_path, ec );
65 }
66
67 const std::filesystem::path& Path() const { return m_path; }
68 std::string Str() const { return m_path.string(); }
69 wxString WxStr() const { return wxString( m_path.string() ); }
70
71private:
72 std::filesystem::path m_path;
73};
74
75
76std::string slurp( const std::filesystem::path& aPath )
77{
78 std::ifstream in( aPath );
79 std::stringstream ss;
80 ss << in.rdbuf();
81 return ss.str();
82}
83
84
85std::unique_ptr<BOARD> loadTestBoard()
86{
87 const std::filesystem::path boardPath =
88 std::filesystem::path( KI_TEST::GetPcbnewTestDataDir() ) / "issue3812.kicad_pcb";
89
90 BOOST_REQUIRE( std::filesystem::exists( boardPath ) );
91
92 return KI_TEST::RequireBoardFromPcbnewQAData( "issue3812.kicad_pcb" );
93}
94
95
96int countTraces( BOARD* aBoard )
97{
98 int n = 0;
99
100 for( PCB_TRACK* track : aBoard->Tracks() )
101 {
102 if( track->Type() == PCB_TRACE_T )
103 ++n;
104 }
105
106 return n;
107}
108
109
110void importSession( BOARD* aBoard, const wxString& aSesPath )
111{
112 TOOL_MANAGER toolMgr;
113 toolMgr.SetEnvironment( aBoard, nullptr, nullptr, nullptr, nullptr );
114 toolMgr.RegisterTool( new KI_TEST::DUMMY_TOOL() );
115
116 BOARD_COMMIT commit( &toolMgr, true, false );
117 ImportSpecctraSession( aBoard, aSesPath, commit );
118 commit.Push( wxT( "Import Specctra Session" ), SKIP_UNDO );
119}
120
121
122void importSession( BOARD* aBoard, const wxString& aSesPath, WX_STRING_REPORTER* aReporter,
123 int* aSkipped )
124{
125 TOOL_MANAGER toolMgr;
126 toolMgr.SetEnvironment( aBoard, nullptr, nullptr, nullptr, nullptr );
127 toolMgr.RegisterTool( new KI_TEST::DUMMY_TOOL() );
128
129 BOARD_COMMIT commit( &toolMgr, true, false );
130 ImportSpecctraSession( aBoard, aSesPath, commit, aReporter, aSkipped );
131 commit.Push( wxT( "Import Specctra Session" ), SKIP_UNDO );
132}
133} // namespace
134
135
136/*
137 * A family of Specctra DSN quoting/naming defects that made otherwise-valid boards un-exportable
138 * or produced structurally invalid interchange files (#24946/7/8).
139 */
140
141
142// #24946: a field payload holding the string delimiter (an inch mark in the Value/PN) must not
143// terminate the quoted string early and desync a conforming reader.
144BOOST_AUTO_TEST_CASE( SpecctraExportQuoteInField )
145{
146 LOCALE_IO toggle;
147 std::unique_ptr<BOARD> board = loadTestBoard();
148
149 BOOST_REQUIRE( !board->Footprints().empty() );
150 board->Footprints().front()->SetValue( wxT( "2x20 pin 0.1\" female header" ) );
151
152 TEMP_FILE out( wxT( "kicad_specctra_24946_" ) );
153 BOOST_REQUIRE_NO_THROW( ExportBoardToSpecctraFile( board.get(), out.Str() ) );
154
155 const std::string dsn = slurp( out.Path() );
156
157 // The delimiter must no longer appear inside the payload, and the transformed form is emitted.
158 BOOST_CHECK( dsn.find( "0.1\" female" ) == std::string::npos );
159 BOOST_CHECK( dsn.find( "0.1'' female" ) != std::string::npos );
160}
161
162
163// #24947: duplicate and empty reference designators (unannotated REF** fiducials, intentional
164// duplicates, case-only differences) must not abort the export; they are uniquified on the fly,
165// case-insensitively to match the exported case_sensitive default.
166BOOST_AUTO_TEST_CASE( SpecctraExportDuplicateEmptyRefs )
167{
168 LOCALE_IO toggle;
169 std::unique_ptr<BOARD> board = loadTestBoard();
170
171 BOOST_REQUIRE_GE( board->Footprints().size(), 5u );
172
173 board->Footprints()[0]->SetReference( wxEmptyString );
174 board->Footprints()[1]->SetReference( wxEmptyString );
175 board->Footprints()[2]->SetReference( wxT( "U1" ) );
176 board->Footprints()[3]->SetReference( wxT( "U1" ) );
177 board->Footprints()[4]->SetReference( wxT( "u1" ) );
178
179 TEMP_FILE out( wxT( "kicad_specctra_24947_" ) );
180 BOOST_REQUIRE_NO_THROW( ExportBoardToSpecctraFile( board.get(), out.Str() ) );
181
182 const std::string dsn = slurp( out.Path() );
183
184 // Empty ids take a REF** base; case-insensitive collisions are all suffixed distinctly.
185 BOOST_CHECK( dsn.find( "(place REF**_1 " ) != std::string::npos );
186 BOOST_CHECK( dsn.find( "(place U1 " ) != std::string::npos );
187 BOOST_CHECK( dsn.find( "(place U1_1 " ) != std::string::npos );
188 BOOST_CHECK( dsn.find( "(place u1_2 " ) != std::string::npos );
189}
190
191
192// Allegro Specctra writes zone fills as (wire (poly ...)) — an abbreviation of (polygon).
193// Parsing must accept that token and skip the pour geometry (zones stay on the board).
194// A rule area inside a rotated footprint must be exported in the footprint's frame, like its pads:
195// the keepout polygon of the image is the library-frame outline, whatever the placement.
196BOOST_AUTO_TEST_CASE( SpecctraExportRotatedFootprintKeepout )
197{
198 LOCALE_IO toggle;
199 BOARD board;
200
201 // A board outline, which the export requires.
202 const VECTOR2I corners[4] = { { 0, 0 }, { pcbIUScale.mmToIU( 150 ), 0 },
203 { pcbIUScale.mmToIU( 150 ), pcbIUScale.mmToIU( 100 ) },
204 { 0, pcbIUScale.mmToIU( 100 ) } };
205
206 for( int i = 0; i < 4; ++i )
207 {
208 PCB_SHAPE* edge = new PCB_SHAPE( &board, SHAPE_T::SEGMENT );
209 edge->SetLayer( Edge_Cuts );
210 edge->SetStart( corners[i] );
211 edge->SetEnd( corners[( i + 1 ) % 4] );
212 board.Add( edge );
213 }
214
215 FOOTPRINT* footprint = new FOOTPRINT( &board );
216 footprint->SetReference( wxS( "K1" ) );
217 footprint->SetPosition( { pcbIUScale.mmToIU( 100 ), pcbIUScale.mmToIU( 50 ) } );
218 footprint->SetOrientation( ANGLE_90 );
219
220 // Library frame: x 1..3 mm, y 0.5..1.5 mm.
221 ZONE* keepout = new ZONE( footprint );
222 keepout->SetIsRuleArea( true );
223 keepout->SetDoNotAllowTracks( true );
224 keepout->SetDoNotAllowVias( true );
225 keepout->SetLayer( F_Cu );
226 keepout->AppendCorner( { pcbIUScale.mmToIU( 1 ), pcbIUScale.mmToIU( 0.5 ) }, -1 );
227 keepout->AppendCorner( { pcbIUScale.mmToIU( 3 ), pcbIUScale.mmToIU( 0.5 ) }, -1 );
228 keepout->AppendCorner( { pcbIUScale.mmToIU( 3 ), pcbIUScale.mmToIU( 1.5 ) }, -1 );
229 keepout->AppendCorner( { pcbIUScale.mmToIU( 1 ), pcbIUScale.mmToIU( 1.5 ) }, -1 );
230 footprint->Add( keepout );
231 board.Add( footprint );
232
233 TEMP_FILE out( wxT( "kicad_specctra_keepout_" ) );
234 BOOST_REQUIRE_NO_THROW( ExportBoardToSpecctraFile( &board, out.Str() ) );
235
236 const std::string dsn = slurp( out.Path() );
237 const size_t image = dsn.find( "(image " );
238 BOOST_REQUIRE( image != std::string::npos );
239 const std::string imageText = dsn.substr( image, dsn.find( "(network", image ) - image );
240
241 // DSN points are in micrometres with y up: the library-frame corners, not a rotated copy.
242 BOOST_CHECK_MESSAGE( imageText.find( "(keepout" ) != std::string::npos, imageText );
243 BOOST_CHECK_MESSAGE( imageText.find( "1000 -500" ) != std::string::npos, imageText );
244 BOOST_CHECK_MESSAGE( imageText.find( "3000 -1500" ) != std::string::npos, imageText );
245 BOOST_CHECK_MESSAGE( imageText.find( "3000 -500" ) != std::string::npos, imageText );
246 BOOST_CHECK_MESSAGE( imageText.find( "1000 -1500" ) != std::string::npos, imageText );
247}
248
249
250BOOST_AUTO_TEST_CASE( SpecctraImportAllegroPolyWire )
251{
252 LOCALE_IO toggle;
253 std::unique_ptr<BOARD> board = loadTestBoard();
254
255 TEMP_FILE ses( wxT( "kicad_specctra_allegro_poly_" ) );
256
257 const std::string validLayer = std::string( board->GetLayerName( F_Cu ).ToUTF8() );
258
259 std::ofstream out( ses.Path() );
260 out << "(session test.ses\n"
261 << " (base_design test.dsn)\n"
262 << " (routes\n"
263 << " (resolution um 10)\n"
264 << " (library_out )\n"
265 << " (network_out\n"
266 << " (net \"/ALLPST\"\n"
267 << " (wire (path \"" << validLayer << "\" 1600 0 0 1000 0)\n"
268 << " (type route))\n"
269 << " (wire (poly \"" << validLayer << "\" 0 0 0 1000 0 1000 1000 0 1000 0 0)\n"
270 << " (type normal))\n"
271 << " )\n"
272 << " )\n"
273 << " )\n"
274 << ")\n";
275 out.close();
276
277 BOOST_REQUIRE_NO_THROW( importSession( board.get(), ses.Str() ) );
278
279 // Path wire imported; poly wire ignored (zone fill), so exactly one trace.
280 BOOST_CHECK_EQUAL( countTraces( board.get() ), 1 );
281}
282
283
284// #24948: single unresolved session items (an unknown wire layer or a placement referencing a
285// uniquified id the board never had) must be skipped rather than sinking the whole import.
286BOOST_AUTO_TEST_CASE( SpecctraImportSkipsInvalidWireLayer )
287{
288 LOCALE_IO toggle;
289 std::unique_ptr<BOARD> board = loadTestBoard();
290
291 TEMP_FILE ses( wxT( "kicad_specctra_24948_" ) );
292
293 // The valid wire uses a layer name taken from the loaded board so this is a faithful
294 // router-output fragment; the placement id and the second wire's layer are deliberately absent.
295 const std::string validLayer = std::string( board->GetLayerName( F_Cu ).ToUTF8() );
296
297 std::ofstream out( ses.Path() );
298 out << "(session test.ses\n"
299 << " (base_design test.dsn)\n"
300 << " (placement\n"
301 << " (resolution um 10)\n"
302 << " (component test\n"
303 << " (place Nonexistent_Ref 0 0 front 0)\n"
304 << " )\n"
305 << " )\n"
306 << " (routes\n"
307 << " (resolution um 10)\n"
308 << " (library_out )\n"
309 << " (network_out\n"
310 << " (net \"/ALLPST\"\n"
311 << " (wire (path \"" << validLayer << "\" 1600 0 0 1000 0))\n"
312 << " (wire (path Bogus_Missing_Layer 1600 0 0 1000 1000))\n"
313 << " )\n"
314 << " )\n"
315 << " )\n"
316 << ")\n";
317 out.close();
318
319#ifdef __WXMAC__
320 // Don't convert log messages to throws, as they will trip up BOOST_REQUIRE_NO_THROW
321 wxLog::SetTimestamp( wxEmptyString );
322#endif
323
324 BOOST_REQUIRE_NO_THROW( importSession( board.get(), ses.Str() ) );
325
326 // The session replaces all unlocked traces; only the valid wire survives, the bogus wire and
327 // the unresolved placement are dropped rather than throwing.
328 BOOST_CHECK_EQUAL( countTraces( board.get() ), 1 );
329}
330
331
332/*
333 * DSN export must produce a file that the DSN parser can read back.
334 */
335BOOST_AUTO_TEST_CASE( SpecctraDsnExportParseable )
336{
337 LOCALE_IO toggle;
338 std::unique_ptr<BOARD> board = loadTestBoard();
339
340 TEMP_FILE out( wxT( "kicad_specctra_parseable_" ) );
341 BOOST_REQUIRE_NO_THROW( ExportBoardToSpecctraFile( board.get(), out.Str() ) );
342
343 SPECCTRA_DB db;
344 try
345 {
346 db.LoadPCB( out.WxStr() );
347 BOOST_CHECK( db.GetPCB() != nullptr );
348 }
349 catch( const IO_ERROR& ioe )
350 {
351 BOOST_FAIL( ioe.What().ToStdString() );
352 }
353}
354
355
356BOOST_AUTO_TEST_CASE( SpecctraDsnExportContent )
357{
358 LOCALE_IO toggle;
359 std::unique_ptr<BOARD> board = loadTestBoard();
360
361 BOOST_REQUIRE( !board->Footprints().empty() );
362
363 TEMP_FILE out( wxT( "kicad_specctra_content_" ) );
364 BOOST_REQUIRE_NO_THROW( ExportBoardToSpecctraFile( board.get(), out.Str() ) );
365
366 const std::string dsn = slurp( out.Path() );
367
368 // The unit declaration the exporter writes (mm-based resolution; um units).
369 BOOST_CHECK( dsn.find( "(unit um" ) != std::string::npos );
370
371 // At least one (net "<name>" header matches an existing net.
372 bool netHeaderFound = false;
373
374 for( const NETINFO_ITEM* net : board->GetNetInfo().NetsByNetcode() | std::views::values )
375 {
376 if( net->GetNetname().IsEmpty() )
377 continue;
378
379 if( dsn.find( "(net \"" + std::string( net->GetNetname().ToUTF8() ) + "\"" ) != std::string::npos )
380 netHeaderFound = true;
381 }
382
383 BOOST_CHECK( netHeaderFound );
384}
385
386
387BOOST_AUTO_TEST_CASE( SpecctraExportReporterCapturesOutlineWarning )
388{
389 LOCALE_IO toggle;
390
391 std::unique_ptr<BOARD> board = std::make_unique<BOARD>();
392
394 TEMP_FILE out( wxT( "kicad_specctra_reporter_" ) );
395 BOOST_REQUIRE_NO_THROW( ExportBoardToSpecctraFile( board.get(), out.WxStr(), &reporter ) );
396
397 BOOST_CHECK( reporter.GetMessages().Contains( wxT( "Board outline is malformed" ) ) );
398}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
General utilities for PCB file IO for QA programs.
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:1548
const TRACKS & Tracks() const
Definition board.h:463
A DSN data tree, usually coming from a DSN file.
Definition specctra.h:3621
void LoadPCB(const wxString &aFilename)
A recursive descent parser for a SPECCTRA DSN "design" file.
Definition specctra.cpp:246
void SetPosition(const VECTOR2I &aPos) override
void SetOrientation(const EDA_ANGLE &aNewAngle)
void SetReference(const wxString &aReference)
Definition footprint.h:799
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Adds an item to the container.
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition locale_io.h:37
Handle the data for a net.
Definition netinfo.h:50
void SetEnd(const VECTOR2I &aEnd) override
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
void SetStart(const VECTOR2I &aStart) override
Master controller class:
void RegisterTool(TOOL_BASE *aTool)
Add a tool to the manager set and sets it up.
void SetEnvironment(EDA_ITEM *aModel, KIGFX::VIEW *aView, KIGFX::VIEW_CONTROLS *aViewControls, APP_SETTINGS_BASE *aSettings, TOOLS_HOLDER *aFrame)
Set the work environment (model, view, view controls and the parent window).
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 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
virtual void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
Definition zone.cpp:677
void SetIsRuleArea(bool aEnable)
Definition zone.h:835
void SetDoNotAllowTracks(bool aEnable)
Definition zone.h:859
void SetDoNotAllowVias(bool aEnable)
Definition zone.h:858
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
@ SEGMENT
Definition eda_shape.h:57
@ Edge_Cuts
Definition layer_ids.h:108
@ F_Cu
Definition layer_ids.h:60
This source file implements export and import capabilities to the specctra dsn file format.
Definition specctra.cpp:60
void ExportBoardToSpecctraFile(BOARD *aBoard, const wxString &aFullFilename, REPORTER *aReporter=nullptr)
Helper method to export board to DSN file.
bool ImportSpecctraSession(BOARD *aBoard, const wxString &fullFileName, COMMIT &aCommit, REPORTER *aReporter=nullptr, int *aSkippedCount=nullptr)
Helper method to import SES file to a board.
std::string GetPcbnewTestDataDir()
Utility which returns a path to the data directory where the test board files are stored.
std::unique_ptr< BOARD > RequireBoardFromPcbnewQAData(const std::filesystem::path &aFilename)
Require a board from the path relative to the pcbnew QA data directory.
#define SKIP_UNDO
Definition sch_commit.h:38
BOOST_CHECK(res.column_datatype(0)==SQL_NUMERIC||res.column_datatype(0)==SQL_DECIMAL)
BOOST_CHECK_EQUAL(std::any_cast< std::string >(rows[0].at("val")), "12345678901234567.89")
BOOST_REQUIRE(res.columns()==1)
IbisParser parser & reporter
BOOST_AUTO_TEST_CASE(SpecctraExportQuoteInField)
@ 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