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
69
73 {
74 aOut = js;
75 aDoc = doc;
76 return true;
77 }
78 }
79 else if( aName.Lower().EndsWith( wxS( ".zip" ) ) )
80 {
81 std::shared_ptr<wxZipEntry> entry;
82 wxZipInputStream zip( aStream );
83
84 if( !zip.IsOk() )
85 return false;
86
87 while( entry.reset( zip.GetNextEntry() ), entry.get() != NULL )
88 {
89 wxString name = entry->GetName();
90
91 if( FindBoardInStream( name, zip, aOut, aDoc ) )
92 return true;
93 }
94 }
95
96 return false;
97}
98
99
100bool PCB_IO_EASYEDA::CanReadBoard( const wxString& aFileName ) const
101{
102 if( !PCB_IO::CanReadBoard( aFileName ) )
103 return false;
104
105 try
106 {
107 wxFFileInputStream in( aFileName );
108 nlohmann::json js;
110
111 return FindBoardInStream( aFileName, in, js, doc );
112 }
113 catch( nlohmann::json::exception& )
114 {
115 }
116 catch( std::exception& )
117 {
118 }
119
120 return false;
121}
122
123
124bool PCB_IO_EASYEDA::CanReadFootprint( const wxString& aFileName ) const
125{
126 return CanReadBoard( aFileName );
127}
128
129
130bool PCB_IO_EASYEDA::CanReadLibrary( const wxString& aFileName ) const
131{
132 return CanReadBoard( aFileName );
133}
134
135
136void PCB_IO_EASYEDA::loadBoard( const wxString& aFileName, BOARD& aBoard, bool aIsNewLoad,
137 const std::map<std::string, UTF8>* aProperties, PROJECT* aProject )
138{
139 m_loadedFootprints.clear();
140
141 m_props = aProperties;
142 m_board = &aBoard;
143
144 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
146
148 {
149 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
150
151 if( !m_progressReporter->KeepRefreshing() )
153 }
154
155 PCB_IO_EASYEDA_PARSER parser( nullptr );
156
157 try
158 {
159 wxFFileInputStream in( aFileName );
160 nlohmann::json js;
162
163 if( !FindBoardInStream( aFileName, in, js, doc ) )
164 THROW_IO_ERRORF( _( "Unable to find a valid board in '%s'" ), aFileName );
165
167
168 const int innerStart = 21;
169 const int innerEnd = 52;
170
171 int maxLayer = innerStart;
172 std::map<PCB_LAYER_ID, wxString> layerNames;
173
174 for( const wxString& layerLine : pcbDoc.layers )
175 {
176 wxArrayString parts = wxSplit( layerLine, '~', '\0' );
177 int layerId = wxAtoi( parts[0] );
178 wxString layerName = parts[1];
179 wxString layerColor = parts[2];
180 wxString visible = parts[3];
181 wxString active = parts[4];
182 bool enabled = parts[5] != wxS( "false" );
183
184 if( layerId >= innerStart && layerId <= innerEnd && enabled )
185 maxLayer = layerId + 1;
186
187 layerNames[parser.LayerToKi( parts[0] )] = layerName;
188 }
189
190 m_board->SetCopperLayerCount( 2 + maxLayer - innerStart );
191
192 for( auto& [klayer, name] : layerNames )
193 m_board->SetLayerName( klayer, name );
194
195 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
196 std::shared_ptr<NETCLASS> defNetclass = bds.m_NetSettings->GetDefaultNetclass();
197 bool importedNetclassRules = false;
198
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 importedNetclassRules = true;
214 }
215
216 key = wxS( "clearance" );
217 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
218 {
219 double val = parser.ScaleSize( defRules->at( key ) );
220 defNetclass->SetClearance( val );
221 importedNetclassRules = true;
222 }
223
224 key = wxS( "viaHoleD" );
225 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
226 {
227 double val = parser.ScaleSize( defRules->at( key ) );
228
229 defNetclass->SetViaDrill( val );
230 importedNetclassRules = true;
231 }
232
233 key = wxS( "viaHoleDiameter" ); // Yes, this is via diameter, not drill diameter
234 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
235 {
236 double val = parser.ScaleSize( defRules->at( key ) );
237 defNetclass->SetViaDiameter( val );
238 importedNetclassRules = true;
239 }
240 }
241 }
242 if( importedNetclassRules )
243 m_board->m_LegacyNetclassesLoaded = true;
244
245
246 VECTOR2D origin( doc.head.x, doc.head.y );
247 parser.ParseBoard( m_board, origin, m_loadedFootprints, doc.shape );
248
249 // Center the board
250 BOX2I outlineBbox = m_board->ComputeBoundingBox( true, true );
251 PAGE_INFO pageInfo = m_board->GetPageSettings();
252
253 VECTOR2D pageCenter( pcbIUScale.MilsToIU( pageInfo.GetWidthMils() / 2 ),
254 pcbIUScale.MilsToIU( pageInfo.GetHeightMils() / 2 ) );
255
256 VECTOR2D offset = pageCenter - outlineBbox.GetCenter();
257
258 int alignGrid = pcbIUScale.mmToIU( 10 );
259 offset.x = KiROUND( offset.x / alignGrid ) * alignGrid;
260 offset.y = KiROUND( offset.y / alignGrid ) * alignGrid;
261
262 m_board->Move( offset );
263 bds.SetAuxOrigin( offset );
264 }
265 catch( nlohmann::json::exception& e )
266 {
267 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
268 }
269 catch( std::exception& e )
270 {
271 THROW_IO_ERRORF( _( "Error loading board '%s': %s" ), aFileName, e.what() );
272 }
273}
274
275
276long long PCB_IO_EASYEDA::GetLibraryTimestamp( const wxString& aLibraryPath ) const
277{
278 return 0;
279}
280
281
282void PCB_IO_EASYEDA::FootprintEnumerate( wxArrayString& aFootprintNames,
283 const wxString& aLibraryPath, bool aBestEfforts,
284 const std::map<std::string, UTF8>* aProperties )
285{
286 try
287 {
288 wxFFileInputStream in( aLibraryPath );
289 nlohmann::json js;
291
292 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
293 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
294
297 {
298 for( wxString shap : doc.shape )
299 {
300 shap.Replace( wxS( "#@$" ), "\n" );
301 wxArrayString parts = wxSplit( shap, '\n', '\0' );
302
303 if( parts.size() < 1 )
304 continue;
305
306 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
307
308 if( paramsRoot.size() < 1 )
309 continue;
310
311 wxString rootType = paramsRoot[0];
312
313 if( rootType == wxS( "LIB" ) )
314 {
315 if( paramsRoot.size() < 4 )
316 continue;
317
318 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
319 paramsRoot[2] );
320
321 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
322
323 std::map<wxString, wxString> paramMap;
324
325 for( int i = 1; i < (int) paramParts.size(); i += 2 )
326 {
327 wxString key = paramParts[i - 1];
328 wxString value = paramParts[i];
329
330 if( key == wxS( "package" ) )
331 packageName = value;
332
333 paramMap[key] = value;
334 }
335
336 aFootprintNames.Add( packageName );
337 }
338 }
339 }
341 {
343
344 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
345 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
346
347 std::optional<std::map<wxString, wxString>> c_para;
348
349 if( pcbDoc.c_para )
350 c_para = pcbDoc.c_para;
351 else if( doc.head.c_para )
352 c_para = doc.head.c_para;
353
354 if( c_para )
355 packageName = get_def( *c_para, wxS( "package" ), packageName );
356
357 aFootprintNames.Add( packageName );
358 }
359 }
360 catch( nlohmann::json::exception& e )
361 {
362 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
363 }
364 catch( std::exception& e )
365 {
366 THROW_IO_ERRORF( _( "Error enumerating footprints in library '%s': %s" ), aLibraryPath, e.what() );
367 }
368}
369
370
371std::unique_ptr<FOOTPRINT> PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath, const wxString& aFootprintName,
372 bool aKeepUUID,
373 const std::map<std::string, UTF8>* aProperties )
374{
375 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
376 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
377
378 PCB_IO_EASYEDA_PARSER parser( nullptr );
379
380 m_loadedFootprints.clear();
381
382 try
383 {
384 wxFFileInputStream in( aLibraryPath );
385 nlohmann::json js;
387
388 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
389 THROW_IO_ERRORF( _( "Unable to find valid footprints in '%s'" ), aLibraryPath );
390
393 {
394 for( wxString shap : doc.shape )
395 {
396 if( !shap.Contains( wxS( "LIB" ) ) )
397 continue;
398
399 shap.Replace( wxS( "#@$" ), "\n" );
400 wxArrayString parts = wxSplit( shap, '\n', '\0' );
401
402 if( parts.size() < 1 )
403 continue;
404
405 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
406
407 if( paramsRoot.size() < 1 )
408 continue;
409
410 wxString rootType = paramsRoot[0];
411
412 if( rootType == wxS( "LIB" ) )
413 {
414 if( paramsRoot.size() < 4 )
415 continue;
416
417 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
418 parser.Convert( paramsRoot[2] ) );
419
420 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
421 paramsRoot[2] );
422
423 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
424
425 std::map<wxString, wxString> paramMap;
426
427 for( int i = 1; i < (int) paramParts.size(); i += 2 )
428 {
429 wxString key = paramParts[i - 1];
430 wxString value = paramParts[i];
431
432 if( key == wxS( "package" ) )
433 packageName = value;
434
435 paramMap[key] = value;
436 }
437
439 if( !paramsRoot[4].IsEmpty() )
440 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
441
442 int layer = 1;
443
444 if( !paramsRoot[7].IsEmpty() )
445 layer = parser.Convert( paramsRoot[7] );
446
447 if( packageName == aFootprintName )
448 {
449 parts.RemoveAt( 0 );
450
451 std::unique_ptr<FOOTPRINT> footprint = parser.ParseFootprint(
452 origin, orientation, layer, nullptr, paramMap, m_loadedFootprints, parts );
453
454 if( !footprint )
455 return nullptr;
456
457 footprint->Reference().SetPosition( VECTOR2I() );
458 footprint->Reference().SetTextAngle( ANGLE_0 );
459 footprint->Reference().SetVisible( true );
460
461 footprint->Value().SetPosition( VECTOR2I() );
462 footprint->Value().SetTextAngle( ANGLE_0 );
463 footprint->Value().SetVisible( true );
464
465 footprint->AutoPositionFields();
466
467 return footprint;
468 }
469 }
470 }
471 }
473 {
475
476 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
477 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
478
479 std::optional<std::map<wxString, wxString>> c_para;
480
481 if( pcbDoc.c_para )
482 c_para = pcbDoc.c_para;
483 else if( doc.head.c_para )
484 c_para = doc.head.c_para;
485
486 if( c_para )
487 {
488 packageName = get_def( *c_para, wxS( "package" ), packageName );
489
490 if( packageName != aFootprintName )
491 return nullptr;
492
493 VECTOR2D origin( doc.head.x, doc.head.y );
494
495 std::unique_ptr<FOOTPRINT> footprint( parser.ParseFootprint( origin, ANGLE_0, F_Cu, nullptr, *c_para,
496 m_loadedFootprints, doc.shape ) );
497
498 if( !footprint )
499 return nullptr;
500
501 footprint->Reference().SetPosition( VECTOR2I() );
502 footprint->Reference().SetTextAngle( ANGLE_0 );
503 footprint->Reference().SetVisible( true );
504
505 footprint->Value().SetPosition( VECTOR2I() );
506 footprint->Value().SetTextAngle( ANGLE_0 );
507 footprint->Value().SetVisible( true );
508
509 footprint->AutoPositionFields();
510
511 return footprint;
512 }
513 }
514 }
515 catch( nlohmann::json::exception& e )
516 {
517 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
518 aFootprintName,
519 aLibraryPath,
520 e.what() );
521 }
522 catch( std::exception& e )
523 {
524 THROW_IO_ERRORF( _( "Error reading footprint '%s' from library '%s': %s" ),
525 aFootprintName,
526 aLibraryPath,
527 e.what() );
528 }
529
530 return nullptr;
531}
532
533
535{
536 std::vector<FOOTPRINT*> result;
537
538 for( auto& [fpUuid, footprint] : m_loadedFootprints )
539 {
540 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
541 }
542
543 return result;
544}
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
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:411
constexpr const Vec GetCenter() const
Definition box2.h:233
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:267
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:404
virtual bool CanReadBoard(const wxString &aFileName) const
Definition pcb_io.cpp:40
PCB_IO(const wxString &aName)
Definition pcb_io.h:383
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:407
Container for project specific data.
Definition project.h:63
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
@ 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
bool UnwrapDataStr(nlohmann::json &aJson)
Replace a document the EasyEDA server wraps in a metadata envelope with the document it carries.
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
static EDA_ORIENTATION orientation(double d)
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