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, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
28#include <pcb_io/pcb_io.h>
29
30#include <font/fontconfig.h>
31#include <progress_reporter.h>
32#include <common.h>
33#include <macros.h>
34#include <board.h>
35#include <footprint.h>
37#include <reporter.h>
38
39#include <wx/log.h>
40#include <wx/wfstream.h>
41#include <wx/zipstrm.h>
42#include <wx/stdstream.h>
43
44#include <json_common.h>
45#include <core/map_helpers.h>
46
47
48PCB_IO_EASYEDA::PCB_IO_EASYEDA() : PCB_IO( wxS( "EasyEDA (JLCEDA) Standard" ) )
49{
50}
51
52
56
57
58static bool FindBoardInStream( const wxString& aName, wxInputStream& aStream, nlohmann::json& aOut,
59 EASYEDA::DOCUMENT& aDoc )
60{
61 if( aName.Lower().EndsWith( wxS( ".json" ) ) )
62 {
63 wxStdInputStream sin( aStream );
64 nlohmann::json js = nlohmann::json::parse( sin, nullptr, false );
65
66 if( js.is_discarded() )
67 return false;
68
70
74 {
75 aOut = js;
76 aDoc = doc;
77 return true;
78 }
79 }
80 else if( aName.Lower().EndsWith( wxS( ".zip" ) ) )
81 {
82 std::shared_ptr<wxZipEntry> entry;
83 wxZipInputStream zip( aStream );
84
85 if( !zip.IsOk() )
86 return false;
87
88 while( entry.reset( zip.GetNextEntry() ), entry.get() != NULL )
89 {
90 wxString name = entry->GetName();
91
92 if( FindBoardInStream( name, zip, aOut, aDoc ) )
93 return true;
94 }
95 }
96
97 return false;
98}
99
100
101bool PCB_IO_EASYEDA::CanReadBoard( const wxString& aFileName ) const
102{
103 if( !PCB_IO::CanReadBoard( aFileName ) )
104 return false;
105
106 try
107 {
108 wxFFileInputStream in( aFileName );
109 nlohmann::json js;
111
112 return FindBoardInStream( aFileName, in, js, doc );
113 }
114 catch( nlohmann::json::exception& )
115 {
116 }
117 catch( std::exception& )
118 {
119 }
120
121 return false;
122}
123
124
125bool PCB_IO_EASYEDA::CanReadFootprint( const wxString& aFileName ) const
126{
127 return CanReadBoard( aFileName );
128}
129
130
131bool PCB_IO_EASYEDA::CanReadLibrary( const wxString& aFileName ) const
132{
133 return CanReadBoard( aFileName );
134}
135
136
137BOARD* PCB_IO_EASYEDA::LoadBoard( const wxString& aFileName, BOARD* aAppendToMe,
138 const std::map<std::string, UTF8>* aProperties, PROJECT* aProject )
139{
140 m_loadedFootprints.clear();
141
142 m_props = aProperties;
143 m_board = aAppendToMe ? aAppendToMe : new BOARD();
144
145 // Collect the font substitution warnings (RAII - automatically reset on scope exit)
147
148 // Give the filename to the board if it's new
149 if( !aAppendToMe )
150 m_board->SetFileName( aFileName );
151
153 {
154 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
155
156 if( !m_progressReporter->KeepRefreshing() )
157 THROW_IO_ERROR( _( "File import canceled by user." ) );
158 }
159
160 PCB_IO_EASYEDA_PARSER parser( nullptr );
161
162 try
163 {
164 wxFFileInputStream in( aFileName );
165 nlohmann::json js;
167
168 if( !FindBoardInStream( aFileName, in, js, doc ) )
169 {
171 wxString::Format( _( "Unable to find a valid board in '%s'" ), aFileName ) );
172 }
173
175
176 const int innerStart = 21;
177 const int innerEnd = 52;
178
179 int maxLayer = innerStart;
180 std::map<PCB_LAYER_ID, wxString> layerNames;
181
182 for( const wxString& layerLine : pcbDoc.layers )
183 {
184 wxArrayString parts = wxSplit( layerLine, '~', '\0' );
185 int layerId = wxAtoi( parts[0] );
186 wxString layerName = parts[1];
187 wxString layerColor = parts[2];
188 wxString visible = parts[3];
189 wxString active = parts[4];
190 bool enabled = parts[5] != wxS( "false" );
191
192 if( layerId >= innerStart && layerId <= innerEnd && enabled )
193 maxLayer = layerId + 1;
194
195 layerNames[parser.LayerToKi( parts[0] )] = layerName;
196 }
197
198 m_board->SetCopperLayerCount( 2 + maxLayer - innerStart );
199
200 for( auto& [klayer, name] : layerNames )
201 m_board->SetLayerName( klayer, name );
202
203 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
204 std::shared_ptr<NETCLASS> defNetclass = bds.m_NetSettings->GetDefaultNetclass();
205
206 if( pcbDoc.DRCRULE )
207 {
208 std::map<wxString, nlohmann::json>& rules = *pcbDoc.DRCRULE;
209
210 if( auto defRules = get_opt( rules, "Default" ) )
211 {
212 wxString key;
213
214 key = wxS( "trackWidth" );
215 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
216 {
217 double val = parser.ScaleSize( defRules->at( key ) );
218 defNetclass->SetTrackWidth( val );
219 }
220
221 key = wxS( "clearance" );
222 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
223 {
224 double val = parser.ScaleSize( defRules->at( key ) );
225 defNetclass->SetClearance( val );
226 }
227
228 key = wxS( "viaHoleD" );
229 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
230 {
231 double val = parser.ScaleSize( defRules->at( key ) );
232
233 defNetclass->SetViaDrill( val );
234 }
235
236 key = wxS( "viaHoleDiameter" ); // Yes, this is via diameter, not drill diameter
237 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
238 {
239 double val = parser.ScaleSize( defRules->at( key ) );
240 defNetclass->SetViaDiameter( val );
241 }
242 }
243 }
244
245 VECTOR2D origin( doc.head.x, doc.head.y );
246 parser.ParseBoard( m_board, origin, m_loadedFootprints, doc.shape );
247
248 // Center the board
249 BOX2I outlineBbox = m_board->ComputeBoundingBox( true );
250 PAGE_INFO pageInfo = m_board->GetPageSettings();
251
252 VECTOR2D pageCenter( pcbIUScale.MilsToIU( pageInfo.GetWidthMils() / 2 ),
253 pcbIUScale.MilsToIU( pageInfo.GetHeightMils() / 2 ) );
254
255 VECTOR2D offset = pageCenter - outlineBbox.GetCenter();
256
257 int alignGrid = pcbIUScale.mmToIU( 10 );
258 offset.x = KiROUND( offset.x / alignGrid ) * alignGrid;
259 offset.y = KiROUND( offset.y / alignGrid ) * alignGrid;
260
261 m_board->Move( offset );
262 bds.SetAuxOrigin( offset );
263
264 return m_board;
265 }
266 catch( nlohmann::json::exception& e )
267 {
268 THROW_IO_ERROR( wxString::Format( _( "Error loading board '%s': %s" ), aFileName, e.what() ) );
269 }
270 catch( std::exception& e )
271 {
272 THROW_IO_ERROR( wxString::Format( _( "Error loading board '%s': %s" ), aFileName, e.what() ) );
273 }
274}
275
276
277long long PCB_IO_EASYEDA::GetLibraryTimestamp( const wxString& aLibraryPath ) const
278{
279 return 0;
280}
281
282
283void PCB_IO_EASYEDA::FootprintEnumerate( wxArrayString& aFootprintNames,
284 const wxString& aLibraryPath, bool aBestEfforts,
285 const std::map<std::string, UTF8>* aProperties )
286{
287 try
288 {
289 wxFFileInputStream in( aLibraryPath );
290 nlohmann::json js;
292
293 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
294 {
295 THROW_IO_ERROR( wxString::Format( _( "Unable to find valid footprints in '%s'" ),
296 aLibraryPath ) );
297 }
298
301 {
302 for( wxString shap : doc.shape )
303 {
304 shap.Replace( wxS( "#@$" ), "\n" );
305 wxArrayString parts = wxSplit( shap, '\n', '\0' );
306
307 if( parts.size() < 1 )
308 continue;
309
310 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
311
312 if( paramsRoot.size() < 1 )
313 continue;
314
315 wxString rootType = paramsRoot[0];
316
317 if( rootType == wxS( "LIB" ) )
318 {
319 if( paramsRoot.size() < 4 )
320 continue;
321
322 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
323 paramsRoot[2] );
324
325 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
326
327 std::map<wxString, wxString> paramMap;
328
329 for( int i = 1; i < paramParts.size(); i += 2 )
330 {
331 wxString key = paramParts[i - 1];
332 wxString value = paramParts[i];
333
334 if( key == wxS( "package" ) )
335 packageName = value;
336
337 paramMap[key] = value;
338 }
339
340 aFootprintNames.Add( packageName );
341 }
342 }
343 }
345 {
347
348 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
349 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
350
351 std::optional<std::map<wxString, wxString>> c_para;
352
353 if( pcbDoc.c_para )
354 c_para = pcbDoc.c_para;
355 else if( doc.head.c_para )
356 c_para = doc.head.c_para;
357
358 if( c_para )
359 packageName = get_def( *c_para, wxS( "package" ), packageName );
360
361 aFootprintNames.Add( packageName );
362 }
363 }
364 catch( nlohmann::json::exception& e )
365 {
366 THROW_IO_ERROR( wxString::Format( _( "Error enumerating footprints in library '%s': %s" ),
367 aLibraryPath, e.what() ) );
368 }
369 catch( std::exception& e )
370 {
371 THROW_IO_ERROR( wxString::Format( _( "Error enumerating footprints in library '%s': %s" ),
372 aLibraryPath, e.what() ) );
373 }
374}
375
376
377FOOTPRINT* PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath,
378 const wxString& aFootprintName, bool aKeepUUID,
379 const std::map<std::string, UTF8>* aProperties )
380{
381 // Suppress font substitution warnings (RAII - automatically restored on scope exit)
382 FONTCONFIG_REPORTER_SCOPE fontconfigScope( nullptr );
383
384 PCB_IO_EASYEDA_PARSER parser( nullptr );
385
386 m_loadedFootprints.clear();
387
388 try
389 {
390 wxFFileInputStream in( aLibraryPath );
391 nlohmann::json js;
393
394 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
395 {
396 THROW_IO_ERROR( wxString::Format( _( "Unable to find valid footprints in '%s'" ),
397 aLibraryPath ) );
398 }
399
402 {
403 for( wxString shap : doc.shape )
404 {
405 if( !shap.Contains( wxS( "LIB" ) ) )
406 continue;
407
408 shap.Replace( wxS( "#@$" ), "\n" );
409 wxArrayString parts = wxSplit( shap, '\n', '\0' );
410
411 if( parts.size() < 1 )
412 continue;
413
414 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
415
416 if( paramsRoot.size() < 1 )
417 continue;
418
419 wxString rootType = paramsRoot[0];
420
421 if( rootType == wxS( "LIB" ) )
422 {
423 if( paramsRoot.size() < 4 )
424 continue;
425
426 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
427 parser.Convert( paramsRoot[2] ) );
428
429 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
430 paramsRoot[2] );
431
432 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
433
434 std::map<wxString, wxString> paramMap;
435
436 for( int i = 1; i < paramParts.size(); i += 2 )
437 {
438 wxString key = paramParts[i - 1];
439 wxString value = paramParts[i];
440
441 if( key == wxS( "package" ) )
442 packageName = value;
443
444 paramMap[key] = value;
445 }
446
447 EDA_ANGLE orientation;
448 if( !paramsRoot[4].IsEmpty() )
449 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
450
451 int layer = 1;
452
453 if( !paramsRoot[7].IsEmpty() )
454 layer = parser.Convert( paramsRoot[7] );
455
456 if( packageName == aFootprintName )
457 {
458 parts.RemoveAt( 0 );
459
460 FOOTPRINT* footprint = parser.ParseFootprint( origin, orientation, layer, nullptr,
461 paramMap, m_loadedFootprints, parts );
462
463 if( !footprint )
464 return nullptr;
465
466 footprint->Reference().SetPosition( VECTOR2I() );
467 footprint->Reference().SetTextAngle( ANGLE_0 );
468 footprint->Reference().SetVisible( true );
469
470 footprint->Value().SetPosition( VECTOR2I() );
471 footprint->Value().SetTextAngle( ANGLE_0 );
472 footprint->Value().SetVisible( true );
473
474 footprint->AutoPositionFields();
475
476 return footprint;
477 }
478 }
479 }
480 }
482 {
484
485 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
486 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
487
488 std::optional<std::map<wxString, wxString>> c_para;
489
490 if( pcbDoc.c_para )
491 c_para = pcbDoc.c_para;
492 else if( doc.head.c_para )
493 c_para = doc.head.c_para;
494
495 if( c_para )
496 {
497 packageName = get_def( *c_para, wxS( "package" ), packageName );
498
499 if( packageName != aFootprintName )
500 return nullptr;
501
502 VECTOR2D origin( doc.head.x, doc.head.y );
503
504 FOOTPRINT* footprint = parser.ParseFootprint( origin, ANGLE_0, F_Cu, nullptr, *c_para,
506
507 if( !footprint )
508 return nullptr;
509
510 footprint->Reference().SetPosition( VECTOR2I() );
511 footprint->Reference().SetTextAngle( ANGLE_0 );
512 footprint->Reference().SetVisible( true );
513
514 footprint->Value().SetPosition( VECTOR2I() );
515 footprint->Value().SetTextAngle( ANGLE_0 );
516 footprint->Value().SetVisible( true );
517
518 footprint->AutoPositionFields();
519
520 return footprint;
521 }
522 }
523 }
524 catch( nlohmann::json::exception& e )
525 {
526 THROW_IO_ERROR( wxString::Format( _( "Error reading footprint '%s' from library '%s': %s" ),
527 aFootprintName, aLibraryPath, e.what() ) );
528 }
529 catch( std::exception& e )
530 {
531 THROW_IO_ERROR( wxString::Format( _( "Error reading footprint '%s' from library '%s': %s" ),
532 aFootprintName, aLibraryPath, e.what() ) );
533 }
534
535 return nullptr;
536}
537
538
540{
541 std::vector<FOOTPRINT*> result;
542
543 for( auto& [fpUuid, footprint] : m_loadedFootprints )
544 {
545 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
546 }
547
548 return result;
549}
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:112
BOX2< VECTOR2I > BOX2I
Definition box2.h:922
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:990
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:322
constexpr const Vec GetCenter() const
Definition box2.h:230
static double Convert(const wxString &aValue)
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:395
virtual void SetTextAngle(const EDA_ANGLE &aAngle)
Definition eda_text.cpp:308
RAII class to set and restore the fontconfig reporter.
Definition reporter.h:322
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:777
PCB_FIELD & Reference()
Definition footprint.h:778
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:240
static LOAD_INFO_REPORTER & GetInstance()
Definition reporter.cpp:218
std::shared_ptr< NETCLASS > GetDefaultNetclass()
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:79
double GetHeightMils() const
Definition page_info.h:147
double GetWidthMils() const
Definition page_info.h:142
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:326
virtual bool CanReadBoard(const wxString &aFileName) const
Checks if this PCB_IO can read the specified board file.
Definition pcb_io.cpp:42
PCB_IO(const wxString &aName)
Definition pcb_io.h:319
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition pcb_io.h:329
virtual void SetPosition(const VECTOR2I &aPos) override
Definition pcb_text.h:84
Container for project specific data.
Definition project.h:65
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
@ F_Cu
Definition layer_ids.h:64
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:64
std::optional< V > get_opt(const std::map< wxString, V > &aMap, const wxString &aKey)
Definition map_helpers.h:34
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:695
VECTOR2< double > VECTOR2D
Definition vector2d.h:694