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
134BOARD* PCB_IO_EASYEDA::LoadBoard( const wxString& aFileName, BOARD* aAppendToMe,
135 const std::map<std::string, UTF8>* aProperties, PROJECT* aProject )
136{
137 m_loadedFootprints.clear();
138
139 m_props = aProperties;
140 m_board = aAppendToMe ? aAppendToMe : new BOARD();
141
142 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
144
145 // Give the filename to the board if it's new
146 if( !aAppendToMe )
147 m_board->SetFileName( aFileName );
148
150 {
151 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
152
153 if( !m_progressReporter->KeepRefreshing() )
154 THROW_IO_ERROR( _( "File import canceled by user." ) );
155 }
156
157 PCB_IO_EASYEDA_PARSER parser( nullptr );
158
159 try
160 {
161 wxFFileInputStream in( aFileName );
162 nlohmann::json js;
164
165 if( !FindBoardInStream( aFileName, in, js, doc ) )
166 THROW_IO_ERRORF( _( "Unable to find a valid board in '%s'" ), aFileName );
167
169
170 const int innerStart = 21;
171 const int innerEnd = 52;
172
173 int maxLayer = innerStart;
174 std::map<PCB_LAYER_ID, wxString> layerNames;
175
176 for( const wxString& layerLine : pcbDoc.layers )
177 {
178 wxArrayString parts = wxSplit( layerLine, '~', '\0' );
179 int layerId = wxAtoi( parts[0] );
180 wxString layerName = parts[1];
181 wxString layerColor = parts[2];
182 wxString visible = parts[3];
183 wxString active = parts[4];
184 bool enabled = parts[5] != wxS( "false" );
185
186 if( layerId >= innerStart && layerId <= innerEnd && enabled )
187 maxLayer = layerId + 1;
188
189 layerNames[parser.LayerToKi( parts[0] )] = layerName;
190 }
191
192 m_board->SetCopperLayerCount( 2 + maxLayer - innerStart );
193
194 for( auto& [klayer, name] : layerNames )
195 m_board->SetLayerName( klayer, name );
196
197 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
198 std::shared_ptr<NETCLASS> defNetclass = bds.m_NetSettings->GetDefaultNetclass();
199
200 if( pcbDoc.DRCRULE )
201 {
202 std::map<wxString, nlohmann::json>& rules = *pcbDoc.DRCRULE;
203
204 if( auto defRules = get_opt( rules, "Default" ) )
205 {
206 wxString key;
207
208 key = wxS( "trackWidth" );
209 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
210 {
211 double val = parser.ScaleSize( defRules->at( key ) );
212 defNetclass->SetTrackWidth( val );
213 }
214
215 key = wxS( "clearance" );
216 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
217 {
218 double val = parser.ScaleSize( defRules->at( key ) );
219 defNetclass->SetClearance( val );
220 }
221
222 key = wxS( "viaHoleD" );
223 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
224 {
225 double val = parser.ScaleSize( defRules->at( key ) );
226
227 defNetclass->SetViaDrill( val );
228 }
229
230 key = wxS( "viaHoleDiameter" ); // Yes, this is via diameter, not drill diameter
231 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
232 {
233 double val = parser.ScaleSize( defRules->at( key ) );
234 defNetclass->SetViaDiameter( val );
235 }
236 }
237 }
238
239 VECTOR2D origin( doc.head.x, doc.head.y );
240 parser.ParseBoard( m_board, origin, m_loadedFootprints, doc.shape );
241
242 // Center the board
243 BOX2I outlineBbox = m_board->ComputeBoundingBox( true, true );
244 PAGE_INFO pageInfo = m_board->GetPageSettings();
245
246 VECTOR2D pageCenter( pcbIUScale.MilsToIU( pageInfo.GetWidthMils() / 2 ),
247 pcbIUScale.MilsToIU( pageInfo.GetHeightMils() / 2 ) );
248
249 VECTOR2D offset = pageCenter - outlineBbox.GetCenter();
250
251 int alignGrid = pcbIUScale.mmToIU( 10 );
252 offset.x = KiROUND( offset.x / alignGrid ) * alignGrid;
253 offset.y = KiROUND( offset.y / alignGrid ) * alignGrid;
254
255 m_board->Move( offset );
256 bds.SetAuxOrigin( offset );
257
258 return m_board;
259 }
260 catch( nlohmann::json::exception& e )
261 {
262 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
263 }
264 catch( std::exception& e )
265 {
266 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
267 }
268}
269
270
271long long PCB_IO_EASYEDA::GetLibraryTimestamp( const wxString& aLibraryPath ) const
272{
273 return 0;
274}
275
276
277void PCB_IO_EASYEDA::FootprintEnumerate( wxArrayString& aFootprintNames,
278 const wxString& aLibraryPath, bool aBestEfforts,
279 const std::map<std::string, UTF8>* aProperties )
280{
281 try
282 {
283 wxFFileInputStream in( aLibraryPath );
284 nlohmann::json js;
286
287 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
288 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
289
292 {
293 for( wxString shap : doc.shape )
294 {
295 shap.Replace( wxS( "#@$" ), "\n" );
296 wxArrayString parts = wxSplit( shap, '\n', '\0' );
297
298 if( parts.size() < 1 )
299 continue;
300
301 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
302
303 if( paramsRoot.size() < 1 )
304 continue;
305
306 wxString rootType = paramsRoot[0];
307
308 if( rootType == wxS( "LIB" ) )
309 {
310 if( paramsRoot.size() < 4 )
311 continue;
312
313 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
314 paramsRoot[2] );
315
316 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
317
318 std::map<wxString, wxString> paramMap;
319
320 for( int i = 1; i < (int) paramParts.size(); i += 2 )
321 {
322 wxString key = paramParts[i - 1];
323 wxString value = paramParts[i];
324
325 if( key == wxS( "package" ) )
326 packageName = value;
327
328 paramMap[key] = value;
329 }
330
331 aFootprintNames.Add( packageName );
332 }
333 }
334 }
336 {
338
339 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
340 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
341
342 std::optional<std::map<wxString, wxString>> c_para;
343
344 if( pcbDoc.c_para )
345 c_para = pcbDoc.c_para;
346 else if( doc.head.c_para )
347 c_para = doc.head.c_para;
348
349 if( c_para )
350 packageName = get_def( *c_para, wxS( "package" ), packageName );
351
352 aFootprintNames.Add( packageName );
353 }
354 }
355 catch( nlohmann::json::exception& e )
356 {
357 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
358 }
359 catch( std::exception& e )
360 {
361 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
362 }
363}
364
365
366FOOTPRINT* PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath,
367 const wxString& aFootprintName, bool aKeepUUID,
368 const std::map<std::string, UTF8>* aProperties )
369{
370 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
371 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
372
373 PCB_IO_EASYEDA_PARSER parser( nullptr );
374
375 m_loadedFootprints.clear();
376
377 try
378 {
379 wxFFileInputStream in( aLibraryPath );
380 nlohmann::json js;
382
383 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
384 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
385
388 {
389 for( wxString shap : doc.shape )
390 {
391 if( !shap.Contains( wxS( "LIB" ) ) )
392 continue;
393
394 shap.Replace( wxS( "#@$" ), "\n" );
395 wxArrayString parts = wxSplit( shap, '\n', '\0' );
396
397 if( parts.size() < 1 )
398 continue;
399
400 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
401
402 if( paramsRoot.size() < 1 )
403 continue;
404
405 wxString rootType = paramsRoot[0];
406
407 if( rootType == wxS( "LIB" ) )
408 {
409 if( paramsRoot.size() < 4 )
410 continue;
411
412 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
413 parser.Convert( paramsRoot[2] ) );
414
415 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
416 paramsRoot[2] );
417
418 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
419
420 std::map<wxString, wxString> paramMap;
421
422 for( int i = 1; i < (int) paramParts.size(); i += 2 )
423 {
424 wxString key = paramParts[i - 1];
425 wxString value = paramParts[i];
426
427 if( key == wxS( "package" ) )
428 packageName = value;
429
430 paramMap[key] = value;
431 }
432
433 EDA_ANGLE orientation;
434 if( !paramsRoot[4].IsEmpty() )
435 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
436
437 int layer = 1;
438
439 if( !paramsRoot[7].IsEmpty() )
440 layer = parser.Convert( paramsRoot[7] );
441
442 if( packageName == aFootprintName )
443 {
444 parts.RemoveAt( 0 );
445
446 FOOTPRINT* footprint = parser.ParseFootprint( origin, orientation, layer, nullptr,
447 paramMap, m_loadedFootprints, parts );
448
449 if( !footprint )
450 return nullptr;
451
452 footprint->Reference().SetPosition( VECTOR2I() );
453 footprint->Reference().SetTextAngle( ANGLE_0 );
454 footprint->Reference().SetVisible( true );
455
456 footprint->Value().SetPosition( VECTOR2I() );
457 footprint->Value().SetTextAngle( ANGLE_0 );
458 footprint->Value().SetVisible( true );
459
460 footprint->AutoPositionFields();
461
462 return footprint;
463 }
464 }
465 }
466 }
468 {
470
471 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
472 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
473
474 std::optional<std::map<wxString, wxString>> c_para;
475
476 if( pcbDoc.c_para )
477 c_para = pcbDoc.c_para;
478 else if( doc.head.c_para )
479 c_para = doc.head.c_para;
480
481 if( c_para )
482 {
483 packageName = get_def( *c_para, wxS( "package" ), packageName );
484
485 if( packageName != aFootprintName )
486 return nullptr;
487
488 VECTOR2D origin( doc.head.x, doc.head.y );
489
490 FOOTPRINT* footprint = parser.ParseFootprint( origin, ANGLE_0, F_Cu, nullptr, *c_para,
492
493 if( !footprint )
494 return nullptr;
495
496 footprint->Reference().SetPosition( VECTOR2I() );
497 footprint->Reference().SetTextAngle( ANGLE_0 );
498 footprint->Reference().SetVisible( true );
499
500 footprint->Value().SetPosition( VECTOR2I() );
501 footprint->Value().SetTextAngle( ANGLE_0 );
502 footprint->Value().SetVisible( true );
503
504 footprint->AutoPositionFields();
505
506 return footprint;
507 }
508 }
509 }
510 catch( nlohmann::json::exception& e )
511 {
512 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
513 aFootprintName,
514 aLibraryPath,
515 e.what() );
516 }
517 catch( std::exception& e )
518 {
519 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
520 aFootprintName,
521 aLibraryPath,
522 e.what() );
523 }
524
525 return nullptr;
526}
527
528
530{
531 std::vector<FOOTPRINT*> result;
532
533 for( auto& [fpUuid, footprint] : m_loadedFootprints )
534 {
535 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
536 }
537
538 return result;
539}
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:121
BOX2< VECTOR2I > BOX2I
Definition box2.h:918
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:986
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:373
constexpr const Vec GetCenter() const
Definition box2.h:226
static double Convert(const wxString &aValue)
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:381
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:368
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:893
PCB_FIELD & Reference()
Definition footprint.h:894
void AutoPositionFields()
Position Reference and Value fields at the top and bottom of footprint's bounding box.
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:306
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
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.
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...
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.
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).
BOARD * LoadBoard(const wxString &aFileName, BOARD *aAppendToMe, const std::map< std::string, UTF8 > *aProperties=nullptr, PROJECT *aProject=nullptr) override
Load information from some input file format that this PCB_IO implementation knows about into either ...
bool CanReadFootprint(const wxString &aFileName) const override
Checks if this PCB_IO can read a footprint from specified file or directory.
BOARD * m_board
The board BOARD being worked on, no ownership here.
Definition pcb_io.h:349
virtual bool CanReadBoard(const wxString &aFileName) const
Checks if this PCB_IO can read the specified board file.
Definition pcb_io.cpp:38
PCB_IO(const wxString &aName)
Definition pcb_io.h:342
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:352
virtual void SetPosition(const VECTOR2I &aPos) override
Definition pcb_text.h:95
void SetTextAngle(const EDA_ANGLE &aAngle) override
Definition pcb_text.cpp:553
Container for project specific data.
Definition project.h:63
The common library.
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:411
@ DEGREES_T
Definition eda_angle.h:31
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
@ 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