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 (C) 2023 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 <nlohmann/json.hpp>
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( _( "Open cancelled 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 {
268 wxString::Format( _( "Error loading board '%s': %s" ), aFileName, e.what() ) );
269 }
270 catch( std::exception& e )
271 {
273 wxString::Format( _( "Error loading board '%s': %s" ), aFileName, e.what() ) );
274 }
275
276 return m_board;
277}
278
279
280long long PCB_IO_EASYEDA::GetLibraryTimestamp( const wxString& aLibraryPath ) const
281{
282 return 0;
283}
284
285
286void PCB_IO_EASYEDA::FootprintEnumerate( wxArrayString& aFootprintNames,
287 const wxString& aLibraryPath, bool aBestEfforts,
288 const std::map<std::string, UTF8>* aProperties )
289{
290 try
291 {
292 wxFFileInputStream in( aLibraryPath );
293 nlohmann::json js;
295
296 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
297 {
298 THROW_IO_ERROR( wxString::Format( _( "Unable to find valid footprints in '%s'" ),
299 aLibraryPath ) );
300 }
301
304 {
305 for( wxString shap : doc.shape )
306 {
307 shap.Replace( wxS( "#@$" ), "\n" );
308 wxArrayString parts = wxSplit( shap, '\n', '\0' );
309
310 if( parts.size() < 1 )
311 continue;
312
313 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
314
315 if( paramsRoot.size() < 1 )
316 continue;
317
318 wxString rootType = paramsRoot[0];
319
320 if( rootType == wxS( "LIB" ) )
321 {
322 if( paramsRoot.size() < 4 )
323 continue;
324
325 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
326 paramsRoot[2] );
327
328 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
329
330 std::map<wxString, wxString> paramMap;
331
332 for( int i = 1; i < paramParts.size(); i += 2 )
333 {
334 wxString key = paramParts[i - 1];
335 wxString value = paramParts[i];
336
337 if( key == wxS( "package" ) )
338 packageName = value;
339
340 paramMap[key] = value;
341 }
342
343 aFootprintNames.Add( packageName );
344 }
345 }
346 }
348 {
350
351 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
352 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
353
354 std::optional<std::map<wxString, wxString>> c_para;
355
356 if( pcbDoc.c_para )
357 c_para = pcbDoc.c_para;
358 else if( doc.head.c_para )
359 c_para = doc.head.c_para;
360
361 if( c_para )
362 {
363 packageName = get_def( *c_para, wxS( "package" ), packageName );
364 }
365
366 aFootprintNames.Add( packageName );
367 }
368 }
369 catch( nlohmann::json::exception& e )
370 {
371 THROW_IO_ERROR( wxString::Format( _( "Error enumerating footprints in library '%s': %s" ),
372 aLibraryPath, e.what() ) );
373 }
374 catch( std::exception& e )
375 {
376 THROW_IO_ERROR( wxString::Format( _( "Error enumerating footprints in library '%s': %s" ),
377 aLibraryPath, e.what() ) );
378 }
379}
380
381
382FOOTPRINT* PCB_IO_EASYEDA::FootprintLoad( const wxString& aLibraryPath,
383 const wxString& aFootprintName, bool aKeepUUID,
384 const std::map<std::string, UTF8>* aProperties )
385{
387
388 PCB_IO_EASYEDA_PARSER parser( nullptr );
389
390 m_loadedFootprints.clear();
391
392 try
393 {
394 wxFFileInputStream in( aLibraryPath );
395 nlohmann::json js;
397
398 if( !FindBoardInStream( aLibraryPath, in, js, doc ) )
399 {
400 THROW_IO_ERROR( wxString::Format( _( "Unable to find valid footprints in '%s'" ),
401 aLibraryPath ) );
402 }
403
406 {
407 for( wxString shap : doc.shape )
408 {
409 if( !shap.Contains( wxS( "LIB" ) ) )
410 continue;
411
412 shap.Replace( wxS( "#@$" ), "\n" );
413 wxArrayString parts = wxSplit( shap, '\n', '\0' );
414
415 if( parts.size() < 1 )
416 continue;
417
418 wxArrayString paramsRoot = wxSplit( parts[0], '~', '\0' );
419
420 if( paramsRoot.size() < 1 )
421 continue;
422
423 wxString rootType = paramsRoot[0];
424
425 if( rootType == wxS( "LIB" ) )
426 {
427 if( paramsRoot.size() < 4 )
428 continue;
429
430 VECTOR2D origin( parser.Convert( paramsRoot[1] ),
431 parser.Convert( paramsRoot[2] ) );
432
433 wxString packageName = wxString::Format( wxS( "Unknown_%s_%s" ), paramsRoot[1],
434 paramsRoot[2] );
435
436 wxArrayString paramParts = wxSplit( paramsRoot[3], '`', '\0' );
437
438 std::map<wxString, wxString> paramMap;
439
440 for( int i = 1; i < paramParts.size(); i += 2 )
441 {
442 wxString key = paramParts[i - 1];
443 wxString value = paramParts[i];
444
445 if( key == wxS( "package" ) )
446 packageName = value;
447
448 paramMap[key] = value;
449 }
450
451 EDA_ANGLE orientation;
452 if( !paramsRoot[4].IsEmpty() )
453 orientation = EDA_ANGLE( parser.Convert( paramsRoot[4] ), DEGREES_T );
454
455 int layer = 1;
456
457 if( !paramsRoot[7].IsEmpty() )
458 layer = parser.Convert( paramsRoot[7] );
459
460 if( packageName == aFootprintName )
461 {
462 parts.RemoveAt( 0 );
463
464 FOOTPRINT* footprint =
465 parser.ParseFootprint( origin, orientation, layer, nullptr,
466 paramMap, m_loadedFootprints, parts );
467
468 if( !footprint )
469 return nullptr;
470
471 footprint->Reference().SetPosition( VECTOR2I() );
472 footprint->Reference().SetTextAngle( ANGLE_0 );
473 footprint->Reference().SetVisible( true );
474
475 footprint->Value().SetPosition( VECTOR2I() );
476 footprint->Value().SetTextAngle( ANGLE_0 );
477 footprint->Value().SetVisible( true );
478
479 footprint->AutoPositionFields();
480
481 return footprint;
482 }
483 }
484 }
485 }
487 {
489
490 wxString packageName = wxString::Format( wxS( "Unknown_%s" ),
491 pcbDoc.uuid.value_or( wxS( "Unknown" ) ) );
492
493 std::optional<std::map<wxString, wxString>> c_para;
494
495 if( pcbDoc.c_para )
496 c_para = pcbDoc.c_para;
497 else if( doc.head.c_para )
498 c_para = doc.head.c_para;
499
500 if( c_para )
501 {
502 packageName = get_def( *c_para, wxS( "package" ), packageName );
503
504 if( packageName != aFootprintName )
505 return nullptr;
506
507 VECTOR2D origin( doc.head.x, doc.head.y );
508
509 FOOTPRINT* footprint = parser.ParseFootprint(
510 origin, ANGLE_0, F_Cu, nullptr, *c_para, m_loadedFootprints, doc.shape );
511
512 if( !footprint )
513 return nullptr;
514
515 footprint->Reference().SetPosition( VECTOR2I() );
516 footprint->Reference().SetTextAngle( ANGLE_0 );
517 footprint->Reference().SetVisible( true );
518
519 footprint->Value().SetPosition( VECTOR2I() );
520 footprint->Value().SetTextAngle( ANGLE_0 );
521 footprint->Value().SetVisible( true );
522
523 footprint->AutoPositionFields();
524
525 return footprint;
526 }
527 }
528 }
529 catch( nlohmann::json::exception& e )
530 {
531 THROW_IO_ERROR( wxString::Format( _( "Error reading footprint '%s' from library '%s': %s" ),
532 aFootprintName, aLibraryPath, e.what() ) );
533 }
534 catch( std::exception& e )
535 {
536 THROW_IO_ERROR( wxString::Format( _( "Error reading footprint '%s' from library '%s': %s" ),
537 aFootprintName, aLibraryPath, e.what() ) );
538 }
539
540 return nullptr;
541}
542
543
545{
546 std::vector<FOOTPRINT*> result;
547
548 for( auto& [fpUuid, footprint] : m_loadedFootprints )
549 {
550 result.push_back( static_cast<FOOTPRINT*>( footprint->Clone() ) );
551 }
552
553 return result;
554}
const char * name
Definition: DXF_plotter.cpp:57
constexpr EDA_IU_SCALE pcbIUScale
Definition: base_units.h:108
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:290
void SetFileName(const wxString &aFileName)
Definition: board.h:325
const PAGE_INFO & GetPageSettings() const
Definition: board.h:689
bool SetLayerName(PCB_LAYER_ID aLayer, const wxString &aLayerName)
Changes the name of the layer given by aLayer.
Definition: board.cpp:595
void Move(const VECTOR2I &aMoveVector) override
Move this object.
Definition: board.cpp:502
BOX2I ComputeBoundingBox(bool aBoardEdgesOnly=false) const
Calculate the bounding box containing all board items (or board edge segments).
Definition: board.cpp:1670
void SetCopperLayerCount(int aCount)
Definition: board.cpp:744
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:892
constexpr const Vec GetCenter() const
Definition: box2.h:230
static double Convert(const wxString &aValue)
virtual void SetVisible(bool aVisible)
Definition: eda_text.cpp:290
virtual void SetTextAngle(const EDA_ANGLE &aAngle)
Definition: eda_text.cpp:204
PCB_FIELD & Value()
read/write accessors:
Definition: footprint.h:638
PCB_FIELD & Reference()
Definition: footprint.h:639
void AutoPositionFields()
Position Reference and Value fields at the top and bottom of footprint's bounding box.
Definition: footprint.cpp:2599
PROGRESS_REPORTER * m_progressReporter
Progress reporter to track the progress of the operation, may be nullptr.
Definition: io_base.h:221
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:342
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:345
virtual void SetPosition(const VECTOR2I &aPos) override
Definition: pcb_text.h:87
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:64
static REPORTER & GetInstance()
Definition: reporter.cpp:199
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:401
@ 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:93
constexpr int mmToIU(double mm) const
Definition: base_units.h:88
VECTOR2< int32_t > VECTOR2I
Definition: vector2d.h:691