KiCad PCB EDA Suite
Loading...
Searching...
No Matches
design_block_io.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) 2024 Mike Williams <[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
25#include <common.h>
26#include <gestfich.h>
27#include <json_common.h>
28#include <i18n_utility.h>
29#include <kiplatform/io.h>
30#include <wx/dir.h>
31#include <wx/ffile.h>
32#include <wx/filename.h>
33#include <wx/log.h>
34#include <wx/translation.h>
35#include <wx/string.h>
36#include <wx/arrstr.h>
37#include <wx/datetime.h>
39#include <kiway_player.h>
40#include <design_block_io.h>
41#include <design_block.h>
42#include <ki_exception.h>
43#include <trace_helpers.h>
44#include <fstream>
47
49{
50 switch( aFileType )
51 {
52 case KICAD_SEXP: return _( "KiCad" );
54 default: return wxString::Format( _( "UNKNOWN (%d)" ), aFileType );
55 }
56}
57
58
60DESIGN_BLOCK_IO_MGR::EnumFromStr( const wxString& aFileType )
61{
62 if( aFileType == _( "KiCad" ) )
64 else if( aFileType == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
66
68}
69
70
72{
73 switch( aFileType )
74 {
75 case KICAD_SEXP: return new DESIGN_BLOCK_IO();
76 default: return nullptr;
77 }
78}
79
80
82DESIGN_BLOCK_IO_MGR::GuessPluginTypeFromLibPath( const wxString& aLibPath, int aCtl )
83{
85
86 if( parser.Parse( aLibPath.ToStdString() ).has_value() )
87 return NESTED_TABLE;
88
89 if( IO_RELEASER<DESIGN_BLOCK_IO>( FindPlugin( KICAD_SEXP ) )->CanReadLibrary( aLibPath )
90 && aCtl != KICTL_NONKICAD_ONLY )
91 {
92 return KICAD_SEXP;
93 }
94
96}
97
98
99bool DESIGN_BLOCK_IO_MGR::ConvertLibrary( std::map<std::string, UTF8>* aOldFileProps,
100 const wxString& aOldFilePath,
101 const wxString& aNewFilePath )
102{
105
106 if( oldFileType == DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
107 return false;
108
109
112 wxArrayString dbNames;
113 wxFileName newFileName( aNewFilePath );
114
115 if( newFileName.HasExt() )
116 {
117 wxString extraDir = newFileName.GetFullName();
118 newFileName.ClearExt();
119 newFileName.SetName( "" );
120 newFileName.AppendDir( extraDir );
121 }
122
123 if( !newFileName.DirExists() && !wxFileName::Mkdir( aNewFilePath, wxS_DIR_DEFAULT ) )
124 return false;
125
126 try
127 {
128 bool bestEfforts = false; // throw on first error
129 oldFilePI->DesignBlockEnumerate( dbNames, aOldFilePath, bestEfforts, aOldFileProps );
130
131 for( const wxString& dbName : dbNames )
132 {
133 std::unique_ptr<const DESIGN_BLOCK> db( oldFilePI->GetEnumeratedDesignBlock( aOldFilePath, dbName,
134 aOldFileProps ) );
135 kicadPI->DesignBlockSave( aNewFilePath, db.get() );
136 }
137 }
138 catch( ... )
139 {
140 return false;
141 }
142
143 return true;
144}
145
146
148{
149 return IO_BASE::IO_FILE_DESC( _HKI( "KiCad Design Block folders" ), {},
151}
152
153
154long long DESIGN_BLOCK_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
155{
156 wxDir libDir( aLibraryPath );
157
158 if( !libDir.IsOpened() )
159 return 0;
160
161 long long ts = 0;
162
163 wxString filename;
164 bool hasMoreFiles = libDir.GetFirst( &filename, wxEmptyString, wxDIR_DIRS );
165
166 while( hasMoreFiles )
167 {
168 wxFileName blockDir( aLibraryPath, filename );
169
170 // Check if the directory ends with ".kicad_block", if so hash all the files in it.
171 if( blockDir.GetFullName().EndsWith( FILEEXT::KiCadDesignBlockPathExtension ) )
172 ts += KIPLATFORM::IO::TimestampDir( blockDir.GetFullPath(), wxT( "*" ) );
173
174 hasMoreFiles = libDir.GetNext( &filename );
175 }
176
177 return ts;
178}
179
180
181void DESIGN_BLOCK_IO::CreateLibrary( const wxString& aLibraryPath,
182 const std::map<std::string, UTF8>* aProperties )
183{
184 if( wxDir::Exists( aLibraryPath ) )
185 {
186 THROW_IO_ERROR( wxString::Format( _( "Cannot overwrite library path '%s'." ),
187 aLibraryPath.GetData() ) );
188 }
189
190 wxFileName dir;
191 dir.SetPath( aLibraryPath );
192
193 if( !dir.Mkdir() )
194 {
196 wxString::Format( _( "Library path '%s' could not be created.\n\n"
197 "Make sure you have write permissions and try again." ),
198 dir.GetPath() ) );
199 }
200}
201
202
203bool DESIGN_BLOCK_IO::DeleteLibrary( const wxString& aLibraryPath,
204 const std::map<std::string, UTF8>* aProperties )
205{
206 wxFileName fn;
207 fn.SetPath( aLibraryPath );
208
209 // Return if there is no library path to delete.
210 if( !fn.DirExists() )
211 return false;
212
213 if( !fn.IsDirWritable() )
214 {
215 THROW_IO_ERROR( wxString::Format( _( "Insufficient permissions to delete folder '%s'." ),
216 aLibraryPath.GetData() ) );
217 }
218
219 wxDir dir( aLibraryPath );
220
221 // Design block folders should only contain sub-folders for each design block
222 if( dir.HasFiles() )
223 {
224 THROW_IO_ERROR( wxString::Format( _( "Library folder '%s' has unexpected files." ),
225 aLibraryPath.GetData() ) );
226 }
227
228 // Must delete all sub-directories before deleting the library directory
229 if( dir.HasSubDirs() )
230 {
231 wxArrayString dirs;
232
233 // Get all sub-directories in the library path
234 CollectSubdirsLoopSafe( aLibraryPath, dirs );
235
236 for( size_t i = 0; i < dirs.GetCount(); i++ )
237 {
238 wxFileName tmp = dirs[i];
239
241 {
242 THROW_IO_ERROR( wxString::Format( _( "Unexpected folder '%s' found in library path '%s'." ),
243 dirs[i].GetData(), aLibraryPath.GetData() ) );
244 }
245 }
246
247 for( size_t i = 0; i < dirs.GetCount(); i++ )
248 wxRemoveFile( dirs[i] );
249 }
250
251 wxLogTrace( traceDesignBlocks, wxT( "Removing design block library '%s'." ),
252 aLibraryPath.GetData() );
253
254 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
255 // we don't want that. we want bare metal portability with no UI here.
256 if( !wxFileName::Rmdir( aLibraryPath, wxPATH_RMDIR_RECURSIVE ) )
257 {
258 THROW_IO_ERROR( wxString::Format( _( "Design block library '%s' cannot be deleted." ),
259 aLibraryPath.GetData() ) );
260 }
261
262 // For some reason removing a directory in Windows is not immediately updated. This delay
263 // prevents an error when attempting to immediately recreate the same directory when over
264 // writing an existing library.
265#ifdef __WINDOWS__
266 wxMilliSleep( 250L );
267#endif
268
269 return true;
270}
271
272
273void DESIGN_BLOCK_IO::DesignBlockEnumerate( wxArrayString& aDesignBlockNames,
274 const wxString& aLibraryPath, bool aBestEfforts,
275 const std::map<std::string, UTF8>* aProperties )
276{
277 // From the starting directory, look for all directories ending in the .kicad_block extension
278 wxDir dir( aLibraryPath );
279
280 if( !dir.IsOpened() )
281 {
282 THROW_IO_ERROR( wxString::Format( _( "Design block '%s' does not exist." ), aLibraryPath ) );
283 }
284
285 wxString dirname;
286 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadDesignBlockPathExtension );
287 bool cont = dir.GetFirst( &dirname, fileSpec, wxDIR_DIRS );
288
289 while( cont )
290 {
291 aDesignBlockNames.Add( dirname.Before( wxT( '.' ) ) );
292 cont = dir.GetNext( &dirname );
293 }
294}
295
296
297DESIGN_BLOCK* DESIGN_BLOCK_IO::DesignBlockLoad( const wxString& aLibraryPath,
298 const wxString& aDesignBlockName, bool aKeepUUID,
299 const std::map<std::string, UTF8>* aProperties )
300{
301 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
302 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
303 wxString dbSchPath = dbPath + aDesignBlockName + wxT( "." )
305 wxString dbPcbPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::KiCadPcbFileExtension;
306 wxString dbMetadataPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::JsonFileExtension;
307
308 if( !wxDir::Exists( dbPath ) )
309 THROW_IO_ERROR( wxString::Format( _( "Design block '%s' does not exist." ), dbPath ) );
310
311 DESIGN_BLOCK* newDB = new DESIGN_BLOCK();
312
313 // Library name needs to be empty for when we fill it in with the correct library nickname
314 // one layer above
315 newDB->SetLibId( LIB_ID( wxEmptyString, aDesignBlockName ) );
316
317 if( wxFileExists( dbSchPath ) )
318 newDB->SetSchematicFile( dbSchPath );
319
320 if( wxFileExists( dbPcbPath ) )
321 newDB->SetBoardFile( dbPcbPath );
322
323 // Parse the JSON file if it exists
324 if( wxFileExists( dbMetadataPath ) )
325 {
326 try
327 {
328 nlohmann::ordered_json dbMetadata;
329 std::ifstream dbMetadataFile( dbMetadataPath.fn_str() );
330
331 dbMetadataFile >> dbMetadata;
332
333 if( dbMetadata.contains( "description" ) )
334 newDB->SetLibDescription( dbMetadata["description"].get<std::string>() );
335
336 if( dbMetadata.contains( "keywords" ) )
337 newDB->SetKeywords( dbMetadata["keywords"].get<std::string>() );
338
339 // Read the "fields" object from the JSON
340 if( dbMetadata.contains( "fields" ) )
341 {
342 for( auto& item : dbMetadata["fields"].items() )
343 {
344 wxString name = wxString::FromUTF8( item.key() );
345 wxString value = wxString::FromUTF8( item.value().get<std::string>() );
346
347 newDB->GetFields()[name] = value;
348 }
349 }
350 }
351 catch( ... )
352 {
353 delete newDB;
354 THROW_IO_ERROR( wxString::Format( _( "Design block metadata file '%s' could not be read." ),
355 dbMetadataPath ) );
356 }
357 }
358
359 return newDB;
360}
361
362
363bool DESIGN_BLOCK_IO::DesignBlockExists( const wxString& aLibraryPath,
364 const wxString& aDesignBlockName,
365 const std::map<std::string, UTF8>* aProperties )
366{
367 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
368 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
369
370 return wxDir::Exists( dbPath );
371}
372
373
374void DESIGN_BLOCK_IO::DesignBlockSave( const wxString& aLibraryPath,
375 const DESIGN_BLOCK* aDesignBlock,
376 const std::map<std::string, UTF8>* aProperties )
377{
378 // Make sure we have a valid LIB_ID or we can't save the design block
379 if( !aDesignBlock->GetLibId().IsValid() )
380 {
381 THROW_IO_ERROR( _( "Design block does not have a valid library ID." ) );
382 }
383
384 if( aDesignBlock->GetSchematicFile().IsEmpty() && aDesignBlock->GetBoardFile().IsEmpty() )
385 {
386 THROW_IO_ERROR( _( "Design block does not have a schematic or board file." ) );
387 }
388
389 wxFileName schematicFile( aDesignBlock->GetSchematicFile() );
390 wxFileName boardFile( aDesignBlock->GetBoardFile() );
391
392 if( !aDesignBlock->GetSchematicFile().IsEmpty() && !schematicFile.FileExists() )
393 {
395 wxString::Format( _( "Schematic source file '%s' does not exist." ), schematicFile.GetFullPath() ) );
396 }
397
398 if( !aDesignBlock->GetBoardFile().IsEmpty() && !boardFile.FileExists() )
399 {
400 THROW_IO_ERROR( wxString::Format( _( "Board source file '%s' does not exist." ), boardFile.GetFullPath() ) );
401 }
402
403 // Create the design block folder
404 wxFileName dbFolder( aLibraryPath + wxFileName::GetPathSeparator()
405 + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
407 + wxFileName::GetPathSeparator() );
408
409 if( !dbFolder.DirExists() )
410 {
411 if( !dbFolder.Mkdir() )
412 {
413 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be created." ),
414 dbFolder.GetFullPath().GetData() ) );
415 }
416 }
417
418 if( !aDesignBlock->GetSchematicFile().IsEmpty() )
419 {
420 // The new schematic file name is based on the design block name, not the source sheet name
421 wxString dbSchematicFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
423
424 // If the source and destination files are the same, then we don't need to copy the file
425 // as we are just updating the metadata
426 if( schematicFile.GetFullPath() != dbSchematicFile )
427 {
428 // Copy the source sheet file to the design block folder, under the design block name
429 if( !wxCopyFile( schematicFile.GetFullPath(), dbSchematicFile ) )
430 {
432 wxString::Format( _( "Schematic file '%s' could not be saved as design block at '%s'." ),
433 schematicFile.GetFullPath(), dbSchematicFile ) );
434 }
435 }
436 }
437
438 if( !aDesignBlock->GetBoardFile().IsEmpty() )
439 {
440 // The new Board file name is based on the design block name, not the source sheet name
441 wxString dbBoardFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
443
444 // If the source and destination files are the same, then we don't need to copy the file
445 // as we are just updating the metadata
446 if( boardFile.GetFullPath() != dbBoardFile )
447 {
448 // Copy the source sheet file to the design block folder, under the design block name
449 if( !wxCopyFile( boardFile.GetFullPath(), dbBoardFile ) )
450 {
451 THROW_IO_ERROR( wxString::Format( _( "Board file '%s' could not be saved as design block at '%s'." ),
452 boardFile.GetFullPath(), dbBoardFile ) );
453 }
454 }
455 }
456
457 wxString dbMetadataFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
458 + wxT( "." ) + FILEEXT::JsonFileExtension;
459
460 // Write the metadata file
461 nlohmann::ordered_json dbMetadata;
462 dbMetadata["description"] = aDesignBlock->GetLibDescription();
463 dbMetadata["keywords"] = aDesignBlock->GetKeywords();
464 dbMetadata["fields"] = aDesignBlock->GetFields();
465
466 bool success = false;
467
468 try
469 {
470 std::string payload = dbMetadata.dump( 0 );
471 wxString writeError;
472 success = KIPLATFORM::IO::AtomicWriteFile( dbMetadataFile, payload.data(), payload.size(),
473 &writeError );
474
475 if( !success )
476 {
477 wxLogError( _( "Cannot save design block metadata '%s': %s" ), dbMetadataFile,
478 writeError );
479 }
480 }
481 catch( ... )
482 {
483 success = false;
484 }
485
486 if( !success )
487 {
488 THROW_IO_ERROR( wxString::Format(
489 _( "Design block metadata file '%s' could not be saved." ), dbMetadataFile ) );
490 }
491}
492
493
494void DESIGN_BLOCK_IO::DesignBlockDelete( const wxString& aLibPath, const wxString& aDesignBlockName,
495 const std::map<std::string, UTF8>* aProperties )
496{
497 wxFileName dbDir = wxFileName( aLibPath + wxFileName::GetPathSeparator() + aDesignBlockName
499
500 if( !dbDir.DirExists() )
501 {
503 wxString::Format( _( "Design block '%s' does not exist." ), dbDir.GetFullName() ) );
504 }
505
506 // Delete the whole design block folder
507 if( !wxFileName::Rmdir( dbDir.GetFullPath(), wxPATH_RMDIR_RECURSIVE ) )
508 {
509 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be deleted." ),
510 dbDir.GetFullPath().GetData() ) );
511 }
512}
513
514
515bool DESIGN_BLOCK_IO::IsLibraryWritable( const wxString& aLibraryPath )
516{
517 wxFileName path( aLibraryPath );
518 return path.IsOk() && path.IsDirWritable();
519}
const char * name
@ KICAD_SEXP
S-expression KiCad file format.
@ DESIGN_BLOCK_FILE_UNKNOWN
0 is not a legal menu id on Mac
static const wxString ShowType(DESIGN_BLOCK_FILE_T aFileType)
static DESIGN_BLOCK_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
static DESIGN_BLOCK_FILE_T EnumFromStr(const wxString &aFileType)
static bool ConvertLibrary(std::map< std::string, UTF8 > *aOldFileProps, const wxString &aOldFilePath, const wxString &aNewFilePath)
Convert a design block library to the latest KiCad format.
static DESIGN_BLOCK_IO * FindPlugin(DESIGN_BLOCK_FILE_T aFileType)
bool DesignBlockExists(const wxString &aLibraryPath, const wxString &aDesignBlockName, const std::map< std::string, UTF8 > *aProperties=nullptr)
long long GetLibraryTimestamp(const wxString &aLibraryPath) const
void DesignBlockDelete(const wxString &aLibraryPath, const wxString &aDesignBlockName, const std::map< std::string, UTF8 > *aProperties=nullptr)
DESIGN_BLOCK * DesignBlockLoad(const wxString &aLibraryPath, const wxString &aDesignBlockName, bool aKeepUUID=false, const std::map< std::string, UTF8 > *aProperties=nullptr)
void DesignBlockSave(const wxString &aLibraryPath, const DESIGN_BLOCK *aDesignBlock, const std::map< std::string, UTF8 > *aProperties=nullptr)
void DesignBlockEnumerate(wxArrayString &aDesignBlockNames, const wxString &aLibraryPath, bool aBestEfforts, const std::map< std::string, UTF8 > *aProperties=nullptr)
virtual bool DeleteLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete an existing library and returns true, or if library does not exist returns false,...
void CreateLibrary(const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Create a new empty library at aLibraryPath empty.
bool IsLibraryWritable(const wxString &aLibraryPath) override
Return true if the library at aLibraryPath is writable.
const IO_BASE::IO_FILE_DESC GetLibraryDesc() const override
Get the descriptor for the library container that this IO plugin operates on.
void SetLibDescription(const wxString &aDesc)
void SetKeywords(const wxString &aKeywords)
void SetSchematicFile(const wxString &aFile)
void SetBoardFile(const wxString &aFile)
const wxString & GetKeywords() const
const wxString & GetLibDescription() const
void SetLibId(const LIB_ID &aName)
const wxString & GetBoardFile() const
const wxString & GetSchematicFile() const
const LIB_ID & GetLibId() const
const nlohmann::ordered_map< wxString, wxString > & GetFields() const
tl::expected< LIBRARY_TABLE_IR, LIBRARY_PARSE_ERROR > Parse(const std::filesystem::path &aPath)
static const wxString TABLE_TYPE_NAME
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:49
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:172
const UTF8 & GetLibItemName() const
Definition lib_id.h:102
The common library.
#define _(s)
void CollectSubdirsLoopSafe(const wxString &aRoot, wxArrayString &aDirs, int aFlags)
Recursively collect every subdirectory under aRoot using the same loop detection as CollectFilesLoopS...
Definition gestfich.cpp:831
static const std::string KiCadDesignBlockLibPathExtension
static const std::string KiCadDesignBlockPathExtension
static const std::string JsonFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string KiCadPcbFileExtension
const wxChar *const traceDesignBlocks
Some functions to handle hotkeys in KiCad.
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define KICTL_NONKICAD_ONLY
chosen file is non-KiCad according to user
bool AtomicWriteFile(const wxString &aTargetPath, const void *aData, size_t aSize, wxString *aError=nullptr)
Writes aData to aTargetPath via a sibling temp file, fsyncs the data and directory,...
long long TimestampDir(const wxString &aDirPath, const wxString &aFilespec)
Computes a hash of modification times and sizes for files matching a pattern.
Definition unix/io.cpp:123
#define _HKI(x)
Definition page_info.cpp:44
Container that describes file type info.
Definition io_base.h:43
std::string path
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.