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
54{
55}
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
146
147 // Give the filename to the board if it's new
148 if( !aAppendToMe )
149 m_board->SetFileName( aFileName );
150
152 {
153 m_progressReporter->Report( wxString::Format( _( "Loading %s..." ), aFileName ) );
154
156 THROW_IO_ERROR( _( "File import canceled by user." ) );
157 }
158
159 PCB_IO_EASYEDA_PARSER parser( nullptr );
160
161 try
162 {
163 wxFFileInputStream in( aFileName );
164 nlohmann::json js;
166
167 if( !FindBoardInStream( aFileName, in, js, doc ) )
168 {
170 wxString::Format( _( "Unable to find a valid board in '%s'" ), aFileName ) );
171 }
172
174
175 const int innerStart = 21;
176 const int innerEnd = 52;
177
178 int maxLayer = innerStart;
179 std::map<PCB_LAYER_ID, wxString> layerNames;
180
181 for( const wxString& layerLine : pcbDoc.layers )
182 {
183 wxArrayString parts = wxSplit( layerLine, '~', '\0' );
184 int layerId = wxAtoi( parts[0] );
185 wxString layerName = parts[1];
186 wxString layerColor = parts[2];
187 wxString visible = parts[3];
188 wxString active = parts[4];
189 bool enabled = parts[5] != wxS( "false" );
190
191 if( layerId >= innerStart && layerId <= innerEnd && enabled )
192 maxLayer = layerId + 1;
193
194 layerNames[parser.LayerToKi( parts[0] )] = layerName;
195 }
196
197 m_board->SetCopperLayerCount( 2 + maxLayer - innerStart );
198
199 for( auto& [klayer, name] : layerNames )
200 m_board->SetLayerName( klayer, name );
201
203 std::shared_ptr<NETCLASS> defNetclass = bds.m_NetSettings->GetDefaultNetclass();
204
205 if( pcbDoc.DRCRULE )
206 {
207 std::map<wxString, nlohmann::json>& rules = *pcbDoc.DRCRULE;
208
209 if( auto defRules = get_opt( rules, "Default" ) )
210 {
211 wxString key;
212
213 key = wxS( "trackWidth" );
214 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
215 {
216 double val = parser.ScaleSize( defRules->at( key ) );
217 defNetclass->SetTrackWidth( val );
218 }
219
220 key = wxS( "clearance" );
221 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
222 {
223 double val = parser.ScaleSize( defRules->at( key ) );
224 defNetclass->SetClearance( val );
225 }
226
227 key = wxS( "viaHoleD" );
228 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
229 {
230 double val = parser.ScaleSize( defRules->at( key ) );
231
232 defNetclass->SetViaDrill( val );
233 }
234
235 key = wxS( "viaHoleDiameter" ); // Yes, this is via diameter, not drill diameter
236 if( defRules->find( key ) != defRules->end() && defRules->at( key ).is_number() )
237 {
238 double val = parser.ScaleSize( defRules->at( key ) );
239 defNetclass->SetViaDiameter( val );
240 }
241 }
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 );
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 return m_board;
264 }
265 catch( nlohmann::json::exception& e )
266 {
267 THROW_IO_ERROR( wxString::Format( _( "Error loading board '%s': %s" ), aFileName, e.what() ) );
268 }
269 catch( std::exception& e )
270 {
271 THROW_IO_ERROR( wxString::Format( _( "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 {
294 THROW_IO_ERROR( wxString::Format( _( "Unable to find valid footprints in '%s'" ),
295 aLibraryPath ) );
296 }
297
300 {
301 for( wxString shap : doc.shape )
302 {
303 shap.Replace( wxS( "#@$" ), "\n" );
304 wxArrayString parts = wxSplit( shap, '\n', '\0' );
305
306 if( parts.size() < 1 )
307 continue;
308
309 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
310
311 if( paramsRoot.size() < 1 )
312 continue;
313
314 wxString rootType = paramsRoot[0];
315
316 if( rootType == wxS( "LIB" ) )
317 {
318 if( paramsRoot.size() < 4 )
319 continue;
320
321 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
322 paramsRoot[2] );
323
324 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
325
326 std::map<wxString, wxString> paramMap;
327
328 for( int i = 1; i < paramParts.size(); i += 2 )
329 {
330 wxString key = paramParts[i - 1];
331 wxString value = paramParts[i];
332
333 if( key == wxS( "package" ) )
334 packageName = value;
335
336 paramMap[key] = value;
337 }
338
339 aFootprintNames.Add( packageName );
340 }
341 }
342 }
344 {
346
347 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
348 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
349
350 std::optional<std::map<wxString, wxString>> c_para;
351
352 if( pcbDoc.c_para )
353 c_para = pcbDoc.c_para;
354 else if( doc.head.c_para )
355 c_para = doc.head.c_para;
356
357 if( c_para )
358 packageName = get_def( *c_para, wxS( "package" ), packageName );
359
360 aFootprintNames.Add( packageName );
361 }
362 }
363 catch( nlohmann::json::exception& e )
364 {
365 THROW_IO_ERROR( wxString::Format( _( "Error enumerating footprints in library '%s': %s" ),
366 aLibraryPath, e.what() ) );
367 }
368 catch( std::exception& e )
369 {
370 THROW_IO_ERROR( wxString::Format( _( "Error enumerating footprints in library '%s': %s" ),
371 aLibraryPath, e.what() ) );
372 }
373}
374
375
376FOOTPRINT* PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath,
377 const wxString& aFootprintName, bool aKeepUUID,
378 const std::map<std::string, UTF8>* aProperties )
379{
381
382 PCB_IO_EASYEDA_PARSER parser( nullptr );
383
384 m_loadedFootprints.clear();
385
386 try
387 {
388 wxFFileInputStream in( aLibraryPath );
389 nlohmann::json js;
391
392 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
393 {
394 THROW_IO_ERROR( wxString::Format( _( "Unable to find valid footprints in '%s'" ),
395 aLibraryPath ) );
396 }
397
400 {
401 for( wxString shap : doc.shape )
402 {
403 if( !shap.Contains( wxS( "LIB" ) ) )
404 continue;
405
406 shap.Replace( wxS( "#@$" ), "\n" );
407 wxArrayString parts = wxSplit( shap, '\n', '\0' );
408
409 if( parts.size() < 1 )
410 continue;
411
412 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
413
414 if( paramsRoot.size() < 1 )
415 continue;
416
417 wxString rootType = paramsRoot[0];
418
419 if( rootType == wxS( "LIB" ) )
420 {
421 if( paramsRoot.size() < 4 )
422 continue;
423
424 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
425 parser.Convert( paramsRoot[2] ) );
426
427 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
428 paramsRoot[2] );
429
430 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
431
432 std::map<wxString, wxString> paramMap;
433
434 for( int i = 1; i < paramParts.size(); i += 2 )
435 {
436 wxString key = paramParts[i - 1];
437 wxString value = paramParts[i];
438
439 if( key == wxS( "package" ) )
440 packageName = value;
441
442 paramMap[key] = value;
443 }
444
445 EDA_ANGLE orientation;
446 if( !paramsRoot[4].IsEmpty() )
447 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
448
449 int layer = 1;
450
451 if( !paramsRoot[7].IsEmpty() )
452 layer = parser.Convert( paramsRoot[7] );
453
454 if( packageName == aFootprintName )
455 {
456 parts.RemoveAt( 0 );
457
458 FOOTPRINT* footprint = parser.ParseFootprint( origin, orientation, layer, nullptr,
459 paramMap, m_loadedFootprints, parts );
460
461 if( !footprint )
462 return nullptr;
463
464 footprint->Reference().SetPosition( VECTOR2I() );
465 footprint->Reference().SetTextAngle( ANGLE_0 );
466 footprint->Reference().SetVisible( true );
467
468 footprint->Value().SetPosition( VECTOR2I() );
469 footprint->Value().SetTextAngle( ANGLE_0 );
470 footprint->Value().SetVisible( true );
471
472 footprint->AutoPositionFields();
473
474 return footprint;
475 }
476 }
477 }
478 }
480 {
482
483 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
484 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
485
486 std::optional<std::map<wxString, wxString>> c_para;
487
488 if( pcbDoc.c_para )
489 c_para = pcbDoc.c_para;
490 else if( doc.head.c_para )
491 c_para = doc.head.c_para;
492
493 if( c_para )
494 {
495 packageName = get_def( *c_para, wxS( "package" ), packageName );
496
497 if( packageName != aFootprintName )
498 return nullptr;
499
500 VECTOR2D origin( doc.head.x, doc.head.y );
501
502 FOOTPRINT* footprint = parser.ParseFootprint( origin, ANGLE_0, F_Cu, nullptr, *c_para,
504
505 if( !footprint )
506 return nullptr;
507
508 footprint->Reference().SetPosition( VECTOR2I() );
509 footprint->Reference().SetTextAngle( ANGLE_0 );
510 footprint->Reference().SetVisible( true );
511
512 footprint->Value().SetPosition( VECTOR2I() );
513 footprint->Value().SetTextAngle( ANGLE_0 );
514 footprint->Value().SetVisible( true );
515
516 footprint->AutoPositionFields();
517
518 return footprint;
519 }
520 }
521 }
522 catch( nlohmann::json::exception& e )
523 {
524 THROW_IO_ERROR( wxString::Format( _( "Error reading footprint '%s' from library '%s': %s" ),
525 aFootprintName, aLibraryPath, e.what() ) );
526 }
527 catch( std::exception& e )
528 {
529 THROW_IO_ERROR( wxString::Format( _( "Error reading footprint '%s' from library '%s': %s" ),
530 aFootprintName, aLibraryPath, e.what() ) );
531 }
532
533 return nullptr;
534}
535
536
538{
539 std::vector<FOOTPRINT*> result;
540
541 for( auto& [fpUuid, footprint] : m_loadedFootprints )
542 {
543 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
544 }
545
546 return result;
547}
const char * name
Definition: DXF_plotter.cpp:62
constexpr EDA_IU_SCALE pcbIUScale
Definition: base_units.h:112
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:317
void SetFileName(const wxString &aFileName)
Definition: board.h:352
const PAGE_INFO & GetPageSettings() const
Definition: board.h:740
bool SetLayerName(PCB_LAYER_ID aLayer, const wxString &aLayerName)
Changes the name of the layer given by aLayer.
Definition: board.cpp:697
void Move(const VECTOR2I &aMoveVector) override
Move this object.
Definition: board.cpp:568
BOX2I ComputeBoundingBox(bool aBoardEdgesOnly=false) const
Calculate the bounding box containing all board items (or board edge segments).
Definition: board.cpp:1842
void SetCopperLayerCount(int aCount)
Definition: board.cpp:864
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:1023
constexpr const Vec GetCenter() const
Definition: box2.h:230
static double Convert(const wxString &aValue)
virtual void SetVisible(bool aVisible)
Definition: eda_text.cpp:386
virtual void SetTextAngle(const EDA_ANGLE &aAngle)
Definition: eda_text.cpp:299
PCB_FIELD & Value()
read/write accessors:
Definition: footprint.h:661
PCB_FIELD & Reference()
Definition: footprint.h:662
void AutoPositionFields()
Position Reference and Value fields at the top and bottom of footprint's bounding box.
Definition: footprint.cpp:2762
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition: io_base.h:223
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition: page_info.h:59
double GetHeightMils() const
Definition: page_info.h:141
double GetWidthMils() const
Definition: page_info.h:136
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.
A base class that BOARD loading and saving plugins should derive from.
Definition: pcb_io.h:71
BOARD * m_board
The board BOARD being worked on, no ownership here.
Definition: pcb_io.h:324
virtual bool CanReadBoard(const wxString &aFileName) const
Checks if this PCB_IO can read the specified board file.
Definition: pcb_io.cpp:42
const std::map< std::string, UTF8 > * m_props
Properties passed via Save() or Load(), no ownership, may be NULL.
Definition: pcb_io.h:327
virtual void SetPosition(const VECTOR2I &aPos) override
Definition: pcb_text.h:89
virtual bool KeepRefreshing(bool aWait=false)=0
Update the UI (if any).
virtual void Report(const wxString &aMessage)=0
Display aMessage in the progress bar dialog.
Container for project specific data.
Definition: project.h:65
static REPORTER & GetInstance()
Definition: reporter.cpp:202
static void SetReporter(REPORTER *aReporter)
Set the reporter to use for reporting font substitution warnings.
Definition: fontconfig.cpp:64
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)
Definition: ki_exception.h:39
@ 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
constexpr int MilsToIU(int mils) const
Definition: base_units.h:97
constexpr int mmToIU(double mm) const
Definition: base_units.h:92
VECTOR2< int32_t > VECTOR2I
Definition: vector2d.h:695