KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pcb_io_easyeda_plugin.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2023 Alex Shvartzkop <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
24#include <pcb_io/pcb_io.h>
25
26#include <font/fontconfig.h>
27#include <progress_reporter.h>
28#include <common.h>
29#include <macros.h>
30#include <board.h>
31#include <footprint.h>
34#include <reporter.h>
35
36#include <wx/log.h>
37#include <wx/wfstream.h>
38#include <wx/zipstrm.h>
39#include <wx/stdstream.h>
40
41#include <json_common.h>
42#include <core/map_helpers.h>
43
44
45PCB_IO_EASYEDA::PCB_IO_EASYEDA() : PCB_IO( wxS( "EasyEDA (JLCEDA) Standard" ) )
46{
47}
48
49
53
54
55static bool FindBoardInStream( const wxString& aName, wxInputStream& aStream, nlohmann::json& aOut,
56 EASYEDA::DOCUMENT& aDoc )
57{
58 if( aName.Lower().EndsWith( wxS( ".json" ) ) )
59 {
60 wxStdInputStream sin( aStream );
61 nlohmann::json js = nlohmann::json::parse( sin, nullptr, false );
62
63 if( js.is_discarded() )
64 return false;
65
67
71 {
72 aOut = js;
73 aDoc = doc;
74 return true;
75 }
76 }
77 else if( aName.Lower().EndsWith( wxS( ".zip" ) ) )
78 {
79 std::shared_ptr<wxZipEntry> entry;
80 wxZipInputStream zip( aStream );
81
82 if( !zip.IsOk() )
83 return false;
84
85 while( entry.reset( zip.GetNextEntry() ), entry.get() != NULL )
86 {
87 wxString name = entry->GetName();
88
89 if( FindBoardInStream( name, zip, aOut, aDoc ) )
90 return true;
91 }
92 }
93
94 return false;
95}
96
97
98bool PCB_IO_EASYEDA::CanReadBoard( const wxString& aFileName ) const
99{
100 if( !PCB_IO::CanReadBoard( aFileName ) )
101 return false;
102
103 try
104 {
105 wxFFileInputStream in( aFileName );
106 nlohmann::json js;
108
109 return FindBoardInStream( aFileName, in, js, doc );
110 }
111 catch( nlohmann::json::exception& )
112 {
113 }
114 catch( std::exception& )
115 {
116 }
117
118 return false;
119}
120
121
122bool PCB_IO_EASYEDA::CanReadFootprint( const wxString& aFileName ) const
123{
124 return CanReadBoard( aFileName );
125}
126
127
128bool PCB_IO_EASYEDA::CanReadLibrary( const wxString& aFileName ) const
129{
130 return CanReadBoard( aFileName );
131}
132
133
134void PCB_IO_EASYEDA::loadBoard( const wxString& aFileName, BOARD& aBoard, bool aIsNewLoad,
135 const std::map<std::string, UTF8>* aProperties, PROJECT* aProject )
136{
137 m_loadedFootprints.clear();
138
139 m_props = aProperties;
140 m_board = &aBoard;
141
142 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
144
146 {
147 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
148
149 if( !m_progressReporter->KeepRefreshing() )
151 }
152
153 PCB_IO_EASYEDA_PARSER parser( nullptr );
154
155 try
156 {
157 wxFFileInputStream in( aFileName );
158 nlohmann::json js;
160
161 if( !FindBoardInStream( aFileName, in, js, doc ) )
162 THROW_IO_ERRORF( _( "Unable to find a valid board in '%s'" ), aFileName );
163
165
166 const int innerStart = 21;
167 const int innerEnd = 52;
168
169 int maxLayer = innerStart;
170 std::map<PCB_LAYER_ID, wxString> layerNames;
171
172 for( const wxString& layerLine : pcbDoc.layers )
173 {
174 wxArrayString parts = wxSplit( layerLine, '~', '\0' );
175 int layerId = wxAtoi( parts[0] );
176 wxString layerName = parts[1];
177 wxString layerColor = parts[2];
178 wxString visible = parts[3];
179 wxString active = parts[4];
180 bool enabled = parts[5] != wxS( "false" );
181
182 if( layerId >= innerStart && layerId <= innerEnd && enabled )
183 maxLayer = layerId + 1;
184
185 layerNames[parser.LayerToKi( parts[0] )] = layerName;
186 }
187
188 m_board->SetCopperLayerCount( 2 + maxLayer - innerStart );
189
190 for( auto& [klayer, name] : layerNames )
191 m_board->SetLayerName( klayer, name );
192
193 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
194 std::shared_ptr<NETCLASS> defNetclass = bds.m_NetSettings->GetDefaultNetclass();
195
196 if( pcbDoc.DRCRULE )
197 {
198 std::map<wxString, nlohmann::json>& rules = *pcbDoc.DRCRULE;
199
200 if( auto defRules = get_opt( rules, "Default" ) )
201 {
202 wxString key;
203
204 key = wxS( "trackWidth" );
205 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
206 {
207 double val = parser.ScaleSize( defRules->at( key ) );
208 defNetclass->SetTrackWidth( val );
209 }
210
211 key = wxS( "clearance" );
212 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
213 {
214 double val = parser.ScaleSize( defRules->at( key ) );
215 defNetclass->SetClearance( val );
216 }
217
218 key = wxS( "viaHoleD" );
219 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
220 {
221 double val = parser.ScaleSize( defRules->at( key ) );
222
223 defNetclass->SetViaDrill( val );
224 }
225
226 key = wxS( "viaHoleDiameter" ); // Yes, this is via diameter, not drill diameter
227 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
228 {
229 double val = parser.ScaleSize( defRules->at( key ) );
230 defNetclass->SetViaDiameter( val );
231 }
232 }
233 }
234
235 VECTOR2D origin( doc.head.x, doc.head.y );
236 parser.ParseBoard( m_board, origin, m_loadedFootprints, doc.shape );
237
238 // Center the board
239 BOX2I outlineBbox = m_board->ComputeBoundingBox( true, true );
240 PAGE_INFO pageInfo = m_board->GetPageSettings();
241
242 VECTOR2D pageCenter( pcbIUScale.MilsToIU( pageInfo.GetWidthMils() / 2 ),
243 pcbIUScale.MilsToIU( pageInfo.GetHeightMils() / 2 ) );
244
245 VECTOR2D offset = pageCenter - outlineBbox.GetCenter();
246
247 int alignGrid = pcbIUScale.mmToIU( 10 );
248 offset.x = KiROUND( offset.x / alignGrid ) * alignGrid;
249 offset.y = KiROUND( offset.y / alignGrid ) * alignGrid;
250
251 m_board->Move( offset );
252 bds.SetAuxOrigin( offset );
253 }
254 catch( nlohmann::json::exception& e )
255 {
256 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
257 }
258 catch( std::exception& e )
259 {
260 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
261 }
262}
263
264
265long long PCB_IO_EASYEDA::GetLibraryTimestamp( const wxString& aLibraryPath ) const
266{
267 return 0;
268}
269
270
271void PCB_IO_EASYEDA::FootprintEnumerate( wxArrayString& aFootprintNames,
272 const wxString& aLibraryPath, bool aBestEfforts,
273 const std::map<std::string, UTF8>* aProperties )
274{
275 try
276 {
277 wxFFileInputStream in( aLibraryPath );
278 nlohmann::json js;
280
281 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
282 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
283
286 {
287 for( wxString shap : doc.shape )
288 {
289 shap.Replace( wxS( "#@$" ), "\n" );
290 wxArrayString parts = wxSplit( shap, '\n', '\0' );
291
292 if( parts.size() < 1 )
293 continue;
294
295 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
296
297 if( paramsRoot.size() < 1 )
298 continue;
299
300 wxString rootType = paramsRoot[0];
301
302 if( rootType == wxS( "LIB" ) )
303 {
304 if( paramsRoot.size() < 4 )
305 continue;
306
307 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
308 paramsRoot[2] );
309
310 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
311
312 std::map<wxString, wxString> paramMap;
313
314 for( int i = 1; i < (int) paramParts.size(); i += 2 )
315 {
316 wxString key = paramParts[i - 1];
317 wxString value = paramParts[i];
318
319 if( key == wxS( "package" ) )
320 packageName = value;
321
322 paramMap[key] = value;
323 }
324
325 aFootprintNames.Add( packageName );
326 }
327 }
328 }
330 {
332
333 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
334 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
335
336 std::optional<std::map<wxString, wxString>> c_para;
337
338 if( pcbDoc.c_para )
339 c_para = pcbDoc.c_para;
340 else if( doc.head.c_para )
341 c_para = doc.head.c_para;
342
343 if( c_para )
344 packageName = get_def( *c_para, wxS( "package" ), packageName );
345
346 aFootprintNames.Add( packageName );
347 }
348 }
349 catch( nlohmann::json::exception& e )
350 {
351 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
352 }
353 catch( std::exception& e )
354 {
355 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
356 }
357}
358
359
360std::unique_ptr<FOOTPRINT> PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath, const wxString& aFootprintName,
361 bool aKeepUUID,
362 const std::map<std::string, UTF8>* aProperties )
363{
364 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
365 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
366
367 PCB_IO_EASYEDA_PARSER parser( nullptr );
368
369 m_loadedFootprints.clear();
370
371 try
372 {
373 wxFFileInputStream in( aLibraryPath );
374 nlohmann::json js;
376
377 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
378 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
379
382 {
383 for( wxString shap : doc.shape )
384 {
385 if( !shap.Contains( wxS( "LIB" ) ) )
386 continue;
387
388 shap.Replace( wxS( "#@$" ), "\n" );
389 wxArrayString parts = wxSplit( shap, '\n', '\0' );
390
391 if( parts.size() < 1 )
392 continue;
393
394 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
395
396 if( paramsRoot.size() < 1 )
397 continue;
398
399 wxString rootType = paramsRoot[0];
400
401 if( rootType == wxS( "LIB" ) )
402 {
403 if( paramsRoot.size() < 4 )
404 continue;
405
406 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
407 parser.Convert( paramsRoot[2] ) );
408
409 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
410 paramsRoot[2] );
411
412 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
413
414 std::map<wxString, wxString> paramMap;
415
416 for( int i = 1; i < (int) paramParts.size(); i += 2 )
417 {
418 wxString key = paramParts[i - 1];
419 wxString value = paramParts[i];
420
421 if( key == wxS( "package" ) )
422 packageName = value;
423
424 paramMap[key] = value;
425 }
426
427 EDA_ANGLE orientation;
428 if( !paramsRoot[4].IsEmpty() )
429 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
430
431 int layer = 1;
432
433 if( !paramsRoot[7].IsEmpty() )
434 layer = parser.Convert( paramsRoot[7] );
435
436 if( packageName == aFootprintName )
437 {
438 parts.RemoveAt( 0 );
439
440 std::unique_ptr<FOOTPRINT> footprint = parser.ParseFootprint(
441 origin, orientation, layer, nullptr, paramMap, m_loadedFootprints, parts );
442
443 if( !footprint )
444 return nullptr;
445
446 footprint->Reference().SetPosition( VECTOR2I() );
447 footprint->Reference().SetTextAngle( ANGLE_0 );
448 footprint->Reference().SetVisible( true );
449
450 footprint->Value().SetPosition( VECTOR2I() );
451 footprint->Value().SetTextAngle( ANGLE_0 );
452 footprint->Value().SetVisible( true );
453
454 footprint->AutoPositionFields();
455
456 return footprint;
457 }
458 }
459 }
460 }
462 {
464
465 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
466 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
467
468 std::optional<std::map<wxString, wxString>> c_para;
469
470 if( pcbDoc.c_para )
471 c_para = pcbDoc.c_para;
472 else if( doc.head.c_para )
473 c_para = doc.head.c_para;
474
475 if( c_para )
476 {
477 packageName = get_def( *c_para, wxS( "package" ), packageName );
478
479 if( packageName != aFootprintName )
480 return nullptr;
481
482 VECTOR2D origin( doc.head.x, doc.head.y );
483
484 std::unique_ptr<FOOTPRINT> footprint( parser.ParseFootprint( origin, ANGLE_0, F_Cu, nullptr, *c_para,
485 m_loadedFootprints, doc.shape ) );
486
487 if( !footprint )
488 return nullptr;
489
490 footprint->Reference().SetPosition( VECTOR2I() );
491 footprint->Reference().SetTextAngle( ANGLE_0 );
492 footprint->Reference().SetVisible( true );
493
494 footprint->Value().SetPosition( VECTOR2I() );
495 footprint->Value().SetTextAngle( ANGLE_0 );
496 footprint->Value().SetVisible( true );
497
498 footprint->AutoPositionFields();
499
500 return footprint;
501 }
502 }
503 }
504 catch( nlohmann::json::exception& e )
505 {
506 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
507 aFootprintName,
508 aLibraryPath,
509 e.what() );
510 }
511 catch( std::exception& e )
512 {
513 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
514 aFootprintName,
515 aLibraryPath,
516 e.what() );
517 }
518
519 return nullptr;
520}
521
522
524{
525 std::vector<FOOTPRINT*> result;
526
527 for( auto& [fpUuid, footprint] : m_loadedFootprints )
528 {
529 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
530 }
531
532 return result;
533}
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:121
BOX2< VECTOR2I > BOX2I
Definition box2.h:927
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:995
Container for design settings for a BOARD object.
std::shared_ptr< NET_SETTINGS > m_NetSettings
void SetAuxOrigin(const VECTOR2I &aOrigin)
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:409
constexpr const Vec GetCenter() const
Definition box2.h:227
static double Convert(const wxString &aValue)
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:385
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition io_base.h:241
static LOAD_INFO_REPORTER & GetInstance()
Definition reporter.cpp:351
std::shared_ptr< NETCLASS > GetDefaultNetclass() const
Gets the default netclass for the project.
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
double GetHeightMils() const
Definition page_info.h:143
double GetWidthMils() const
Definition page_info.h:138
std::unique_ptr< FOOTPRINT > ParseFootprint(const VECTOR2D &aOrigin, const EDA_ANGLE &aOrientation, int aLayer, BOARD *aParent, std::map< wxString, wxString > aParams, std::map< wxString, std::unique_ptr< FOOTPRINT > > &aFootprintMap, wxArrayString aShapes)
double ScaleSize(double aValue) override
void ParseBoard(BOARD *aBoard, const VECTOR2D &aOrigin, std::map< wxString, std::unique_ptr< FOOTPRINT > > &aFootprintMap, wxArrayString aShapes)
PCB_LAYER_ID LayerToKi(const wxString &aLayer)
bool CanReadBoard(const wxString &aFileName) const override
Checks if this PCB_IO can read the specified board file.
bool CanReadLibrary(const wxString &aFileName) const override
Checks if this IO object can read the specified library file/directory.
void FootprintEnumerate(wxArrayString &aFootprintNames, const wxString &aLibraryPath, bool aBestEfforts, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Return a list of footprint names contained within the library at aLibraryPath.
void loadBoard(const wxString &aFileName, BOARD &aBoard, bool aIsNewLoad, const std::map< std::string, UTF8 > *aProperties=nullptr, PROJECT *aProject=nullptr) override
Parse aFileName into aBoard.
std::map< wxString, std::unique_ptr< FOOTPRINT > > m_loadedFootprints
std::vector< FOOTPRINT * > GetImportedCachedLibraryFootprints() override
Return a container with the cached library footprints generated in the last call to Load.
long long GetLibraryTimestamp(const wxString &aLibraryPath) const override
Generate a timestamp representing all the files in the library (including the library directory).
bool CanReadFootprint(const wxString &aFileName) const override
Checks if this PCB_IO can read a footprint from specified file or directory.
std::unique_ptr< FOOTPRINT > FootprintLoad(const wxString &aLibraryPath, const wxString &aFootprintName, bool aKeepUUID=false, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a footprint having aFootprintName from the aLibraryPath containing a library format that this PC...
BOARD * m_board
The board BOARD being worked on, no ownership here.
Definition pcb_io.h:368
virtual bool CanReadBoard(const wxString &aFileName) const
Checks if this PCB_IO can read the specified board file.
Definition pcb_io.cpp:40
PCB_IO(const wxString &aName)
Definition pcb_io.h:351
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:371
Container for project specific data.
Definition project.h:63
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:422
@ DEGREES_T
Definition eda_angle.h:31
#define THROW_IO_ERRORF(msg,...)
#define THROW_IO_CANCELLED()
@ F_Cu
Definition layer_ids.h:60
This file contains miscellaneous commonly used macros and functions.
wxString get_def(const std::map< wxString, wxString > &aMap, const char *aKey, const char *aDefval="")
Definition map_helpers.h:60
std::optional< V > get_opt(const std::map< wxString, V > &aMap, const wxString &aKey)
Definition map_helpers.h:30
static bool FindBoardInStream(const wxString &aName, wxInputStream &aStream, nlohmann::json &aOut, EASYEDA::DOCUMENT &aDoc)
std::optional< std::map< wxString, nlohmann::json > > DRCRULE
std::optional< std::map< wxString, wxString > > c_para
std::vector< wxString > layers
std::optional< wxString > uuid
std::optional< std::map< wxString, wxString > > c_para
wxString result
Test unit parsing edge cases and error handling.
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683
VECTOR2< double > VECTOR2D
Definition vector2d.h:682