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 bool importedNetclassRules = false;
196
197
198 if( pcbDoc.DRCRULE )
199 {
200 std::map<wxString, nlohmann::json>& rules = *pcbDoc.DRCRULE;
201
202 if( auto defRules = get_opt( rules, "Default" ) )
203 {
204 wxString key;
205
206 key = wxS( "trackWidth" );
207 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
208 {
209 double val = parser.ScaleSize( defRules->at( key ) );
210 defNetclass->SetTrackWidth( val );
211 importedNetclassRules = true;
212 }
213
214 key = wxS( "clearance" );
215 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
216 {
217 double val = parser.ScaleSize( defRules->at( key ) );
218 defNetclass->SetClearance( val );
219 importedNetclassRules = true;
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 importedNetclassRules = true;
229 }
230
231 key = wxS( "viaHoleDiameter" ); // Yes, this is via diameter, not drill diameter
232 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
233 {
234 double val = parser.ScaleSize( defRules->at( key ) );
235 defNetclass->SetViaDiameter( val );
236 importedNetclassRules = true;
237 }
238 }
239 }
240 if( importedNetclassRules )
241 m_board->m_LegacyNetclassesLoaded = true;
242
243
244 VECTOR2D origin( doc.head.x, doc.head.y );
245 parser.ParseBoard( m_board, origin, m_loadedFootprints, doc.shape );
246
247 // Center the board
248 BOX2I outlineBbox = m_board->ComputeBoundingBox( true, true );
249 PAGE_INFO pageInfo = m_board->GetPageSettings();
250
251 VECTOR2D pageCenter( pcbIUScale.MilsToIU( pageInfo.GetWidthMils() / 2 ),
252 pcbIUScale.MilsToIU( pageInfo.GetHeightMils() / 2 ) );
253
254 VECTOR2D offset = pageCenter - outlineBbox.GetCenter();
255
256 int alignGrid = pcbIUScale.mmToIU( 10 );
257 offset.x = KiROUND( offset.x / alignGrid ) * alignGrid;
258 offset.y = KiROUND( offset.y / alignGrid ) * alignGrid;
259
260 m_board->Move( offset );
261 bds.SetAuxOrigin( offset );
262 }
263 catch( nlohmann::json::exception& e )
264 {
265 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
266 }
267 catch( std::exception& e )
268 {
269 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
270 }
271}
272
273
274long long PCB_IO_EASYEDA::GetLibraryTimestamp( const wxString& aLibraryPath ) const
275{
276 return 0;
277}
278
279
280void PCB_IO_EASYEDA::FootprintEnumerate( wxArrayString& aFootprintNames,
281 const wxString& aLibraryPath, bool aBestEfforts,
282 const std::map<std::string, UTF8>* aProperties )
283{
284 try
285 {
286 wxFFileInputStream in( aLibraryPath );
287 nlohmann::json js;
289
290 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
291 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
292
295 {
296 for( wxString shap : doc.shape )
297 {
298 shap.Replace( wxS( "#@$" ), "\n" );
299 wxArrayString parts = wxSplit( shap, '\n', '\0' );
300
301 if( parts.size() < 1 )
302 continue;
303
304 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
305
306 if( paramsRoot.size() < 1 )
307 continue;
308
309 wxString rootType = paramsRoot[0];
310
311 if( rootType == wxS( "LIB" ) )
312 {
313 if( paramsRoot.size() < 4 )
314 continue;
315
316 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
317 paramsRoot[2] );
318
319 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
320
321 std::map<wxString, wxString> paramMap;
322
323 for( int i = 1; i < (int) paramParts.size(); i += 2 )
324 {
325 wxString key = paramParts[i - 1];
326 wxString value = paramParts[i];
327
328 if( key == wxS( "package" ) )
329 packageName = value;
330
331 paramMap[key] = value;
332 }
333
334 aFootprintNames.Add( packageName );
335 }
336 }
337 }
339 {
341
342 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
343 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
344
345 std::optional<std::map<wxString, wxString>> c_para;
346
347 if( pcbDoc.c_para )
348 c_para = pcbDoc.c_para;
349 else if( doc.head.c_para )
350 c_para = doc.head.c_para;
351
352 if( c_para )
353 packageName = get_def( *c_para, wxS( "package" ), packageName );
354
355 aFootprintNames.Add( packageName );
356 }
357 }
358 catch( nlohmann::json::exception& e )
359 {
360 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
361 }
362 catch( std::exception& e )
363 {
364 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
365 }
366}
367
368
369std::unique_ptr<FOOTPRINT> PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath, const wxString& aFootprintName,
370 bool aKeepUUID,
371 const std::map<std::string, UTF8>* aProperties )
372{
373 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
374 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
375
376 PCB_IO_EASYEDA_PARSER parser( nullptr );
377
378 m_loadedFootprints.clear();
379
380 try
381 {
382 wxFFileInputStream in( aLibraryPath );
383 nlohmann::json js;
385
386 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
387 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
388
391 {
392 for( wxString shap : doc.shape )
393 {
394 if( !shap.Contains( wxS( "LIB" ) ) )
395 continue;
396
397 shap.Replace( wxS( "#@$" ), "\n" );
398 wxArrayString parts = wxSplit( shap, '\n', '\0' );
399
400 if( parts.size() < 1 )
401 continue;
402
403 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
404
405 if( paramsRoot.size() < 1 )
406 continue;
407
408 wxString rootType = paramsRoot[0];
409
410 if( rootType == wxS( "LIB" ) )
411 {
412 if( paramsRoot.size() < 4 )
413 continue;
414
415 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
416 parser.Convert( paramsRoot[2] ) );
417
418 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
419 paramsRoot[2] );
420
421 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
422
423 std::map<wxString, wxString> paramMap;
424
425 for( int i = 1; i < (int) paramParts.size(); i += 2 )
426 {
427 wxString key = paramParts[i - 1];
428 wxString value = paramParts[i];
429
430 if( key == wxS( "package" ) )
431 packageName = value;
432
433 paramMap[key] = value;
434 }
435
436 EDA_ANGLE orientation;
437 if( !paramsRoot[4].IsEmpty() )
438 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
439
440 int layer = 1;
441
442 if( !paramsRoot[7].IsEmpty() )
443 layer = parser.Convert( paramsRoot[7] );
444
445 if( packageName == aFootprintName )
446 {
447 parts.RemoveAt( 0 );
448
449 std::unique_ptr<FOOTPRINT> footprint = parser.ParseFootprint(
450 origin, orientation, layer, nullptr, paramMap, m_loadedFootprints, parts );
451
452 if( !footprint )
453 return nullptr;
454
455 footprint->Reference().SetPosition( VECTOR2I() );
456 footprint->Reference().SetTextAngle( ANGLE_0 );
457 footprint->Reference().SetVisible( true );
458
459 footprint->Value().SetPosition( VECTOR2I() );
460 footprint->Value().SetTextAngle( ANGLE_0 );
461 footprint->Value().SetVisible( true );
462
463 footprint->AutoPositionFields();
464
465 return footprint;
466 }
467 }
468 }
469 }
471 {
473
474 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
475 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
476
477 std::optional<std::map<wxString, wxString>> c_para;
478
479 if( pcbDoc.c_para )
480 c_para = pcbDoc.c_para;
481 else if( doc.head.c_para )
482 c_para = doc.head.c_para;
483
484 if( c_para )
485 {
486 packageName = get_def( *c_para, wxS( "package" ), packageName );
487
488 if( packageName != aFootprintName )
489 return nullptr;
490
491 VECTOR2D origin( doc.head.x, doc.head.y );
492
493 std::unique_ptr<FOOTPRINT> footprint( parser.ParseFootprint( origin, ANGLE_0, F_Cu, nullptr, *c_para,
494 m_loadedFootprints, doc.shape ) );
495
496 if( !footprint )
497 return nullptr;
498
499 footprint->Reference().SetPosition( VECTOR2I() );
500 footprint->Reference().SetTextAngle( ANGLE_0 );
501 footprint->Reference().SetVisible( true );
502
503 footprint->Value().SetPosition( VECTOR2I() );
504 footprint->Value().SetTextAngle( ANGLE_0 );
505 footprint->Value().SetVisible( true );
506
507 footprint->AutoPositionFields();
508
509 return footprint;
510 }
511 }
512 }
513 catch( nlohmann::json::exception& e )
514 {
515 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
516 aFootprintName,
517 aLibraryPath,
518 e.what() );
519 }
520 catch( std::exception& e )
521 {
522 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
523 aFootprintName,
524 aLibraryPath,
525 e.what() );
526 }
527
528 return nullptr;
529}
530
531
533{
534 std::vector<FOOTPRINT*> result;
535
536 for( auto& [fpUuid, footprint] : m_loadedFootprints )
537 {
538 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
539 }
540
541 return result;
542}
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
BOX2< VECTOR2I > BOX2I
Definition box2.h:914
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:982
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:410
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:142
double GetWidthMils() const
Definition page_info.h:137
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
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
Check 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:393
virtual bool CanReadBoard(const wxString &aFileName) const
Definition pcb_io.cpp:40
PCB_IO(const wxString &aName)
Definition pcb_io.h:372
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:396
Container for project specific data.
Definition project.h:63
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:448
@ DEGREES_T
Definition eda_angle.h:30
#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:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707